Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / IIS

A Windows Communication Foundation (WCF) Overview

4.78/5 (119 votes)
18 Sep 2008CPOL8 min read 1   5.1K  
This article talks about the Windows Communication Foundation (WCF) and how to consume it in applications. It describes the WCF model, and is a quick introduction for beginners.

Introduction

Windows Communication Foundation (WCF) is an extension of the .NET framework to build and run connected systems. Windows Communication Foundation provides a unified framework for building secure and reliable transacted Web services. Windows Communication Foundation combines and extends the capabilities of Distributed Systems, Microsoft .NET Remoting, Web Services, and Web Services Enhancements (WSE), to develop and deliver unified secured systems. The WCF framework builds loosely-coupled applications on a service oriented architecture that interoperates more securely and reliably across platforms.

WCF simplifies the development effort to make service oriented applications by combining the technologies together, leading to higher development productivity. Also, it reduces the complexity of applications by unifying Enterprise Services, Messaging, .NET Remoting, Web Services, and WSE. WCF builds applications with an attributed programming model, leading to higher developer productivity. WCF was introduced as part of the .NET 3.0 Runtime components. The Windows Communication Foundation provides a service oriented programming model to build service oriented applications that interoperate across organizational and platform boundaries. It supports a broad range of Web Service standards like XML, XSD, SOAP, XPath, WSDL, and advanced standards and specifications like WS-Addressing, WS-Policy, WS-Security, WS-Trust, WS-Secure Conversation, WS-Reliable Messaging, WS-Atomic Transaction, WS-Coordination, and WS-Policy. The following diagram depicts the Windows Communication Foundation (WCF) framework model:

Image 1

WCF Communication Model

Windows Communication Foundation (WCF) follows a client–server model to establish communication between applications. Client applications can directly access services through Endpoints exposed by the service. Endpoints are nothing but locations defined, through which messages can be sent or received, and a service can have multiple endpoints.

Image 2

A WCF Service is comprised of the following major components. The diagram below shows how the components are related to each other:

  • Service Contract
  • Operation Contract
  • Data Contract
  • Data Member

Image 3

Service Contract

Service contract is a contract that specifies the direction and type of the messages in a conversation. It is an interface or a class that defines the service contract in a Windows Communication Foundation (WCF) application. A service contract is the gateway to a service for external applications to make use of the service functions, and at least one service contract should be available in a service. A service contract is defined as follows:

C#
// Student ServiceContract
[ServiceContract]
public interface IStudentService
{
    // Define the OperationContact here….
}

The ServiceContract attribute of the interface defines the service contract in the service interface. The service contract defines the operations available in the service, operations like web service methods in a web service. IstudentService is a student service interface which exposes all the operation contracts or methods in this service to external systems.

Operation Contract

An operation contract defines the methods of the service that are accessible by external systems. The OperationContract attribute needs to be applied for all these methods, these are also like web methods in a web service. Operation contracts are defined as follows:

C#
// Student ServiceContract
[ServiceContract]
public interface IStudentService
{
      // Define the GetStudentFullName OperationContact here….
    [OperationContract]
    String GetStudentFullName (int studentId);

      // Define the GetStudentInfo OperationContact here….
    [OperationContract]
    StudentInformation GetStudentInfo (int studentId);

}

Data Contract

A data contract defines a type with a set of data members or fields that will be used as the composite type in a service contract. It is a loosely-coupled model that is defined outside the implementation of the service and accessible by services in other platforms. To define a data contract, apply the DataContract attribute to the class to serialize the class by a serializer, and apply the DataMember attribute to the fields in the class that must be serialized. A StudentInformation data contract can be defined as follows:

C#
[DataContract]
public class StudentInformation
{
    // Define the Datamembers here….
}

Data Member

A data member specifies the type which is part of a data contract used as a composite type member of the contract. To define a data member, apply the DataMember attribute to the fields that must be serialized. The DataMember attribute can be applied to private properties, but they will be serialized and deserialized, and will be accessible to the user or process. The code below shows how to define a data member in a data contract:

C#
[DataContract]
public class StudentInformation
{
      _studentId = studId;

    [DataMember]
    public int StudentId
    {
        get { return _studentId; }
        set { _studentId = value; }
    }

}

Creating WCF Applications with Visual Studio 2008

These are the steps needed to be followed to create a WCF application with Visual Studio 2008:

  1. Open Visual Studio 2008.
  2. Click on New Project in the File menu.
  3. Expand the Visual C# node in the Project types tree, and select the Web node.
  4. Select WCF Service Application.
  5. Choose the folder where the application is to be saved and click the OK button.
  6. The project will be created with the default files, which are IService1.cs, Service1.svc, Service1.svc.cs, and web.config.

Image 4

You can see the ServiceContract attribute with IService1, and the methods exposed are defined with the OperationContract attribute. Service1 is the concrete class for the implementation of IService1. Endpoints and other behavioral properties are defined in the system.serviceModel section of the Web.Config file.

You need to make the necessary changes in the above section of Web.Config if you are renaming the services; otherwise, external systems can not identify the services.

Customizing the Default WCF Service

Now, we need to make the necessary changes in the default WCF application according to our requirements. The first step is renaming the existing service files or deleting the existing files and create new ones. In this example, I would go ahead with the first approach, renaming the existing files.

Rename the project to WcfStudentService, the file Iservice1.cs to IstudentService.cs, Service.svc to StudentService.svc. Note that the code file Service.svc.cs will also be renamed to Service.svc.cs. Make the corresponding changes in the Web.Config file.

Remove the existing code from IstudentService and add the following code. The OperationContract attribute should be applies to the methods which are accessible to external systems. DataContract should be applied to the StudentInformation class, and fields in the StudentInformation attributed with DataMember since StudentInformation is using as composite type in IstudentService.

C#
namespace WcfStudentService
{
    // Defines IStudentService here
    [ServiceContract ]
    public interface IStudentService
    {
        // Define the GetStudentFullName OperationContact here….
        [OperationContract]
        String GetStudentFullName(int studentId);

        // Define the GetStudentInfo OperationContact here….
        [OperationContract]
        IEnumerable<studentinformation> GetStudentInfo(int studentId);
    }


    // Use a data contract as illustrated in the sample below to add
    // composite types to service operations.
    [DataContract]
    public class StudentInformation
    {
        int _studentId ;
        string _lastName;
        string _firstName;

        public StudentInformation(int studId, string firstname, string lastName)
        {
            _studentId = studId;
            _lastName = lastName;
            _firstName = firstname;
        }

        [DataMember]
        public int StudentId
        {
            get { return _studentId; }
            set { _studentId = value; }
        }

        [DataMember]
        public string FirstName
        {
            get { return _firstName; }
            set { _firstName = value; }
        }

        [DataMember]
        public string LastName
        {
            get { return _lastName; }
            set { _lastName = value; }
        }
    }
}

Note that StudentInformation is an independent class and accessible to external systems since it declared as public.

StudentService is the concrete class implemented from IstudentService. Add the following code in the service class:

C#
namespace WcfStudentService
{
    // StudentService is the concrete implmentation of IStudentService.
    public class StudentService : IStudentService
    {

        List<studentinformation> Students = new List<studentinformation>() ;

        // Create  list of students
        public StudentService()
        {
            Students.Add(new StudentInformation(1001, "Nikhil",
                "Vinod"));
            Students.Add(new StudentInformation(1002, "Joshua",
                "Hunter"));
            Students.Add(new StudentInformation(1003, "David",
                "Sam"));
        }

        // Method returning the Full name of the student for the studentId
        public string GetStudentFullName(int studentId)
        {
            IEnumerable<string> Student
                         = from student in Students
                           where student.StudentId == studentId
                           select student.FirstName + " " + student.LastName;

            return Student.Count() != 0 ? Student.First() : string.Empty;
        }

        // Method returning the details of the student for the studentId
        public IEnumerable<studentinformation> GetStudentInfo(int studentId)
        {

            IEnumerable<studentinformation> Student =  from student in Students
                                   where student.StudentId == studentId
                                   select student ;
            return Student;
        }
    }

Hosting and Testing the WCF Service

The WCF service can be hosted in Internet Information Service (IIS), and Windows Activation Service (WAS) with Vista and IIS 7.0. In this example, IIS is used for hosting the WCF service. Build the service project, and run it by pressing F5 to run from Visual Studio 2008. By default, it would take IIS as the hosting service. You can select the StudentService.svc file from the list of files displayed in the browser window, and the page will be displayed as follows:

Image 5

You can not directly test the WCF service with out a client, as we do in a web service.

There is an interface provided by Microsoft to test the service in an easy way, which is the WcfTestClient utility. The WcfTestClient window will be opened if the service is hosted by the WCF Service Host (WcfSvcHost.exe), from Visual Studio, or you can explicitly run the WcfTestClient utility from the command prompt. You can run it as follows:

C :\> WcfTestClient http://localhost:4489/StudentService.svc

http://localhost:4489/StudentService.svc should be the name of the service to be tested. WcfTestClient displays the service with the exposed methods on the left side pane; it also provide the options to enter the parameter values on the right top pane. When you enter the values in the parameter box and click the Invoke button, it displays the results on the right bottom pane of this utility.

Image 6

Consuming the WCF Service

The WCF service can be communicated through a WCF client from a client application. The first step of consuming a WCF service is to create a WCF client and the related configuration files. The Service Model Metadata Utility Tool (Svcutil.exe) is a command-line tool and one of its options is to create a WCF Client. The other option is to create a WCF Client by adding the service reference in the Windows project. The second option is used in this example to create the WCF Client.

Also, add a Windows application with a form which has Buttons, Labels, a TextBox, and a DataGridView to display the student information.

Create the WCF Client

To add the service reference to the Windows application, follow these steps:

  1. Open Solution Explorer.
  2. Right click on References of the Windows application, or right click on Service References and select Add Service Reference.
  3. And Service Reference window will pop up.
  4. Image 7

  5. Click on Discover, select the Services in the Solution in the Discover dropdown.
  6. It would search and display the services in the solution as shown below:
  7. Image 8

  8. Rename Namespace to StudentServiceReference, select StudentService, and click the OK button.
  9. The proxy is created and added to the service reference, and is ready to consume the service in the application with the StudentService reference.
  10. Image 9

Using the WCF Client

Create the instance of the WCF client to communicate to the service. The following line create the service client proxy:

C#
// create the proxy to access the service
StudentServiceClient studClient = 
  new StudentServiceClient("WSHttpBinding_IStudentService");

StudentServiceClient is the WCF client class generated when the service reference is added to the project. WSHttpBinding is the endpoint binding method specified in the web.config file of the service, and IStudentService is the service to be communicated.

After creating the proxy or instance of the WCF client, we can access the methods of the service like accessing the methods of a web service in the previous versions of .NET. The GetStudentFullName and GetStudentInfo methods of the service can be called as follows:

C#
// Get Fullname of the Student through the proxy from service
lblFullName.Text = studClient.GetStudentFullName(
                     Convert.ToInt16(textBox1.Text));

// Get details of the Student through the proxy from service
IEnumerable<studentinformation> x = 
   studClient.GetStudentInfo(Convert.ToInt16(textBox1.Text));
dataGridView1.DataSource = x;

In the form, if you enter the student ID and click on the Display Student Info button, you will call the service methods and populate the Fullname label and The DataGridView with the details.

Image 10

Conclusion

This is just an introduction to the Windows Communication Foundation framework. I will include details about configuring a service and a client for different types of communication in my next article.

Reference

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)