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:
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.
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.
Data Contract
Create new console app from visual studio select project type as console application gives some name as you like.
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. |
|||
|
|||
160 comments :
Great post bro...thanks.
good post... u did not use Fault Contract while consuming the service.. can u please giv the more information on this...
Nice and succint
my name is babu my home town is tenali,
Good post. Thanks for the information.
i did it......thanx for d example
This is article is very easy to understand.Thanks for Sharing.(4m Kadapa)
This is very easily understandable for WCF begineers. Thanks
Rajesh
Good Sample
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
Online video streaming from webcam is possible in wcf
Good post it is easy understandable...Thanks alot...(4m RAMU Hyderabad)
Mohan babu good !
Very nice article especially for beginners.Looking ahead with more and more...
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
good article for beginners..
Thanks bro !! Very good Tutorial
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.
thanks suresh for sharing your knowledge
rahul M
Thanks for the good Article on WCF
Great post for beginners to know what and how WCF works ..,thanks you so much ..,
thanks for this post...its very helpfull and easy.
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.
is this above method describes all about self hosting?if yes, can you give me some contents regarding IIS hosting pls?
@deva..
it's IIS hosting only not self hosting please check the post
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
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.
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.....
suresh.. u are awesome..!! I like ur blog. Me too have the one but some what different.
This is Santhosh
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.
Yes that was really helpfull :)
great post. thanks. http://prasadaknair.blogspot.com
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
Very helpfull for beginners
Very informative Artical..
Thanks,
Kajal N
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
Hello Suresh can u post some topics regarding Mobile Apps using .Net
Great post Bro. Easy to understand the concepts.
Good article. It helps me a lot in learning WCF..
Thank
good
great
Thanks. Done my 1st WCF example by this
good post, thanks..
Great article Suresh, well written.. Thanks
http://www.migpeg.com
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
If you right click the Project in VS you ll see Add service reference or you can use Proxy(SVCUTIL) to create the same
This is a Very simple way to learn WCF service.
Thanks for this post.
thanku
Please Upload File Upload With Percentage Progress Bar In Asp.net Please Upload It. I Need It Very Much. Thank You
this is a best example for wcf
hi suresh,nice article.try to post more advanced details reg wcf
Thanks for the good Article on WCF
this is not a standard Process to create a WCF service
hello..
can u help me how to do online video streaming via webcam in asp.net..?
Simply and very good explanation for beginners.
nice..
This link is good..
Cud u provide any other link to explain more abt WCF?
nice tutorial
Thanks man..
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.
Thanks for this post. Simple and informative. It helps me a lot.
Thanks,
AL
its a very nice post for beginners........
Hi Suresh ,
Really this is great posting for all beginners.
Thanks a lot !!!
Rajendra
ffdfff
Very informative blog.... thanks
hum yeh tutorial padh kar khush huye
good one
very nice tutorial dude
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
Awesome bhava..
-killerBapu
Hi dis is lakshmi.good post and very useful and thanks.
its very nice and useful one
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?
Hi iam Geting an error 'Service' does not implement interface member 'IService.Welcome(string)'
how to create Asp.net application using wcf service in Mtom
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)
Sir:>>
How to actually work MVC Architecture in asp.net ?
How to create View,Controller and Model...
Very nice and simple to understand
-Vijay
very useful..
Can you pls tell us about widget...thanx in advance
Nice aritical
Hi Sir
Nice Article
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)'
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
very useful for beginners
This is very easily understandable for WCF begineers. Thanks
Really Its Nice Suresh. I had done my first WCF program using your example. Thanks
Great Article for beginners ! Appreciated your efforts !
Thnx Sir, this is so gud example of WCF technology.
Great post bro...thanks.
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..
xlent...
you are doing a great job....keep it up.:)
sir.... plz. send the chat code on your site ...
plz sir......
thankssss you.......
very nice article on wcf..i got clear understanding about WCF..this site helping lot.
Thank u so much sir.
-
Shanth
Bangalore
Very good Site for Asp.Net
Sarika
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
Sir Please give one link for Android application(Hello world)
this is gooddfdfdfdfdfdfdf
qwqwqqw
weweew
awesome suresh sir lot of thanks
Regards
Rajkumar Chavan
Very nice article bro.
Very concise and well written. Well done mate!
Thanks it really works....
good article ...its really helpful
its really help me lot
Nice One Ya Brother
Your posts are very nice ..
Thank you friend, great post. Great Explaination. Thanks a lot.
Hi,
Your WCF service and Console Application are as
some as in the one solution for Visual studio ?
hello sir,
please tell me that where we use @@ in .net
This question was asked in interview to me.
Please Give An Example of Invoice in C sharp...
Such as Sr.no. ProductName Rate Qty
Please Please
Good Explanation about wcf
Thank You!!!!
sir,i want some help from u regards mobile application developement.Kindly guide me and post some useful topics.
Well Explained.....
Thanks for posting........
I don't have endpoints mentioned in webconfig
great one...everything excellent
Thanks for this excellent article, I really like this. I have started just learning on wcf, It help me lot much.
How to insert data, update and delete and display data from database using MVC in C sharpDotNet?
very nice , and helpful , thank u for uploading such content .
very nice , and helpful , thank u for uploading such content .
nice post
nice post
Excellent post. Keep it up
nice............
Good Post for WCF Basics.........
good.....
good platform to expand your skills
Nice Article...Thanks
Lightweight Informative Post
Good job.
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
very nice......
Rajesh m Somvanshi
A very informative article...
This gives basic idea about WCF and how to build a simple WCF services. Very good for beginners. :)
Yep!!...it is good one for beginers like me
Good Article to star WCF
Nice Article.. Very helpful
Thanks
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
Thanks for the good Article on WCF for Beginners....
very good post ............!
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)
Nice post
Ajay Kumar
SE
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 ..
Very good article! Thanks a lot :)
Very Nice .. )
kollam.... polichu tto........................
Great post
Understud bt therz no clarity in article
kem javab nahi apto...
Thanks Sir , Its Working,
I always Follows Yor Site
Pabitra Behera ,Bhubaneswar
Your blog is very good
Very Informative blog scholarship essay writing help
Thanks a lot for this tutorial Good blog. Very interesting and helpful.
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 -muhasin.nk@benzyinfotech.com,
sir please post new articles in "WEB API"
Thank you sir,...................
That's very good blogs for biggners. please give another example with different types of bindings like WSHttpBinding, WSDualHttpBinding, MsmqIntegrationBinding etc.
mr suresh too good and i ll kidnap u......................hhhhhhhhhaaaaaaaaaaaaaa
Thanku Sir ..sir
Thanks sir..It is easy to understand for beginner's..Nice
Note: Only a member of this blog may post a comment.