![]() |
Platforms, Frameworks & Libraries »
Windows Communication Foundation »
General
Beginner
License: The Code Project Open License (CPOL)
WCF (Windows Communication Foundation) Introduction and ImplementationBy Murali Manohar PareekThis article includes WCF Introduction, Sample WCF Service Library, Hosting of WCF Service at Windows Service and Consuming the WCF Service at Web Application |
C#, .NET, WCF, Dev
|
||||||||||
|
Advanced Search Add to IE Search |
|
|
|
||||||||||||||||
This article includes WCF Introduction, Sample WCF Service Library, Hosting of WCF Service at Windows Service and consuming the WCF Service at Web Application.
Basic knowledge of C#, and HTML is required.
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 detail you can refer
http://en.wikipedia.org/wiki/Windows_Communication_Foundation
One of the good article is available at code project site. you can refer this article WCFOverview.aspx
These are the steps needed to be followed to create a WCF Service Library with Visual Studio 2008
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.
//<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; }
}
}
}
//<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;
}
}
}
<?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>
When we run this application as like simple windows or web application, it will host the application automatically and run the Test Client. We can use Test Client as follows:
Here we will host the WCF Service on Managed Windows Service. We will Add New Project as follows:
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;
}
}
}
}
To run the windows service we have to install the windows service. There is two option to install the windows service.
Open the command prompt and run below command
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe D:\murali\projects\WCF Demo\SampleWCFService\WCFServiceHost\bin\Debug\ WCFServiceSampleWindowsServiceHost.exe
We add Web Application Project as a 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;
}
Enter the input into the given text box and get the output by pressing the button.
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.
Version 1.0.0.0 has Initial code includes WCF Introduction, Sample WCF Service Library, Hosting of WCF Service at Windows Service and consuming the WCF Service at Web Application.
| You must Sign In to use this message board. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
General
News
Question
Answer
Joke
Rant
Admin
|
PermaLink |
Privacy |
Terms of Use
Last Updated: 13 Nov 2008 Editor: Sean Ewington |
Copyright 2008 by Murali Manohar Pareek Everything else Copyright © CodeProject, 1999-2009 Web19 | Advertise on the Code Project |