Ado.Net
Ado.Net
Ado.Net
Net Programs
Program for inserting, deleting, updating, displaying data in textboxes (single & all records).
Adding data in combobox, tree view, selecting from combobox, treeview and showing in
textboxes.
SqlDataReader dr;
SqlCommand cmd = new SqlCommand();
int r,r1;
string qry,fname;
if (! Page.IsPostBack)
{
con.Open();
cmd.Connection = con;
cmd.CommandText = "select * from student";
dr = cmd.ExecuteReader();
TreeNode t1;
TreeNode t2=new TreeNode(Roll No);
TreeView1.Nodes.Add(t2);
DropDownList1.Items.Add(Select any Roll No);
ListBox1.Items.Add(Select any Roll No);
string rno;
while (dr.Read())
{
rno= dr.GetValue(0).ToString();
DropDownList1.Items.Add(rno);
ListBox1.Items.Add(rno);
t1=new TreeNode();
t1.Text =rno;
TreeView1.Nodes.Add(t1);
TreeView1.Nodes[0].ChildNodes.Add(t1);
}
2 | Page
con.Close();
}
try
{
r = int.Parse(DropDownList1.SelectedItem.Text);
r1 = r;
qry = "select * from student where rno=" + r;
//MessageBox.Show(qry);
con.Open();
cmd.Connection = con;
cmd.CommandText = qry;
dr = cmd.ExecuteReader();
if (dr.Read())
{
textBox1.Text = dr.GetValue(0).ToString();
textBox2.Text = dr.GetValue(1).ToString();
textBox3.Text = dr.GetValue(2).ToString();
textBox4.Text = dr.GetValue(3).ToString();
textBox5.Text = dr.GetValue(4).ToString();
fname = dr.GetValue(5).ToString();
if (File.Exists(fname))
pictureBox1.Image = Image.FromFile(fname);
}
}
con.Close();
1)
2)
3)
4)
5)
6)
7)
8)
sp6.Value = (textBox6.Text);
com.Parameters.Clear();
com.Parameters.Add(sp1);
com.Parameters.Add(sp2);
com.Parameters.Add(sp3);
com.Parameters.Add(sp4);
com.Parameters.Add(sp5);
com.Parameters.Add(sp6);
5 | Page
sda.Fill(ds, "student1");
GridView1.DataSource = ds;
GridView1.DataMember = "student1";
GridView1.DataBind();
//sda.Fill(ds, "student");
//GridView1.DataSource = ds.Tables["student"];
6 | Page
GridView1.DataBind();
//sda.Fill(ds);
//GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
GridView1.DataSource = ds.Tables["emp"];
GridView1.DataBind();
GridView1.DataSource = ds.Tables["student"];
GridView1.DataBind();
if (! Page.IsPostBack)
{
sda = new SqlDataAdapter("select * from student", con);
sda.Fill(ds, "student");
DropDownList1.DataSource=ds.Tables[student];
DropDownList1.DataTextField=rno;
DropDownList1.DataValueField=rno;
DropDownList1.DataBind();
ListBox1.DataSource=ds.Tables[student];
ListBox1.DataTextField=rno;
ListBox1.DataValueField=rno;
ListBox1.DataBind();
RadioButtonList1.DataSource=ds.Tables[student];
RadioButtonList1.DataTextField=rno;
RadioButtonList1.DataValueField=rno;
RadioButtonList1.DataBind();
}
try
{
int r = int.Parse(DropDownList1.SelectedItem.ToString());
string qry = "select * from student where rno=" + r;
ds1.Clear();
sda = new SqlDataAdapter(qry, con);
sda.Fill(ds1);
9 | Page
Label1.Text = ds1.Tables[0].Rows[0].ItemArray[1].ToString();
Image1.ImageUrl= ds1.Tables[0].Rows[0].ItemArray[5].ToString();
}
catch (Exception e1)
{
}
try
{
int r = int.Parse(ListBox1.SelectedItem.ToString());
string qry = "select * from student where rno=" + r;
ds1.Clear();
sda = new SqlDataAdapter(qry, con);
sda.Fill(ds1);
Label1.Text = ds1.Tables[0].Rows[0].ItemArray[1].ToString();
Image1.ImageUrl= ds1.Tables[0].Rows[0].ItemArray[5].ToString();
}
catch (Exception e1)
{
}
try
{
int r = int.Parse(RadioButtonList1.Text);
qry = "select * from student where rno=" + r;
ds1.Clear();
10 | P a g e
if (! Page.IsPostBack)
{
sda = new SqlDataAdapter("select * from student", con);
sda.Fill(ds, "student");
CheckBoxList1.DataSource=ds.Tables[student];
CheckBoxList1.DataTextField=rno;
CheckBoxList1.DataValueField=rno;
CheckBoxList1.DataBind();
}
11 | P a g e
string s1=,s2=,s3;
for (int i=0;i<CheckBoxList1.Items.Count;i++)
{
if (CheckBoxList1.Items[i].Selected)
s1=s1++CheckBoxList1.Items[i].Text++,;
// if string
s1=s1+CheckBoxList1.Items[i].Text+,;
// if numeric
int l=s1.length;
s2=s1.Substring(0,l-1);
s3=select * from student where rno in (+s2+);
Response.Write(s1=+s1);
Response.Write(<br>s2=+s2);
Response.Write(<br>s3=+s3);
SqlDataAdapter sda1=new SqlDataAdapter(s3,con);
DataSet ds1=new DataSet();
sda1.fill(ds1);
GridView1.DataSource = ds1.Tables[0];
GridView1.DataBind();
12 | P a g e
if (! Page.IsPostBack)
{
Session[cr] = 0;
13 | P a g e
}
sda = new SqlDataAdapter("select * from student", con);
sda.Fill(ds);
Session[tr] = ds.Tables[0].Rows.Count - 1;
// first
private void button1_Click(object sender, EventArgs e)
{
Session[cr] = 0;
display();
}
// last
private void button3_Click(object sender, EventArgs e)
{
Session[cr] = Session[tr];
display();
}
// next
private void button2_Click(object sender, EventArgs e)
{
14 | P a g e
cr=Convert.ToInt32(Session[cr]);
cr = cr + 1;
Session[cr]=cr;
tr=Convert.ToInt32(Session[tr]);
if (cr > tr)
Session[cr] = 0;
display();
}
// previous
private void button4_Click(object sender, EventArgs e)
{
cr=Convert.ToInt32(Session[cr]);
cr = cr - 1;
Session[cr]=cr;
if (cr < 0)
Session[cr] = Session[tr]/0;
display();
}
}
}
Calling Stored Procedures of SQL Server from .NET
15 | P a g e
-- stored procedure for counting total no. of records according to a given condition
testCMD.CommandType = CommandType.StoredProcedure;
testCMD.Parameters.Clear();
16 | P a g e
sp1.Value=Convert.ToInt32(textBox1.Text);
con.Open();
SqlDataReader myReader = testCMD.ExecuteReader();
myReader.Close();
textBox2.Text=sp2.Value.ToString();
con.Close();
p4.Value = (textBox4.Text);
p5.Value = Convert.ToInt32 (textBox5.Text);
p6.Value = Convert.ToInt32 (textBox6.Text);
p7.Value = Convert.ToInt32 (textBox7.Text);
p8.Value = (textBox8.Text);
p9.Value = (textBox9.Text);
p10.Value = (textBox10.Text);
con.Open();
testCMD.ExecuteNonQuery();
Response.Write("Record added");
con.Close();
19 | P a g e
ADO.NET
It is a collection of Managed Providers that can be used for communication with Data Sources.
-> When .NET was designed for Data Source communication ADO.NET has been designed, which
is an extension to the Older ADO (Collection of Unmanaged Providers).
-> ADO.NET provides various 'types' that can be used for data source communication under the
following namespaces.
1) System. Data
2) System.Data.OleDb
3) System.Data.SqlClient
4) System.Data.OracleClient
5) System.Data.Odbc
System. Data
Types under this namespace are used for holding and managing of data on Client machines.
'Classes' under this namespace are DataSet, DataTable, DataColumn, DataRow, DataView,
DataRelation etc.
System.Data.OleDb
Types under this namespace are used for communicating with any data source like Files,
Databases, and IndexingServers etc.
System.Data.SqlClient
Types under this namespace are used only for Sql Server Database communication.
System.Data.OracleClient
Types under this namespace are used only for Oracle Database communication.
System.Data.Odbc
Types under this namespace are used for communicating with traditional Odbc drivers and they
will in turn communicate with any data source.
All the above four namespaces contains same set of Classes as following.
-Connection
-Command
-DataReader
-DataAdapter
-CommandBuilder
20 | P a g e
-Parameter
Note: - Each 'class' here is referred by prefixing with their namespace before 'class' name to
discriminate between each other as following.
-OleDbConnection
-OleDbCommand
-SqlConnection
-SqlCommand
-OracleConnection
-OracleCommand
-OdbcConnection
-OdbcCommand
Each and every operation we perform on a data source has three steps in it.
1) Establishing a Connection
2) Sending request as a Statement
3) Capturing the results given by DataSource
1) Establishing a Connection
In this process we open a channel for communication with the DataSource present on local or
remote machine to perform the operations. To open a channel for communication we use
'Connection' class.
Constructors
Connection ()
Connection (string connectionstring)
'Connectionstring' is a collection of attributes that are used for connecting with a data source those
are
1) Providers
2) DataSource
3) User Id and Password
4) Database (or) Initial catalog
5) Trusted_Connection = True
6) DSN
1) Provider
As we discussed earlier a Provider is required for communicating with Data sources, where we
need to use different Provider for different Data Source.
Oracle
Msdaora
SqlServer
SqlOleDb
Microsoft.Jet.OleDb.4.0
21 | P a g e
IndexingServer
Msidxs
2) DataSource
It is the name of target machine to which we want to connect with doesnt require to be specified if
data source is on local machine only.
3) User Id & Password
As Databases are secured places for storing data, to connect with them we require a valid
Username and Password.
Oracle
Scott/tiger
SqlServer
Sa/<pwd>
User
Id=Sa;
Password=<pwd>;
Database=<db
name>
[;
Data
using System.Data.OleDb;
Under Connect with Oracle button:
OleDbConnection
oracon
=
new
Id=Scott;Password=tiger");
oracon.Open();
MessageBox.Show(oracon.State.ToString());
oracon.Close();
MessageBox.Show(oracon.State.ToString());
OleDbConnection("Provider=Msdora;User
User
Id=Sa;
sqlcon.Open();
MessageBox.Show(sqlcon.State.ToString());
sqlcon.Close();
MessageBox.Show(sqlcon.State.ToString());
Sending request as a Statement
In this process we send a request to Data source specifying the type of action we want to perform
using a Sql Statement like Insert, Update, Delete and Select. 'Command' class is used for sending
request and executing of the statements.
Command ()
Command (string sqlstmt, Connection con)
Properties of Command class
1) Connection: - Sets or gets the connection object associated with Command.
23 | P a g e
---> DataReader
ExecuteScalar ()
---> object
ExecutNonQuery ()
---> int
After creating the object of 'Command' class we need to call any of these three methods to execute
the statement.
-> Use 'ExecuteReader' method when we want to execute a 'Select' statement that returns data as
Rows and Columns. The method returns an object of class 'DataReader' which holds the data that is
retrieved in the form of Rows and Columns.
-> Use 'ExecuteScalar' method when we want to execute a 'Select' statement that returns a single
value result. Return type of this method is object, which gets the value in a generic type.
-> Use 'ExecutNonQuery' method when we want to ExecutNonQuery statements (DML statements
like Insert, Update and Delete). In this case we need to find out the number of Rows affected by the
statement and also the return type of the method is an 'int'.
Note: - The above process of calling an appropriate method in the appropriate case is our third step
capturing of the results.
Accessing Data from DataReader
DataReader is a class which will hold the data in the form of Rows and Columns (Table Structure).
To access data from DataReader it provides us following methods.
1) Read () -> bool
Move record 'Pointer' from the current location to next row and returns a Boolean status which tells
whether the row to which we have moved contains data in it or not. That will be 'true' if present or
'false' if not represent.
2) GetValue (int index) -> object
Used for retrieving field values from the row to which 'pointer' was pointing by specifying the
Column index position.
Note: - We can access the row pointer by pointer in the form of a single Dimensional array also
either by specifying column index position or name as following.
<DR> [index]
24 | P a g e
-> object
<DR> [columnname]
-> object
-> bool
Moves the record pointer from current table to next table if a table exists and returns true or else
returns false.
using System.Data.OleDb;
Declarations:
OleDbConnection con;
OleDbCommand cmd;
OleDbDataReader dr;
Under Form Load:
con = new OleDbConnection("Provider=Msdaora;User Id=Scott;Password=tiger");
cmd = new OleDbCommand("Select Deptno,Dname,Loc From Dept", con);
con.Open ();
dr = cmd.ExecuteReader();
label1.Text = dr.GetName (0);
label2.Text = dr.GetName (1);
label3.Text = dr.GetName (2);
ShowData ();
25 | P a g e
Declarations:
OleDbConnection con;
OleDbCommand cmd;
OleDbDataReader dr;
string sqlstr;
Under Form Load:
con = new OleDbConnection("Provider=Msdaora;User Id=Scott;Password=tiger");
cmd = new OleDbCommand();
cmd.Connection = con;
LoadData ();
private void LoadData()
{
sqlstr = "Select Deptno,Dname,Loc From Dept Order By Deptno";
SetStmt ();
dr = cmd.ExecuteReader();
ShowData ();
}
private void SetStmt()
{
if (con.State != ConnectionState.Closed)
con.Close ();
cmd.CommandText = sqlstr;
con.Open ();
}
private void ShowData()
{
if (dr.Read())
{
textBox1.Text = dr [0].ToString ();
textBox2.Text = dr [1].ToString ();
textBox3.Text = dr [2].ToString ();
}
else
MessageBox.Show ("Last record of the Table");
}
private void ExecuteDML()
{
DialogResult d = MessageBox.Show (sqlstr + "\n\nDo you wish to execute the Query?",
"Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (d == DialogResult.Yes)
{
SetStmt ();
int Count = cmd.ExecuteNonQuery();
if (Count > 0)
MessageBox.Show ("Statement Executed Successfully");
Else
MessageBox.Show ("Statement Execution Failed");
LoadData ();
27 | P a g e
}
}
Under Next button:
ShowData ();
Under New button:
textBox1.Text = textBox2.Text = textBox3.Text = ""; sqlstr = "Select Max(Deptno) + 10 From
Dept";
SetStmt ();
textBox1.Text = cmd.ExecuteScalar ().ToString ();
textBox2.Focus ();
Under Insert button:
sqlstr=String.Format("Insert
Into
Dept
textBox1.Text, textBox2, Text, textBox3.Text);
ExecuteDML ();
(Deptno,Dname,Loc)
Values({0},'{1}','{2}')",
When a user connects through windows authentication, Sql Server validates the account name and
password using the windows principal token in the operating system; this means that the user
identity is confirmed by windows, Sql Server does not ask for the password and does not perform
the identity validation. When using Sql Server authentication, logins are created in Sql server that
is not based on Windows user accounts, both the user name and password are created by using Sql
Server and stored in Sql Server database. Users connecting with Sql Server authentication must
provide their credentials every time they connect with Database server.
28 | P a g e
Note: - If we want to connect from a .NET application using Windows authentication mode, within
the connection string in the place of User Id and Password attributes use
"Trusted_Connection=True" or "Integrated Security=SSPI" attributes.
Connection String for Sql Server Authentication:
"Provider=SqlOleDb; User
Source=<Server Name>]"
Id=SA;
Password=<pwd>;
Database=<DBName>
[;
Data
Go to Start Menu
-> Programs
-> MS Sql Server
-> Sql Server Management Studio
Click on it to open & provide the authentication details to login. Once the studio is opened in the
LHS we find a window "Object Explorer", in that right click on the node Databases, Select "New
Database" that opens a windows asking for the name, enter name as "CSharDB", click 'OK' which
adds the database under databases node. Now expand the CSharpDB node, right click on Tables
node & select "New Table" which opens a window asking for column names & data types enter the
following.
Eno (int), Ename (Varchar), Job (Varchar), Salary (Money), Photo (Image), Status (Bit)
Select Status column and go into column properties in the bottom and set "Default value or
Binding" property as 1, which takes the default value for status column as true. Click on the save
button on top of the studio which will prompt for table name enter name as "Employee" & Click
OK which adds the table under tables node. Now right click on the table created and select "Edit"
which opens a window under it enters the data we want ignoring Photo and Status columns. Close
the Studio.
29 | P a g e
using System.Data.SqlClient;
Declarations:
sqlConnection con;
sqlCommand cmd;
sqlDataReader dr;
Under Form Load:
con=new sqlConnection("User Id=Sa;Password=<pwd>;Database=C#DB");
cmd=new sqlCommand("Select eno,ename,job,salary From employee",con);
con.Open();
dr=cmd.ExecuteReader();
Label1.Text=dr.GetName(0);
Label2.Text=dr.GetName(1);
Label3.Text=dr.GetName(2);
Label4.Text=dr.GetName(3);
ShowData();
}
private void ShowData()
{
if(dr.Read())
30 | P a g e
{
textBox1.Text=dr[0].ToString();
textBox2.Text=dr [1].ToString ();
textBox3.Text=dr [2].ToString ();
textBox4.Text=dr [3].ToString ();
}
else
MessageBox.Show ("Last record of the Table");
Under Next button:
if(con.State !=ConnectionState.Closed)
con.Close ();
this.Close ();
DataReader
It is a class that can hold you the data on client machine in the form of Rows and Columns.
Features of DataReader
1) Faster in access to data from the data source as it is Connection oriented.
2) Can hold multiple tables in it at a time. To load Multiple table with DataReader pass multiple
selection statements as args to command separated by a ';'
Eg:
Command
Teacher; on);
cmd=new
Command
(Select*From
Statements;
Select*From
In the first case we require a continuous connection with data source for accessing the data in it.
Here 'DataReader' class is used for holding data on client machines, where as in the second case we
dont require a continuous connection with Data source for accessing of the data. Here 'DataSet'
class is used for holding the data on client machines.
DatSet
It is a class under 'System.Data' namespace used for holding and managing data on Client machine
apart from DataReader.
Features of DataSet
1) It is capable of holding multiple tables.
2) It is designed in Dis-Connected architecture which doesn't require any permanent connection
with source for holding of the data.
3) If provides scrollable navigation to data that allows to navigate in any direction that is top to
bottom or bottom to top.
4) It is updatable that is changes can be performed to data present in it. And also send them back to
database.
Working with DataSet
The class that is responsible for loading of data into a DataReader from DataSource is 'Command'.
In the same way 'DataAdopter' class is used for communication between data source and 'DataSet'.
DataReader <------- Command -------> DataSource
DataSet <-------> DataAdopter <------> DataSource
Constructors
DataAdopter(string stmt,Connection con)
DataAdopter(Command cmd)
Eg: - DataAdopter da=new DataAdopter("<sql stmt>",con);
Methods of Adopter
-> Fill (DataSet ds,string tname)
-> Update (DataSet ds,string tname)
32 | P a g e
'Fill' is to load Data from a DataSource into DataSet. 'Update' is to transfer data from a DataSet to
DataSource.
Data Adopter is internally collection of four commands.
1) Select Command
2) Insert Command
3) Update Command
4) Delete Command
When we call 'Fill' method on Adopter following things takes place
1) Opens a Connection with Data Source
2) Execute the Select Command under it on the Data Source and loads data from table to DataSet.
3) Closes the Connection.
As we aware DataSet is Updatable we can make changes to the Data that in loaded into it like
Adding, Modifying and Deleting.
After making the changes to data if we want to send those changes back to data source we need to
call 'Update' method on Adopter, which performs the following.
1) Re-Open the connection with Data source
2) Changes that are made in DataSet will be back to the table where in this process it will make use
of Insert, Update and Delete Commands of Adopter.
3) Closes the Connection.
'DataReader' provides pointer based access to the data. So we can get the data only in a sequential
order where as 'DataSet' provides Index based access to the data. So we can get the from any
location ReadOnly.
'DataSet' is a collection of tables where each table is represented as a class 'DataTable' and
identified by its Index position or name.
DataSet:
-Collection of Tables (DataTable) <dataset>.Tables [Index]
(Or)
-ds.Tables [0] (or) ds.Tables ["Employee"]
-> Every DataTable is again collection of Rows and Columns where each Row is represented as a
class 'DataRow' and identified by its IndexPosition. Each column is represented as a class
'DataColumn' and identified by its Index position or name.
DataTable:
-Collection of Rows (DataRow)
< datatable >.Rows[Index]
ds.Tables [0].Rows [0]
34 | P a g e
-> Add reference of 'Microsoft.VisualBasic' assembly from .NET tab of add reference window and
write the following code.
using System.Data.SqlClient;
using Microsoft.VisualBasic;
Declarations:
SqlConnection con;
SqlDataAdapter da;
SqlCommandBuilder cb;
DataSet ds;
int rno = 0;
\Under Form Load:
con = new SqlConnection("User Id=sa;Password=123;Database=mydb");
da = new SqlDataAdapter("Select Empno,Ename,Job,Sal from Emp", con);
ds = new DataSet();
da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
da.Fill(ds, "Emp");
ShowData();
private void ShowData()
35 | P a g e
{
textBox1.Text = ds.Tables[0].Rows[rno][0].ToString();
textBox2.Text = ds.Tables[0].Rows[rno][1].ToString();
textBox3.Text = ds.Tables[0].Rows[rno][2].ToString();
textBox4.Text = ds.Tables[0].Rows[rno][3].ToString();
}
Under First button:
rno = 0;
ShowData();
Under Prev button:
if (rno > 0)
{
rno -= 1;
if (ds.Tables[0].Rows[rno].RowState == DataRowState.Deleted)
{
MessageBox.Show("Deleted Row Cannot be Accessed");
return;
}
ShowData();
}
else
MessageBox.Show("First Record of the Table");
Under Next button:
if (rno < ds.Tables[0].Rows.Count - 1)
{
rno += 1;
if (ds.Tables[0].Rows[rno].RowState == DataRowState.Deleted)
{
MessageBox.Show("Deleted Row Cannot be Acceessed");
return;
}
ShowData();
}
else
MessageBox.Show("Last Record of the Table");
Under Last button:
rno = ds.Tables[0].Rows.Count - 1;
ShowData();
Under New button:
textBox1.Text = textBox2.Text = textBox3.Text = textBox4.Text = "";
int index = ds.Tables[0].Rows.Count - 1;
textBox1.Text = (Convert.ToInt32(ds.Tables[0].Rows[index][0])+1.ToString());
textBox2.Focus();
36 | P a g e
DataGridView Control
38 | P a g e
It is a control that can display data in the form of Rows and Columns, that is table structure we can
directly bind a DataTable to the Control using Data Source property of the Control. So that all the
records of DataTable gets displayed under Gridview.
dataGridView1.DataSource=<data table>
The control has a specialty, that is changes can be made to the data that is present under the control
and these changes gets reflected directly into the DataTable to which the GridView was bound
without any coding.
Eg:-
using System.Data.SqlClient;
Declarations:
SqlConnection con;
SqlDataAdapter da;
SqlCommandBuilder cb;
39 | P a g e
DataSet ds;
Under Form Load:
con = new SqlConnection("User Id=sa;Password=123;Database=MYDB");
da = new SqlDataAdapter("Select Empno,Ename,Job,Sal From Emp", con);
ds = new DataSet();
da.Fill(ds, "Emp");
dataGridView1.DataSource = ds.Tables[0];
Under Save to DB button:
cb = new SqlCommandBuilder(da);
da.Update(ds, "Emp");
MessageBox.Show("Data Saved to DB");
Under Close Button:
this.Close();
Note: Before installing the Setup on the Client Machine make sure that the .Net Framework is
installed on it.
40 | P a g e
Remoting
Application Architecture's: Every application contains 3 different parts in it like:
1. UI Part
2. Logic Part(BL+DL)
Organizations as per their requirement adopts different architecture's for execution of their
application 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 Database 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 Architecture: In this model all the 3 parts will sit on 3 different machines to execute, so
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. Maintanance of the
software becomes easier in this model there were more number of client accessing the application.
41 | P a g e
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)
42 | P a g e
To perform Serialization & De-Serialization remoting provides Formatter Classes, those are:
-Binary Formatters:
-TCPServerChannel
-Soap Formatters:
-HttpServerChannel
-TCPClientChannel
-HttpClientChannel
Binary Formatters are used for binary serialiaztion and De-Serialization & Soap Formatters are
used for text serialization and de-serialization.
Note: - Traditional DCOM supports only binary.
HostName
192.168.26.0 (Praveen)
192.168.26.24 (Naveen)
Note: - A class which is available on the server for the consumption of clients is referred as a
'Remote Class' and this Remote Class will contain all the Methods that are necessary for the
clients.
3. Activation Models:
43 | P a g e
In execution of Remoting application clients needs object or remote class to invoke methods under
it. Activation Models decide where the remote class objects resides in execution of the application.
Remoting supports 2 different activation models.
-Server Activated Objects (SAO)
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 object of remote class resides on client machine using which clients can invoke the
methods of remote class.
SingleTon: In this case whenever a first request comes from a client an object of remote class gets
created and its reference is given to the client, from then every new request coming 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 model whenever a requedt comes from a client 1 object of remote class gets
created and its reference is given to client, once the request is served immediately object gets
destroyed without 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 developement of single request application
like "Railway PNR Status Enquiry", "ATM Machines" & "Examination Results".
44 | P a g e
Client Activated Objects (CAO): In this case whenever the first request from a client an object of
remote class is created and provided, using which the client can make any number of requests.
Here a separate object will be given for each client so changes made by 1 client will never reflect
to the other. Used in the development of application that requires multiple requests for a single
client like "Traditional ATM Machines", where we can perfrom multiple transactions once we
insert the card.
1. Server:
When we want to develop an application to be consumed from remote machines we require
someone to take the request from clients. To take a request from client we use server's, which
works on the principles request and response. We can install multiple server software's on a
machine, but each server should be running on a separate logical address known as port.
45 | P a g e
In process of developing remoting application it is our responsibility to develop a server that takes
requests of clients to the Remote Class, because a class is not capable of taking the request. Te
server should be running on a unique port of the OS. By default every machine has port's that are
ranging between 0-65535 in which 0-1023 were OS reserved ports, rest can be used by any
application.
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 act as a proxy to Remote Class on client
machine, which will be used in 2 ways.
1. Using it clients can recognize methods of remote class (works as Metadata).
2. Using it we can hold reference of remote class on client machines.
46 | P a g e
Developing an Interface:
Open a new project of type "Class Library" & name it as "InterfaceProject". Delete the 'Class1.cs'
file under the project and add an "Interface" to the project naming it "IRemoteApp.cs", and write
the following code:
public interface IRemoteApp
{
string Get_Ename(int eno);
47 | P a g e
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=mydb");
cmd=new SqlCommand();
cmd.Connection=con;
}
public string Get_Ename(int eno)
{
string name=null;
try
48 | P a g e
{
cmd.CommandText="Select Ename From Employee Where Eno="+eno;
con.Open();
name=cmd.ExecuteScalar().ToString();
}
catch (Exception ex)
{
ex=null;
}
finally
{
con.Close();
}
retrun name;
}
public decimal Get_Bal(int custid)
{
decimal bal=0;
try
{
cmd.CommandText="Select Balacne From Customer Where Custid="+custid;
con.Open();
bal=Convert.ToDecimal(cmd.ExecuteScalar());
}
catch (Exception ex)
{
ex=null;
}
finally
{
49 | P a g e
con.Close();
}
return bal;
}
public string SayHello()
{
x+=1;
return "Hello: "+x;
}
public string Demo()
{
return "Not accessible to Remote Clients";
}
}
Note: - While developing an Windows Service it is our responsibility to set all above 4 attributes.
1.System.Runtime.Remoting.dll(.net) 2.ClassProject.dll(browse)
3.InterfaceProject.dll(browse)
Now go to design view of the project, right click on it & select Add Installer, which adds 2
components ServiceInstaller1 & ServiceProcessInstaller1 using which you need to set the 4
attributes of service. Under ServiceInstaller1 Properties set following.
1.DisplayName:RemoteServer
2.Description:Takes request from remote clients
3.StartupType:Automatic
And under ServiceProcessInstaller1 Properties set 'Account' property as "Local System" & build
the project which creates an assembly "RemoteServer.exe"
Format:
tcp://<server name>:5000/xxx
Step4: 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>)
Step5: Now client needs to convert reference of Remote class present in object format to Interface
format.
Eg:- IremoteApp ira=(IRemoteApp)obj;
53 | P a g e
Step6: Now using the reference invoke methods of Remote Class that executes on server machine
only.
using InterfaceProject;
using System.Configuration;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channesl.Tcp;
Declarations:
IRemoteApp ira;
54 | P a g e
SingleTon vs SingleCall
Right now remote class is registered under remote server in singleton mode, in this mode whenever
the first request comes from the client an object of remote class is created and it's reference is
provided to the client, form then for any new request coming from a new client server provides
reference of same object that is already created, so all clients share same object memory because of
this changes mady by any 1 client gets reflected to others. To change mode of application from
sigleton to singlecall follow the belwo process:
1) Open Visual Studio command prompt, go into the folder where RemoteSerer.exe was present &
un-install it using 'installutil' tool
eg: installutil -u RemoteServer.exe
2) 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.
3) Re-install RemoteServer from VS command prompt again.
55 | P a g e
Multi Threading
A single program performing multiple options in a symaltanious fashion is known as 'Multi
Threading'.
Traditionally we have a concept known as 'Multi Tasking' where multiple programs can execute at
a time, which is basically supported by your Operating System.
Eg: Windows, Unix, Linux etc
Where 'Dos' is a Single Tasking Operating System, which is capable of running only one program
at a given point of time.
Multi Threading is supported by languages with the help of Operating System.
A thread is a unit of execution and by default every program has a thread responsible for executing
the program that is 'Main Thread', means every program is by default 'Single Threaded' that
executes a program by performing the actions one by one.
In single threaded model because the action gets performed one after the other until the current
action is completed, we cannot go to the next action, even if we have ideal time in performing the
action also.
To Overcome the above drawback we use 'Multi Threading', where we will be using multiple
threads to perform multiple actions are calling multiple methods, that is one thread for each
method.
when a application is 'Multi Threaded' the execution of an application takes place as following..
1) Time Shared: Here the operating system allocates some time period for each thread to execute
and once the time is completed it gets automatically transfer to the other thread in execution giving
equal preference to all the threads.
2) Maximum Utilization of Resources: This comes into picture when the first principle violates,
that is if a thread could not execute for some reason in its given time period without waiting for it
to execute the control immediately gets transferred to the other thread in execution without wasting
the 'CPU' resources.
How to create a Thread
To create a thread we need to create object of the class 'Thread', where each object we create is
considered as a thread.
56 | P a g e
The class 'Thread' is present under 'System.Threading' namespace & while creating the object we
should explicitly specify the method we want to call in its constructor.
System.Threading.Thread(MethodName)
eg:
Open a new project of type 'Console' and name it as 'ThreadProject' and write the following coe in
the default class 'Program'.
using System.Threading;
class Program
{
Thread t1, t2;
public Program()
{
t1 = new Thread(Test1);
t2 = new Thread(Test2);
t1.Start(); t2.Start();
}
public void Test1()
{
for (int i = 1; i <= 100; i++)
{
Console.WriteLine("Test1:" + i);
if (i == 50)
Thread.Sleep(10000);
}
}
public void Test2()
{
for (int i = 1; i <= 100; i++)
{
Console.WriteLine("Test2:" + i);
}
}
static void Main(string[] args)
{
Program p = new Program();
Console.ReadLine();
}
}
'Start' is a Method of Thread class which starts the execution of your thread.
57 | P a g e
'Stop' is a statci method of thread class which makes the current executing thread to sleep until the
given time period is elapsed.
58 | P a g e