Search This Blog

Showing posts with label WCF. Show all posts
Showing posts with label WCF. Show all posts

2009-12-20

Create Multi Layer Architecture using WCF

WCF is the Microsoft next generation technology for developing distributed applications.WCF is based on SOA.So,if we want to expose our component as a service,we can use WCF to host the service in IIS,WAS,Self Hosting or managed windows service.
In the following example ,the main component is written in CalculateNumber class which contains a method Calculate.The calculate method takes two integer number and return an integer.So this is the component class.
Now we have created CalculateServiceLayer class in the another project to make the component class(CalculateNumber ) to be available in the WCF Host.So in one side ,it will contain System.ServiceModel namespace for WCF and on the other side it will refer the component class CalculateNumber.
Then as we need to host the service we need a console application projectHost) to hosting the service.The Host application configure the necessary settings like address,binding and contract and start the service in a particular address mentioned in the end point.
Now the service is available for invoking.So we will create a client application (web/windows) to invoke the service.
Lets start the step by step development.

Step 1.Create a Class Library Project "CalculateNumber"


Step 2. Write a method in the class and build your component class CalculateNumber.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CalculateNumber
{
public class CalculateNumber
{
public int Calculate(int x, int y)
{
return x + y;
}
}
}


Step 3.Add a new project (Service Layer) in the solution


Step 4.Choose a class library project and put the project name "CalculateServiceLayer".


Step 5.Add a reference of System.ServiceModel and your component class dll i.e CalculateNumber.dll


Step 6.Modify the class name Class1.cs to ICalculateSevice.cs and copy the entire code in place of existing code in Class1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CalculateNumber;
using System.ServiceModel;

namespace CalculateServiceLayer
{
[ServiceContract]
interface ICalculateSevice
{
[OperationContract]
int CalcalculateNumber(int m,int n);
}
}

Step 7.Add an another class file CalculateServiceType.cs and write the following code.Then build your application


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CalculateNumber;
using System.ServiceModel;

namespace CalculateServiceLayer
{
public class CalculateServiceType:ICalculateSevice
{
CalculateNumber.CalculateNumber cn;
#region ICalculateSevice Members

public int CalcalculateNumber(int m, int n)
{
cn=new CalculateNumber.CalculateNumber();
return cn.Calculate(m, n);
}

#endregion
}
}

Step 8.Now add a Host console application in the same solution


Step 9.Add a reference of System.ServiceModel and CalculateServiceLayer.dll.
Open the Program.cs and write the code as follows

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using CalculateServiceLayer;

namespace Host
{
class Program
{
static void Main(string[] args)
{
ServiceHost sh = new ServiceHost(typeof(CalculateServiceLayer.CalculateServiceType));
sh.Open();
Console.WriteLine("The Service is ready to use");
Console.ReadKey(true);
sh.Close();

}
}
}

Step 10.Add an App.config file in your Host project


Step 11.Write the necessary configuration in your App.config file as follows
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="NewBehavior">
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="NewBehavior" name="CalculateServiceLayer.CalculateServiceType">
<endpoint address="basic" binding="basicHttpBinding" bindingConfiguration=""
contract="CalculateServiceLayer.ICalculateSevice" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:3333/" />
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
</configuration>

Step 12.Now your overall solution structure will be as follows


Step 13.Right click on your Host application and click on "Start new instance" under Debug menu


Step 14.You can see the following console output


Step 15.Now create a web application that will invoke the Wcf service.Right click on the Reference and click on "Add service reference".


Step 16.Put the address "http://localhost:3333/" ,click on Go and then select the service and click OK.Before that make sure your host application is running.


Step 17.Now implement the service in your aspx page as follows

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ImplementCalculateNumber
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ServiceReference1.CalculateSeviceClient myproxy = new ImplementCalculateNumber.ServiceReference1.CalculateSeviceClient();
Response.Write(myproxy.CalcalculateNumber(19, 30).ToString());
}
}
}

Step 18.Run your application ,you can see the following output


Step 19.If you modify in the component or service layer,update the service reference in the client (web) application

2009-06-18

Basics Of Windows Communication Foundation

What is WCF?
Windows Communication Foundation (WCF) is an SDK for developing and deploying services on Windows. WCF provides a runtime environment for services, enabling you to expose CLR types as services, and to consume other services as CLR types.
WCF is part of .NET 3.0 and requires .NET 2.0, so it can only run on systems that support it.
WCF is a unification of .NET framework communication technologies which unites the following technologies:-

-NET remoting
-MSMQ
-Web services
-COM+

What is service and client in perspective of data communication?
A service is a unit of functionality exposed to the world. The client of a service is merely the party consuming the service.

What is ABCs Of WCF?
Hosts and Clients communicate with each other by agreeing on the ABCs.ABC indicates three things:
-Address:The location Of the service
-Binding:WCF Ships with a number of different bindings that specify network protocols
-Contract:A description of each method exposed from the WCF Service.

<system.serviceModel>
<services>
<service name="MyNameService" behaviorConfiguration="MyNameServiceBehavior">
<endpoint address="" binding="wsHttpBinding" contract="IMyService"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MyNameServiceBehavior">
<!-- 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="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>

What is endpoint in WCF?
Every service must have Address that defines where the service resides, Contract that defines what the service does and a Binding that defines how to communicate with the service. In WCF the relationship between Address, Contract and Binding is called Endpoint.
The Endpoint is the fusion of Address, Contract and Binding.

What is address in WCF and how many types of transport schemas are there in WCF?
Address is a way of letting client know that where a service is located. In WCF, every service is associated with a unique address. This contains the location of the service and transport schemas.
WCF supports following transport schemas
-HTTP
-TCP
-Peer network
-IPC (Inter-Process Communication over named pipes)
-MSMQ
The sample address for above transport schema may look like
http://localhost:85
http://localhost:85/MyService
net.tcp://localhost:85/MyService
net.pipe://localhost/MyPipeService
net.msmq://localhost/private/MyMsMqService
net.msmq://localhost/MyMsMqService

What is binding and how many types of bindings are there in WCF?
A binding defines how an endpoint communicates to the world. A binding defines the transport (such as HTTP or TCP) and the encoding being used (such as text or binary). A binding can contain binding elements that specify details like the security mechanisms used to secure messages, or the message pattern used by an endpoint.

WCF supports nine types of bindings.
-Basic binding
Offered by the BasicHttpBinding class, this is designed to expose a WCF service as a legacy ASMX web service, so that old clients can work with new services. When used by the client, this binding enables new WCF clients to work with old ASMX services.

-TCP binding
Offered by the NetTcpBinding class, this uses TCP for cross-machine communication on the intranet. It supports a variety of features, including reliability, transactions, and security, and is optimized for WCF-to-WCF communication. As a result, it requires both the client and the service to use WCF.

-Peer network binding
Offered by the NetPeerTcpBinding class, this uses peer networking as a transport. The peer network-enabled client and services all subscribe to the same grid and broadcast messages to it.

-IPC binding
Offered by the NetNamedPipeBinding class, this uses named pipes as a transport for same-machine communication. It is the most secure binding since it cannot accept calls from outside the machine and it supports a variety of features similar to the TCP binding.

-Web Service (WS) binding
Offered by the WSHttpBinding class, this uses HTTP or HTTPS for transport, and is designed to offer a variety of features such as reliability, transactions, and security over the Internet.

-Federated WS binding
Offered by the WSFederationHttpBinding class, this is a specialization of the WS binding, offering support for federated security.

-Duplex WS binding
Offered by the WSDualHttpBinding class, this is similar to the WS binding except it also supports bidirectional communication from the service to the client.

-MSMQ binding
Offered by the NetMsmqBinding class, this uses MSMQ for transport and is designed to offer support for disconnected queued calls.

-MSMQ integration binding
Offered by the MsmqIntegrationBinding class, this converts WCF messages to and from MSMQ messages, and is designed to interoperate with legacy MSMQ clients.

What are contracts in WCF?
In WCF, all services expose contracts. The contract is a platform-neutral and standard way of describing what the service does.

WCF defines four types of contracts.

-1.Service contracts:
Describe which operations the client can perform on the service.
There are two types of Service Contracts.
--a)ServiceContract - This attribute is used to define the Interface.
--b)OperationContract - This attribute is used to define the method inside Interface.
[ServiceContract]
interface IMyContract
{
[OperationContract]
string MyMethod( );
}
class MyService : IMyContract
{
public string MyMethod( )
{
return "Hello World";
}
}

-2.Data contracts:Define which data types are passed to and from the service. WCF defines implicit contracts for built-in types such as int and string, but we can easily define explicit opt-in data contracts for custom types.

There are two types of Data Contracts.
--a)DataContract - attribute used to define the class
--b)DataMember - attribute used to define the properties.
[DataContract]
class Contact
{
[DataMember]
public string FirstName;

[DataMember]
public string LastName;
}
If DataMember attributes are not specified for a properties in the class, that property can't be passed to-from web service.

-3.Fault contracts:Define which errors are raised by the service, and how the service handles and propagates errors to its clients.

-4.Message contracts :Allow the service to interact directly with messages. Message contracts can be typed or untyped, and are useful in interoperability cases and when there is an existing message format we have to comply with.

Where we can host WCF services?
Every WCF services must be hosted somewhere. There are three ways of hosting WCF services.

They are

-1. IIS
-2. Self Hosting
-3. WAS (Windows Activation Service)

How to deal with operation overloading while exposing the WCF services?
By default overload operations (methods) are not supported in WSDL based operation. However by using Name property of OperationContract attribute, we can deal with operation overloading scenario.
[ServiceContract]
interface ICalculator
{
[OperationContract(Name = "AddInt")]
int Add(int arg1,int arg2);

[OperationContract(Name = "AddDouble")]
double Add(double arg1,double arg2);
}

What is the difference WCF and Web services?
-Web services can only be invoked by HTTP. While WCF Service or a WCF component can be invoked by any protocol and any transport type. Second web services are not flexible. However, WCF Services are flexible.
-If you make a new version of the service then you need to just expose a new end. Therefore, services are agile and which is a very practical approach looking at the current business trends.

How to set the timeout property for the WCF Service client call?
The timeout property can be set for the WCF Service client call using binding tag.
<client>
<endpoint
...
binding = "wsHttpBinding"
bindingConfiguration = "LongTimeout"
...
/>
</client>
<bindings>
<wsHttpBinding>
<binding name = "LongTimeout" sendTimeout = "00:04:00"/>
</wsHttpBinding>
</bindings>
If no timeout has been specified, the default is considered as 1 minute.

What is Proxy and how to generate proxy for WCF Services?
The proxy is a CLR class that exposes a single CLR interface representing the service contract. The proxy provides the same operations as service's contract, but also has additional methods for managing the proxy life cycle and the connection to the service. The proxy completely encapsulates every aspect of the service: its location, its implementation technology and runtime platform, and the communication transport.

The proxy can be generated using Visual Studio by right clicking Reference and clicking on Add Service Reference. This brings up the Add Service Reference dialog box, where you need to supply the base address of the service (or a base address and a MEX URI) and the namespace to contain the proxy.

Proxy can also be generated by using SvcUtil.exe command-line utility. We need to provide SvcUtil with the HTTP-GET address or the metadata exchange endpoint address and, optionally, with a proxy filename. The default proxy filename is output.cs but you can also use the /out switch to indicate a different name.

SvcUtil http://localhost/MyService/MyService.svc /out:Proxy.cs

When we are hosting in IIS and selecting a port other than port 80 (such as port 88), we must provide that port number as part of the base address:

SvcUtil http://localhost:88/MyService/MyService.svc /out:Proxy.cs
-------------------------------------------------------------------------------------
Resource:http://www.dotnetfunda.com/interview/ShowCatQuestion.aspx?start=0&page=1&category=74

2009-06-17

Create A Step by Step WCF Application

This is a getting started tutorial to Windows Communication Foundation(WCF) Service.The followinh application provide two services
-1.getName:Which will take two input string parameter first name and the last name and returns a string which is a concatination of both two input string
-2.getMessage:Which will take one input string parameter and returns the same string appending another string "Message :" as a prefix

I have used Microsoft Visual Web Developer 2008 Express Edition for creating service and Microsoft Visual C# 2008 Express Edition for creating a windows application to invoke that service.
So it is very Simple.Let's Start

Step 1.Create New WCF Service
Open Microsoft Visual Web Developer 2008 Express Edition to create a New Website
Go to File->New Web Site and you will see a template called WCF Service.Select this template and put "MyWCFService" as a File Name



Step 2.Define ServiceContract and OperationContract
Open the IService.cs under App_Code,Delete all lines of code except the namespace portion and copy the following code after namespace.
[ServiceContract]
public interface IMyService
{
[OperationContract]
string getName(string fName, string lName);
[OperationContract]
string getMessage(string Message);
}

Step 3.Implement the Service
Open Service.cs under App_Code ,similarly delete all lines of code except the namespace.Create a new class MyNameService and implement IMyService.

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

public class MyNameService : IMyService
{
#region IMyService Members

public string getName(string fName, string lName)
{
return fName + " " + lName;
}

public string getMessage(string Message)
{
return "Message :" + Message;
}
#endregion
}

Step 4.Create Service Defination File(.SVC)
Open Service.svc change service to "MyNameService".
<%@ ServiceHost Language="C#" Debug="true" Service="MyNameService" CodeBehind="~/App_Code/Service.cs" %>

Step 5.Edit web.config file for service hosting
Go to web.config.Within system.serviceModel you have a services.Under services you will get service tag,
-Change the name to "MyNameService" which is a user defined class under Service.cs that impement IMyService.
-Change the behaviorConfiguration to MyNameServiceBehavior
Go to the end point tag within service tage,
-Change contract to IMyService which is the name of your interface.

Step 6.Enable metadata for client access
Within this web.config file go To serviceBehaviors under behaviors,Go To behavior tag
-Within the behavior tag change the name to MyNameServiceBehavior which you have mention in the behaviorConfiguration at step 5.
-Within serviceDebug tag set includeExceptionDetailInFaults=true

The system.serviceModel will look like as follows(Step 5 and Step 6)

<system.serviceModel>
<services>
<service name="MyNameService" behaviorConfiguration="MyNameServiceBehavior">
<endpoint address="" binding="wsHttpBinding" contract="IMyService"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MyNameServiceBehavior">
<!-- 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="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>

Step 7.Build and Test the application
Select Service.svc and right click.Click on "Set As Start Page"
Now run your application by clicking F5.You can see the following page when you run it.


Step 8.Generate a configuration file and a code file that contains the client class


Go to command prompt (type cmd in Start menu->run)

To go to the folder which contain SvcUtil.exe,Type
cd C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin

run the following command
svcutil.exe http://localhost:1805/MyWCFService/Service.svc?wsdl
You can get the url from the output window(web site) generated at step 7

After executing the command ,you will get following two files within the folder C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin or the folder which contain SvcUtil.exe

-1.MyNameService.cs
-2.output.config

Step 9.Create A client application which will invoke your WCF Service
Create a windows application "MyWCFClient" in different .NET IDE

Step 10.Add Service Reference
Right click on your solution and click on "Add Service Reference"



Put the URL generated at step 7.
Click on GO.
Type "MyServiceReference" in a Namespace textbox.


Now Click OK
Now it will generate/Modify two files
-MyServiceReference under Service References folder
-app.config

Step 11.Copy Configuratin and code file
Copy MyNameService.cs and output.config generated at Step 8. Paste it in the root folder of your windows application(MyWCFClient)

Step 12.Invoke the WCF Service
Call your WCF Service(MyService) in a button click event.Create an object of MyServiceClient and call two methods getName and getMessage that is declared in IMyService at step 2 and implemented in MyNameService at step 3

private void button1_Click(object sender, EventArgs e)
{
MyServiceClient msc = new MyServiceClient();
MessageBox.Show(msc.getName("Manab", "Basu"));
MessageBox.Show(msc.getMessage("Tested"));
}

Step 13.Modify the app.config
Open the app.config and go to the endpoint tage within client under system.serviceModel.
Modify contract="MyServiceReference.IMyService" to contract="IMyService"

The file will look like as follows
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_IMyService" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
allowCookies="false">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<reliableSession ordered="true" inactivityTimeout="00:10:00"
enabled="false" />
<security mode="Message">
<transport clientCredentialType="Windows" proxyCredentialType="None"
realm="" />
<message clientCredentialType="Windows" negotiateServiceCredential="true"
algorithmSuite="Default" establishSecurityContext="true" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:1805/MyWCFService/Service.svc"
binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IMyService"
contract="MyServiceReference.IMyService" name="WSHttpBinding_IMyService">
<identity>
<userPrincipalName value="manuba@wipro.com" />
</identity>
</endpoint>
</client>
</system.serviceModel>
</configuration>

Step 14.Run your client application
Run your windows application and clik on the button


So now you can see that the WCF is so simple :)

2009-06-15

Advantages of WCF over Webservice

Following are the few key points which describes the advantages of WCF over Webservice
  • WCF has support for multiple protocols (TCP/IP, HTTP, PIPE, MSMQ etc.)
  • WCF can be hosted outside if IIS ie: can be hosted in managed windows applications, a windows service, and WAS (Windows Process Activation Service)
  • WCF provides customisation such as event hooks into service start / end / init / custom global error Handling etc. etc.