by
purushotam
on Tue 08 Apr 2008 21:46 BST
In my
previous post, I have created a WCF service. In this part, I will create a
client to consume the WCF Service created. Since this is an hello world
example, Let's create a web method in WCF service. Todo that, create a
method first on interface and then implement it in the service as shown
in code.
[ServiceContract]
public interface IHelloWorldService
{
[OperationContract]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
// TODO: Add your service operations here
[OperationContract]
string GetGreetings(string name);
}
public class HelloWorldService : IHelloWorldService
{
...
public string GetGreetings(string name)
{
return string.Format("Hello {0}, Welcome to WCF World!", name);
}
....
}
Now, lets create a client to consume this service. I prefer to create a
web client. In order to do this, one needs a service proxy, which will
communicate to the service using Soap as transport mechanism. There are
2 ways to create a proxy.
1. by using Visual Studio
2. by using svcutil.exe utility by WCF framework.
for this example, i will simply use Visual Studio as we used to do
earlier versions of .net. Add a new website by name WCFHelloWorld-Web
and add a service reference and point to the WCF service created as
show shown fig below.

Add namespace of WCF Service to codebehind of aspx file, in this case
ServiceReference1 is the namespace. using this namespace, create a
proxy object as class variable in the aspx.cs file and in aspx file
create some server controls in order to type some input and display as
label. I have created UI as follows:

and in button event handler, pass the textbox input to webservice's
GetGreetings method and display on UI with label as shown below:
using ServiceReference1;
public partial class _Default : System.Web.UI.Page
{
HelloWorldServiceClient proxy = new HelloWorldServiceClient();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSumbit_Click(object sender, EventArgs e)
{
lblGreetings.Text = proxy.GetGreetings(txtName.Text);
}
}
Hit F5 to see the aspx page in browser. Input some name and hit Get
Greetings button, you should be able to see display output as shown in
fig below:

that's it.. simple to create a web cilent and consume a WCF service. I
will take you in depth in next part of this series, until then bye.