WCF Overview

The purpose of this tutorial is to explain the basics of WCF in a manner as simple as possible. This tutorial explains WCF Services and why we use a WCF Service and how to create a basic WCF Service and consume it and and many more things related to WCF. 

In the tutorial we will talk about the following points:

  1. What a Service is
  2. What a WCF Service is
  3. Why to use a WCF Service
  4. Advantages of WCF over a Web Service
  5. Components of Web Services
    • WCF Service class
    • WCF Service host
    • WCF Service endpoints with address, binding and contract
  6. WCF Service file Structure
  7. Features of WCF
    • Interoperability
    • Service Orientation
    • Multiple Message Patterns
    • Security
    • Transactions
    • AJAX and REST Support
  8. Creating a Web Service
1. What a Service is

A Service is a program or application that is used by other applications. In other words, a service that is directly consumed by the end user to do their work and is something they ask for and recognize. or. It's just self-contained business functionality.

Service-Oriented Architecture (SOA)

SOA is an architectural approach to the distributed systems to integrate flexibility with interoperability. The following figure illustrates a basic Service-Oriented Architecture.

Service-Oriented Architecture 

 

The preceding figure shows a service consumer sending a service request message to a service provider. The service provider returns a response message to the service consumer. The request and response connections are defined in some way that is understandable to both the service consumer and service provider. The service consumer will not have a direct interaction with the service provider, instead the messages are formed out of the value of the input parameters, return parameters and the data are formatted by the SOAP. The service response will be in XML, which is understandable to both the service consumer and service provider.

2. What a WCF Service is

Windows Communication Foundation (WCF) was introduced in .NET 3.0. This is a great network distributed system developed by Microsoft for communication between applications. WCF is meant for designing and deploying distributed applications under a Service-Oriented Architecture (SOA) implementation. From MSDN: Windows Communication Foundation is a part of the .NET Framework that provides a unified programming model for rapidly building service-oriented applications that communicate across the web and the enterprise. WCF is a combined feature of Web Service, Remoting, MSMQ and COM+. The following figure illustrates WCF  architecture. 

WCF Service

3. Why use WCF Service?

WCF is a replacement for all earlier web service technologies from Microsoft. It also does much more than what is traditionally considered as web services. The major limitation with web services is that the communication can happen over HTTP only. In WCF you can access using HTTP, TCP, Named pipes, MSMQ, P2P and so on. A second limitation with web services is that it provides simplex communication and there is no way to have half duplex or full duplex communication using web services and a third limitation with web services is that it can be hosted in IIS. In WCF, the service can be hosted in IIS, Windows Activation Service, self-hosted, or a Windows Service.

We will also learn some great features of WCF Service later in the article.

4. Components of WCF Services

There are the following three main components of a WCF application.

  1. WCF Service class: A WCF Service class implements some service as a set of methods.

  2. WCF Service host: WCF supports four types of hosting, IIS, Windows Process Activation Services (WAS), self-hosting and Windows Services.

  3. WCF Service endpoints: All communication with a Windows Communication Foundation (WCF) service occurs through the endpoints of the service. Usually the name of the Interface will be specified in the contract, so the client application will be aware of the operations that are exposed to the client.

    Each endpoint contains:

    • Address: An address that indicates where to find the service.
    • Binding: A binding that specifies how a client can communicate with the service.
    • Contract: A Contract that specifies what can the service do for us

5. Advantage of WCF over Web Service

The following are the advantages of a WCF over a Web Service.

  1. WCF supports more of the WS-* standards than Web Services.
  2. Web services provide simplex communication. In WCF we can also use half duplex or full duplex communication.
  3. WCF supports multiple bindings, such as HTTP, WSHTTP, TCP and MSMQ. ASP.NET Web Services has only HTTP.
  4. It can be hosted on IIS, WAS, self hosted or Windows Services
  5. WCF Services have instance management.
  6. WCF Services can control concurrency.

6. WCF Service File Structure

Visual Studio includes WCF Service by default to use. You need to open Visual Studio and select WCF Service. It will look such as in the following:

Service File Structure
You will get the following 3 files in the solution.

  1. IService.cs
  2. Service.svc

1. The IService1.cs file contains the two sections:

  1. OperationContract
  2. DataContract

The OperationContract section is used to add service operations and DataContract is used to add types to service operations.

2. Service.svc.cs File

In this file we define the definition of the function.

7. WCF Service Important Features

WCF includes the following set of features.

  1. Interoperability

    WCF is interoperable with other services when compared to .Net Remoting where the client and service must be .Net.
     
  2. Multiple Message Patterns

    The Message Exchange Pattern describes how the client and server should exchange messages. There are three types of message exchange patterns.

     

    • Request-Response
    • One Way
    • Duplex
       
  3. Service Orientation

    Service-Oriented Architecture (SOA) is the reliance on Web services to send and receive data.
     
  4. Security

    Messages can be encrypted to protect privacy and you can require users to authenticate themselves before being allowed to receive messages. Security can be implemented using well-known standards such as SSL or WS-SecureConversation.
     
  5. Durable Messages

    A durable message is one that is never lost due to a disruption in the communication. You can also create a durable message using the Windows Workflow Foundation (WF).
     
  6. Transactions

    WCF also supports transactions using one of the following three transaction models:

    • WS-AtomicTtransactions
    • APIs in the System.Transactions namespace
    • Microsoft Distributed Transaction Coordinator
     
  7. AJAX and REST Support

    WCF can be configured to process plain XML data that is not wrapped in a SOAP envelope. WCF can also be extended to support specific XML formats, such as ATOM (a popular RSS standard) and even non-XML formats, such as JavaScript Object Notation (JSON).

8. Creating a Web Service

Now we create a service to insert data into a database using a WCF Service, we must do the following 3 things:

  1. Create Database Table
  2. Create WCF Service
  3. Create web application

In the first step we will create a table in SQL Server, then we create a simple function to insert data into the database using a WCF Service. In a web application, add a reference of the service and the data to be inserted will be sent to the web services function that will be inserted into the database table. Let's have a look at a practical example. The example application is developed in Visual Studio 2010 and SQL Server 2008.

Step 1: Creating Database Table

  1. Database name:  Registration
  2. Database table name: RegistrationTable

RegistrationTable Table

  1.  CREATE TABLE [dbo].[RegistrationTable]  
  2. (  
  3.       [UserName] [varchar](100) NOT NULL,  
  4.       [Password] [varchar](20) NOT NULL,  
  5.       [Country] [varchar](100) NOT NULL,  
  6.       [Email] [varchar](200) NOT NULL  

Step 2: Creating WCF Service

Now you need to create a WCF Service:

  • Go to Visual Studio 2010
  • New-> Select a project

img1.jpg

Now click on the project and select WCF Service Application and provide a name for the service:

img2.jpg

Now click on the Ok Button. Then you will get the following 3 files in the solution.

  1. IService.cs
  2. Service.svc
  3. Service.svc.cs

The following image shows the files:

img3.jpg

Iservice1.cs File

Now we create a function in the OperationContract section of the Iservice1.cs file:

  1. public interface IService1  
  2. {  
  3.   [OperationContract]  
  4.   string InsertUserDetails(UserDetails userInfo);  

Now add types to service operations in the DataContract section:

  1. public class UserDetails  
  2. {
      string username = string.Empty;  
  3.   string password = string.Empty;  
  4.   string country = string.Empty;  
  5.   string email = string.Empty;  
  6.   [DataMember]  
  7.   public string UserName  
  8.   {  
  9.      get { return username; }  
  10.      set { username = value; }  
  11.   }  
  12.   [DataMember]  
  13.   public string Password  
  14.   {  
  15.      get { return password; }  
  16.      set { password = value; }  
  17.  }  
  18. [DataMember]  
  19. public string Country  
  20. {   
  21.    get { return country; }  
  22.    set { country = value; }  
  23. }  
  24. [DataMember]  
  25. public string Email  
  26. {  
  27.   
  28.   get { return email; }  
  29.   set { email = value; }  
  30. }  

 Service.svc.cs File

In this file we define the definition of the function InsertUserDetails(UserDetails userInfo).

And replace the code with the following:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Runtime.Serialization;  
  5. using System.ServiceModel;  
  6. using System.ServiceModel.Web;  
  7. using System.Text;  
  8. using System.Data.SqlClient;  
  9. using System.Data;  
  10.    
  11. namespace WCFServiceForInsert  
  12. {  
  13.     // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.  
  14.     public class Service1 : IService1  
  15.     {  
  16.         public string InsertUserDetails(UserDetails userInfo)  
  17.         {  
  18.             string Message;  
  19.             SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Rajesh;User ID=sa;Password=wintellect");  
  20.             con.Open();  
  21.             SqlCommand cmd = new SqlCommand("insert into RegistrationTable(UserName,Password,Country,Email) values(@UserName,@Password,@Country,@Email)", con);  
  22.             cmd.Parameters.AddWithValue("@UserName", userInfo.UserName);  
  23.             cmd.Parameters.AddWithValue("@Password", userInfo.Password);  
  24.             cmd.Parameters.AddWithValue("@Country", userInfo.Country);  
  25.             cmd.Parameters.AddWithValue("@Email", userInfo.Email);  
  26.             int result = cmd.ExecuteNonQuery();  
  27.             if (result == 1)  
  28.             {  
  29.                 Message = userInfo.UserName + " Details inserted successfully";  
  30.             }  
  31.             else  
  32.             {  
  33.                 Message = userInfo.UserName + " Details not inserted successfully";  
  34.             }  
  35.             con.Close();  
  36.             return Message;  
  37.         }  
  38.     }  

 

Testing the Service

Press F5 to run the service. A WCF Test Client form will be displayed and it will load the service.

img4.jpg

Now double-click the InserUserDetails() method under IService1. The InserUserDetails tab will be displayed.

img5.jpg

The service was added successfully.

Now open the service in the browser.

Now right-click on the service1.vcs-> open in the browser:

img16.jpg

Now copy the URL.

http://localhost:2268/Service1.svc

Step 3: Create web application (Accessing the Service)

Now, you need to create a web site.

  • Go to Visual Studio 2010
  • New-> Select a website application
  • Click OK

image1.gif
 

Now add a new page to the website:

  • Go to the Solution Explorer
  • Right-click on the Project name
  • Select add new item
  • Add new web page and provide it a name
  • Click OK
image2.gif

Add the service reference in web application

Now add the service reference.

img7.jpg
 

When we click on the add the service reference the following window will be opened:

ing9.jpg
 

Now paste the preceding URL in the address and click on the go Button.

img8.jpg

Click on the OK Button. Now the reference has been added to the solution.

img10.jpg
 

Now create a new website and drag and drop controls onto the aspx page. The aspx code is the following:

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Registration.aspx.cs" Inherits="Registration" %>  
  2.    
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4.    
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title></title>  
  8. </head>  
  9. <body>  
  10.     <form id="form1" runat="server">  
  11.     <div>  
  12.       <table width="84%" cellpadding="0" cellspacing="0" style="border: solid 1px #3366CC;">  
  13.             <tr>  
  14.                 <td colspan="4" style="height: 30px; background-color: #f5712b;">  
  15.                     <span class="TextTitle" style="color: #FFFFFF;">Registration Form</span>  
  16.                 </td>  
  17.             </tr>  
  18.             <tr>  
  19.                 <td height="20px" colspan="0">  
  20.                 </td>  
  21.             </tr>  
  22.             <tr>  
  23.                 <td width="50%" valign="top">  
  24.                     <table id="TableLogin" class="HomePageControlBGLightGray" cellpadding="4" cellspacing="4"  
  25.                         runat="server" width="100%">  
  26.                         <tr>  
  27.                             <td colspan="3" align="center">  
  28.                                 <asp:Label ID="LabelMessage" ForeColor="Red" runat="server" EnableViewState="False"  
  29.                                     Visible="False"></asp:Label><br>  
  30.                             </td>  
  31.                         </tr>  
  32.                         <tr style="font-weight: normal; color: #000000">  
  33.                             <td align="right">  
  34.                                 <span>UserName:</span>;  
  35.                             </td>  
  36.                             <td align="left" style="padding-left: 10px;">  
  37.                                 <asp:TextBox ID="TextBoxUserName" runat="server" CssClass="textbox" Width="262px"  
  38.                                     MaxLength="50" Height="34px"></asp:TextBox>  
  39.                             </td>  
  40.                         </tr>  
  41.                         <tr>  
  42.                             <td align="right">  
  43.                                 <span class="TextTitle">Password:</span>  
  44.                             </td>  
  45.                             <td align="left" style="padding-left: 10px;">  
  46.                                 <asp:TextBox ID="TextBoxPassword" runat="server" CssClass="textbox" Width="261px"  
  47.                                     MaxLength="50" TextMode="Password" Height="34px"></asp:TextBox>  
  48.                                 <br />  
  49.                             </td>  
  50.                         </tr>  
  51.                         <tr>  
  52.                             <td align="right">  
  53.                                 <span class="TextTitle">Country:</span>  
  54.                             </td>  
  55.                             <td align="left" style="padding-left: 10px;">  
  56.                                 <asp:TextBox ID="TextBoxCountry" runat="server" CssClass="textbox" Width="258px"  
  57.                                     MaxLength="50" Height="34px"></asp:TextBox>  
  58.                                 <br />  
  59.                             </td>  
  60.                         </tr>  
  61.                         <tr>  
  62.                             <td align="right">  
  63.                                 <span class="TextTitle">Email:</span>  
  64.                             </td>  
  65.                             <td align="left" style="padding-left: 10px;">  
  66.                                 <asp:TextBox ID="TextBoxEmail" runat="server" CssClass="textbox" Width="258px"   
  67.                                     MaxLength="50" Height="34px"></asp:TextBox>  
  68.                                 <br />  
  69.                             </td>  
  70.                         </tr>  
  71.                         <tr>  
  72.                             <td align="right">  
  73.                             </td>  
  74.                             <td align="left" style="padding-left: 10px;">  
  75.                                 <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" Width="87px" />  
  76.                                 <br />  
  77.                             </td>  
  78.                         </tr>  
  79.                     </table>  
  80.                 </td>  
  81.             </tr>  
  82.         </table>  
  83.     </div>  
  84.     </form>  
  85. </body>  
  86. </html> 

The form looks like:

img11.jpg
 

Double-click the button and add the following code to the Click event handler:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using ServiceReference1;  
  8.    
  9. public partial class Registration : System.Web.UI.Page  
  10. {  
  11.     ServiceReference1.Service1Client objServiceClientobjService = new ServiceReference1.Service1Client();  
  12.     protected void Page_Load(object sender, EventArgs e)  
  13.     {  
  14.           
  15.     }  
  16.     protected void Button1_Click(object sender, EventArgs e)  
  17.     {  
  18.         UserDetails userInfo = new UserDetails();  
  19.         userInfo.UserName = TextBoxUserName.Text;  
  20.         userInfo.Password = TextBoxPassword.Text;  
  21.         userInfo.Country = TextBoxCountry.Text;  
  22.         userInfo.Email = TextBoxEmail.Text;  
  23.         string result = objServiceClientobjService.InsertUserDetails(userInfo);  
  24.         LabelMessage.Text = result;  
  25.     }  

Now run the application.

Press CTRL+F5 to run the project and enter the UserName, Password, country and Email and click on the button.

img12.jpg

Data has been inserted into the SQL Server database table and check it.

Clipboard14.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all