Abstract

Over the years, we have learned innumerable ways of consuming services across the network such as Remoting, COM, COM+, MSMQ, Web Services using ASP.NET and DCOM. Every technology has its advantages and disadvantages. This article commences by framing the need for WCF and examining the problems it intends to resolve by way of a quick regression of earlier distributing computing technologies. After completion of this article, you will be able to build several WCF services, host each service and consume it in a client application using various WCF development tools. This article intends to provide an understanding of in-house development of WCF services rather than the actual hosting environment such as IIS web server.

Legacy Distributed Technologies

Anatomy of WCF

We can build web services and client applications that can communicate and interoperate with web services and client applications running on other non-Windows operating systems. So why do we need WCF? If you are building a distributed application for Windows, which technology should we use? The objective behind WCF is to provide a unified programming model for many of these technologies such as Web services, MSMQ, Remoting, COM+ and DCOM, enabling you to build an application that is as independent as possible from the underlying mechanism used to connect services and applications together.

WCF is the acronym for Windows Communication Foundation, introduced with the .NET 3.0 Framework. It integrates many previously independent distributed technologies into a streamlined API represented by the System.ServiceModel namespace. We can expose the service to callers using a wide variety of tactics by employing WCF. Integration and interoperability of diverse APIs are typically two major aspects of WCF. Here, consider the following list of major features of WCF:

When you build a WCF distributed system, you will typically need to create three interrelated assemblies as in the following:

If we develop a WCF service on the local machine, then we do not need to create three files, we can eliminate the host DLL generation part.

Building WCF Service Assembly

The Visual Studio 2010 IDE provides the ideal environment for building and consuming WCF web services and applications. The Visual Studio development tools for the .NET framework 4.0 include a project template that you can use for creating WCF services.

Building WCF Service Assembly

At this moment, we are creating a WCF service that is hosted locally. Since we are hosting it locally, we do not need to create a separate solution to host this service that typically happens in the case of an HTTP or TCP binding.

To begin, open the Visual Studio 2010 IDE and create a WCF Service Library project named MagicMathWcf, making sure the correct option under the WCF node of the New Project Dialog box is as in the following:

wcf service liberary

Defining the Contract

The WCF service requires an interface-like structure referred to as Contracts that the service will implement and then build a service that conforms to these contracts. The WCF typically stipulates three types of contracts, Data Contract, Message Contract and Service Contract. The Data contract specifies the details of products that the WCF service can pass to the operation. In simple terms, the Data contract defines the variables. On the other hand, the service contract defines the operations (methods) that the WCF service implements. For a CLR interface to participate in the service provided by WCF, it must be adorned with the [ServiceContract] attribute.

The following code depicts the implementation of the Service contract. Here, change the name of the initial IService.cs file to IMath.cs and Service1.cs to MathLib.cs. Once you do so, delete all the existing example code from both of files and place the following code in the IMath.cs as in the following:

  1. using System;
  2. using System.ServiceModel;
  3. namespace MagicMathWcf
  4. {
  5. [ServiceContract]
  6. public interface IMath
  7. {
  8. [OperationContract]
  9. double calSqrt(double value);
  10. [OperationContract]
  11. string WelcomeMsg(string str);
  12. }
  13. }
Implementing the Service

We have now specified the structure of the data passed to the WCF service by using a data contract and defined the shape of the WCF service by using a service contract. The next step is to write the code that actually implements the service code like an interface.

So, open the MathLib.cs file and implement the IMath interface over there. Here, specify the previously defined method body implementation logic as in the following:
  1. using System;
  2. using System.ServiceModel;
  3. namespace MagicMathWcf
  4. {
  5. public class MathLib : IMath
  6. {
  7. public double calSqrt(double value)
  8. {
  9. return Math.Sqrt(value);
  10. }
  11. public string WelcomeMsg(string str)
  12. {
  13. return "Hello " + str;
  14. }
  15. }
  16. }
Testing and Deploying the Service

Finally, double-check the details in the app.config file to ensure and verify that file renaming operation has been done correctly. Finally, debug the service project. One benefit of a WCF service project is that it provides a service simulator where we can test our service implementation. Just double-click over the method that you wanted to test, supply the necessary argument and click the Invoke button. It will yield the output as in the following:

Testing and Deploying the Service

We can also test the WCF service from the command prompt using the wcftestclient.exe utility. Just pass the service metadata URL and testing begin with a similar simulator as earlier.

WCF Service Binding Hosting WCF Service

Since we are hosting the WCF service on the local machine we do not need this section indeed. Basically, this step is required when we create a WCF service that is hosted on an IIS server. During that process, a final endpoint address is generated that is referenced in the configuration file. Just for knowledge purposes, we create a separate console based application that works as a middleware responsible for starting and stopping the service. In order to start the service, first add the reference of WCF service DLL and ServiceModel.dll in that solution and use the following code.
  1. using System;
  2. using System.ServiceModel;
  3. using MagicMathWcf;
  4. namespace MathMagicHOST
  5. {
  6. class Program
  7. {
  8. static void Main(string[] args)
  9. {
  10. using (ServiceHost sHost=new ServiceHost(typeof(MathLib)))
  11. {
  12. sHost.Open();
  13. Console.WriteLine("The Service Started.......");
  14. Console.ReadLine();
  15. }
  16. }
  17. }
  18. }
Thereafter, add a configuration file and mention the endpoint address and base address that is responsible to invoke the service.
  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <configuration>
  3. <system.serviceModel>
  4. <services>
  5. <service name ="MagicMathWcf.MathLib">
  6. <endpoint address =""
  7. binding="basicHttpBinding"
  8. contract="MagicMathWcf.IMath" />
  9. <host>
  10. <baseAddresses>
  11. <add baseAddress =""/>
  12. </baseAddresses>
  13. </host>
  14. </service>
  15. </services>
  16. </system.serviceModel>
  17. </configuration>
We shall dig deeper into this topic in the next article of this series.

Consuming WCF Service

Now, the final task is to build a piece of software to communicate with this WCF service type. Consumtion of a WCF service is basically generating a proxy class of that service that is later referenced in the client application. There are many ways to generate a proxy class. In this section, we shall create a proxy class using the Visual Studio IDE. So, first of all create a Console based application (called MagicMathClient) and right-click over the project in the Solution Explorer. Here, choose the Add Service Reference vommand, then the following dialog box will ask you to enter the address of the WCF service. Just enter the address and hit the Go button. It will expose the metadata that resides in the WCF reference as in the following:

add service reference

In the bottom of that dialog box, you can set the name of this proxy class, for instance ServiceReference1. Finally, click the OK button and once that is done, you will see that a service reference is added under the Solution Explorer as in the following:

Consuming WCF Service

Now, import the WCF ServiceReference1 namespace and place the following code in the program class as in the following:
  1. using System;
  2. using MagicMathClient.ServiceReference1;
  3. namespace MagicMathClient
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. using (MathClient obj=new MathClient())
  10. {
  11. Console.Write("Enter the Value:");
  12. double x = double.Parse(Console.ReadLine());
  13. Console.WriteLine("Sqrt={0}",obj.calSqrt(x));
  14. Console.ReadLine();
  15. }
  16. }
  17. }
  18. }
Here, we just instantiated the class MathLib defined in the WCF Service and consumed its methods. Finally, it's time to run the project. The output will be as in the following:

output

One thing to always remember, before running this application, first start the hosted service application, otherwise this application throws an exception.

Summary

As we have stated, WCF is platform-independent like ASP.NET web services but offers features similar to Remoting, XML Web services and MSMQ. In this article, we learned how to use WCF between a client and server application and explored the various aspects of a WCF service contract, data contract, its advantage over inherent technology, how to configure the service and finally, how to consume its functionality into a client console-based application. In the next article of this series, we will illustrate the HTTP, TCP and MSMQ binding implementation and other features such as security and session management.