What is .NET Remoting ?
Introduction
Any Distributed Communications involves ultimately two things
- It marshals an instance of programmatic data types into messages that can be sent across network or different Application Domains. Any marshalling Engine or Marshaller can do this marshalling.
- Providing a description of what those messages look like. This is achieved through some metadata that describes the messages in data format
The Key difference between ASP.NET webservices and .NET Remoting is how they serialize data into messages and the format they choose for metadata.
ASP.NET uses XML serializer for serializing or Marshalling. And XSD is used for Metadata.
.NET Remoting relies on System.Runtime.Serialization.Formatter.Binary
and System.Runtime.Serialization.SOAPFormatter
and relies on .NET CLR Runtime assemblies for metadata. Which contain all the relevant information about the datatypes they implement via. Reflection and ILDASM.
Before going into the discussion of .NET Remoting lets talk about some important objects involved in .NET remoting.
- CLR Common Language Runtime is an Execution Environment in .NET.
- The process of Packaging and unpacking and sending the method calls across the different application domains via serialization and deserialization is called as Marshalling.
- Marshalling is done by the object called sink. Sink is an object that allow custom processing of messages during remote invocation.
- Channels are objects used to transport the messages through the network or across different application domains
- Application Domain is the Logical construct of the CLR that is the unit of Isolation for an application which guarantees, Each Application can be Independently stopped, An application can not directly access code or resource of the other application, a fault in one application will not effect the other application CLR allows multiple applications in a single Process by Implementing Application Domains.
.NET Remoting provides a Framework, which enables applications in different application domains to talk to each other.
The .NET Remoting Framework provides number of services like Activation Lifetime, Communication Channels for transporting messages to and from remote application, Formatters are used for encoding and decoding the messages before they are transmitted by the channel.
Applications can use binary Formatter where Performance is critical and XML where Interoperability is Critical.
There are really 7 steps that are mainly involved in understanding the .NET Remoting
- When a Client object wants to create an instance of the server object (to access the remote object) the remoting System Framework will create a proxy (Transparent Proxy) of the server object on the Client side, that contains list of all classes, as well as interface methods of the remote object. The TransparentProxy class gets registered with the CLR.
- The Proxy object behaves just like the remote object, this leaves the client with the impression that the server object is in the client's process
- When a Client object calls a method on the server object, the proxy passes the call information to the remoting Framework on the client. This remoting System (Remoting Framework) in turn sends the call over the channel to the remoting System on the server
- The Remoting system on the server receives the call information and on the basis of it, it invokes the method on the actual object on the server creating object if necessary
- Then the remoting system on the server collects all the results of the invocation and passes through the channel to the remoting System on the client.
- The remoting System on the client receives the response of the server and passes the results to the client object through the proxy
- The process of Packaging and unpacking and sending the method calls across the different application domains via serialization and deserialization is called as Marshalling.
Note: Remotable objects are the objects that can be marshaled across different platforms. All other are object are nonremotable.
They are basically two types of remotable objects
- Marshall-By-Value(MBV) This objects are copied and passed over the server application domain to the client application domain
MBV objects reside on the server. However when the client invokes a method of the MBV object, the MBV object is serialized, (by the Remoting Framework) and transferred over the network (using the channels & sinks) and restored on the client as an exact copy of the server-side object. The Method is then invoked directly on the Client. The Method is then invoked directly on the client (because it call by value client will have a copy of it on the client side). When this happens, the MBV object is no longer a remote object. Any method calls to the object do not require any proxy object or marshalling because the object is Locally available.
So the MBV objects provide faster Performance by reducing the number of network round trips, but in the case of large objects the time taken to transfer the serialized object from the server to the client can be very significant. Further, MBV objects don’t allow you the flexibility to run the remote object on the server environment (That is you have to bring it to the client side)
A MBV object can be created by declaring a class with serializable attribute
Ex:
Public class MyMBVObject
{
'Implementation details
}If a class needs to control its own serialization, it can do so by implementing the
ISerializable
interface
public class MyMBVObject : (Implements) ISerializable - Marshall-By-Reference (MBR) this objects are accessed on the client side by using a proxy. Client just holds the reference of this object which in on server-side.
MBR objects are remote objects they always reside on the server and all the methods invoked on these objects are executed at the server side. The Client Communicates with the MBR objects on the server using the Local proxy object that holds reference to the MBR object.
Although the use of MBR object Increase the network round trips, they are good choice when the objects are prohibitively very large or when the functionality of the object is only available on the sever environment on which it is created.
MBR object can be created by deriving from the Namespace System.MarshalByRefObject
class
Ex:
Define MBR remoting object
Public class MyMBRObject :MarshalByRefObject
'class details
End class
Channels
Channels are the objects that transport messages across remoting boundaries such as application domains, processes and computers.
When a client calls a method on a remote object, the details of the method are transported through Sinks via Channels to the remote object.
Any results returned from the remote object are Communicated back to the client again through the same Channel and the Sink.
The .NET remoting Framework ensures that before a remote object can be called, it has to register at least one channel with the remoting framework on which it will travel.
Similarly the client object should specify a channel before it can communicate with a remote object. If the remote object offers more than one channel, the client can connect using the channel that best suits its requirements.
A Channel
has two end points. The Channel
object at the receiving end of a channel (Server) listens to a particular protocol using the specified port number, where as the channel object at the sending end of the channel (the client) sends information to the receiving end using the protocol and port number specified channel object at the receiving end.
Port Numbers should be unique on a machine.
HTTP Channels
HTTP channels use HTTP for establishing Communication between the two ends.
These Channels are implemented through the classes of the System.Runtime.Remoting.Channels.Http namespace
- HttpServerChannel
, IChannelReceiver
HttpClientChannel
->IChannel
Sender : An implementation for a client that uses the HTTP protocol to send messages.
HttpChannel
->IChannelReceiver
and IChannelSendee
: An Implementation of combined and channel that provides the functionality of both ServerChannel
and HttpClientChannel
Code to Register a sender-receiver HTTP channel on port 1234
Using System;
Using System.Runtime.Remoting.Channels;
Using System.Runtime.Remoting.Channels.Http;
HttpChannel channel = new HttpChannel(1234);
ChannelServices.RegisterChannel(channel);
The Channel services class used in the code provides various remoting-related services. One of its static methods isRegisterChannel (),
which helps in registering a channel with the remoting framework.
Security: There is no built in Support for security in .NET Remoting. Instead it depends upon the remoting host to provide security. The only built in security in remoting host that provides security for remote object is IIS (per my knowledge) Therefore any secured objects must be hosted on IIS unless you write your own security system.
TCP Channels are created in the same way.
Formatters
Formatters are objects used to encode and serialize data into messages before they are transmitted over a channel.
To participate in .NET Remoting Framwork, a formatter class must implement IForammter Interface.
There are two types of Formatters, which dot Net supports
- Binary Formatter class
- Soap Formatter class
We can also define our own logic for a custom Formatter by implementing IFormatter Interface.
By default Http uses the SOAP formatter as its default formatter to transport the messages to and from the remote objects. The Http channel uses SoapClientFormatterSinkProvider
and SoapServerFormatterSinkProvider
classes to serialize and deserialize messages using soap formatter.
The TCP channel uses the binary format by default to transport messages to and from remote objects. The TCP channel uses BinaryClientFormatterSinkProvider
and BinayServerFormatterSinkProvider
classes to serialize and deserialize messages using BinayFormatter
However you can configure the channels. You can configure the HttpChannel to use the binary formatter or a custom formatter instead of the SOAP formatter. Similarly the TCP channel can be configured to use the SOAP formatter or a custom formatter instead of the binary formatter.
Remote Object Activation
We have two types of remote objects MBV and MBR among these two only MBR objects can be activated remotely. No remote activation is needed in the case of MBV because the object itself is transferred to the client as explained earlier.
Remotable Members
An MBR object can remote the following types of members
- Non-Static public methods
- Non-Static public properties
- Non-Static public fields.
There are two types of activation modes an MBR object is classified to
- Server Activated objects
- Client Activated objects
Server Activated Objects (SAO)
Server Activated objects SAO’s are those remote objects whose lifetime is directly controlled by the server. (I will discuss the Lifetime later, Sponsors etc later)
When a client requests an instance of a server-activated object, a proxy to the remote object is created in the clients. The remote application domain object is only instantiated (or activated) on the server side when the client calls a method in the proxy object.
Server activated object provide limited flexibility because they are only be instantiated using their default constructors (Parameter-less).
There are two possible activation modes for server activated objects
- Single-call activation mode
- Singleton activation mode
Single call activation Mode: (object per call)
In the single call activation mode an object is instantiated for the sole purpose of responding to just one client request. After the request is fulfilled the .NET remoting Framework deletes the object and reclaims the memory.
Objects activated in singlecall mode are also known as stateless because the objects are created and destroyed with each client request, therefore they do not maintain state across requests. The behavior of singlecall mode allows for greater scalability as an object consumes server resources only for small period, therefore allowing the server to allocate resources to other objects.
The single call activation mode is desired solution when
- The overhead of creating an object is not significant
- The object is not required to maintain the state
- The Server needs to support a large number of requests for the object( because created and deleted)
- The objects needs to be supported in a loadbalanced environment
What is Load balancing and Singlecall Activation?
Some times to improve the overall efficiency of an application it might be hosted on multiple servers that share the incoming request to the application. In this case a request can go to any of the available servers for processing. This scenario is called load-balancing environment.
Because the single call objects are state less it does not matter which server processes the request for such objects. For this reason Singlecall activation is ideally suited for load balanced environment. Common scenarios of the single call activation mode are those applications in which the object is required by the client to do small amount of work and then the object is no longer required.
Example: Retrieving an Item from an Inventory and displaying the tracking information and so on.
Singleton Activation Mode
In the Singleton activation mode at most (Minimum) there will be one instance of the remote object regardless of the no. Of clients accessing it.
A singleton mode object can maintain state information across method calls. For this reason such objects, are also sometimes known as stateful objects. The state maintained by the singleton-mode object is globally shared by all its clients.
A Singleton object is desired solution when
- The Overhead of creating objects is substantial
- The Object is required to maintain its state over a prolonged period
- Several clients need to work on the shared state.
Singleton activation mode is useful in scenarios such as in chat server where multiple clients talk to the same remote object and share the date between one another through this object.
Client Activate objects (CAO)
Client Activated objects are those remote objects whose Lifetime is directly Controlled by the client.
This is in direct contrast to SAO. Where the server, not the client has complete control over the lifetime of the objects.
Client activated objects are instantiated on the server as soon as the client request the object to be created. Unlike as SAO a CAO doesn’t delay the object creation until the first method is called on the object. (In SAO the object is instantiated when the client calls the method on the object)
A CAO can be created using any of the available constructors (unlike SAO’s where default constructors are used) for the class. A typical CAO activation involves the following steps.
- When the client attempts to create an instance of the server object, an activation request message is sent to the remote server
- The server then creates an instance of the requested class using the specified constructor and returns and ObjRef object to the client application that invoked it. The ObjRef object contains all the required information to generate a proxy object that is capable of communicating with a remote object at the client.
- The client uses the ObjRef object to create a proxy for the server object on the Client side.
An instance of CAO serves only the client responsible for its creation and the CAO doesn’t get discarded with each request, for this reason the CAO maintains the state with each client that it is serving, but (Like Singleton) unlike the Singleton SAO’s different CAO’s cannot share a Common state. The Lifetime if a CAO is determined using lifetime leases maintained by the File time manager. (This will be discussed later)
A CAO is desired solution when
- The Clients want to maintain Private Session with remote object.
- The Client wants to have more control over how the objects are created and how long they will leave.
A CAO is useful in scenarios such as entering a complex purchase order in which multiple round trips are involved and clients want to maintain their own private state with the remote object.
Comparing the Object Activations
The Single call server activation has maximum scalability because such objects occupy server resources for a minimum amount of time. This enables the server to allocate its resources between large number of clients.
On the other hand the client activated remote objects offers maximum flexibility because you have complete control over the construction and Lifetime of the remote object.
Lifetime Leases
A Lifetime lease is the period of time that a particular object can be active in memory before the .NET framework deletes it and reclaims the memory. Both Singleton SAO and CAO use lifetime leases to determine how they should continue to exist. In Single call activation mode objects are created and destroyed with each method call.
Object Lifetime with Leasing
SAO (Singleton) and Client Activated objects are under the Control of Leased based lifetime Managers that ensure the object is Garbage collected when its lease expires.
- Each application domain contains a lease Manager that is responsible for administering leases in the application domain
- There will be as many leases as the objects are or number of objects equal to number of lease’s but there will be only one Lease manager for one particular Domain.
- All Leases are examined periodically for the Expiry of the lease time
- If the lease expires one of the lease’s sponsors are invoked where they are given a chance to renew the lease
- If non-of the Sponsor’s is ready to renew the lease the lease manager removes the lease and the object is garbage collected.
- The Lease manager maintains a list of leases sorted by remaining lease time with the shortest remaining time on the top of the list
- Leases implement Ilease interface and store a collection of properties that determine which policies and methods to renew
- Leases can be renewed on call.
- Each time a method is called on the remote object the lease time is set to the maximum of the current Lease time plus
RenewOnCallTime
- When the lease time elapses, the sponsor of the lease is asked to renew the lease.
- There are situations where the Lease sponsor is not available we have a SponsorshipTimeout.
- If the Server cannot contact the sponsor or if the sponsor doesn’t renew the lease of the object the object is considered as Garbage Collected.
- The SponsorshipTimeout is the time to wait for sponsor to reply before the lease is terminated.
- If the Value of SponshipTimeOut is null then CurrentLeaseTime will be used to determine when the lease should expire
- If the CurrentLeaseTime is Zero then the Lease will not expire
Lease Times:
A remote object can choose to have a custom defined lifetime by overriding the InitalizeLifeTimeService ()
method of the base class MarshalByRefObject
.
When an object is created its lifetime lease (CurrentLeaseTime
) is set using the value of the IinitialLeaseTime property (Which is 5 minutes by default)
Whenever the object receives a call to its CurrentLeaseTime
is reset to the time specified by the value of the RenewOnCallTime
property (which is 2 minutes by default)
The Client can also renew a lease for a remote object by directly calling the Ilease.Renew()
method. When the value of the CurrentLeaseTime
reaches to 0, the .NET Framework contacts any sponsors registered with the lease to check if they are ready to sponsor renewing the object’s lease. If the sponsor does not renew the object or the server cannot contact the sponsor within the duration specified by the SponsorshipTimeout
property, the object is marked for garbage collection. Sponsors are the objects responsible for dynamically renewing the lease of an object in case of its lease expiry.