.NET Remoting: The Interface Approach

.NET Remoting provides a powerful and high-performance way of working with remote objects. Architecturally, .NET Remote objects are a perfect fit for accessing resources across the network without the overhead posed by SOAP-based Web services. .NET Remoting is easier to use than Java's RMI, but definitely more difficult than creating a WebService. In this article, we will create a remote object, and access this object using the Interface. The object returns rows from a database table. For the sake of simplicity, I have used the Northwind database that is packed with the installation of the Microsoft SQL Server.
 
Developed using the Release version of Microsoft .NET Visual Studio.
 
For my previous article in .NetRemoting Visit NetRemoting ( A Simple Approach ).
 
In this example, we will create a remote object and access it only by the interface.
 
Part I: Creating the Interface Library .. Interface_CustomerInfo
 
Click on File->New->Project. Choose to create a new "C# Library" and name it Interface_CustomerInfo then click on OK. This will create the "shared vocabulary" that both our .NET Remote client and Server will use to communicate. Any database activity happens on the server-side. The important thing to note here is that we define an object ICustomerInfo of the type Interface.
  1. public interface ICustomerInfo 
This interface exposes 3 methods. The actual work is done by the server, But this is transparent to the client. What the client looks at is, are the methods and the interface that exposes these methods. Here is the complete source listing.
  1. using System;  
  2. namespace Interface_CustomerInfo {  
  3.     ///  
  4.     /// Summary description for Class1.  
  5.     ///  
  6.     public interface ICustomerInfo {  
  7.         void Init(string username, string password);  
  8.         bool ExecuteSelectCommand(string selCommand);  
  9.         string GetRow();  
  10.     }  
Compile this project to generate the Interface_CustomerInfo.DLL.
 
Part II:  Creating the Server (CustomerServer)
 
In Visual Studio.NET, Click on File->New Project has created a simple Windows Application.
 
You can also play around by creating a simple console application.
 
We need to Add a Reference to the Interface_CustomerInfo.DLL that will make use of the Interface. Click on the Project->Add Reference, and add a reference to the DLL that we created in Part I by clicking the "Browse" button. In order to use the .NET remote functionality, you must add a reference to the System.Runtime.Remoting.DLL using Project->Add Reference under the .NET tab.
  1. hts = new HttpServerChannel(8228);  
  2. ChannelServices.RegisterChannel(hts); 
.Net Remoting supports 2 types of channels. For local applications or intranetwork applications, you can use the TcpChannel for better performance. The other type, the HttpChannel can be used for internet applications In this example I am using the TcpChannnel ( just for the heck of it !! ). The previous application I mentioned above uses an HttpChannel. If you're working over the internet HTTP can sometimes be the only choice depending on firewall configurations This will set up the port number we want our object to respond to requests on and the ChannelServices.RegisterChannel will bind that port number to the stack on the operating system.
  1. RemotingConfiguration.RegisterWellKnownServiceType(typeof(CUSTOMER_SERVER1) ,"CUSTOMER_SERVER1" , WellKnownObjectMode.Singleton); 
The first parameter is the object you're binding, typeof ( (CUSTOMER_SERVER1 ). The second parameter is the String that is the name for the object on the TCP or HTTP channel. For example, remote clients would refer to the above object as "http://localhost:8228/CUSTOMER_SERVER1". The third parameter tells the container what should be done with the object when a request for the object comes in.
 
WellKnownObjectMode.Single call makes a new instance of the object for each client WellKnownObjectMode.Singleton uses one instance of the object for all callers.
It makes sense to use the Singleton option here since we have to maintain a unique database connection that can be used across clients and SQL calls.
 
Important: The server class will actually implement the methods that are exposed to the interface.
 
Note the following declaration of the Customer_Server1 class
  1. public class CUSTOMER_SERVER1 : MarshalByRefObject , ICustomerInfo 
This class inherits from the MarshalByRefObject object and ICustomerInfo interface that we have created in the interface DLL in step 1.
 
The complete code for the Server object is below. 
  1. using System;  
  2. using System.Drawing;  
  3. using System.Collections;  
  4. using System.ComponentModel;  
  5. using System.Windows.Forms;  
  6. using System.Data;  
  7. using System.Text;  
  8. using System.IO;  
  9. using System.Data.SqlClient;  
  10. using Interface_CustomerInfo;  
  11. using System.Runtime.Remoting;  
  12. using System.Runtime.Remoting.Channels;  
  13. using System.Runtime.Remoting.Channels.Tcp;  
  14. namespace CustomerServer {  
  15.     public class CUSTOMER_SERVER1: MarshalByRefObject, ICustomerInfo {  
  16.         private SqlConnection myConnection = null;  
  17.         private SqlDataReader myReader;  
  18.         public CUSTOMER_SERVER1() {}  
  19.         public void Init(string userid, string password) {  
  20.             try {  
  21.                 MessageBox.Show("COMES HERE");  
  22.                 string myConnectString = "user id=" + userid + ";password=" + password + ";Database=Northwind;Server=SKYWALKER;Connect Timeout=30";  
  23.                 myConnection = new SqlConnection(myConnectString);  
  24.                 myConnection.Open();  
  25.                 if (myConnection == null) {  
  26.                     Console.WriteLine("OPEN NULL VALUE =====================");  
  27.                     return;  
  28.                 }  
  29.             } catch (Exception es) {  
  30.                 Console.WriteLine("[Error WITH DB CONNECT...] " + es.Message);  
  31.             }  
  32.         }  
  33.         public bool ExecuteSelectCommand(string selCommand) {  
  34.             try {  
  35.                 Console.WriteLine("EXECUTING .. " + selCommand);  
  36.                 SqlCommand myCommand = new SqlCommand(selCommand);  
  37.                 if (myConnection == null) {  
  38.                     Console.WriteLine("NULL VALUE =====================");  
  39.                     return false;  
  40.                 }  
  41.                 myCommand.Connection = myConnection;  
  42.                 myCommand.ExecuteNonQuery();  
  43.                 myReader = myCommand.ExecuteReader();  
  44.                 return true;  
  45.             } catch (Exception e) {  
  46.                 return false;  
  47.             }  
  48.         }  
  49.         public string GetRow() {  
  50.             if (!myReader.Read()) {  
  51.                 myReader.Close();  
  52.                 return "";  
  53.             }  
  54.             int nCol = myReader.FieldCount;  
  55.             string outstr = "";  
  56.             object[] values = new Object[nCol];  
  57.             myReader.GetValues(values);  
  58.             for (int i = 0; i < values.Length; i++) {  
  59.                 string coldata = values[i].ToString();  
  60.                 coldata = coldata.TrimEnd();  
  61.                 outstr += coldata + ",";  
  62.             }  
  63.             return outstr;  
  64.         }  
  65.     }  
  66.     ///  
  67.     /// Summary description for Form1.  
  68.     ///  
  69.     public class Form1: System.Windows.Forms.Form {  
  70.         public System.Windows.Forms.TextBox textBox1;  
  71.         ///  
  72.         /// Required designer variable.  
  73.         ///  
  74.         private System.ComponentModel.Container components = null;  
  75.         public Form1() {  
  76.             //  
  77.             // Required for Windows Form Designer support  
  78.             //  
  79.             InitializeComponent();  
  80.             //  
  81.             // TODO: Add any constructor code after InitializeComponent call  
  82.             //  
  83.         }  
  84.         ///  
  85.         /// Clean up any resources being used.  
  86.         ///  
  87.         protected override void Dispose(bool disposing) {  
  88.             if (disposing) {  
  89.                 if (components != null) {  
  90.                     components.Dispose();  
  91.                 }  
  92.             }  
  93.             base.Dispose(disposing);  
  94.         }  
  95.         #region Windows Form Designer generated code  
  96.         ///  
  97.         /// Required method for Designer support - do not modify  
  98.         /// the contents of this method with the code editor.  
  99.         ///  
  100.         private void InitializeComponent() {  
  101.             this.textBox1 = new System.Windows.Forms.TextBox();  
  102.             this.SuspendLayout();  
  103.             //  
  104.             // textBox1  
  105.             //  
  106.             this.textBox1.Dock = System.Windows.Forms.DockStyle.Fill;  
  107.             this.textBox1.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25 F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));  
  108.             this.textBox1.Multiline = true;  
  109.             this.textBox1.Name = "textBox1";  
  110.             this.textBox1.Size = new System.Drawing.Size(288, 85);  
  111.             this.textBox1.TabIndex = 0;  
  112.             this.textBox1.Text = "textBox1";  
  113.             //  
  114.             // Form1  
  115.             //  
  116.             this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);  
  117.             this.ClientSize = new System.Drawing.Size(288, 85);  
  118.             this.Controls.AddRange(new System.Windows.Forms.Control[] { this.textBox1 });  
  119.             this.Name = "Form1";  
  120.             this.Text = "Interface_Server";  
  121.             this.Load += new System.EventHandler(this.Form1_Load);  
  122.             this.ResumeLayout(false);  
  123.         }  
  124.         #endregion  
  125.             ///  
  126.             /// The main entry point for the application.  
  127.             ///  
  128.             [STAThread]  
  129.         static void Main() {  
  130.             Application.Run(new Form1());  
  131.         }  
  132.         private void Form1_Load(object sender, System.EventArgs e) {  
  133.             TcpServerChannel tsc = new TcpServerChannel(8228);  
  134.             ChannelServices.RegisterChannel(tsc);  
  135.             RemotingConfiguration.RegisterWellKnownServiceType(typeof(CUSTOMER_SERVER1), "CUSTOMER_SERVER2", WellKnownObjectMode.Singleton);  
  136.             textBox1.Text = "SERVER RUNNING ..";  
  137.         }  
  138.     }  
Compile the Server Object.
 
Part III:  Creating the Client ( CustomerClient )
 
The CustomerClient object is the test object of our newly created CustomerServer remote object. Create a new project by clicking File->New->Project. I have created a simple windows client that connects to the remote object, executes an SQL command, and returns rows from the database as a single string separated by a comma.
 
Note that we need to add a reference to our shared Interface_CustomerInfo.DLL created in Part I. Also, add a reference to the System.Runtime.Remoting DLL using the References->AddRefrences option in Solution Explorer.
 
Now Notice the 2 important lines in the program. The first line creates a TcpClientChannel. This channel is not bound to a port. The second line actually gets a reference to our server CUSTOMER_SERVER1 object. The Activator.GetObject method returns a type of Object that we can then cast into our CUSTOMER_SERVER1. The parameters we pass in are extremely similar to what we passed to the RemotingConfiguration object on the server project. The first parameter is the Type of the object, the second is the URI of our remote object. Notice that we are using an ICustomerInfo object. The server is serving the CUSTOMER_SERVICE1 object but we are using the ICustomerInfo object. When you are calling the Init method of the interface, the implemented version of the method, handled by the server is activated. This process is completely transparent to the client when using the ICustomerInfo interface.
  1. ChannelServices.RegisterChannel(new TcpClientChannel());  
  2. custl = (ICustomerInfo) Activator.GetObject(typeof(ICustomerInfo), "tcp://localhost:8228/CUSTOMER_SERVER1");  
  3. if (custl == null) {  
  4.     Console.WriteLine("TCP SERVER OFFLINE ...PLEASE TRY LATER");  
  5.     return;  
  6. }  
  7. custl.Init("skulkarni"""); 
Here is the complete listing.
  1. using System;  
  2. using System.Drawing;  
  3. using System.Collections;  
  4. using System.ComponentModel;  
  5. using System.Windows.Forms;  
  6. using System.Data;  
  7. using System.Runtime;  
  8. using System.Runtime.Remoting;  
  9. using System.Runtime.Remoting.Channels;  
  10. using System.Runtime.Remoting.Channels.Tcp;  
  11. using Interface_CustomerInfo;  
  12. namespace CustomerClient {  
  13.     ///  
  14.     /// Summary description for Form1.  
  15.     ///  
  16.     public class Form1: System.Windows.Forms.Form {  
  17.         ICustomerInfo custl;  
  18.         private System.Windows.Forms.TextBox textBox1;  
  19.         private System.Windows.Forms.Button button1;  
  20.         private System.Windows.Forms.TextBox textBox2;  
  21.         private System.Windows.Forms.Button button2;  
  22.         private System.Windows.Forms.Label label1;  
  23.         private System.Windows.Forms.Label label2;  
  24.         ///  
  25.         /// Required designer variable.  
  26.         ///  
  27.         private System.ComponentModel.Container components = null;  
  28.         public Form1() {  
  29.             //  
  30.             // Required for Windows Form Designer support  
  31.             //  
  32.             InitializeComponent();  
  33.             //  
  34.             // TODO: Add any constructor code after InitializeComponent call  
  35.             //  
  36.         }  
  37.         ///  
  38.         /// Clean up any resources being used.  
  39.         ///  
  40.         protected override void Dispose(bool disposing) {  
  41.             if (disposing) {  
  42.                 if (components != null) {  
  43.                     components.Dispose();  
  44.                 }  
  45.             }  
  46.             base.Dispose(disposing);  
  47.         }  
  48.         #region Windows Form Designer generated code  
  49.         ///  
  50.         /// Required method for Designer support - do not modify  
  51.         /// the contents of this method with the code editor.  
  52.         ///  
  53.         private void InitializeComponent() {  
  54.             this.textBox1 = new System.Windows.Forms.TextBox();  
  55.             this.button1 = new System.Windows.Forms.Button();  
  56.             this.textBox2 = new System.Windows.Forms.TextBox();  
  57.             this.button2 = new System.Windows.Forms.Button();  
  58.             this.label1 = new System.Windows.Forms.Label();  
  59.             this.label2 = new System.Windows.Forms.Label();  
  60.             this.SuspendLayout();  
  61.             //  
  62.             // textBox1  
  63.             //  
  64.             this.textBox1.Font = new System.Drawing.Font("Verdana", 8.25 F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));  
  65.             this.textBox1.Location = new System.Drawing.Point(0, 32);  
  66.             this.textBox1.Multiline = true;  
  67.             this.textBox1.Name = "textBox1";  
  68.             this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Both;  
  69.             this.textBox1.Size = new System.Drawing.Size(736, 176);  
  70.             this.textBox1.TabIndex = 0;  
  71.             this.textBox1.Text = "";  
  72.             //  
  73.             // button1  
  74.             //  
  75.             this.button1.Location = new System.Drawing.Point(544, 216);  
  76.             this.button1.Name = "button1";  
  77.             this.button1.Size = new System.Drawing.Size(80, 24);  
  78.             this.button1.TabIndex = 1;  
  79.             this.button1.Text = "Run SQL";  
  80.             this.button1.Click += new System.EventHandler(this.button1_Click);  
  81.             //  
  82.             // textBox2  
  83.             //  
  84.             this.textBox2.Location = new System.Drawing.Point(0, 248);  
  85.             this.textBox2.Name = "textBox2";  
  86.             this.textBox2.Size = new System.Drawing.Size(736, 20);  
  87.             this.textBox2.TabIndex = 2;  
  88.             this.textBox2.Text = "";  
  89.             //  
  90.             // button2  
  91.             //  
  92.             this.button2.Enabled = false;  
  93.             this.button2.Location = new System.Drawing.Point(632, 216);  
  94.             this.button2.Name = "button2";  
  95.             this.button2.Size = new System.Drawing.Size(104, 24);  
  96.             this.button2.TabIndex = 1;  
  97.             this.button2.Text = "Get Next Row";  
  98.             this.button2.Click += new System.EventHandler(this.button2_Click);  
  99.             //  
  100.             // label1  
  101.             //  
  102.             this.label1.Location = new System.Drawing.Point(0, 232);  
  103.             this.label1.Name = "label1";  
  104.             this.label1.Size = new System.Drawing.Size(192, 16);  
  105.             this.label1.TabIndex = 3;  
  106.             this.label1.Text = "Type Your SQL Command Here";  
  107.             //  
  108.             // label2  
  109.             //  
  110.             this.label2.Location = new System.Drawing.Point(0, 8);  
  111.             this.label2.Name = "label2";  
  112.             this.label2.Size = new System.Drawing.Size(480, 16);  
  113.             this.label2.TabIndex = 4;  
  114.             this.label2.Text = "Data Returned From Remote Object ( Field Values are separated by commas ) ";  
  115.             //  
  116.             // Form1  
  117.             //  
  118.             this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);  
  119.             this.ClientSize = new System.Drawing.Size(736, 269);  
  120.             this.Controls.AddRange(new System.Windows.Forms.Control[] { this.label2, this.label1, this.textBox2, this.button1, this.textBox1, this.button2 });  
  121.             this.Name = "Form1";  
  122.             this.Text = "CustClient";  
  123.             this.Load += new System.EventHandler(this.Form1_Load);  
  124.             this.ResumeLayout(false);  
  125.         }  
  126.         #endregion  
  127.             ///  
  128.             /// The main entry point for the application.  
  129.             ///  
  130.             [STAThread]  
  131.         static void Main() {  
  132.             Application.Run(new Form1());  
  133.         }  
  134.         private void Form1_Load(object sender, System.EventArgs e) {  
  135.             ChannelServices.RegisterChannel(new TcpClientChannel());  
  136.             custl = (ICustomerInfo) Activator.GetObject(typeof(ICustomerInfo), "tcp://localhost:8228/CUSTOMER_SERVER1");  
  137.             if (custl == null) {  
  138.                 Console.WriteLine("TCP SERVER OFFLINE ...PLEASE TRY LATER");  
  139.                 return;  
  140.             }  
  141.             custl.Init("skulkarni""");  
  142.         }  
  143.         private void button2_Click(object sender, System.EventArgs e) {  
  144.             textBox1.Text = custl.GetRow();  
  145.             if (textBox1.Text == "")  
  146.                 button2.Enabled = false;  
  147.         }  
  148.         private void button1_Click(object sender, System.EventArgs e) {  
  149.             button2.Enabled = false;  
  150.             textBox1.Text = "";  
  151.             if (textBox2.Text == "") {  
  152.                 MessageBox.Show("Enter a SQL Command""Error");  
  153.                 return;  
  154.             }  
  155.             bool ret = custl.ExecuteSelectCommand(textBox2.Text);  
  156.             if (!ret) {  
  157.                 textBox1.Text = "Error Executing SQL command or 0 rows returned";  
  158.                 return;  
  159.             }  
  160.             button2.Enabled = true;  
  161.             textBox1.Text = custl.GetRow();  
  162.         }  
  163.     }  
Run the Server, then Run the client. Type in a SQL statement ( against the NorthWind ) database.
 
NET remoting makes life very easy for us.
 
It's very simple to use and can provide an excellent way to work with resources across your network or the internet.


Similar Articles