C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Communities   Interview   Jobs   Projects   Offshore Development    
Silverlight Tutorials | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Revenue Sharing |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...

New Feature: Community Sites: Create your own .NET community website and start earning from Google AdSense ! It's Free !




WINDOWS COMMUNICATION FOUNDATION (WCF) - An Introduction


Posted Date: 21 Apr 2008    Resource Type: Articles    Category: .NET Framework

Posted By: srilu       Member Level: Diamond
Rating:     Points: 12



INTRODUCTION TO WCF



WCF is an enhanced technology that ships with .Net 3.0. It helps developers build service oriented applications which are distributed systems that communicate between the service and the clients.

The main advantages of WCF are its rich communication capabilities and interoperability .It can be used to provide a service across different platforms.WCF provides the same functionality as the web services but with some better functionality and features. The main difference between a web service and WCF Service is that a web service uses HTTP protocol where as a WCF service can use any protocol.

Having services located in several systems at several places to effectively serve the common needs is referred to as distributed systems which finally leads to the service oriented design. The service oriented architecture also uses object oriented concepts as its core .The main benefit of service oriented design is that the services can be developed using OOP’s in any technology and platform and cam communicate with other services through any protocol.

The basic terminology of WCF includes: Client and Service. The program which requests a service is referred to as Client and the program which responds to the Client is called Service. The client and Service communicate with each other by sending and receiving messages using WCF.

A single service can have multiple clients and the service itself can be a client to another service. In between the client and the service are the intermediaries which acts as a firewall and can also be used to rout messages between them.

The basic unit of communication in the WCF is called the end point through which we interchange the information with a service. Each endpoint contains three elements: Address which may be the URI, Binding and a Contract (which are referred to as ABC of an endpoint).

ARCHITECTURE OF WCF


The WCF architecture consists of 5 layers namely:
1. Application.
2. Contracts.
3. Runtime.
4. Messaging.
5. Hosting.

APPLICATION: The Application layer is the top most layers in which the application is located.

CONTRACTS: This is the second layer in the application and comprises of the service contracts, message contracts, data contracts and the bindings and policies. In this layer the services describe themselves to the client.

SERVICE CONTRACT: The service contracts are the entry point into the definition of the service. They are Interfaces which consists of the method signatures used in the service. They need to be declared using the [Service Contract ()] attribute and the method signatures need to be declared using the [Operation Contract] attribute. One WCF can have more than one Service Contract.

[Operation Contracts] are similar to [Webmethods] in web services.
You can control the generation of the WSDL at operation level, by making use of some of the properties of the Operation Contract method like Action, AsyncPatter, Name, IsTerminating, IsInitiating, IsOneWay, and ReplyAction etc.

The syntax for using the properties will be like


[OperationContract(Action=http://abcd/def,
IsOneWAy=false, IsTerminating=true,IsInitiating=false,
Name=”abcd”,AsyncPattern=false)]
[/CPDE]
We can control the behavior of a service (like concurrency, sessionmode, threadbehaviour, transaction, throttling) at class level using [ServiceBehavior()] attribute and by making use of its properties .

So the code sample looks like this:


[Service Contract()]
public Interface Isum
{
[OperationContract]
int sum(int x,int y);
}


You need to write a class which inherits that interface and implement the methods in the interface there.

public class sum:Isum
{
public int sum(int x,int y)
{
return x+y;
}
}

There are three types of Service contracts:


  1. TYPED: Which are used for simple communication.


  2. UNTYPED: Which are used for message level communication.


  3. TYPED MESSAGES: These are intermediate between Typed and Untyped which make use of custom classes defined in Message Contracts.



DATA CONTRACTS


Data Contracts define the members, properties and return values. They make use of classes instead of Interfaces as in the case of Service Contracts.

The properties of the attributes are defined in the data contracts using the [Data Member] attribute.

For example you have a service which contains a method that takes 2 values and returns their sum, your Data contract for that service looks like below:


[DataContract]
public class getsum
{
[Datamember]
public int x
{
Get{ return x;}
Set {x=value;}
}

[Datamember]
public int y;
{
Get{ return y;}
Set {y=value;}
}
}


If a data member is mandatory , you can set that using the “IsRequired” attribute of the data member like


[Datamember (IsRequired=true)]
public int x;


This indicates that it is mandatory to supply the value of x to the method which uses these variables but supply of y is optional.


MESSAGE CONTRACT


The message contract contains definition for the message parts like the header and the body using SOAP protocol. It defines the format of the message. They are declared using the [MessageHeader] and [MessageBodyMember] respectively.

The Message contract looks like below:


[MessageContract]
public class Mymessage
{
[MessageHeader]
Public string Myheader;

[MessageBodymember]
Public Employee mymessagebody;
}


POLICY AND BINDING CONTRACT


Bindings are the communication channels between the service and the client.
It holds information about the transport, security details, and other aspects that are required in order to communicate with a service.

Depending on the type of protocol different types of bindings are available.
Binding decides whether a service is session enabled or not because all bindings do not enable sessions.
The different properties of bindings are as follows. They can be declared in the web.config file like





BasicHttpBinding: For Basic web service communication without security
WSHttpBinding: For web services which follow WS-* standards and also support transactions
WSDualHttpBinding: For web services with duplex contract (two way messaging) and which also supports transactions.
WSFederationHttpBinding: For web services which have federated security and also supports transactions
MsmqIntegratedBinding: For web services which directly communicate with MSMQ and also supports transactions.
NetMsmqBinding: For web services which communicate between WCF applications using queuing and transactions.
NetNamedpipeBinding: For web services which communicate between WCF applications and some duplex contracts using transactions
NetPeerTcpBinding: For web services which communicate across peer to peer services using duplex contracts
NetTcpBinding: For web services which communicate across peer to peer services using duplex contracts

FAULT CONTRACT: They are used to document the errors which a service may cause.
Sample code looks like


[FaultContract (typeof(System.Exception)]


SERVICE RUNTIME: This is the third layer of the WCF.
In this layer the behavior of the services are defined.
It is responsible for loading all the services. It also manages the execution of the services.

The behaviors in the runtime layer can be defined using attributes or making necessary settings in the web.config file.

The behaviors included in the runtime layer are:

THROTTLING BEHAVIOR: This is where you can define the limit of connections, sessions and threads.

ERROR HANDLING BEHAVIOR: Defines how error handling takes place and how error messages are displayed to the clients.

METADATA BEHAVIOR: Describes whether the metadata is displayed to the end user and if yes, how it is displayed.

TRANSACTION BEHAVIOR: Enables a transaction to be rolled back when an error or failure occurs.

DISPATCH BEHAVIOR: Controls the way of how messages are processed by the WCF.

PARAMETER FILTERING: Filter the actions based on the filtration occurring at the message headers.

MESSAGING: It comprises of the different types of channels and encoders and enables communication between the client and the service.

It tells the available formats and exchange patterns of the data.

This layer comprises of the
WS SECURITY CHANNEL: This enables the security of the messages while they are sent/received at the messaging layer.

WS RELIABLE MESSAGING CHANNEL: This guarantees the delivery of the sent/received messages.

ENCODERS: Provides different encoders based on the message formats.

HTTP CHANNEL: Indicates that the HTTP protocol is being used for delivering messages.

TCP CHANNEL: Indicates that the TCP protocol is being used for delivering messages.

TRANSACTION FLOW CHANNEL: Takes care of the transacted message patterns.

NAMED PIPE CHANNEL: Enables Inter-Process communication.

MSMQ CHANNEL: It enables the communication with MSMQ applications.

ACTIVATION AND HOSTING: This layer is responsible for hosting the services.
There are two ways to host a service. One is to directly host the service in the IIS and the other is to create a dll for the service and consume it through the application.

We need to declare contracts and behaviors using attributes. The endpoints and security need to be defined by making some configuration setting s in the web.config file. The methods in the service can be defined using logics and simple coding.

USING WCF IN YOUR WEB APPLICATION



Having got a basic idea about WCF, now let’s go ahead and try an example of how to use WCF in our applications.

To work with WCF we need to install .NET Framework 3.0 and Visual Studio 2005 Xtensions.
As said above, there are two ways of developing and hosting a WCF.

One is you can directly develop the WCF from your web application. The following are the steps involved in doing that.

Go to the Solution Explorer in your web application and in the “Add New Item” add “WCF Service” named “test service”. This adds testservice.cs file in your App_Code folder and testservice.svc in the solution explorer.

“testservice.svc” contains information about the service created and the testservice.cs is the file in which you do the coding.

After you write the implementation for the methods in the interface, you can use it in your application by creating the instance for that service and calling its methods.

The other way of using WCF is, first develop the WCF and add its reference to your application and make use of its methods.

Follow these steps:

Create a new WCF Service by navigating through

File>New>Website and there select WCF Service named MyService .

Once this file is created, you can see the service contract for a sample application.

You can try and test the same or you can write your own code there.

Let’s take an example of printing the sum of 2 numbers. So your code should like this example:


[ServiceContract()]
Public Interface Itestservice
{
[OperationContract]
int sum(int x,int y);

[OperationContract]
int diff(int x,int y);
}


Now we need to write a class which inherits Isum and provide the implementation for its methods.


Public class testservice:Itestservice
{
Public int sum(int x,int y)
{
return x+y;
}
Public int diff(int x,int y)
{
If(x>y)
{
return x-y;
}
return y-x;
}
}


Now you need to invoke the above method in the service through your web application. To use this service in your web application you need to add the System.ServiceModel.Activation name space to your testservice.cs.
You also need to add the following line after the interface and above the class.
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]

This makes your service compatible with your web application.You also have to make some changes in your web.config to make this service work.


<system.serviceModel>
<services>

<service name="MyService" behaviorConfiguration="returnFaults">
<endpoint contract="I MyService " binding="basicHttpBinding"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="returnFaults">
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
</system.serviceMo del>


After making all the above configurations, build and run your service.
When you run the service you can see a page saying. “you have built a service.To use it……” .After that you will see a link to its wsdl .Copy that link.
http://localhost:xxxx/MyService/Service.svc?wsdl.
Now open your web application and add a reference to the service.For that go to “Add Web Reference” and paste the link of the wsdl in that and click go. You can see the list of the methods in your service listed there .Give a name to your service as “useservice” and click “Add Reference” button there.
Now you are ready to use theservice in your application.

In your webform, in button click you can create an instance for this service and make use of its methods.


protected void Button1_Click(object sender, EventArgs e)
{
useservice.MyService ms = new useservice.MyService();
bool res=true;
int z;
int sum = Convert.ToInt32(ts.sum(10,true,20,true,out z,out res));
int diff = Convert.ToInt32(ts.diff(30,true,10,true,out z,out res));
Response.Write(sum);
Response.Write(diff);
}


You need to pass the extra parameters to your method to satisfy the other overload parameters.
Run the application and you can see the result.





Responses


No responses found. Be the first to respond and make money from revenue sharing program.

Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Windows communication foundation  .  Wcf  .  Using wcf  .  Introduction to wcf  .  Architecture of wcf  .  

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: ADO.NET Connection Pooling at a Glance
Previous Resource: C#.Net Basics
Return to Discussion Resource Index
Post New Resource
Category: .NET Framework


Post resources and earn money!
 
Related Resources



dotNet Slackers   BizTalk Adaptors    Web Design

UK Conference calling Company

Contact Us    Privacy Policy    Terms Of Use