Tuesday, May 8, 2012

Your first WCF Service - Step by step

Today I'm gonna make a demo for those who want to step into the world of WCF. I'm not going into details about what is WCF. In short, it is a platform to build distributed applications using a unified modeling language.

Step 1. Create a new WCF Service Application
Open Visual Studio -> File-> New -> Project. Select from the WCF panel a WCF Service Application and give it a name. Mine is called Service1.


Step 2. Configure the service using the confiugration file
In the newly created project double click the Web.config file. Here we will have to add a service element an endpoint element and a binding. This step is not mandatory because Wcf creates by default an endpoint and a service, but for the sake of this exercise I will create new elements. 

The Binding - this is where we specify what protocol do we use (http, tcp, etc.), how our data is formatted, what security do we use for sending the message and other things. So first we create a bindings element where we will use a wsHttpBinding like so:
<bindings>
<wsHttpBinding>
<binding name="MyBinding">

<security mode="None">
</security>

</binding>
</wsHttpBinding>
</bindings>


The Service - here we add our endpoints and configure the service behavior if we have one
<services>
<service

</service>
</services>

The EndPoints - The endpoint is a structure where we have to specify the Address, Binding  and Contract.
Address - the location (url) where we find the endpoint
Binding - the protocol and other settings that are used to transport data
Contract - the interface (set of operations) that is exposed through this endpoint.
Inside the <service> tag add the definition of the endpoint:
<service name="WcfServiceBlog.Service1">
<endpoint address="" binding="wsHttpBinding" bindingConfiguration="MyBinding" contract="WcfServiceBlog.IService1">
</service>
</endpoint>

Our service is ready.

Step 3. Create a client that consumes the service
Create a new console application. Expand the project, Right click on References -> Add Service Reference
A popup should appear where you have to enter the url of the service. Because the service is in the same solution you can click the Discover button.

After your service is discovered, select it and click Ok. In thi moment the tools of visual studio would create the necessary proxy classes so that we can use the service.
In the Main program write the following code:
static void Main(string[] args)
{
using (ServiceReference1.Service1Client proxy = new ServiceReference1.Service1Client())
{
Console.WriteLine(proxy.GetData(10));
}
Console.ReadLine();
}

Set your client application as a startup project. Right click on project -> Set as startup project.
Run your first wcf service application! :)

0 comments:

Post a Comment