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.
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.
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace WCFServiceSample
{
[ServiceContract]
public interface IService1
{
[OperationContract]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
}
[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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace WCFServiceSample
{
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
="1.0"="utf-8"
<configuration>
<system.web>
<compilation debug="true" />
</system.web>
<system.serviceModel>
<services>
<service name="WCFServiceSample.Service1" behaviorConfiguration=
"WCFServiceSample.Service1Behavior">
<host>
<baseAddresses>
<add baseAddress = "http://localhost:8731/Design_Time_Addresses
/WCFServiceSample/Service1/" />
</baseAddresses>
</host>
<endpoint address ="" binding="wsHttpBinding" contract=
"WCFServiceSample.IService1">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="WCFServiceSample.Service1Behavior">
<serviceMetadata httpGetEnabled="True"/>
<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:
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
Step 2: Select Windows Service Project
Step 3: Add Reference
Step 4: Select Project Tab and Add “WCFServiceSample” Library as a Reference into Windows Service
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.
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.
Step 7: Now we add the code in Windows service to open the Host.
Step 8: Add Windows Service Code
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.
Step 10: Set the ServiceProcessInstaller
Property as required.
Step 11: Set the ServiceInstaller
Property as required and build the application.
Run Windows Service
To run the Windows service, we have to install the windows service. There are two options to install the Windows service.
- 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
Step 2: Add Project Output
Step 3: Select “WCFServiceSampleWindowsServiceHost
” as primary output.
Step 4: View Custom Actions
Step 5: Add Custom Actions
Step 6: Select Primary output from Application Folder of Setup Project
Step 7: Primary output will automatically add with all sub folder of Custom Actions. Now Build the Setup Application
Step 8: Install the Setup Application
Step 9: It will show the Setup Wizard, using this wizard we will install the Windows Service
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.
Step 11: Starting Service.
Consuming the WCF Service
We add Web Application Project as a client.
Step 1: Add ASP.NET Web Application Project
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.
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.
Using WCF Service Client
Create the instance of the WCF client to communicate to the WCF service as follows:
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.
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