Wednesday, March 20, 2013

Remoting in C#.net


Application Architecture:

-Every application may contain 3 different parts in it like:
1. UI Part
2. Logic Part (BL + DL)
3. DataSource Part

-Organizations as per their requirement adopts diff architecture's for execution of their applications those are:

1. Single Tier Architecture: in this model all the 3 parts (UI + Logic + DB) will reside on the same machine to execute, so as the DB is also present on every machine changes made on 1 machine will not be reflected to the other.

2. 2-Tier  Architecture: in this model the (UI+Logic) sits on all the client machines, moving the DB to a centralized location, so all the clients connect with the same DB Server to store & access data. In this model changes made on 1 machine reflects to the other.

3. 3-Tier or N-Tier Architecture: in this model all the 3 parts will sit on 3 diff. machines to execute. On the client machine what we have is only light weight client (UI) which will connect with the logic part residing on server machine that will in turn connect with the DB Server. Maintainance of the software becomes easier in this model when there were more no. of client accessing the application.
-------------------------------------------------------------------------------------
-To develop a 3-Tier application in desktop model we have various distributed technologies like:

   -RPC (Remote Procedure Call)
   -CORBA (Common Object Request Broker Architecture)
   -RMI (Remote Method Invocation (Java))
   -DCom (Distributed Component Object Model)
   -Remoting (.Net Languages)
-------------------------------------------------------------------------------------
Remoting:
-It was a technology from Microsoft for developing distributed applications replacing traditional DCOM available under COM.

-All the distributed technologies speak about the same i.e. consuming of libraries present on remote machines.

-In .Net libraries were implemented as Assemblies, where we can consume an assembly residing on local machine by adding its reference. We can now consume Assemblies residing on remote machines also using Remoting.
-------------------------------------------------------------------------------------
Developing a Remoting Application:
-To develop a Remoting Application first we need to understand various things regarding the process of communication, those are:

1. How does both the parties (client and server) exchange information between each other ?

Ans: To exchange information between both the parties they make use of a process known as Serialization and Deserialization.

-As applications represent the data in High Level (Object Format) which are not free flowable, needs to be converted into Low Level (Binary or Text) and then transferred to the other system where on the target machine Low Level data has to be converted back into High Level.

-Serialization is a process of converting high level data to low level and De-Serialization is in opposite of serialization that converts low level data to high level.

-To perform serialization & deserialization remoting provides Formatter Classes, those are:
-Binary Formatters
  -TCPServerChannel
  -TCPClientChannel
-Soap Formatters
  -HttpServerChannel
  -HttpClientChannel
-Binary Formatters are used for binary serialization and deserialization & Soap Formatters are used for text serialization and deserialization.

Note: traditional DCOM supports only binary.
-------------------------------------------------------------------------------------
2. Marshalling and UnMarshalling:
-After serializing the data which has to be sent to the target machine it packages the data into packets this is what we call as marshalling, at this time it associates the IP Address of the target machine where the information has to be sent.

UnMarshalling is in opposite to Marshalling which opens the packets of data for de-serializing.
-------------------------------------------------------------------------------------
-Every system in a network is identified by using a unique id known as IPAddress.
-It is a 4 part numeric value where each part will be ranging between 0-255.
eg: 0-255.0-255.0-255.0-255
-We can mask IP Address of a system by specifying an alias name to it known as HostName. Systems under a network will be configured as following:
 IPAddress HostName
192.168.26.0      (nit0)
192.168.26.1      (nit1)
......
192.168.26.24   (nit24)
-------------------------------------------------------------------------------------
3. Activation Models:
-In execution of remoting application clients needs  object of remote class to invoke methods under it.

-Activation Models decide where does the remote class object resides in execution of the app.

-Remoting supports 2 different activation models:
-Server Activated Objects (SAO)
-Client Activated Objects (CAO)

-In SAO model object of remote class resides on server Machine and a reference of this object is maintained on the client machine using which clients can invoke the methods of remote class.

-In CAO model the object of remote class resides on client machine using which clients can invoke the methods of remote class.

Server Activated Objects:
-In SAO model we were again provided with 2 types like singleton and singlecall.

SingleTon:
-In this case when ever a first request comes from a client an object of remote class gets created and it's reference is given to the client, from then every new request comming from a new client, server provides the reference of same object which is already created, so changes made by 1 client gets reflected to the other.

-Used in the development of application like public chat, cricket scores, share prices etc.,

SingleCall:
-In this mode when ever a request comes from a client 1 object of remote class gets created and it's reference is given to client, once the request is served immediately object gets destroyed with out allowing him to make any other requests on that object, for a new request a new object gets created again and destroyed.

-Used in the development of single request app like "Railway PNR Status Enquiry", "ATM Machines", "Examination Results".

Note: this is very highly secured model used in app development.

Client Activated Objects:
-In this case when ever the first request from a client an object of remote class is created and provided using which the client can make any no. of requests. Here a seperate object will be given for each client so changes made by 1 client will never reflect to the other.

-Used in the development of applications that requires multiple requests for a single client.
eg: "Traditional ATM Machines", where we can perform multiple transactions once we insert the card.
-------------------------------------------------------------------------------------
4. Server:
-When we want to develop an application to be consumed from remote machines we require some one to take the request from clients. To take a request from client we use server softwares, which works on the principles request and response.

-We can install multiple server softwares on a machine, but each server should be running on a seperate logical address known as port.

-In process of developing a remoting application it is our responsibility to develop a server that takes requests of clients to the RemoteClass, because a class is not capable of taking the request.

-The server which we are going to develop has to be running on a unique port of the OS. By default every machine has port's ranging between 0-65535 in which 0-1023 were OS reserved ports, rest can be used by any app.

-After developing a Remote Server every Remote Class on the machine has to be registered under the Server with an alias name, so that clients can send their request to required class.
-------------------------------------------------------------------------------------
5. Remote Interface:

-In remoting the methods what we want to define under Remote Class, that are accessible to clients should be first declared under an interface & then implemented in remote class which was a rule.

-The same interface will also be provided to clients that acts as a Proxy to Remote Class on client machine, which will be used in 2 ways:
   1. Using it clients can recongnize methods of               remote class.
   2. Using it we can hold reference of remote class         on client machines.
-------------------------------------------------------------------------------------
Execution of a Remoting Application:

1. Client sends a request to server.
2. Server creates object of Remote Class.
3. Sends reference of that object to client which         has to be captured under interface variable.
4. After capturing, the variable gets converted into      reference pointing to the object on Server.
5. Now UI can invoke methods on the reference.
6. Methods gets executed on server machine as the     reference points to object on server.
-------------------------------------------------------------------------------------
-To develop a Remoting Application we require the following:
1. Interface (Class Library)
2. Remote Class (Class Library)
3. Remote Server (Windows Service)
4. Client (UI) (Windows or Console Application)
-------------------------------------------------------------------------------------
Developing an Interface:
-Open a new project of type class library & name it as InterfaceProject.

-Delete the Class1.cs file under project and add a Interface to the project naming it IRemoteApp.cs, and write the following code:

public interface IRemoteApp
{
   string Get_Sname(int sno);
   decimal Get_Bal(int cid);
   string SayHello();
}

-Now open solution explorer and build the project which generates an assembly.

   Project Name: InterfaceProject
   Interface Name: IRemoteApp.cs
   Assembly Name: InterfaceProject.dll
-------------------------------------------------------------------------------------
Developing a Remote Class:
-The RemoteClass needs to be inherited from the predefined class MarshalByRefObject & implement all the methods that were declared under interface.

-Open a new project of type class library and name it as ClassProject, rename the class Class1.cs as ClsRemoteApp.cs using Solution Explorer.

-Add reference of InterfaceProject.dll we have created previously & write the following code:

using InterfaceProject;
using System.Data.SqlClient;
public class ClsRemoteApp : MarshalByRefObject, IRemoteApp
{
 SqlConnection con;
 SqlCommand cmd;
 int x = 0;
 public ClsRemoteApp()
 {
  con = new SqlConnection(
    "User Id=Sa;Password=123;Database=CSharp7");
  cmd = new SqlCommand();
  cmd.Connection = con;
 }
 public string Get_Sname(int sno)
 {
  string name = "";
  try
  {
   cmd.CommandText = "Select Sname From Students Where Sno=" + sno;
   con.Open();
   name = cmd.ExecuteScalar().ToString();
  }
  catch (Exception ex)
  { ex = null; }
  finally
  { con.Close(); }
  return name;
 }
 public decimal Get_Bal(int cid)
 {
  decimal bal = 0;
  try
  {
   cmd.CommandText = "Select Balance From Customer Where Custid=" + cid;
   con.Open();
   bal = Convert.ToDecimal(cmd.ExecuteScalar());
  }
  catch (Exception ex)
  { ex = null; }
  finally
  { con.Close(); }
  return bal;
 }
 public string SayHello()
 {
  x += 1;
  return "Hello: " + x;
 }
 public string Demo()
 {
  return "Not accessible to remote clients";
 }
}

-Now open solution explorer and build the project to generate an assembly.

   Project Name: ClassProject
   Remote Class: ClsRemoteApp.cs
   Assembly Name: ClassProject.dll
-------------------------------------------------------------------------------------
Process to develop a RemoteServer:

-If you want to develop a remote server that should be started along with OS, develop it as an windows service.

-A Windows Service is an application which runs in the background process with out any knowledge to end users.

-Windows Services will be under control of OS and gets started when OS is started & stopped when we shutdown the system.

-DataBase's & Web Servers will be implemented as Windows Services only. Every system by default has no. of services installed on it.

-You can view the Services that are present on a machine making use of Service Control Manager window as following:
Start -> Settings -> Control Panel -> Administrative Tools -> Services

-Every service will have 4 attributes, those are:
1. Display Name: It is the name for identification.
2. Description: It is a brief information about the service (Optional).
3. StartupType: It decides how a service gets started on the machine, which can be set with 3 options:
   i) Automatic: Service gets started by OS.
  ii) Manual: Service needs to be started by users or some other applications.
 iii) Disabled: Service cannot be started by any one      from any where.

4. LogOnAs (Account): Indicates the account type under which the service runs, can be set with 3 options:
   i) User: runs under a particular user account.
  ii) Local System: runs under all users of the local system.
 iii) Network Service: runs under remote users   account also.

Note: While developing a windows service it is our responsibility to set all the 4 attributes we discussed above.
-------------------------------------------------------------------------------------
How to develop a Windows Service ?
-If we want to develop a windows service we can make use of "Windows Service" Project template under VS.

-If we want to choose Windows Service Project template, under New Project Window expand the Language node i.e Visual C# in the LHS panel and select the option Windows which displays Windows Service template on RHS panel.

-Every Windows Service Class is a sub class of pre-defined class ServiceBase present under System.ServiceProcess namespace.

-In a Windows Service code has to be written under few overridden methods like OnStart, OnStop, OnPause etc., which were declared as virtual under parent class ServiceBase.

-The code under OnStart executes when service is started & OnStop executes before the service is getting stopped.

-After defining code in the service class we need to set the 4 attributes discussed previously, for this, under the project we were given "Add Installer" option to set all the 4 attributes.

-Once we build the project it will generate an exe assembly that should be installed on a machine by using "installutil" tool. Once the service is installed we can view this under Services Windows of OS.
-------------------------------------------------------------------------------------
Developing Remote Server:
-Open a New Project of type Windows Service and name it as RemoteServer.

-Add reference of 3 assemblies to the project:
1. System.Runtime.Remoting.dll (.net)
2. ClassProject.dll (browse)
3. InterfaceProject.dll (browse)

-Write the following code in Code View:

using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;

Under OnStart Method:
TcpServerChannel chan = new         TcpServerChannel(5000);
ChannelServices.RegisterChannel(chan, true);
            RemotingConfiguration.RegisterWellKnownServiceType(typeof(ClassProject.ClsRemoteApp), "XXX", WellKnownObjectMode.Singleton);

-Now go to design view of the project, right click on it & select Add Installer which adds 2 components ServiceInstaller1 & ServiceProcessInstaller1 using which we need to set the 4 attributes of service.

-Under serviceInstaller1 Properties set following:
1. DisplayName: Remote Server
2. Description: Takes request from remote clients
3. StartupType: Automatic.

-Under serviceProcessInstaller1 Properties set the following:
1. Account: Local System

-Now open Solution Explorer and build the Project which creates an assembly RemoteServer.exe.

Installing the service on your machine:
-To Install the service on a machine we were given with a command line utility "installutil", which has to be used as following:
installutil <service exe name>
Note: To un-install a service which is installed use as following:
installutil -u <service exe name>

-Open VS Command Prompt and go into the location where RemoteServer.exe is present and write the following:

C:\CSharp6\RemoteServer\RemoteServer\bin\Debug>installutil RemoteServer.exe

-Now we can find our service under Service Window, right click on it & select start which will start the server.

-To check server running or not open VS Command Prompt and use the following statement: "netstat -a"
-------------------------------------------------------------------------------------
-Under Server App we have done the following:

Step 1: Create an object of TcpServerChannel or HttpServerChannel by passing port no as argument to the constructor.

System.Runtime.Remoting.Channels.Tcp
TcpServerChannel(int port)

System.Runtime.Remoting.Channels.Http
HttpServerChannel(int port)

Step 2: Register the Channel under OS using RegisterChannel static method of ChannelServices class.

System.Runtime.Remoting.Channels
   ChannelServices.RegisterChannel(Channel chan, bool security)
   true - secured;   false - unsecured

Step 3: Register the Remote Class under Remote Server with an alias name using the static method RegisterWellKnownServiceType of the class RemotingConfiguration.

System.Runtime.Remoting
RemotingConfiguration.RegisterWellKnownServiceType(Type type, string alias, Mode mode)

Note: Mode can be SingleTon or SingleCall
-------------------------------------------------------------------------------------
Developing the Client(UI): under client application we perform following activities:

Step 1: Create object of appropriate client channel class which doesn't require any port no.

Step 2: Register the channel under OS.

Step 3: Send request from Client to Remote Server requesting for reference of Remote Class using the static method GetObject of Activator class present under System.Runtime.Remoting namespace.

Activator.GetObject(Type type, string url) -> Object

URL: Uniform Resource Locator
<protocol>://<host name>:<port>/<request for>
eg: http://www.yahoo.com:80/index.htm
tcp://<server name>:5000/XXX

Step 4: Server takes request & provides reference of RemoteClass to client in object format as return type of GetObject method is object.
eg: Object obj = Activator.GetObject(<type>, <url>);

Step 5: Now client needs to convert reference of Remote Class present in object format to Interface format.
eg: IRemoteApp ira = (IRemoteApp)obj;

Step 6: Now using the reference we can invoke methods of Remote Class thats executes on server machine only.
-------------------------------------------------------------------------------------
Developing Client Application (UI):
-Open a new project of type windows & name it as RemoteClient.

-Add Reference of 3 assemblies to the project
1. System.Runtime.Remoting.dll (.net)
2. System.Configuration.dll (.net)
3. InterfaceProject.dll (Browse)

-Add an "Application Configuration File" under the project using "Add New Item" window and write the following in it:

<configuration>
 <appSettings>
  <add key ="URL" value ="tcp://server:5000/XXX"/>
 </appSettings>
</configuration>

-Write the following code under form:

using InterfaceProject;
using System.Configuration;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
-------------------------------------------------------------------------------------
Class Declarations:
   IRemoteApp ira;
-------------------------------------------------------------------------------------
Under Form Load:
string url =                                                                           ConfigurationManager.AppSettings.Get("URL");
TcpClientChannel chan = new TcpClientChannel();
ChannelServices.RegisterChannel(chan, true);
Object obj = Activator.GetObject(
typeof(IRemoteApp), url);
ira = (IRemoteApp) obj;
-------------------------------------------------------------------------------------
Under Call SayHello Button:
button1.Text = ira.SayHello();
-------------------------------------------------------------------------------------
Under Call Get_Sname Button:
button2.Text =                                                                       ira.Get_Sname(int.Parse(textBox1.Text));
-------------------------------------------------------------------------------------
Under Call Get_Bal Button:
button3.Text = ira.Get_Bal(int.Parse(textBox2.Text)).ToString();
-------------------------------------------------------------------------------------
Execution of the Application:
-As our Remote Server is a windows service it gets started automatically when ever OS is started.

-Now run the Remote Client application we have developed & test it. Once it was working perfectly prepare a set-up for the application which includes RemoteClient.exe, ConfigFile & InterfaceProject.dll which can be carried & installed on any systems in the network.

-To run the client application on a machine, first open the config file, edit the "URL" and then start the application.
-------------------------------------------------------------------------------------
Singleton Vs SingleCall:
-Right now Remote Class is registered under Remote Server in Singleton mode, in this mode when ever the first request comes from first client an object of RemoteClass is created and it's reference is provided to the client. From then for any new request comming from a new client server provides reference of same object that is already created, so all clients share same object because of this changes made by a client gets reflected to  other clients.

-To change the mode of our app from Singleton to SingleCall follow the below process:

  i) Open visual studio command prompt, go into the location where RemoteServer.exe was present &
uninstall it using installutil tool as following:
C:\CSharp6\RemoteServer\RemoteServer\bin\Debug > installutil -u RemoteServer.exe

 ii) Now open RemoteServer project in VS & under it change the mode from Singleton to SingleCall with in the 3rd statement of OnStart method and rebuild the project.

iii) Re-install RemoteServer from VS Command Prompt again.
C:\CSharp6\RemoteServer\RemoteServer\bin\Debug > installutil RemoteServer.exe

 iv) Open the service's window and start the server for first time.
-------------------------------------------------------------------------------------


No comments:

Post a Comment

amazon

Sukanya Samriddhi Account - SBI

SUKANYA SAMRIDDHI Account information by SBI SUKANYA SAMRIDDHI ACCOUNT : FACILITY AVAILABLE AT ALL BRANCHES OF SBI Sukanya Samriddhi ...