Tuesday, September 18, 2012

WCF


introduction
What is WCF?

WCF is a service Oriented programming in .net framework 3.0 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

1>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.

What is WCF?


introduction
What is WCF?

WCF is a service Oriented programming in .net framework 3.0 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

1>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.

Friday, June 10, 2011

JQuery



What is jQuery?
jQuery is a light weight javascript library which provides fast and easy way of HTML DOM traversing and manipulation, event handling, client
side animations, etc. One of the greatest features of jQuery is, it supports an efficient way to implement AJAX applications because of its light
weight nature. According to the jQuery official site, “jQuery is designed to change the way that you write JavaScript.”

Advantages of jQuery
1.      It’s lightweight, easy and fast.
2.      Write less but do more.
3.      Cross Browser Compatibility.
4.      Separate javascript code from HTML mark-up.
5.      Easy and Light-weight Ajax Application.
6.      Availability of various plug-in’s.
7.      You can extend it.
8.      We can use CDN (Content Distribution Network) for internet site.
9.      Microsoft and Intellisense support in Visual Studio 2008.
10.  Easy Integration with ASP.Net Ajax projects.


var optons={
method:'post',
url:'chanName.aspx',
after:funtion(responce){
$("div#divView").html(responce).show();
$("div#divEdit").empty().hide();
$(a#editName").show();
}

$("form#ChangeName").ajaxForm(options);
%("a#editName").hide();
$("a#lnkCancel").click(function(){
$("div#divView").show();
$("div#divEdit").empty().hide();



$("a#editName").click(function(){
$.get("ChangeName.aspx",function(responce){
$("div#divEdit").html(responce).show();
$("div#divView").hide();



var options={
method: 'post',
url: 'changeName.aspx',
after: function(responce){
$("div#divView").html(responce).show();
$("div#divEdit").empty().hide();
}
};
----------------------------------------------------------------------
GET:   $('#<%=DropDownList1.ClientID%>').val()
SET:   $('#<%=DropDownList1.ClientID%>').val("value_to_set")

----------------------------------------------------------------------
get: $('#<%=ddl1.clientid%>').attr("selectedIndex")
get:$('#<%=ddl1.clientid%>')[0].selectdIndex;

set:$('#<%=ddl1.clientid%>').attr("selectedIndex","0")
set:$('#<%=ddl1.clientid%>').attr("selectdIndex")=0

----------------------------------------------------------------------
get:$("input[name='<%=radiobuttonlist1.uniqueid%>']:checked").vlaue()
set: $("input[name='<%=radiobuttonlist1.uniqueid%>'][value='value_to_set']").attr("checked",true)

----------------------------------------------------------------------
$('#<%=button1.ClientId%>').attr("disabled",true/false);
----------------------------------------------------------------------
get: $('#<%=label1.ClientId%>').text()

set:$('#<%=lable1.ClientId%>').text("value_to_set")

-----------------------------------------------------------------------
get:$('#<%=TextBox1.clientid%>').val()
set:$('#<%=textbox.clientId%>').val("value_to_set")
---------------------------------------------------------------------
if($('#<%=Button1.ClientID%>').is(':visible'))
-----------------------------------------------------------------------
$(function(){
$('#startdate').datepick({dateFormat:'dd/mm/yyyy'});
$('#enddate').datepick({dateFormat:'dd/mm/yyyy'});
});

-----------------------------------------------------------------------
$('#startdate').datepick({dateFormat:'mm/dd/yyyy',showAnim:'fadeIn'});

$('#startdate').datepick({datepick({dateformat:'mm/dd/yyyy',showSpeed:'fast'});
mindate--maxdate
$('#startdate').datepick({minDate:'07/01/2010',maxDate:'07/15/2010'});


POST Method
     <script src="_scripts/jQuery-1.2.6.js" type="text/javascript"></script>
        <script language="javascript">
            $(document).ready(function() {

$("#txtNoOfTicketsByPOST").change(function() {
                    $("#Error2").html("");
                    var ticketsReq = $("#txtNoOfTicketsByPOST").val();
                    $.post("GetAvailableTicketsByPOST.aspx", { TicReq: ticketsReq }, function(result) {
                        if (result != "") {
                            $("#Error2").html(result);                          
                        }
                    });
                });
            });           
        </script>

    <div>
    <div id="TicketsByPOST ">
    No of Tickets:<asp:TextBox ID=" txtNoOfTicketsByPOST" runat="server"></asp:TextBox>
    <div id="Error2" style="color:Red;"></div>
    </div>
    </div>

public partial class GetAvailableTicketsByPOST : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string ticReq = Request["TicReq"];
        int tics = int.Parse(ticReq);
      
        int NoOfTicketsAvailable = 5;
        if (tics > NoOfTicketsAvailable)
        {
            Response.Write("Only " + NoOfTicketsAvailable.ToString()+" are available!");
            Response.End();
        }
    }
}

------------------------------------------------------------------------------------------------
Implementing PageMethods in ASP.Net AJAX
The page methods should be defined as a public static method and it should be decorated with WebMethod attribute. Refer the below page
method that returns a string of available number of tickets at that moment.

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    
    }
    [WebMethod]
    public static string GetAvailableTickets()
    {
        int NoOfTicketsAvailable = 5;
        return NoOfTicketsAvailable.ToString();
    }
}

Include System.Web.Services namespace for the above web method to work.

Calling the PageMethod using JQuery
We can use JQuery.ajax() method to call the PageMethod from client side,

<script src="_scripts/jquery-1.2.6.js" type="text/javascript"></script>
        <script language="javascript">
            $(document).ready(function() {
                $("#txtNoOfTickets").blur(function() {
                    var ticketRequired = this.value;
                    var options = {
                        type: "POST",
                        url: "Default.aspx/GetAvailableTickets",
                        data: "{}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function(response) {
var avilabletic = parseInt(response.d);                          
                            if (ticketRequired > avilabletic) {
                                alert("Only " + response.d + " tickets available!");
                            }
                            else {
                                alert(response.d);
                            }

                        }
                    };
                    //Call the PageMethods
                    $.ajax(options);

                });
            });
        </script>




Calling PageMethods with parameters
The code in previous section discussed about calling a page method without passing parameters. In this section, we will see how to call
PageMethods with parameters.
We will have 2 PageMethods, one will check for available number of tickets for males and the other will check for the available number of tickets
for females.
 ------------------------------------------------------------------------------------
Codebehind
public partial class CallServerWithParameters : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    [WebMethod]
    public static string GetAvailableTicketsForMales(int no)
    {
        string result = "";
        int NoOfTicketsAvailable = 5;
        if (no > NoOfTicketsAvailable)
        {
            result = "Only " + NoOfTicketsAvailable.ToString() + " Male ticket(s) avaialable. Please enter a lower number!";
        }
        return result;
    }
    [WebMethod]
    public static string GetAvailableTicketsForFemales(int no)
    {

        string result = "";
        int NoOfTicketsAvailable = 5;
        if (no > NoOfTicketsAvailable)
        {
            result = "Only " + NoOfTicketsAvailable.ToString() + " Female ticket(s) avaialable. Please eneter a lower number!";
        }
        return result;
    }
}
<form id="form1" runat="server">
        <asp:TextBox ID="txtNoOfTickets" runat="server"></asp:TextBox>
</form>

As I have said earlier, the JQuery.ajax() method will use JSON to communicate to the server. This method will return the number of tickets
available at that moment. In this example, I have hard-coded the available number of tickets. You can replace this value from the one got from
the database.

Download the source code attached in the download section of this article.


aspx:
<script src="_scripts/jquery-1.2.6.js" type="text/javascript"></script>
        <script language="javascript">
            $(document).ready(function() {
                $("#txtNoOfMales").change(function() {
                    var ticketRequired = this.value;
                    var options = {
                        type: "POST",
                        url: "CallServerWithParameters.aspx/GetAvailableTicketsForMales",
                        data: "{no:" + ticketRequired + "}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function(response) {
                            if (response.d != "") {
                                alert(response.d);
                                $("#txtNoOfMales").focus();
                            }
                        }
                    };
                    //Call the PageMethods
                    $.ajax(options);

                });

                $("#txtNoOfFemales").change(function() {
                    var ticketRequired = this.value;
                    var options = {
                        type: "POST",
                        url: "CallServerWithParameters.aspx/GetAvailableTicketsForFemales",
                        data: "{no:" + ticketRequired + "}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function(response) {
                            if (response.d != "") {
                                alert(response.d);
                                $("#txtNoOfFemales").focus();
                            }
                        }
                    };
                    //Call the PageMethods
                    $.ajax(options);

                });

            });
        </script>

<div>
    No of Male Tickets:<asp:TextBox ID="txtNoOfMales" runat="server"></asp:TextBox>
    No of Female Tickets:<asp:TextBox ID="txtNoOfFemales" runat="server" ></asp:TextBox>
    </div>
-------------------------------------------------------------
GridView Style Edit Update in Repeater Control Using jQuery and Ajax:
http://www.codedigest.com/Articles/jQuery/261_GridView_Style_Edit_Update_in_Repeater_Control_Using_jQuery_and_Ajax.aspx
-----------------------------------------------------------------
Get Lable value:    $('#<%=Lables1.ClientID%>').text();
Set Lable value:     $('#<%=Lable1.ClientID%>').text("New Value");
Get Textbox value: $('#<%=TextBox1.ClientID%>').val();
Set Textbox value: $('#<%=TextBox1.ClientID%>').val("New Value");
Get Dropdown value: $('#<%=ddl1.ClientID%>').val();
Set Dropdown value: $('#<%=ddl1.ClientID%>').val("New value");
Get text of selected item in dropdown: $('#ddl1.ClientID%> option:selected').text();
Get Checkbox Status: $('#<%=CheckBox1.ClientID%>').attr('checked');
Check the checkbox: $('#<%=CheckBox1.ClientID%>').attr('checked',true);
Uncheck the Radiobutton: $('#<%=RadioButton1.ClientID%>').attr('checked',false);
Disable any control: $('#<%=TextBox1.ClientID%>').attr('disabled',true);
Enable any control: $('#<%=TextBox1.ClientId%>').attr('disabled',false);
Make textbox read only: $('#<%=TextBox1.clientid%>').attr('readonly','readonly');