Monday, 18 July 2011

Introduction to WCF in ASP.NET and VB.NET


This tutorial will guide you through creating and consuming your first WCF Service using Visual Studio 2008 and VB.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.vb in the App_Code folder, and a Service1.svc in the root. Firstly, our .svc file will look like this:

<%@ ServiceHost Language="VB" Debug="true" Service="Service1" CodeBehind="~/App_Code/Service1.vb" %>

The Service1.vb file will look something like this:

Imports System.ServiceModel
Imports System.ServiceModel.Activation
Imports System.ServiceModel.Web

<ServiceContract(Namespace:="")> _
<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)> _
Public Class Service1

' Add <WebGet()> attribute to use HTTP GET
<OperationContract()> _
Public Sub DoWork()
' Add your operation implementation here
End Sub

' Add more operations here and mark them with <OperationContract()>
End Class

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!

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 Shared Function Hello(ByVal theString As String) As String
Return "Hello, " & theString & "."
End Function

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" /><br />
<asp:Literal ID="lit_Display" runat="server" />

Nothing much different to a regular ASP.NET Web Application here. We need to include a handler for the button's click event. In the code-behind we will reference the Service to call the method we created earlier:

Protected Sub btn_Submit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_Submit.Click
lit_Display.Text = Service1.Hello(fld_String.Text)
End Sub

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.

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 an Imports directive to the top of the page, Imports 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" /><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>

We moved our web sites to Server Intellect and have found them to be incredibly professional. Their setup is very easy and we were up and running in no time.

Notice we have an onclick handler, where 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.vb 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 Function HelloJS(ByVal theString As String) As String
Return "Hello, " & theString & "."
End Function

We migrated our web sites to Server Intellect over one weekend and the setup was so smooth that we were up and running right away. They assisted us with everything we needed to do for all of our applications. With Server Intellect's help, we were able to avoid any headaches!

Our entire Service1.vb will look something like this:

Imports System.ServiceModel
Imports System.ServiceModel.Activation
Imports System.ServiceModel.Web

<ServiceContract(Namespace:="")> _
<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)> _
Public Class Service1

' Add <WebGet()> attribute to use HTTP GET
<OperationContract()> _
Public Sub DoWork()
' Add your operation implementation here
End Sub

' Add more operations here and mark them with <OperationContract()>
<OperationContract()> _
Public Shared Function Hello(ByVal theString As String) As String
Return "Hello, " & theString & "."
End Function

<OperationContract()> _
Public Function HelloJS(ByVal theString As String) As String
Return "Hello, " & theString & "."
End Function
End Class

No comments:

Post a Comment