Praveen Katiyar' Blog

Learning along the way . . . .

Creating Simple WCF Service with IIS Hosting

In this post I am going to explain how to create a simple WCF Service, with IIS Hosting and consume it, there will be two parts of the project.

  • A WCF Service (MyMathService.svc): will be hosted by IIS.
  • Client Application (MyMathClient.exe): Client Application which will use this service.

let’s start with creating the WCF Service.

Creating the WCF Service

Start the Visual Studio 2010 in administrator Mode (Run as Administrator), and click File->New->Web Site. Select the project template ‘WCF Service’ and Location as http. This will directly host the service in IIS and click OK. select the template “WCF Service”. 

image

Now let’s analyse the project created by wizard for us, and do little house keeping, before we write any code.

  • IService.cs (the interface definition of the service)
  • Service.cs (the implementation of the service).
  • web.config (Service configuration file).
  • Service.svc

Assumption

We are going to create a Service as per following assumptions.

  • Service will be named as "MyMathService" (MyMathService.svc)
  • Interface will named as IMyMathService (IMyMathService.cs)
  • Service will be implemented as MyMathService (MyMathService.cs)
  • Service will implement Http endpoint at Port 8001.
  • Service will also expose IMetadataExchange endpoint.  IMetadataExchange interface Exposes methods used to return metadata about a service.

Little house keeping. (just to keep things organized)

  • Rename IService.cs as IMyMathService.cs.
  • Rename Service.cs as MyMathService.cs.
  • Rename Service.svc as MyMathService.svc, and change its content as

Previous Content

<%@ ServiceHost Language="C#" Debug="true" Service="Service" CodeBehind="~/App_Code/Service.cs" %>

New Content

<%@ ServiceHost Language="C#" Debug="true" Service="MyMathService" CodeBehind="~/App_Code/MyMathService.cs" %>

Defining Configuration File

Changing web.config file.

Below is the listing of the configuration file, generated by visual studio wizard, as we know, that Services are defined in <System.servicemodel> section. Below is the listing of the configuration file, generated by visual studio wizard.  let’s define a service and endpoint, see the highlighted part.

<?xml version="1.0"?>
<configuration>

                 <configSections>
        . . . . . . . . .
         . . . . . . . . .
      </configSections>

    <system.web>
     . . . . . . . . .
     . . . . . . . . .
    </system.web>

  <system.serviceModel> 
<services>
     <service name="MyMathService" behaviorConfiguration="svcBehavior">  
        
<endpoint address=http://localhost:8001/MyMathService/MyMathService.svc" binding="wsHttpBinding" contract="IMyMathService">

          <identity> <dns value="localhost"/> </identity>
</endpoint>

      <endpoint address ="MEX" binding ="mexHttpBinding" contract="IMetadataExchange" /> 
   </service> 
</services>

   <behaviors>
      <serviceBehaviors>
        <behavior  name="svcBehavior">
          <!– 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="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
   
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel> 

<system.codedom>
         . . . . . . . . .
         . . . . . . . . .
      </system.codedom>

   <system.webServer>
         . . . . . . . . .
         . . . . . . . . .
   </system.webServer>    

   <runtime>
         . . . . . . . . .
         . . . . . . . . .
   </runtime>

 
</configuration>

Explanation

See the highlighted text, as you can see service defines two endpoints, one is first end point defines an address(http://localhost:8001/MyMathService), binding(HTTP) and contract (IMyMathService), the other is MEX endpoint, MEX endpoint are defined to import Metadata (to be used by client applications) from a Service using utility SVCUtil.exe

<endpoint address ="http://localhost:8001/MyMathService&quot; binding ="basicHttpBinding" contract="IMyMathService" />

<endpoint address ="MEX" binding ="mexHttpBinding" contract="IMetadataExchange" />

In the serviceBehaviors, a behavior named "svcBehavior" defines following attributes about the service.

<serviceMetadata httpGetEnabled="true"/>

metadata information about the service can disclosed through a get request (if this is false, SVCUtil.exe would not be able to obtain metadata information about the service).

<serviceDebug includeExceptionDetailsInFaults="true"/>

can be set true, to receive exception details in faults for debugging purposes, should be set to false, before deployment, to avoid disclosing exception information.

Defining Service Interface (IMyMathService.cs)

using System;
using System.ServiceModel;
using System.Text;

[ServiceContract]
public interface IMyMathService
{
    [OperationContract]
    double Add(double dblNum1, double dblNum2);

    [OperationContract]
    double Subtract(double dblNum1, double dblNum2);

    [OperationContract]
    double Multiply(double dblNum1, double dblNum2);

    [OperationContract]
    double Divide(double dblNum1, double dblNum2);
}

explanation

as one can see, there is one service contract (IMyMathService), and 4 operation contract to perform 4 basic math operations.

Implementing Service (MyMathService.cs)

using System;
using System.ServiceModel;
using System.Text;

public class MyMathService : IMyMathService
{
    public double Add(double dblNum1, double dblNum2)
    {
        return (dblNum1 + dblNum2);
    }

    public double Subtract(double dblNum1, double dblNum2)
    {
        return (dblNum1 – dblNum2);
    }

    public double Multiply(double dblNum1, double dblNum2)
    {
        return (dblNum1 * dblNum2);
    }

    public double Divide(double dblNum1, double dblNum2)
    {
        return ((dblNum2 == 0) ? 0 : (dblNum1 / dblNum2));
    }
}

explanation

here simply those 4 methods has been implemented.

Creating Client for the Service

Add a new project to the workspace, say a Console based application, name it MyMathClient, for instance.

image

newly created project will be added to the work space.

Generating proxy and config file.

right click on the newly created (client) project, and click on "Add Service Reference", as shown below.

image

a dialog box will be displayed as shown below. in the address bar type the address of the service,

image

Click OK,

  • A app.config (client side configuration) will be added to the project.
  • a Service reference named MyMathServiceProxy will be added in Service References node of the client project.

Calling the Service

Now write the code to use the proxy and call the service, here is the listing of the Program.cs.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyMathClient
{
    class Program
    {
        static void Main(string[] args)
        {
            double dblX = 2000.0 ;
            double dblY = 100.0 ;
            double dblResult = 0 ;
            MyMathServiceProxy.MyMathServiceClient mathClient = new MyMathServiceProxy.MyMathServiceClient();

            dblResult = mathClient.Add (dblX, dblY );
            Console.WriteLine("Calling Add >>  X : {0:F2}  Y : {1:F2}  Result : {2:F2}", dblX, dblY, dblResult);
           
            dblResult = mathClient.Subtract (dblX, dblY);
            Console.WriteLine("Calling Sub >>  X : {0:F2}  Y : {1:F2}  Result : {2:F2}", dblX, dblY, dblResult);

            dblResult = mathClient.Multiply(dblX, dblY);
            Console.WriteLine("Calling Mul >>  X : {0:F2}  Y : {1:F2}  Result : {2:F2}", dblX, dblY, dblResult);

            dblResult = mathClient.Divide(dblX, dblY);
            Console.WriteLine("Calling Sub >>  X : {0:F2}  Y : {1:F2}  Result : {2:F2}", dblX, dblY, dblResult);
        }
    }
}

and here is the output.

image

Creating a web Client for the Service

Add a new web site to the workspace, name it MyWebMathClient, for instance as shown below.

image

Add Service reference of the Math Service to the newly created website, as shown below

image

Adding this Service Reference, made a change in the web.config file of the Client Web site, if you open the web.config, you will find the following changes, at the bottom of the file.

<system.serviceModel>
        <bindings>
            <wsHttpBinding>
                <binding name="WSHttpBinding_IMyMathService" />
            </wsHttpBinding>
        </bindings>
        <client>
            <endpoint address="
http://localhost/MyMathService/MyMathService.svc"
                binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IMyMathService"
                contract="MyMathServiceReference.IMyMathService" name="WSHttpBinding_IMyMathService">
                <identity>

                   <!—this name can be different on your machine. –!>
                    <servicePrincipalName value="host/PRAVEEN-WIN7" />
                </identity>
            </endpoint>
        </client>
    </system.serviceModel>

 

Open the Page_load Handler of the Default.aspx in the newly created (Client Web Site) and put the code as shown below.

protected void Page_Load(object sender, EventArgs e)
   {
       double dblX = 10000.0;
       double dblY = 2000.0;
       double dblResult = 0;
       Response.Write("<p>Value 1 : " + dblX.ToString("F2"));
       Response.Write("<br>Value 2 : " + dblY.ToString("F2"));

       try
       {
           Response.Write("<p>Using WS HTTP Binding");

           MyMathServiceReference.MyMathServiceClient mathProxy2 = new MyMathServiceReference.MyMathServiceClient("WSHttpBinding_IMyMathService");

           dblResult = mathProxy2.Add(dblX, dblY);
           Response.Write("<br>Calling Add >>  X : " + dblX.ToString("F2") + "  Y : " + dblY.ToString("F2") + " Result : " + dblResult.ToString("F2"));

           dblResult = mathProxy2.Subtract(dblX, dblY);
           Response.Write("<br>Calling Add >>  X : " + dblX.ToString("F2") + "  Y : " + dblY.ToString("F2") + " Result : " + dblResult.ToString("F2"));

           dblResult = mathProxy2.Multiply(dblX, dblY);
           Response.Write("<br>Calling Add >>  X : " + dblX.ToString("F2") + "  Y : " + dblY.ToString("F2") + " Result : " + dblResult.ToString("F2"));

           dblResult = mathProxy2.Divide(dblX, dblY);
           Response.Write("<br>Calling Add >>  X : " + dblX.ToString("F2") + "  Y : " + dblY.ToString("F2") + " Result : " + dblResult.ToString("F2"));
       }
       catch (Exception eX)
       {
           Response.Write("There was an error while calling Service <p> <b>[" + eX.Message + "] </b>");
       }
   }

and when you run this web site, you will get following output.

image

Advertisements

September 6, 2013 - Posted by | .NET, CodeProject, SOA, WCF | , , ,

1 Comment »

  1. Very Nice Explaination. can u refer a good book WCF Beginers and professionals

    Comment by Amit | April 12, 2014 | Reply


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: