Windows Communication Foundation (Code named Indigo) is a
programming platform and runtime system for building, configuring and deploying
network-distributed services. It is the latest service oriented technology;
Interoperability is the fundamental characteristics of WCF. It is unified
programming model provided in .Net Framework 3.0 WCF is a combined features of
Web Service, Remoting, MSMQ and COM+. WCF provides a common platform for all
.NET communication.
Definition:
Windows Communication
Foundation (WCF) is a framework for building service-oriented applications.
Using WCF we can build secure, reliable, transacted solutions that integrate
across platforms.
Below figures shows the different technology combined to form
WCF.
- WCF
is interoperable with other services when compared to .Net Remoting,where
the client and service have to be .Net.
- WCF
services provide better reliability and security in compared to ASMX web
services.
- In
WCF, there is no need to make much change in code for implementing the
security model and changing the binding. Small changes in the
configuration will make your requirements.
- WCF
has integrated logging mechanism, changing the configuration file settings
will provide this functionality. In other technology developer has to
write the code.
WCF Architecture
The following figure
illustrates the major components of WCF.
Contracts
Contracts layer are
next to that of Application layer. Developer will directly use this contract to
develop the service. We are also going to do the same now. Let us see briefly
what these contracts will do for us and we will also know that WCF is working
on message system.
Service contracts
- Describe about the
operation that service can provide. Example, Service provided to know the
temperature of the city based on the zip code, this service we call as Service
contract. It will be created using Service and Operational Contract attribute.
Data contract
- It describes the
custom data type which is exposed to the client. This defines the data types,
are passed to and from service. Data types like int, string are identified by
the client because it is already mention in XML schema definition language
document, but custom created class or datatype cannot be identified by the
client e.g. Employee data type. By using DataContract we can make client aware
that we are using Employee data type for returning or passing parameter to the
method.
Message Contract
- Default SOAP message
format is provided by the WCF runtime for communication between Client and
service. If it is not meeting your requirements then we can create our own
message format. This can be achieved by using Message Contract attribute.
Policies and Binding
- Specify conditions
required to communicate with a service e.g security requirement to communicate
with service, protocol and encoding used for binding.
Service Runtime
- It contains the
behaviors that occur during runtime of service.
- Throttling Behavior- Controls
how many messages are processed.
- Error Behavior - Specifies what
occurs, when internal error occurs on the service.
- Metadata Behavior - Tells how
and whether metadata is available to outside world.
- Instance Behavior - Specifies
how many instance of the service has to be created while running.
- Transaction Behavior - Enables
the rollback of transacted operations if a failure occurs.
- Dispatch Behavior - Controls
how a message is processed by the WCF Infrastructure.
Messaging
- Messaging layer is
composed of channels. A channel is a component that processes a message in some
way, for example, by authenticating a message. A set of channels is also known
as a channel stack. Channels are the core abstraction for sending message to
and receiving message from an Endpoint. Broadly we can categories channels as
- Transport Channels
Handles sending and receiving message from
network. Protocols like HTTP, TCP, name pipes and MSMQ.
- Protocol Channels
Implements SOAP based protocol by processing
and possibly modifying message. E.g. WS-Security and WS-Reliability.
Activation and Hosting
- Services can be
hosted or executed, so that it will be available to everyone accessing from the
client. WCF service can be hosted by following mechanism
- IIS
Internet information Service provides number
of advantages if a Service uses Http as protocol. It does not require Host code
to activate the service, it automatically activates service code.
- Windows Activation Service
(WAS) is the new process activation mechanism
that ships with IIS 7.0. In addition to HTTP based communication, WCF can also
use WAS to provide message-based activation over other protocols, such as TCP
and named pipes.
- Self-Hosting
WCF service can be self hosted as console
application, Win Forms or WPF application with graphical UI.
- Windows Service
WCF can also be hosted as a Windows Service,
so that it is under control of the Service Control Manager (SCM).
Features of WCF:
1.
Service Orientation
2.
Interoperability
3.
Multiple Message Patterns
4.
Service Metadata
5.
Data Contracts
6.
Security
7.
Multiple Transports and Encodings
8.
Reliable and Queued Messages
9.
Durable Messages
10.
Transactions
11.
AJAX and REST Support
12.
Extensibility
Terms of WCF:
A WCF service is exposed to the outside world as a
collection of endpoints.
1.
Endpoint: Endpoint is a construct at which messages are sent or received (or
both). Endpoint comprises of ABC’s
What are ABC’s
of WCF ?
A. Address - Address
is a location that defines where messages can be sent
B. Binding - Binding
is a specification of the communication mechanism (a binding) that described
how messages should be sent
The endpoints also define a
binding that specifies how a client will communicate with the service and the
address where the endpoint is hosted. Various components of the WCF are
depicted in the figure below.
·
"A" stands for Address: Where is the service?
·
"B" stands for Binding: How can we talk to the service?
·
"C" stands for Contract: What can the service do for us?
Different bindings supported by
WCF
Binding
|
Description
|
BasicHttpBinding
|
Basic Web service communication. No security
by default
|
WSHttpBinding
|
Web services with WS-* support. Supports
transactions
|
WSDualHttpBinding
|
Web services with duplex contract and
transaction support
|
WSFederationHttpBinding
|
Web services with federated security.
Supports transactions
|
MsmqIntegrationBinding
|
Communication directly with MSMQ
applications. Supports transactions
|
NetMsmqBinding
|
Communication between WCF applications by
using queuing. Supports transactions
|
NetNamedPipeBinding
|
Communication between WCF applications on
same computer. Supports duplex contracts and transactions
|
NetPeerTcpBinding
|
Communication between computers across
peer-to-peer services. Supports duplex contracts
|
NetTcpBinding
|
Communication between WCF applications
across computers. Supports duplex contracts and transactions
|
BasicHttpBinding
|
Basic Web service communication. No security
by default
|
WSHttpBinding
|
Web services with WS-* support. Supports
transactions
|
C. Contract -
Contract is a definition for a set of messages that can be sent or received (or
both) at that location (a service contract) that describes what message can be
sent.
2.
Service: A construct that exposes one or more endpoints, with each
endpoint exposing one or more service operations.
3.
Contracts: A contract is a agreement between two or more parties for common
understanding and it is a is a platform-neutral and standard way of
describing what the service does. In WCF, all services expose contracts.
Types of Contracts:
1) Operation Contract: An operation contract defines the parameters and return type of an operation.
1) Operation Contract: An operation contract defines the parameters and return type of an operation.
1
|
[OperationContract]
|
|
2
|
double Add(double i, double j);
|
2) Service Contract: Ties together multiple related operations
contracts into a single functional unit.
01
|
[ServiceContract] //System.ServiceModel
|
|
02
|
public interface IMath
|
03
|
{
|
|
04
|
[OperationContract]
|
05
|
double Add(double i, double j);
|
|
06
|
[OperationContract]
|
07
|
double Sub(double i, double j);
|
|
08
|
[OperationContract]
|
09
|
Complex
AddComplexNo(Complex i, Complex j);
|
|
10
|
[OperationContract]
|
11
|
Complex
SubComplexNo(Complex i, Complex j);
|
|
12
|
}
|
3) Data Contract: The descriptions in metadata of the data types
that a service uses.
01
|
// Use a data
contract
|
|
02
|
[DataContract] //using
System.Runtime.Serialization
|
03
|
public class Complex
|
|
04
|
{
|
05
|
private int real;
|
|
06
|
private int imaginary;
|
07
|
||
08
|
[DataMember]
|
09
|
public int Real
{ get; set; }
|
|
10
|
11
|
[DataMember]
|
|
12
|
public int Imaginary
{ get; set; }
|
13
|
}
|
Difference between WCF and Web service
Web service is a part
of WCF. WCF offers much more flexibility and portability to develop a service
when comparing to web service. Still we are having more advantages over Web
service, following table provides detailed difference between them.
Features
|
Web Service
|
WCF
|
Hosting
|
It can be hosted in
IIS
|
It can be hosted in
IIS, windows activation service, Self-hosting, Windows service
|
Programming
|
[WebService]
attribute has to be added to the class
|
[ServiceContraact]
attribute has to be added to the class
|
Model
|
[WebMethod]
attribute represents the method exposed to client
|
[OperationContract]
attribute represents the method exposed to client
|
Operation
|
One-way, Request-
Response are the different operations supported in web service
|
One-Way,
Request-Response, Duplex are different type of operations supported in WCF
|
XML
|
System.Xml.serialization
name space is used for serialization
|
System.Runtime.Serialization
namespace is used for serialization
|
Encoding
|
XML 1.0,
MTOM(Message Transmission Optimization Mechanism), DIME, Custom
|
XML 1.0, MTOM,
Binary, Custom
|
Transports
|
Can be accessed
through HTTP, TCP, Custom
|
Can be accessed
through HTTP, TCP, Named pipes, MSMQ,P2P, Custom
|
Protocols
|
Security
|
Security, Reliable
messaging, Transactions
|
WCF Examples:
This is the Basic WCF Tutorial ‘wcfMathSerLib’ will be created in a step by step approach. This ‘wcfMathSerLib’ will be tested by ‘ConsoleMathClient’ and with ‘WCF Test Client’
This is the Basic WCF Tutorial ‘wcfMathSerLib’ will be created in a step by step approach. This ‘wcfMathSerLib’ will be tested by ‘ConsoleMathClient’ and with ‘WCF Test Client’
Steps for
creating wcfMathSerLib
1. Open Visual Studio
2010 and File->NewProject
2.select WCF in ‘Recent Templates’
3.select ‘WCF Service Library’
4.Give Name as wcfMathServiceLibrary
5.Click OK
2.select WCF in ‘Recent Templates’
3.select ‘WCF Service Library’
4.Give Name as wcfMathServiceLibrary
5.Click OK
2. Delete IService1.cs
and Service1.cs
3. Add IMath.cs and
MathService.cs and add the code listed below
IMath.cs
01
|
using System.Runtime.Serialization;
|
|
02
|
using System.ServiceModel;
|
03
|
||
04
|
namespace WcfMathServLib
|
05
|
{
|
|
06
|
[ServiceContract] //System.ServiceModel
|
07
|
public interface IMath
|
|
08
|
{
|
09
|
[OperationContract]
|
|
10
|
double Add(double i, double j);
|
11
|
[OperationContract]
|
|
12
|
double Sub(double i, double j);
|
13
|
[OperationContract]
|
|
14
|
Complex
AddComplexNo(Complex i, Complex j);
|
15
|
[OperationContract]
|
|
16
|
Complex
SubComplexNo(Complex i, Complex j);
|
17
|
}
|
|
18
|
19
|
//
Use a data contract
|
|
20
|
[DataContract] //using
System.Runtime.Serialization
|
21
|
public class Complex
|
|
22
|
{
|
23
|
private int real;
|
|
24
|
private int imaginary;
|
25
|
||
26
|
[DataMember]
|
27
|
public int Real
{ get; set; }
|
|
28
|
29
|
[DataMember]
|
|
30
|
public int Imaginary
{ get; set; }
|
31
|
}
|
|
32
|
}
|
MathService.cs
01
|
namespace WcfMathServLib
|
|
02
|
{
|
03
|
public class MathService
: IMath
|
|
04
|
{
|
05
|
||
06
|
public double Add(double i, double j)
|
07
|
{
|
|
08
|
return (i
+ j);
|
09
|
}
|
|
10
|
11
|
public double Sub(double i, double j)
|
|
12
|
{
|
13
|
return (i
- j);
|
|
14
|
}
|
15
|
||
16
|
public Complex
AddComplexNo(Complex i, Complex j)
|
17
|
{
|
|
18
|
Complex
result = new Complex();
|
19
|
result.Real
= i.Real + j.Real;
|
|
20
|
result.Imaginary
= i.Imaginary + j.Imaginary;
|
21
|
return result;
|
|
22
|
}
|
23
|
||
24
|
public Complex
SubComplexNo(Complex i, Complex j)
|
25
|
{
|
|
26
|
Complex
result = new Complex();
|
27
|
result.Real
= i.Real - j.Real;
|
|
28
|
result.Imaginary
= i.Imaginary - j.Imaginary;
|
29
|
return result;
|
|
30
|
}
|
31
|
}
|
|
32
|
}
|
4.Modify the
App.config file as shown
App.config
01
|
<?xml version="1.0" encoding="utf-8" ?>
|
|
02
|
<configuration>
|
03
|
||
04
|
<system.web>
|
05
|
<compilation debug="true" />
|
|
06
|
</system.web>
|
07
|
||
08
|
<system.serviceModel>
|
09
|
<services>
|
|
10
|
<service name="WcfMathServLib.MathService">
|
11
|
||
12
|
<host>
|
13
|
<baseAddresses>
|
||
14
|
|||
15
|
</baseAddresses>
|
|
16
|
</host>
|
17
|
||
18
|
<!--
Service Endpoints -->
|
19
|
<endpoint address ="" binding="wsHttpBinding" contract="WcfMathServLib.IMath">
|
||
20
|
<identity>
|
||
21
|
<dns value="localhost"/>
|
|
22
|
</identity>
|
23
|
</endpoint>
|
|
24
|
25
|
<!--
Metadata Endpoints -->
|
||
26
|
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
|
||
27
|
</service>
|
|
28
|
</services>
|
29
|
<behaviors>
|
|
30
|
31
|
<serviceBehaviors>
|
|
32
|
<behavior>
|
33
|
<serviceMetadata httpGetEnabled="True"/>
|
|
34
|
<serviceDebug includeExceptionDetailInFaults="False" />
|
35
|
</behavior>
|
|
36
|
</serviceBehaviors>
|
37
|
</behaviors>
|
|
38
|
39
|
</system.serviceModel>
|
|
40
|
41
|
</configuration>
|
Result Using WCF Test Client
1. Run the WcfMathServLib project you will get the ‘WCF Test Client’
2. Select each method say ‘AddComplexNo’ Give the values in ‘Request’
3. Click on Invoke button
4. See the results in “Response”
Steps for
creating ConsoleMathClient
1. Open Visual Studio
2010 and File->NewProject
2. select Visual C#->Windows in ‘Installed Templates’
3. select ‘Console Application’
4. Give Name as ConsoleMathClient
5. Click OK
2. select Visual C#->Windows in ‘Installed Templates’
3. select ‘Console Application’
4. Give Name as ConsoleMathClient
5. Click OK
2. Go to ‘Solution
Explorer’ Right click on ConsoleMathClient -> Select ‘Add Service
Reference’ the below dialog will be displayed
1. Click on Discover button
2. Give namespace as ‘MathServiceReference’ and click OK
Reference’ the below dialog will be displayed
1. Click on Discover button
2. Give namespace as ‘MathServiceReference’ and click OK
The service reference
will be added now modify the program.cs as shown below.
Program.cs
01
|
using System;
|
|
02
|
using ConsoleMathClient.MathServiceReference;
|
03
|
||
04
|
namespace ConsoleMathClient
|
05
|
{
|
|
06
|
class Program
|
07
|
{
|
|
08
|
static void Main(string[]
args)
|
09
|
{
|
|
10
|
Console.WriteLine("Press
<Enter> to run the client....");
|
11
|
Console.ReadLine();
|
|
12
|
13
|
MathClient
math = new MathClient();
|
|
14
|
Console.WriteLine("Add
of 3 and 2 = {0}", math.Add(3, 2));
|
15
|
Console.WriteLine("Sub
of 3 and 2 = {0}", math.Sub(3, 2));
|
|
16
|
17
|
Complex
no1 = new Complex();
|
|
18
|
no1.Real
= 3;
|
19
|
no1.Imaginary
= 3;
|
|
20
|
21
|
Complex
no2 = new Complex();
|
|
22
|
no2.Real
= 2;
|
23
|
no2.Imaginary
= 2;
|
|
24
|
25
|
Complex
result = new Complex();
|
|
26
|
result
= math.AddComplexNo(no1, no2);
|
27
|
Console.WriteLine("Add
of 3+3i and 2+2i = {0}+{1}i", result.Real, result.Imaginary);
|
|
28
|
29
|
result
= math.SubComplexNo(no1, no2);
|
|
30
|
Console.WriteLine("Sub
of 3+3i and 2+2i = {0}+{1}i", result.Real, result.Imaginary);
|
31
|
||
32
|
Console.ReadLine();
|
33
|
}
|
|
34
|
}
|
35
|
}
|
Result
Compile and Run the
project to see the Result
Another Example:
Add new project to this
Select "WCF Service Library" as shown in above figure.
Delete the two files IService1.cs and Service1.cs
Now add two classes with the names IMyClass.cs and MyClass.cs
Now your solution should look like:
Now define the service contract and operation contract in iMyclass
The sample code is as given,using System;using System.Collections.Generic;using System.Linq;using System.Text;
Select "WCF Service Library" as shown in above figure.
Delete the two files IService1.cs and Service1.cs
Now add two classes with the names IMyClass.cs and MyClass.cs
Now your solution should look like:
Now define the service contract and operation contract in iMyclass
The sample code is as given,using System;using System.Collections.Generic;using System.Linq;using System.Text;
using System.ServiceModel;using System.Runtime.Serialization;
namespace WcfServiceLibrary1
{
[ServiceContract]
public interface IMyClass {
[OperationContract]
string[] Answers(int a, int b);
}
}
Implement that interface in the Myclass
The sample code is as given,using System;using System.Collections.Generic;using System.Linq;using System.Text;
namespace WcfServiceLibrary1
{
public class MyClass : IMyClass { #region IMyClass Members
public string[] Answers(int a, int b)
{
string[] result = new string[5];
if (a > b)
result[0] = a.ToString() + " is greater than " + b.ToString();
else if (a == b)
result[0] = a.ToString() + " is Equal to " + b.ToString();
else result[0] = a.ToString() + " is Smaller than " + b.ToString();
result[1] = "Addition is " + (a + b).ToString();
result[2] = "Multiplication is " + (a * b).ToString();
if (a > b)
{
if (b != 0)
{
result[3] = "Division is " + (a / b).ToString();
}
else {
result[3] = "Division is " + "infinite";
}
}
else if (a < b)
{
if (a != 0)
{
result[3] = "Division is " + (b / a).ToString();
}
else {
result[3] = "Division is " + "infinite";
}
}
else {
if (a != 0 && b != 0)
{
result[3] = "Division is " + "1";
}
else {
result[3] = "Division is " + "infinite";
}
{
[ServiceContract]
public interface IMyClass {
[OperationContract]
string[] Answers(int a, int b);
}
}
Implement that interface in the Myclass
The sample code is as given,using System;using System.Collections.Generic;using System.Linq;using System.Text;
namespace WcfServiceLibrary1
{
public class MyClass : IMyClass { #region IMyClass Members
public string[] Answers(int a, int b)
{
string[] result = new string[5];
if (a > b)
result[0] = a.ToString() + " is greater than " + b.ToString();
else if (a == b)
result[0] = a.ToString() + " is Equal to " + b.ToString();
else result[0] = a.ToString() + " is Smaller than " + b.ToString();
result[1] = "Addition is " + (a + b).ToString();
result[2] = "Multiplication is " + (a * b).ToString();
if (a > b)
{
if (b != 0)
{
result[3] = "Division is " + (a / b).ToString();
}
else {
result[3] = "Division is " + "infinite";
}
}
else if (a < b)
{
if (a != 0)
{
result[3] = "Division is " + (b / a).ToString();
}
else {
result[3] = "Division is " + "infinite";
}
}
else {
if (a != 0 && b != 0)
{
result[3] = "Division is " + "1";
}
else {
result[3] = "Division is " + "infinite";
}
}
if (a > b)
result[4] = "Substraction is " + (a - b).ToString();
else if (a < b)
result[4] = "Substraction is " + (b - a).ToString();
else result[4] = "Substraction is " + "0";
if (a > b)
result[4] = "Substraction is " + (a - b).ToString();
else if (a < b)
result[4] = "Substraction is " + (b - a).ToString();
else result[4] = "Substraction is " + "0";
return result;
} #endregion }
}
Now build the solution. It is necessary that your solution will build; if it doesn't then fix the error(s) then re-build.
Now add one more project to the solution as given below:
Again delete the two files Service1.svc.cs and IService1.cs
Add the reference of the dll which we have generated by building.
Open the service1.svc file and make the changes to make similar to the following line<%@ ServiceHost Language="C#" Debug="true" Service="WcfServiceLibrary1.MyClass"CodeBehind="MyClass.cs %>
Save it.
Now right click and select View in browser. It will show an error. No problem just take the url.
For me it gave the url : http://localhost:54640/Service1.svc
Now right click on web.config and select "Edit WCF Configuration"
Delete the Endpoints (whatever you have) then also delete the service.
Now, click on the "Create a new Service".
Click on the browse button --> Go to bin folder. You will find two Dlls over there ,
Double click both one by one so you can be given this screen,
Select That. And click on next.
Select the contract by repeating above step generally it has been given. Click next button
Select HTTP and click next. Again next.
Now It will ask for the address give the address which we have got I am giving this addresshttp://localhost:54640/Service1.svc
Proceed ahead and click finish.
In the end point section, Give Name Basic
Now Click on the Services it will give you following screen,
} #endregion }
}
Now build the solution. It is necessary that your solution will build; if it doesn't then fix the error(s) then re-build.
Now add one more project to the solution as given below:
Again delete the two files Service1.svc.cs and IService1.cs
Add the reference of the dll which we have generated by building.
Open the service1.svc file and make the changes to make similar to the following line<%@ ServiceHost Language="C#" Debug="true" Service="WcfServiceLibrary1.MyClass"CodeBehind="MyClass.cs %>
Save it.
Now right click and select View in browser. It will show an error. No problem just take the url.
For me it gave the url : http://localhost:54640/Service1.svc
Now right click on web.config and select "Edit WCF Configuration"
Delete the Endpoints (whatever you have) then also delete the service.
Now, click on the "Create a new Service".
Click on the browse button --> Go to bin folder. You will find two Dlls over there ,
Double click both one by one so you can be given this screen,
Select That. And click on next.
Select the contract by repeating above step generally it has been given. Click next button
Select HTTP and click next. Again next.
Now It will ask for the address give the address which we have got I am giving this addresshttp://localhost:54640/Service1.svc
Proceed ahead and click finish.
In the end point section, Give Name Basic
Now Click on the Services it will give you following screen,
Click on link says "click to create"
Again give the name "Basic"
Now go to advanced => Service Behaviour.
Which Gives you following screen
Right click on service behavior and add new .
Click on add button,
Select ServiceMetadata.
Go to top and do like the following screen.
Just save now and exit.
Refresh the url now it will gives you something instead of error.
Actually I have forgotten one setting no problem we will do that now
Again edit web.config by right clicking as done previously.
Try to reach following screen ,
Just enable httpgetenabled so it will look like,
Again save and exit.
Now refresh the page again it is ready to work.
Your refreshed page now look like this,
You can test the wcf from visual studio command prompt by writing
Wcftestclient http://localhost:54640/Service1.svc
Please provide your own url over here.
Now add website to our solution,
Add service reference give namespace that you want to give rest of the thing is simple as we do in the webservice.
Sample code to use this using System;using System.Configuration;using System.Data;using System.Linq;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Xml.Linq;using ServiceReference1;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
{
protected void Page_Load(object sender, EventArgs e)
{
MyClassClient obj = new MyClassClient("Basic");
string[] datas = obj.Answers(5, 10);
foreach (string data in datas)
{
Response.Write(data);
}
}
}
string[] datas = obj.Answers(5, 10);
foreach (string data in datas)
{
Response.Write(data);
}
}
}
Reference Books:
Microsoft Windows
Communication Foundation Step by Step
Microsoft Windows Communication Foundation: Hands-on
No comments:
Post a Comment