Dealing with .NET Enterprise Services: .NET Remoting, Web Services and Service Components

This article will give you a kick start for learning advanced concepts for .NET Enterprise services such as .NET Remoting, Web Services and Service Components (COM+).

Contributed by
Rating: 5 stars5 stars5 stars5 stars5 stars / 13
February 08, 2006
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

A downloadable file for this article is available here.

All demonstration solutions have been developed using SQL Server 2000 Enterprise Edition and Visual Studio 2003 Enterprise Architect on Windows Server 2003 Standard Edition.  Please note that I didn’t really test the solution on any  other versions/editions of similar Microsoft products. 

It has been a while since I contributed an article on “Building a Robust and Highly Scalable Distributed Architecture in VB.NET” which you can read at this link: http://www.aspfree.com/c/a/VB.NET/Building-a-Robust-and-Highly-Scalable-
Distributed-Architecture-using-VB-NET/
. In that article, I mixed all of the technologies together, or, to put it another way, I integrated them. Now in this article, I would like to provide samples of each of those technologies individually, showing them in ways that are not at all related each other.  The previous article gave you enough of an explanation about each of these technologies that I won't repeat myself.

I strongly suggest you go to that link to read a brief overview on the technologies if you are not familiar with them.

Working with the .NET Remoting Server

.NET Remoting is simply a next generation DCOM.  Those who are familiar with DCOM, can simply consider .NET Remoting to be something like DCOM+.NET BCL + “some extras too.”

For any Remoting application, there will generally be a server and client (apart from a Remote Object).  The Remoting server will continuously listen to the incoming requests of the Remoting client and pass the messages (or info) accordingly.  Let us go through the code for the Remoting Server.  You can skip to the next section, if you would like to view the definition of “Remoting Object” which is being used by this Remoting Server.

Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles btnStart.Click
        Dim chan As New TcpChannel(8085)
        ChannelServices.RegisterChannel(chan)
        RemotingConfiguration.RegisterWellKnownServiceType( _
            GetType(RemoteObject.HelloServer), _
            "SayHello", WellKnownObjectMode.SingleCall)
        MessageBox.Show("Server started succesfully...." &
ControlChars.CrLf & "click OK to stop the server")
        ChannelServices.UnregisterChannel(chan)
    End Sub

It is simply a Windows desktop-based application, which starts to listen to any request from the Remoting client.  The Remoting service (according to the above coding) listens at the 8085 port (or TcpChannel).

Working with the Remoting Client and Remoting Object

Now let us go through the code of the Remoting Client.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles Button1.Click
 
        Dim chan As New TcpChannel
        ChannelServices.RegisterChannel(chan)
 
        Dim obj As HelloServer = _
            CType(Activator.GetObject(GetType(HelloServer), _
                "tcp://localhost:8085/SayHello"), HelloServer)
 
        Try
            MessageBox.Show(obj.HelloMethod(Me.TextBox1.Text))
        Catch ex As Exception
            MessageBox.Show("Server could not be located or
communication error")
        End Try
        ChannelServices.UnregisterChannel(chan)
    End Sub

You can clearly observe from the above program that the client is trying to contact through the “tcp” protocol (and that too at the 8085 port) with the service name “SayHello.”  Once the client receives the proxy of the server remote object, it can directly execute the methods (“HelloMethod”), as if they are locally available.

Considering the issue of the “RemoteObject,” it is simply a class which is used for distributed programming.  It is defined as follows within the solution:

Imports System
Imports System.Runtime.Remoting
Imports System.Runtime.Remoting.Channels
Imports System.Runtime.Remoting.Channels.Tcp
 
Public Class HelloServer
    Inherits MarshalByRefObject
 
    Public Function HelloMethod(ByVal name As String) As String
        Return "Hi there, " & name
    End Function
 
End Class

Every “RemoteObject” (or the class used by the Remoting server to create and share with clients) should be extended from “MarshalByRefObject” (just to give “remote” access).

Working with a basic COM+ application

I already introduced COM+ issues in my earlier article.  So, at the moment, I don’t want to go into its details.  Let us directly attack the code.

Imports System.EnterpriseServices
Imports System.Reflection
'c:...bin/> sn -k COMPlusEx1Srv.snk
'regsvcs [/reconfig] /fc COMPlusEx1Srv.snk
 
<Assembly: ApplicationName("COMPlusEx1Srv")>
<Assembly: AssemblyKeyFile("../../bin/COMPlusEx1Srv.snk")>
<Assembly: ApplicationAccessControl()>
 
Public Class Test
    Inherits ServicedComponent
 
    Public Function getSum(ByVal a As Integer, ByVal b As
Integer) As Integer
        Return (a + b)
    End Function
 
    Public Function getProduct(ByVal a As Integer, ByVal b As
Integer) As Integer
        Return (a * b)
    End Function
End Class

Any COM+ application should be extended from the base class “ServicedComponent.”  And we also need to import “System.EnterpriseServices” and “System.Reflection.”  The most important issue to remember is that the COM+ application needs to be strongly signed.  In the above program, two lines of comments exist to assist you in creating the “strong name key pair” and registering our application with COM+ services.

The two methods I defined in the above program are only for demonstration and not practical.

It is quite simple to create an object based on a COM+ definition. The following code shows you how you can access the above COM+ application.

Private Sub btnCal_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles btnCal.Click
        Dim obj As New COMPlusEx1Srv.Test
        MessageBox.Show(obj.getSum(CInt(Me.txtFirst.Text), CInt
(Me.txtSecond.Text)))
        MessageBox.Show(obj.getProduct(CInt(Me.txtFirst.Text),
CInt(Me.txtSecond.Text)))
    End Sub

It is as simple as creating your own object and accessing its members.

Working with a database-based COM+ application

Let us go through the following program.

<ClassInterface(ClassInterfaceType.AutoDispatch), Transaction
(TransactionOption.Supported), ConstructionEnabled([Default]:="Data Source=.;Initial Catalog=Northwind;User
id=sa"), JustInTimeActivation()> _
Public Class DBTest
    Inherits ServicedComponent
 
    Dim m_ConnectionString As String
 
    Protected Overrides Sub Construct(ByVal constructString As String)
        ' Called after constructor
        m_ConnectionString = constructString
    End Sub
 
    Public ReadOnly Property ConnectionString()
        Get
            Return m_ConnectionString
        End Get
    End Property
 
    <AutoComplete()> _
    Public Sub ExecuteDML(ByVal strSQL As String)
        Dim cn As New SqlConnection(m_ConnectionString)
        cn.Open()
        Dim cmd As New SqlCommand(strSQL, cn)
        cmd.ExecuteNonQuery()
        cmd.Dispose()
        cn.Close()
    End Sub
End Class

You can provide a connection string within your COM+ application (which can be modified later, even at run time, using a Component Services snap-in).  And to retrieve the same connection string you use the following code fragment:

    Protected Overrides Sub Construct(ByVal constructString As
String)
        ' Called after constructor
        m_ConnectionString = constructString
    End Sub

And you can expose the same connection string using the following code:

    Public ReadOnly Property ConnectionString()
        Get
            Return m_ConnectionString
        End Get
    End Property

The “ExecuteDML” method is the most important method of the above COM+ application.  It has an attribute, “<AutoComplete>”, which says that the transaction has to commit after successful execution (or roll back if any error arises).

The client program to call the above database-based COM+ would be as follows:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles Button1.Click
 
        Dim obj As New COMPlusEx2Srv.DBTest
        MessageBox.Show(obj.ConnectionString)
        obj.ExecuteDML(Me.txtQuery.Text)
        MessageBox.Show("Updated succesfully")
    End Sub

The above code just creates an object of the COM+ application and accesses its properties (“ConnectionString”) and methods (“ExecuteDML”).

Working with Web Services

I want to demonstrate a very simple web service (like the first COM+ application) first.  Let us consider the following code:

<WebMethod()> _
        Public Function getSum(ByVal a As Integer, ByVal b As
Integer)
        Return (a + b)
    End Function
    <WebMethod()> _
        Public Function getProduct(ByVal a As Integer, ByVal b As
Integer)
        Return (a * b)
    End Function

Really, it is very exciting to work with Web Services within the Visual Studio environment.  You cannot just leave it, once you get habituated.  It is such a productive environment that you can develop a simple web service (like the one above) in a minute or less.

Coming to the above scenario, all the methods within a web service are to be preceded with an attribute “<WebMethod()>”.  This lets IIS know that the method could be accessed by any other remote access client through http!

The client code to access the same is very simple.  You can take a look at the following:

Private Sub btnSum_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles btnSum.Click
        Dim srv As New Calculate.CalcService
        lblResult.Text = srv.getSum(CInt(Me.txtFirst.Text), CInt
(Me.txtSecond.Text))
    End Sub
 
    Private Sub btnProduct_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles btnProduct.Click
        Dim srv As New Calculate.CalcService
        lblResult.Text = srv.getProduct(CInt(Me.txtFirst.Text),
CInt(Me.txtSecond.Text))
    End Sub

The web service is named “Calculate.CalcService”.  Just create an object on that and access the members!

Working with database based Web Services

Even this part is very similar to what I discussed in the previous section.  Let's see the code:

<WebMethod()> _
    Public Function getInfo(ByVal strSQL As String) As DataSet
        Dim cn As New SqlConnection("Data Source=.;Initial
Catalog=Northwind;User ID=sa")
        cn.Open()
        Dim adp As New SqlDataAdapter(strSQL, cn)
        Dim ds As New DataSet
        adp.Fill(ds)
        adp.Dispose()
        cn.Close()
        Return ds
    End Function

You can observe that it is very similar to a fundamental data access program, but preceded with “<WebMethod()>” at the front.

And to access the above web service, the client could be something like the following:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles Button1.Click
        Dim srv As New MyService.DBService
        Dim ds As DataSet
        ds = srv.getInfo(Me.txtSQL.Text)
        Me.DataGrid1.DataSource = ds
        Me.DataGrid1.DataMember = ds.Tables(0).TableName
    End Sub

“dataset” and “datatable” work as offline data.  The internal architecture of both of them is made up of XML.  And thus I can receive a dataset or data table from the web service and assign it as a data source to data grid!

Remarks

All the sample code attached to this article can also be reused in your applications.  But please be aware that the proper configuration is necessary before you attach real time applications.  You need to thoroughly test the code before you deploy it at the production level.

Any comments, suggestions, ideas, improvements, bugs, errors, feedback etc. are highly appreciated at jag_chat@yahoo.com.

blog comments powered by Disqus
.NET ARTICLES

- .Net 4.5 Brings Changes
- Understanding Events in VB.NET
- Objects, Properties, Events and Methods in V...
- Install Visual Web Developer Express 2010
- Microsoft Gadgeteer an Open Source Alternati...
- Best DotNetNuke Modules
- Facebook Image Viewer in Visual Basic
- Murach`s ADO.NET 4 Database Programming with...
- 5 Must Have Visual Studio 2010 Extensions
- Dynamic Web Applications with ASP.NET Mono u...
- PDFSharp: HTML to PDF in ASP.NET 3.5 using V...
- Using the PDFSharp Library in ASP.NET 3.5 wi...
- Sending Email in ASP.NET 3.5 using VB.NET wi...
- ASP.NET 3.5 Role Based Security and User Aut...
- Creating ASP.NET Login Web Pages and Basic C...

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