Friday, September 4, 2009

WCF Service, C#

I wanted to create a WCF service in C#.

Communication was the problem. After creating the service, and implementing the method properly, you must either create a new project in the solution or have a console implementation in the project with the service. In order to communication with the service you must have a console.

This is on the SERVICE side.

using System.ServiceModel;
using System.ServiceModel.Description;
using [SolutionNamespace].[NamespaceList].SimpleService;

class Program
{
static void Main(string[] args)
{
Uri baseAddr = new Uri("http://localhost:8080/SimpleService.svc");
ServiceHost localHost = new ServiceHost(typeof(SimpleService), baseAddr);

try
{
localHost.AddServiceEndpoint(typeof(ISimpleService), new WSHttpBinding(), "SimpleName");

ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
localHost.Description.Behaviors.Add(smb);

localHost.Open();

Console.WriteLine("Server's up...");
Console.ReadLine();
localHost.Close();
}
catch (Exception ex)
{

}
}
}

SimpleService is the class that implements ISimpleService. ISimpleService is the ServiceContract for WCF. "SimpleName" is just a name string.



For the client, you must add a Service Reference to the WCF service. You can name it what ever, but every example I have seen has named it exactly what the service implementation is called. This was quite confusing. You can reference this service inside your console class. SimpleService is the name of the reference inside the CLIENT.
The namespace is the reference to the Service References that the service is referenced by.

This is the CLIENT side.

using [SolutionNamespace].[namespaceList].SimpleService;

class Program
{
static void Main(string[] args)
{
SimpleService client = new SimpleService();

try
{
string data = client.GetData(1);
Console.Write(">:" + data);
Console.ReadKey();
}
catch (Exception ex)
{

}
}
}

This will allow the two to communication between solutions.

No comments:

Post a Comment