Tuesday 3 May 2011

Creating a WCF service

Introduction

To begin with, we are going to create a very simple WCF service and WCF client in C#/VB.NET first. After this article, we will have a working WCF application. Then in the next article, we will create a Java client to connect to the WCF service created in this article.

Creating a WCF service

Using Visual Studio 2008, we can easily create Windows Communication Foundation (WCF) service and client. This topic describes how to create a basic WCF service and a client that can call the service.
To create a basic WCF service, please follow the steps below:
1. Open Visual Studio 2008.
2. Create a new WCF Service Application project. In Visual Studio 2008, click menu File -> New -> Project. In the New Project dialog, expand Visual Basic or Visual C# and choose the WCF Service Application template to create a project named “WcfService1″. Click OK.

Now, we have created a basic WCF service application. In Solution Explorer, we can see four files in the “WcfService1″ project.

File
Description
IService1.cs
IService1 interface, a WCF service contract
Service1.svc
A service file, accessed by the client as a part of URL
Service1.svc.cs
A class, implements the IService1interface
Web.config
Service configuration file

In the “Service1.svc.cs” file, we can find a class named “Service” which includes two functions, “GetData” and “GetDataUsingDataContract”.
You can create a new service or add more functions to the existing service. I will talk about these in the future. Now we can run the server in the Debug mode. The ASP.NET Deployment Server will start and the service will be deployed to the server:

Creating a WCF client

To create a WCF client that calls the service, please follow the steps below:
1. Open Visual Studio 2008.
2. Create a new Console Application project. In Visual Studio 2008, click menu File -> New -> Project. In the New Project dialog, expand Visual Basic or Visual C# and choose the Console Application template to create a project named “WcfClient1″. Click OK.

3. Add a service reference to the project. Go to Solution Explorer, right-click the “References” node in the “WcfClient1″ project, and click Add Service Reference.

4. In the Add Service Reference dialog, input the server URL above in Address. Click Go and then click OK.

5. We can find a node named “ServiceReference1″ under Service References.

6. Add a using statement (Imports in Visual Basic) for the System.ServiceModel namespace in the generated “Program.cs” file.
using System.ServiceModel;
7. Add the following code into the Main function in the “Program.cs” file:
Service1Client client = new Service1Client();
String strResponse = client.GetData(100);
Console.WriteLine(strResponse);
Console.ReadLine();
client.Close();

8. Then we can run the client application in the Debug mode. If we see the following result, our WCF application is working properly.

No comments:

Post a Comment