Creating WCF Service, IIS Hosting and Consuming

How to create WCF service with IIS hosting?

 
In Visual Studio go to "File" -> "New" -> "Project..." then select "C#" -> "WCF" -> "WCF Service Library".
 
Now set the name of the project as "ProductServiceLibrary" then click "OK".
 
WCF1.jpg 
 
In the next step change the name of the files:
 
From "IService.cs" to "IProductService.cs"
 
WCF2.jpg 
 
Now in "IProductService.cs" write the following code to implement it with the Service Class i.e. "ProductService.cs":
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Runtime.Serialization;  
  5. using System.ServiceModel;  
  6. using System.Text;  
  7.   
  8. namespace ProductServiceLibrary  
  9. {  
  10.     [ServiceContract]  
  11.     public interface IProductService  
  12.     {  
  13.         [OperationContract]  
  14.         List<Product> GetAllProduct();  
  15.         [OperationContract]  
  16.         Product GetProductByID(string ProductId);  
  17.     }  
  18.     [DataContract]  
  19.     public class Product  
  20.     {  
  21.         [DataMember]  
  22.         public int ProductID  
  23.         {  
  24.             get;  
  25.             set;  
  26.         }  
  27.         [DataMember]  
  28.         public string ProductName  
  29.         {  
  30.             get;  
  31.             set;  
  32.         }  
  33.         [DataMember]  
  34.         public string QuantityPerUnit  
  35.         {  
  36.             get;  
  37.             set;  
  38.         }  
  39.         [DataMember]  
  40.         public decimal UnitPrice  
  41.         {  
  42.             get;  
  43.             set;  
  44.         }  
  45.     }  
  46. }  
After creating the interface we must implement it and must write code for the service.
 
WCF3.jpg 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Runtime.Serialization;  
  5. using System.ServiceModel;  
  6. using System.Text;  
  7.   
  8. namespace ProductServiceLibrary  
  9. {  
  10.     public class ProductService : IProductService  
  11.     {  
  12.         public List<Product> GetAllProduct()  
  13.         {  
  14.             throw new NotImplementedException();  
  15.         }  
  16.         public Product GetProductByID(string ProductId)  
  17.         {  
  18.             throw new NotImplementedException();  
  19.         }  
  20.     }  
  21. }  
Now we have implemented the IProductService interface with the Service.
 
We must write the code to get all the products from the database and one product detail by product ID.
 
But before this we will set the database connection string in the Project property.
 
WCF4.jpg
 
WCF5.jpg
 
WCF6.jpg
 
After clicking "Ok" open the "App.config" file and we will see the database connection string.
 
WCF7.jpg 
 
After setting the connection string in the project properties, now we will write code to access the data from the database in the methods we implemented.
 
So here is the code:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Runtime.Serialization;  
  5. using System.ServiceModel;  
  6. using System.Text;  
  7. using System.Data.SqlClient;  
  8.   
  9. namespace ProductServiceLibrary  
  10. {  
  11.     public class ProductService : IProductService  
  12.     {  
  13.         public List<Product> GetAllProduct()  
  14.         {  
  15.             List<Product> Products = new List<Product>();  
  16.             using (SqlConnection con = new SqlConnection(Properties.Settings.Default.ConStr))  
  17.             {  
  18.                 using (SqlCommand cmd = new SqlCommand("Select ProductId,ProductName,QuantityPerUnit,UnitPrice from Products", con))  
  19.                 {  
  20.                     con.Open();  
  21.                     SqlDataReader dr = cmd.ExecuteReader();  
  22.                     while (dr.Read())  
  23.                     {  
  24.                         Product product = new Product();  
  25.                         product.ProductID = dr.GetInt32(0);  
  26.                         product.ProductName = dr.GetString(1);  
  27.                         product.QuantityPerUnit = dr.GetString(2);  
  28.                         product.UnitPrice = dr.GetDecimal(3);  
  29.                         Products.Add(product);  
  30.                     }  
  31.                 }  
  32.             }  
  33.             return Products;  
  34.         }  
  35.         public Product GetProductByID(string ProductId)  
  36.         {  
  37.             Product product = new Product();  
  38.             using (SqlConnection con = new SqlConnection(Properties.Settings.Default.ConStr))  
  39.             {  
  40.                 using (SqlCommand cmd = new SqlCommand("Select ProductId,ProductName,QuantityPerUnit,UnitPrice from Products", con))  
  41.                 {  
  42.                     con.Open();  
  43.                     SqlDataReader dr = cmd.ExecuteReader();  
  44.                     while (dr.Read())  
  45.                     {  
  46.                         product.ProductID = dr.GetInt32(0);  
  47.                         product.ProductName = dr.GetString(1);  
  48.                         product.QuantityPerUnit = dr.GetString(2);  
  49.                         product.UnitPrice = dr.GetDecimal(3);  
  50.                     }  
  51.                 }  
  52.             }  
  53.             return product;  
  54.         }  
  55.     }  
  56. }  
Now our first WCF has been created. It is time to test our WCF Service Application; just press the F5 button.
 
The WCF Test Client will run.
 
WCF8.jpg 
 
Select the method "GetAllProduct" and click "Invoke".
 
WCF9.jpg 
 
The preceding screen is the indication that the f WCF Service was created successfully.
 
Now our second step is just to host this WCF Application using IIS.
 
Click on the solution then right-click then select "Add" -> "New Website".
 
WCF10.jpg
 
WCF11.jpg 
 
After clicking "OK" the Website application will be added to the solution. Then after it has been added it, two extra files will get generated in the project, i.e. "IService.cs" & "Service.cs". We have, however, already created these file in the WCF Library, so now we will delete them and add the reference to "ProductServiceLibrary.dll".
 
WCF12.jpg 
 
Add the reference to the ProductServiceLibrary.dll in this project.
 
WCF13.jpg
 
WCF14.jpg
 
WCF15.jpg 
 
Now open the Service.svc file.
 
Delete the selected code (in the following image) and the reason is very simple, because in our ProductServiceLibrary.dll we created the ProductService.cs and in the current project we have deleted the Service.cs file from the App_code folder.
 
And replace the current line with this line of code:
  1. <%@ ServiceHost Language="C#" Debug="true" Service="ProductServiceLibrary.ProductService" %>
WCF16.jpg 
 
We have altered the .svc file and it is time to add the End Points to Web.Config, as in:
  1. <?xml version="1.0"?>  
  2. <configuration>  
  3.   <system.web>  
  4.     <compilation debug="false" targetFramework="4.0" />  
  5.   </system.web>  
  6.   <system.serviceModel>  
  7.     <services>  
  8.       <service name="ProductServiceLibrary.ProductService">  
  9.         <endpoint address="" binding="wsHttpBinding" contract="ProductServiceLibrary.IProductService">  
  10.           <identity>  
  11.             <dns value="localhost" />  
  12.           </identity>  
  13.         </endpoint>  
  14.         <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />  
  15.       </service>  
  16.     </services>  
  17.     <behaviors>  
  18.       <serviceBehaviors>  
  19.         <behavior>  
  20.           <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->  
  21.           <serviceMetadata httpGetEnabled="true"/>  
  22.           <!-- 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 -->  
  23.           <serviceDebug includeExceptionDetailInFaults="false"/>  
  24.         </behavior>  
  25.       </serviceBehaviors>  
  26.     </behaviors>  
  27.     <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />  
  28.   </system.serviceModel>  
  29.   <system.webServer>  
  30.     <modules runAllManagedModulesForAllRequests="true"/>  
  31.   </system.webServer>  
  32. </configuration>  
After adding the End Points in the web.config file, our hosting task is finished. Now it is time to test the Hosting Application.
 
For that please use the following steps in the following image:
 
WCF17.jpg
 
WCF18.jpg
 
WCF19.jpg 
 
The preceding color full page is the indication of successfully hosting WCF in IIS.
 
Now our next step is to consume this WCF IIS hosted service in a client application and this is a very easy task.
 

Consume WCF IIS hosted service

 
So let's proceed to our last step.
 
WCF20.jpg
 
WCF21.jpg
 
WCF22.jpg
 
WCF23.jpg
 
WCF24.jpg
 
WCF25.jpg
 
WCF26.jpg 
 
On the Default.aspx.cs page write the 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 ProductWebClient.ProductServiceClient;  
  8. namespace ProductWebClient  
  9. {  
  10.     public partial class Default : System.Web.UI.Page  
  11.     {  
  12.         protected void Page_Load(object sender, EventArgs e)  
  13.         {  
  14.         }  
  15.         protected void BtnAdd_Click(object sender, EventArgs e)  
  16.         {  
  17.             ProductServiceClient.ProductServiceClient proxy = new ProductServiceClient.ProductServiceClient();  
  18.             ProductGridView.DataSource= proxy.GetAllProduct();  
  19.             ProductGridView.DataBind();  
  20.         }  
  21.     }  
  22. }  
Now run the application, except before doing that do one more last task.
 
WCF27.jpg 
 
WCF28.jpg 
 
Set the ProductWebClient as "Set as StartUp Project" and press F5 and here is the result.
 
ENJOY!


Similar Articles