Sunday, May 03, 2009

First WCF server/client app

After a lot of trial and errors I was finally able to get the server and client running, here’s my code

I have a dll referenced in server which has the Service1 and IService1

Server:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using WcfServiceLibrary1;
using System.ServiceModel.Description;

namespace WCFServer
{
class Program
{
static void Main(string[] args)
{
ServiceHost h = new ServiceHost(typeof(Service1));
h.AddServiceEndpoint(typeof(IService1), new NetTcpBinding(), "net.tcp://localhost:8080/service");

ServiceMetadataBehavior metadataBehavior;
metadataBehavior = h.Description.Behaviors.Find();
if (metadataBehavior == null)
{
metadataBehavior = new ServiceMetadataBehavior();
metadataBehavior.HttpGetUrl = new Uri("http://localhost:8001/service");
metadataBehavior.HttpGetEnabled = true;
metadataBehavior.ToString();
h.Description.Behaviors.Add(metadataBehavior);
}

h.Open();
Console.Read();
h.Close();
}
}
}


In the server, the metadata behavior is important, coz thats the only way to discover all the available bindings, so if you dont have metadata, your client will never be able to discover your service.

Once your server is up and running, you need to add the service reference, to do that - enter the service URL as http://localhost:8001/service and hit Ok, visual studio will generate the proxy classes, config file and give you Service1Client class using which you can invoke operations such as GetData.

Client:



static void Main(string[] args)
{
Service1Client c = new Service1Client();
string s = c.GetData(5);
}


Technorati Tags:

No comments: