Developing an Object Oriented Business Component Using WCF and Visual Studio 2008

In this article, we will focus on implementing OOPS to develop a business component using WCF. We will also use Visual Studio 2008 beta. Finally, we will access it using ASP.NET 3.5.

Contributed by
Rating: 5 stars5 stars5 stars5 stars5 stars / 18
October 31, 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 you to go through my previous two articles available at:



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 with Microsoft SQL Server 2008 beta 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 a WCF Service Library in a previous 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. The following is a glimpse of the solution explorer (Fig 01).

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. This project contains all of the business logic, developed using object oriented techniques. The following are the classes defined as part of this project.

  • Product

  • Products

  • IProductService

  • ProductFactoryService

  • DBHelper

The explanations for each of those classes are detailed in the successive sections.

“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 Business Component

The object oriented approach followed in this article is simple and yet powerful. Let us try to understand the classes included as part of the component.

The class “Product” (Product.vb) is specially created to hold one row of the “Products” table (of the “Northwind” database) in the form of an object. It is also called an “Entity” class. This is the basic unit of the Business Component to hold the data (which can be passed through tiers).

The “Products” class (Products.vb) is mainly used to hold more than one row of the “Products” table in the form of a collection. It is also called an “Entity Collection” class. When we need to have a set of rows grouped together as a single object, this class helps us a lot.

Next comes the “IProductService” interface (IProductService.vb). This defines the skeleton of all services (or operations) offered by our WCF Business Component. Each of these operations works as an interface between the consumer (WCF consumers) and our component. These operations generally interact with databases (or even other business components). As it is an interface, it doesn’t contain any implements of those operations.

When it comes to implementing the “IProductService” interface, the  “ProductFactoryService” class (ProductFactoryService.vb) enters the picture. It implements each and every operation declared in “IProductService.” This is the true “Business Logic Implementation” class which may include data validations, computations and business calculations, transactions, interaction with databases, populating entity objects, and so forth.

Database interactions can be directly included as part of “ProductFactoryService.” But it is always better to separate data access into a different class. This approach of separation not only gives you a great advantage as far as scalability (say you wanted to access Microsoft Enterprise Library in future), but also acts as a common data access gateway for all of your business logic implementation classes.

Now that you understand the object oriented structure implemented as part of WCF Business Component, it is time to go through the code.

Understanding the WCF Business Component: Source Code for Entity classes

As explained in the previous section, we have two entity related classes, “Product” and “Products.”

The following is the source code for the “Product” class:


<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

The following is the source code for the “Products” class:


Public Class Products

Inherits List(Of Product)


End Class

The “Products” class is very simple (as shown above) as the entire code to handle a collection is defined in the “generic” class “List” in “System.Collections.Generics.”

Understanding the WCF Business Component: Source Code for Business Logic

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.

“IProductService” is an interface defined exclusively for the above purpose. It contains all the methods which are accessible to the client. It is defined as follows:


<ServiceContract()> _

  Public Interface IProductService


<OperationContract()> _

  Function GetProductInfo(ByVal ProductID As Integer) As Product


<OperationContract()> _

  Function GetProductsLookup() As DataTable


<OperationContract()> _

  Function GetProductsList() As Products


<OperationContract()> _

  Sub Add(ByVal p_Product As Product)


<OperationContract()> _

  Sub Update(ByVal p_Product As Product)


<OperationContract()> _

  Sub Delete(ByVal p_Product As Product)


<OperationContract(name:="DeleteProductByID")> _

  Sub Delete(ByVal p_ProductID As Integer)


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 a concrete class. “ProductFactoryService” is the class which implements the structure defined in the “IProductService” interface and it is defined as follows:


Imports System.Data

Imports System.Data.SqlClient


Public Class ProductFactoryService

  Implements IProductService


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

Dim dr As DataRow = DBHelper.getRow("SELECT ProductID, ProductName, UnitPrice, UnitsInStock, UnitsOnOrder FROM dbo.Products WHERE ProductID=" & ProductID)

  If dr Is Nothing Then

    Return Nothing

  Else

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

  End If

End Function


Public Function GetProductsLookup() As System.Data.DataTable Implements IProductService.GetProductsLookup

Return DBHelper.getDataTable("SELECT ProductID, ProductID + ' - ' + ProductName AS ProductName FROM dbo.Products")

End Function


Public Function GetProductsList() As Products Implements IProductService.GetProductsList

  Dim clnProducts As New Products

For Each dr As DataRow In DBHelper.getDataTable("SELECT ProductID, ProductName, UnitPrice, UnitsInStock, UnitsOnOrder FROM dbo.Products").Rows

clnProducts.Add(New Product With {.ProductID = dr("ProductID"), .ProductName = dr("ProductName") & "", .UnitPrice = dr("UnitPrice") & "", .UnitsInStock = dr("UnitsInStock") & "", .UnitsOnOrder = dr("UnitsOnOrder") & ""})

  Next

   Return clnProducts

  End Function


Public Sub Add(ByVal p_Product As Product) Implements IProductService.Add

DBHelper.SQLExecute("INSERT INTO dbo.Products(ProductName, UnitPrice, UnitsInStock, UnitsOnOrder) VALUES ('" & p_Product.ProductName & "'," & p_Product.UnitPrice & "," & p_Product.UnitsInStock & "," & p_Product.UnitsOnOrder & ")")

End Sub


Public Sub Delete(ByVal p_Product As Product) Implements IProductService.Delete

  Me.Delete(p_Product.ProductID)

End Sub


Public Sub Update(ByVal p_Product As Product) Implements IProductService.Update

DBHelper.SQLExecute("UPDATE dbo.Products SET ProductName='" & p_Product.ProductName & "', UnitPrice=" & p_Product.UnitPrice & ", UnitsInStock=" & p_Product.UnitsInStock & ", UnitsOnOrder=" & p_Product.UnitsOnOrder & " WHERE ProductID=" & p_Product.ProductID)

End Sub


Public Sub Delete(ByVal p_ProductID As Integer) Implements IProductService.Delete

DBHelper.SQLExecute("DELETE FROM dbo.Products WHERE ProductID = " & p_ProductID)

End Sub


End Class

You can observe that, each operation (or method) in the above class works with a utility class named “DBHelper,” which is a common gateway for data access.

Understanding the WCF Business Component: Source Code for “DBHelper”

I kept this utility class (“DBHelper”) very simple. It can be enhanced by implementing features like stored procedure access, support for transactions and so on.

In fact, I suggest you go to Microsoft Enterprise Library and use the Data Access Application block as part of the “DBHelper” façade. If you are new to Microsoft Enterprise Library (or Data Access Application block), you can find my excellent series on the subject at:

http://www.aspfree.com/c/a/ASP.NET/Developing-ASPNET-20-Applications-with-
the-Microsoft-Data-Access-Application-Block/

http://www.aspfree.com/c/a/ASP.NET/Interacting-with-Databases-Using-ASPNET-
20-with-the-Microsoft-Data-Access-Application-Block/

http://www.aspfree.com/c/a/ASP.NET/Working-with-Stored-Procedures-using-
ASPNET-20-with-Microsoft-Data-Access-Application-Block/

http://www.aspfree.com/c/a/ASP.NET/More-about-Stored-Procedures-using-
ASPNET-20-with-the-Microsoft-Data-Access-Application-Block/

The following is the code used for simple data access:


Imports System.Data

Imports System.Data.SqlClient


Public Class DBHelper


  Private Shared Function getConnectionString() As String

  Return My.Settings.cnNorthwind

End Function


Public Shared Sub SQLExecute(ByVal strSQL As String)

  Dim Conn As New SqlConnection(getConnectionString)

  Dim cmd As New SqlCommand(strSQL, Conn)

With cmd

  .Connection.Open()

  .ExecuteNonQuery()

  .Connection.Close()

  .Dispose()

End With

End Sub


Public Shared Function getRow(ByVal strSELECT As String) As DataRow

  Dim da As New SqlDataAdapter(strSELECT, getConnectionString)

  Dim dt As New DataTable

   da.Fill(dt)

   da.Dispose()

If dt.Rows.Count = 0 Then Return Nothing Else Return dt.Rows(0) 'return only first row

End Function


Public Shared Function getDataTable(ByVal strSELECT As String) As DataTable

  Dim Conn As New SqlConnection(getConnectionString)

  Dim da As New SqlDataAdapter(strSELECT, Conn)

  Dim dt As New DataTable

   da.Fill(dt)

   da.Dispose()

Return dt


End Function


Public Shared Function getRowValue(ByVal strSELECT As String) As String

  Dim Conn As New SqlConnection(getConnectionString)

  Dim cmd As New SqlCommand(strSELECT, Conn)

  Dim value As String = ""

With cmd

  .Connection.Open()

value = .ExecuteScalar() & "" 'concatenating an empty string..to eliminate null or nothing

  .Connection.Close()

  .Dispose()

End With

  Return value

End Function


End Class

Hosting, managing and accessing (or consuming) the WCF Service are very similar to my previous articles and I suggest you refer to those.

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
BRAINDUMP ARTICLES

- Microsoft Windows 8 Committed to Cloud Compu...
- Independent Developers Favor Windows Phone 7
- Dell Introduces VMware-based Cloud
- Microsoft and Skype Agree to Acquisition Deal
- Transfer Contacts in Microsoft Outlook
- Zune`s Next Steps
- Safari Books Online Review
- Does Microsoft Get Touch Screens Now?
- Microsoft`s Record Quarterly Earnings Not En...
- Basic Operations and Registers in Assembly
- Assembly Coding within Visual C/C++ IDE
- New Microsoft Office Coming with a Twist
- Microsoft`s FUSE Labs Unveils Spindex Social...
- HP Slate with Windows 7: Dead or Alive?
- Windows Phone 7 Mobile OS to Rival Android a...

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 9 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials