Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

WCF (Windows Communication Foundation) Introduction and Implementation

4.58/5 (30 votes)
13 Nov 2008CPOL5 min read 1   1.5K  
This article includes WCF Introduction, Sample WCF Service Library, Hosting of WCF Service at Windows Service and Consuming the WCF Service at Web Application

Introduction

This article includes WCF Introduction, Sample WCF Service Library, Hosting of WCF Service at Windows Service and consuming the WCF Service at Web Application. 

Background

Basic knowledge of C# and HTML is required.

WCF Introduction  

WCF(Windows Communication Foundation), originally tagged with the code name "Indigo" is a programming framework used to build applications that inter-communicate. It is Microsoft’s unified programming model for building service-oriented applications. It enables developers to build secure, reliable, transacted solutions that integrate across platforms and interoperate with existing investments. WCF is the part of the .NET Framework dedicated to communications.

WCF.JPG

This definition is from Wikipedia and Microsoft. For more details, you can refer to:  http://en.wikipedia.org/wiki/Windows_Communication_Foundation

Creating WCF Service Application with Visual Studio 2008

One of the good articles is available on CodeProject. You can refer to this article.

Creating WCF Service Library with Visual Studio 2008

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

  • Open Visual Studio 2008. 
  • Click on New Project in the File menu. 
  • Expand the Visual C# node in the Project types tree, and select the WCF node. 
  • Select WCF Service Library. 
  • Choose the Name and Location where the application is to be saved and click the OK button.
  • The project will be created with the default files, which are IService1.cs, Service1.cs, and App.config.
WCFServiceSample.JPG

We 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 App.Config file.

We need to make the necessary changes in the above section of App.Config if we are renaming the services; otherwise, external systems cannot identify the services.

WCF Service Code

IService1.cs
C#
//<createdby> Murali Manohar Pareek </createdby>
//<date> Oct 23, 2008 </date>
//<description> WCF Service</description>
//<version> 1.0.0.0 </version>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WCFServiceSample
{
    // NOTE: If you change the interface name "IService1" here,
    // you must also update the reference to "IService1" in App.config.
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string GetData(int value);

        [OperationContract]
        CompositeType GetDataUsingDataContract(CompositeType composite);

        // TODO: Add your service operations here
    }

    // Use a data contract as illustrated in the sample below to 
    //add composite types to service operations
    [DataContract]
    public class CompositeType
    {
        bool boolValue = true;
        string stringValue = "Hello ";

        [DataMember]
        public bool BoolValue
        {
            get { return boolValue; }
            set { boolValue = value; }
        }

        [DataMember]
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue = value; }
        }
    }
}
Service1.cs
C#
//<createdby> Murali Manohar Pareek </createdby>
//<date> Oct 23, 2008 </date>
//<description> WCF Service</description>
//<version> 1.0.0.0 </version>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WCFServiceSample
{
    // NOTE: If you change the class name "Service1" here, 
you must also update the reference to "Service1" in App.config.
    public class Service1 : IService1
    {
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

        public CompositeType GetDataUsingDataContract(CompositeType composite)
        {
            if (composite.BoolValue)
            {
                composite.StringValue += "Suffix";
            }
            return composite;
        }
    }
}
App.Config
XML
 <?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.web>
    <compilation debug="true" />
  </system.web>
  <!-- When deploying the service library project, the content of the config file 
must be added to the host's 
  app.config file. System.Configuration does not support config files for libraries. -->
  <system.serviceModel>
    <services>
      <service name="WCFServiceSample.Service1" behaviorConfiguration=
"WCFServiceSample.Service1Behavior">
        <host>
          <baseAddresses>
            <add baseAddress = "http://localhost:8731/Design_Time_Addresses
/WCFServiceSample/Service1/" />
          </baseAddresses>
        </host>
        <!-- Service Endpoints -->
        <!-- Unless fully qualified, address is relative to base address supplied
 above -->
        <endpoint address ="" binding="wsHttpBinding" contract=
"WCFServiceSample.IService1">
          <!-- 
              Upon deployment, the following identity element should be removed 
or replaced to reflect the identity under which the deployed service runs. 
 If removed, WCF will infer an appropriate identity 
              automatically.
          -->
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <!-- Metadata Endpoints -->
        <!-- The Metadata Exchange endpoint is used by the service to describe
 itself to clients. --> 
        <!-- This endpoint does not use a secure binding and should be secured 
or removed before deployment -->
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="WCFServiceSample.Service1Behavior">
          <!-- 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="False" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

Run WCF Service Library

When we run this application as a simple Windows or web application, it will host the application automatically and run the Test Client. We can use Test Client as follows:

WCFServiceTestClient.JPG

Hosting the WCF Service

  • IIS 6 (ASPNET_WP.EXE / W3wp.exe)
    • Activation on demand upon client request
    • Only supports HTTP/S transport
  • Self Hosting
    • Can be any managed application, i.e. Console or WinForms application
    • Low-level but flexible
  • Windows Activation Service (WAS)
    • Supports all transports
    • Will ship with IIS 7 on Vista and Longhorn Server
  • Managed Windows Services (NT Services)

Here we will host the WCF Service on Managed Windows Service. We will Add New Project as follows:

Step 1: Add New Project

WCFServiceSampleAddNewProject.JPG

Step 2: Select Windows Service Project

WCFServiceSampleWindowsServiceHost.JPG

Step 3: Add Reference

AddReference.JPG

Step 4: Select Project Tab and Add “WCFServiceSample” Library as a Reference into Windows Service

AddReferenceProject.JPG

Step 5: Now we will open the WCF Service Host. To open the service Host, we need System.ServiceModel Library as a reference into the windows service.

AddReferenceServiceModel.JPG

Step 6: Windows service itself does not have any configuration file related to WCF Service Configuration like endpoint, behavior etc. so we have to include App.Config file into the windows service. We simply add Application Configuration File and make the same copy as App.Config file in WCFServcieSample application.

AppConfig.JPG

Step 7: Now we add the code in Windows service to open the Host.

WCFHostViewCode.JPG

Step 8: Add Windows Service Code

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.ServiceModel;
using System.IO;

namespace WCFServiceSampleWindowsServiceHost
{
    public partial class Service1 : ServiceBase
    {
        ServiceHost host;
        FileStream fs;
        StreamWriter m_streamWriter;

        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            fs = new FileStream(@"c:\temp\WCFLog.txt", FileMode.OpenOrCreate, 
            FileAccess.Write);
            m_streamWriter = new StreamWriter(fs);

            try
            {
                if (host != null)
                {
                    host.Close();
                }

                host = new ServiceHost(typeof(WCFServiceSample.Service1));
                host.Open();


                m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
                m_streamWriter.WriteLine(DateTime.Now + " WCF: Host 
                open successfully \n");

                m_streamWriter.WriteLine(DateTime.Now + " WCF: Service 
                Started successfully \n");
            }
            catch (Exception ex)
            {
                m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
                m_streamWriter.WriteLine(DateTime.Now + " WCF: Error in 
                opening Host : " + ex.Message + "\n");

                if (host != null)
                {
                    host = null;
                }
            }
            finally
            {
                m_streamWriter.Flush();
                m_streamWriter.Close();
                m_streamWriter = null;
                fs.Close();
                fs = null;
            }
        }

        protected override void OnStop()
        {
            fs = new FileStream(@"c:\temp\WCFLog.txt", FileMode.OpenOrCreate,
                                FileAccess.Write);
            m_streamWriter = new StreamWriter(fs);

            try
            {
                if (host != null)
                {
                    host.Close();
                    host = null;

                    m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
                    m_streamWriter.WriteLine(DateTime.Now + " WCF: Host close 
                    successfully \n");
                    m_streamWriter.WriteLine(DateTime.Now + " WCF: Stopped 
                    successfully \n");

                }
            }
            catch (Exception ex)
            {
                m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
                m_streamWriter.WriteLine(DateTime.Now + " WCF: Error in 
                closing Host : " + ex.Message + "\n");
            }
            finally
            {
                m_streamWriter.Flush();
                m_streamWriter.Close();
                m_streamWriter = null;
                fs.Close();
                fs = null;
            }
        }
    }
}

Step 9: Add Installer. It will add Service Process Installer and Service Installer. Service Process Installer takes care for Service Account related information and Service Installer takes care of service related information like ServiceName, DisplayName, StartupType, etc.

WCFHostAddInstaller.JPG

Step 10: Set the ServiceProcessInstaller Property as required.

LocalSystem.JPG

Step 11: Set the ServiceInstaller Property as required and build the application.

AutomaticService.JPG

Run Windows Service

To run the Windows service, we have to install the windows service. There are two options to install the Windows service.

  1. Using InstallUtil Command of .NET Framework.

Open the command prompt and run the below command:

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe 
D:\murali\projects\WCF Demo\SampleWCFService\WCFServiceHost\bin\Debug\ 
WCFServiceSampleWindowsServiceHost.exe 

Using Setup Project

Install Windows Service using Setup Project

Step 1: Add Setup Project

HostSetup.JPG

Step 2: Add Project Output

AddProjectOutput.JPG

Step 3: Select “WCFServiceSampleWindowsServiceHost” as primary output.

AddProjectOutput2.JPG

Step 4: View Custom Actions

ViewCustomActions.JPG

Step 5: Add Custom Actions

ViewCustomActions2.JPG

Step 6: Select Primary output from Application Folder of Setup Project

ViewCustomActions3.JPG

Step 7: Primary output will automatically add with all sub folder of Custom Actions. Now Build the Setup Application

ViewCustomActions4.JPG

Step 8: Install the Setup Application

InstallWCFHost.JPG

Step 9: It will show the Setup Wizard, using this wizard we will install the Windows Service

InstallWCFHost2.JPG

Step 10: Now open Services using Control Panel -> Administrative Tools -> Services. It will show the list of available service. Select our “WCFServiceSample” Service and Start it.

StartService.JPG

Step 11: Starting Service.

StartService2.JPG

Consuming the WCF Service

We add Web Application Project as a client.

Step 1: Add ASP.NET Web Application Project

AddNewWebProject.JPG

Step 2: Add Service Reference using Right click on References of the Web application, and select Add Service Reference. Add Service Address, this address is same as defined in App.Config file. Type the Namespace of the Service that we desire and press Ok button.

AddServiceRefrence.JPG

Step 3: The proxy is created and added to the service reference, and is ready to consume the service in the application with the WCFServiceSample reference.

AddServiceRefrence2.JPG

Using WCF Service Client

Create the instance of the WCF client to communicate to the WCF service as follows:

C#
protected void btnGetData_Click(object sender, EventArgs e)
        {
            WCFServiceSample.Service1Client proxy = 
             new WebApplicationSample.WCFServiceSample.Service1Client();
            lblOutput.Text =proxy.GetData(Convert.ToInt32(txtInput.Text));
        }

protected void btnGetCompData_Click(object sender, EventArgs e)
        {
            WCFServiceSample.Service1Client proxy = 
              new WebApplicationSample.WCFServiceSample.Service1Client();
            WCFServiceSample.CompositeType compType = 
              new WebApplicationSample.WCFServiceSample.CompositeType();
            compType.BoolValue = true;
            compType.StringValue = txtInput.Text;
            compType = proxy.GetDataUsingDataContract(compType);
            lblOutput.Text = compType.StringValue;
        }

Run Web Application

Enter the input into the given text box and get the output by pressing the button.

WebOutput.JPG

Conclusion

This article includes WCF Introduction, Sample WCF Service Library, Hosting of WCF Service at Windows Service and consuming the WCF Service at Web Application. I will include details about configuring a service and a client for different types of communication in my next article very soon.

History

Version 1.0.0.0 has Initial code that includes WCF Introduction, Sample WCF Service Library, Hosting of WCF Service at Windows Service and consuming the WCF Service at Web Application.

References

License

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