.NET Remoting and SOAP

This article has been excerpted from book "The Complete Visual C# Programmer's Guide" from the Authors of C# Corner.

.NET Remoting is a framework built into the common language runtime (CLR) that can be used to build sophisticated distributed applications and network services. The CLR remoting infrastructure provides a rich set of classes that allows developers to ignore most of the complexities of deploying and managing remote objects. Although we are dealing with applications running against different runtime environments, calling methods on remote objects is nearly identical to calling local methods. This is a new procedure when compared with COM+ and CORBA; it is more platform independent because it is XML based.

When a client creates an instance of a remote object, it receives a proxy representing the class instance on the server. All methods called on the proxy are forwarded automatically to the remote class, and any result is returned to the client. From the client's perspective, this process is no different than making a local call. Any exception thrown by the remote object is returned automatically to the client. This enables the client to use normal try-and-catch blocks around sections of the code to trap and deal with exceptions.

When a client calls a method on a remote object, the remoting framework automatically serializes any data associated with the request and uses a channel to transport the data to the remote object. Some of the more popular channels supported are HTTP, TCP, and SMTP. In the case of HTTP, the framework uses the SOAP protocol to transport data in XML format from the client to the server and back. The default serialization formatter for HTTP is a SOAP formatter. Because programmers can create custom formatters to use with any channel, the remoting framework can be configured to work with any external .NET Framework on other platforms. The TCP channel uses plain sockets and binary serialization by default and can be used to communicate with any object on a remote server. Remote objects can be hosted easily in Internet Information Server (IIS). This allows any client to connect to the object by using normal HTTP on port 80. It is also possible to create Web pages that allow a user to connect to a remote object by using Internet Explorer.

A SOAP Client/Server Application in .NET

Listing 23.9 shows a simple SOAP server application.

Listing23.9.cs , DateTimeServer and DateTimeServer remote object

Execute the following commands to generate two files from the source code-object1.dll and Listing23.9.exe:

csc /t:library /out:object1.dll Listing23.9.cs
csc /r:object1.dll Listing23.9.cs

Listing 23.9: SOAP Server1 (Listing23.9.cs)


// compile with:
// csc /out:object1.dll Listing23.9.cs
// csc /r:object1.dll Listing23.9.cs
/* sample output:
press <enter> to exit
DateTime server activated
DateTime server activated
Hi Bozo the clown. Here is the current DateTime: 8/19/2002 9:22:23 AM
DateTime server activated
DateTime server Object Destroyed
*/


using
System;
using
System.Runtime.Remoting;
using
System.Runtime.Remoting.Channels;
using
System.Runtime.Remoting.Channels.Http;

namespace
ExampleRemoting
{
    public class DateTimeServer : MarshalByRefObject, IDisposable
    {
        public DateTimeServer()
        {
            Console.WriteLine("DateTime server activated");
        }

        ~DateTimeServer()
        {
            Console.WriteLine("DateTime server Object Destroyed.");
        }

        public void Dispose()
        {
            GC.SuppressFinalize(this);
        }

        public String MyMethod(String name)
        {
            String strMessage = "Hi " + name + ". Here is the current DateTime: " + DateTime.Now;
            Console.WriteLine(strMessage);
            return strMessage;
        }
    }

    public class Server
    {
        public static void Main()
        {
            HttpChannel channel = new HttpChannel(9999);
            ChannelServices.RegisterChannel(channel);
            RemotingConfiguration.RegisterWellKnownServiceType(
            Type.GetType("ExampleRemoting.DateTimeServer,Listing23.9"), "SayDateTime",
            WellKnownObjectMode.SingleCall);
            System.Console.WriteLine("press <enter> to exit.");
            System.Console.ReadLine();
        }

        public String MyMethod(String name)
        {
            String strMessage = "Hi " + name + ". Here is the current DateTime: " + DateTime.Now;
            Console.WriteLine(strMessage);
            return strMessage;
        }
    }
}


When a client calls MyMethod on the DateTimeServer class, the server object appends the string passed from the client to the current DateTime and returns the resulting string to the client. The DateTimeServer class is derived from MarshalByRefObject to make it remotable. When the server is started, we create and register a HTTP channel that will listen for clients to connect on port 9999. We also register the remote object with the remoting framework by calling RemotingConfiguration.RegisterWellKnownServiceType.

When you start the server, the object will be instantiated as part of the registration process so the framework can extract the relevant metadata from the object. After registration, this object is destroyed, and the framework starts listening for clients to connect on the registered channels.

Clients can reach and reference remote objects in the following ways:

  • When we compile the client, the server object can be compiled and specified as an EXE (executable) or a DLL (dynamic-link library) reference to the compiler.
  • The server and client can both implement the same interfaces. The interfaces can be compiled to a DLL and shipped to the client site as necessary.
  • The utility SOAPSUDS.EXE can be used to generate proxies for the remote component. The Soapsuds tool can extract the required metadata from a running server object. It can be pointed to a remote Uniform Resource Identifier (URI) and generate the required metadata as source code or a DLL. Notice that Soapsuds creates only metadata, as if we were using or implementing an interface. It will not generate the source code for the remote object.

Generally the preferred way is to use interfaces common to both the client and server. This is like using a type library (TLB) file of a COM+ component. When you are distributing a COM+ component, it is enough to deliver only type library, which includes only global unique identifiers (GUIDs) and function signatures. We will see an example later in the chapter in the section "Using Common Interfaces." Creating a client proxy requires us to use the Soapsuds tool provided by Microsoft. That utility reads the XML description and generates a proxy assembly (class signatures) used to access the SOAP server. For example:

soapsuds -url:http://<hostname>:1095/ServiceClass?WSDL -oa:Server1

This creates a proxy called Server1.dll that will be used for access by referencing the remote object from the client.

Microsoft .NET Remoting provides a rich and extensible framework for objects living in different application domains, in different processes, and in different machines to communicate with each other seamlessly. .NET Remoting offers a powerful yet simple programming model and runtime support for making such interactions transparent. Two types of objects can be configured to serve as .NET remote objects. The type you choose depends on the requirements of your application. SingleCall objects service one and only one request coming in. They are useful in scenarios where objects are required to do a finite amount of work and cannot store state information. SingleCall objects can be configured in a load-balanced fashion. They cannot hold state information between method calls. Singleton objects service multiple clients and should not store instance data. They are useful in cases where data needs to be explicitly shared between clients and also where the overhead of creating and maintaining objects is substantial.

Client-activated objects are server-side objects that are activated on request from the client. This way of activating server objects is very similar to the classic COM co-class activation. When the client requests a server object by using the new operator, an activation request message is sent to the remote application. The server then creates an instance of the requested class and returns an ObjRef back to the client application that invoked it. A proxy is then created on the client side by using the ObjRef. The client's method calls will be executed on the proxy. A client-activated object can maintain state information between method calls. Each invocation of new returns a proxy to an independent instance of the server type.

Execute the following command to compile the client source code in Listing 23.10 to generate proxy object object11.dll and client executable Listing23.10.exe:

soapsuds -url:http://127.0.0.1:9999/SayDateTime?WSDL -oa:object11.dll

csc /r:object11.dll Listing23.10.cs

Listing 23.10: SOAP Client1 (Listing23.10.cs)


/* after executing the Listing23.9.exe, use the SOAPSUDS tool to create
object11.dll proxy:
soapsuds -url:http://127.0.0.1:9999/SayDateTime?WSDL -oa:object11.dll
*/
// compile with:
// csc /r:object11.dll Listing23.10.cs


using
System;
using
System.Runtime.Remoting;
using
System.Runtime.Remoting.Channels;
using
System.Runtime.Remoting.Channels.Http;

namespace
ExampleRemoting
{
    public class Client
    {
        public static void Main()
        {
            ChannelServices.RegisterChannel(new HttpChannel());
            DateTimeServer obj1 = (DateTimeServer)Activator.GetObject(
            typeof(ExampleRemoting.DateTimeServer),
            "http://127.0.0.1:9999/SayDateTime");
            if (obj1 == null)
            {
                System.Console.WriteLine("Could not locate server");
            }
            else
            {
                Console.WriteLine(obj1.MyMethod("Bozo the clown"));
                obj1.Dispose();
            }
        }
    }
}


Listing 23.10 shows an example of a client calling the single-call server in Listing 23.9. When the client starts up, it registers an HTTP channel and proceeds to activate the object by calling the GetObject method on the Activator class. The type of class we need to activate is ExampleRemoting.DateTimeServer. Next we specify the URI of the object we need to activate. For this client the URI is simply http://127.0.0.1:9999/SayDateTime. (Remember that 127.0.0.1 refers to the local host or loopback address of the local computer.) It is important to note that the URI includes the protocol, machine name, and port number as well as the endpoint. If the server is deployed on a host named "mindcracker," clients can connect to the server by specifying http://mindcracker:9999/SayDateTime.

The .NET Remoting framework provides developers with a modern distributed object model that allows remote method invocation between different common language runtimes across a network or between different application domains in the same common language runtime. Any interaction with a remote object occurs through a proxy mechanism; a client cannot access a remote object directly because the object is meaningful only inside its own application domain.

Once a message arrives at the server, the framework reassembles the original call, activates the target object if it is not already activated, and forwards the call to the object in question. Returning a result back to the client follows exactly the opposite path-the result is packaged in a message that is transported back to the client. If the server object type is SingleCall, the object is automatically recycled after the result returns to the client. When the client code is executed, the client locates and connects to the server, retrieves a proxy for the remote object, and calls MyMethod on the remote object, passing the string "Clown Bozo" as a parameter. The server returns "Bozo the clown. Here is the current DateTime: 2001-06-11T01:52:50."

It is worth noting that all TCP channels use binary serialization when transporting local objects to and from a remote object.

Conclusion

Hope this article would have helped you in understanding .NET Remoting and SOAP. See other articles on the website on .NET and C#.

visual C-sharp.jpg The Complete Visual C# Programmer's Guide covers most of the major components that make up C# and the .net environment. The book is geared toward the intermediate programmer, but contains enough material to satisfy the advanced developer.


Similar Articles