Introduction: Windows Communication Foundation (WCF) previously known as "Indigo" is a framework for building configuring and deploying network distributed system .Wcf is a service-oriented application. Using WCF we can build connected secure, reliable, transacted solutions that integrate across platforms.
Description: In some of my previous articles i demonstrated with example How to create WCF Service to bind,insert,edit,update,delete from sql server database in asp.net and How to create crystal reports in visual studio 2010 using asp.net and How to Bind,Save,Edit,Update,Cancel,Delete,Paging example in GridView in asp.net C#
Now in this article i will explain with example how easily you can create your first WCF service and how to consume WCF service. It is a network distributed system developed by Microsoft for communication between applications interoperate between WCF-based applications and any other processes that communicate via SOAP (Simple Object Access Protocol) messages.
WCF allows sending data as asynchronous messages from one service endpoint to another. A service endpoint can be part of a continuously available service hosted by IIS, or it can be a service hosted in an application. An endpoint can be a client of a service that requests data from a service endpoint. The messages that can be sent can be as simple as a single character or word sent as XML, or as complex as a stream of binary data.
What is ABC in WCF
We had gone through the feature of WCF and understood why its termed as advanced version of web services. Now it’s time to answer a very basic question related to WCF i.e., what is ABC of WCF?
When we say WCF, we came across end points. Service endpoint can be a part of continuously hosted service hosted in IIS or service hosted in an application.
ABC where "A"stands for Address,"B" stands for Binding and "C" stands for Contract are the three elements which constitutes and Service Endpoint.
Now it’s time to create a consuming application that will consume the service provided by WcfSample service we just created.
Create a new website as:
Now add the service reference of the WCF service we created as:
Using ServiceReference;
Description: In some of my previous articles i demonstrated with example How to create WCF Service to bind,insert,edit,update,delete from sql server database in asp.net and How to create crystal reports in visual studio 2010 using asp.net and How to Bind,Save,Edit,Update,Cancel,Delete,Paging example in GridView in asp.net C#
Now in this article i will explain with example how easily you can create your first WCF service and how to consume WCF service. It is a network distributed system developed by Microsoft for communication between applications interoperate between WCF-based applications and any other processes that communicate via SOAP (Simple Object Access Protocol) messages.
WCF allows sending data as asynchronous messages from one service endpoint to another. A service endpoint can be part of a continuously available service hosted by IIS, or it can be a service hosted in an application. An endpoint can be a client of a service that requests data from a service endpoint. The messages that can be sent can be as simple as a single character or word sent as XML, or as complex as a stream of binary data.
WCF Hosting
Web services that was used earlier was hosted inside web server such as IIS using http or wsHttp protocols. But WCF (Windows Communication Foundation) supports four types of hosting.
Web services that was used earlier was hosted inside web server such as IIS using http or wsHttp protocols. But WCF (Windows Communication Foundation) supports four types of hosting.
- IIS
- WAS (Windows process activation services)
- Self-hosting
- Windows services
What is ABC in WCF
We had gone through the feature of WCF and understood why its termed as advanced version of web services. Now it’s time to answer a very basic question related to WCF i.e., what is ABC of WCF?
When we say WCF, we came across end points. Service endpoint can be a part of continuously hosted service hosted in IIS or service hosted in an application.
ABC where "A"stands for Address,"B" stands for Binding and "C" stands for Contract are the three elements which constitutes and Service Endpoint.
- Address - Where the Service is residing (URL of the service.) i..e. where the service is?
- Binding – Way to talk to the service? Example – basicHttpBinding, wsHttpBinding, webHttpBinding etc.
- Contract – What can the service do for me?
- WCF is interoperable with other services when compared to .Net Remoting where the client and service have to be .Net.
- WCF services provide better reliability and security in compared to ASMX web services.
- In WCF, there is no need to make much change in code for implementing the security model and changing the binding. Instead it requires small changes in the configuration.
- WCF has integrated logging mechanism, changing the configuration file settings will provide this functionality. In other technology developer has to write the code.
- Open visual studio ->File -> New ->Website -> select Visual C# language from the left pane and WCF Service from the right pane and Name it WcfSample or whatever you want.
- Now it will create a file Service.svc and two files IService.cs and Service.cs under App_Code folder in Solution Explorer
- In the IService.cs interface remove all existing sample code that is placed in the interface IService and let’s declare our own functions as:
[ServiceContract]
public interface IService
{
[OperationContract]
int GetEmpId(int id);
[OperationContract]
string GetEmpName(string
name);
[OperationContract]
string GetDept(string
dept);
[OperationContract]
int GetBasicSalary(int
BasicSal);
[OperationContract]
int GetPF(int
BasicSal);
[OperationContract]
int GetHRA(int
BasicSal);
[OperationContract]
int GetGrossSalary(int
BasicSal);
}
- Similarly remove all existing sample
code that is placed inside the Service class in the Service.cs file and write
define the function. Our Service.cs file will look like as:
public class Service : IService
{
public int GetEmpId(int id)
{
return id;
}
public string
GetEmpName(string name)
{
return name;
}
public string
GetDept(string dept)
{
return dept;
}
public int
GetBasicSalary(int BasicSal)
{
return BasicSal;
}
public int GetPF(int BasicSal)
{
return (BasicSal * 7) / 100;
}
public int GetHRA(int BasicSal)
{
return (BasicSal * 4) / 100;
}
public int
GetGrossSalary(int BasicSal)
{
return BasicSal + GetPF(BasicSal) + GetHRA(BasicSal);
}
}
- Now in web.config file write as:
<system.serviceModel>
<services>
<service name="Service" behaviorConfiguration="ServiceBehavior">
<endpoint address="" binding="wsHttpBinding" contract="IService">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange">
</endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<!-- To
avoid disclosing metadata information, set the value below to false and remove
the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To
receive exception details in faults for debugging purposes, set the value below
to true. Set to false before deployment
to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
- Congratulations you have created a Wcf service. Now
make Service.svc file as startup page by right clicking on the Service.svc file
in the solution explorer and select “set as start up page” and run the website.
If everything is fine then it will look like as shown in the image below:
Click on image to enlarge |
- Copy the URL of the service. Here in our example it is “http://localhost:1416/WcfSample/Service.svc”
Note: Leave the Wcf application running.
Consuming WCF Service
Now it’s time to create a consuming application that will consume the service provided by WcfSample service we just created.
Create a new website as:
Open visual studio ->File -> New ->Website ->
select Visual C# language from the left pane and ASP.NET Empty website from the
right pane and Name it "ConsumingWcfSample" or whatever you want.
Add a new page as: Website menu-> Add new item ->Web Form->
default.aspx
Now add the service reference of the WCF service we created as:
Right click on the ConsumingWcfSample website and select Add
Service Reference and paste the WCF service address (“http://localhost:1416/WcfSample/Service.svc”)
that we copied earlier in the address box. Notices that ServiceReference is the
namespace that is to be included on the page where we want to consume the WCF
service .You can also rename it as per your choice. But we have not changed the
default name. Click on GO button
Click on image to enlarge |
You can also view all the functions declared in the IService
by clicking on the Service-> IService in the Add Service Reference box as shown in image
below:
Click on image to enlarge |
- Now In the design page default.aspx create the structure as:
<table>
<tr>
<td>
Employee ID</td>
<td>
<asp:TextBox ID="txtEmpID" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Employee Name</td>
<td>
<asp:TextBox ID="txtEmpName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Department</td>
<td>
<asp:TextBox ID="txtDept" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Basic Salary</td>
<td>
<asp:TextBox ID="txtBasicSal" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
onclick="btnSubmit_Click"/>
</td>
</tr>
</table>
- In the code behind
file default.aspx.cs
Add the following required namespace:
Using ServiceReference;
- In the submit button
click event write the code as:
protected void btnSubmit_Click(object sender, EventArgs e)
{
ServiceReference1.ServiceClient obj = new ServiceReference1.ServiceClient();
Response.Write("Employee ID:
" + obj.GetEmpId(Convert.ToInt32(txtEmpID.Text.Trim())));
Response.Write("<BR/>Employee
Name: " +
obj.GetEmpName(txtEmpName.Text.Trim()));
Response.Write("<BR/>Employee
Department: " +
obj.GetDept(txtDept.Text.Trim()));
Response.Write("<BR/>Basic
Salary: " +
obj.GetBasicSalary(Convert.ToInt32(txtBasicSal.Text.Trim())));
Response.Write("<BR/>PF:
" + obj.GetPF(Convert.ToInt32(txtBasicSal.Text.Trim())));
Response.Write("<BR/>HRA:
" + obj.GetHRA(Convert.ToInt32(txtBasicSal.Text.Trim())));
Response.Write("<BR/>Gross
Salary: " +
obj.GetGrossSalary(Convert.ToInt32(txtBasicSal.Text.Trim())));
}
- Now run the default page and enter the details as:
Click on image to enlarge |
- And click on submit. It will call the WCF service methods and process the data and return the Output as :
Click on image to enlarge |
Now suppose you want to add another function or make
modification in the existing functions then how it is possible?
In fact it’s very easy. What you need to do is to add
another function or modify existing function in the WCF service and then run
the service.
Now open your ConsumingWcfSample application and right click
on the App_WebReferences folder under solution explorer and click on Update
Web/Service References as:
Click on image to enlarge |
Now over to you:
"If you like my work; you can appreciate by leaving your comments,
hitting Facebook like button, following on Google+, Twitter, Linked in and
Pinterest, stumbling my posts on stumble upon and subscribing for receiving
free updates directly to your inbox . Stay tuned for more technical
updates."
49 comments
Click here for commentsvery informative article...it cleared all my doubts... perfect!!
Reply: )
thanks for your valuable feedback..keep reading and get updated always.
ReplyThank U BOSS it's very use full for me
Replyreally great article thank you so much...
Replyvery clear and usefull post on WCF great thanx...
Replythanks for your valuable feedback bhagwat..keep reading for similar useful articles
ReplyGood article for beginners - Ramesh Venkat
ReplyThanks for your feedback Ramesh Venkat. Yes this article was solely written form the beginners. I will post the articles on WCF for intermediate level and experts very soon. Stay tuned for more updates
ReplyThank u so much lalit...i m new follower of ur blog...vry useful content..till date i have so many doubt about WCF and nw it cleared..again thanks a lot.
Replythanks for your appreciation..Stay tuned for more updates
ReplyBoss Done great Job
ReplyKeep it up
And how to use session in my application and after some times it tell me session expires
are u continue yes or no
Thanks gurmeet and read the article to solve your session expire problem
ReplyHow to increase session timeout period in asp.net
http://www.webcodeexpert.com/2013/02/how-to-increase-session-timeout-period.html
This is awesome!! really helpful for me. Thanks for sharing with us. It helped me to complete my task.
Replyvery nice article for wcf begineers,..
ReplyCan you please post some more article,examples,code snippets on WCF..
very nice article for wcf begineers,..
ReplyCan you please post some more article,examples,code snippets on WCF..
Sir..Can you please provide code Snippets where Interface Concept,Data Abstraction,Sealed class,Abstract class is implemented..I would be very thankfull...
ReplyThanks for the feedback Asif..Please check my another article on WCF..hope it will be more useful for you
ReplyWCF Service to bind,insert,edit,update,delete from sql server database in asp.net C#
http://www.webcodeexpert.com/2013/08/wcf-service-to-bindinserteditupdatedele.html
Thanks..
Replyhello Asif..thanks for the reading and suggestions..I'll post related to Interface Concept,Data Abstraction,Sealed class,Abstract classes in my upcoming articles..please stay tuned for updates..
ReplySir , u r d best .... all the articles are best with simplest code snippet and examples ... i m beginner in advance will u plz further cover some advance topics of wcf and wpf.
ReplyThanks
Thanks for the appreciation..this blog has article for the beginners as well as experienced..and it is growing so stay tuned for the more advanced topics as per your suggestions..
Replynice article.....really good stuff for beginners.....
Replythanks for the appreciation..
Replythanku u sir very useful article for me and all wcf beginners....
Replythanks for appreciating this article..keep reading..
ReplyThank You! It was "Very" Imformative!
ReplyThanks for your appreciation..keep reading..
ReplyI have followed the instructions but i get error saying "metadata publishing for this service is currently disabled" i have double and triple cheked the code with no error. can you tell me what might be wrong on my end. please.
ReplyHi, it seems there is any error in setting service name,behavior etc your web.config. i suggest you to recheck that and notify me..if still you face error then send your sample project to me on my email lalit24rocks.com and i will check and help you to sort out the problem..
Replyfinally got what i want to start wcf . thank you so much sir
ReplyYour welcome Ajay..stay connected and keep reading for more useful updates like this..:)
ReplyThanks Lalit for a nice article for beginners of WCF.
ReplyIm so much confuse to where i start to learn wcf.
Now im cleared about wcf. Can u give me one more example which service have work with sql database and produce some complex results in form of text based on some client input and produce result to client machine. and tell me how to security and other things are managed in that example
Hi, also read the article to learn more about WCF
ReplyWCF Service to bind,insert,edit,update,delete from sql server database in asp.net C#
http://www.webcodeexpert.com/2013/08/wcf-service-to-bindinserteditupdatedele.html
very nice article
ReplyI am glad you found this article useful..stay connected and keep reading..:)
ReplyGreat Work Useful Article....
ReplyHello lohith r..thanks for appreciating my work..i am glad you found this article helpful..stay connected and keep reading..:)
ReplyThank You!
ReplyNice Article!
Hello tilahun abebe..thanks for appreciating my work..it is always nice to hear that someone found my articles helpful..stay connected and keep reading for more useful updates..:)
ReplyGood job!
ReplyIt is very helpful...
Got my basics cleared here
Thanks :)
Hi Rasmita..i am glad you found this article helpful..stay connected and keep reading...:)
ReplyVery Nice and Clear Work Lalit Sir...
ReplyThis is my 1st Programm of Wcf & It's Work Properly...
But I am Still confused for What the Change done in Web.config File...
And Why we need to change it???
It's very Nice and Clear Work Lalit Sir...
Replythis is my 1st Programm in WCF and it's Work Successfully
But, I am Still Confused for what Change done in Web.config and why????
hey lalit its very useful for me really
Replylet me know ur cell number in case i need more help
Thanks for appreciating my work..it is always nice to hear that my article helped anyone in learning asp.net..in case you need my help you can comment here...stay connected and keep reading..:)
Replyhi.how to select data in asp.net using web revice in xml format? :( please help me.
ReplyFinally! a page that explains in simple and easy steps by steps the use of WCF.
ReplyThanks a lot for help..
ReplyThanks for your feedback..Stay connected and keep reading for more useful updates
ReplyIf you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..