Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

Introduction to WCF - WCF tutorial | WCF Tutorial - Windows Communication Foundation | WCF Example | WCF Sample code in asp.net 3.5 | Basic WCF Tutorial for Beginners

Jun 26, 2011
Introduction:

Here I will explain what WCF (windows communication foundation) is, uses of windows communication foundation and how to create and use windows communication foundation in c#.

Description:
In previous articles explained clearly what webservice is and how to create and consume webservice using asp.net . In another post I explained clearly what windows service is and how to create windows service and sample of windows service using c#. Now in this article I will explain about windows communication foundation. First we will see what a WCF (window communication foundation) is and uses of WCF (windows communication foundation) after that we will see how to create and use WCF in c#.net.

What is WCF (windows communication foundation) Service?

Windows Communication Foundation (Code named Indigo) is a programming platform and runtime system for building, configuring and deploying network-distributed services. It is the latest service oriented technology; Interoperability is the fundamental characteristics of WCF. It is unified programming model provided in .Net Framework 3.0. WCF is a combined feature of Web Service, Remoting, MSMQ and COM+. WCF provides a common platform for all .NET communication.
Advantages of WCF
     1)    WCF is interoperable with other services when compared to .Net Remoting where the client and service have to be .Net.

     2)    WCF services provide better reliability and security in compared to ASMX web services.

     3)    In WCF, there is no need to make much change in code for implementing the security model and changing the binding. Small changes in the configuration will make your requirements.

     4)    WCF has integrated logging mechanism, changing the configuration file settings will provide this functionality. In other technology developer has to write the code.

Difference between WCF and Web service

Web service is a part of WCF. WCF offers much more flexibility and portability to develop a service when comparing to web service. Still we are having more advantages over Web service; following table provides detailed difference between them.

Features
Web Service
WCF
Hosting
It can be hosted in IIS
It can be hosted in IIS, windows activation service, Self-hosting, Windows service
Programming
[WebService] attribute has to be added to the class
[ServiceContract] attribute has to be added to the class
Model
[WebMethod] attribute represents the method exposed to client
[OperationContract] attribute represents the method exposed to client
Operation
One-way, Request- Response are the different operations supported in web service
One-Way, Request-Response, Duplex are different type of operations supported in WCF
XML
System.Xml.serialization name space is used for serialization
System.Runtime.Serialization namespace is used for serialization
Encoding
XML 1.0, MTOM(Message Transmission Optimization Mechanism), DIME, Custom
XML 1.0, MTOM, Binary, Custom
Transports
Can be accessed through HTTP, TCP, Custom
Can be accessed through HTTP, TCP, Named pipes, MSMQ,P2P, Custom
Protocols
Security
Security, Reliable messaging, Transactions

A WCF Service is composed of three components parts viz,

1) Service Class - A WCF service class implements some service as a set of methods.

2) Host Environment - A Host environment can be a Console application or a Windows Service or a Windows Forms application or IIS as in case of the normal asmx web service in .NET.

3) Endpoints - All communications with the WCF service will happen via the endpoints. The endpoint is composed of 3 parts (collectively called as ABC's of endpoint) as defines below:

Address: The endpoints specify an Address that defines where the endpoint is hosted. It’s basically url.

Ex:http://localhost/WCFServiceSample/Service.svc

Binding: The endpoints also define a binding that specifies how a client will communicate with the service and the address where the endpoint is hosted. Various components of the WCF are depicted in the figure below.
  • "A" stands for Address: Where is the service?
  • "B" stands for Binding: How can we talk to the service?
  • "C" stands for Contract: What can the service do for us?
Different bindings supported by WCF

Binding
Description
BasicHttpBinding
Basic Web service communication. No security by default
WSHttpBinding
Web services with WS-* support. Supports transactions
WSDualHttpBinding
Web services with duplex contract and transaction support
WSFederationHttpBinding
Web services with federated security. Supports transactions
MsmqIntegrationBinding
Communication directly with MSMQ applications. Supports transactions
NetMsmqBinding
Communication between WCF applications by using queuing. Supports transactions
NetNamedPipeBinding
Communication between WCF applications on same computer. Supports duplex contracts and transactions
NetPeerTcpBinding
Communication between computers across peer-to-peer services. Supports duplex contracts
NetTcpBinding
Communication between WCF applications across computers. Supports duplex contracts and transactions
BasicHttpBinding
Basic Web service communication. No security by default
WSHttpBinding
Web services with WS-* support. Supports transactions

Contract: The endpoints specify a Contract that defines which methods of the Service class will be accessible via the endpoint; each endpoint may expose a different set of methods.

Different contracts in WCF

Service Contract

Service contracts describe the operation that service can provide. For Eg, a Service provide to know the temperature of the city based on the zip code, this service is called as Service contract. It will be created using Service and Operational Contract attribute.

Data Contract

Data contract describes the custom data type which is exposed to the client. This defines the data types, which are passed to and from service. Data types like int, string are identified by the client because it is already mention in XML schema definition language document, but custom created class or data types cannot be identified by the client e.g. Employee data type. By using DataContract we can make client to be aware of Employee data type that are returning or passing parameter to the method.

Message Contract

Default SOAP message format is provided by the WCF runtime for communication between Client and service. If it is not meeting your requirements then we can create our own message format. This can be achieved by using Message Contract attribute.

Fault Contract

Suppose the service I consumed is not working in the client application. I want to know the real cause of the problem. How I can know the error? For this we are having Fault Contract. Fault Contract provides documented view for error occurred in the service to client. This helps us to easy identity, what error has occurred.

Overall Endpoints will be mentioned in the web.config file for WCF service like this

<system.serviceModel>
<services>
<service name="Service" behaviorConfiguration="ServiceBehavior">
<!-- Service Endpoints -->
<endpoint address="http://localhost:8090/MyFirstWcfService/SampleService.svc" binding="wsHttpBinding" contract="IService">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>


Creating simple application using WCF

First open Visual Studio and click file --> Select New --> Website Under that select WCF Service and give name for WCF Service and click OK 



Once you created application you will get default class files including Service.cs and IService.cs



Here IService.cs is an interface it does contain Service contracts and Data Contracts and Service.cs is a normal class inherited by IService where you can all the methods and other stuff.

Now open IService.cs write the following code

[ServiceContract]
public interface IService
{
[OperationContract]
string SampleMethod(string Name);
}

After that open Service.cs class file and write the following code 

public class Service : IService
{
public string SampleMethod(string Name)
{
return "First WCF Sample Program " + Name;
}
}


Here we are using basicHttpBinding for that our web.config file system.serviceModel code should be like this and I hope no need to write any code because this code already exists in your web.config file in system.serviceModel

<system.serviceModel>
<services>
<service name="Service" behaviorConfiguration="ServiceBehavior">
<!-- Service Endpoints -->
<endpoint address="" binding="wsHttpBinding" contract="IService">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>

Our WCF service ready to use with basicHttpBinding. Now we can call this WCF Service method console applications

After completion of WCF service creation publish or deploy your WCF Service in your system. If you don’t’ have idea on deploy check this post publish or deploy website

After completion of deploy webservice now we can see how to use WCF Service in our console application

Calling WCF Service using Console Application

To call WCF service we have many ways like using console app, windows app and web app but here I am going for console application.

Create new console app from visual studio select project type as console application gives some name as you like.



After Creation Console application now we need to add WCF reference to our console application for that right click on your windows application and select Add Service Reference


Now one wizard will open in that give your WCF service link and click Go after add your service click OK button.


After completion of adding WCF Service write the following code in Program.cs class file Main method

static void Main(string[] args)
{
ServiceReference1.ServiceClient objService = new ServiceClient();
Console.WriteLine("Please Enter your Name");
string Message = objService.SampleMethod(Console.ReadLine());
Console.WriteLine(Message);
Console.ReadLine();
}
After that open your app.config file and check your endpoint connection for WCF Service reference that should be like this

<endpoint address=" http://localhost/WCFServiceSample/Service.svc"
binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IService"
contract="ServiceReference1.IService" name="WSHttpBinding_IService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
Now everything is ready run your application that output should be like this




If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

158 comments :

raja said...

Great post bro...thanks.

tnvbalaji.com said...
This comment has been removed by a blog administrator.
Subhash said...

good post... u did not use Fault Contract while consuming the service.. can u please giv the more information on this...

Martinez said...

Nice and succint

Anonymous said...

my name is babu my home town is tenali,
Good post. Thanks for the information.

Mats said...

i did it......thanx for d example

Shakeer said...

This is article is very easy to understand.Thanks for Sharing.(4m Kadapa)

Anonymous said...

This is very easily understandable for WCF begineers. Thanks

Rajesh

Sudharshan said...

Good Sample

Anonymous said...

just a rubbish question.. in Interface u named method as Welcome & in service you say SampleMethod.. wont this cause a compile error....or WCF can handle this... if yes then do we have to write something in .config file for it?... please clarify

techsoftweb said...

Online video streaming from webcam is possible in wcf

G Ramu said...

Good post it is easy understandable...Thanks alot...(4m RAMU Hyderabad)

Anonymous said...

Mohan babu good !

Anonymous said...

Very nice article especially for beginners.Looking ahead with more and more...

SANDEEP SHARMA said...

sir
i have some problem in user control, like i have 1 Usercontrol Having Text Box(as will as textChange event) and 1 aspx Page whre we use this usercontrol.in this page 1 Gridview .i wana to filter this gridview when any value entered on Usercontrol textbox, bind this gridview on TextChange Event of usercontrol.plz help me. send me any Ans at -sandeep.mca008@gmail.com,sandeepsharma264@gmail.com


thanks in advance

Anonymous said...

good article for beginners..

bhuvan said...

Thanks bro !! Very good Tutorial

Anonymous said...

The code in your Service.cs is not quite correct. The method name should be Welcome as it should be implementing the method defined in the IService interface else it won't compile.

Anonymous said...

thanks suresh for sharing your knowledge

rahul M

Subbu said...

Thanks for the good Article on WCF

Anonymous said...

Great post for beginners to know what and how WCF works ..,thanks you so much ..,

vishal said...

thanks for this post...its very helpfull and easy.

Unknown said...
This comment has been removed by the author.
Muralidhar Kotur said...

Hi Suresh,
I'm developing application in android, now i need to develop the wfs service in .net 2010 in such away that the values entered and submitted in android application has to be stored in sql server 2008. So plase could you help me.

thanking you.

deva said...

is this above method describes all about self hosting?if yes, can you give me some contents regarding IIS hosting pls?

Suresh Dasari said...

@deva..
it's IIS hosting only not self hosting please check the post

Dorababu said...

Hi Suresh i like your blog a lot. I need some more examples on WCF where we can insert, edit, update and delete data using Sql from asp.net

Anonymous said...

Thank your for this resource. I m trying start a wcf service for a long time. but this resource really help me very much. now i can do any wcf programming.

Anonymous said...

Hi Suresh,

You blog is very informative and easy to understand.Thanks for such a useful site.
I have one question about difference b/w windows and webforms?please clarify.....

Anonymous said...

suresh.. u are awesome..!! I like ur blog. Me too have the one but some what different.

This is Santhosh

Dylan Shaw said...

Moreover it is an structure to create Service focused programs under microsoft foundation preparing both concept and rpc design of programming.Through this we can obtain optimization platform through binary as well as start standards based marketing and sales communications.

Shayan Khan said...

Yes that was really helpfull :)

Anonymous said...

great post. thanks. http://prasadaknair.blogspot.com

Pavan Bhardwaj said...

Awesome post dear!!!!!!!!
thnks a lot for giving the basic details about wcf
Pls post article for other . net topics
like WPF, Silver light, LINQ, WFF
I am liking your blog bcuz of content quality that is simple and understandable [minimum content but describe much more in proper way] for a beginner

Anonymous said...

Very helpfull for beginners

Anonymous said...

Very informative Artical..

Thanks,
Kajal N

Anonymous said...

hai sir,
his is rajesh how to used in piechart in asp.net connect to database using dynamically.please send me my mail sir,,,vuda.rajesh59@gmail.com

Anonymous said...

Hello Suresh can u post some topics regarding Mobile Apps using .Net

Anonymous said...

Great post Bro. Easy to understand the concepts.

Anonymous said...

Good article. It helps me a lot in learning WCF..
Thank

Anonymous said...

good

Anonymous said...

great

SagarDarshan said...

Thanks. Done my 1st WCF example by this

Brijesh said...

good post, thanks..

Anonymous said...

Great article Suresh, well written.. Thanks

http://www.migpeg.com

Anonymous said...

nice,

ANIL KUMAR REDDY said...

hello suresh ,I have one doubt,iam create service then iam adding refrence to consoleapplication , i didnt find' Addservicerefrence' can you help me where i can add

Peru said...

If you right click the Project in VS you ll see Add service reference or you can use Proxy(SVCUTIL) to create the same

Anonymous said...

This is a Very simple way to learn WCF service.
Thanks for this post.

jagadeesh said...

thanku

Anonymous said...

Please Upload File Upload With Percentage Progress Bar In Asp.net Please Upload It. I Need It Very Much. Thank You

Anonymous said...

this is a best example for wcf

Anonymous said...

hi suresh,nice article.try to post more advanced details reg wcf

KiranK said...

Thanks for the good Article on WCF

Anonymous said...

this is not a standard Process to create a WCF service

Anonymous said...

hello..

can u help me how to do online video streaming via webcam in asp.net..?

Anonymous said...

Simply and very good explanation for beginners.

Anonymous said...

nice..

satya said...

This link is good..
Cud u provide any other link to explain more abt WCF?

Anonymous said...

nice tutorial

Anonymous said...

Thanks man..

Anonymous said...

Nice Article. In WSHttpBinding : Web services with WS-* support. Supports transactions, could you please let me know what do you mean by WS-*?
This is Ashok here from Bengaluru.

Anonymous said...

Thanks for this post. Simple and informative. It helps me a lot.

Thanks,
AL

Anonymous said...

its a very nice post for beginners........

Anonymous said...

Hi Suresh ,
Really this is great posting for all beginners.
Thanks a lot !!!
Rajendra

Anonymous said...

ffdfff

Anonymous said...

Very informative blog.... thanks

Anonymous said...

hum yeh tutorial padh kar khush huye

Josey said...

good one

rock sam said...

very nice tutorial dude

Rid said...

Cool Man..

I read your articles regarding web services and now read WCF Article its awesome yar..
Too much help full for beginners...

Thank you so much

Anonymous said...

Awesome bhava..
-killerBapu

lakshmi said...

Hi dis is lakshmi.good post and very useful and thanks.

pallavi said...

its very nice and useful one

crazy kittu said...

Hi Suresh, After writing the methods in iservice and service classes when i build the application it is showing the error as

"Error 1 'Service' does not implement interface member 'IService.Welcome(string)' C:\Users\muralikrishna\Documents\Visual Studio 2008\WebSites\myWCF\App_Code\Service.cs 9 14 C:\...\myWCF\
"


Why like that?

Anonymous said...

Hi iam Geting an error 'Service' does not implement interface member 'IService.Welcome(string)'

STANLY said...

how to create Asp.net application using wcf service in Mtom

Hanny G said...

Hi suresh,

IService.cs
string Welcome(string Name);

Service.cs
public string SampleMethod(string Name)



please change the method name in IService.cs
Welcome(string Name) to SampleMethod(string Name)
or

SampleMethod(string Name) to Welcome(string Name)


H@R$H said...

Sir:>>

How to actually work MVC Architecture in asp.net ?
How to create View,Controller and Model...

Anonymous said...

Very nice and simple to understand
-Vijay

Anonymous said...

very useful..

Anonymous said...

Can you pls tell us about widget...thanx in advance

Anonymous said...

Nice aritical

Keshava Praveen said...

Hi Sir
Nice Article

saurabh said...

There is an error in above example.In Iservice.cs the [OperationContract] has name 'Welcome' and in Service.cs while implementing it ,bymistakely 'SampleMethod' name is used(instead of 'Welcome').Please edit it otherwise it will give error as : 'Service' does not implement interface member 'IService.Welcome(string)'

BRIJESH said...

Hello sir I have read your blog and beginner to WCF. I have wcf web service so service and client on the same windows machine ...But whenever I call the service it gives an error like this



"The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'NTLM'."



Please help me and figure out what to do

Angel M said...

very useful for beginners

shanti said...

This is very easily understandable for WCF begineers. Thanks

SAI said...

Really Its Nice Suresh. I had done my first WCF program using your example. Thanks

Anonymous said...

Great Article for beginners ! Appreciated your efforts !

Anonymous said...

Thnx Sir, this is so gud example of WCF technology.

Mohamed Kalif Raja Syed Ahamed said...

Great post bro...thanks.

.. said...

Hi,
The type 'WcfService1.Service1', provided as the Service attribute value in the ServiceHost directive, or provided in the configuration element system.serviceModel/serviceHostingEnvironment/serviceActivations could not be found.
I am getting the above error.. Could you help me out..

Anonymous said...

g8

Anonymous said...

xlent...

Anonymous said...

you are doing a great job....keep it up.:)

Nikhil Verma said...

sir.... plz. send the chat code on your site ...
plz sir......



thankssss you.......

Santosh Rathod said...

very nice article on wcf..i got clear understanding about WCF..this site helping lot.
Thank u so much sir.

-
Shanth
Bangalore

Anonymous said...

Very good Site for Asp.Net



Sarika

Anonymous said...

nice one

santosh chhotaray said...

Hi Sir
This is Santosh Kumar Chhotaray working in Asp.Net and C#. I want some tutorial in WCF. Please post some tutorial in WCF. Or mail me On hellosantoshchhotaray@gmail.com

Anonymous said...

Sir Please give one link for Android application(Hello world)

sumit said...

this is gooddfdfdfdfdfdfdf

Anonymous said...

qwqwqqw

Anonymous said...

weweew

Rajkumar Chavan said...

awesome suresh sir lot of thanks
Regards
Rajkumar Chavan

Anonymous said...

Very nice article bro.

Anonymous said...

Very concise and well written. Well done mate!

ankush jassal said...

Thanks it really works....

Anonymous said...

good article ...its really helpful

lalita patil said...

its really help me lot

Nowfal Vazhappally said...

Nice One Ya Brother

Anonymous said...

Your posts are very nice ..

TamilFriendsClub said...

Thank you friend, great post. Great Explaination. Thanks a lot.

Anonymous said...

Hi,
Your WCF service and Console Application are as
some as in the one solution for Visual studio ?

Yogendra Singh said...

hello sir,
please tell me that where we use @@ in .net
This question was asked in interview to me.

Subhash Yadav said...

Please Give An Example of Invoice in C sharp...
Such as Sr.no. ProductName Rate Qty



Please Please

Anonymous said...

Good Explanation about wcf

Thank You!!!!

Anonymous said...

sir,i want some help from u regards mobile application developement.Kindly guide me and post some useful topics.

Mllikarjuna said...

Well Explained.....

Thanks for posting........

mem said...

I don't have endpoints mentioned in webconfig

Anonymous said...

great one...everything excellent

Anonymous said...

Thanks for this excellent article, I really like this. I have started just learning on wcf, It help me lot much.

Anonymous said...

good post

Anonymous said...

How to insert data, update and delete and display data from database using MVC in C sharpDotNet?

neeraj kanojiya said...

Thanks suresh!!!
You are doing an EXCELLENT job.

neeraj kanojiya said...

I need to ask one more thing...
If i want to become an expert in WCF so what should I do?

ALOK DEO said...

very nice , and helpful , thank u for uploading such content .

ALOK DEO said...

very nice , and helpful , thank u for uploading such content .

meraj anwer said...

nice post

Anonymous said...

nice post

Anonymous said...

Excellent post. Keep it up

Anonymous said...

nice............

Anonymous said...

Good Post for WCF Basics.........

Anonymous said...

good.....

nwsindia said...

good platform to expand your skills

Sakthi Vengatesan.S said...

Nice Article...Thanks

Arun said...

Lightweight Informative Post
Good job.

thudish kumar D said...

HI .. i have one doubt in my service have two method ,but Clint can see only one method other should be hide can u explain this .my mail id thudishkumar@gmail.com

Anonymous said...

very nice......

Rajesh m Somvanshi

Tijo said...

A very informative article...

Venkatesh Venki said...

This gives basic idea about WCF and how to build a simple WCF services. Very good for beginners. :)

Anonymous said...

Yep!!...it is good one for beginers like me

Venu guda said...

Good Article to star WCF

Anonymous said...

Nice Article.. Very helpful
Thanks

pravallika dasari said...

Hai its Good Article to star WCF ..........
I have a problem. I am a beginner and can any one tel me the answer could be in a simple words ....
I Use Visual Studio 2012 and I want to create a WCF Service with Entity Framework to get access to a database. It can be done in 5-10 minutes...
I created a simple database with SQL Express (For example : 2 tables : Employee and Company, with CId as a foreign key in the Employee table)
I created a new WCF service
I added an ADO.NET Entity Data Model (.edmx) linked to my database
I created a method to return all my clients
When I try the method in the WCF Test Client. I getting a error.

But it works correctly if I remove the foreign key in my Client table...

My getClients method :

public List GetUserRegDetails()
{
using (DropdownsEntities de = new DropdownsEntities())
{
de.Configuration.LazyLoadingEnabled = false;
return de.Employees.ToList();
}

}

Or

public List GetUserRegDetails()
{
List e = new List();
try
{
e = de.Employees.ToList();

return e;
}
catch{}

finally{}

return e;
}
all the other methods insert and delete methods are wroking when i am trying to test the GetUserDtails() in WCF test client i am getting error failed to invoke the service how to slove

nalini moganti said...

Thanks for the good Article on WCF for Beginners....

Ramdas Mutkule said...

very good post ............!

Abhisek Das said...

its my fav tuitorial site.sir,can u explian how to create "sidebar" in asp.net?
like in This page "facebook" option includede like..(@ right hand side)

Anonymous said...

Nice post

Ajay Kumar
SE

suresh said...

hai

muhasinnk@gmail.com said...

sir can i work with you as junior developer with your company
please reply sir

i need to study more advanced about ASP.NET

please sir include me ..

autuk said...

Very good article! Thanks a lot :)

Pushparaj S said...

Very Nice .. )

njan from kerala said...

kollam.... polichu tto........................

Anonymous said...

Great post

Anonymous said...

Understud bt therz no clarity in article

Anonymous said...

kem javab nahi apto...

Give your Valuable Comments

Other Related Posts

© 2010-2012 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.