Add

Showing posts with label wcf. Show all posts
Showing posts with label wcf. Show all posts

Channel Model Overview in WCF

Introductions 

WCF endpoints are the main components, those communicate withe the external world, And this communication was done b using\g a communication stack called channel stack.

Here in this article we will go through the little basics of channel stacks in WCF service programing.

Behind The Scene 

See the image below, which shows a basic diagram of the channel stack and the HTTP stack.
In wcf services when two stacks communicates, then the corresponding layers communicates between them. That is the HTTP layer communicates with the HTTP layer of the other stack and respectively.

Channel Stack


Now, the differences: While the TCP stack was designed to provide an abstraction of the physical network, the channel stack is designed to provide an abstraction of not only how the message is delivered, that is, the transport, but also other features such as what is in the message or what protocol is used for communication, including the transport but much more than that. For example, reliable session binding element is part of the channel stack but is not below the transport or the transport itself.

Messages flow through the communication stack as Message objects. As shown in figure above, the bottom channel is called a transport channel. It is the channel that is responsible for sending and receiving messages to and from other parties.

Each channel implements one or more interfaces known as channel shape interfaces or channel shapes. Those channel shapes provide the communication-oriented methods such as send and receive or request and reply that the channel implements and the user of the channel calls.
The interface is call IChannel, The five channel shapes that extend IChannel are:

  • IInputChannel
  • IOutputChannel
  • IRequestChannel
  • IReplyChannel
  • IDuplexChannel
The channel shapes are patterned after some of the fundamental message exchange patterns supported by existing transport protocols. For example, one-way messaging corresponds to an IInputChannel/IOutputChannel pair, request-reply corresponds to IRequestChannel/IReplyChannel pairs and two-way duplex communications corresponds to IDuplexChannel

Hope, this article gives you some basic idea about channel stacks in WCF.


Happy Coding...

Previous Next

Serialization and Deserialization in WCF

Introductions 

In this article we will discuss various types of serialization and deserialization  in wcf.

Serialization and Deserialization are the two most important techniques of data transmission from one end to another ( client to service and vice verse ).

Serialization : This is the process of converting a .NET object to a linear sequence of bytes for either storage or transmission from one end to another.

Deserialization : This is the process of converting a sequence of bytes to a .NET object. This is just the reverse process of serialization to recreate the .NET object from the bytes.

.NET framwork provides a namespace for this serialization and deserialization of objects, called "System.Runtime.Serialization" .

Behind The Scene 

Types of Serializations and Deserializations in WCF:
  •  DataContractSerializer
  •  XmlSerializer
  •  DataContractJsonSerializer
 Let's understand all the above techniques through a small example.

We will use the below data contract for all the three types of serialization and deserialization.

 
[DataContract]
    Public class Employee
    {
        [DataMember]
        Public string emp_Name;
 
        [DataMember]
        Public int emp_Id;
    }
 

Initialize the class with the below values.

 
Employee emp = new Employee { emp_Name = "Tapan kumar", 
                emp_Id = 001 };
 

 DataContractSerializer :

           This is the default serializer used by .NET framework. 

      Serialization : 

                 In order to use this, first create an object of the Employee class, then we will serialize the object to a memory stream using DataContractSerializer.

 
// create the employee class.
Employee objEmp = new Employee ();
FileStream fs = new FileStream("test.xml", FileMode.Open);

DataContractSerializer ser = new DataContractSerializer( typeof(Employee));

// write the object data to the file stream
XmlDictionaryWriter writer =
    XmlDictionaryWriter.CreateTextWriter(fs ,Encoding.UTF8 );

ser.WriteObject(writer, objEmp);
 

This serialization produces a "test.xml" file similar to;

 
<Employee>
  <emp_Name>Tapan kumar</emp_Name>
  <emp_Id>001</emp_Id>
</Employee>
 

       Deserialization :

                   Here the same will be done but in a reverse manner.

 
// create the employee class.
Employee objEmp = new Employee ();
FileStream fs = new FileStream("test,xml", FileMode.Open);

DataContractSerializer dcs = new DataContractSerializer(typeof(Employee));

// Read the object data from the file stream
XmlDictionaryReader reader =
      XmlDictionaryReader.CreateText(fs, new XmlDictionaryReaderQuotas());

objEmp = (Employee)dcs.ReadObject(reader);
 

    The ReadObject( ) method is used to read from the stream file.

XmlSerializer :

         This one is a prety old method, that is used for serialization and deserialization. Windows Communication Foundation supports it for backwards compatibility.

      Serialization : 

          In order to use this, first create an object of the Employee class, then we will serialize the object to a memory stream using XmlSerializer .      

 
// create the employee class.
Employee objEmp = new Employee ();
FileStream fs = new FileStream("test.xml", FileMode.Open);

XmlSerializer ser = new XmlSerializer( typeof(Employee));

// write the object data to the file stream
XmlDictionaryWriter writer =
    XmlDictionaryWriter.CreateTextWriter(fs ,Encoding.UTF8 );

ser.Serialize(writer, objEmp);
 

This serialization produces a "test.xml" file similar to;

 
<Employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
      xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <emp_Name>Tapan kumar</emp_Name>
  <emp_Id>001</emp_Id>
</Employee>
 

       Deserialization :

                   Here the same will be done but in a reverse manner.

 
// create the employee class.
Employee objEmp = new Employee ();
FileStream fs = new FileStream("test.xml", FileMode.Open);

XmlSerializer ser = new XmlSerializer( typeof(Employee));

// Read the object data from the file stream
XmlDictionaryReader reader =
      XmlDictionaryReader.CreateText(ms, new XmlDictionaryReaderQuotas());

objEmp = (Employee)ser.Deserialize(reader);
 


DataContractJsonSerializer :

         This one is the most advance serialization method, and used in a large scale due to its increasing popularity of data representation and for providing quicker and better packaging of data.

      Serialization : 

          In order to use this, first create an object of the Employee class, then we will serialize the object to a memory stream using DataContractJsonSerialization .      

 
// create the employee class.
Employee objEmp = new Employee ();
MemoryStream ms = new MemoryStream();

DataContractJsonSerializer ser = new 
             DataContractJsonSerializer(typeof(Employee));

// write the object data to the memory stream
 
ser.WriteObject(ms, objEmp);
 

This serialization produces a JSON file similar to;

 
JSON serialized Person object: {"emp_Name":"Tapan kumar","emp_Id":"001"}.
 

       Deserialization :

                   Here the same will be done but in a reverse manner.

 
// create the employee class.
Employee objEmp = new Employee ();
MemoryStream ms = new MemoryStream();

DataContractJsonSerializer ser = new 
                 DataContractJsonSerializer(typeof(Employee));

// first write 
 
ser.WriteObject(ms, objEmp);

// Read the object data from the memory stream

objEmp = (Employee)ReadObject(ms); 


Hope, this article gives you some idea about Serialization and Deserialization in WCF.


Happy Coding...

Previous Next

Data Contracts in WCF

Introductions 

In this article we will discuss about the data contracts in wcf.

Data contract defines the data types that are being transmitted to and from the client and service. This contract describes the data types those are exposed by the service.

The exposed data types are as simple as int, string, char and also as complex as user defined data types like class, structure.

Here we will see an example to clear our fundamentals on Data Contracts.

Behind The Scene 

The Data contract defines the how the data types are serialized and deserialized; In serialization we convert an object to an array of bytes and through deserialization we convert the byte array to an object.

The .NET framework provides a namespace named "System.Runtime.Serialization" for the this contract.

A data contract has many data members in side it, these are the individual data types.

Example

 

Lets create a service that returns a class named Employee; where the Employee class holds all the details of the Employee like Employee ID, Name, Age, Department, Phone No, Email Id.

So, for this requirement our service interface will look like this

[ServiceContract]
    public interface IEmployeeService
    {
        [OperationContract]
        Employee GetEmployeeDetails(int EmpId);
    }

For this let's design the data contract keeping the data types of the attributes we have mentioned above.

[DataContract]
    public class Employee
    {
 private int emp_ID;
        private string emp_Name;
        private int emp_Age;
        private String emp_Department;
        private int emp_PhoneNo;
        private string emp_EmailId;

 [DataMember]
        public int ID
        {
            get { return emp_ID;}
            set { emp_ID = value; }
        }

        [DataMember]
        public string Name
        {
            get { return emp_Name;}
            set { emp_Name = value; }
        } 

        [DataMember]
        public int Age
        {
            get { return emp_Age; }
            set { emp_Age = value; }
        }

        [DataMember]
        public int DepartMent
        {
            get { return emp_Department; }
            set { emp_Department = value; }
        }

        [DataMember]
        public int PhoneNo
        {
            get { return emp_PhoneNo; }
            set { emp_PhoneNo = value; }
        }

        [DataMember]
        public string EmailId
        {
            get { return emp_EmailId; }
            set { emp_EmailId = value; }
        }

    }

In the above contract we have defined the data contract containing the data members those will be transmitted over the service - client comunication.

Here is the implementation of the service class;
public class EmployeeService : IEmployeeService
    {
        public Employee GetEmployeeDetails(int empId)
        {
            
            Employee empDetail = new Employee();

            //Do something here 

            return empDetail;
        }
    }

This method inside the service will return the user defined class ( Employee ) that holds many details of the Employee like name, id age etc.

Now, see the below method how to use this in client side programing.

protected void ShowEmplyeeDetails()
{
     EmployeeServiceClient objEmployee = new EmployeeServiceClient();
     
     Employee employee;
     employee = objEmployee.GetEmployeeDetails( employeeID );
     
     // Access the attributes of the Employee class
     
     lblEmpID.Text = employee.ID;
     lblEmpName.Text = employee.Name;
     lblEmpAge.Text = employee.Age;
     lblEmpDepartment.Text = employee.DepartMent;
     lblEmpPhoneNo.Text = employee.PhoneNo;
     lblEmpEmailId.Text = employee.EmailId;
}


In client side once the service returns you the object then you would be able to access the data inside that object like above method.

Hope, this article gives you some idea about the Data Contracts in WCF.


Happy Coding...

Previous Next

Message Layer in WCF ( How message passes from clients to service and vice versa )

Introduction

In my previous article ( ABC of WCF ) I have given some brief idea about the basic concept of WCF.
Here we will see how the message is passed between the client and the service.

Different modes of message transmission and how it works.

Behind The Scene

While, we are talking about WCF, we should keep in mind that there is two separate parts in WCF programing. One is client and another is service. And in order to access the service the client needs to send some message to the service with some argument in a certain format, that is described in the
binding section of the service.
This messaging layer defines in what format and patterns the data is exchanged between client and service.


Client - Service Communication

Messages

A message is a packet of data, that is transmitted from the client to the service and vice versa in a secure manner. The messages are formatted in XML.

WCF meassages are generally SOAP( simple object access protocol ) messages. Here I am giving you  brief idea about the SOAP messages.

 The SOAP message contains three parts such as

  • SOAP Envelope
                 The is the outermost part of the SOAP message. A SOAP envelope contains several pieces of key information in the form of elements. They includes: The name of the envelope, a namespace name, an optional <header> element, a required <body> element.
  • SOAP Header
                It is a collection of zero or more header blocks, i.e. a SOAP message can contain no headers or have collection of headers. So it's optional, if included then it must be the first child element of the SOAP envelop. Using a SOAP header, we can pass useful information about the services to the outer world if needed; it's just for information sharing. Any child elements of the header element are called "header blocks". This provides a mechanism for grouping logical data together
  • SOAP Body
               This element contains the actual SOAP message for communication with the SOAP receiver, a message can contain zero or more bodies. Any information intended to be exchanged
when the message reaches the intended destination goes in the message body. In simple terms the SOAP body contains the response for the client request.

Example:

<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">

 <soap:Header>

    This is just for Information to outer world

 </soap:Header>

 <soap:Body>

   Message goes here

 </soap:Body>

</soap:Envelope> 
 
In WCF there the messages can be sent from a client to a service, from a service to a client and from a service to a service.

Messaging Patterns

  • Simplex
              One way communication between the client and the service, here the message is being sent from the client to the service without any response from the latter.

Simplex Messaging
  •  Duplex
            Here two way communication is occurred between the service and the client. The client requests some task to the service and the service responds back to the client with the result.


Duplex messaging


  •  Request-Reply
            The Request-Reply messaging pattern doesn't allow bi-directional communication to happen freely. The client sends a response and then waits for reply. The service doesn't communicate anything until it receives a message.

Request Reply Messaging



That's all about the messaging in WCF service, hope you enjoyed this article.


Happy Coding...

Previous Next

ABC of WCF ( Address, Binding, and Contract of WCF )

Introduction

WCF ; Windows Communication Foundation, the name already describes what it is. Let me clarify it once again. WCF is an advance technology of Microsoft that enables user to use it in a network distributed manner. In layman's language lets say you have written some bunch of code and you want to use it from various applications at a single time, then WCF gives you this freedom.

Before going into details we have to know the fundamentals of WCF. The Microsoft .NET framework provides you the template for developing the WCF application.

Behind The Scene

In this article I will give a brief idea about the ABC of WCF.

A ( Address ) : A stands for address, this is the url ( address ) through which the WCF service can be accessible. You can say it as a url or address. The basic format of an WCF service address is below;

[Protocol]://[Machine Name/Domain Name] : [Port]/[Service Name]

** Here the [Port] number is optional.

There are various protocols are used in WCF services like

  • HTTP
  • TCP
  • MSMQ
  • NAMED PIPE
So an example of the url/address will look like this

http://localhost:4040/PublishService

B ( Binding ) : B stands for Binding, and this defines how the service can be used and called. I mean this says you how the message should pass to the service in order to get the desired out put from the service.

There are many types of bindings like
  • basicHttpBinding
  • wsHttpBinding
  • wsDualHttpBinding
  • netTcpBinding
  • netMSMQBinding
C ( Contract ) : C stands for Contract, that is the interface and this says what the service should do. there are variou contracts like
  • Data Contract ( Data Contract defines the data types used in the service methods. )
  • Operation Contract ( This contracts holds the signature of the service method )
  • Service Contract ( Here the functionality is achieved )
  • Message Contract ( This controls the SOAP messages sent and received by service )
See the next article (Message Layers in WCF) to know the details how the message is being transferred between client and the service in WCF technology.


Happy Coding...

Next