Developing Business Logic using the WCF Service Library with VS2K8 and ASP.NET 3.5

In this article, we will focus on developing a WCF library which performs business logic (with CRUD operations) at the middle tier level and finally access it using ASP.NET 3.5.

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


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

A downloadable zip file is available for this article.

If you are new to WCF, I strongly recommend that you go through my previous two articles. In my first 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. In my second article, we focused on developing a WCF library, hosting it using a custom application and finally testing it using Windows Forms.

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.

Understanding the sample Visual Studio solution

As I already explained the step-by-step creation of WCF Service Library in my previous second article, I will not go through the details of those steps. But, before proceeding further, let us try to understand the Visual Studio solution created for this article. Below you will see a glimpse of Solution Explorer.

From the above figure, we have three different projects combined as a single solution. The name of the solution is "WCFNorthwindBLLService." It is comprised of the following three projects:

  • NorthwindBLLService
  • NorthwindBLLServiceHost
  • WCFClientWebsite

"NorthwindBLLService" is created based on the "WCF Service Library" template. It contains the core business logic for the entire application. This project provides direct interfacing to business objects (available in it) and in turn, this directly interacts with the database.

"NorthwindBLLServiceHost" is created based on the "Windows Forms" template. It is an application which simply hosts "NorthwindBLLService" as a service. The service can be started or stopped using this simple application. You will have to start the service to make "NorthwindBLLService" work.

"WCFClientWebsite" is created based on the "ASP.NET website" template. It is a web application which accesses the "NorthwindBLLService" through "NorthwindBLLServiceHost" and finally interacts with the business classes. A service reference is added to "NorthwindBLLServiceHost" as part of its development.

Understanding the WCF Service Library: Employee class

The "Employee" class mimics the "emp" table. For the simplicity of this article, I added a table called "emp" as follows:

The "Employee" class is specially created to store one row of the above table in the form of an object. It simply contains the properties of each of the columns available in the above table. It is defined as follows:

<DataContract()>

  Public Class Employee

  Private _Empno As Integer

  Private _Ename As String

  Private _Sal As Double

  Private _Deptno As Integer

<DataMember()> _

  Public Property Empno() As Integer

   Get

    Return _Empno

   End Get

    Set(ByVal value As Integer)

     _Empno = value

    End Set

End Property

<DataMember()> _

  Public Property Ename() As String

   Get

    Return _Ename

   End Get

    Set(ByVal value As String)

     _Ename = value

    End Set

End Property

<DataMember()> _

 Public Property Sal() As Double

  Get

   Return _Sal

  End Get

   Set(ByVal value As Double)

    _Sal = value

   End Set

End Property

<DataMember()> _

 Public Property Deptno() As Integer

  Get

   Return _Deptno

  End Get

   Set(ByVal value As Integer)

    _Deptno = value

   End Set

End Property

End Class

Understanding the WCF Service Library: IEmpService interface and EmpService class

To enable applications to utilize the services of WCF Service, an interface must be defined. The client accesses business objects and executes the methods which are defined in this interface.

"IEmpService" is an interface defined exclusively for the above purpose. It contains all the methods which are accessible to the client. In this case, all the CRUD methods concern the "emp" table. It is defined as follows:

Imports System.Data

<ServiceContract()> _

  Public Interface IEmpService

<OperationContract()> _

  Function GetInfo(ByVal EmpNo As Integer) As Employee

<OperationContract()> _

  Function GetLookup() As DataSet

<OperationContract()> _

  Function GetList() As DataSet

<OperationContract()> _

  Sub Add(ByVal p_emp As Employee)

<OperationContract()> _

  Sub Update(ByVal p_emp As Employee)

<OperationContract()> _

  Sub Delete(ByVal p_emp As Employee)

End Interface

The above is simply an interface, which always contain abstract methods (or methods without any code). It has to be implemented using another class to make it as a concrete class. "EmpService" is the class which implements the structure defined in "IEmpService" interface and it is defined as follows:

Imports System.Data.SqlClient

  Public Class EmpService

  Implements IEmpService

Public Function GetInfo(ByVal EmpNo As Integer) As Employee
Implements IEmpService.GetInfo

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

Using cmd As New SqlCommand("SELECT empno,ename,sal,deptno FROM
dbo.emp WHERE empno=" & EmpNo, cn)

  cmd.Connection.Open()

   Using rdr As SqlDataReader = cmd.ExecuteReader

    If rdr.Read() Then

Return New Employee With {.Empno = rdr(rdr.GetOrdinal("Empno")),
.Ename = rdr(rdr.GetOrdinal(
"Ename")) & "", .Sal = rdr
(rdr.GetOrdinal(
"sal")) & "", .Deptno = rdr(rdr.GetOrdinal
(
"Deptno")) & ""}

  Else

   Return Nothing

 End If

End Using

   cmd.Connection.Close()

  End Using

 End Using

End Function

Public Function GetList() As System.Data.DataSet Implements
IEmpService.GetList

Dim ds As New DataSet

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

Using cmd As New SqlCommand("SELECT empno,ename,sal,deptno FROM
dbo.emp ", cn)

 Using da As New SqlDataAdapter(cmd)

   da.Fill(ds)

  End Using

 End Using

End Using

  Return ds

End Function

Public Function GetLookup() As System.Data.DataSet Implements
IEmpService.GetLookup

 Dim ds As New DataSet

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

Using cmd As New SqlCommand("SELECT empno, convert(varchar,empno)
+ ' - ' + ename as ename FROM dbo.emp ", cn)

  Using da As New SqlDataAdapter(cmd)

   da.Fill(ds)

  End Using

 End Using

End Using

  Return ds

End Function

Public Sub Add(ByVal p_emp As Employee) Implements
IEmpService.Add

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

Using cmd As New SqlCommand("INSERT INTO emp
(empno,ename,sal,deptno) VALUES (" & p_emp.Empno &
", '" &
p_emp.Ename &
"'," & p_emp.Sal & "," & p_emp.Deptno & ")", cn)

   cmd.Connection.Open()

   cmd.ExecuteNonQuery()

   cmd.Connection.Close()

  End Using

 End Using

End Sub

Public Sub Update(ByVal p_emp As Employee) Implements
IEmpService.Update

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

Using cmd As New SqlCommand("UPDATE emp SET ename='" &
p_emp.Ename &
"', sal=" & p_emp.Sal & ", deptno=" & p_emp.Deptno
&
" WHERE empno = " & p_emp.Empno, cn)

   cmd.Connection.Open()

   cmd.ExecuteNonQuery()

   cmd.Connection.Close()

  End Using

 End Using

End Sub

Public Sub Delete(ByVal p_emp As Employee) Implements
IEmpService.Delete

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

Using cmd As New SqlCommand("DELETE FROM emp WHERE empno = " &
p_emp.Empno, cn)

   cmd.Connection.Open()

   cmd.ExecuteNonQuery()

   cmd.Connection.Close()

  End Using

 End Using

End Sub

End Class

Understanding the WCF Service Library: the app.config file

Every WCF Service must be configured with several settings. Complicated deployments have complicated configurations. As this article assumes that the solution sits on a developer machine, the service model element in "app.config" is defined as follows:

<system.serviceModel>

<services>

<service name="NorthwindBLLService.EmpService"
behaviorConfiguration="NorthwindBLLService.EmpServiceBehavior">

<host>

<baseAddresses>

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

</baseAddresses>

</host>

<endpoint address="" binding="wsHttpBinding"
contract="NorthwindBLLService.IEmpService" />

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

</service>

</services>

<behaviors>

<serviceBehaviors>

<behavior name="NorthwindBLLService.EmpServiceBehavior">

<serviceMetadata httpGetEnabled="True"/>

<serviceDebug includeExceptionDetailInFaults="True" />

</behavior>

</serviceBehaviors>

</behaviors>

</system.serviceModel>

Make sure that the following is always true to give full details of errors raised during development:

<serviceDebug includeExceptionDetailInFaults="True" />

The service gets hosted using the following address:

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

The main endpoint for the above service is defined as follows:

<endpoint address="" binding="wsHttpBinding"
contract="NorthwindBLLService.IEmpService" />

And finally, the service is named as follows:

<service name="NorthwindBLLService.EmpService" behaviorConfiguration="NorthwindBLLService.EmpServiceBehavior">

Depending upon the deployment/hosting requirements, the "app.config" needs to be modified appropriately. It varies greatly from intranet configurations to extranet or even Internet configurations. It could be completely different from the above if the hosting will be on IIS (Web Service) or WAS or Windows Service.

Understanding the WCF Service host

Every WCF Service must be hosted. There are several ways of hosting (depending on the requirements) a WCF Service. In this article we focused on hosting a WCF Service using a custom application.

The custom application (or a simple service host utility) manages the service. The main two operations for any service to manage are "start" and "stop." A separate Windows forms application (NorthwindBLLServiceHost) is developed specifically for this purpose.

The application simply contains a form with two buttons (for "start" and "stop") and finally a label to show the status of the service. The following is the source code for both "Start" and "Stop" buttons:

Imports System

  Imports System.ServiceModel

  Public Class Form1

  Dim hostEmpService As ServiceHost

Private Sub btnStartNorthwindEmpService_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
btnStartNorthwindEmpService.Click

  hostEmpService = New ServiceHost(GetType
(NorthwindBLLService.EmpService))

  hostEmpService.Open()

 Me.lblEmpServiceStatus.Text = "Service Started Successfully"

End Sub

Private Sub btnStopNorthwindEmpService_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
btnStopNorthwindEmpService.Click

  hostEmpService.Close()

  Me.lblEmpServiceStatus.Text = "Stopped"

End Sub

Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As
System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

  Try

   If hostEmpService.State = CommunicationState.Opened Then

    hostEmpService.Close()

   End If

  Catch ex As Exception

 End Try

End Sub

End Class

Once the application is executed and you have hit the "Start" button, it should start the service as follows:

 

Always start the service before working with any application which tries to access the service.

Understanding the WCF Client: ASP.NET 3.5 web site

Once the service is up and running, we should have a client accessing the service. In this case, I would like to access the WCF service using ASP.NET 3.5. For this purpose, a project named "WFClientWebsite" (of type ASP.NET website) is added to the solution.

Once the web site is created, a service reference is added to http://localhost:8181/EmpService which is hosted by "NorthwindBLLServiceHost" (refer to Fig 1). Once the reference is added, a proxy gets created at ASP.NET and all of those classes are available to ObjectDataSource controls for data binding.

The following is an output screen shot which demonstrates the access to service using the ObjectDataSource control.

Understanding the WCF Client: ASP.NET 3.5 web page source code

The following is the source design (which use ObjectDataSource, FormView and GridView controls) for the above web page:

<body>

<form id="form1" runat="server">

<div>

<asp:DropDownList ID="ddlEmpLookup" runat="server"
AutoPostBack="True"

DataSourceID="odsrcEmpLookup" DataTextField="ename"
DataValueField="empno">

</asp:DropDownList>

<asp:Button ID="btnEdit" runat="server" Text="Edit" />

<asp:Button ID="btnAddNew" runat="server" Text="Add New" />

<asp:ObjectDataSource ID="odsrcEmpLookup" runat="server"

SelectMethod="GetLookup" TypeName="EmpService.EmpServiceClient">

</asp:ObjectDataSource><hr />

<asp:FormView ID="fvEmpInfo" runat="server"
DataSourceID="odsrcEmpInfo"

  DataKeyNames="empno">

<EditItemTemplate>

  Empno:

<asp:TextBox ID="EmpnoTextBox" runat="server" Text='<%# Bind
("Empno") %>' />

<br />

  Ename:

<asp:TextBox ID="EnameTextBox" runat="server" Text='<%# Bind
("Ename") %>' />

<br />

  Sal:

<asp:TextBox ID="SalTextBox" runat="server" Text='<%# Bind("Sal") %>' />

<br />

  Deptno:

<asp:TextBox ID="DeptnoTextBox" runat="server" Text='<%# Bind
("Deptno") %>' />

<br />

<br />

<asp:LinkButton ID="UpdateButton" runat="server"
CausesValidation="True"

  CommandName="Update" Text="Update" />

&nbsp;<asp:LinkButton ID="DeleteButton" runat="server"
CausesValidation="True"

  CommandName="Delete" Text="Delete" />

  &nbsp;<asp:LinkButton ID="UpdateCancelButton" runat="server"

 CausesValidation="False" CommandName="Cancel" Text="Cancel" />

</EditItemTemplate>

<InsertItemTemplate>

  Empno:

<asp:TextBox ID="EmpnoTextBox" runat="server" Text='<%# Bind
("Empno") %>' />

<br />

  Ename:

<asp:TextBox ID="EnameTextBox" runat="server" Text='<%# Bind
("Ename") %>' />

<br />

  Sal:

<asp:TextBox ID="SalTextBox" runat="server" Text='<%# Bind("Sal")
%>' />

<br />

  Deptno:

<asp:TextBox ID="DeptnoTextBox" runat="server" Text='<%# Bind
("Deptno") %>' />

<br />

<br />

<asp:LinkButton ID="InsertButton" runat="server"
CausesValidation="True"

  CommandName="Insert" Text="Insert" />

 &nbsp;<asp:LinkButton ID="InsertCancelButton" runat="server"

  CausesValidation="False" CommandName="Cancel" Text="Cancel" />

</InsertItemTemplate>

<ItemTemplate>

  Empno:

<asp:Label ID="EmpnoLabel" runat="server" Text='<%# Bind("Empno")
%>' />

<br />

  Ename:

<asp:Label ID="EnameLabel" runat="server" Text='<%# Bind("Ename")
%>' />

<br />

  Sal:

<asp:Label ID="SalLabel" runat="server" Text='<%# Bind("Sal") %
>
' />

<br />

  Deptno:

<asp:Label ID="DeptnoLabel" runat="server" Text='<%# Bind
("Deptno") %>' />

<br />

</ItemTemplate>

</asp:FormView><asp:ObjectDataSource ID="odsrcEmpInfo"
runat="server"

  SelectMethod="GetInfo" TypeName="EmpService.EmpServiceClient"

  DataObjectTypeName="EmpService.Employee" DeleteMethod="Delete"

  InsertMethod="Add" UpdateMethod="Update">

<SelectParameters>

<asp:controlparameter ControlID="ddlEmpLookup" Name="EmpNo"

  PropertyName="SelectedValue" Type="Int32" />

</SelectParameters>

</asp:ObjectDataSource> <hr /><asp:GridView ID="gvEmpList"
runat="server"

  DataSourceID="odsrcEmpList">

</asp:GridView><asp:ObjectDataSource ID="odsrcEmpList"
runat="server"

  SelectMethod="GetList" TypeName="EmpService.EmpServiceClient">

</asp:ObjectDataSource>

</div>

</form>

</body>

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