Search Forum
(53671 Postings)
Search Site/Articles

Archived Articles
712 Articles

C# Books
C# Consultants
What Is C#?
Download Compiler
Code Archive
Archived Articles
Advertise
Contribute
C# Jobs
Beginners Tutorial
C# Contractors
C# Consulting
Links
C# Manual
Contact Us
Legal

GoDiagram for .NET from Northwoods Software www.nwoods.com


 
Printable Version

How to Use .Net Remoting Using C#?
By Mohamed Ashraf

 The information in this article help to:
  • What is .NET Remoting?
  • .NET Remoting Architecture?
  • Howdoes .NET Remoting work?
  • Why .NET Remoting?
  • Advantages over WebServies
  • Advantages over COM/DCOM
  • How to Create and use .NET Remoting object
  • How to Create and use .NET Remoting Server (Console and windows service application)
  • How to Create and use .NET Remotig Client (Console and Web application)

What is .NET Remoting?

Net remoting replaces DCOM. Web Services that uses remoting can run in any Application type i.e. Console Application, Windows Form Applications, Window Services etc. In CLR Object Remoting we can call objects across network.


.NET Remoting  Architecture?
  • Methods that will be called from the client are implemented in a remote object class. 
  • Client uses a proxy to call a remote object. 
  • Remote objects runs inside a process that is different from the client process
  • For the client, the proxy looks like the real object with the same public methods. 
  • When the methods of the proxy are called, messages are created. 
  • Messages are serialized using a binary formatter class, and are sent into a client channel. 
  • The client channel communicates with the server part of the channel to transfer the message across the network. 
  • The server channel uses a formatter to deserialize the message, so that the methods can be dispatched to the  remote object.
  • The formatter and the proxy is supplied automatically. 

 How does .NET Remoting work?
.NET remoting involves sending messages along channels. Two of the standard channels are HTTP and TCP. TCP is intended for LANs only - HTTP can be used for LANs or WANs (internet).

Support is provided for multiple message serializarion formats. Examples are SOAP (XML-based) and binary. By default, the HTTP channel uses SOAP (via the .NET runtime Serialization SOAP Formatter), and the TCP channel uses binary (via the .NET runtime Serialization Binary Formatter). But either channel can use either serialization format. 

There are a number of styles of remote access: 

SingleCall:

Each incoming request from a client is serviced by a new object. The object is thrown away when the request has finished. This (essentially stateless) model can be made stateful in the ASP.NET environment by using the ASP.NET state service to store application or session state.

Singleton:

All incoming requests from clients are processed by a single server object. 

Client-activated object:

This is the old stateful (D)COM model whereby the client receives a reference to the remote object and holds that reference (thus keeping the remote object alive) until it is finished with it. 


.NET Remoting Specific Advantage?
Lease-Based Lifetime :
Distributed garbage collection of objects is managed by a system called 'leased based lifetime'. Each object has a 
lease time, and when that time expires the object is disconnected from the .NET runtime remoting infrastructure.

Net Remoting takes a Lease-base Lifetime of the object that is scaleable

Call Context :
Additional information can be passed with every method call that is not part of the argument with the help of SOAP 
Header

Distributed Identities :
If we pass a reference to a remote object, we will access the same object using this reference. 

Advantage over Web Services?
1.
It works using purely Commmon Type System.
2.It supports high speed binary over tcp/ip communication.


Advantage over COM/DCOM?
1.It does not have extra interface language (IDL)
2.It Works using purely managed code
3.It's using Common Type System.. No Safearrays etc

Disadvantages
1.It is not an open standard like web services.
2.It is not as widespread and established ad DCOM.
3.Less support for  transactions,load balancing compared with DCOM
.
Now, Let's have look at remote object, client and server interactions.
Remote Objects 
A remote object is implemented in a class that derives from System.MarshalByRefObject. A client doesn't call the methods directly;  instead a proxy object is used to invoke methods on the remote object. Every public method that we define in the remote object class is available to be called from clients. 
To create MyRemoteObject.dll Take .NET IDE New Project->YourName.Samples(for example, MohamedAshraf.Samples(Type Class Library). 

By Default.,Class1.cs will come. Change that file name MyRemoteObject.cs. Copy and paste this file there.

MyRemoteObject.cs
using System;
using System.Runtime.Remoting.Lifetime;
namespace MohamedAshraf.Samples
{
public class MyRemoteObject:System.MarshalByRefObject 

public MyRemoteObject() 

Console.WriteLine("MyRemoteObject Constructor Called"); 

public override object InitializeLifetimeService()
{
return null;
}
public string Hello() 

return "Hello, Welcome to .Net Remoting !"; 


}
Build the assembly MyRemoteObject from the class MyRemoteObject 
Server 
The remote object needs a server process where it will be instantiated. This server has to create a channel and put 
it into listening mode so that clients can connect to this channel. For creating server, Take .NET IDE-> New Project  named "Simple Server".This is console application.
Server Configuration File 
In Configuration file channel, endpoint, name etc. can be changed without a recompile. When the client connects to the remote object it needs to know the URI of the object, i.e. the name of the host where the remote object is running, the protocol and port number to connect to, the name of the server, and the name of the remote object. With the exception of the host name we have to specify all these items in the configuration file. tcp://localhost:9000/SimpleServer/MyRemoteObject 

In SimpleServer.exe.config 
All of the remoting configurations must be added as child elements to <system.runtime.remoting>. 
The <application> element specifies the name of the server with the name attribute. The application offers a service and requires the configuration of channels for the service. 

We have the <service> and <channel>elements. The service that is offered from the application must be listed as a child of <service>. This is the remote object itself. 

The remote object is specified with the <wellknown> element. For instantiating the object the framework requires the name of the assembly to know where the type of this object can be loaded from. We can set this information with the XML attribute type.type="MohamedAshraf.Samples. MyRemoteObject, MohamedAshraf.Samples" defines that the type of the remote object is MyRemoteObject in the namespace SimpleServer, and it can be found in the assembly MyRemoteObject. The mode attribute is set to SingleCall. 


We reference the predefined server channel using the TCP protocol: tcp server. We assign the port of this channel 
with the port attribute, as the server must have a well-known port number that the client must be aware of. 

How to create app.config
  • Take Project -> Add New Item -> Xml File -> Enter  file name "app.config" and paster following codes. It will create "ExeName.exe.config" file in debug folder.
app.config file
<?xml version="1.0" encoding="utf-8" ?> 
<configuration>
<system.runtime.remoting>
<application>
<channels>
<channel ref="tcp" port="8000" />
</channels>
<service>
<wellknown mode="Singleton" type="MohamedAshraf.Samples.MyRemoteObject,MohamedAshraf.Samples" 
objectUri="MyRemoteObject" />
</service>
</application>
</system.runtime.remoting>
</configuration>
The Server is implemented in the console application. RemotingConfiguration.Configure() reads the configuration file 
to configure SimpleServer.exe.config to configure and activate the channels. We have to keep the process alive. 
Using Console Application as Server
SimpleServer.cs

using System; 
using System.Runtime.Remoting; 
using MohamedAshraf.Samples; 
namespace SimpleServer
{
class SimpleServer 

public static MyRemoteObject MRB=null;
static void Main(string [] args) 

RemotingConfiguration.Configure("SimpleServer.exe.config"); 
MRB=new MyRemoteObject(); 
RemotingServices.Marshal((MRB),"MyRemoteObject");
Console.WriteLine("Press return to exit"); 
Console.ReadLine(); 



}
Build it.It will create SimpleServer.exe


Using Window Services as Server

For creating server, Take .NET IDE-> New Project  named "RemotingServerWebService". Type windows Service.

SimpleServer.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Runtime.Remoting;
using MohamedAshraf.Samples; 
namespace RemotingServerWebService
{
public class Service1 : System.ServiceProcess.ServiceBase
{
private System.ComponentModel.Container components = null;
public Service1()
{
InitializeComponent();
}

// The main entry point for the process
static void Main()
{
System.ServiceProcess.ServiceBase[] ServicesToRun;
ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Service1() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}

/// <summary> 
/// Required method for Designer support - do not modify 
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
this.ServiceName = "MohamedAshrafRemotingService";
}

/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null) 
{
components.Dispose();
}
}
base.Dispose( disposing );
}

/// <summary>
/// Set things in motion so your service can do its work.
/// </summary>
protected override void OnStart(string[] args)
{
try
{
string fileName = AppDomain.CurrentDomain.BaseDirectory+"RemotingServerWebService.exe.config"; 
//configure remoting
RemotingConfiguration.Configure(fileName);
MyRemoteObject m=new MyRemoteObject(); 
RemotingServices.Marshal((m),"MyRemoteObject");
}
catch(Exception error)
{
}
}

/// <summary>
/// Stop this service.
/// </summary>
protected override void OnStop()
{
}
}
}

Project Installer
With the installer class, it's possible to build transaction based installations.  With a transaction based installation it's possible to go back to the previous state if the installation fails. It has Install(), Commit(), Rollback() and Uninstall() methods. 
How to create installer class. Right click " RemotingServerWebService" project add new item->Installer Class and copy the following lines.
ProjectInstaller.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;
namespace RemotingServerWebService
{
[RunInstaller(true)]
public class ProjectInstaller : System.Configuration.Install.Installer
{
private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1;
private System.ServiceProcess.ServiceInstaller serviceInstaller1;
private System.ComponentModel.Container components = null;
public ProjectInstaller()
{
InitializeComponent();
}

#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
// 
// serviceProcessInstaller1
// 
this.serviceProcessInstaller1.Account = 
System.ServiceProcess.ServiceAccount.LocalSystem;
this.serviceProcessInstaller1.Password = null;
this.serviceProcessInstaller1.Username = null;
// 
// serviceInstaller1
// 
this.serviceInstaller1.DisplayName = "MohamedAshrafRemotingService";
this.serviceInstaller1.ServiceName = "MohamedAshrafRemotingService";
this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
// 
// ProjectInstaller
// 
this.Installers.AddRange(new System.Configuration.Install.Installer[] {

this.serviceProcessInstaller1,

this.serviceInstaller1});
}
#endregion
}
}

Build it.It will create RemotingServerWebService.exe


How to run window Service?

I. Build it. It will create RemotingServerWebService.exe

II. Install the Window Service using InstallUtil.exe

     installutil RemotingServerWebService.exe

Installutil.exe Allows you to install and uninstall server resources by executing the installer components of a specified assembly. 
Note:Installutil.exe can be found in "%windir%\Microsoft.NET\Framework\v1.0.xxxx" where xxxx is the build number of the  .NET     Framework you installed.

II.Check Our Window services in stalled properly. 

    Take MyComputer -> Manage -> Services and Applications -> Services .

    Here you can see the service name "MohamedAshrafRemotingService". Now the window service is running correctly.. 

II. Uninstall the window service

   installutill /u RemotingServerWebService.exe. Now, Let's have a look at how to to create a client


Client 

For creating client, Take .NET IDE-> New Project  named "SimpleClient".This is console application.

Client Configuration File 
The client configuration file SimpleClient.exe.config uses the XML <client> element to specify the URL of the server using protocol://hostname:port/application. We use tcp as the protocol, and the server runs on localhost with the port number 9000. The application name of the server is defined with the name attribute of the <application> element in the server configuration file. The <wellknown> element specifies the remote object we want to access. 


The type attribute defines the type of the remote object and the assembly. The url attribute defines the path to the remote object. Appended to the URL of the application is the endpoint name MyRemoteObject. The channel that is configured with the client can again be found in the configuration file machine.config

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
<system.runtime.remoting> 
<application name = "SimpleClient"> 
<client> 
<wellknown 
type="MohamedAshraf.Samples.MyRemoteObject,MohamedAshraf.Samples" 
url="tcp://localhost:8000/MyRemoteObject"/> 
</client> 
<channels> 
<channel ref="tcp" port="0"/> 
</channels> 
</application> 
</system.runtime.remoting> 
</configuration> 
Client Application Activate the client channel by calling RemotingConfiguration.Configure(). Using configuration files 
we can simply use new to create the remote object. Next we call the method Hello() of this object. 
Using Console Application as Client
SimpleClient.cs

using System;
using System.Runtime.Remoting; 
using MohamedAshraf.Samples; 
namespace SimpleClient
{
class SimpleClient 

static void Main(string[] args) 

RemotingConfiguration.Configure("SimpleClient.exe.config"); 
MyRemoteObject robj = new MyRemoteObject(); 
Console.WriteLine(robj.Hello()); 
Console.ReadLine(); 


}

Build it you will get SimpleClient.exe


Using Web Application as Client we can embed config file with webconfig file
Using Web Application as Client

For creating web application as client, Take .NET IDE-> New Project  named "RemotingWebClient" Type ASP.NET Web application. Take web.config and replace this file.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

<system.web>

<compilation 
defaultLanguage="c#"
debug="true"
/>

<customErrors 
mode="RemoteOnly" 
/> 

<trace
enabled="false"
requestLimit="10"
pageOutput="false"
traceMode="SortByTime"
localOnly="true"
/>

<sessionState 
mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;user id=sa;password="
cookieless="false" 
timeout="20" 
/>

<globalization 
requestEncoding="utf-8" 
responseEncoding="utf-8" 
/>

</system.web>
<system.runtime.remoting>
<application>
<client>
<wellknown 
type="MohamedAshraf.Samples.MyRemoteObject,MohamedAshraf.Samples" 
url="tcp://localhost:8000/MyRemoteObject"/>
</client>
<channels>
<channel ref="tcp" port="0">
<clientProviders>
<formatter ref="binary"/>
</clientProviders>
</channel>
</channels>
</application>
</system.runtime.remoting>
</configuration>
RemotingWebClient.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Runtime.Remoting; 
using MohamedAshraf.Samples; 

namespace RemotingWebClient
{
/// <summary>
/// Summary description for WebForm1.
/// </summary>
public class RemotingWebClient : System.Web.UI.Page
{
private void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
RemotingConfiguration.Configure(Server.MapPath(".") + "\Web.config"); 
MyRemoteObject robj =new MyRemoteObject(); 
Response.Write(robj.Hello()); 
}

}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()

this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
}
}

How to run it?
Console application as server and client: Run the SimpleServer.exe then run SimpleClient.exe. 
Console application as server and web as client : Run the SimpleServer.exe the run RemotingWebClient.aspx.
Window service as web service and web as client :Start window service thenrun SimpleClient.exe or RemotingWebClient.aspx