Developing a WCF Service Library and Hosting it with a Custom App Using VS2K8

In this article, we will focus on developing a Windows Communication Foundation (WCF) library, hosting it using a custom application and finally test it by developing a simple WCF client using Windows Forms. This article can serve as an excellent walk through resource for beginners.

Contributed by
Rating: 5 stars5 stars5 stars5 stars5 stars / 8
October 02, 2007
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

A downloadable zip file is available for this article.

In my previous article, we focused on developing a Windows Communication Foundation (WCF) library, turning it into a WCF web service, hosting it on an IIS web server and finally tested it by developing a simple WCF client using Windows Forms. This article is quite different from the previous one as we will develop a custom application from scratch to host a WCF library.

Please be aware that we are not directly creating a WCF web service in this article. In fact, Visual Studio 2008 beta 2 includes two templates, "WCF Service Application" and "WCF Service Library." "WCF Service Application" itself is a direct web service application relying on WCF technology (which is similar to the ASP.NET web service development). "WCF Service Library" however is a compiled component which can be deployed as a web service or a Windows service or even as a part of a customized hosting application.

If you have not configured IIS after installing Visual Studio 2008 beta 2, it is highly advised that you run the following (for proper mappings and automated IIS configuration):

ServiceModelReg.exe /i /x

The entire source code for this article is available in the form of a downloadable zip file. The solution was developed using Microsoft Visual Studio 2008 Beta 2 on Microsoft Windows Server 2003 Enterprise Edition. I didn't really test it in any other environment. I request that you post in the discussion area if you have any problems with execution.

Creating a WCF Service Library

The following are the steps required to create a WCF Service Library:

  • Open Microsoft Visual Studio 2008 Beta 2

  • Go to File || New Project

  • In the "New Project" dialog box, open "Visual Basic" project types and select WCF. The respective templates for WCF will be shown on the right side.

  • Select the "WCF Service Library" template.

  • Provide  "WCFSampleService" as the name and provide the proper path as the location.

  • Make sure that ".NET Framework 3.5" is selected at the top.

  • Once everything looks like the following (fig 01), click OK.

  • Rename "IService1.vb" to "IProductService.vb."

  • Rename "Service1.vb" to "ProductService.vb."

Creating a WCF Service Library: application configuration

As we created a WCF Service Library (instead of a WCF Service Application), Visual Studio adds an "app.config" file (as opposed to a "web.config" file in a WCF Service Application) to the solution. Modify the "app.config" file to match the following:

<system.serviceModel>

<services>

<service name="NorthwindService.ProductService"
behaviorConfiguration="NorthwindService.ProductServiceBehavior">

<host>

<baseAddresses>

<add baseAddress="http://localhost:8181/ProductService" />

</baseAddresses>

</host>

<!-- Service Endpoints -->

<!-- Unless fully qualified, address is relative to base address supplied
above
-->

<endpoint address="" binding="wsHttpBinding"
contract="NorthwindService.IProductService" />

<!-- Metadata Endpoints -->

<!-- The Metadata Exchange endpoint is used by the service to describe
itself to clients.
-->

<!-- This endpoint does not use a secure binding and should be secured or
removed before deployment
-->

<endpoint address="mex" binding="mexHttpBinding"
contract="IMetadataExchange" />

</service>

</services>

<behaviors>

<serviceBehaviors>

<behavior name="NorthwindService.ProductServiceBehavior">

<!-- To avoid disclosing metadata information, set the value below to
false and remove the metadata endpoint above before deployment
-->

<serviceMetadata httpGetEnabled="True"/>

<!-- To receive exception details in faults for debugging purposes, set
the value below to true. Set to false before deployment 
to avoid
disclosing exception information
-->

<serviceDebug includeExceptionDetailInFaults="True" />

</behavior>

</serviceBehaviors>

</behaviors>

</system.serviceModel>

Now it is time to specify the connection string. Using Solution Explorer, right click on project and go to properties (Fig 02):

Within the project properties, open the Settings tab and add a new setting with the name "cnNorthwind," "Type" as "String", "Scope" as "Application" and "Value" as required connection string (to connect to database) as shown below (Fig 03):

Creating a WCF Service Library: source code

Once the project is created and configured (as shown in previous sections), modify "IProductService.vb" to match the following:

<ServiceContract()> _

  Public Interface IProductService

<OperationContract()> _

  Function GetProductInfo(ByVal ProductID As Integer) As Product

<OperationContract()> _

  Function GetProductNames() As List(Of String)

End Interface

<DataContract()> _

  Public Class Product

   Private _ProductID As Integer

   Private _ProductName As String

   Private _UnitPrice As Double

   Private _UnitsInStock As Integer

   Private _UnitsOnOrder As Integer

<DataMember()> _

  Public Property ProductID() As Integer

   Get

    Return _ProductID

   End Get

    Set(ByVal value As Integer)

     _ProductID = value

    End Set

End Property

<DataMember()> _

  Public Property ProductName() As String

   Get

    Return _ProductName

   End Get

    Set(ByVal value As String)

     _ProductName = value

    End Set

End Property

<DataMember()> _

  Public Property UnitPrice() As Double

   Get

    Return _UnitPrice

   End Get

    Set(ByVal value As Double)

     _UnitPrice = value

    End Set

End Property

<DataMember()> _

  Public Property UnitsInStock() As Integer

  Get

   Return _UnitsInStock

  End Get

   Set(ByVal value As Integer)

    _UnitsInStock = value

   End Set

End Property

<DataMember()> _

  Public Property UnitsOnOrder() As Integer

   Get

    Return _UnitsOnOrder

   End Get

     Set(ByVal value As Integer)

      _UnitsOnOrder = value

     End Set

End Property

End Class

Modify "ProductService.vb" to match the following:

  Imports System.Data

  Imports System.Data.SqlClient

   Public Class ProductService

   Implements IProductService

Public Function GetProductInfo(ByVal ProductID As Integer) As Product Implements IProductService.GetProductInfo

  Using cn As New SqlConnection(My.Settings.cnNorthwind)

Using cmd As New SqlCommand("SELECT ProductID, ProductName, UnitPrice, UnitsInStock, UnitsOnOrder FROM dbo.Products WHERE ProductID=" & ProductID, cn)

  cmd.Connection.Open()

   Using rdr As SqlDataReader = cmd.ExecuteReader

    If rdr.Read() Then

Return New Product With {.ProductID = rdr(rdr.GetOrdinal("ProductID")), .ProductName = rdr(rdr.GetOrdinal("ProductName")) & "", .UnitPrice = rdr(rdr.GetOrdinal("UnitPrice")) & "", .UnitsInStock = rdr(rdr.GetOrdinal("UnitsInStock")) & "", .UnitsOnOrder = rdr(rdr.GetOrdinal("UnitsOnOrder")) & ""}

   Else

     Return Nothing

   End If

End Using

   cmd.Connection.Close()

  End Using

 End Using

End Function

Public Function GetProductNames() As System.Collections.Generic.List(Of
String) Implements IProductService.GetProductNames

  Dim ProductNames As New List(Of String)

   Using cn As New SqlConnection(My.Settings.cnNorthwind)

  Using cmd As New SqlCommand("SELECT ProductName FROM dbo.Products", cn)

   cmd.Connection.Open()

    Using rdr As SqlDataReader = cmd.ExecuteReader

     If rdr.HasRows Then

      While rdr.Read

       ProductNames.Add(rdr(rdr.GetOrdinal("ProductName")))

      End While

       Return ProductNames

     Else

       Return Nothing

    End If

End Using

   cmd.Connection.Close()

  End Using

 End Using

End Function

End Class

Build the project

Developing a custom application to host the WCF: creation and configuration

To host the previous WCF Service Library, I want my own custom application to be developed using Windows Forms. The following is the walk through:

  • Go to File || Add || New Project.

  • Select "Windows Forms Application" as template, provide "Name" as "NorthwindServiceHost" at the same solution location as shown below (Fig 04).

  • Design the form with two buttons (for Start and Stop service) and a label (for messaging).

  • Add an "app.config" file using "Add new Item" as shown below (Fig 05).

  • Copy the same <system.serviceModel> element from the previous "App.Config" (of the "NorthwindService" project) into the current one.

  • Within the project properties, open the Settings tab and add a new setting with the name "cnNorthwind,", "Type" as "String," "Scope" as "Application" and "Value" as required connection string (to connect to database) as shown in previous sections.

  • Add a reference to "NorthwindService" project (fig 06, fig 07).

  • Add a reference to "System.ServiceModel" (fig 08).

Figure 04

Figure 05

Figure 06

Figure 07

Figure 08

Developing a custom application to host the WCF: coding and testing

The following is the source code for both the "Start" and "Stop" buttons designed in previous section:

Imports System

Imports System.ServiceModel

Public Class Form1

Dim host As ServiceHost

Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnStart.Click

  host = New ServiceHost(GetType(NorthwindService.ProductService))

   host.Open()

    Me.lblMsg.Text = "Started"

End Sub

Private Sub btnStop_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnStop.Click

  host.Close()

   Me.lblMsg.Text = "Stopped"

End Sub

End Class

Set the "NorthwindServiceHost" as the startup project as shown below (Fig 09).

Execute the application and hit the "Start" button. It should start the service as follows (Fig 10). Always stop the service before closing the application.

Go to the "bin" folder of "NorthwindServiceHost" and execute the "NorthwindServiceHost.exe" independently (without using Visual Studio). It should respond without any difference as shown in the following image (Fig 11).

Testing the WCF custom hosted Service: creating the WCF Client using Windows Forms

To test the WCF service hosted in previous sections, we need to develop a WCF client. In this case, for simplicity, I would like to work with Windows Forms.

Add a new project (to the existing solution), select "Windows Forms Application" as the template, provide the name "NorthwindClient" and hit on OK.

If not already started, start the service independently from Windows Explorer (as shown in the previous section).

Add a service reference by right clicking on the "NorthwindClient" project and selecting "Add Service Reference" (fig 12).

In the "Address" field, type http://localhost:8181/ProductService and hit GO. Before you hit GO, make sure that the service is already started independently (outside Visual Studio) as shown in previous section.

Once the service is found, provide the namespace as "ProductService" and click OK (Fig 13).

Design a form that looks like the following (Fig 14):

Testing the WCF custom hosted Service: source code

For the Windows form previously created, make the modifications to the existing code so that it matches with the following:

Public Class Form1

Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnSearch.Click

Dim proxy As New ProductService.ProductServiceClient
("WSHttpBinding_IProductService")

Dim objProduct As ProductService.Product = proxy.GetProductInfo
(Me.txtProductID.Text)

  proxy.Close()

   With objProduct

    Me.txtProductName.Text = .ProductName

    Me.txtUnitPrice.Text = .UnitPrice

    Me.txtUnitsInStock.Text = .UnitsInStock

    Me.txtUnitsOnOrder.Text = .UnitsOnOrder

   End With

End Sub

Private Sub btnGetAllProducts_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles btnGetAllProducts.Click

Dim proxy As New ProductService.ProductServiceClient
("WSHttpBinding_IProductService")

  Me.ListBox1.DataSource = proxy.GetProductNames

  proxy.Close()

End Sub

End Class

Make the "NorthwindClient" a "Startup project"

While still keeping the service in "started" mode independently, hit F5 to execute and test the application (which accesses and retrieves information from the WCF service hosted earlier). If everything works fine, you should be able see the output as follows (Fig 15):

I hope you enjoyed the article and any suggestions, bugs, errors, enhancements etc. are highly appreciated at http://jagchat.spaces.live.com

blog comments powered by Disqus
ASP.NET ARTICLES

- Implementing ASP.NET 4.0 Page.MetaDescriptio...
- ASP.Net Development Tips
- Intro to Sessions in ASP.Net
- Google Maps API Introduction in ASP.NET usin...
- Creating an ASP.NET 3.5 Gridview Image Galle...
- Encrypt QueryString in ASP.NET 3.5 using VB....
- ASP.NET 3.5 Drop Down List Controls
- Connect to Access Database with ASP.Net
- Secure Audio Streaming with ASP.Net and Flash
- Dynamic Sitemap and Navigation in ASP.Net
- Implement Gzip and Deflate Compression in AS...
- Run ASP.Net in Ubuntu with Apache
- ASP.Net Mono Website Contact Forms
- ASP.Net URL Rewriting Methods
- Murach`s ASP.NET 4 Web Programming with C# 2...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
 
 
 

ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 2 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials