Home > Articles

.NET Remoting

  • Print
  • + Share This
This chapter is from the book

Applying .NET Remoting

So far, I have discussed the architecture and various concepts related to .NET remoting. In this section, you will learn how to apply these concepts to see remoting in action. In particular, you will learn 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 or any of its derived classes. Step-by-Step 3.1 creates a remotable class named DbConnect. This class connects to a specified SQL Server database and enables you to execute a SELECT SQL statement by using its ExecuteQuery() method.

STEP BY STEP 3.1 - Creating a Remotable Class

  1. Launch Visual Studio .NET. Select File, New, Blank Solution, and name the new solution 320C03. Click OK.

  2. Add a new Visual C# .NET class library named StepByStep3_1 to the solution.

  3. In the Solution Explorer, rename the default Class1.cs to DbConnect.cs.

  4. Open the DbConnect.cs and replace the code with the following code:
    using System;
    using System.Data;
    using System.Data.SqlClient;
    
    namespace StepByStep3_1
    {
      // Marshal-by-Reference Remotable Object
      public class DbConnect : MarshalByRefObject
      {
        private SqlConnection sqlconn;
    
        // Default constructor connects to the
        // Northwind database by calling
        // the overloaded constructor
        public DbConnect() : this("Northwind")
        {
        }
    
        // Parameterized constructor connects to the
        // specified database
        public DbConnect(string DbName)
        {
          // Open a connection to the specified
          // sample SQL Server database
          sqlconn = new SqlConnection(
            @"data source=(local);" +
            @"initial catalog=" + DbName +
            @";integrated security=SSPI");
          Console.WriteLine(
            "Created a new connection " +
            "to the {0} database.", DbName);
        }
    
        public DataSet ExecuteQuery(string strQuery)
        {
          Console.Write("Starting to execute " +
            "the query...");
          // Create a SqlCommand object
          // to represent the query
          SqlCommand sqlcmd =
            sqlconn.CreateCommand();
          sqlcmd.CommandType = CommandType.Text;
          sqlcmd.CommandText = strQuery;
    
          // Create a SqlDataAdapter object
          // to talk to the database
          SqlDataAdapter sqlda =
            new SqlDataAdapter();
          sqlda.SelectCommand = sqlcmd;
          // Create a DataSet to hold the results
          DataSet ds = new DataSet();
          try
          {
            // Fill the DataSet
            sqlda.Fill(ds, "Results");
          }
          catch (Exception ex)
          {
            Console.WriteLine(ex.Message,
              "Error executing query");
          }
          Console.WriteLine("Done.");
          return ds;
        }
      }
    }
  5. Select Build, Build StepByStep3_1. This step packages the remotable class into the file StepByStep3_1.dll, which is located in the bin\Debug or bin\Release 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.

Although you now have a remotable class available to you, it cannot be called directly from the client application domains yet. 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

Create and consume a .NET Remoting object.

  • Implement server-activated components.

  • Instantiate and invoke a .NET Remoting 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 allows the design to be modular and the code to be reusable.

In this section, I'll show you how to create a remoting server. To achieve this, the remoting server must take the following steps:

  1. 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 a TCP server channel on port 1234
    TcpServerChannel channel = new TcpServerChannel(1234);
    
    // Register an HTTP server channel on port 1235
    HttpServerChannel channel = new HttpServerChannel(1235);
  2. Register the channel with the remoting framework. This registration is performed through the RegisterChannel() method of the ChannelServices class:
    // Register the channel with the remoting framework
    ChannelServices.RegisterChannel(channel); 
  3. Register the remotable class with the remoting framework. For a server-activated object, the RegisterWellKnownServiceType() method of the RemotingConfiguration class is used to perform this registration, as follows:
    //Register a remote object with the remoting framework
    RemotingConfiguration.RegisterWellKnownServiceType(
      typeof(DbConnect), // type of the remotable class
      "DbConnect",   // URI of the remotable class
      WellKnownObjectMode.SingleCall //Activation mode
    );
  4. 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 remote object's location. The last parameter specifies the activation mode. The activation mode should be one of the two possible values of the WellKnownObjectMode enumeration—SingleCall and Singleton.

TIP

Accessing an Object Through Multiple Channels From step 2 and step 3, 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.

As I discussed, earlier, an SAO can be activated in two different modes—SingleCall 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.

Using the SingleCall Activation Mode to Register a Remotable Class As a Server-Activated Object

In this section, I'll demonstrate how to create a server that exposes the remotable class through the remoting framework. The server process here is a long-running user interface-less process that continues to listen to 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 the 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 system.

However, later in this chapter, in the section "Using IIS As an Activation Agent," I cover how to use IIS as a remoting server. I talk about Windows services later in Chapter 6, "Windows Services."

STEP BY STEP 3.2: Using the SingleCall Activation Mode to Register a Server-Activated Object

  1. Add a new Visual C# .NET console application named StepByStep3_2 to the solution.

  2. In the Solution Explorer, right-click project StepByStep3_2 and select Add Reference from the context menu. In the Add Reference dialog box, 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 (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.4Figure 3.4 The Add Reference dialog box enables you to add references to components.

  1. In the Solution Explorer, rename the default Class1.cs to DbConnectSingleCallServer.cs. Open the file and change the name of the class to DbConnectSingleCallServer in the class declaration.

  2. Add the following using directives:
    using System.Runtime.Remoting;
    using System.Runtime.Remoting.Channels;
    using System.Runtime.Remoting.Channels.Tcp;
  3. Add the following code in the Main() method:
    [STAThread]
    static void Main(string[] args)
    {
      // Create and register a TCP server channel
      // that listens on port 1234
      TcpServerChannel channel =
        new TcpServerChannel(1234);
      ChannelServices.RegisterChannel(channel);
    
      // Register the service that publishes
      // DbConnect for remote access in SingleCall mode
      RemotingConfiguration.RegisterWellKnownServiceType
        (typeof(StepByStep3_1.DbConnect), "DbConnect",
        WellKnownObjectMode.SingleCall);
    
      Console.WriteLine("Started server in the " +
        "SingleCall mode");
      Console.WriteLine("Press <ENTER> to terminate " +
        "server...");
      Console.ReadLine();
    } 
  4. Build the project. This step creates a remoting server that is capable of registering the StepByStep3_1.DbConnect class for remote invocation by using the SingleCall activation mode.

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 the HTTP channel is not difficult—you 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 may or may 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 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 starting 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 65535—provided, of course, that the port number you choose is not used by another internal application. If you are distributing the application, you should get a port number registered from 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. To achieve this, the remoting client needs to take the following steps:

  1. Create and register a client channel that is 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:

    // Create and register a TCP client channel
    TcpClientChannel channel = new TcpClientChannel();
    ChannelServices.RegisterChannel(channel);
    
    // Create and register an HTTP client channel
    HttpClientChannel channel = 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 of registering the remote class in the client's application domain.

  1. Register the remotable class as a valid type in the client's application domain. The RegisterWellKnownClientType() method of the RemotingConfiguration class is used to perform this registration, as shown below:
    // Register the remote class as a valid
    // type in the client's application domain
    RemotingConfiguration.RegisterWellKnownClientType(
      // Remote class
      typeof(DbConnect),
      // URL of the remote class
      "tcp://localhost:1234/DbConnect"
    );
  2. 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.
  3. Instantiate the SAO on the server. You can only use the default constructor.
    // Instantiate the remote object
    DbConnect dbc = new DbConnect();

TIP

Instantiating a Server-Activated Object You can instantiate an SAO at client side only, by using its default constructor.

I demonstrate the preceding steps in Step-by-Step 3.3, where I 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

  1. Add a new Visual C# .NET Windows application named StepByStep3_3 to the solution.

  2. Add references to the .NET assembly System.Runtime.Remoting and the project StepByStep3_1 (the remotable class assembly).

  3. In the Solution Explorer, rename the default Form1.cs to DbConnectClient.cs. Open the form in code view and change all occurrences of Form1 to refer to DbConnectClient instead.

  4. Add the following using directives:

    using System.Runtime.Remoting;
    using System.Runtime.Remoting.Channels;
    using System.Runtime.Remoting.Channels.Tcp;
    using StepByStep3_1;
  5. Place two GroupBox controls, a TextBox control (txtQuery, with its MultiLine property set to true), a Button control (btnExecute), and a DataGrid control (dgResults) on the form. Arrange the controls as shown in Figure 3.5.

Figure 3.5Figure 3.5 This form invokes a method of a remote object to execute the given query.

  1. Add the following code in the class definition:

    // Declare a Remote object
    DbConnect dbc; 
  2. Double-click the form and add the following code in the Load event handler:

  3. private void DbConnectClient_Load(
      object sender, System.EventArgs e)
    {
      // Register a TCP client channel
      TcpClientChannel channel = new TcpClientChannel();
      ChannelServices.RegisterChannel(channel);
    
      // Register the remote class as a valid
      // type in the client's application domain
      RemotingConfiguration.RegisterWellKnownClientType(
        // Remote class
        typeof(DbConnect),
        // URL of the remote class
        "tcp://localhost:1234/DbConnect"
        );
    
      // Instantiate the remote class
      dbc = new DbConnect();
    }

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 to set the project you want to run first as the startup object and select Debug, Run Without Debugging to run the project. This doesn't lock Visual Studio .NET in the debug mode and you can run more programs from within IDE by using the same technique.

  1. Double-click the Button control and add the following code in the Click event handler:

    private void btnExecute_Click
      (object sender, System.EventArgs e)
    {
      try
      {  // Invoke a method on the remote object
        this.dgResults.DataSource =
          dbc.ExecuteQuery(this.txtQuery.Text);
        dgResults.DataMember = "Results";
      }
      catch(Exception ex)
      {
        MessageBox.Show(ex.Message,
          "Query Execution Error");
      }
    }
  2. Right-click on the name of the solution in the Solution Explorer window and select Properties. This opens the Solution '320C03' Property Pages dialog box. In the dialog box, select the Multiple Startup Projects check box and then 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 is not already in order, and then click on the Move Up and Move Down button to get the correct order.

Figure 3.6Figure 3.6 Use the Solution Property Pages dialog box to control what projects are started and in what order.

  1. 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.

  2. Shortly after, 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.7Figure 3.7 The remoting client populates the data grid with the result returned from the method invocation on a remote object.

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, note the output as shown in Figure 3.8. The remote object is created every time you click on the Execute Query button. That's normal behavior based on what you have read so far in the chapter; however, what's peculiar is that for the first call, the constructor is called twice.

Figure 3.8Figure 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 the 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 object's activation mode.

  • The second constructor is called because of the client's call on the remote object. With SingleCall activation, the server does not preserve the state of the constructor that was called earlier and therefore the object has to be re-created with each client request.

Some of you might have a question about why I included a reference to StepByStep3_1.dll in this project. You may support your argument by saying that the DbConnect class contained in the StepByStep3_1.dll is a remotable class and its proper place is on the server—not on the client.

Well said, but I have included the reference to StepByStep3_1.dll for the following reasons:

  • The client project StepByStep3_3 won't compile without it—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 enables me to compile the project.

  • The client program StepByStep3_3.exe won't execute without it—I 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. 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.

However, you would say this won't work in real life, because the StepByStep3_1.dll may 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 in the section "Using Interface Assemblies to Compile Remoting Clients."

Using the Singleton Activation Mode to Register a Remotable Class As a Server-Activated Object

You can activate the same remotable object in different modes without making any changes to the remotable object itself. In the case of SAOs, 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 by 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: Using the Singleton Activation Mode to Register a Server-Activated Object

  1. Add a new Visual C# .NET console application named StepByStep3_4 to the solution.

  2. Add references to the .NET assembly System.Runtime.Remoting, and the project StepByStep3_1 (the remotable class assembly).

  3. In the Solution Explorer, rename the default Class1.cs to DbConnectSingletonServer.cs. Open the file and change the name of the class to DbConnectSingletonServer in the class declaration.

  4. Add the following using directives:

    using System.Runtime.Remoting;
    using System.Runtime.Remoting.Channels;
    using System.Runtime.Remoting.Channels.Tcp;
  5. Add the following code in the Main() method:

    [STAThread]
    static void Main(string[] args)
    {
      // Create and Register a TCP server channel
      // that listens on port 1234
      TcpServerChannel channel =
           new TcpServerChannel(1234);
      ChannelServices.RegisterChannel(channel);
    
      // Resgister the service that publishes
      // DbConnect for remote access in Singleton mode
      RemotingConfiguration.RegisterWellKnownServiceType
        (typeof(StepByStep3_1.DbConnect), "DbConnect",
         WellKnownObjectMode.Singleton);
      Console.WriteLine("Started server in the " +
        "Singleton mode");
      Console.WriteLine("Press <ENTER> to terminate " +
        "server...");
      Console.ReadLine();
    } 
  6. Build the project. This step creates a remoting server that is capable of registering the StepByStep3_1.DbConnect class for remote invocation by using the Singleton activation mode.

  7. Set 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 activation mode.

  8. 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.

Although for the client there has been no changes in the output, if you note the messages generated by the server (see Figure 3.9), you can see that just one instance of the connection is created and is shared by all the clients that connect to this server.

Figure 3.9Figure 3.9 The Singleton remoting server uses the same instance of the 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 use the HTTP channel and SOAP formatter to establish communication between the remoting server and client?

This exercise helps you practice creating a remoting server and client that uses the HTTP channel and SOAP formatter for communication.

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:

  1. Add a new Visual C# .NET console application named GuidedPracticeExercise3_1_Server to the solution.

  2. Add references to the .NET assembly System.Runtime.Remoting and the project StepByStep3_1 (the remotable class assembly).

  3. In the Solution Explorer, rename the default Class1.cs to DbConnectSingletonServer.cs. Open the file and change the name of the class to DbConnectSingletonServer in the class declaration.

  4. Add the following using directives:

    using System.Runtime.Remoting;
    using System.Runtime.Remoting.Channels;
    using System.Runtime.Remoting.Channels.Http;
  5. Add the following code in the Main() method:

    [STAThread]
    static void Main(string[] args)
    {
      // Create and Register an HTTP server channel
      // that listens on port 1234
      HttpServerChannel channel =
        new HttpServerChannel(1234);
      ChannelServices.RegisterChannel(channel);
    
      // Register the service that publishes
      // DbConnect for remote access in Singleton mode
      RemotingConfiguration.RegisterWellKnownServiceType
        (typeof(StepByStep3_1.DbConnect), "DbConnect",
        WellKnownObjectMode.Singleton);
      Console.WriteLine("Started server in the " +
        "Singleton mode");
      Console.WriteLine("Press <ENTER> to terminate " +
        "server...");
      Console.ReadLine();
    } 
  6. 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 by using the Singleton activation mode via the HTTP channel.

  7. Add a new Visual C# .NET Windows application named GuidedPracticeExercise3_1_Client to the solution.

  8. Add references to the .NET assembly System.Runtime.Remoting and the project StepByStep3_1 (the remotable class assembly).

  9. In the Solution Explorer, rename the default Form1.cs to DbConnectClient.cs. Open the form in code view and change all occurrences of Form1 to refer to DbConnectClient instead.

  10. Add the following using directives:

    using System.Runtime.Remoting;
    using System.Runtime.Remoting.Channels;
    using System.Runtime.Remoting.Channels.Http;
    using StepByStep3_1;
  11. Place two GroupBox controls, a TextBox control (txtQuery, with its MultiLine property set to true), a Button control (btnExecute) and a DataGrid control (dgResults) on the form. Refer to Figure 3.5 for the design of the form.

  12. Add the following code in the class definition:

    // Declare a Remote object
    DbConnect dbc; 
  13. Double-click the form and add the following code in the Load event handler:

    private void DbConnectClient_Load
      (object sender, System.EventArgs e)
    {
      // Register an HTTP client channel
      HttpClientChannel channel =
        new HttpClientChannel();
      ChannelServices.RegisterChannel(channel);
    
      // Register the remote class as a valid
      // type in the client's application domain
      RemotingConfiguration.RegisterWellKnownClientType(
        // Remote class
        typeof(DbConnect),
        // URL of the remote class
        "http://localhost:1234/DbConnect"
        );
    
      // Instantiate the remote class
      dbc = new DbConnect();
    }
  14. Double-click the Button control and add the following code in the Click event handler:

    private void btnExecute_Click
      (object sender, System.EventArgs e)
    {
      try
      {  // Invoke a method on the remote object
        this.dgResults.DataSource =
          dbc.ExecuteQuery(this.txtQuery.Text);
        dgResults.DataMember = "Results";
      }
      catch(Exception ex)
      {
        MessageBox.Show(ex.Message,
          "Query Execution Error");
      }
    }
  15. Build the project. 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 activation mode. The remoting server is now ready to receive SOAP messages via HTTP.

  16. 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.

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 to Step-by-Step 3.4. After doing that review, try this exercise again.

Creating a Client-Activated Object

Create and consume a .NET Remoting object.

  • Implement client-activated components.

  • Instantiate and invoke a .NET Remoting object.

When exposing a remotable class as a CAO, no changes are required 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:

  1. 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 a TCP server channel on port 1234
    TcpServerChannel channel = new TcpServerChannel(1234);
    
    // Register an HTTP server channel on port 1235
    HttpServerChannel channel =
      new HttpServerChannel(1235);
  2. Register the channel with the remoting framework. This registration is performed through the RegisterChannel() method of the ChannelServices class:

    // Register the channel with the remoting framework
    ChannelServices.RegisterChannel(channel); 
  3. Register the remotable class with the remoting framework. For a client-activated object, use the RegisterActivatedServiceType() method of the RemotingConfiguration class to perform the registration, as shown below:

    // Register a remote object as a CAO
    // with the remoting framework
    RemotingConfiguration.RegisterActivatedServiceType(
      typeof(DbConnect)); // type of the remotable class
  4. Here, the only parameter is the type of the remotable class.

Step-by-Step 3.5 shows how to expose the familiar DbConnect class from StepByStep3_1 as a CAO.

STEP BY STEP 3.5: Registering a Remotable Class As a Client-Activated Object

  1. Add a new Visual C# .NET console application named StepByStep3_5 to the solution.

  2. Add references to the .NET assembly System.Runtime.Remoting and the project StepByStep3_1 (the remotable class assembly).

  3. In the Solution Explorer, rename the default Class1.cs to DbConnectCAOServer.cs. Open the file and change the name of the class to DbConnectCAOServer in the class declaration.

  4. Add the following using directives:

    using System.Runtime.Remoting;
    using System.Runtime.Remoting.Channels;
    using System.Runtime.Remoting.Channels.Tcp;
    using StepByStep3_1;
  5. Add the following code in the Main() method:

    [STAThread]
    static void Main(string[] args)
    {
      // Create and register a TCP channel on port 1234
      TcpServerChannel channel =
        new TcpServerChannel(1234);
      ChannelServices.RegisterChannel(channel);
    
      // Register the client-activated object
      RemotingConfiguration.RegisterActivatedServiceType
        (typeof(DbConnect));
      Console.WriteLine(
       "Started server in the Client Activation mode");
      Console.WriteLine(
        "Press <ENTER> to terminate server...");
      Console.ReadLine();
    } 
  6. 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 by using the client activation mode.

Instantiating and Invoking a Client-Activated Object

To instantiate and invoke a client-activated object, the remoting client needs to take the following steps:

  1. Create and register a client channel that the remoting framework uses to send messages to the remoting server. The type of the channel the client uses should be compatible with the channel the server uses. The following examples show how to create a TCP client channel and an HTTP client channel:

    // Create and register a TCP client channel
    TcpClientChannel channel = new TcpClientChannel();
    ChannelServices.RegisterChannel(channel);
    
    // Create and register an HTTP client channel
    HttpClientChannel channel = new HttpClientChannel();
    ChannelServices.RegisterChannel(channel);
  2. 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 below:

    // Register DbConnect as a type on client,
    // which can be activated on the server
    RemotingConfiguration.RegisterActivatedClientType
       (typeof(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 by using any of its available constructors.

  1. Instantiate the CAO on the server by using the desired constructor.

    // Instantiate the remote object
    DbConnect dbc = new DbConnect("Pubs");

I'll demonstrate the preceding steps in Step-by-Step 3.6. This step is similar to the client program created in Step-by-Step 3.3, but this time the client allows the user to choose between the databases on the server.

STEP BY STEP 3.6: Instantiating and Invoking a Client-Activated Object

  1. Add a new Visual C# .NET Windows application named StepByStep3_6 to the solution.

  2. Add references to the .NET assembly System.Runtime.Remoting, and the project StepByStep3_1 (the remotable class assembly).

  3. In the Solution Explorer, rename the default Form1.cs to DbConnectClient.cs. Open the form in code view and change all occurrences of Form1 to refer to DbConnectClient instead.

  4. Add the following using directives:

    using System.Runtime.Remoting;
    using System.Runtime.Remoting.Channels;
    using System.Runtime.Remoting.Channels.Tcp;
    using StepByStep3_1;
  5. Place three GroupBox controls (grpDatabases, grpQuery and grpResults), a ComboBox control (cboDatabases), a TextBox control (txtQuery, with its MultiLine property set to true), two Button controls (btnSelect and btnExecute), and a DataGrid control (dgResults) on the form. Refer to Figure 3.10 for this form's design.

  6. 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 database names in the editor:

    Northwind
    Pubs
    GrocerToGo 
  7. Click OK to add the databases to the Items collection of the cboDatabases control.

  8. Add the following code in the class definition:

    // Declare a Remote object
    DbConnect dbc; 
  9. Double-click the form and add the following code in the Load event handler:

    private void DbConnectClient_Load(
      object sender, System.EventArgs e)
    {
      cboDatabases.SelectedIndex = 0;
      grpQuery.Enabled = false;
    }
  10. Double-click the btnSelect control and add the following code in the Click event handler:

    private void btnSelect_Click(
      object sender, System.EventArgs e)
    {
      // Disable the Databases group box and
      // enable the Query group box
      grpDatabases.Enabled = false;
      grpQuery.Enabled = true;
    
      // Register a TCP client channel
      TcpClientChannel channel = 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
        (typeof(DbConnect), "tcp://localhost:1234");
    
      // Instantiate the remote class
      dbc = new DbConnect(
        cboDatabases.SelectedItem.ToString());
    }
  11. Double-click the btnExecute control and add the following code in the Click event handler:

    private void btnExecute_Click
      (object sender, System.EventArgs e)
    {
      try
      {  // Invoke a method on the remote object
        this.dgResults.DataSource =
          dbc.ExecuteQuery(this.txtQuery.Text);
        dgResults.DataMember = "Results";
      }
      catch(Exception ex)
      {
        MessageBox.Show(ex.Message,
          "Query Execution Error");
      }
    }
  12. Build the project. You now have a remoting client ready to use.

  13. 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.

  14. 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.

Figure 3.10Figure 3.10 A CAO client allows database selection by taking advantage of the capability to call various constructors.

  1. 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. Switch to the server command window. You can 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 a remotable object for each client.

Figure 3.11Figure 3.11 The client-activated remoting server creates a new instance of a 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 the client registers should be compatible with the type of channel the server uses for receiving messages.

  • You do not specify a port number when you register the client channel. The port number is instead specified when the remote class is registered in the client's application domain.

  • To register SAO objects, on the server side you call the RemotingConfiguration.RegisterWellKnownServiceType() method and 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 on the client side you call the RemotingConfiguration.RegisterActivatedClientType() method.

  • You can instantiate SAOs only at the client side by using their default constructor, whereas you can instantiate CAOs by using any of the constructors.

Using Configuration Files to Configure the Remoting Framework

Create and consume a .NET Remoting object: Create client configuration files and server configuration files.

In all the examples written so far, I have written code to register the channel and remote object with the remoting framework. This approach of specifying settings is also known as programmatic configuration. Although this approach works fine, there is a drawback: Every time you decide to make any changes in how the channel and the remote objects are registered, you 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 the code file. The program can automatically pick up any changes made to the configuration file when it executes the next time. You need not recompile the sources. This approach of specifying configuration settings is also known as declarative configuration.

The declarative configuration can be specified at two levels:

  • Machine-Level—The 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 directory (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 Conventions for the Application-Level Configuration Files Although it is not 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-related or security-related, are all in one place.

  • Application-Level—The 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 the extension. For example, the configuration file name for StepByStep3_7.exe is StepByStep3_7.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 configuration as well as machine-level configuration for an application, the application-level configuration takes priority over the machine-level configuration.

The general format of the configuration file is as 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-->
   <!-- an SAO and 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 -->
   <!-- call to the SAO and use the <activated> -->
   <!-- tag to configure a call to the 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 create a remoting server with Singleton activation mode, similar to one created in Step-by-Step 3.4. However, you'll note that the code itself is reduced, as most of the configuration-related code is now moved to a separate configuration file.

STEP BY STEP 3.7: Using Configuration Files to Register a Server-Activated Object in the Singleton Activation Mode

  1. Add a new Visual C# .NET console application named StepByStep3_7 to the solution.

  2. Add references to the .NET assembly System.Runtime.Remoting and the project StepByStep3_1 (the remotable class assembly).

  3. 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.

  4. Open the StepByStep3_7.exe.config file and modify it to contain the following code:

    <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>
  5. 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\Debug folder under the project where the StepByStep3_7.exe file will be created when the project is compiled.

  6. In the Solution Explorer, rename the default Class1.cs to DbConnectSingletonServer.cs. Open the file and change the name of the class to DbConnectSingletonServer in the class declaration.

  7. Add the following using directive:

    using System.Runtime.Remoting;
  8. Add the following code in the Main() method:

    [STAThread]
    static void Main(string[] args)
    {
      // 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();
    } 
  9. Build the project. This step creates a remoting server that is capable of registering the StepByStep3_1.DbConnect class for remote invocation by using the Singleton activation mode via its settings in the configuration file.

  10. 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 activation mode by retrieving the remoting configuration settings from the configuration file.

  11. 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.

The most important thing to note in Step-by-Step 3.7 is the way I have written the <service> and <channels> elements in the configuration file.

The <service> element is written as follows:

<service>
  <!-- Set the activcation 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, where you specify the activation mode, type, and the object URI. The type attribute is specified as a pair made up of the qualified classname (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 the server uses 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, and based on the settings, calls the relevant methods to register the channels and the remoting objects.

Client-Side Configuration

The configuration of the remoting client is quite similar to that of the remoting server. However, you configure the <client> element of the configuration file instead of the <service> element.

Step-by-Step 3.8 demonstrates how to use the client-side configuration files.

STEP BY STEP 3.8: Instantiating and Invoking a Server-Activated Object

  1. Add a new Visual C# .NET Windows application named StepByStep3_8 to the solution.

  2. Add references to the .NET assembly System.Runtime.Remoting, and the project StepByStep3_1 (the remotable class assembly).

  3. In the Solution Explorer, right-click 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.

  4. Open the StepByStep3_8.exe.config file and modify it to contain the following code:

    <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>
  5. 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\Debug folder under the project, where the StepByStep3_8.exe file will be created when the project is compiled.

  6. In the Solution Explorer, rename the default Form1.cs to DbConnectClient.cs. Open the form in code view and change all occurrences of Form1 to refer to DbConnectClient instead.

  7. Place two GroupBox controls (grpQuery and grpResults), a TextBox control (txtQuery, with its MultiLine property set to true), a Button control (btnExecute), and a DataGrid control (dgResults) on the form. Refer to Figure 3.5 for this form's design.

  8. Add the following using directives:

    using System.Runtime.Remoting;
    using StepByStep3_1;
  9. Add the following code in the class definition:

    // Declare a Remote object
    DbConnect dbc; 
  10. Double-click the form and add the following code in the Load event handler:

    private void DbConnectClient_Load(
      object sender, System.EventArgs e)
    {
      // Load remoting configuration
      RemotingConfiguration.Configure
        ("StepByStep3_8.exe.config");
    
      // Instantiate the remote class
      dbc = new DbConnect();
    }
  11. Double-click the Button control and add the following code in the Click event handler:

    private void btnExecute_Click(
      object sender, System.EventArgs e)
    {
      try
      {  // Invoke a method on the remote object
        this.dgResults.DataSource =
          dbc.ExecuteQuery(this.txtQuery.Text);
        dgResults.DataMember = "Results";
      }
      catch(Exception ex)
      {
        MessageBox.Show(ex.Message,
          "Query Execution Error");
      }
    }
  12. 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 activation mode by retrieving the remoting configuration settings from the configuration file.

  13. 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.

The most important thing to note in Step-by-Step 3.8 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 the remote object.

<client>
  <!-- Set the remotable object
     and its URL -->
  <wellknown
      type=
       "StepByStep3_1.DbConnect, StepByStep3_1"
      url="tcp://localhost:1234/DbConnect"
  />
</client>

Unlike the server configuration file, the <channel> element is not required for the client because the client uses the URL to determine protocol and the port number.

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 through the HTTP channel. You also need 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 needing to recompile the server.

How would you design such a remoting client and server?

This exercise helps you practice creating configuration files for the remoting server and the client to 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:

  1. Add a new Visual C# .NET console application named GuidedPracticeExercise3_2_Server to the solution.

  2. Add references to the .NET assembly System.Runtime.Remoting and the project StepByStep3_1 (the remotable class assembly).

  3. 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.

  4. Open the GuidedPracticeExercise3_2_Server.exe.config file and modify it to contain the following code:

    <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>
  5. 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\Debug folder under the project, where the GuidedPracticeExercise3_2_Server.exe file will be created when the project is compiled.

  6. In the Solution Explorer, rename the default Class1.cs to DbConnectCAOServer.cs. Open the file and change the name of the class to DbConnectCAOServer in the class declaration.

  7. Add the following using directive:

    using System.Runtime.Remoting;
  8. Add the following code in the Main() method:

    [STAThread]
    static void Main(string[] args)
    {
      // 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();
    } 
  9. Build the project. This step creates a remoting server that is capable of registering the StepByStep3_1.DbConnect class for remote invocation by using the client activation mode via its settings in the configuration file.

  10. Add a new Visual C# .NET Windows application named GuidedPracticeExercise3_2_Client to the solution.

  11. Add references to the .NET assembly System.Runtime.Remoting and the project StepByStep3_1 (the remotable class assembly).

  12. 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.

  13. Open the GuidedPracticeExercise3_2_Client.exe.config file and modify it to contain the following code:

    <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>
  14. In the Solution Explorer, select the project and click the Show All Files button in the tool bar. 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.

  15. In the Solution Explorer, rename the default Form1.cs to DbConnectClient.cs. Open the form in code view and change all occurrences of Form1 to refer to DbConnectClient instead.

  16. Place three GroupBox controls (grpDatabases, grpQuery and grpResults), a ComboBox control (cboDatabases), a TextBox control (txtQuery, with its MultiLine property set to true), 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.

  17. 17Select 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 database names in the editor:

    Northwind
    Pubs
    GrocerToGo 
  18. Click OK to add the databases to the Items collection of the cboDatabases control.

  19. 18Add the following using directives:

    using System.Runtime.Remoting;
    using StepByStep3_1;
  20. Add the following code in the class definition:

    // Declare a Remote object
    DbConnect dbc; 
  21. Double-click the form and add the following code in the Load event handler:

    private void DbConnectClient_Load(
      object sender, System.EventArgs e)
    {
      cboDatabases.SelectedIndex = 0;
      grpQuery.Enabled = false;
    }
  22. Double-click the btnSelect control and add the following code in the Click event handler:

    private void btnSelect_Click(
      object sender, System.EventArgs e)
    {
      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());
    }
  23. Double-click the btnExecute control and add the following code in the Click event handler:

    private void btnExecute_Click(
      object sender, System.EventArgs e)
    {
      try
      {  // Invoke a method on the remote object
        this.dgResults.DataSource =
          dbc.ExecuteQuery(this.txtQuery.Text);
        dgResults.DataMember = "Results";
      }
      catch(Exception ex)
      {
        MessageBox.Show(ex.Message,
          "Query Execution Error");
      }
    }
  24. Build the project. Set 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 retrieving the remoting configuration settings from the configuration file.

  25. Set GuidedPracticeExercise3_2_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, which is created from the settings stored in the configuration file. The code binds the results from the remote method to the DataGrid control.

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, I had to copy the assembly containing the remotable class to the client project for the client to work. However, this is not a desirable solution in most cases because you may 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 share only 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 demonstrate how you can create interfaces that will enable you to create remote SAOs and CAOs without sharing the implementation. I 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 create an assembly that contains an interface named IDbConnect. The interface defines a contract (as shown in Step-by-Step 3.9). All the classes or structs that implement the interface must adhere to this contract.

STEP BY STEP 3.9: Creating an Interface Assembly

  1. Add a new Visual C# .NET class library named StepByStep3_9 to the solution.

  2. In the Solution Explorer, rename the default Class1.cs to IDbConnect.cs.

  3. Open the IDbConnect.cs and replace the code with the following code:

    using System;
    using System.Data;
    
    namespace StepByStep3_9
    {
      public interface IDbConnect
      {
        DataSet ExecuteQuery(string strQuery);
      }
    }
  4. Build the project. This step creates an assembly that contains the definition of the IDbConnect interface.

Creating a Remotable Object That Implements an Interface

Now that you have created the interface IDbConnect, you can 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 you must implement the method ExecuteQuery() and the data types of parameters, and the return value must match with that defined in the interface.

Step-by-Step 3.10 creates the class DbConnect, which adheres to the IDbConnect interface.

STEP BY STEP 3.10: Creating a Remotable Object That Implements an Interface Assembly

  1. Add a new Visual C# .NET class library named StepByStep3_10 to the solution.

  2. Add references to the .NET assembly System.Runtime.Remoting and the project StepByStep3_9 (the interface assembly).

  3. In the Solution Explorer, rename the default Class1.cs to DbConnect.cs.

  4. Open the DbConnect.cs and replace the code with the following code:

    using System;
    using System.Data;
    using System.Data.SqlClient;
    using StepByStep3_9;
    
    namespace StepByStep3_10
    {
      // Marshal-by-Reference Remotable Object
      // Inheriting from MarshalByRefObject and
      // Implementing IDbConnect interface
      public class DbConnect :
         MarshalByRefObject, IDbConnect
      {
        private SqlConnection sqlconn;
    
        // Default constructor connects to the
        // Northwind database
        public DbConnect() : this("Northwind")
        {
        }
    
        // Parameterized constructor connects to the
        // specified database
        public DbConnect(string DbName)
        {
          // Open a connection to the specified
          // sample SQL Server database
          sqlconn = new SqlConnection(
            "data source=(local);" +
            "initial catalog=" + DbName +
            ";integrated security=SSPI");
          Console.WriteLine(
            "Created a new connection to " +
            "the {0} database.", DbName);
        }
    
        public DataSet ExecuteQuery(string strQuery)
        {
          Console.Write("Starting to execute " +
            "the query...");
          // Create a SqlCommand object
          // to represent the query
          SqlCommand sqlcmd =
            sqlconn.CreateCommand();
          sqlcmd.CommandType = CommandType.Text;
          sqlcmd.CommandText = strQuery;
    
          // Create a SqlDataAdapter object
          // to talk to the database
          SqlDataAdapter sqlda =
            new SqlDataAdapter();
          sqlda.SelectCommand = sqlcmd;
          // Create a DataSet to hold the results
          DataSet ds = new DataSet();
          try
          {
            // Fill the DataSet
            sqlda.Fill(ds, "Results");
          }
          catch (Exception ex)
          {
            Console.WriteLine(ex.Message,
              "Error executing query");
          }
          Console.WriteLine("Done.");
          return ds;
        }
      }
    }
  5. Build the project. This step creates StepByStep3_10.DbConnect, a remotable class that implements the IDbConnect interface.

This program is similar to the one created in Step-by-Step 3.1, except that the DbConnect class is now implementing the IDbConnect interface in addition to deriving from the MarshalByRefObject class:

public class DbConnect :
  MarshalByRefObject, IDbConnect
{...}

You can expose this remotable object to the clients via the remoting framework by using the techniques that 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

  1. Add a new Visual C# .NET console application named StepByStep3_11 to the solution.

  2. Add references to the .NET assembly System.Runtime.Remoting, the project StepByStep3_9 (the interface assembly), and StepByStep3_10 (the remotable class assembly).

  3. In the Solution Explorer, rename the default Class1.cs to DbConnectSingletonServer.cs. Open the file and change the name of the class to DbConnectSingletonServer in the class declaration.

  4. Add the following using directives:

    using System.Runtime.Remoting;
    using System.Runtime.Remoting.Channels;
    using System.Runtime.Remoting.Channels.Tcp;
  5. Add the following code in the Main() method:

    [STAThread]
    static void Main(string[] args)
    {
      // Register a TCP server channel that
      // listens on port 1234
      TcpServerChannel channel =
        new TcpServerChannel(1234);
      ChannelServices.RegisterChannel(channel);
    
      // Register the service that publishes
      // DbConnect for remote access in Singleton mode
      RemotingConfiguration.RegisterWellKnownServiceType
        (typeof(StepByStep3_10.DbConnect), "DbConnect",
        WellKnownObjectMode.Singleton);
      Console.WriteLine("Started server in the " +
        "Singleton mode");
      Console.WriteLine("Press <ENTER> to terminate " +
        "server...");
      Console.ReadLine();
    } 
  6. Build the project. This step creates a remoting server that is capable of registering StepByStep3_10.DbConnect, the remotable object that implements StepByStep3_9.IDbConnect interface, for remote invocation by using the Singleton activation mode.

Creating a Remoting Client That Uses an Interface Instead of the Implementation

When the remotable class is implementing an interface, you can include just the reference to the interface assembly rather than the implementation assembly itself at the client side. The client then extracts 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

  1. Add a new Visual C# .NET Windows application named StepByStep3_12 to the solution.

  2. Add references to the .NET assembly System.Runtime.Remoting and the project StepByStep3_9 (the interface assembly).

  3. In the Solution Explorer, rename the default Form1.cs to DbConnectClient.cs. Open the form in code view and change all occurrences of Form1 to refer to DbConnectClient instead.

  4. Add the following using directives:

    using System.Runtime.Remoting;
    using System.Runtime.Remoting.Channels;
    using System.Runtime.Remoting.Channels.Tcp;
    using StepByStep3_9;
  5. Place two GroupBox controls (grpQuery and grpResults), a TextBox control (txtQuery, with its MultiLine property set to true), a Button control (btnExecute), and a DataGrid control (dgResults) on the form. Refer to Figure 3.5 for the design of this form.

  6. Add the following code in the class definition:

    // Declare a Remote object
    IDbConnect dbc; 
  7. Double-click the form and add the following code in the Load event handler:

    private void DbConnectClient_Load(
      object sender, System.EventArgs e)
    {
      // Register a TCP client channel
      TcpClientChannel channel = new TcpClientChannel();
      ChannelServices.RegisterChannel(channel);
    
      // Instantiate the remote class
      dbc = (IDbConnect)
        Activator.GetObject(typeof(IDbConnect),
        @"tcp://localhost:1234/DbConnect");
    }
  8. Double-click the Button control and add the following code in the Click event handler:

    private void btnExecute_Click
      (object sender, System.EventArgs e)
    {
      try
      {  // Invoke a method on the remote object
        this.dgResults.DataSource =
          dbc.ExecuteQuery(this.txtQuery.Text);
        dgResults.DataMember = "Results";
      }
      catch(Exception ex)
      {
        MessageBox.Show(ex.Message,
          "Query Execution Error");
      }
    }
  9. Build the project. Set 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 activation mode.

  10. 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.

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: You can use the methods of the Activator class of the System namespace as follows:

  • The Activator.GetObject() Method—Calls 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 the server-activated objects.

  • The Activator.CreateInstance() Method—Uses the constructor that best matches the specified parameters to create an instance of the specified type. This method is useful for activating the client-activated objects.

In Step-by-Step 3.12, I am using the Activator.GetObject() method to create a proxy for the server-activated object indicated by the type IDbConnect and the server URL.

Using the Soapsuds Tool to Automatically Generate an Interface Assembly

In the previous section, you learned how you can distribute the interface assemblies, rather than the implementation assembly, to the client, and still enable clients to instantiate the remote objects.

However, when you have large numbers of clients, distribution of interface files to each of them is 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. All the clients need to know is the URL of the remotable object. They can then generate interface assemblies on their own by using the Soapsuds tool. A typical usage of the soapsuds.exe is:

soapsuds -nowrappedproxy -urltoschema:http://MyServer.com/DbConnect?wsdl -
outputassemblyfile:DbConnectInterface.dll

NOTE

Wrapped Proxies Wrapped proxies are useful when you need to quickly test a Web service because with the use of wrapped proxies you don't have to write code for channel configuration and remote object registration. However, for better flexibility, you should use unwrapped proxies.

where the urltoschema (or url) switch specifies the remote object's URL, you normally have to append the URL with ?wsdl to enable the Soapsuds tool to generate the metadata from the URL. The outputassemblyfile (or oa) switch specifies the name of the file in which you want the output assembly to be created. The nowrappedproxy (or nwp) switch instructs the Soapsuds tool to generate an unwrapped proxy.

TIP

Soapsuds Tool The Soapsuds tool can be used only 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.

By default the Soapsuds tool generates wrapped proxies. Wrapped proxies are the proxies 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, this is 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.

In Step-by-Step 3.13 you create a client that uses the soapsuds-generated unwrapped proxy to connect with the HTTP server created in Guided Practice Exercise 3.1.

STEP BY STEP 3.13: Using the Soapsuds Tool (soapsuds.exe) to Automatically Generate an Interface Assembly

  1. Set the GuidedPracticeExercise3_1_Server as the startup project. Select Debug, Start Without Debugging to run the project.

  2. Select Start, Programs, Microsoft Visual Studio .NET, Visual Studio .NET Tools, Visual Studio .NET Command Prompt to launch a .NET command prompt.

  3. Make sure that GuidedPracticeExercise3_1_Server is running. Navigate to 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:

    soapsuds -url:http://localhost:1234/DbConnect?wsdl 
    -oa:DbConnectInterface.dll -nowp
  4. Add references to the .NET assembly System.Runtime.Remoting and DbConnectInterface.dll (the interface assembly auto-generated by soapsuds.exe in step 3).

  5. In the Solution Explorer, rename the default Form1.cs to DbConnectClient.cs. Open the form in code view and change all occurrences of Form1 to refer to DbConnectClient instead.

  6. Add the following using directives:

    using System.Runtime.Remoting;
    using System.Runtime.Remoting.Channels;
    using System.Runtime.Remoting.Channels.Http;
    using StepByStep3_1;
  7. Place two GroupBox controls (grpQuery and grpResults), a TextBox control (txtQuery, with its MultiLine property set to true), a Button control (btnExecute), and a DataGrid control (dgResults) on the form. Refer to Figure 3.5 for the design of this form.

  8. Add the following code in the class definition:

    // Declare a Remote object
    DbConnect dbc; 
  9. Double-click the form and add the following code in the Load event handler:

    private void DbConnectClient_Load(
      object sender, System.EventArgs e)
    {
      // This step is not required if you use
      // a wrapped proxy
      // Register an HTTP client channel
      HttpClientChannel channel =
        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(
        // Remote class
        typeof(DbConnect),
        // URL of the remote class
        "http://localhost:1234/DbConnect");
    
      // Instantiate the remote class
      dbc = new DbConnect();
    }
  10. Double-click the Button control and add the following code in the Click event handler:

    private void btnExecute_Click
      (object sender, System.EventArgs e)
    {
      try
      {  // Invoke a method on the remote object
        this.dgResults.DataSource =
          dbc.ExecuteQuery(this.txtQuery.Text);
        dgResults.DataMember = "Results";
      }
      catch(Exception ex)
      {
        MessageBox.Show(ex.Message,
          "Query Execution Error");
      }
    }
  11. 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 activation mode.

  12. 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.

In Step-by-Step 3.13, you learned how to use the Soapsuds tool to automatically generate the interface for the remotable object.

TIP

Soapsuds Tool and Client-Activated Objects You cannot use the Soapsuds tool with the client-activated object because the metadata generated by the Soapsuds tool can use only the default constructor to create the remote objects.

Also, the interface generated by the Soapsuds tool enables you to directly use the name of the remotable class, which means you can access the remotable class directly in the client as if you had a direct reference to the remotable class at the client side. Therefore you can use the RegisterWellKnownClientType() method of the RemotingConfiguration class, rather than the Activator.GetObject() method, to register the remote object on the client side.

Creating an Interface Assembly That Works with the Client-Activated Objects

Both 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" are not useful for CAO.

The problem lies with the constructors. The CAOs have capabilities of invoking even the non-default constructors of the remotable class. However, interfaces cannot contain the declaration for a constructor because they contain only method and property declarations.

This common problem is generally solved by following these steps:

  1. Create an interface and the 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 exposed to the clients.

  2. Create an interface that declares as many different methods as there are constructors in the remotable class. Each method is responsible for creating an object in a way defined by its corresponding constructor. This technique is also called as an abstract factory pattern. The name contains the word "factory" because it enables you to create objects in different ways. Let's call this interface IDbConnectFactory.

  3. 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 (DbConnect). Let's call this class DbConnectFactory.

  4. Create a remoting server that registers the class created in step 3 (DbConnectFactory) as the remotable class.

  5. Create a client that connects to the server and create an instance of the remotable class created in step 3 (DbConnectFactory).

  6. Invoke the methods corresponding to a constructor on the remotable object created in step 5. The return value of the constructor is a remotable object of the type defined in step 1 (DbConnect).

  7. 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 show you how to implement the preceding technique to create a client-activated object that allows you to use any of its available constructors to create objects.

I use the same remotable class that I defined in Step-by-Step 3.10 (DbConnect), and its interface (IDbConnect), which I defined in Step-by-Step 3.9. I'll start directly with Step 2 of 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 Objects.

  1. Add a new Visual C# .NET class library named StepByStep3_14 to the solution.

  2. Add references to the project StepByStep3_9 (the interface assembly).

  3. In the Solution Explorer, rename the default Class1.cs to IDbConnectFactory.cs.

  4. Open the IDbConnectFactory.cs and replace the code with the following code:

    using System;
    using System.Data;
    using StepByStep3_9;
    
    namespace StepByStep3_14
    {
      public interface IDbConnectFactory
      {
        IDbConnect CreateDbConnectInstance();
        IDbConnect CreateDbConnectInstance(
          string dbName);
      }
    }
  5. 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.

The next step is to create a class that implements the IDbConnectFactory interface and then expose that class as a remotable class through the remoting framework. Step-by-Step 3.15 shows the steps for doing so.

STEP BY STEP 3.15: Creating a Remoting Server That Exposes the DbConnectFactory As a Remotable Class

  1. Add a new Visual C# .NET console application named StepByStep3_15 to the solution.

  2. Add references to the .NET assembly System.Runtime.Remoting, the project StepByStep3_9 (the interface assembly containing IDbConnect) StepByStep3_14 (the new interface assembly containing the IDbConnectFactory) and StepByStep3_10 (the remotable class assembly).

  3. 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.cs. Open the DbConnectFactory.cs and replace the code with the following code:

    using System;
    using StepByStep3_9;
    using StepByStep3_10;
    using StepByStep3_14;
    
    namespace StepByStep3_15
    {
      class DbConnectFactory :
        MarshalByRefObject, IDbConnectFactory
      {
        public IDbConnect CreateDbConnectInstance()
        {
          return new DbConnect();
        }
        public IDbConnect CreateDbConnectInstance(
          string dbName)
        {
          return new DbConnect(dbName);
        }
      }
    }
  4. In the Solution Explorer, rename the default Class1.cs to DbConnectFactoryServer.cs. Open the file and change the name of the class to DbConnectFactoryServer in the class declaration.

  5. Add the following using directives:

    using System.Runtime.Remoting;
    using System.Runtime.Remoting.Channels;
    using System.Runtime.Remoting.Channels.Tcp;
  6. Add the following code in the Main() method:

    [STAThread]
    static void Main(string[] args)
    {
      // Register a TCP server channel that
      // listens on port 1234
      TcpServerChannel channel =
        new TcpServerChannel(1234);
      ChannelServices.RegisterChannel(channel);
    
      RemotingConfiguration.RegisterWellKnownServiceType
        (typeof(DbConnectFactory),
        "DbConnectFactory",
        WellKnownObjectMode.Singleton);
      Console.WriteLine("Started server in " +
        "client-activated mode");
      Console.WriteLine("Press <ENTER> to terminate " +
        "server...");
      Console.ReadLine();
    } 
  7. Build the project. This step uses the Singleton activation mode to create a remoting server that is capable of registering StepByStep3_15.DbConnectFactory, the remotable object that implements the StepByStep3_14. IDbConnectFactory interface, for remote invocation.

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 (DbConnect) are CAOs because they are created only on an explicit request from the client.

Step-by-Step 3.16 is the final step for creating a CAO using the abstract factory pattern.

STEP BY STEP 3.16: Using the Abstract Factory Pattern to Instantiate and Invoke a Client-Activated Object

  1. Add a new Visual C# .NET Windows application named StepByStep3_16 to the solution.

  2. 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).

  3. In the Solution Explorer, rename the default Form1.cs to DbConnectClient.cs. Open the form in code view and change all occurrences of Form1 to refer to DbConnectClient instead.

  4. Add the following using directives:

    using System.Runtime.Remoting;
    using System.Runtime.Remoting.Channels;
    using System.Runtime.Remoting.Channels.Tcp;
    using StepByStep3_9; // contains IDbConnect
    using StepByStep3_14; // contains IDbConnectFactory
  5. Place three GroupBox controls (grpDatabases, grpQuery, and grpResults), a ComboBox control (cboDatabases), a TextBox control (txtQuery, with its MultiLine property set to true), two Button controls (btnSelect and btnExecute), and a DataGrid control (dgResults) on the form. Refer to Figure 3.10 for this form's design.

  6. 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 database names in the editor:

    Northwind
    Pubs
    GrocerToGo 

    Click OK to add the databases to the Items collection of the cboDatabases control.

  7. Add the following code in the class definition:

    // Declare a Remote object
    IDbConnect dbc; 
  8. Double-click the form and add the following code in the Load event handler:

    private void DbConnectClient_Load(
      object sender, System.EventArgs e)
    {
      cboDatabases.SelectedIndex = 0;
      grpQuery.Enabled = false;
    }
  9. Double-click the btnSelect control and add the following code in the Click event handler:

    private void btnSelect_Click(
      object sender, System.EventArgs e)
    {
      // Disable the Databases group box and
      // enable the Query group box
      grpDatabases.Enabled = false;
      grpQuery.Enabled = true;
    
      // Register a TCP client channel
      TcpClientChannel channel = 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
      IDbConnectFactory dbcf = (IDbConnectFactory)
         Activator.GetObject(typeof(IDbConnectFactory),
          "tcp://localhost:1234/DbConnectFactory");
    
      dbc = dbcf.CreateDbConnectInstance
         (cboDatabases.SelectedItem.ToString());
    }
  10. Double-click the btnExecute control and add the following code in the Click event handler:

    private void btnExecute_Click
      (object sender, System.EventArgs e)
    {
      try
      {  // Invoke a method on the remote object
        this.dgResults.DataSource =
          dbc.ExecuteQuery(this.txtQuery.Text);
        dgResults.DataMember = "Results";
      }
      catch(Exception ex)
      {
        MessageBox.Show(ex.Message,
          "Query Execution Error");
      }
    }
  11. Build the project. This step creates a remoting client that is capable of activating DbConnect as a CAO.

  12. Set 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 client-activation mode.

  13. 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.

  14. 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 two times the remote object is instantiated with different databases, as shown earlier in Figure 3.10. This shows that client activation creates an instance of the remotable object per client.

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 is only one instance for all the clients; however, there is one DbConnect object for each client.

REVIEW BREAK

  • The .NET Framework allows you to store remoting configuration details in an XML-based configuration file rather than the code file. This causes any changes in the configuration file to be automatically picked up and eliminates the need to recompile the code files.

  • To configure remoting configuration details from configuration files, you should call the RemotingConfiguration.Configure() method and pass the configuration file's name.

  • You can distribute the interface assemblies to the client rather than 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 for the remotable object rather than manually define the interface. However, the Soapsuds tool works only when the HTTP channel is used for communication.

  • To create an interface that allows client-activated remote objects to be created, 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 object in a way that its corresponding constructor defines.

Using IIS As an Activation Agent

Create and consume a .NET Remoting object: Create the listener service.

So far in this chapter, you are hosting the remotable class by creating your own server that is a console application. The 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 as an activation agent (which is a built-in Windows service) for the server process. I'll talk about the former 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 port 80.

  • IIS can provide other functionality, such as authentication and secure socket layers (SSL).

The following list specifies what you need to do 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).

TIP

IIS Does Not Support CAO When creating IIS-hosted remote objects, you cannot specify constructor parameters; therefore it is not possible to use IIS to activate CAO.

  • 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() event handler of the global.asax file in the same way you would register a remote object in an .exe host.

  • 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.

NOTE

Channels and IIS Activation IIS Activation supports only HTTP channels. The default formatting is SOAP, but IIS also supports binary and other custom formatting.

  • The well-known object URIs must end with .rem or .soap because these are the two extensions that 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

  1. Add a new empty Web project named StepByStep3_17 to the solution.

  2. Add references to the project StepByStep3_9 (the interface assembly) and StepByStep3_10 (the remotable object) by selecting Add Reference from the context menu.

  3. 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:

    <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>
  4. IIS is now hosting the StepByStep3_10.DbConnect remotable class as a server-activated object by using the Singleton activation mode.

Note that the objectUri of the SAO in the preceding example ends with the extension .rem.

Step-by-Step 3.18 demonstrates how to invoke a remote object hosted in the IIS.

STEP BY STEP 3.18: Instantiating and Invoking an IIS-Hosted Remote Object

  1. Add a new Visual C# .NET Windows application named StepByStep3_18 to the solution.

  2. Add references to the .NET assembly System.Runtime.Remoting and the project StepByStep3_9 (the interface assembly).

  3. In the Solution Explorer, rename the default Form1.cs to DbConnectClient.cs. Open the form in code view and change all occurrences of Form1 to refer to DbConnectClient instead.

  4. Add the following using directives:

    using System.Runtime.Remoting;
    using System.Runtime.Remoting.Channels;
    using System.Runtime.Remoting.Channels.Http;
    using StepByStep3_9; // contains IDbConnect
  5. Place two GroupBox controls, a TextBox control (txtQuery, with its MultiLine property set to true), a Button control (btnExecute), and a DataGrid control (dgResults) on the form. Refer to Figure 3.5 for the design of this form.

  6. Add the following code in the class definition:

    // Declare a Remote object
    IDbConnect dbc; 
  7. Double-click the form and add the following code in the Load event handler:

    private void DbConnectClient_Load(
      object sender, System.EventArgs e)
    {
      // Register an HTTP client channel
      HttpClientChannel channel =
        new HttpClientChannel();
      ChannelServices.RegisterChannel(channel);
    
      // Instantiate the remote class
      dbc = (IDbConnect)
        Activator.GetObject(typeof(IDbConnect),
      @"http://localhost/StepByStep3_17/DbConnect.rem");
    }
  8. Double-click the Button control and add the following code in the Click event handler:

    private void btnExecute_Click
      (object sender, System.EventArgs e)
    {
      try
      {  // Invoke a method on the remote object
        this.dgResults.DataSource =
          dbc.ExecuteQuery(this.txtQuery.Text);
        dgResults.DataMember = "Results";
      }
      catch(Exception ex)
      {
        MessageBox.Show(ex.Message,
          "Query Execution Error");
      }
    }
  9. Build the project. This step creates the remoting client that can invoke an IIS-hosted remote object.

  10. 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.

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, there is no port number specified in the URL, and the URL ends with .rem.

Asynchronous Remoting

Create and consume a .NET Remoting object: Implement an asynchronous method.

So far, all the method invocations that you've 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.

NOTE

Asynchronous Method Calls For asynchronous method calls, the remote objects need not explicitly support the asynchronous behavior. It is up to the caller to decide whether a particular remote call is asynchronous or not.

Such types of synchronous calls can make the user interface very non-responsive if the client program is waiting for a long process to finish executing on the server. This is especially true for remote method calls where additional time is involved because the calls are made across the network.

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 string LongProcessDelegate(string param);

So if there is a method definition, such as the following:

string LongProcess(string param)
{
...
}

then the LongProcessDelegate can hold references to this method like this:

LongProcessDelegate delLongProcess;
delLongProcess = new LongProcessDelegate(LongProcess);

After you have the delegate object available, you can call its BeginInvoke() method to call the LongProcess() method asynchronously, such as in the following:

IAsyncResult ar =
 delLongProcess.BeginInvoke("Test", null, null);

Here the IAsyncResult 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 immediately comes back to the next statement while the LongProcess() method may still be executing.

To return the value of an asynchronous method call, you can call the EndInvoke() method on the same delegate, such as in the following:

String result = delLongProcess.EndInvoke(ar);

However, it is important to know where to place this method call, because when you call the EndInvoke() method, if the LongProcess() method has not yet completed execution, the EndInvoke() method causes the current thread to wait for the completion of the LongProcess() method. A poor use of the EndInvoke() method, such as placing it in just the next statement after the BeginInvoke() method, can cause an asynchronous method call to result in a synchronous method call.

One of the alternatives to this problem is to use the IsCompleted property of the IAsyncResult object to check whether the method has completed the execution, and then call the EndInvoke() method only in such a case.

string result;
if(ar.IsCompleted)
{
  result = delLongProcess.EndInvoke(ar);
}

But regular polling of the IAsyncResult.IsCompleted property requires additional work at the client side.

You can also use a WaitHandle object to manage asynchronous remote method calls. When you are ready to wait for the results of the remote method call, you can retrieve a WaitHandle object from the IAsyncResult object's AsyncWaitHandle property:

ar.AsyncWaitHandle.WaitOne();
String result = delLongProcess.EndInvoke(ar);

The WaitOne() method of the WaitHandle object causes the thread to pause until the results are ready. The WaitHandle object has other methods that are useful if you have multiple outstanding asynchronous remote method calls. You can wait for all the method calls to come back by using the static WaitHandle.WaitAll() method, or for the first one to return by using the static WaitHandle.WaitAny() method. Therefore, the WaitHandle object essentially lets you turn the asynchronous process back into a synchronous process.

There is, in fact, a better technique for managing asynchronous method invocation—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 the EndInvoke() method inside the callback method to collect the result of remote method execution.

To implement the callback technique with an asynchronous method invocation, you need to take the following steps in the client program:

  1. Define a callback method that you want to execute when the remote method has finished execution.

  2. Create an object of delegate type AsyncCallback to store the reference to the method created in step 1.

  3. Create an instance of the remote object on which you wish to invoke remote method calls.

  4. Declare a delegate type capable of storing references to the remote method.

  5. Using the object in step 3, create a new instance of delegate declared in step 4 to refer to the remote method.

  6. Call the BeginInvoke() method on the delegate created in step 5, passing any arguments and the AsyncCallback object.

  7. Wait for the server object to call your callback method when the method has completed.

Applying Asynchronous Programming

In the following sections I create a set of three projects to demonstrate the use of the callback method for an asynchronous method call:

  • The Remotable Class—The remotable class exposes the remote methods that are called from the client program.

  • The Remote Server—I use IIS to host the remotable object.

  • The Client Program—The client program calls the remote method asynchronously. I use the Soapsuds tool to automatically generate the metadata required to invoke the remote object.

I 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 5 seconds to simulate a long process call.

STEP BY STEP 3.19: Creating a Remotable Class

  1. Add a new Visual C# .NET class library named StepByStep3_19 to the solution.

  2. In the Solution Explorer, rename the default Class1.cs to RemotableClass.cs.

  3. Open the RemotableClass.cs and replace the code with the following code:

    using System;
    using System.Threading;
    
    namespace StepByStep3_19
    {
      public class RemotableClass : MarshalByRefObject
      {
        public string LongProcess(string param)
        {
          Thread.Sleep(5000);
          return param;
        }
      }
    }
  4. 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\Debug or bin\Release directory of your project.

RemotableClass is now ready to be hosted in a remoting host. In Step-by-Step 3.20, I decided to use IIS to host the remotable class because it requires only a minimum amount of code. I control the remoting configuration by modifying the web.config file.

STEP BY STEP 3.20: Using IIS to Host a Remotable Class

  1. Add a new Visual C# ASP.NET application named StepByStep3_20 to the solution.

  2. Add references the project StepByStep3_19 (the remotable class assembly).

  3. Open the web.config file and add the following <system.runtime.remoting> element inside the <configuration> element:

    <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>
  4. The remoting server is now hosting the RemotableClass contained in the assembly StepByStep3_19 for remote invocation by using the Singleton activation mode.

Both RemotableClass, the remote object and the remoting host contain no additional information that supports an asynchronous method call. The asynchronous call is completely dependent on the client code. So in the final step, I create a client application that calls a remote method synchronously as well as asynchronously. Seeing both ways of calling a method will help you note the difference.

STEP BY STEP 3.21: Instantiating and Invoking a Client That Calls Remote Object Methods Synchronously and Asynchronously

  1. Add a new Visual C# .NET Windows application named StepByStep3_21 to the solution.

  2. Add references to the .NET assembly System.Runtime.Remoting.

  3. Select Start, Programs, Microsoft Visual Studio .NET, Visual Studio .NET Tools, Visual Studio .NET Command Prompt to launch a .NET command prompt.

  4. Navigate to the StepByStep3_13 project and run the following command to automatically generate the source code for the interface of the remotable class RemotableClass, registered by the IIS Web server:

    soapsuds -nowp –gc 
    -url:http://localhost/StepByStep3_20/RemotableClass. rem?wsdl
    

    This step generates a file named StepByStep3_19.cs, which contains the interface code for the RemotableClass class.

  5. 5In the Solution Explorer, right-click project StepByStep3_21 and select Add, Add Existing Item to add the StepByStep3_19.cs file (generated by the soapsuds.exe in step 4).

  6. Open the file StepByStep3_19.cs. You will notice that the RemotableClass class definition is applied with two attributes—Serializable and SoapType. Remove the SoapType attribute definition so that the class definition looks like this:

    [Serializable]
    public class RemotableClass :
      System.MarshalByRefObject
    {
      ...
    }
  7. In the Solution Explorer, rename the default Form1.cs to SyncAsync.cs. Open the form in code view and change all occurrences of Form1 to refer to SyncAsync instead.

  8. Add the following using directives:

    using System.Runtime.Remoting;
    using System.Runtime.Remoting.Channels;
    using System.Runtime.Remoting.Channels.Http;
    // Contains RemotableClass interface
    using StepByStep3_19; 
  9. Place a Label control, 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.

  10. Add the following code to the class definition:

    // Remotable object
    RemotableClass remObject;
    
    // Create a delegate for the LongProcess method
    // of the Remotable object
    delegate string LongProcessDelegate(string param);
    
    // Declare a LongProcessDelegate object,
    // an AsyncCallback delegate object,
    // and an IAsyncResult object
    LongProcessDelegate delLongProcess;
    AsyncCallback ab;
    IAsyncResult ar;
    
    // Declare a static integer variable to hold
    // the number of times the method is called
    static int counter; 
  11. Double-click the form and add the following code in the Load event handler:

    private void SyncAsync_Load(
      object sender, System.EventArgs e)
    {
      // Register an HTTP client channel
      HttpClientChannel channel =
        new HttpClientChannel();
      ChannelServices.RegisterChannel(channel);
    
      // Instantiate the remote class
      remObject = (RemotableClass) Activator.GetObject(
        typeof(RemotableClass),
        @"http://localhost/StepByStep3_20/RemotableClass.rem");
    
      // Create an AsyncCallback delegate object to hold
      // the reference of the LongProcessCompleted
      // callback method, which is called when
      // the asynchronous call is completed
      ab = new AsyncCallback(LongProcessCompleted);
    
      // Create a LongProcessDelegate delegate object to
      // hold the reference of the LongProcess method
      delLongProcess = new LongProcessDelegate(
        remObject.LongProcess);
    }
  12. Double-click the btnSync control and add the following code in the Click event handler:

    private void btnSync_Click(
      object sender, System.EventArgs e)
    {
      // Increment the method call counter
      counter++;
      string param = String.Format(
        "Call: {0}, Type=Synchronous", counter);
    
      // Append the start message to the text box
      txtResults.AppendText(String.Format(
        "{0}, Started at: {1}\n",
        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}\n",
        param, DateTime.Now.ToLongTimeString()));
    }
  13. Double-click the btnAsync control and add the following code in the Click event handler:

    private void btnAsync_Click(
      object sender, System.EventArgs e)
    {
      // Increment the method call counter
      counter++;
      string param = 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, null);
    }
  14. Add the following callback method definition for LongProcessCompleted() to the class:

    void LongProcessCompleted(IAsyncResult ar)
    {
      // Call the EndInvoke method to retrieve the
      // return value of the asynchronous method call
      string result = delLongProcess.EndInvoke(ar);
    
      // Append the completed message to the text box
      txtResults.AppendText(
        String.Format("{0}, Completed at: {1}\n",
        result, DateTime.Now.ToLongTimeString()));
    }
  15. Build the project. This step creates a remoting client for the RemotableClass remotable object.

  16. Set StepByStep3_21, the remoting client, as the startup project. Select Debug, Start Without Debugging to run the project. Click the Call Long Process 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 Long Process 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 can still work with the application (such as by moving the form, clicking buttons, and so on, although clicking the synchronous call button freezes the application). When the method is completed, you notice a completed message in the text box, as shown in Figure 3.12.

Figure 3.12Figure 3.12 The asynchronous method call invokes the method and transfers the control back to the form. The asynchronous call can use a callback method to get a notification when the remote method finishes execution.

In this program I am following 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."

The only surprise in Step-by-Step 3.21 is the special use of the Soapsuds tool. Step 4 uses the Soapsuds tool to generate the source code of the interface assembly instead of the assembly itself. The soapsuds-generated assembly uses a SoapType attribute that doesn't work with delegates. The advantage of soapsuds-generated source code is that I can manually remove the problematic SoapType attribute and compile the program to generate the interface assembly.

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 the 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 using IIS to activate CAO is not possible.

  • You can invoke a method asynchronously by calling the BeginInvoke() method on that method's delegate.

  • 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.

  • + Share This
  • 🔖 Save To Your Account