Wednesday, 26 December 2012

A Beginner's Tutorial for Understanding Windows Communication Foundation (WCF) Part-4



Consuming a WCF Service
We have seen how to create a WCF service. Let us now see how we can consume a WCF service. Let us start by adding a default ASP.NET website in the same solution. We then need to add a service reference to the WCF service we just created.


Adding this service reference will mainly do two things:
  1. Create the Address and Binding part to access this service in the web.config file.
  2. Create the proxy class for us to access the service.
So let us first look at the Address and Binding in the web.config to complete the ABC part of the WCF service.
<system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_IPairArihmeticService"/>
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:1062/WcfTestWebSite/PairArihmeticService.svc"
          binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IPairArihmeticService"
          contract="PairServiceReference.IPairArihmeticService"
          name="BasicHttpBinding_IPairArihmeticService"/>
    </client>
</system.serviceModel>
This web.config shows the address of the WCF service, the binding to use the webservice, and the contract that is being exposed by this web service. All this was generated by extracting the meta data from the service.
Now let us look at how to use the proxy class that was generated. We will use this proxy class to call the methods of the WCF service and then extract the results out of it.
PairServiceReference.Pair p1 = new PairServiceReference.Pair();
p1.First = Convert.ToInt32(txtP1First.Text);
p1.Second = Convert.ToInt32(txtp1Second.Text);

PairServiceReference.Pair p2 = new PairServiceReference.Pair();
p2.First = Convert.ToInt32(txtP2First.Text);
p2.Second = Convert.ToInt32(txtp2Second.Text);

PairServiceReference.PairArihmeticServiceClient pairServiceClient =
           new PairServiceReference.PairArihmeticServiceClient();
PairServiceReference.Pair addResult = pairServiceClient.Add(p1, p2);

PairServiceReference.Pair minusResult = pairServiceClient.Subtract(p1, p2);

lblsum.Text = addResult.First.ToString() + ", " + addResult.Second.ToString();
lblminus.Text = minusResult.First.ToString() + ", " + minusResult.Second.ToString();
Note: The above code snippet refers to control IDs. Please see the source code for that.
Now we have successfully consumed the WCF service from our ASP.NET website. Before we wrap up, let us now build this web site and see the results.
 

Click here for next step.

No comments:

Post a Comment