Quote for the Week

"Learn to enjoy every moment of your life"

Tuesday, September 9, 2014

Trigger in WPF

Triggers



Triggers is used in style to perform action on change any property value or event fires. Triggers create visual effects on controls. By using Triggers we can change the appearance of Framework Elements.


Types of Triggers :




01. Property Trigger

This trigger gets active when UIElements property value changes. The below Trigger is created on Button. It will set Opacity to 0.5 when Buttons IsPressed property change.

    <Style x:Key="ButtonStyle" TargetType="{x:Type Button}">
    <Style.Triggers>
    <Trigger Property="IsPressed" Value="True">
    <Setter Property="Opacity" Value="0.5" />
    </Trigger>
    <Trigger Property="IsEnabled" Value="False">
    <Setter Property="Foreground" Value="Red" />
    </Trigger>
    </Style.Triggers>
    </Style>

02. Event Trigger

This trigger gets active when RoutedEvent of FrameworkElement raise. Event Trigger is generally used to perform some animation on control like as colorAnimation, doubleAnumation using KeyFrame etc.

The below trigger is used to animate/change the color property (SolidColorBrush, LinearGradientBrush ) of the UIElement at defined time duration.

    <Border Name="border1" Width="100" Height="30"
    BorderBrush="Black" BorderThickness="1">
    <Border.Background>
    <SolidColorBrush x:Name="MyBorder" Color="LightBlue" />
    </Border.Background>
    <Border.Triggers>
    <EventTrigger RoutedEvent="Mouse.MouseEnter">
    <BeginStoryboard>
    <Storyboard>
    <ColorAnimation Duration="0:0:1"
    Storyboard.TargetName="MyBorder"
    Storyboard.TargetProperty="Color"
    To="Gray" />
    </Storyboard>
    </BeginStoryboard>
    </EventTrigger>
    </Border.Triggers&
    gt;
    </Border>

03. Data Trigger

This trigger gets active when Binding Data matches specified condition. Below DataTrigger is created on Picture property of binding data. Setter objects of the DataTrigger describes property values to apply when binding data match the condition. Picture is Byte[] property of the class. If Picture is null then DataTrigger applies on image to set image source to noImage.png, otherwise it will set image source from picture.

Same as if picture is null, applies TextBlock value to "No Image Availalbe" and foreground color to red otherwise sets default value from data.

    <DataTemplate>
    <Grid Margin="0 5 0 0">
    <Grid.RowDefinitions>
    <RowDefinition Height="Auto" />
    <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <Image x:Name="viewImage"
    Grid.Row="0" Width="100"
    Height="60" HorizontalAlignment="Center"
    Source="{Binding Picture}" Stretch="Fill" />
    <TextBlock x:Name="viewText"
    Grid.Row="1" Margin="0 5 0 0"
    HorizontalAlignment="Center"
    FontWeight="Black" Foreground="Green"
    Text="{Binding Title}" />
    </Grid>
    <DataTemplate.Triggers>
    <DataTrigger Binding="{Binding Path=Picture}" Value="{x:Null}">
    <Setter TargetName="viewImage" Property="Source" Value="/Images/noImage.png" />
    <Setter TargetName="viewText" Property="Text" Value="No Image Available" />
    <Setter TargetName="viewText" Property="Foreground" Value="Red" />
    </DataTrigger>
    </DataTemplate.Triggers>
    </DataTemplate>


Summary:

What do you think about this Article? Please give your feedback to dotnetcircle@gmail.com

Subscribe to this blog for Interesting Concepts to Know in .Net.

Friday, September 5, 2014

Thursday, September 4, 2014

Basics on WCF Service

Introduction



What is WCF?



WCF is a service Oriented programming in .net framework 3.0 and plus, which provide unique platform for all type of Communications in .net for distributed Applications.

It is the latest service oriented technology; Interoperability is the fundamental characteristics of WCF.

Basic Bare Bones of WCF

Endpoints (ABC terms).


- Address

- Binding

- Contract

All the WCF communications are take place through end point. End point consists of three components.(i.e ABC)

Address:

   Basically URL, specifies where this WCF service is hosted .Client will use this url to connect to the service.

         e.g http://localhost:8071/MyService/Calculator.svc.

Binding:

   Binding will describes how client will communicate with service. There are different protocols available for the WCF to communicate to the Client. You can mention the protocol type based on your requirements.

In My service I used Basic Http Service protocol for communication.i.e wsHttpBinding

Contract: 

   Collection of operation that specifies what the endpoint will communicate with outside world. Usually name of the Interface will be mentioned in the Contract, so the client application will be aware of the operations which are exposed to the client. Each operation is a simple exchange pattern such as one-way, duplex and request/reply.

In My Service Contract is” Service1 “.

Exchange pattern is” request/reply”;

2. Service Contract: Service contracts describe the operation that service can provide

3. Operation Contract: Attribute Which is used to define the Method as part of Service.


Demo of the Calculator Example.
Step By Step Procedure

1   Creating WCF Service

2   Consuming WCF Service in Web Application using VS 2008.

3   Creating WCF Client.

Creating WCF Service.
Steps:

1.    Open  VS 2008 > Projects > Select C#  >  WCF  > WCF Service Library.

2.    Type name of  the service file as u need. In this ex.MyWCFSolution. then click OK.

3.    New Window will open with one Class.cs and Interface .cs File which can be seen in Solution Explore.

4.    Add the Namespace System.ServiceModel and  also add  Reference in Solution Explore.

5.    Type the Code in Interface file and class file as shown below.

Code in Interface(EX: IService1.cs)

[ServiceContract]
    public interface IService1
    {
        [OperationContract]
       int add(int a,int b);

        [OperationContract]
       int Sub(int a, int b);

        [OperationContract]
        int Mul(int a, int b);

        [OperationContract]
        int Div(int a, int b);

        // TODO: Add your service operations here
    }



Code in Class file(EX: Service1.cs)

public class Service1 : IService1
    {
     
        int IService1.add(int a, int b)
        {
            return (a + b);
        }

        int IService1.Sub(int a, int b)
        {
            if (a >= b)
            {
                return (a - b);
            }
            else
            {
                return (b - a);
            }
        }
     
     
        public int Mul(int a, int b)
        {
            return (a * b);
        }

        public int Div(int a, int b)
        {
            if(a>=b)
                try { return (a / b); }
                catch
                { return 0; }
            else
                return (b / a);
        }
    }

Consuming WCF Service in Web Application.

Steps:

1. Create web Application as shown in attachment please download the File.



2. After Creating Desing of the Calculator web application the add reference System.ServiceModel namespace into web application in Solution Explore.

3. Add the WCF Service in visual studio by right click on Reference and select Add service Reference

4. Give the Service hosted Address and click on Go button and select the service which u created I mean in Ex service1.

5. Give the namespace: Name as Myservice and  the click OK .

1.    Creating WCF Client.

In Order to call the Methods (services from WCFService) we need to Create the porxy WCF Client.

Once service is consumed in Application, WCF Client is Created, So Using the name of the Client Name we can call the methods in out applications

EX. In  Our WCF Service we have 4 methods (add, sub, mul, div).

2.   TO get the WCF client name Double click on Service i.e Myservice and take the copy of the Client name.

The fwindow will open in that u take the copy.

3.   Paste the Client Name in Default.cs File get the following code then create the instance of the client as show in below code. Using this porxy client u can call the services of the WCF service as shown in below code.

4.   On paste u get MY.Myservice.Service1Client

5.  Code to be Right in Default.cs in web application(EX:Calculator)

namespace Calculator
{
    public partial class _Default : System.Web.UI.Page
    {
     
        Calculator.Myservice.Service1Client Client = new Calculator.Myservice.Service1Client();
//Creating proxy client instance “Client”
        int a, b;
        protected void Page_Load(object sender, EventArgs e)
        {
         
            Response.Write("MY Calculator");

        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
a = Convert.ToInt32(txt1st.Text);
            b = Convert.ToInt32(txt2nd.Text);

            int Addition = Client.add(10,20);
            txtResult.Text = Addition.ToString();
        }

        protected void btnsub_Click(object sender, EventArgs e)
        {
            a = Convert.ToInt32(txt1st.Text);
            b = Convert.ToInt32(txt2nd.Text);
int Addition = Client.Sub(10, 20);
            txtResult.Text = Addition.ToString();

        }

        protected void btnmul_Click(object sender, EventArgs e)
        {
a = Convert.ToInt32(txt1st.Text);
            b = Convert.ToInt32(txt2nd.Text);
            int Addition = Client.Mul(10, 20);
            txtResult.Text = Addition.ToString();
        }

        protected void btndiv_Click(object sender, EventArgs e)
        {
            a = Convert.ToInt32(txt1st.Text);
            b = Convert.ToInt32(txt2nd.Text);
int Addition = Client.Div(10, 20);
            txtResult.Text = Addition.ToString();

        }
    }
}

Testing the application and using WCF services.

1.  Run the WCF service First.(Ex:MyWCFsolution)

2.  Run the wev Application(EX: Calculator)(download the attachements)



Conclusion

Hope this article makes Sense of  basic Idea about WCF. Thank you.

Tuesday, September 2, 2014

How get JSON Data and set to the text boxes using Ajax call in jQuery in Asp.net MVC

Today, we will see how to get JSON data using Ajax in jQuery


I have table "tblEmployee" in SQL Server database like




and View design


<table>
<tr>
<td>Specify Employee Id:</td>
<td>
<input type="text" value="" id="txtEmpId"/>
</td>
<tr>
<td>First Name</td><td><input type="text" id="txtFirstName"></td>
</tr>
<tr>
<td>Annual Salary</td><td><input type="text" id="txtAnnualSal"></td>
</tr>
<tr>
<td>Country</td><td><input type="text" id="txtCountry"></td>
</tr>
<tr>
<td>Culture</td><td><input type="text" id="txtCulture"></td>
</tr>
</table>
<input type="button" value="Get Result" id="btnUpdate"/>


In your Controller Action Method


public JsonResult GetEmployeeDetails(int empid)
{

var employeeDetails=(from emp in context.TBLEMPLOYEE where emp.ID=empid
                               select  emp).FirstorDefault();

return Json(employeeDetails,JsonRequestBehaviour.AllowGet);
}

In your Script

<script>
$(document).ready(function(){
$("#btnUpdate").click(function(){
var empid=$("#txtEmpId").val();
$.ajax({
                url: '/your controller/GetEmployeeDetails',
               type: 'POST',
               data: empid,
              error: function () {
               alert(" An error occurred.");
                },
               success: function (data) {
              $("#txtFirstName").val(data[o].FirstName);
              $("#txtAnnualSal").val(data[o].AnnualSalary);
              $("#txtCountry").val(data[o].Country);
              $("#txtCulture").val(data[o].Culture);
              }
             });
 });
});
</script>


Summary:

Do you like this Article? then subscribe and follow this blog.

Have queries ? you can mail to dotnetcircle@gmail.com

Monday, September 1, 2014

How to write SQL “not exists” in LINQ


I want to execute the query in sql where i want to get the employees which are not in the department in Dept_id=4,

In SQL

Select emp.ID,emp.First_Name,
from Employee emp
where not exists (select * from Department where Dept_id=4)
order by  emp.ID

In LINQ

var employeesNotEnteredList = (from emps in reslandentity.EMPLOYEE
                                         
                                           where reslandentity.DEPARTMENT.Any(m=>m.Dept_id!=4)
                                         
                                           select emps).Distinct().ToList();

That's it so simple..!!