Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Ads by Lake Quincy Media
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » .NET 3.0/3.5 » WCF programming for Beginners

WCF programming for Beginners

This article provides the basics for programming the WCF Service.

Total page views :  64449
Total downloads :  1865
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
HostWCFService_IIS.zip | WCFService.zip
 
Become a Sponsor


Windows Communication Foundation (WCF)

Windows Communication Foundation (WCF) is a dedicated communication frame work provided by the Microsoft. WCF is a part of .NET 3.0. The runtime environment provided by the WCF enables us to expose our CLR types as services and to consume other existing services as CLR types.

Background:

In the world there are lot of distributed communication technologies exist. Some of them are:

  • ASP.NET Web Services (ASMX)
  • Web Services Enhancements (WSE)
  • Messaging (MSMQ)
  • .NET Enterprise Services (ES)
  • .NET Remoting

Creating and Consuming a Sample WCF Service:

Three major steps are involved while creating and consuming the WCF services. Those are:

  1. Create the Service.(Creating)
  2. Binding an address to the service and host the Service. (Hosting)
  3. Consuming the Service.(Consuming)

Step 1: Creating the Service

In WCF, all services are exposed as contracts. Contract is a neutral way of describing the service what it does. Mainly we have four types of contracts:

  1. Service Contract

    This contract describes all the available operations that client can perform on the service.

    .Net uses "System.ServiceModel" Name space to work with WCF services.

    ServiceContract attribute is used to define the service contract. We can apply this attribute on class or interface. Servicecontract attribute exposes a CLR interface (or a class) as a WCF contract.

    OperationContract attribute, is used to indicate explicitly which method is used to expose as part of WCF contract. We can apply OperationContract attribute only on methods, not on properties or indexers.  

    [ServiceContract] applies at the class or interface level.
    [OperatiContract] applies at the method level. 

  2. Data Contract

    This contract defines the data types that passed in and out to the service.

    [DataContract] attribute is used at the custom data type definition level, i.e. at class or structure level.
    [DataMember] attribute is used to fields, properties, and events.

  3. Fault Contract

    This contract describes about the error raised by the services. 

    [FaultContract(<<type of Exception/Fault>>)] attribute is used for defining the fault contracts.

  4. Message Contracts

    This contract provides the direct control over the SOAP message structure. This is useful in inter operability cases and when there is an existing message format you have to comply with.

    [MessageContract] attribute is used to define a type as a Message type. 
    [MessageHeader] attribute is used to those members of the type we want to make into SOAP headers
    [MessageBodyMember] attribute is used to those members we want to make into parts of the SOAP body of the message. 

Sample Service Creation :

[ServiceContract]

          public interface IFirstWCFService

                    {

                   [OperationContract]

                   int Add(int x, int y);

 

 

                   [OperationContract]

                   string Hello(string strName);

                  

                  int Multiplication(int x, int y);

                   }

Here "IFirstWCFService" is a service exposed by using the servicecontract attribute. This service exposes two methods "Add","Hello" by using the [OperationContract] attribute. The method "Multiplication" is not exposed by using the [OperationContract] attribute. So it wnt be avlible in the WCF service.

public class FrtWCFService : IFirstWCFService

    {

        public int Add(int x, int y)

        {

            return x + y;

        }

 

        public string Hello(string strName)

        {

            return "WCF program  : " + strName;

        }

 

        public int Multiplication(int x, int y)

        {

            return x * y;

        }

 

    }

"FrtWCFService" is a class,which implements the interface "IFirstWCFService". This class definse the functionality of methods exposed as services. 

STEP 2:  Binding and Hosting

Each service has an end point. Clients communicates with this end points only. End point describes 3 things :

  1. Address
  2. Binding type
  3. Contract Name (which was defined in STEP 1)

Address

Every service must be associated with a unique address. Address mainly contains the following  two key factors :

  1. Transport protocal used to communicate between the client proxy and service.

    WCF supports the following transport machinisams:

    • HTTP   (ex : http://  or https:// )
    • TCP     (ex :  net.tcp :// )
    • Peer network   (ex: net.p2p://)
    • IPC (Inter-Process Communication over named pipes) (ex: net.pipe://)
    • MSMQ  (ex: net.msmq://)

  2. Location of the service.

    Location of the service describes the targeted machine(where service is hosted) complete name (or) path  and optionally port / pipe /queue name. 

    Example :   localhost:8081 
    Here local host is the target machine name.
    8081 is the optional port number. 

    Example 2:  localchost
    This is with out optional parameter. 

Here are a few sample addresses:  

http://localhost:8001

http://localhost:8001/MyFirstService

net.tcp://localhost:8002/MyFirstService

net.pipe://localhost/MyFirstPipe

net.msmq://localhost/MyFirstService

net.msmq://localhost/MyFirstService

Binding is nothing but a set of choices regarding the  transport protocol (which transport protocal we have to use : http /tcp /pipe etc.) ,message encoding (tells about the message encdong / decoidng technique)  ,communication pattern (whether communication is asynchronous, synchronous,  message queued etc.) , reliability, security, transaction propagation, and interoperability.

WCF defines the nine basic bindings:

Binding Type .Net Class implements this binding Transport Encoding Inter operable Comments
Basic Binding BasicHttpBinding Http / Https Text / MTOM Yes Used to expose a WCF service as a legacy ASMX web service.
TCP binding NetTcpBinding TCP Binary NO TCP is used for cross-machine communication on the intranet.
Peer network binding NetPeerTcpBinding P2P Binary NO In this peer network transport schema is used to communicate.
IPC binding NetNamedPipeBinding IPC Binary NO This uses named pipes as a transport for same-machine communication. It is the most secure binding since it cannot accept calls from outside the machine.
WSbinding WSHttpBinding Http / Https Text / MTOM Yes This uses Http / Https as a communication schema.
Federated WS binding WSFederationHttpBinding Http / Https Text / MTOM Yes This is a specialization of the WS binding. This offers the support for federated security
Duplex WS binding WSDualHttpBinding Http Text / MTOM Yes This is a WS binding with bidirectional communication support from the service to the client.
MSMQ binding NetMsmqBinding MSMQ Binary NO This supports for disconnected queued calls
MSMQ integration binding MsmqIntegrationBinding MSMQ Binary Yes This is designed to interoperate with legacy MSMQ clients.

Hosting:

Every service must be hosted in a host process. Hosting can be done by using the

  • IIS
  • Windows Activation Service (WAS)
  • Self hosting
     

Hosting Type Advantages Limitations
IIS Hosting IIS manages the life cycle of host process. ( like application pooling, recycling, idle time management, identity management, and isolation) Only HTTP transport schemas WCF service are hosted in IIS.
WAS Hosting
  • WAS supports for all available WCF transports, ports, and queues.
  • WAS manages the life cycle of host process.
Some adv of self hosted processing is missing.
Self Hosting
  • Developer can have explicit control over opening and closing the host.
  • In-Proc hosting can be done.
Missing the host process life cycle management.

IIS Hosting

IIS hosting is same as hosting the traditional web service hosting. Create a virtual directory and supply a .svc file.

In Vs2008 select a project type: "WCF Service Application".

In the solution explorer, under the App_code folder you can find the two files: "IService.cs" and "Service.cs".

"IService.cs" class file defines the contracts. "Service.cs" implements the contracts defined in the "IService.cs". Contracts defined in the "IService.cs" are exposed in the service. 

Check in the Web.Config file, under <system.serviceModel> section:

<services>

      <service name="Service" behaviorConfiguration="ServiceBehavior">

        <!-- Service Endpoints -->

        <endpoint address="" binding="wsHttpBinding" contract="IService">

          <!--

              Upon deployment, the following identity element should be removed or replaced to reflect the

              identity under which the deployed service runs.  If removed, WCF will infer an appropriate identity

              automatically.

          -->

          <identity>

            <dns value="localhost"/>

          </identity>

        </endpoint>

        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>

      </service>

    </services>

In this one , end point node specifies the : address, binding type, contract (this is the name of the class that defines the contracts.)

Another end point node endpoint address="mex" specify about the Metadata end point for the service.

Now host this serivce by creating the virtual directory and browse the *.SVC file:

 

Hosting with Windows Activation Service (WAS)

WAS is a part of IIS 7.0. It comes with VISTA OS. The hosting with the Windows Activation Service is same as hosting with IIS. The only difference between these two is, IIS supports for HTTP binding only. Whereas WAS supports for all transport schemas.

Self Hosting

In this technique developer is only responsible for providing and managing the life cycle of the host process. In this one host service must be running before the client calls the service.  To host the service we use the .NET class ServiceHost.  We have to create an instance of the "ServiceHost".  Constructor of this class takes two parameters: service type, base address. (Base address can be empty set.)

Uri baseaddress = new Uri("http://localhost:8080");

ServiceHost srvHost = new
ServiceHost(typeof(WCFService.FrtWCFService),baseaddress);

Add the Service End points to the host :

We will use the AddServiceEndpoint() to add an end point to the host. As we awre that end point contains thress things:  type of service, type of binding, service Name.

So, AddServiceEndpoint() method accepts these three as the required parameters.

srvHost.AddServiceEndpoint(typeof(WCFService.IFirstWCFService), new BasicHttpBinding(), "FirstWCFService");

Adding the Meta Data End points to the host:

For the Meta data, service type will be: typeof(IMetadataExchange)

srvHost.AddServiceEndpoint(typeof(IMetadataExchange), httpBinding, "MEX");

Up to Now, we have created the host process and add the end points to it. Now call the open() method on the host. By calling the Open( ) method on the host, we allow calls in, and by calling the Close( ) method, we stylishly exit the host instance, that means, allowing calls in progress to complete, and yet refusing future new client calls even if the host process is still running

srvHost.Open();

STEP 3: Consuming the Service

With WCF, the client always communicates with the proxy only. Client never directly communicates with the services, even though the service is located on the same machine. Client communicates with the proxy; proxy forwards the call to the service.  Proxy exposes the same functionalities as Service exposed.

  

Consuming WCF Service Hosted by IIS/WAS

Consuming WCF service is very similar way of consuming a web service by using the proxy. To consume the service, in the solution explorer click on "Add service Reference" and add the service created in the STEP1.

A service reference is created under the service reference folder. Use this proxy class to consume the WCF service as we are doing with web services.

ServiceReference1.FirstWCFServiceClient obj = new                 

             UsingWCFService.ServiceReference1.FirstWCFServiceClient();

 

Console.WriteLine(obj.Add(2, 3).ToString());

 

obj.Close();

Alternatively: We can create  the proxy class by using the following command

svcutil.exe [WCFService Address]

This generates a service proxy class, just include this class in to the solution and consume the service.

Consuming by creating the channel factory:

We can consume the service by creating the channel factory manually. While creating the channel, we have to provide the same binding type and end point address where the service is hosted.

IFirstWCFService chnl = new ChannelFactory<IFirstWCFService>

(new BasicHttpBinding(), new EndpointAddress("http://localhost:8080/MYFirstWCFService")).CreateChannel();

Here IFirstWCFService is the service contract interface, that is exposed.


Login to add your contents and source code to this article
 About the author
 
Sunil
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
HostWCFService_IIS.zip | WCFService.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
Great Article by Adnan On September 15, 2008
Hey Sunil, Great write dude, to the point and completely informative.
Reply | Email | Delete | Modify | 
Great Article by Adnan On September 15, 2008
Hey Sunil, Great write dude, to the point and completely informative.
Reply | Email | Delete | Modify | 
Informative article by Mamta On November 4, 2008
This article was well-written and is quite deep.
Reply | Email | Delete | Modify | 
excellent by deba On November 17, 2008
Hey Sunil... What a article you have been described here. really it is superb. Thanks.
Reply | Email | Delete | Modify | 
Nice article for a newbie by Satyanand On December 11, 2008
A very good article to start off with WCF. Good writeup. Thanks
Reply | Email | Delete | Modify | 
Please proof-read it by Dharni On December 17, 2008
Lots of mistakes.
Reply | Email | Delete | Modify | 
Great for beginners by Shalu On December 18, 2008
I definitely like the article and was successful with IIS hosting, Self hosting. I only had an issue with ChannelFactory where i could not figure out the endpointaddress. Anyway a must read for beginners! Thanks Sunil for taking the time to write it.
Reply | Email | Delete | Modify | 
good job by samir On February 18, 2009
really really good article.....
Reply | Email | Delete | Modify | 
Great Article by KYAW MYINT On March 11, 2009
Hi Sunil, Short to the points for beginner. Thanks for your time.
Reply | Email | Delete | Modify | 
Nice artical. On the dot.. by phani On March 18, 2009
Hey Sunil, I spent more than an hour on MSDN and I was lost. Your artical is crisp and clear. Thanks again.
Reply | Email | Delete | Modify | 
Great Article by sudha On June 25, 2009

Excellent, crisp and informative article

Reply | Email | Delete | Modify | 
Excellent Article by sudha On June 25, 2009
Excellent Article
Reply | Email | Delete | Modify | 
WCF by shashi On June 25, 2009
for dummies:) good job!
Reply | Email | Delete | Modify | 
really greate. by prem On September 2, 2009
Thanks sunil..it's really helpfull.

Reply | Email | Delete | Modify | 
Very Good Article.... by rupali On September 21, 2009
Very Clear and informative
Reply | Email | Delete | Modify | 
Re: Very Good Article.... by Atithi On October 6, 2009
Hey Sunil,

Really nice article for a newbie like me. Thanks a lot !!
Reply | Email | Delete | Modify | 
dfghdfghdfg by Srini On November 20, 2009
dfghdfghdfghdfghdfghdfgh dfghdgfh hhdfg
Reply | Email | Delete | Modify | 
Super Article by selva On December 20, 2009
Hi Sunil,
Super article . will help more .
247
Reply | Email | Delete | Modify | 
Thank you by rajesharra On February 7, 2010
Hi,
Thank you for this article...i am very new to WCF servicess and it's given me a complete picture in one shot.

thanks once again..

regards
rajesh A
Reply | Email | Delete | Modify | 
Nice Article by pavani On February 15, 2010
Nice Article
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.