How To Create A WCF Service In C#

In this tutorial, learn how to create a WCF service in C#.

What is WCF

 
WCF is Windows Communication Foundation and we can say it the elder brother of Web Service.
 
We will create two projects:
  1. Web Application.
  2. WCF Service Library.
Note: Within one solution we can create n number of projects and this is the advantage of Solution.
  1. Create Web Application.

    File, New, Project, then ASP.NET Empty Web Application.

    Asp.Net Empty Web Application

    Give the name WCF_TestingWebApplication. 

  2. Create another project of WCF Service Library under same solution.

    MyWCFServiceLibrary

    Give name MyWCFServiceLibrary

  3. After creating Wcf ServiceLibrary project, You can see default two service base file created:

    1. IService.cs
    2. Service1.cs

    Delete these two default created service files.
  4. Now, add new service item. You can add new service by the following,

    Add new item

  5. Select WCF Service item and give name FriendService,

    WCF Service

  6. After creating FriendService you can see two files get created,

    1. IFriendService.cs: Interface to declare your Service contracts and Data Contracts.
    2. FriendService.cs: Is a normal class inherited by IFriendService where you can define all the methods and other processes.

  7. You can see both files having one DoWork() kind of thing. You can comment out or remove or let it be. This is by default.

  8. Namespace required,

    Namespace Functionalities
    Using System.Data To get ado.net data handling classes.
    Using System.Data.SqlClient To connect to Microsoft Sql server.
    Using Systen.Configuration To fetch configuration settings and connectionstrings from app.config.
     
    Firstly, give reference of system.configuration.dll.
     
  9. Now we will define our function name GetFriendNameBySearchKeywords(). Firstly, we have given signature of this function in IFriendService.cs then Implemented in FriendService.cs.

    Double click on IFriendService.cs file.

    Write the following codes just above DoWork().
    1. [ServiceContract]  
    2. public interface IFriendService  
    3. {  
    4.     [OperationContract]  
    5.     Friend GetFriendNameBySearchKeywords();  
    6.     [OperationContract]  
    7.     void DoWork();  
    8. }  
    In gray color code we define method GetFreindNameBySearchKeywords as per Friend class declaration. 
    1. [DataContract]  
    2. public class Friend  
    3. {  
    4.     public Friend()  
    5.     {  
    6.         this.FriendsTable = new DataTable("FriendsTable");  
    7.     }  
    8.     [DataMember]  
    9.     public DataTable FriendsTable  
    10.     {  
    11.         get;  
    12.         set;  
    13.     }  
    14. }  
    In orange color code we defined implementation of Friend class.

    Friend class

  10. By default WCF service library application give you APP.CONFIG file.

    Insert Connection String inside CONFIGURATION tag.
    1. <connectionStrings>  
    2.    <add name="MemberCDACConnectionString" connectionString="Data Source=SAIBABA-PC\SAIBABA;Initial Catalog=MemberCDAC;Integrated Security=True" providerName="System.Data.SqlClient"/>  
    3.   
    4. </connectionStrings>  
  11. Table structure of tblFriends,
    1. CREATE TABLE [dbo].[tblFriends](  
    2.     [FriendID] [int] IDENTITY(1,1)NOT NULL,  
    3.     [FriendName] [varchar](50)NULL,  
    4.     [FriendImage] [varchar](500)NULL,  
    5.     [Place] [varchar](500)NULL,  
    6.     [Mobile] [varchar](20)NULL  
    7. )ON [PRIMARY]  
    8.   
    9. GO  
    The sample records of tblFriends,

    tblFriends

  12. Now, we implement GetFriendNameBySearchKeywords() method in FriendService.cs.

    FriendService.cs, this file inheriting interface file IFreindService.

    Here we are implementing our method GetFreindNameBySearchKeywords.
    1. public class FriendService: IFriendService  
    2. {  
    3.     //To fetch connection string from APP.CONFIG file.  
    4.     string ConStr = ConfigurationManager.ConnectionStrings["MemberCDACConnectionString"].ConnectionString;  
    5.     public Friend GetFriendNameBySearchKeywords(string FriendSearchKeyword)  
    6.     {  
    7.         //Set connection which feteched from app.config.  
    8.         SqlConnection con = new SqlConnection(ConStr);  
    9.         //SELECT query to fetch data from ProductsTable  
    10.         SqlDataAdapter da = new SqlDataAdapter("Select FriendName From tblFriends Where ProductName Like '%" + FriendSearchKeyword + "%'", ConStr);  
    11.         //DataSet is virutual database or data container.  
    12.         Friend _friends = new Friend();  
    13.         //Fill data inside ds(DataSet) with TableNamed ProductsTable  
    14.         da.Fill(_friends.FriendsTable);  
    15.         return _friends;  
    16.     }  
    17.     public void DoWork()  
    18.     {}  
    19. }  
    WCF work

    We had completed WCF work, check and build your WCF Service Library project.

    If you have any error solve or cannot you can comment I will answer as early as possible.

Implementing WCF Service in WCF_TestingWebApplication


Switch to WCF_TestingWebApplication and add new WebForm1.aspx
  1. For adding new WebForm1.aspx.

    Right click on project Add - New Item, then write the name WebForm1,

    New WebForm1

  2. Right click on WCF project and select Add Service Reference,

    Add Service Reference

  3. Now switch back to WebForm1.ASPX page, drag and drop HTML TABLE from TOOL BOX.

    Note:
    HTML toolbox of controls located at bottom of toolbox.

    Add the following controls as per charts.

    CONTROL TYPE CONTROL ID DESCRIPTION
    TextBox txtFriendSearchKeyword To enter member name.
    Button btnSubmit Button to submit data.
    GridView gvMember Gridview to display data.
    Set following settings from properties:
    AutoGenerateSelectButton="True" Width="100%"
     
    Drag and Drop above mentioned controls from TOOLBOX after HTML table. 
     
  4. Click on GridView Smart Tag, click AutoFormat and select BrownSugar.

    AutoFormat

  5. WebForm1.aspx file code
    1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WCF_TestingWebApplication.WebForm1" %>  
    2.     <!DOCTYPE html>  
    3.     <html xmlns="http://www.w3.org/1999/xhtml">  
    4.   
    5.     <head runat="server">  
    6.         <title></title>  
    7.         <style type="text/css">  
    8. .auto-style1 {  
    9.     text-align: center;  
    10. }  
    11.   
    12. .auto-style2 {  
    13.     width: 170px;  
    14. }  
    15.   
    16. .auto-style3 {  
    17.     width: 104px;  
    18. }  
    19.         </style>  
    20.     </head>  
    21.   
    22.     <body>  
    23.         <form id="form1" runat="server">  
    24.             <div>  
    25.                 <table style="width:100%;">  
    26.                     <tr>  
    27.                         <td class="auto-style3">Search Friend</td>  
    28.                         <td class="auto-style2">  
    29.                             <asp:TextBox ID="txtFriendSearchKeyword" runat="server" Height="22px"></asp:TextBox>  
    30.                         </td>  
    31.                         <td> </td>  
    32.                     </tr>  
    33.                     <tr>  
    34.                         <td class="auto-style1" colspan="2">  
    35.                             <asp:Button ID="btnFriend" runat="server" Text="Submit" OnClick="btnFriend_Click" />  
    36.                         </td>  
    37.                         <td> </td>  
    38.                     </tr>  
    39.                     <tr>  
    40.                         <td class="auto-style3"> </td>  
    41.                         <td class="auto-style2"> </td>  
    42.                         <td> </td>  
    43.                     </tr>  
    44.                     <tr>  
    45.                         <td colspan="3">  
    46.                             <asp:GridView ID="GridView1" runat="server" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2" Width="100%">  
    47.                                 <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />  
    48.                                 <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />  
    49.                                 <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />  
    50.                                 <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />  
    51.                                 <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />  
    52.                                 <SortedAscendingCellStyle BackColor="#FFF1D4" />  
    53.                                 <SortedAscendingHeaderStyle BackColor="#B95C30" />  
    54.                                 <SortedDescendingCellStyle BackColor="#F1E5CE" />  
    55.                                 <SortedDescendingHeaderStyle BackColor="#93451F" /> </asp:GridView>  
    56.                         </td>  
    57.                     </tr>  
    58.                 </table>  
    59.             </div>  
    60.         </form>  
    61.     </body>  
    62.   
    63. </html>  
  6. WebForm1.aspx.cs file code:
    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 WCF_TestingWebApplication.WCFServiceReference;  
    8. namespace WCF_TestingWebApplication  
    9. {  
    10.     public partial class WebForm1: System.Web.UI.Page  
    11.     {  
    12.         FriendServiceClient _friendclient = new FriendServiceClient();  
    13.         protected void Page_Load(object sender, EventArgs e)  
    14.         {  
    15.             if (!IsPostBack)  
    16.             {  
    17.                 GridView1.DataSource = _friendclient.GetFriendNameBySearchKeywords("NULL")  
    18.                     .FriendsTable;  
    19.                 GridView1.DataBind();  
    20.             }  
    21.         }  
    22.         protected void btnFriend_Click(object sender, EventArgs e)  
    23.         {  
    24.             GridView1.DataSource = _friendclient.GetFriendNameBySearchKeywords(txtFriendSearchKeyword.Text)  
    25.                 .FriendsTable;  
    26.             GridView1.DataBind();  
    27.         }  
    28.     }  
    29. }  
  7. When you press F5 your WebForm1 view will be like the following,

    WebForm1

  8. Now, we can search friend(s).

    search
Thank you, our task completed.