Applying .NET Remoting
So far, I have discussed the architecture and various concepts related to the .NET remoting. In this section, you will learn how to apply these concepts to see remoting in action. In particular, you will learn how to
Create a remotable class.
Create a Server-activated object.
Create a Client-activated object.
Use configuration files to configure the remoting framework.
Use interface assemblies to compile remoting clients.
Creating a Remotable Class
Creating a remotable class is simple. All you need to do is to inherit a class from the MarshalByRefObject class. Step By Step 3.1 creates a remotable class named DbConnect. This class connects to a specified SQL Server database and allows you to execute a SELECT SQL statement using its ExecuteQuery() method.
STEP BY STEP 3.1: Creating a Remotable Class
-
Launch Visual Studio .NET. Select File, New, Blank Solution, and name the new solution 310C03. Click OK.
-
Add a new Visual Basic .NET Class library named StepByStep3-1 to the solution.
-
In the Solution Explorer, rename the default Class1.vb to DbConnect.vb.
-
Open the DbConnect.vb class and replace the code with the following code:
-
Select Build, Build StepByStep3-1. This step packages the remotable class into the file StepByStep3-1.dll, which is located in the bin or directory of your project. You can navigate to it through the Solution Explorer: Just select the project and click the Show All Files button in the Solution Explorer toolbar.
Imports System Imports System.Data Imports System.Data.SqlClient ' Marshal-by-Reference Remotable Object Public Class DbConnect Inherits MarshalByRefObject Private sqlconn As SqlConnection ' Default constructor connects to the Northwind ' database Public Sub New() sqlconn = New SqlConnection( _ "data source=(local);" & _ "initial catalog=Northwind;" & _ "integrated security=SSPI") Console.WriteLine( _ "Created a new connection " & _ "to the Northwind database") End Sub ' Parameterized constructor connects to the ' specified database Public Sub New(ByVal DbName As String) sqlconn = New SqlConnection( _ "data source=(local);" & _ "initial catalog=" & DbName & ";" & _ "integrated security=SSPI") Console.WriteLine( _ "Created a new connection " & _ "to the " & DbName & " database") End Sub Public Function ExecuteQuery( _ ByVal strQuery As String) As DataSet Console.Write("Starting to execute " & _ "the query...") ' Create a SqlCommand to represent the query Dim sqlcmd As SqlCommand = _ sqlconn.CreateCommand() sqlcmd.CommandType = CommandType.Text sqlcmd.CommandText = strQuery ' Create a SqlDataAdapter object ' to talk to the database Dim sqlda As SqlDataAdapter = _ New SqlDataAdapter() sqlda.SelectCommand = sqlcmd ' Create a DataSet to hold the results Dim ds As DataSet = New DataSet() Try ' Fill the DataSet sqlda.Fill(ds, "Results") Catch ex As Exception Console.WriteLine(ex.Message, _ "Error executing query") End Try Console.WriteLine("Done.") ExecuteQuery = ds End Function End Class
You've now created a remotable class, but it cannot yet be directly called from client application domains. For a remotable class to be activated, you need to connect the class to the remoting framework. You'll learn how to do that in the next section.
Creating a Server-Activated Object
A remotable class is usually connected with the remoting framework through a separate server program. The server program listens to the client request on a specified channel and instantiates the remote object or invokes calls on it as required.
It is a good idea to keep the remotable class and server program separate; this enables the design to be modular and the code to be reusable.
In this section, I'll show you how to create a remoting server. Here's an overview of the steps that the remoting server must take.
-
Create a server channel that listens on a particular port to the incoming object activation requests from other application domains. The following code segment shows how to create a TCP server channel and an HTTP server channel:
-
Register the channel with the remoting framework. This tells the framework which requests should be directed to this particular server. This registration is performed through the RegisterChannel() method of the ChannelServices class:
-
Register the remotable class with the remoting framework. This tells the framework which classes this particular server can create for remote clients. For a server-activated object, this registration is performed using the RegisterWellKnownServiceType() method of the RemotingConfiguration class, as shown here:
-
' Register a remote object with the remoting framework RemotingConfiguration.RegisterWellKnownServiceType( _ GetType(DbConnect), "DbConnect", _ WellKnownObjectMode.SingleCall)
Here, the first parameter is the type of the remotable class. The second parameter specifies the uniform resource identifier (URI) through which the server publishes the location of the remote object. The last parameter specifies the activation mode. The activation mode can be one of the two possible values of the WellKnownObjectMode enumerationSingleCall or Singleton.
' Register a TCP server channel on port Dim channel As TcpServerChannel = _ New TcpServerChannel(1234) ' Register a HTTP server channel on port Dim channel As HttpServerChannel = _ New HttpServerChannel(1234)
' Register the channel with remoting framework ChannelServices.RegisterChannel(channel)
TIP
Accessing an Object Through Multiple Channels From steps 2 and 3, you can note that the channel registration and the remote object registration are not related. In fact, a remote object can be accessed through all registered channels.
-
With the channel and class both registered, the remoting server is ready to go. The remoting framework will direct all requests for that class via that channel to the registered server.
As I discussed, earlier, an SAO can be activated in two different modesSingleCall and Singleton. In the next few sections, I'll cover how to create a remoting server for activating objects in each of these modes. I'll also tell the story on the other side of the channel; that is, how to connect the client program to the remoting framework so that it can instantiate the SAO and call methods on it.
Registering a Remotable Class As a Server-Activated Object Using the SingleCall Activation Mode
In this section, I'll demonstrate how to create a server that exposes the remotable class through the remoting framework. The server process here will be a long running user interface-less process that will continue to listen for incoming client requests on a channel.
Ideally, you should write this type of server program as a Windows service or use an existing Windows service such as Internet Information Services (IIS) to work as a remoting server. But I have chosen to write the server program as a console application mainly because I'll use the console Window to display various messages that will help you understand the workings of the remoting server.
Later in this chapter, in the section "Using IIS As an Activation Agent," I'll cover how to use IIS as a remoting server. I'll talk about Windows services in Chapter 6, "Windows Services."
STEP BY STEP 3.2: Registering a Server-Activated Object Using the SingleCall Activation Mode
Add a new Visual Basic .NET Console application named StepByStep3-2 to the solution.
-
In the Solution Explorer, right-click the project StepByStep3-2 and select Add Reference from the context menu. In the Add Reference dialog box (see Figure 3.4), select the .NET tab, select the System.Runtime.Remoting component from the list view, and click the Select button. Now select the Projects tab, select the Project named StepByStep3-1 (which contains the remotable object) from the list view, and click the Select button. Both the selected projects then appear in the Selected Components list, as shown in Figure 3.4. Click OK.
Figure 3.4 The Add Reference dialog box allows you to add references to components.
-
In the Solution Explorer, rename the default Module1.vb module to DbConnectSingleCallServer.vb. Open the file and change the name of the module to DbConnectSingleCallServer in the module declaration.
NOTE
Namespace Naming Note that although the project is named StepByStep3-1, the corresponding namespace is named StepByStep3_1. That's because the .NET Framework considers a dash to be an illegal character in a namespace name.
-
Add the following Imports directives above the module declaration:
-
Add the following code in the Main() procedure:
-
Right-click on the StepByStep3-2 project in the Solution Explorer and select Properties. Change the Startup object to DbConnectSingleCallServer.
-
Build the project. This step creates a remoting server that is capable of registering the StepByStep3_1.DbConnect class for remote invocation using the SingleCall activation mode.
Imports StepByStep3_1 Imports System.Runtime.Remoting Imports System.Runtime.Remoting.Channels Imports System.Runtime.Remoting.Channels.Tcp
Public Sub Main() ' Create and Register a TCP server channel ' that listens on port Dim channel As TcpServerChannel = _ New TcpServerChannel(1234) ChannelServices.RegisterChannel(channel) ' Register the service that publishes ' DbConnect for remote access in SingleCall mode RemotingConfiguration. _ RegisterWellKnownServiceType( _ GetType(StepByStep3_1.DbConnect), "DbConnect", _ WellKnownObjectMode.SingleCall) Console.WriteLine("Started server in the " & _ "SingleCall mode") Console.WriteLine("Press <ENTER> to terminate " & _ "server...") Console.ReadLine() End Sub
Step by Step 3.2 uses a receiver TCP channel (TcpServerChannel) to register a remotable class with the remoting framework. However, converting this program to use HTTP channel is not difficultyou just need to change all instances of Tcp to Http.
Step By Step 3.2 creates a remoting host that listens on port 1234. This is an arbitrary port number that might or might not work on your computer. A good idea is to check whether a port is already in use by some other application before running this program. You can do this from the command line on a particular computer by using the Windows netstat command.
This suggestion works only in a test scenario. It is not reasonable to instruct a customer to check whether the port is available before he starts the application. If the application will run entirely on your company's network, you can safely use a port in the private port range of 49152 through 65535provided, of course, that the port number you choose is not used by any other internal application. In case you are distributing the application, you should get a port number registered with the IANA (Internet Assigned Numbers Authority). You can see a list of already assigned port numbers at http://www.iana.org/assignments/port-numbers.
Instantiating and Invoking a Server-Activated Object
At this stage, you have a remotable object as well as a remoting server ready. In this section, I'll show you how to create a remoting client and use it to send messages to the remoting server to activate the remote object. In order to achieve this, the remoting client needs to take the following steps:
-
Create and register a client channel that is used by the remoting framework to send messages to the remoting server. The type of the channel used by the client should be compatible with the channel used by server. The following examples show how to create a TCP client channel and an HTTP client channel:
' Create and register a TCP client channel Dim channel As TcpClientChannel = _ New TcpClientChannel() ChannelServices.RegisterChannel(channel) ' Create and register a HTTP client channel Dim channel As HttpClientChannel = _ New HttpClientChannel() ChannelServices.RegisterChannel(channel)
TIP
Client Channel Registration You do not specify a port number when you register the client channel. The port number is instead specified at the time you register the remote class in the client's domain.
-
Register the remotable class as a valid type in the client's application domain. This registration is performed using the RegisterWellKnownClientType() method of the RemotingConfiguration class as shown here:
' Register the remote class as a valid ' type in the client's application domain RemotingConfiguration.RegisterWellKnownClientType( _ GetType(DbConnect), "tcp://localhost:1234/DbConnect")
Here, the first parameter is the type of the remotable class. The second parameter specifies the uniform resource identifier (URI) through which the server publishes the location of the remote object. Localhost maps to your local development machine. If the remote object is on some other computer, you'll replace localhost with the name of the computer.
TIP
Instantiating a Server-Activated Object You can only instantiate an SAO at client side using its default constructor.
-
Instantiate the SAO on the server. You can only use the default constructor.
' Instantiate the remote object DbConnect dbc = new DbConnect()
I'll demonstrate the preceding steps in Step by Step 3.3. In this example, I'll create the client program as a Windows application that accepts a SQL statement from the user and passes it to the remotable object. The rows returned by the remotable object are displayed in a DataGrid control.
STEP BY STEP 3.3: Instantiating and Invoking a Server-Activated Object
-
Add a new Visual Basic .NET Windows Application named StepByStep3-3 to the solution.
-
Add references to the .NET assembly System.Runtime.Remoting and the project StepByStep3-1 (the remotable class assembly).
-
In the Solution Explorer, delete the default Form1.vb. Add a new form named DbConnectClient.vb. Set the new form as the Startup object for the project.
-
Add the following directives to the form's module:
-
Place two GroupBox controls, a TextBox control (txtQuery), a Button control (btnExecute) and a DataGrid control (dgResults) on the form. Set the Multiline property of txtQuery to True. Arrange the controls as shown in Figure 3.5.
Imports System.Runtime.Remoting Imports System.Runtime.Remoting.Channels Imports System.Runtime.Remoting.Channels.Tcp Imports StepByStep3_1
Figure 3.5 This form invokes a method of a remote object to execute the given query.
-
Add the following code to the form directly after the designer-generated code:
-
Double-click the form and add the following code in the Load event handler:
-
Double-click the Button control and add the following code in the Click event handler:
-
Right-click on the name of the solution in the Solution Explorer window and select Properties. This opens the Solution Property Pages dialog box. In the dialog box, select the Multiple Startup Projects check box, select the action Start for StepByStep3-2 and StepByStep3-3, and set the action to None for other projects as shown in Figure 3.6. Make sure that StepByStep3-2 is placed above StepByStep3-3. If it isn't already there, click the Move Up and Move Down buttons to get the right order.
' Declare a Remote object Dim dbc As DbConnect
Private Sub DbConnectClient_Load( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' Register a TCP client channel Dim channel As TcpClientChannel = _ New TcpClientChannel() ChannelServices.RegisterChannel(channel) ' Register the remote class as a valid ' type in the client's application domain RemotingConfiguration. _ RegisterWellKnownClientType( _ GetType(DbConnect), _ "tcp://localhost:1234/DbConnect") ' Instantiate the remote class dbc = New DbConnect() End Sub
Private Sub btnExecute_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnExecute.Click Try ' Invoke a method on the remote object Me.dgResults.DataSource = _ dbc.ExecuteQuery(Me.txtQuery.Text) dgResults.DataMember = "Results" Catch ex As Exception MessageBox.Show(ex.Message, _ "Query Execution Error") End Try End Sub
Figure 3.6 Use the Solution Property Pages dialog box to control which projects are started and in what order.
-
Build the project. Select Debug, Start to run the project. You should see a command window displaying a message that the server is started in the SingleCall mode.
-
Shortly afterward, you'll see a Windows form for the client program. Enter a query in the text box and click the Execute Query button. The client invokes a method on the remote object and binds the results from the remote method to the DataGrid control as shown in Figure 3.7.
Figure 3.7 The remoting client populates the data grid with the result returned from the method invocation on a remote object.
NOTE
Starting Multiple Instances of a Program When you run a project from the Visual Studio .NET IDE, the default behavior is to run the program in debug mode. However, debug mode does not allow you to start another program from the IDE until you finish the current execution. This can be inconvenient if you want to start multiple client programs from within Visual Studio. A solution is that you can set the project you want to run first as the startup object and select Debug, Start Without Debugging to run the project. This won't lock Visual Studio .NET in the debug mode, and you'll be able to run more programs from within IDE using the same technique.
In the preceding steps, I have chosen to start the client and server programs within the Visual Studio .NET IDE. You can also start these programs by clicking on StepByStep3-2.exe and StepByStep3-3.exe, respectively, from the Windows explorer. Note that the server program should be running before you click on the Execute Query button on the client program.
At the end of Step By Step 3.3 when you look at the console window of the server program, you'll note the output as shown in Figure 3.8. You'll note that the remote object is created every time you click on the Execute Query button. That's normal behavior based on what you've learned so far in the chapter; however, what's peculiar is that for the first call, the constructor is called twice.
Figure 3.8 The SingleCall remoting server creates a new instance of the remote object with each request.
In fact, calling the constructor twice for the first request on a server is also a regular behavior of SingleCall object activation. The following two points explain why this happens:
The first call to constructor is made by the remoting framework at the server side to check whether it is okay to call this object remotely and to check the activation mode of the object.
The second constructor is called because of the client's call on the remote object. In the case of SingleCall activation, the server does not preserve the state of the constructor that was called earlier; therefore, the object has to be re-created with each client request.
You might wonder why I included a reference to StepByStep3-1.dll in this project. You might support your argument by saying that the DbConnect class contained in the StepByStep3-1.dll is a remotable class and its right place is on the server and not on the client.
Well said, but I have included StepByStep3-1.dll because of the following reasons:
The client project StepByStep3-3 won't compile without itThe reason is that I am referring to the DbConnect class in the project StepByStep3-3, and the project StepByStep3-3 by itself has no definition of DbConnect. When I include a reference to StepByStep3-1.dll, the project StepByStep3-3 can resolve the definition for DbConnect from there and allow me to compile the project.
The client program StepByStep3-3.exe won't execute without itI can't remove StepByStep3-1.dll from the project directory after the compilation is successfully completed. The StepByStep3-1.dll is required again at the time of running the client. This is because to create the proxy object for the DbConnect class, the CLR must have the metadata that describes DbConnect. This metadata is read from the assembly stored in StepByStep3-1.dll.
In some cases, this isn't a good real-life solution because the StepByStep3-1.dll might contain important business logic that you do not want your customers to decompile.
You're right! And, I have a solution for that in the form of interface assemblies. With interface assemblies, you just share the interface of an assembly with your customers, not the actual business logic. I'll show you how to create interface assemblies later in this chapter.
Registering a Remotable Class As a Server-Activated Object Using the Singleton Activation Mode
The same remotable object can be activated in different modes without making any changes to the remotable object itself. In case of SAO, the choice of activation mode is totally with the server. In this section, I'll show you how to create a remoting server that publishes the DbConnect class as an SAO using the Singleton activation mode. I'll use the same client program that was created in Step By Step 3.3 to test this Singleton server.
STEP BY STEP 3.4: Registering a Server-Activated Object Using the Singleton Activation Mode
-
Add a new Visual Basic .NET Console application named StepByStep3-4 to the solution.
-
Add references to the .NET assembly System.Runtime.Remoting and the project StepByStep3-1 (the remotable class assembly).
-
In the Solution Explorer, rename the default Module1.vb to DbConnectSingletonServer.vb. Open the file and change the name of the Module to DbConnectSingletonServer in the module declaration.
-
Add the following directives:
-
Add the following code in the Main() method:
-
Right-click on the StepByStep3-4 project in the Solution Explorer and select Properties. Change the Startup object to DbConnectSingletonServer.
-
Build the project. This step creates a remoting server capable of registering the StepByStep3_1.DbConnect class for remote invocation using the Singleton activation mode.
-
Set the StepByStep3-4, the remoting server, as the startup project. Select Debug, Start Without Debugging to run the project. You should see a command window displaying a message that the server is started in the Singleton mode.
-
Now, set StepByStep3-3, the remoting client, as the startup project. Select Debug, Start Without Debugging to run the project. Enter a query in the text box and click the button. The code invokes a method on the remote object, which is created when the form loads. The code binds the results from the remote method to the DataGrid control.
Imports StepByStep3_1 Imports System.Runtime.Remoting Imports System.Runtime.Remoting.Channels Imports System.Runtime.Remoting.Channels.Tcp
Public Sub Main() ' Create and Register a TCP server channel ' that listens on port Dim channel As TcpServerChannel = _ New TcpServerChannel(1234) ChannelServices.RegisterChannel(channel) ' Register the service that publishes ' DbConnect for remote access in SingleCall mode RemotingConfiguration. _ RegisterWellKnownServiceType( _ GetType(StepByStep3_1.DbConnect), "DbConnect", _ WellKnownObjectMode.Singleton) Console.WriteLine("Started server in the " & _ "Singleton mode") Console.WriteLine("Press <ENTER> to terminate " & _ "server...") Console.ReadLine() End Sub
Although there has been no change in the output for the client, if you note the messages generated by server (see Figure 3.9), you'll see that just one instance of the connection is created and is shared by all the clients that connect to this server.
Figure 3.9 The Singleton remoting server uses the same instance of remote object with subsequent requests.
Guided Practice Exercise 3.1
The objective of this exercise is to create a remoting server that exposes the DbConnect class of StepByStep3-1 as a Singleton SAO. However, the server and client should communicate via the HTTP channels and SOAP formatter. Other than this, the server and the client programs are similar to those created in Step by Step 3.4 and Step by Step 3.3, respectively.
How would you establish communication between a remoting server and client using HTTP and SOAP?
This exercise helps you practice creating a remoting server and clients using the HTTP channels and SOAP formatter.
You should try working through this problem on your own first. If you get stuck, or if you'd like to see one possible solution, follow these steps:
-
Add a new Visual Basic .NET Console application named GuidedPracticeExercise3-1_Server to the solution.
-
Add references to the .NET assembly System.Runtime.Remoting and the project StepByStep3-1 (the remotable class assembly).
-
In the Solution Explorer, rename the default Module1.vb to DbConnectSingletonServer.vb. Open the file and change the name of the class to DbConnectSingletonServer in the class declaration.
-
Add the following directives:
-
Add the following code in the Main() method:
-
Right-click on the GuidedPracticeExercise3-1 Server project in the Solution Explorer and select Properties. Change the startup object to DbConnectSingletonServer.
-
Build the project. This step creates a remoting server that is capable of registering the StepByStep3_1.DbConnect class (the remotable object) for remote invocation using the Singleton activation mode via the HTTP channel.
-
Add a new Visual Basic .NET Windows Application named GuidedPracticeExercise3-1_Client to the solution.
-
Add references to the .NET assembly System.Runtime.Remoting and the project StepByStep3-1 (the remotable class assembly).
-
In the Solution Explorer, delete the default Form1.vb. Add a new form named DbConnectClient.vb. Set the new form as the startup object for the project.
-
Add the following directives to the form's module:
-
Place two GroupBox controls, a TextBox control (txtQuery), a Button control (btnExecute) and a DataGrid control (dgResults) on the form. Set the Multiline property of txtQuery to True. Refer to Figure 3.5 for the design of the form.
-
Add the following code to the form directly after the designer-generated code:
-
Double-click the form and add the following code in the Load event handler:
-
Double-click the Button control and add the following code in the Click event handler:
-
Build the solution. Set the GuidedPracticeExercise3-1_Server, the remoting server, as the startup project. Select Debug, Start Without Debugging to run the project. You should see a command window displaying a message that the server is started in the Singleton mode. The remoting server is now ready to receive SOAP messages via HTTP.
-
Now, set GuidedPracticeExercise3-1_Client, the remoting client, as the startup project. Select Debug, Start Without Debugging to run the project. Enter a query in the text box and click the button. The code invokes a method on the remote object and sends the messages in SOAP format via HTTP.
Imports StepByStep3_1 Imports System.Runtime.Remoting Imports System.Runtime.Remoting.Channels Imports System.Runtime.Remoting.Channels.Http
Sub Main() ' Create and Register a HTTP server channel ' that listens on port Dim channel As HttpServerChannel = _ New HttpServerChannel(1234) ChannelServices.RegisterChannel(channel) ' Register the service that publishes ' DbConnect for remote access in Singleton mode RemotingConfiguration. _ RegisterWellKnownServiceType( _ GetType(StepByStep3_1.DbConnect), "DbConnect", _ WellKnownObjectMode.Singleton) Console.WriteLine("Started server in the " & _ "Singleton mode") Console.WriteLine("Press <ENTER> to terminate " & _ "server...") Console.ReadLine() End Sub
Imports StepByStep3_1 Imports System.Runtime.Remoting Imports System.Runtime.Remoting.Channels Imports System.Runtime.Remoting.Channels.Http
' Declare a Remote object Dim dbc As DbConnect
Private Sub DbConnectClient_Load( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' Register a TCP client channel Dim channel As HttpClientChannel = _ New HttpClientChannel() ChannelServices.RegisterChannel(channel) ' Register the remote class as a valid ' type in the client's application domain RemotingConfiguration. _ RegisterWellKnownClientType( _ GetType(DbConnect), _ "http://localhost:1234/DbConnect") ' Instantiate the remote class dbc = New DbConnect() End Sub
Private Sub btnExecute_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnExecute.Click Try ' Invoke a method on the remote object Me.dgResults.DataSource = _ dbc.ExecuteQuery(Me.txtQuery.Text) dgResults.DataMember = "Results" Catch ex As Exception MessageBox.Show(ex.Message, _ "Query Execution Error") End Try End Sub
If you have difficulty following this exercise, review the sections "Channels," "Formatters," "Creating a Remotable class," and "Creating a Server-Activated Object" earlier in this chapter. Make sure that you also perform Step By Step 3.1 through Step By Step 3.4. After doing that review, try this exercise again.
Creating a Client-Activated Object
When exposing a remotable class as a CAO, no changes are required to be made on the remotable class. Instead, only the server and client differ on how the remotable class is registered with the remoting system.
In this section, I'll show you how to register a remotable class as a CAO and how to instantiate and invoke a CAO from a remoting client.
Registering a Remotable Class As a Client-Activated Object
You'll have to take the following steps to register a remotable class as a CAO on the server:
-
Create a server channel that listens on a particular port to the incoming object activation requests from other application domains. The following examples show how to create a TCP server channel and an HTTP server channel:
-
Register the channel with the remoting framework. This registration is performed through the RegisterChannel() method of the ChannelServices class:
-
Register the remotable class with the remoting framework. For a client-activated object, this registration is performed using the RegisterActivatedServiceType() method of the RemotingConfiguration class as shown here:
' Register a TCP server channel on port Dim channel As TcpServerChannel = _ new TcpServerChannel(1234) ' Register a HTTP server channel on port Dim channel As HttpServerChannel = _ new HttpServerChannel(1234)
' Register the channel with remoting framework ChannelServices.RegisterChannel(channel);
' Register a remote object as CAO ' with the remoting framework RemotingConfiguration.RegisterActivatedServiceType( _ GetType(DbConnect), "DbConnect"))Here, the first parameter is the type of the remotable class. The second parameter specifies the URI through which the server publishes the location of the remote object.
Step By Step 3.5 shows how to expose the now-familiar DbConnect class from Step By Step 3.1 as a CAO.
STEP BY STEP 3.5: Registering a Remotable Class As a Client-Activated Object
-
Add a new Visual Basic .NET Console application named StepByStep3-5 to the solution.
-
Add references to the .NET assembly System.Runtime.Remoting and the project StepByStep3-1 (the remotable class assembly).
-
In the Solution Explorer, rename the default Module1.vb to DbConnectCAOServer.vb. Open the file and change the name of the module to DbConnectCAOServer in the module declaration.
-
Add the following directives:
-
Add the following code in the Main() method:
-
Right-click on the StepByStep3-5 project in the Solution Explorer and select Properties. Change the Startup object to DbConnectCAOServer.
-
Build the project. This step creates a remoting server that is capable of registering the StepByStep3_1.DbConnect (the remotable object) class for remote invocation using the client activation mode.
Imports StepByStep3_1 Imports System.Runtime.Remoting Imports System.Runtime.Remoting.Channels Imports System.Runtime.Remoting.Channels.Tcp
Sub Main() ' Create and Register a TCP Channel on port Dim channel As TcpServerChannel = _ New TcpServerChannel(1234) ChannelServices.RegisterChannel(channel) ' Register the client activated object RemotingConfiguration. _ RegisterActivatedServiceType( _ GetType(DbConnect)) Console.WriteLine( _ "Started server in the Client Activation mode") Console.WriteLine( _ "Press <ENTER> to terminate server...") Console.ReadLine() End Sub
Instantiating and Invoking a Client-Activated Object
To instantiate and invoke a client-activated object, the remoting client needs to take the following steps:
-
Create and register a client channel used by the remoting framework to send messages to the remoting server. The type of channel used by the client should be compatible with the channel used by the server. The following examples show how to create a TCP client channel and an HTTP client channel:
-
Register the remotable class as a valid type in the client's application domain. This registration is performed using the RegisterActivatedClientType() method of the RemotingConfiguration class as shown here:
' Create and register a TCP client channel Dim channel As TcpClientChannel = _ New TcpClientChannel() ChannelServices.RegisterChannel(channel) ' Create and register a HTTP client channel Dim channel As HttpClientChannel = _ New HttpClientChannel() ChannelServices.RegisterChannel(channel)
' Register DbConnect as a type on client, ' which can be activated on the server RemotingConfiguration.RegisterActivatedClientType( _ GetType(DbConnect), "tcp://localhost:1234")Here, the first parameter is the type of the remotable class. The second parameter specifies the uniform resource identifier (URI) through which the server publishes the location of the remote object.
TIP
Instantiating a Client-Activated Object You can instantiate a CAO at the client side using any of its available constructors.
-
Instantiate the CAO on the server using the desired constructor.
' Instantiate the remote object Dim dbc As DbConnect = new DbConnect("Pubs")
I'll demonstrate the preceding steps in Step By Step 3.6. This example is similar to the client program created in Step By Step 3.3, but this time the client allows users to choose between the databases on the server.
STEP BY STEP 3.6: Instantiating and Invoking a Client-Activated Object
-
Add a new Visual Basic .NET Windows Application named StepByStep3-6 to the solution.
-
Add references to the .NET assembly System.Runtime.Remoting and the project StepByStep3-1 (the remotable class assembly).
-
In the Solution Explorer, delete the default Form1.vb. Add a new form named DbConnectClient.vb. Set the new form as the startup object for the project.
-
Add the following directives:
-
Place three GroupBox controls (grpDatabases, grpQuery and grpResults), a ComboBox control (cboDatabases), a TextBox control (txtQuery), two Button controls (btnSelect and btnExecute), and a DataGrid control (dgResults) on the form. Refer to Figure 3.10 for the design of this form.
-
Select the Items property of the cboDatabases control in the Properties window and click on the (...) button. This opens the String Collection Editor dialog box. Enter the following names of databases in the editor:
Northwind Pubs
Click OK to add the databases to the Items collection of the cboDatabases control.
-
Add the following code just after the Windows form designer generated code:
-
Double-click the form and add the following code in the Load event handler:
-
Double-click the btnSelect control and add the following code in the Click event handler:
-
Double-click the btnExecute control and add the following code in the Click event handler:
-
Build the project. You now have a remoting client ready to use.
-
Set StepByStep3-5, the CAO remoting server, as the startup project. Select Debug, Start Without Debugging to run the project. You should see a command window displaying a message that the server is started in the Client Activation mode.
-
Now, set StepByStep3-6, the remoting client, as the startup project. Select Debug, Start Without Debugging to run the project. Select a database from the combo box and click the Select button. An instance of the remotable object, DbConnect, is created with the selected database. Now, enter a query in the text box and click the button. The code invokes a method on the remote object. The code binds the results from the remote method to the DataGrid control, as shown in Figure 3.10.
Imports System.Runtime.Remoting Imports System.Runtime.Remoting.Channels Imports System.Runtime.Remoting.Channels.Tcp Imports StepByStep3_1
' Declare a Remote object Dim dbc As DbConnect
Private Sub DbConnectClient_Load( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load cboDatabases.SelectedIndex = grpQuery.Enabled = False End Sub
Private Sub btnSelect_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnSelect.Click ' Disable the Databases group box and ' Enable the Query group box grpDatabases.Enabled = False grpQuery.Enabled = True ' Register a TCP client channel Dim channel As TcpClientChannel _ = New TcpClientChannel() ChannelServices.RegisterChannel(channel) ' Register the remote class as a valid ' type in the client's application domain ' by passing the Remote class and its URL RemotingConfiguration. _ RegisterActivatedClientType( _ GetType(DbConnect), "tcp://localhost:1234") ' Instantiate the remote class dbc = New DbConnect( _ cboDatabases.SelectedItem.ToString()) End Sub
Private Sub btnExecute_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnExecute.Click Try ' Invoke a method on the remote object Me.dgResults.DataSource = _ dbc.ExecuteQuery(Me.txtQuery.Text) dgResults.DataMember = "Results" Catch ex As Exception MessageBox.Show(ex.Message, _ "Query Execution Error") End Try End Sub
Figure 3.10 A CAO client allows database selection by taking advantage of the capability to call various constructors.
-
Now, again select Debug, Start Without Debugging to run one more instance of the remoting client. Select a different database from the combo box and click the Select button. An instance of the remotable object, DbConnect, is created with the selected database. Now, enter a query in the text box and click the button. You should see that the second instance of the client fetches the data from the selected database. Now switch to the Server command window. You see that the remote object is instantiated twice with different databases, as shown in Figure 3.11. This shows that the client activation creates an instance of remotable object for each client.
Figure 3.11 The client-activated remoting server creates a new instance of the remote object for each client.
REVIEW BREAK
To create a remotable class, inherit the remotable class from the MarshalByRefObject class.
A remotable class is usually connected with the remoting framework through a separate server program. The server program listens to the client request on a specified channel and instantiates the remote object or invokes calls on it as required.
You should create a server channel that listens on a given port number and register the channel with the remoting framework before you register the remotable class.
The type of channel registered by the client must be compatible with the type of channel used by the server for receiving messages.
You do not specify a port number when you register the client channel. The port number is instead specified at the time of registering the remote class in the client's domain.
To register SAO objects on the server side, you call the RemotingConfiguration.RegisterWellKnownServiceType() method; and to register SAO objects on the client side, you call the RemotingConfiguration.RegisterWellKnownClientType() method.
To register CAO objects on the server side, you call the RemotingConfiguration.RegisterActivatedServiceType() method; and to register CAO objects on the client side, you call the RemotingConfiguration.RegisterActivatedClientType() method.
You can only instantiate SAO objects at the client side using their default constructors, whereas you can instantiate CAO using any of the object's constructors.
Using Configuration Files to Configure the Remoting Framework
In all the examples so far, I have written code to register the channel and remote object with the remoting framework. This approach to specifying settings is also known as programmatic configuration. Although this approach works fine, there is a drawbackevery time you decide to make any change in how the channel or the remote objects are registered, you'll have to recompile the code to see the effect of the changes.
Alternatively, you can store the remoting settings in an XML-based configuration file instead of in the code file. Any changes made to the configuration file can be automatically picked up by the program when it executes the next time. You need not recompile the sources. This approach of specifying configuration settings is also known as declarative configuration.
Declarative configuration can be specified at two levels:
Machine-LevelThe configuration settings at the machine-level can be specified through the machine.config file. The machine.config file is present in the CONFIG subdirectory of the .NET Framework installation (typically, Microsoft.NET\Framework\v1.0.3705\CONFIG in the Windows directory of your computer, if you're running version 1.0 of the .NET Framework). Any settings specified in this file apply to all the .NET applications running on the machine.
NOTE
Use Naming Convention for the Application-level Configuration Files Although it's not strictly required, you should prefer using the .NET Framework naming convention for naming the application-level configuration file. This ensures that configuration settings for an application, whether remoting or security related, are all at one place.
Application-LevelThe configuration settings for a specific application can be specified through the application configuration file. In a Windows application, the name of the application-level configuration file includes the full application name and the extension, with .config appended to that extension. For example, the configuration file name for StepByStep3-1.exe is StepByStep3-1.exe.config. In an ASP.NET application, the name of the configuration file is web.config.
TIP
Application-Level Configuration File Takes Precedence over Machine-Level Configuration When you specify both application-level and machine-level configurations for an application, the application-level configuration takes priority over the machine-level configuration.
The general format of a configuration file is a follows:
<configuration> <system.runtime.remoting> <application> <lifetime> <!-- Use this section to specify the --> <!-- lifetime information for all --> <!-- the objects in the application. --> </lifetime> <service> <!-- Use this section to specify how a remote--> <!-- object is exposed by the remoting server--> <!-- Use the <wellknown> tag to configure a --> <!-- a SAO while use the <activated> tag --> <!-- to configure a CAO --> <wellknown /> <activated /> </service> <client> <!-- Use this section to specify how a remote--> <!-- object is consumed by the client --> <!-- Use the <wellknown> tag to configure a --> <!-- a call to SAO while use the <activated> --> <!-- tag to configure a call to CAO --> <wellknown /> <activated /> </client> <channels> <!-- Use this section to configure the --> <!-- channels that the application uses --> <!-- to communicate with the remote objects --> </channels> </application> </system.runtime.remoting> </configuration>
TIP
Configuration Files Configuration files are case sensitive.
Server-Side Configuration
In Step By Step 3.7, I'll create a remoting server with Singleton activation mode similar to the one created in Step By Step 3.4. However, you'll note that the code itself is reduced because most of the configuration-related code is now moved to a separate configuration file.
STEP BY STEP 3.7: Registering a Server-Activated Object in the Singleton Activation Mode Using Configuration Files
-
Add a new Visual Basic .NET Console application named StepByStep3-7 to the solution.
-
Add references to the .NET assembly System.Runtime.Remoting and the project StepByStep3-1 (the remotable class assembly).
-
In the Solution Explorer, right-click project StepByStep3-7 and select Add, Add New Item from the context menu. Add an Item named StepByStep3-7.exe.config based on the XML File template.
-
Open the StepByStep3-7.exe.config file and modify it to contain the following code:
-
In the Solution Explorer, select the project and click the Show All Files button in the toolbar. Move the StepByStep3-7.exe.config file from the project folder to the bin folder under the project, where the StepByStep3-7.exe file will be created when the project is compiled.
-
In the Solution Explorer, rename the default Module1.vb to DbConnectSingletonServer.vb. Open the file and change the name of the module to DbConnectSingletonServer in the module declaration. Set the renamed module as the startup object for the project.
-
Add the following directive:
-
Add the following code in the Main() method:
-
Build the project. This step creates a remoting server capable of registering the StepByStep3-1.DbConnect class for remote invocation using the Singleton activation mode via its settings in the configuration file.
-
Set StepByStep3-7, the remoting server, as the startup project. Select Debug, Start Without Debugging to run the project. You should see a command window displaying a message that the server is started in the Singleton mode by configuring from its settings in the configuration file.
-
Now, set StepByStep3-3, the remoting client, as the startup project. Select Debug, Start Without Debugging to run the project. Enter a query in the text box and click the button. The code invokes a method on the remote object, which is created when the form loads. The code binds the results from the remote method to the DataGrid control.
<configuration> <system.runtime.remoting> <application> <service> <!-- Set the activation mode, remotable object and its URL --> <wellknown mode="Singleton" type= "StepByStep3_1.DbConnect, StepByStep3-1" objectUri="DbConnect" /> </service> <channels> <!-- Set the channel and port --> <channel ref="tcp server" port="1234" /> </channels> </application> </system.runtime.remoting> </configuration>
Imports System.Runtime.Remoting
Sub Main() ' Load remoting configuration RemotingConfiguration.Configure( _ "StepByStep3-7.exe.config") Console.WriteLine("Started server in the " & _ "Singleton mode") Console.WriteLine("Press <ENTER> to terminate " & _ "server...") Console.ReadLine() End Sub
The most important thing to note in Step By Step 3.7 is the way I have written the <service> and the <channels> elements in the configuration file.
The <service> element is written as
<service> <!-- Set the activation mode, remotable object and its URL --> <wellknown mode="Singleton" type= "StepByStep3_1.DbConnect, StepByStep3-1" objectUri="DbConnect" /> </service>
For an SAO, you need to use the <wellknown> element in which you specify the activation mode, type, and the object URI. The type attribute is specified as a pair of qualified class names (StepByStep3_1.DbConnect) and the name of the assembly (StepByStep3-1). The objectUri attribute specifies the endpoint of the URI where the client program will attempt to connect.
The <channels> element can be used to specify the channels used by the server to expose the remotable class. The ref attribute specifies the ID of the channel you want to use. The value ref="tcp server" specifies that the channel is a TCP server channel. If I instead write ref="tcp", the channel becomes a receiver-sender channel.
<channels> <!-- Set the channel and port --> <channel ref="tcp server" port="1234" /> </channels>
With the use of configuration files, the remoting code inside the Main() method of the server is now just one statement:
' Load remoting configuration RemotingConfiguration.Configure( _ "StepByStep3-7.exe.config")
The Configure() method of the RemotingConfiguration class loads the configuration file into memory, parses its contents to locate the <system.runtime.remoting> section, andbased on the settingscalls the relevant methods to register the channels and the remoting objects.
Client-Side Configuration
The configuration of a remoting client is quite similar to that of a remoting server. However, you'll configure the <client> element of the configuration file instead of the <service> element.
Step By Step 3.8 demonstrates how to use client-side configuration files.
STEP BY STEP 3.8: Instantiating and Invoking a Server-Activated Object
-
Add a new Visual Basic .NET Windows Application named StepByStep3-8 to the solution.
-
Add references to the .NET assembly System.Runtime.Remoting and the project StepByStep3-1 (the remotable class assembly).
-
In the Solution Explorer, right-click the project StepByStep3-8 and select Add, Add New Item from the context menu. Add an Item named StepByStep3-8.exe.config based on the XML File template.
-
Open the StepByStep3-8.exe.config file and modify it to contain the following code:
-
In the Solution Explorer, select the project and click the Show All Files button in the toolbar. Move the StepByStep3-8.exe.config file from the project folder to the bin folder under the project, where the StepByStep3-8.exe file will be created when the project is compiled.
-
In the Solution Explorer, delete the default Form1.vb. Add a new form named DbConnectClient.vb. Set the new form as the startup object for the project.
-
Place two GroupBox controls (grpQuery and grpResults), a TextBox control (txtQuery), a Button control (btnExecute) and a DataGrid control (dgResults) on the form. Refer to Figure 3.5 for the design of this form.
-
Add the following directives:
-
Add the following code just after the Windows form designer generated code:
-
Double-click the form and add the following code in the Load event handler:
-
Double-click the Button control and add the following code in the Click event handler:
-
Build the project. Set StepByStep3-7, the remoting server, as the startup project. Select Debug, Start Without Debugging to run the project. You should see a command window displaying a message that the server is started in the Singleton mode by configuring from its settings in the configuration file.
-
Now, set StepByStep3-8, the remoting client as the startup project. Select Debug, Start Without Debugging to run the project. Enter a query in the text box and click the button. The code invokes a method on the remote object, which is created from the settings stored in the configuration file. The code binds the results from the remote method to the DataGrid control.
<configuration> <system.runtime.remoting> <application> <client> <!-- Set the remotable object and its URL --> <wellknown type= "StepByStep3_1.DbConnect, StepByStep3-1" url="tcp://localhost:1234/DbConnect" /> </client> </application> </system.runtime.remoting> </configuration>
Imports System.Runtime.Remoting Imports StepByStep3_1
' Declare a Remote object Dim dbc As DbConnect
Private Sub DbConnectClient_Load( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' Load remoting configuration RemotingConfiguration.Configure( _ "StepByStep3-8.exe.config") ' Instantiate the remote class dbc = New DbConnect() End Sub
Private Sub btnExecute_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnExecute.Click Try ' Invoke a method on the remote object Me.dgResults.DataSource = _ dbc.ExecuteQuery(Me.txtQuery.Text) dgResults.DataMember = "Results" Catch ex As Exception MessageBox.Show(ex.Message, _ "Query Execution Error") End Try End Sub
The most important thing to note from this example is the use of the <client> element in the configuration file. The mode attribute is not part of the <wellknown> element of the client, and the objectUri attribute is replaced with the url attribute that specifies the address to connect to.
<client> <!-- Set the remotable object and its URL --> <wellknown type= "StepByStep3_1.DbConnect, StepByStep3-1" url="tcp://localhost:1234/DbConnect" /> </client>
You can note that unlike the server configuration file, the <channel> element is not required for the client as it determines the protocol and the port number using the specified URL.
Guided Practice Exercise 3.2
In this exercise, you are required to expose the DbConnect class from Step By Step 3.1 as a CAO through a remoting server using an HTTP channel. You also want to invoke methods on this client-activated object by creating a form similar to the one created in Step By Step 3.6.
However, you should be able to change various parameters, such as the channel protocol, port number, URL, name, and type of the remote object, without the need to recompile the server.
How would you design such a remoting client and server?
This exercise helps you practice creating configuration files for both server and client that remote a CAO. You should try working through this problem on your own first. If you get stuck, or if you'd like to see one possible solution, follow these steps:
-
Add a new Visual Basic .NET Console application named GuidedPracticeExercise3-2_Server to the solution.
-
Add references to the .NET assembly System.Runtime.Remoting and the project StepByStep3_1 (the remotable class assembly).
-
In the Solution Explorer, right-click the project GuidedPracticeExercise3-2_Server and select Add, Add New Item from the context menu. Add an Item named GuidedPracticeExercise3-2_Server.exe.config based on the XML File template.
-
Open the GuidedPracticeExercise3-2_Server.exe.config file and modify it to contain the following code:
-
In the Solution Explorer, select the project and click the Show All Files button in the toolbar. Move the GuidedPracticeExercise3-2_Server.exe.config file from the project folder to the bin folder under the project, where the GuidedPracticeExercise3-2_Server.exe file will be created when the project is compiled.
-
In the Solution Explorer, rename the default Module1.vb to DbConnectCAOServer.vb. Open the file and change the name of the module to DbConnectCAOServer in the module declaration. Set the module as the Startup object for the project.
-
Add the following directive:
-
Add the following code in the Main() method:
-
Build the project. This step creates a remoting server capable of registering the StepByStep3_1.DbConnect class for remote invocation using the client activation mode via its settings in the configuration file.
-
Add a new Visual Basic .NET Windows Application named GuidedPracticeExercise3-2_Client to the solution.
-
Add references to the .NET assembly System.Runtime.Remoting and the project StepByStep3-1 (the remotable class assembly).
-
In the Solution Explorer, right-click the project GuidedPracticeExercise3-2_Client and select Add, Add New Item from the context menu. Add an Item named GuidedPracticeExercise3-2_Client.exe.config based on the XML File template.
-
Open the GuidedPracticeExercise3-2_Client.exe.config file and modify it to contain the following code:
-
In the Solution Explorer, select the project and click the Show All Files button in the toolbar. Move the GuidedPracticeExercise3-2_Client.exe.config file from the project folder to the bin\Debug folder under the project, where the GuidedPracticeExercise3-2_Client.exe file will be created when the project is compiled.
-
In the Solution Explorer, remove the default Form1.vb. Add a new form named DbConnectClient.vb. Set the new form as the startup object for the project.
-
Place three GroupBox controls (grpDatabases, grpQuery and grpResults), a ComboBox control (cboDatabases), a TextBox control (txtQuery), two Button controls (btnSelect and btnExecute), and a DataGrid control (dgResults) on the form. Set the Multiline property of the txtQuery control to True. Refer to Figure 3.10 for the design of this form.
-
Select the Items property of the cboDatabases control in the Properties window and click on the (...) button. This opens the String Collection Editor dialog box. Enter the following names of databases in the editor:
Northwind Pubs
Click OK to add the databases to the Items collection of the cboDatabases control.
-
Add the following directives to the form's module:
-
Add the following code directly after the Windows Forms designer generated code:
-
Double-click the form and add the following code in the Load event handler:
-
Double-click the btnSelect control and add the following code in the Click event handler:
-
Double-click the btnExecute control and add the following code in the Click event handler:
-
Build the project. Set the GuidedPracticeExercise3-2_Server, the remoting server, as the startup project. Select Debug, Start Without Debugging to run the project. You should see a command window displaying a message that the server is started in the Client Activation mode by configuring from its settings in the configuration file.
-
Now, set GuidedPracticeExercise3-2_Client, the remoting client as the startup project. Select Debug, Start Without Debugging to run the project. Select a database from the combo box. Enter a query in the text box and click the button. The code invokes a method on the remote object, which is created from the settings stored in the configuration file. The code binds the results from the remote method to the DataGrid control.
<configuration> <system.runtime.remoting> <application> <service> <!-- Set the remotable object --> <activated type= "StepByStep3_1.DbConnect, StepByStep3-1" /> </service> <channels> <channel ref="http" port="1234" /> </channels> </application> </system.runtime.remoting> </configuration>
Imports System.Runtime.Remoting
Sub Main() ' Load remoting configuration RemotingConfiguration.Configure( _ "GuidedPracticeExercise3-2_Server.exe.config") Console.WriteLine( _ "Started server in the Client Activation mode") Console.WriteLine( _ "Press <ENTER> to terminate server...") Console.ReadLine() End Sub
<configuration> <system.runtime.remoting> <application> <!-- Set the url for the client activation --> <client url="http://localhost:1234"> <!-- Set the remote object type and its assembly --> <activated type= "StepByStep3_1.DbConnect, StepByStep3-1" /> </client> </application> </system.runtime.remoting> </configuration>
Imports System.Runtime.Remoting Imports StepByStep3_1
' Declare a Remote object Dim dbc As DbConnect
Private Sub DbConnectClient_Load( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load cboDatabases.SelectedIndex = grpQuery.Enabled = False End Sub
Private Sub btnSelect_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnSelect.Click grpDatabases.Enabled = False grpQuery.Enabled = True ' Load remoting configuration RemotingConfiguration.Configure( _ "GuidedPracticeExercise3-2_Client.exe.config") ' Instantiate the remote class dbc = New DbConnect( _ cboDatabases.SelectedItem.ToString()) End Sub
Private Sub btnExecute_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnExecute.Click Try ' Invoke a method on the remote object Me.dgResults.DataSource = _ dbc.ExecuteQuery(Me.txtQuery.Text) dgResults.DataMember = "Results" Catch ex As Exception MessageBox.Show(ex.Message, _ "Query Execution Error") End Try End Sub
If you have difficulty following this exercise, review the sections "Creating a Client-Activated Object" and "Using Configuration Files to Configure the Remoting Framework" earlier in this chapter. After doing that review, try this exercise again.
Using Interface Assemblies to Compile Remoting Clients
So far, in all the examples, you had to copy the assembly containing the remotable class to the client project (which happens automatically when you set a reference to the assembly) in order for the client to work. However, this is not a desirable solution in many cases because you might not want to share the implementation of the remotable object with your customers or business partners who are writing the client application.
An advisable solution in that case is to only share the interface of the remotable class with the client application. An interface does not contain any implementation; instead, it just contains the members that are supplied by the class.
In the following sections, I'll demonstrate how you can create interfaces that will allow you to create a remote SAO and CAO without sharing the implementation. I'll also introduce the Soapsuds tool, which can help you in automatically creating the interfaces for a remotable class.
Creating an Interface Assembly
In this section, I'll create an assembly that implements an interface named IDbConnect class. The interface defines a contract. All the classes or structs that implement the interface must adhere to this contract.
STEP BY STEP 3.9: Creating an Interface Assembly
-
Add a new Visual Basic .NET Class library named StepByStep3-9 to the solution.
-
In the Solution Explorer, rename the default Class1.vbs to IDbConnect.vb.
-
Open the IDbConnect.vb and replace the code with the following code:
-
Build the project. This step creates an assembly that contains the definition of the IDbConnect interface.
Imports System Imports System.Data Public Interface IDbConnect Function ExecuteQuery(ByVal strQuery As String) _ As DataSet End Interface
Creating a Remotable Object That Implements an Interface
Now that you created the interface IDbConnect, you'll implement this interface in a class named DbConnect. You must ensure that the class DbConnect adheres to the contract defined by the IDbConnect interface. This means that you must implement the method ExecuteQuery() and that the data type of parameters and the return value must match exactly with that defined in the interface.
Step By Step 3.10 creates the class DbConnect that adheres to the IDbConnect interface.
STEP BY STEP 3.10: Creating a Remotable Object That Implements an Interface Assembly
-
Add a new Visual Basic .NET Class library named StepByStep3-10 to the solution.
-
Add references to the .NET assembly System.Runtime.Remoting and the project StepByStep3-9 (the interface assembly).
-
In the Solution Explorer, rename the default Class1.vbs to DbConnect.vb.
-
Open the DbConnect.vb and replace the code with the following code:
-
Build the project. This step creates StepByStep3_10.DbConnect, a remotable class that implements the IDbConnect interface.
Imports System Imports System.Data Imports System.Data.SqlClient Imports StepByStep3_9 ' Marshal-by-Reference Remotable Object Public Class DbConnect Inherits MarshalByRefObject ' Implement the IDbConnect interface Implements IDbConnect Private sqlconn As SqlConnection ' Default constructor connects to the Northwind ' database Public Sub New() sqlconn = New SqlConnection( _ "data source=(local);" & _ "initial catalog=Northwind;" & _ "integrated security=SSPI") Console.WriteLine( _ "Created a new connection " & _ "to the Northwind database") End Sub ' Parameterized constructor connects to the ' specified database Public Sub New(ByVal DbName As String) sqlconn = New SqlConnection( _ "data source=(local);" & _ "initial catalog=" & DbName & ";" & _ "integrated security=SSPI") Console.WriteLine( _ "Created a new connection " & _ "to the " & DbName & " database") End Sub Public Function ExecuteQuery( _ ByVal strQuery As String) As DataSet _ Implements IDbConnect.ExecuteQuery Console.Write("Starting to execute " & _ "the query...") ' Create a SqlCommand to represent the query Dim sqlcmd As SqlCommand = _ sqlconn.CreateCommand() sqlcmd.CommandType = CommandType.Text sqlcmd.CommandText = strQuery ' Create a SqlDataAdapter object ' to talk to the database Dim sqlda As SqlDataAdapter = _ New SqlDataAdapter() sqlda.SelectCommand = sqlcmd ' Create a DataSet to hold the results Dim ds As DataSet = New DataSet() Try ' Fill the DataSet sqlda.Fill(ds, "Results") Catch ex As Exception Console.WriteLine(ex.Message, _ "Error executing query") End Try Console.WriteLine("Done.") ExecuteQuery = ds End Function End CLass
This program is similar to the one created in Step By Step 3.4, with the difference being that the DbConnect class is also implementing the IDbConnect interface in addition to deriving from the MarshalByRefObject class:
' Marshal-by-Reference Remotable Object Public Class DbConnect Inherits MarshalByRefObject ' Implement the IDbConnect interface Implements IDbConnect
You can expose this remotable object to the clients via the remoting framework using the techniques you already know. Step By Step 3.11 creates a remoting server that registers the DbConnect class created in Step By Step 3.10 as an SAO in Singleton mode.
STEP BY STEP 3.11: Creating a Remoting Server to Register the Remotable Object that Implements an Interface Assembly
-
Add a new Visual Basic .NET Console application named StepByStep3-11 to the solution.
-
Add references to the .NET assembly System.Runtime.Remoting, the project StepByStep3-9 (the interface assembly), and StepByStep3-10 (the remotable class assembly).
-
In the Solution Explorer, rename the default Module1.vb to DbConnectSingletonServer.vb. Open the file and change the name of the module to DbConnectSingletonServer in the module declaration. Set the module to be the Startup object of the project.
-
Add the following directives:
-
Add the following code in the Main() method:
-
Build the project. This step creates a remoting server capable of registering StepByStep3_10.DbConnect, the remotable object that implements the StepByStep3_9.IDbConnect interface for remote invocation using the Singleton activation mode.
Imports System.Runtime.Remoting Imports System.Runtime.Remoting.Channels Imports System.Runtime.Remoting.Channels.Tcp
Sub Main() ' Register a TCP server channel that ' listens on port Dim channel As TcpServerChannel = _ New TcpServerChannel(1234) ChannelServices.RegisterChannel(channel) ' Register the service that publishes ' DbConnect for remote access in Singleton mode RemotingConfiguration. _ RegisterWellKnownServiceType( _ GetType(StepByStep3_10.DbConnect), "DbConnect", _ WellKnownObjectMode.Singleton) Console.WriteLine("Started server in the " & _ "Singleton mode") Console.WriteLine("Press <ENTER> to terminate " & _ "server...") Console.ReadLine() End Sub
Creating a Remoting Client That Uses an Interface Instead of the Implementation
When the remotable class is implementing an interface, you can just include the reference to the interface assembly instead of the implementation assembly at the client side. The client will then extract the necessary type information and metadata for compiling and running the program from the interface. Step By Step 3.12 shows you how to create such a client.
STEP BY STEP 3.12: Creating a Remoting Client to Invoke the Remotable Object That Implements an Interface Assembly
-
Add a new Visual Basic .NET Windows Application named StepByStep3-12 to the solution.
-
Add references to the .NET assembly System.Runtime.Remoting and the project StepByStep3-9 (the interface assembly).
-
In the Solution Explorer, delete the default Form1.vb. Add a new form named DbConnectClient.vb, and set it as the startup object for the project.
-
Add the following directives:
-
Place two GroupBox controls (grpQuery and grpResults), a TextBox control (txtQuery), a Button control (btnExecute), and a DataGrid control (dgResults) on the form. Set the Multiline property of txtQuery to True. Refer to Figure 3.5 for the design of this form.
-
Add the following code directly after the Windows Form designer generated code:
-
Double-click the form and add the following code in the Load event handler:
-
Double-click the Button control and add the following code in the Click event handler:
-
Build the project. Set the StepByStep3-11, the remoting server, as the startup project. Select Debug, Start Without Debugging to run the project. You should see a command window displaying a message that the server is started in the Singleton mode.
-
Now, set StepByStep3-12, the remoting client, as the startup project. Select Debug, Start Without Debugging to run the project. Enter a query in the text box and click the button. The code invokes a method on the remote object, which is created when the form loads. The code binds the results from the remote method to the DataGrid control.
Imports System.Runtime.Remoting Imports System.Runtime.Remoting.Channels Imports System.Runtime.Remoting.Channels.Tcp Imports StepByStep3_9
' Declare a Remote object Dim dbc As IDbConnect
Private Sub DbConnectClient_Load( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' Register a TCP client channel Dim channel As TcpClientChannel = _ New TcpClientChannel() ChannelServices.RegisterChannel(channel) ' Instantiate the remote class dbc = CType( _ Activator.GetObject(GetType(IDbConnect), _ "tcp://localhost:1234/DbConnect"), IDbConnect) End Sub
Private Sub btnExecute_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnExecute.Click Try ' Invoke a method on the remote object Me.dgResults.DataSource = _ dbc.ExecuteQuery(Me.txtQuery.Text) dgResults.DataMember = "Results" Catch ex As Exception MessageBox.Show(ex.Message, _ "Query Execution Error") End Try End Sub
In the preceding program, you add the reference to StepByStep3-9.dll. This assembly contains the interface IDbConnect. However, an interface variable cannot be instantiated, and, therefore, you cannot create the instance of the remote object by using the new operator.
But there is an alternative way of creating instances of remote objects, which is especially helpful in the case of interfaces. This is by using the methods of Activator class as described here:
The Activator.GetObject() MethodCalls the proxy to send messages to the remote object. No messages are sent over the network until a method is called on the proxy. This method is useful for activating server-activated objects.
The Activator.CreateInstance() MethodCreates an instance of the specified type using the constructor that best matches the specified parameters. This method is useful for activating client-activated objects.
In Step By Step 3.12, I use the Activator.GetObject() method to create a proxy for the server-activated object indicated by the type IDbConnect and the specified server URL.
Using the Soapsuds Tool to Automatically Generate an Interface Assembly
In the previous section, you learned how you can distribute interface assemblies to the client instead of the implementation assembly. Clients will still be able to instantiate the remote objects in this case.
However, in case of large numbers of clients, distribution of interface files to each of them can become another big issue. However, the .NET Framework SDK provides you the soapsuds tool (soapsuds.exe) to overcome this issue.
Given the URL for a remotable object, the soapsuds tool can automatically generate an interface assembly for the remote object. So all the client needs to know is the URL of the remotable object, and they can generate the interface assembly on their own by using the soapsuds tool. A typical usage of the soapsuds tool is
soapsuds NoWrappedProxy -url:http://MyServer.com/DbConnect?wsdl -outputAssemblyFile:DbConnectInterface.dll
In this command line, the url switch specifies the URL of the remote object. You normally have to append ?wsdl to the URL to allow soapsuds to generate the metadata from the URL. The outputAssemblyFile switch specifies the name of the file in which you want the output assembly to be created. The NoWrappedProxy (or nowp) switch instructs the soapsuds tool to generate an unwrapped proxy.
NOTE
Wrapped Proxies Wrapped proxies are useful when you need to quickly test a Web service because with the use of wrapped proxies, you need not have to write code for channel configuration and remote object registration. However, for more flexibility you should use unwrapped proxies.
By default, the soapsuds tool generates wrapped proxiesproxies that store various connection details, such as the channel formatting and the URL within the proxy itself. Although this means that you need not write the code for these things yourself, it's not recommended because it reduces the flexibility to change the configuration. If you want to avoid specifying these details in the code, a better way is to use the configuration files.
TIP
Soapsuds Tool and Channels The soapsuds tool can only be used with the HTTP channel. If you are using the TCP channel, you still need to depend on manually creating and distributing the interfaces for remotable classes.
Step By Step 3.13 creates a client that uses the soapsuds generated unwrapped proxy to connect with the HTTP server created in the Guided Practice Exercise 3.1.
STEP BY STEP 3.13: Using the Soapsuds Tool to Automatically Generate an Interface Assembly
-
Add a new Visual Basic .NET Windows Application to your solution. Name it StepByStep3-13.
-
Set the GuidedPracticeExercise3-1_Server as the startup project. Select Debug, Start Without Debugging to run the project.
-
Select Start, Programs, Microsoft Visual Studio .NET, Visual Studio .NET Tools, Visual Studio .NET Command Prompt to launch a .NET command prompt.
-
Make sure that the GuidedPracticeExercise3-1_Server is running. Navigate to the bin folder of the StepByStep3-13 project and run the following command to automatically generate an interface assembly for the remotable object DbConnect, registered by the remoting server, GuidedPracticeExercise3-1_Server:
-
In Visual Studio .NET, add references to the .NET assembly System.Runtime.Remoting and DbConnectInterface.dll (the interface assembly auto generated by the soapsuds.exe in step 4).
-
In the Solution Explorer, delete the default Form1.vb. Add a new form named DbConnectClient.vb and set it as the Startup object for the project.
-
Add the following directives:
-
Place two GroupBox controls (grpQuery and grpResults), a TextBox control (txtQuery), a Button control (btnExecute), and a DataGrid control (dgResults) on the form. Set the Multiline property of txtQuery to True. Refer to Figure 3.5 for the design of this form.
-
Add the following code directly after the Windows Form designer generated code:
-
Double-click the form and add the following code in the Load event handler:
-
Double-click the Button control and add the following code in the Click event handler:
-
Build the project. If the GuidedPracticeExercise3-1_Server project is not running, set the GuidedPracticeExercise3-1_Server as the startup project and select Debug, Start Without Debugging to run the project. You should see a command window displaying a message that the server is started in the Singleton mode.
-
Now, set StepByStep3_13, the remoting client, as the startup project. Select Debug, Start Without Debugging to run the project. Enter a query in the text box and click the button. The code invokes a method on the remote object, which is created when the form loads. The code binds the results from the remote method to the DataGrid control.
soapsuds -url:http://localhost:1234/DbConnect?wsdl -oa:DbConnectInterface.dll -nowp
Imports System.Runtime.Remoting Imports System.Runtime.Remoting.Channels Imports System.Runtime.Remoting.Channels.Http Imports StepByStep3_1
' Declare a Remote object Dim dbc As DbConnect
Private Sub DbConnectClient_Load( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' This step is not required if you use ' a wrapped proxy ' Register a HTTP client channel Dim channel As HttpClientChannel = _ New HttpClientChannel() ChannelServices.RegisterChannel(channel) ' This step is not required if you use ' a wrapped proxy. ' Register the remote class as a valid ' type in the client's application domain RemotingConfiguration. _ RegisterWellKnownClientType( _ GetType(DbConnect), _ "http://localhost:1234/DbConnect") ' Instantiate the remote class dbc = New DbConnect() End Sub
Private Sub btnExecute_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnExecute.Click Try ' Invoke a method on the remote object Me.dgResults.DataSource = _ dbc.ExecuteQuery(Me.txtQuery.Text) dgResults.DataMember = "Results" Catch ex As Exception MessageBox.Show(ex.Message, _ "Query Execution Error") End Try End Sub
In Step By Step 3.13, you learned how to use the soapsuds tool to automatically generate the interface class for the remotable object.
TIP
Soapsuds and Client-Activated Objects You cannot use soapsuds with client-activated objects because the metadata generated by the soapsuds tool can only create remote objects using the default constructor.
Also, the interface class generated by the soapsuds tool allows you to directly use the name of remotable class. This means that you can access the remotable class directly in the client as if you have a direct reference to the remotable class at the client side. For this reason, I can use the RegisterWellKnownClientType() method of the RemotingConfiguration class to register the remote class on the client side instead of using the Activator.GetObject() method.
Creating an Interface Assembly That Works with the Client-Activated Objects
Neither of the techniques for generating interface assemblies discussed so far (in the sections, "Creating an Interface Assembly" and "Using the Soapsuds Tool to Automatically Generate an Interface Assembly") is useful for CAO.
The problem lies with the constructors. CAO has capabilities of invoking even the non-default constructors of the remotable class. However, an interface cannot contain the declaration for a constructor as it does with a method or a property.
This common problem is generally solved using the following steps:
Create an interface and a remotable class as shown in the previous examples. For easy reference, I'll call them IDbConnect and DbConnect, respectively. IDbConnect contains definitions of all the methods that the DbConnect class wants to be exposed to the clients.
Create an interface that declares as many different methods as there are constructors in the remotable class. Each of these methods is responsible for creating an object in a way defined by its corresponding constructor. This technique is also called an abstract factory pattern. The name contains the word "factory" because it allows you to create objects in different ways. Let's call this interface IDbConnectFactory.
Create a class that derives from the MarshalByRefObject class and implements the interface created in step 2 (IDbConnectFactory). Implement all methods to actually create the remotable object (DbConnect) based on the given parameters and return the created instance. Let's call this class DbConnectFactory.
Create a remoting server that registers the class created in step 3 (DbConnectFactory) as the remotable class.
Create a client that connects to the server and create an instance of the remotable class created in step 3 (DbConnectFactory).
Invoke the methods corresponding to a constructor on the remotable object created in step 5. The return value of the constructor will be a remotable object of type defined in step 1 (DbConnect).
You now have an object of a type that you originally wanted to remote (DbConnect). You can use this object to invoke methods.
In this section, I'll show you how to implement the preceding technique to create a client-activated object that enables the creation of objects using any of its available constructors.
I'll use the same remotable class that I defined in Step By Step 3.10 (DbConnect) and its interface (IDbConnect) that I defined in Step By Step 3.9. So I'll directly start with step 2 of the preceding list by creating an IDbConnectFactory interface in Step By Step 3.14.
STEP BY STEP 3.14: Creating an Assembly That Works As an Abstract Factory for the IDbConnect Object
-
Add a new Visual Basic .NET Class library named StepByStep3-14 to the solution.
-
Add a reference to the project StepByStep3-9 (the interface assembly).
-
In the Solution Explorer, rename the default Class1.vb to IDbConnectFactory.vb.
-
Open the IDbConnectFactory.vb and replace the code with the following code:
-
Build the project. The class library now contains an interface to a class that can act as a factory of objects implementing the IDbConnect interface.
Imports System Imports System.Data Imports StepByStep3_9 Public Interface IDbConnectFactory Function CreateDbConnectInstance() As IDbConnect Function CreateDbConnectInstance( _ ByVal dbName As String) As IDbConnect End Interface
The next step is to create a class that implements the IDbConnectFactory interface and then exposes that class as a remotable class through the remoting framework. Step By Step 3.15 shows how to do so.
STEP BY STEP 3.15: Creating a Remoting Server That Exposes DbConnectFactory As a Remotable Class
-
Add a new Visual Basic .NET Console application named StepByStep3-15 to the solution.
-
Add references to the .NET assembly System.Runtime.Remoting, the projects StepByStep3-9 (the interface assembly containing IDbConnect), StepByStep3-14 (the new interface assembly containing the IDbConnectFactory), and StepByStep3-10 (the remotable class assembly).
-
Add a new class to the project that will create another remotable object that inherits from MarshalByRefObject class and implements the IDbConnectFactory interface, created in Step By Step 3.14. Name it DbConnectFactory.vb. Open the DbConnectFactory.vb class and replace the code with the following code:
-
In the Solution Explorer, rename the default Module1.vb as DbConnectFactoryServer.vb. Open the file and change the name of the module to DbConnectFactoryServer in the module declaration. Set this module to be the Startup object of the project.
-
Add the following directives:
-
Add the following code in the Main() method:
-
Build the project. This step creates a remoting server capable of registering StepByStep3_10.DbConnect, the remotable object that implements the StepByStep3_9.IDbConnect interface, for remote invocation using the Singleton activation mode.
Imports System Imports StepByStep3_9 Imports StepByStep3_10 Imports StepByStep3_14 Public Class DbConnectFactory Inherits MarshalByRefObject Implements IDbConnectFactory Public Function CreateDbConnectInstance() _ As IDbConnect Implements _ IDbConnectFactory.CreateDbConnectInstance Return New DbConnect() End Function Public Function CreateDbConnectInstance( _ ByVal dbName As String) As IDbConnect _ Implements IDbConnectFactory. _ CreateDbConnectInstance Return New DbConnect(dbName) End Function End Class
Imports System.Runtime.Remoting Imports System.Runtime.Remoting.Channels Imports System.Runtime.Remoting.Channels.Tcp
Sub Main() ' Register a TCP server channel that ' listens on port Dim channel As TcpServerChannel = _ New TcpServerChannel(1234) ChannelServices.RegisterChannel(channel) RemotingConfiguration. _ RegisterWellKnownServiceType( _ GetType(DbConnectFactory), _ "DbConnectFactory", _ WellKnownObjectMode.Singleton) Console.WriteLine("Started server in the " & _ "client activated mode") Console.WriteLine("Press <ENTER> to terminate " & _ "server...") Console.ReadLine() End Sub
Step By Step 3.15 exposes the DbConnectFactory as an SAO in Singleton mode. Although the DbConnectFactory object is registered as an SAO, the objects returned by various methods of DbConnectFactory are CAO because they are created only on the explicit request from the client.
Step By Step 3.16 is the final step for creating CAO using the abstract factory pattern.
STEP BY STEP 3.16: Instantiating and Invoking a Client-Activated Object Using the Abstract Factory Pattern
-
Add a new Visual Basic .NET Windows Application named StepByStep3-16 to the solution.
-
Add references to the .NET assembly System.Runtime.Remoting and the projects StepByStep3-9 (the IDbConnect interface assembly) and StepByStep3-14 (the IDbConnectFactory interface assembly).
-
In the Solution Explorer, delete the default Form1.vb. Add a new form and name it DbConnectClient.vb. Set the new form as the startup object for the project.
-
Add the following directives:
-
Place three GroupBox controls (grpDatabases, grpQuery and grpResults), a ComboBox control (cboDatabases), a TextBox control (txtQuery), two Button controls (btnSelect and btnExecute), and a DataGrid control (dgResults) on the form. Set the Multiline property of txtQuery to True. Refer to Figure 3.10 for the design of this form.
-
Select the Items property of the cboDatabases control in the Properties window and click on the (...) button. This opens String Collection Editor dialog box. Enter the following names of databases in the editor:
Northwind Pubs
Click OK to add the databases to the Items collection of the cboDatabases control.
-
Add the following code directly after the Windows Form designer generated code:
-
Double-click the form and add the following code in the Load event handler:
-
Double-click the btnSelect control and add the following code in the Click event handler:
-
Double-click the btnExecute control and add the following code in the Click event handler:
-
Build the project. This step creates a remoting client that is capable of activating DbConnect as a CAO.
-
Set the StepByStep3-15, the remoting server, as the startup project. Select Debug, Start Without Debugging to run the project. You should see a command window displaying a message that the server is started in the Client Activation mode.
-
Now, set StepByStep3-16, the remoting client, as the startup project. Select Debug, Start Without Debugging to run the project. Select a database from the combo box and click the Select button. An instance of the remotable object, DbConnect, is created with the selected database. Now, enter a query in the text box and click the button. The code invokes a method on the remote object. The code binds the results from the remote method to the DataGrid control.
-
Now, again select Debug, Start Without Debugging to run the remoting client. Select a different database from the combo box and click the Select button. An instance of the remotable object, DbConnect, is created with the selected database. Now, enter a query in the text box and click the button. You should see that the second instance of the client fetches the data from the selected database. Now switch to the Server command window. You see that the remote object is instantiated twice with different databases. This shows that the client activation creates an instance of remotable object per client.
Imports System.Runtime.Remoting Imports System.Runtime.Remoting.Channels Imports System.Runtime.Remoting.Channels.Tcp Imports StepByStep3_9 ' contains IDbConnect Imports StepByStep3_14 ' contains IDbConnectFactory
' Declare a Remote object Dim dbc As IDbConnect
Private Sub DbConnectClient_Load( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load cboDatabases.SelectedIndex = grpQuery.Enabled = False End Sub
Private Sub btnSelect_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnSelect.Click ' Disable the Databases group box and ' Enable the Query group box grpDatabases.Enabled = False grpQuery.Enabled = True ' Register a TCP client channel Dim channel As TcpClientChannel = _ New TcpClientChannel() ChannelServices.RegisterChannel(channel) ' Register the remote class as a valid ' type in the client's application domain ' by passing the Remote class and its URL Dim dbcf As IDbConnectFactory = _ CType(Activator.GetObject(GetType(IDbConnect), _ "tcp://localhost:1234/DbConnectFactory"), _ IDbConnectFactory) dbc = dbcf.CreateDbConnectInstance _ (cboDatabases.SelectedItem.ToString()) End Sub
Private Sub btnExecute_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnExecute.Click Try ' Invoke a method on the remote object Me.dgResults.DataSource = _ dbc.ExecuteQuery(Me.txtQuery.Text) dgResults.DataMember = "Results" Catch ex As Exception MessageBox.Show(ex.Message, _ "Query Execution Error") End Try End Sub
In Step By Step 3.16, it is important to note that although the object for DbConnectFactory is created as a server-activated object, the DbConnect object is always created as the client-activated object. For the DbConnectFactory object, there will be only one instance for all the clients; however, there will be one DbConnect object for each client.
The .NET Framework allows you to store remoting configuration details in an XML-based configuration file instead of the code file. This causes any changes in the configuration file to be automatically picked up, rather than recompiling the code files.
To configure remoting configuration details from configuration files, you should call the RemotingConfiguration.Configure() method and pass the name of the configuration file.
You can distribute the interface assembly to the client instead of the implementation assembly by creating an interface that defines the contract and exposes the member definitions to the client. The remotable class should implement this interface.
You can use the soapsuds tool to automatically generate the interface class for the remotable object instead of manually defining the interface. However, the soapsuds tool only works when the HTTP channel is used for communication.
To create an interface that allows creating client-activated remote objects, you should create an additional interface that declares as many different methods as there are constructors in the remotable class. Each of these methods should be able to create the remote object in a way defined by its corresponding constructor.
Using IIS As an Activation Agent
So far, in this chapter, you are hosting the remotable class by creating your own server that is a console application. A major disadvantage with this approach is that you have to manually start the server if it is not already running.
As discussed before, remoting provides two alternatives to overcome this disadvantage. You can either run the server process as a Windows service instead of a console application, or use IIS (which is a built-in Windows service) as an activation agent for the server process. I'll talk about the former alternative in Chapter 6 and the latter in this section.
Using IIS as an activation agent offers the following advantages:
You need not write a separate server program to register the remotable classes.
You need not worry about finding an available port for your server application. You can just host the remotable object, and IIS automatically uses the port 80.
IIS can provide other functionality such as authentication and secure sockets layer (SSL).
TIP
IIS Does Not Support CAO When creating IIS hosted remote objects, you cannot specify constructor parameters. Therefore, activating CAO is not possible using IIS.
The following list specifies what you need to do in order to host a remotable class in IIS:
Place the assembly containing the remotable objects into the \bin directory of an IIS Web application or place the assembly in the GAC (Global Assembly Cache) on the IIS computer.
Configure the remoting settings by placing the <system.runtime.remoting> configuration section into the web.Config file for the Web application. Alternatively, you can write the configuration code in the Application_Start() method of the global.asax file in the same way you would register a remote object in an .exe host.
NOTE
Channels and IIS Activation IIS Activation only supports the HTTP channel. The default formatting is SOAP, but IIS also supports binary and other custom formatting.
You should not specify a channel. IIS already listens on port 80. Specifying a port for a channel causes exceptions to be thrown when new IIS worker processes are started.
The well-known object URIs must end with ".rem" or ".soap" because these are the two extensions, which are registered with both IIS (via the aspnet_isapi.dll) as well as the remoting system (in machine.config).
Step By Step 3.17 demonstrates how to use IIS for activating the DbConnect remotable class from Step By Step 3.10.
STEP BY STEP 3.17: Using IIS As an Activation Agent
-
Add a new Empty Web Project named StepByStep3-17 to the solution.
-
Add references to the project StepByStep3-9 (the interface assembly) and StepByStep3-10 (the remotable object) by selecting Add Reference from the context menu.
-
Add a Web Configuration File to the project. Open the web.config file and add the following <system.runtime.remoting> element inside the <configuration> element:
-
IIS is now hosting StepByStep3_10.DbConnect, the remotable class, as a server activated object using the Singleton activation mode.
<configuration> <system.runtime.remoting> <application> <service> <!-- Set the activation mode, remotable object and its URL --> <wellknown mode="Singleton" type= "StepByStep3_10.DbConnect, StepByStep3-10" objectUri="DbConnect.rem" /> </service> </application> </system.runtime.remoting> ... </configuration>
If you note the objectUri of the SAO in the preceding example, it ends with the extension .rem.
Step By Step 3.18 demonstrates how to invoke a remote object hosted by IIS.
STEP BY STEP 3.18: Instantiating and Invoking an IIS-Hosted Remote Object
-
Add a new Visual Basic .NET Windows Application named StepByStep3-18 to the solution.
-
Add references to the .NET assembly System.Runtime.Remoting and the project StepByStep3-9 (the interface assembly).
-
In the Solution Explorer, delete the default Form1.vb. Add a new form named DbConnectClient.vb. Set the new form as the startup object for the project.
-
Add the following directives:
-
Place two GroupBox controls, a TextBox control (txtQuery), a Button control (btnExecute), and a DataGrid control (dgResults) on the form. Set the Multiline property of txtQuery to True. Refer to Figure 3.5 for the design of this form.
-
Add the following code directly after the Windows Form designer generated code:
-
Double-click the form and add the following code in the Load event handler:
-
Double-click the Button control and add the following code in the Click event handler:
-
Build the project. This step creates the remoting client that can invoke an IIS-hosted remote object.
-
Set StepByStep3-18, the remoting client, as the startup project. Select Debug, Start Without Debugging to run the project. Enter a query in the text box and click the button. The code invokes a method on the remote object, which is created when the form loads. The code binds the results from the remote method to the DataGrid control.
Imports System.Runtime.Remoting Imports System.Runtime.Remoting.Channels Imports System.Runtime.Remoting.Channels.Http Imports StepByStep3_9 ' contains IDbConnect
' Declare a Remote object Dim dbc As IDbConnect
Private Sub DbConnectClient_Load( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' Register a Http client channel Dim channel As HttpClientChannel = _ New HttpClientChannel() ChannelServices.RegisterChannel(channel) ' Instantiate the remote class dbc = CType( _ Activator.GetObject(GetType(IDbConnect), _ "http://localhost/StepByStep3-17/DbConnect.rem"), _ IDbConnect) End Sub
Private Sub btnExecute_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnExecute.Click Try ' Invoke a method on the remote object Me.dgResults.DataSource = _ dbc.ExecuteQuery(Me.txtQuery.Text) dgResults.DataMember = "Results" Catch ex As Exception MessageBox.Show(ex.Message, _ "Query Execution Error") End Try End Sub
This client was similar to the client created in Step By Step 3.12; however, there are a few things to note. The client is using the HTTP channel to communicate with the server, no port number is specified in the URL, and the URL ends with .rem.
Asynchronous Remoting
So far, all the method invocations that you studied in this chapter have been synchronous. In a synchronous method call, the thread that executes the method call waits until the called method finishes execution.
Synchronous calls can make the user interface very non-responsive if the client program is waiting for a long process to finish execution. This is especially true for remote method calls in which additional time is involved because the calls are made across the network.
NOTE
Asynchronous Method Calls For asynchronous method calls, the remote types need not explicitly support the asynchronous behavior. It is up to the caller to decide whether a particular remote call is asynchronous or not.
The .NET framework has a solution for this in the form of asynchronous methods. An asynchronous method calls the method and returns immediately, leaving the invoked method to complete its execution.
Understanding the Model of Asynchronous Programming in the .NET Framework
In the .NET Framework, asynchronous programming is implemented with the help of delegate types. Delegates are types that are capable of storing references to methods of a specific signature. A delegate declared as follows is capable of invoking methods that take a string parameter and return a string type:
Delegate Function _ LongProcessDelegate(param As String) As String
So, if there is a method definition such as
Function LongProcess(Param As String) As String ... End Function
Then the LongProcessDelegate can hold references to the method like this:
Dim delLongProcess As LongProcessDelegate delLongProcess = New LongProcessDelegate( _ AddressOf LongProcess)
Note the use of the AddressOf operator in returning the location of the LongProcess function.
Once you have the delegate object available, you can use its BeginInvoke() method to call the LongProcess() method asynchronously, such as follows:
Dim ar As IAsyncResult = _ delLongProcess.BeginInvoke("Test", Nothing, Nothing)
The IAsync interface is used to monitor an asynchronous call and relate the beginning and the end of an asynchronous method call. When you use the BeginInvoke() method, the control will immediately come back to the next statement while the LongProcess() method might still be executing.
To return the value of an asynchronous method call, you can call the EndInvoke() method on the same delegate, such as
Dim result As String = delLongProcess.EndInvoke(ar)
However, it is important to know where to place the preceding method call because when you call EndInvoke() and, if the LongProcess() method has not yet completed execution, EndInvoke() will cause the current thread to wait for the completion of LongProcess(). A poor use of EndInvoke(), such as placing it as the very next statement after BeginInvoke(), can potentially cause an asynchronous method call to turn into a synchronous method call.
One of the alternatives to this problem is to use the IsCompleted property of the ISyncResult object to check if the method has completed the execution and call the EndInvoke() method only in such cases.
Dim result As String If (ar.IsCompleted) Then result = delLongProcess.EndInvoke(ar) End If
But regular polling of the ar.IsCompleted property requires additional work at the client side. In fact, there's a better way to do this in the form of the callback methods. In this technique, you can register a method that is automatically invoked as soon as the remote method finishes execution. You can then place a call to EndInvoke() method inside the callback method to collect the result of method execution.
To implement a callback method with an asynchronous method invocation, you need to take the following steps in the client program:
Define a callback method that you want to execute when the remote method has finished execution.
Create an object of delegate type AsyncCallback to store the reference to the method created in step 1.
Create an instance of an object that can receive a remote call to a method.
Declare a delegate type capable of storing references of the remote method.
Using the object from step 3, create a new instance of the delegate declared in step 4 to refer to the remote method.
Call BeginInvoke on the delegate created in step 5, passing any arguments and the AsyncCallback object.
Wait for the server object to call your callback method when the method has completed.
Applying Asynchronous Programming
In the following sections, I'll create a set of three projects to demonstrate the use of callback methods for an asynchronous method call:
The Remotable ClassThe Remotable class exposes the remote methods that are called from the client program.
The Remote ServerI'll use IIS to host the remotable object.
The Client ProgramThe client program calls the remote method asynchronously.
I'll create a remotable class that is different from other remotable classes used in this chapter to help you properly understand synchronous and asynchronous method calls.
The remotable class used in Step By Step 3.19 is named RemotableClass, and it has a single method named LongProcess(). The LongProcess() method waits for about five seconds to simulate a long process call.
STEP BY STEP 3.19: Creating a Remotable Class
-
Add a new Visual Basic .NET Class Library named StepByStep3-19 to the solution.
-
In the Solution Explorer, rename the default Class1.vb to RemotableClass.vb.
-
Open the RemotableClass.vb and replace the code with the following code:
-
Select Build, Build StepByStep3-19. This step generates the code for your class library and packages it into the file StepByStep3-19.dll, which is located in the bin\ directory of your project.
Imports System Imports System.Threading Public Class RemotableClass Inherits MarshalByRefObject Public Function LongProcess(ByVal param As String) _ As String Thread.Sleep(5000) Return param End Function End Class
RemotableClass is now ready to be hosted in a remoting host. In Step By Step 3.20, I decided to host the remotable class using IIS because it requires only a minimal amount of code. I'll, of course, control the remoting configuration by modifying the web.config file.
STEP BY STEP 3.20: Using IIS to Host a Remotable Class
-
Add a new Visual Basic ASP.NET Web Application named StepByStep3-20 to the solution.
-
Add a reference to the project StepByStep3-19 (the remotable class assembly).
-
Open the web.config file and add the following <system.runtime.remoting> element inside the <configuration> element:
-
The remoting server is now hosting the RemotableClass contained in the assembly StepByStep3-19 for remote invocation using the Singleton activation mode.
<configuration> <system.runtime.remoting> <application> <service> <!-- Set the activation mode, remotable object and its URL --> <wellknown mode="Singleton" type="StepByStep3_19.RemotableClass, StepByStep3-19" objectUri="RemotableClass.rem" /> </service> </application> </system.runtime.remoting> ... </configuration>
Neither RemotableClass nor the remoting host contains any additional information that supports an asynchronous method call. The asynchronous call is completely managed in the client code. So in the final step, I'll create a client application that calls a remote method synchronously as well as asynchronously. Showing both ways of calling a method will help you to understand the difference.
STEP BY STEP 3.21: Instantiating and Invoking a Client That Calls Remote Object Methods Synchronously and Asynchronously
-
Add a new Visual Basic .NET Windows Application named StepByStep3-21 to the solution.
-
Add references to the .NET assembly System.Runtime.Remoting.
-
Add a new class file named StepByStep3-19.vb.
-
Replace the code in the StepByStep3-19.vb file with code to define the interface and location of the remote object:
Imports System Imports System.Runtime.Remoting.Messaging Imports System.Runtime.Remoting.Metadata Imports System.Runtime.Remoting.Metadata.W3cXsd2001 <Serializable()> _ Public Class RemotableClass Inherits System.MarshalByRefObject <SoapMethod(SoapAction:= "http://schemas.microsoft.com/clr/nsassem/StepByStep3_19.RemotableClass /StepByStep3-19#LongProcess")> _ Public Function LongProcess(ByVal param As String) _ As String Return (CType(CType(Nothing, Object), String)) End Function End Class
NOTE
Generating the Proxy Class The soapsuds tool will generate source code for a proxy class. However, it will only generate this code in C#, not in VB .NET. The Step By Step 3.19 code was developed by running soapsuds url:http://localhost/StepByStep3-20/RemotableClass.rem?wsdl -gc -nowp and then manually translating the C# code to VB .NET.
-
In the Solution Explorer, delete the default Form1.vb. Add a new form named SyncAsync.vb. Set this form as the startup object for the project.
-
Add the following directives:
-
Place a TextBox control (txtResults) and two Button controls (btnSync and btnAsync) on the form. Refer to Figure 3.12 for the design of this form.
-
Add the following code directly after the Windows Form designer generated code:
-
Double-click the form and add the following code in the Load event handler:
-
Double-click the btnSync control and add the following code in the Click event handler:
-
Double-click the btnAsync control and add the following code in the Click event handler:
-
Add the following callback, LongProcessCompleted() method definition, to the form's code-behind file at the class level:
-
Build the project. This step creates a remoting client for the RemotableClass remotable object.
-
Set the StepByStep3_21, the remoting client, as the startup project. Select Debug, Start Without Debugging to run the project. Click the Call LongProcess Synchronously button to call the LongProcess() method synchronously. You should see the start message appended to the text box, and the application freezes for the next five seconds. After the method call is completed, you notice a completed message and you are now able to work with the application. Now, click the Call LongProcess Asynchronously button to call the LongProcess() method asynchronously. As soon as the method starts, the start message is appended to the text box. While the method is executing, you are able to still work with the application (such as moving the form, clicking buttons and so on, although clicking the synchronous call button freezes the application). When the method is completed, you are notified by appending the completed message in the text box as shown in Figure 3.12.
Imports System.Runtime.Remoting Imports System.Runtime.Remoting.Channels Imports System.Runtime.Remoting.Channels.Http
' Remotable object Dim remObject As RemotableClass ' Create a delegate for the LongProcess method ' of the Remotable object Delegate Function LongProcessDelegate( _ ByVal param As String) As String ' Declare a LongProcessDelegate ' object, an AsyncCallback ' delegate object and an IAsyncResult object Dim delLongProcess As LongProcessDelegate Dim ab As AsyncCallback Dim ar As IAsyncResult ' Declare an integer variable to hold ' number of times the method is called Dim counter As Integer
Private Sub SyncAsync_Load( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' Register a Http client channel Dim channel As HttpClientChannel = _ New HttpClientChannel() ChannelServices.RegisterChannel(channel) ' Instantiate the remote class remObject = CType(Activator.GetObject( _ GetType(RemotableClass), _ "http://localhost/StepByStep3-20/RemotableClass.rem"), _ RemotableClass) ' Create a AsyncCallback delegate object to hold ' the reference of the ' LongProcessCompleted method, which is ' called when the asynchronous call is completed ab = New AsyncCallback( _ AddressOf LongProcessCompleted) ' Create a LongProcessDelegate ' delegate object to hold ' the reference of the LongProcess method delLongProcess = New LongProcessDelegate( _ AddressOf remObject.LongProcess) End Sub
Private Sub btnSync_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnSync.Click ' Increment the method call counter counter += Dim param As String = String.Format( _ "Call: {0}, Type=Synchronous", counter) ' Append the start message to the text box txtResults.AppendText(String.Format( _ "{0}, Started at: {1}" & vbCrLf, _ param, DateTime.Now.ToLongTimeString())) ' Call the LongProcess method ' of the remotable object remObject.LongProcess(param) ' Append the completed message to the text box txtResults.AppendText( _ String.Format("{0}, Completed at: {1}" & _ vbCrLf, _ param, DateTime.Now.ToLongTimeString())) End Sub
Private Sub btnAsync_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnAsync.Click ' Increment the method call counter counter += Dim param As String = String.Format( _ "Call: {0}, Type=Asynchronous", _ counter) ' Append the start message to the text box txtResults.AppendText( _ String.Format("{0}, Started at: {1}\n", _ param, DateTime.Now.ToLongTimeString())) ' Call the BeginInvoke method to start ' the asynchronous method call ar = delLongProcess.BeginInvoke(param, ab, Nothing) End Sub
Sub LongProcessCompleted(ByVal ar As IAsyncResult) ' Call the EndInvoke method to retrieve the return ' value of the asynchronous method call Dim result As String = delLongProcess.EndInvoke(ar) ' Append the completed message to the text box txtResults.AppendText( _ String.Format("{0}, Completed at: {1}\n", _ result, DateTime.Now.ToLongTimeString())) End Sub
Figure 3.12 The asynchronous method call invokes the method and transfers the control back to the form. The asynchronous call uses a callback method to get a notification when the remote method finishes the execution.
In this program, I followed the same steps for an asynchronous method call that were discussed earlier in the previous section, "Understanding the Model of Asynchronous Programming in the .NET Framework."
REVIEW BREAK
You can choose to run the remoting host as a console application, as a Windows service, or as an IIS application.
You can use IIS as an activation agent only when the underlying communication is in HTTP channel. Using IIS as an activation agent eliminates the need to write a separate server program that listens on a unique port number (IIS uses the port 80).
When creating IIS hosted remote objects, you cannot specify constructor parameters; therefore, activating CAO is not possible using IIS.
You can invoke a method asynchronously by calling the BeginInvoke() method on the delegate of that method.
You can automatically get a notification when an asynchronous method ends. However, you must first create another delegate object (of AsyncCallback type) that refers to the callback method that you need to execute when the remote method ends. And then you should pass the delegate to the callback method as an argument to the BeginInvoke() method.