How to Create and Consume WCF Services

WCF provides a runtime environment for your services, enabling you to expose CLR types as services and to consume other services as CLR types.

What is WCF?

 
WCF is a unification technology, which unites .Net Remoting, MSMQ, Web Services and COM+ technologies.
 
WCF provides a runtime environment for your services, enabling you to expose CLR types as services and to consume other services as CLR types.
 

Creating WCF Service

 
Open Visual Studio 2008/2010. Click on File menu -> New -> Project ->WCF Service Application. Change the name as "WCFService" then click Ok button.
 
WCF1.gif
 
Delete auto generated files IService1.cs and Service1.svc and create new (right click on WCFService project and select Add -> New Item -> WCF Service). Rename service as "UserService".
 
WCF2.gif
 
Now add an Entity Data Model in your project to communicate with database.
 
Service Code
 
Replace interface IUserService with the code given below :
  1. using System;  
  2. using System.Data;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Runtime.Serialization;  
  6. using System.ServiceModel;  
  7. using System.Text;  
  8.   
  9. namespace WCFService  
  10. {  
  11.     [ServiceContract]  
  12.     public interface IUserService  
  13.     {  
  14.         [OperationContract]  
  15.         string Authenticate(string UserName, string A_CryptKey);  
  16.   
  17.         [OperationContract]  
  18.         DataTable GetApprovedUser();  
  19.     }  
  20. }  
Replace UserService class code with the code given below :
  1. using System;  
  2. using System.Data;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Runtime.Serialization;  
  6. using System.ServiceModel;  
  7. using System.Text;  
  8.   
  9. namespace WCFService  
  10. {  
  11.     public class UserService : IUserService  
  12.     {  
  13.         public string Authenticate(string UserName, string A_CryptKey)  
  14.         {  
  15.             using (var Context = new UsersEntities())  
  16.             {  
  17.                 var user = Context.Users.Where(c => c.UserName == UserName && c.A_CryptKey == A_CryptKey).FirstOrDefault();  
  18.                 if (user != null)  
  19.                     return Convert.ToString(user.UserID) + "," + Convert.ToString(user.B_CryptKey);  
  20.                 else  
  21.                     return string.Empty;  
  22.             }  
  23.   
  24.         }  
  25.   
  26.         public DataTable GetApprovedUser()  
  27.         {  
  28.             using (var Context = new UsersEntities())  
  29.             {  
  30.                 DataTable objdt = new DataTable();  
  31.                 objdt = Context.Users.Where(c => c.IsApproved == true).ToList().CopyToDataTable();  
  32.                 return objdt;  
  33.             }  
  34.         }  
  35.     }  
  36. }  
Service configuration
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <configuration>  
  3.   <system.web>  
  4.     <compilation debug="true" targetFramework="4.0">  
  5.       <assemblies>  
  6.         <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />  
  7.       </assemblies>  
  8.     </compilation>  
  9.   </system.web>  
  10.   <system.serviceModel>  
  11.     <behaviors>  
  12.       <serviceBehaviors>  
  13.         <behavior>  
  14.           <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->  
  15.           <serviceMetadata httpGetEnabled="true" />  
  16.           <!-- 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 -->  
  17.           <serviceDebug includeExceptionDetailInFaults="false" />  
  18.         </behavior>  
  19.       </serviceBehaviors>  
  20.     </behaviors>  
  21.     <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />  
  22.   </system.serviceModel>  
  23.   <system.webServer>  
  24.     <modules runAllManagedModulesForAllRequests="true" />  
  25.   </system.webServer>  
  26.   <connectionStrings>  
  27.     <add name="UsersEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="Data Source=ServerName;Initial Catalog=Favourites;Persist Security Info=True;User ID=UserName;Password=Password;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />  
  28.   </connectionStrings>  
  29. </configuration>  

Consuming WCF Service

 
Now right click on UserService.svc and select "View in Browser". it will show a browser with service URL. Copy that URL
 
WCF3.gif
 
Now right click on WCFClient project select "Add Service Reference" and paste copied URL in Address section of "Add Service Reference" dialog box and click on Go button and rename Namespace as "UserService" and click ok button.
 
WCF4.gif
 
WCF Client code
  1. using System;  
  2. using System.Data;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.UI;  
  7. using System.Web.UI.WebControls;  
  8. using UserService;  
  9. public partial class _Default : System.Web.UI.Page  
  10. {  
  11.     protected void Page_Load(object sender, EventArgs e)  
  12.     {  
  13.         UserServiceClient proxy = new UserServiceClient();  
  14.   
  15.         string User = proxy.Authenticate("Mukesh""X%AY#$tZ");  
  16.   
  17.         DataTable objdt = new DataTable();  
  18.         objdt = proxy.GetApprovedUser();  
  19.    
  20.         proxy.Close();  
  21.   
  22.     }  
  23. }  
Client side configuration
  1. <system.serviceModel>  
  2.     <bindings>  
  3.       <basicHttpBinding>  
  4.         <binding name="BasicHttpBinding_IUserService" closeTimeout="00:01:00"  
  5.           openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"  
  6.           allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"  
  7.           maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"  
  8.           messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"  
  9.           useDefaultWebProxy="true">  
  10.           <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"  
  11.             maxBytesPerRead="4096" maxNameTableCharCount="16384" />  
  12.           <security mode="None">  
  13.             <transport clientCredentialType="None" proxyCredentialType="None"  
  14.               realm="" />  
  15.             <message clientCredentialType="UserName" algorithmSuite="Default" />  
  16.           </security>  
  17.         </binding>  
  18.       </basicHttpBinding>  
  19.     </bindings>  
  20.     <client>  
  21.       <endpoint address="http://localhost:57728/UserService.svc" binding="basicHttpBinding"  
  22.         bindingConfiguration="BasicHttpBinding_IUserService" contract="UserService.IUserService"  
  23.         name="BasicHttpBinding_IUserService" />  
  24.     </client>  
  25.   </system.serviceModel>