Monday 6 February 2012

What is WCF ? And Example.

This tutorial will guide you through creating and consuming your first WCF Service using Visual Studio 2008 and C#.NET


This tutorial was created with Microsoft Visual Studio .NET 2008 using WCF. WCF was implemented into the .NET Framework in 3.0, and received an update in 3.5, this tutorial is directed at users of Visual Studio.NET 2008 and ASP.NET 3.5
WCF (or Windows Communication Foundation) is a union of technologies developed by Microsoft to make it easier and quicker for developers to build distributed applications. WCF builds on the existing technologies of ASMX, .NET Remoting, MSMQ and DCOM. WCF attempts to unify these technologies and harness the power of all, while simplifying the process of implementation.
In this tutorial, we will show how to create a WCF Service, and how to consume it within an ASPX page. To demonstrate WCF, we will create a simple Operation Contract, which is similar to a Web Method, that we will call from our ASPX page. We can even expose the methods of the service to JavaScript, so that we can use them client-side.
To begin, create a new web application in Visual Studio. Then in Solution Explorer, right-click the Project and choose to Add New Item.. AJAX-enabled WCF Service, name it Service1. This should create a Service1.cs in the App_Code folder, and a Service1.svc in the root. Firstly, our .svc file will look like this:

<%@ ServiceHost Language="C#" Debug="true" Service="Service1" CodeBehind="~/App_Code/Service1.cs" %>
The Service1.cs file will look something like this:

using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1
{
// Add [WebGet] attribute to use HTTP GET
[OperationContract]
public void DoWork()
{
// Add your operation implementation here
return;
}

// Add more operations here and mark them with [OperationContract]
}
Need help with Windows Dedicated Hosting? Try Server Intellect. I'm a happy customer!
Notice the OperationContract attributes. We use this attribute to define the method as part of the WCF Service Contract.
Let's go ahead and add a simple method to demonstrate how to use it:

[OperationContract]
public static String Hello(String theString)
{
return "Hello, " + theString + ".";
}
Here, we are expecting an input parameter of type String, and we are also returning a String. A simple method to demonstrate how we can consume the WCF Service.
Going back to our ASPX page, we will create a Literal control, a TextBox control and a Button - all ASP controls:

<asp:TextBox ID="fld_String" runat="server" /><br />
<asp:Button ID="btn_Submit" runat="server" Text="Submit" OnClick="btn_Submit_Click" /><br />
<asp:Literal ID="lit_Display" runat="server" />
Nothing much different to a regular ASP.NET Web Application here. Notice we include the handler for the button. In the code-behind we will reference the Service to call the method we created earlier:

protected void btn_Submit_Click(object sender, EventArgs e)
{
lit_Display.Text = Service1.Hello(fld_String.Text);
}
Server Intellect assists companies of all sizes with their hosting needs by offering fully configured server solutions coupled with proactive server management services. Server Intellect specializes in providing complete internet-ready server solutions backed by their expert 24/365 proactive support team.
We did not wrap our Service1 class in a namespace, but in a real-world scenario it would most likely be beneficial to do so. If this was the case, we would have to reference the Service1 as Namespace.Service1, or simply add a using directive to the top of the page, using Namespace.Service1 for example.
Now if this application is run, you will see that we can input our name and upon button click, the WCF Service will be accessed and we will receive our return string. This all happens very quickly, but there is still a noticeable postback. We can work around this postback by AJAX-enabling the ASPX page, and also exposing the Service to Client-Side JavaScript.
To do this, we will need to add a Service reference to a ScriptManager on the page, like so:

<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/Service1.svc" />
</Services>
</asp:ScriptManager>
By doing this, we make the ScriptManager manage all of our calls behind the scenes, and allow it to access the WCF Service we created earlier. This means that we can use Client-Side JavaScript to access the Methods of the Service. We will also add an UpdatePanel for the existing ASP.NET Controls, and then create some regular HTML form elements:

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/Service1.svc" />
</Services>
</asp:ScriptManager>

<asp:UpdatePanel ID="UP1" runat="server">
<ContentTemplate>
Call from Code-Behind:<br />
<asp:TextBox ID="fld_String" runat="server" /><br />
<asp:Button ID="btn_Submit" runat="server" Text="Submit" OnClick="btn_Submit_Click" /><br />
<asp:Literal ID="lit_Display" runat="server" />
<br /><br />
</ContentTemplate>
</asp:UpdatePanel>
Call from JavaScript: <br />
<input type="text" name="jsString" /><br />
<input type="button" name="jsSubmit" value="Submit" onclick="DisplayName()" />
</form>
Server Intellect offers Windows Hosting Dedicated Servers at affordable prices. I'm very pleased!
Notice again we have an onclick handler, but this time, we are calling a JavaScript function instead of a code-behind method. We will include the following JavaScript at the bottom of the page:

<script language="javascript" type="text/javascript">
function DisplayName() {
Service1.HelloJS(document.getElementById('jsString').value, onSuccess);
}

function onSuccess(string) {
alert(string);
}
</script>
The function we call from the button click, DisplayName, in turn calls a Service method. Because the ScriptManager has the Service Reference, the Service methods are exposed to page level. We also pass the onSuccess function to display the return string in a JavaScript alert box.
Finally, let's move back to the Service1.cs to add our second method, which is being called by JavaScript. It will be just the same as the last one, except not a static method:

[OperationContract]
public String HelloJS(String theString)
{
return "Hello, " + theString + ".";
}
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!
Our entire Service1.cs will look something like this:

using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1
{
// Add [WebGet] attribute to use HTTP GET
[OperationContract]
public void DoWork()
{
// Add your operation implementation here
return;
}

// Add more operations here and mark them with [OperationContract]
[OperationContract]
public static String Hello(String theString)
{
return "Hello, " + theString + ".";
}

[OperationContract]
public String HelloJS(String theString)
{
return "Hello, " + theString + ".";
}
}

No comments:

Post a Comment