DotNet Tutorials

V4 Dot Net Tutorials

Server Intellect Cloud Hosting

 Creating WCF Service of Temp. Conversion in Console C#

This tutorial will show you how to create a Console Application of a WCF Service that will convert Fahrenheit to Celsius (and vice versa), and how to Consume that Service in a Client Console Application. C#

In this tutorial, we are going to look at using WCF (Windows Communication Foundation) to create a Service and a Client in a Console application using C#. We will first create a Console Application that will act as our WCF Service, and then we will consume that within another Console Application, which will be our Client. In order for us to use the Service from the Client, it is required that the Service be running.

This tutorial assumes you are working with Visual Studio 2008, with Windows SDK installed. You can download Windows SDK directly from Microsoft here. We will be using the CMD Shell from SDK to build our Client Application after we have created our Service.
To start, let's create a new project in Visual Studio, Console Application. The first thing we need to do is add a reference to the System.ServiceModel.dll - right-click the References folder in Solution Explorer, and choose to Add Reference. Navigate to the System.ServiceModel entry in the .NET list, and click Ok. Once you've done that, add the following using directives:

using System.ServiceModel;
using System.ServiceModel.Description;

We used over 10 web hosting companies before we found Server Intellect. Their dedicated servers and add-ons were setup swiftly, in less than 24 hours. We were able to confirm our order over the phone. They respond to our inquiries within an hour. Server Intellect's customer support and assistance are the best we've ever experienced.

Now we need to creat our Interface for the WCF Service. We do this with the ServiceContract attribute and by declaring an interface. Then we create a class that inherits from this interface, also creating our two methods:

[ServiceContract(Namespace = "http://DotNetTutorials.Service/")]
public interface ITemperatureConvert
{
[OperationContract]
int FahrenheitToCelsius(int toConvert);
[OperationContract]
int CelsiusToFahrenheit(int toConvert);
}

class TemperatureConvert : ITemperatureConvert
{
public int FahrenheitToCelsius(int toConvert)
{
int fToC = (toConvert - 30) / 2;
Console.WriteLine("Processed: {0}°F to {1}°C.", toConvert, fToC);
return fToC;
}

public int CelsiusToFahrenheit(int toConvert)
{
int cToF = (toConvert * 2) + 30;
Console.WriteLine("Processed: {0}°C to {1}°F.", toConvert, cToF);
return cToF;
}
}

Try Server Intellect for Windows Server Hosting. Quality and Quantity!

Next, we use the default Program class to initialize the Service when it is run, in the Main method. We create an EndPoint, and start the service ready for the Client to consume it.

class Program
{
static void Main(string[] args)
{
Uri baseAddress = new Uri("http://localhost:8000/WCF_Fahrenheit_Celsius_cs");
ServiceHost localHost = new ServiceHost(typeof(TemperatureConvert), baseAddress);

try
{
localHost.AddServiceEndpoint(typeof(ITemperatureConvert), new WSHttpBinding(), "TemperatureConvert");

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

localHost.Open();
Console.WriteLine("TemperatureConvert Service initialized.");
Console.WriteLine("Press the ENTER key to terminate service.");
Console.ReadLine();

localHost.Close();
Console.WriteLine("Service Terminated. Exiting..");
}
catch (CommunicationException ex)
{
Console.WriteLine("Oops! Exception: {0}", ex.Message);
localHost.Abort();
}
}
}

Our next step is to create the Client. Right-click the Solution in Solution Explorer, and choose to Add > New Project, Console Application. Name it TempClient or something similar. Now before we do any coding on the client, we need to build the generatedProxy.cs and the app.config files from the Service. To do this, we will use the CMD Shell and the svcutil tool. Goto the Start Menu > All Programs > Windows SDK > CMD Shell. You should have a Command Prompt up. We need to navigate to the directory of our Client project we just added. To do this, use the cd command: example, cd "C:\Users\Fred.Bloggs\Documents\Visual Studio 2008\Service\ClientApp"

Once in the Client directory, we want to execute the svcutil.exe with the following modifiers:
svcutil.exe /language:cs /out:generatedProxy.cs /config:app.config http://localhost:8000/WCF_Fahrenheit_Celsius_cs

Doing this will generate the generatedProxy.cs and app.config files for us in our Client directory. Once successfully completed, close the CMD Shell, go back to Visual Studio and right-click on the Client Project in Solution Explorer, then choose to Add > Existing Item. Add both newly-generated files.

Finally, we add the logic to the Program.cs of the Client:

static void Main(string[] args)
{
TemperatureConvertClient client = new TemperatureConvertClient();

int fahrenheit;
Console.WriteLine("Enter Fahrenheit to convert to celsius:");
fahrenheit = Convert.ToInt16(Console.ReadLine());
try
{
int toCelsius = client.FahrenheitToCelsius(fahrenheit);
Console.WriteLine("{0}°F is about {1}°C", fahrenheit, toCelsius);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

int celsius;
Console.WriteLine("Enter Celsius to convert to Fahrenheit:");
celsius = Convert.ToInt16(Console.ReadLine());
try
{
int toFahrenheit = client.CelsiusToFahrenheit(celsius);
Console.WriteLine("{0}°C is about {1}°F", celsius, toFahrenheit);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

Console.WriteLine();
Console.WriteLine("Press the ENTER key to terminate client.");
Console.ReadLine();

try
{
client.Close();
}
catch
{}
Console.WriteLine("Client Terminated. Exiting..");
}

We are using Server Intellect and have found that by far, they are the most friendly, responsive, and knowledgeable support team we've ever dealt with!

First, we create a new instance of the Client class which was generated for us in the generatedProxy.cs, and then we call each method from the Service, requesting user input to convert the temperatures. We also use try..catch blocks to handle errors.
NOTE: The service must be running in order for the Client to communicate with it. To do this, right-click on each project in Solution explorer and choose Rebuild. This will build the .exe in the projects bin folder (either debug or release sub-folder). Then we can first execute the Service exe, then the Client exe second.

Download Project Source - Enter your Email to be emailed a link to download the Full Source Project used in this Tutorial!



100% SPAM FREE! We will never sell or rent your email address!