ado.net: activex data objects for .net, set of components...

41
ADO.NET (saideep) > ADO.NET: ActiveX Data Objects for .NET, set of components used to interact with any DB/ XML docs It supports 2 models for interacting with the DB: 1. Disconnected Model 2. Connection Oriented Model Note: System.Data is the namespace of .NET which has the data functionality class. It has objs used for accessing n storing relational data such as DataSet, DataTable and Data relation. ______________________________________________________________________________________ > ADO.NET Disconnected Model No need of connectivity betw app and db. It uses data providers such as Connection (for physical cn with db), DataAdapter n DataSet (binded with the app)- uses DataView (filter/sort/paging data) Whereas for Connection Oriented Model- the data providers are Connection, Command obj (acts as a source for the connection obj) and DataReader

Upload: others

Post on 18-Apr-2020

30 views

Category:

Documents


0 download

TRANSCRIPT

ADO.NET (saideep)

> ADO.NET: ActiveX Data Objects for .NET, set of components used to interact with any DB/ XML docs

It supports 2 models for interacting with the DB:

1. Disconnected Model

2. Connection Oriented Model

Note: System.Data is the namespace of .NET which has the data functionality class. It has objs used for accessing n

storing relational data such as DataSet, DataTable and Data relation.

______________________________________________________________________________________

> ADO.NET Disconnected Model

No need of connectivity betw app and db. It uses data providers such as Connection (for physical cn with db),

DataAdapter n DataSet (binded with the app)- uses DataView (filter/sort/paging data)

Whereas for Connection Oriented Model- the data providers are Connection, Command obj (acts as a source for the

connection obj) and DataReader

ADO.NET (saideep)

> An app cant interact with a DB directly, hence we use ADO.NET. When we use Discn Model Arch we will be provided

with managed 'managed data providers'. They are:

Connection (estb physical connection with the data source),

Data Adapter : Collection of Command Objects used to transfer data betw DB and DataSet. It reads data from the DB n

are used to fills the DataSet n used to read data from the DataTables of DataSet n used to update the DB.

(It uses the connection obj to connect to a data source using command objs to retrieve data from unresolt changes to

the data source. It can't interact with the app directly) so we take a DataSet and pass the data to the Data Set, now the

app can use the data in Data Set for perfm navigation or manipulations. When the data has to be stored, filtered a

DataView can be used.

ADO.NET (saideep)

> Connection obj: sets a physical link betw data source and ADO.NET with support of connection string.

> Data Adapter: collection of command objs- transfers data betw DB and dataset.

ADO.NET (saideep)

The commands present within the Data Adapter are:

Important methods of DataAdapter:

Fill- used to read the data from DB n fill the DataSet

Fill Schema- uses the select command just to extract schema for a table from the data source and creates an empty

table in the DataSet object with all the coresponding constraints.

Update- it updates the data source with changes made to the content of DataSet.

> Data Set: in-memory representation of the data (XML format) at the client system

ADO.NET (saideep)

DataSet can interact with any number of tables present in different databases, such as SQL Server, Oracle, or XML

documents. It also supports establishing the data relationship between the data tables. If any manipulations are

performed on the data table of DataSet, the changes will not be reflected at the tables of the database. Our DataSet

object can also be considered as a collection of DataTables, DataRelations, and XMLSchema, where our DataTable or a

DataMember of a DataSet is a collection of DataColumns, DataRows, and Constraints. Whenever our DataSet object is

defined with the support of XML Schema definition, then we call it a typed DataSet, and without XML Schema definition,

it is set to be untyped DataSet.

Link: https://www.youtube.com/watch?v=fTPc9bCZrnY&list=PL6n9fhu94yhX5dzHunAI2t4kE0kOuv4D7&index=17

Typed DataSet: a custom class, consists of classes derived from DataSet, DataTable n DataRow. It assumes all the

functionality of a DataSet class n can be used with methods that takes an instance of a DataSet class as a parameter. It is

ADO.NET (saideep)

bind with the db tables at the design time. All the schema info is at the design time in your code. It is stored in a .xsd

(xml schema defn) file and do error checking regarding this schema at design time using the .xsd definitions. You can

access the tables n columns with its actual names as it is added in .xsd file in your app.

Untyped DataSet: instance of a class System.Data.DataSet. It is binded with the tables at run time- no built in schema.

You are not aware of the data of the schema and no erro checking facility at design time, as they are filled at the run

time as the code executes.

Link: https://www.youtube.com/watch?v=9fWrddh_7MY&index=9&list=PLyLkn_nipSjMreSs__kL9PRTfTvnpXcfi

> DataView: is used for sorting, filtering, searching, editing and navigation on the data

ADO.NET (saideep)

______________________________________________________________________________________

ADO.NET (saideep)

ADO.NET connection oriented model: Whenever we use this model, then the connectivity between the application and

the database has to be maintained until the application interacts with the database. Connection-oriented model can be

used whenever we constantly make trips to the database to perform group operations. This creates more traffic to the

database, but is normally much faster when we perform smaller transactions. In simple, non-technical terms, to

understand connection-oriented model, it is similar to working with the standard desktop systems, that is, until we need

to work with the system, it should be connected with the power.

Connection-oriented model architecture: Say we have an application and it has to interact with the database using

connection-oriented model. Then, we have been provided with managed data providers. We use connection to establish

the physical connectivity with the database. Command object will use Connection to interact with our database, and it

can interact with the application for executing the commands, and if the command is to retrieve the data, then the

result of Command object will be passed to the DataReader object, which will interact with the application for projecting

the data. DataReader object maintains the records retrieved by the Command object, and this object is a read-only and

forward-only record set. That is, the data present within the DataReader object can be modified, and once the data has

been read from the DataReader, again, we can't retrieve the previous data.

> Command Object: provides the source for the connection obj and used to execute the statements.

Command object is used to store SQL statements that need to be executed against a data source. The Command object

can execute select statements, Insert, Update, Delete statements, StoredProcedure, or any valid SQL statement

understood by the database.

Command object has the following important properties. Connection, used to specify the connection to be used by the

Command object. CommandType, used to specify the type of SQL command you wanted to execute. To assign a value to

this property, we use the enumeration CommandType that has the members Text, StoredProcedures, and TableDirect.

Text is the default and is set when you want to execute any SQL command with Command object. StoredProcedure is set

when you want to call a StoredProcedure ALT function. And TableDirect is set when you want to retrieve data from the

ADO.NET (saideep)

table directly by specifying the table name without writing a Select statement. CommandText, used to specify the SQL

statement you want to execute.Transaction, used to associate a transaction object to the Command object so that the

changes made to the database with Command object can be commited or rolled back. Command object has the

following important methods.

ExecuteScalar, used to execute a Select statement that returns a single value. If the Select statement executed by the

ExecuteScalar method returns more than one value, then the method returns the value present at the first row, first

column retrieved by the query. ExecuteScalar methods return an object.

ExecuteReader, it is used to execute any valid Select statement. Return type of this method is DataReader.

ExecuteNonQuery, used to execute any valid SQL statement other than the Select statement. Written type of this

method is int and it returns the number of rows affected by the given statement.

> Data Reader

We can't define the DataReader object directly. It can be defined with the support of ExecuteReader method of

command object. Whenever we use the DataReader object, it is mandatory to open the connection. While using the

DataReader for accessing the data, it can be used for any other operations.

________________________________________________________________________________________

ADO.NET (saideep)

ADO.NET (saideep)

________________________________________________________________________________________

Connection String:

Note : Whenever we use SQL connection class to interact with the SQL Server database, an Oracle connection class to

interact with the Oracle database, then Provider= provider name is not required within the connection string.

Note: We can generate connection string with support of UDL file. (Universal Data Link)

ADO.NET (saideep)

Note: Remove the 'Provider' while using SQL connection class

_______________________________________________________________________________________

ADO.NET (saideep)

Note: If the table is defined with the PRIMARY KEY, then all the commands for the DataAdapter will be generated, and if

the table is defined without a PRIMARY KEY, then the commands for UpdateCommand and DeleteCommand will not be

generated.

ADO.NET (saideep)

> Adding a Record

Steps common to ADO.NET Disc Model:

After this: Define the DataRow variable, assign the new row of the DataTable, provide the values for the columns. Once

we provided the values for the columns, add the DataRow variable to the Rows collection, and finally, update the

DataAdapter. If all the above steps are executed successfully, then the record should have been added.

So let us try to provide a confirmation Employee Record Added using a MessageBox. Now let us execute the application

to verify. I provide the values for the controls and click on Add Employee. We got the message Employee Record Added.

Now let us quickly flip to SQL Server and execute the statement to verify the record has been added successfully. Now

let us try to understand how the record has been added.

1. First, the connection object is defined to establish the physical connection to the database. Then, our

2. DataAdapter is defined to interact with the employee's table.

ADO.NET (saideep)

3. CommandBuilder object generated the commands for the DataAdapter object.

4. Then we defined the DataSet and filled the data to the DataSet. Once the data has been filled, we have added a

PRIMARY KEY constraint on the data column. In order to add a record, first we

5. defined our DataRow, then we assigned a new row of the DataTable, provided the values to the DataColumns,

and added the row to the DataTable. As we know, if any manipulations are performed on the DataTable, it will

not be reflected. So we

6. updated the DataAdapter, which will reflect the changes at the database.

Link: https://app.pluralsight.com/player?course=adodotnet-by-example&author=sekhar-srinivas&name=adodotnet-by-example-

m3&clip=1&mode=live&start=66.8622472222227

> Retrieving the Data

ADO.NET (saideep)

ADO.NET (saideep)

_______________________________________________________________________________________

_______________________________________________________________________________________

ADO.NET (saideep)

_______________________________________________________________________________________

ADO.NET (saideep)

_______________________________________________________________________________________

> Reading data from Excel Sheet

ADO.NET (saideep)

On 64-bit Windows and Office 2010/2013 there may be this error:

ADO.NET (saideep)

The name of excel sheet in this work book is Marks.

_______________________________________________________________________________________

> Reading data from XML documents

Read XML method of DataSet, is used to read the data from an XML document, and used to maintain the result as

DataTable in DataSet. It is an overloaded method, which can take two parameters, where the first parameter is used to

provide the source of the XML document using either a filename, stream, textreader, and XMLreader, and the second

parameter is used to specify the XML read mode, where XML read mode enumerations specifies how to read the XML

data and schema into DataSet.

The XML read mode supports Diffgram, Fragment, IgnoreSchema andInferSchema, auto, et cetera. Now let us

understand how to project the data present in products.XML document using ReadXML method with a simple example. I

already added a Windows Form, and now let us place our DataGridView control on the form, and set the doc property as

Fill.

ADO.NET (saideep)

____________________________________________________________________________________

> Generate Typed DataSet

> Using Typed DataSet

Alt+Shift+D- to project the data using Typed DataSet. It opens the available data sources for us.

____________________________________________________________________________________

Define variables:

Create Objects at the form_load:

ADO.NET (saideep)

LoadChildData: method which accepts the row index of the parent and projects the relevant products on the

DataGridView control.

Now write the definition for LoadChildData method:

Clone is a method which is used to copy the structure from one DataTable.

Within the SelectionChanged event of the DataGridView control we invoke the LoadChildData method by passing the

DataGridView currentRow index:

ADO.NET (saideep)

____________________________________________________________________________________

> Connection Oriented Model

ExecuteScalar( ): method which returns an object (Select Statement returns a single value)

ExecuteReader( ): method which returns a DataReader Object (more than one value)

ExecuteNonQuery( ): used when the command is any valid SQL statement (not Select statement)

Note: It is mandatory to open the Connection Object but closing is optional.

Note: string cs = @"Data Source=CAPU\SQLEXPRESS; database = PSDB;Integrated Security=SSPI";

Note: DataReader object can't be binded directly in Windows Form app, so DataTable is defined.

My work:

using System.Data.SqlClient; namespace WindowsFormsApplication2 { public partial class Form1 : Form

ADO.NET (saideep)

{ SqlConnection cn; SqlCommand cmd; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { string cs = @"Data Source=CAPU\SQLEXPRESS; database = PSDB;Integrated Security=SSPI"; cn = new SqlConnection(cs); cmd = new SqlCommand(); cmd.Connection = cn; cmd.CommandType = CommandType.Text; } private void buttonAdd_Click(object sender, EventArgs e) { string cname = textBoxCompanyName.Text; decimal revenue = decimal.Parse(textBoxRevenue.Text); cmd.CommandText = "insert into CompanyRevenues values (@cname, @revenue)"; cmd.Parameters.AddWithValue("@cname", cname); cmd.Parameters.AddWithValue("@revenue", revenue); if (cn.State == ConnectionState.Closed) cn.Open(); cmd.ExecuteNonQuery(); cn.Close(); MessageBox.Show("Company added successfully..."); previewFn(); } private void buttonUpdate_Click(object sender, EventArgs e) { try { string cname = textBoxCompanyName.Text; decimal revenue = decimal.Parse(textBoxRevenue.Text); cmd.Parameters.Clear(); cmd.CommandText = "update CompanyRevenues set Revenue=@revenue where CompanyName=@cname"; cmd.Parameters.AddWithValue("@revenue", revenue); cmd.Parameters.AddWithValue("@cname", cname); if (cn.State == ConnectionState.Closed) cn.Open(); cmd.ExecuteNonQuery(); cn.Close(); MessageBox.Show("Company has been updated...", "sucess"); previewFn(); } catch { MessageBox.Show("Opps..."); }

ADO.NET (saideep)

} private void buttonPreview_Click(object sender, EventArgs e) { cmd.Parameters.Clear(); cmd.CommandText = "select * from CompanyRevenues"; if (cn.State == ConnectionState.Closed) cn.Open(); SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); DataTable dt = new DataTable(); dt.Load(dr); dataGridView1.DataSource = dt; chart1.DataSource = dt; chart1.Series[0].XValueMember = "CompanyName"; chart1.Series[0].YValueMembers = "Revenue"; chart1.DataBind(); } private void buttonSearch_Click(object sender, EventArgs e) { cmd.Parameters.Clear(); cmd.CommandText = "select Revenue from CompanyRevenues where CompanyName = @cname"; cmd.Parameters.AddWithValue("@cname", textBoxCompanyName.Text); if (cn.State == ConnectionState.Closed) cn.Open(); decimal revenue; revenue = (decimal)cmd.ExecuteScalar(); textBoxRevenue.Text = revenue.ToString(); cn.Close(); } private void buttonDelete_Click(object sender, EventArgs e) { string cname = textBoxCompanyName.Text; cmd.Parameters.Clear(); cmd.CommandText = "delete from CompanyRevenues where CompanyName = @cname"; cmd.Parameters.AddWithValue("@cname", cname); if (cn.State == ConnectionState.Closed) cn.Open(); cmd.ExecuteNonQuery(); cn.Close(); MessageBox.Show("Company deleted successfully..."); textBoxCompanyName.Clear(); textBoxRevenue.Clear(); previewFn(); } private void previewFn() { cmd.Parameters.Clear(); cmd.CommandText = "select * from CompanyRevenues"; if (cn.State == ConnectionState.Closed) cn.Open(); SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); DataTable dt = new DataTable(); dt.Load(dr);

ADO.NET (saideep)

dataGridView1.DataSource = dt; chart1.DataSource = dt; chart1.Series[0].XValueMember = "CompanyName"; chart1.Series[0].YValueMembers = "Revenue"; chart1.DataBind(); } } } ____________________________________________________________________________________

Consuming Stored Procedures:

____________________________________________________________________________________

DataReader: read only (cannot insert/update/delete/manipulate data back to the data source) & forward only (cannot

read backward/ random). DataReader fetch the data from a DB and stores it in a network buffer n gives whenever

requested. It realizes the record as query executes n doesn’t wait for the entire query to execute (fast). Forward only-

one data at a time from a single table.

It is a connected architecture- data is available as long as the connection with the DB exists. It requires manual open and

close cn code.

DataSet: collection of in-memory tables. It releases data after loading all the data in memory from a data source. It can

fetch data from multiple tables.

It is a dis-connected architecture that automatically opens the cn, fetches the data into memory and closes the cn when

done. DataSet can be serialized eg. represented in XML so used in WCF or web services which returns retrieved data.

Navigating throu data multiple times is possible eg. We can fill data in multiple tables.

Link: https://www.youtube.com/watch?v=nv3W1SKTNaI&index=5&list=PLyLkn_nipSjMreSs__kL9PRTfTvnpXcfi

ADO.NET (saideep)

____________________________________________________________________________________

SqlBulkCopy: class used to bulk copy data from diff data source to SQL server DB. Any data source can be used as long as

the data can be loaded to a DataTable instance/ read with a IDataReader instance.

Link: https://www.youtube.com/watch?v=FOVROz5wc64&list=PL6n9fhu94yhX5dzHunAI2t4kE0kOuv4D7&index=18

My work:

protected void Button1_Click(object sender, EventArgs e) { string cs = ConfigurationManager.ConnectionStrings["CS"].ConnectionString; //create an instance of sql connection obj using (SqlConnection con= new SqlConnection(cs)) { //create an instance of a DataSet DataSet ds = new DataSet(); ds.ReadXml(Server.MapPath("~/Data.xml")); DataTable dtDept = ds.Tables["Department"]; DataTable dtEmp = ds.Tables["Employee"]; con.Open(); using (SqlBulkCopy bc=new SqlBulkCopy(con)) { //specify the table bc.DestinationTableName = "Departments"; //specify column mappings bc.ColumnMappings.Add("ID", "ID"); bc.ColumnMappings.Add("Name", "Name"); bc.ColumnMappings.Add("Location", "Location"); bc.WriteToServer(dtDept); } using (SqlBulkCopy bc = new SqlBulkCopy(con)) { //specify the table bc.DestinationTableName = "Employees";

ADO.NET (saideep)

//specify column mappings bc.ColumnMappings.Add("ID", "ID"); bc.ColumnMappings.Add("Name", "Name"); bc.ColumnMappings.Add("Gender", "Gender"); bc.ColumnMappings.Add("DepartmentId", "DepartmentId"); bc.WriteToServer(dtEmp); } } } ____________________________________________________________________________________

> Copying data from one table to another table using SqlBulkCopy

Link: https://www.youtube.com/watch?v=nNT1blpxvR4&index=19&list=PL6n9fhu94yhX5dzHunAI2t4kE0kOuv4D7&nohtml5=False

____________________________________________________________________________________

Storing IMAGES in the database:

ADO.NET (saideep)

Storing IMG in the DB using Connection Oriented Model:

My Work:

using System.Data; using System.Data.SqlClient; using System.IO; namespace WindowsFormsApplicationImage { public partial class Form1 : Form { OpenFileDialog ofd; public Form1() { InitializeComponent(); } private void buttonBrowse_Click(object sender, EventArgs e) { ofd = new OpenFileDialog(); ofd.Filter = "Image Files| *.jpg"; ofd.ShowDialog(); pictureBox1.Image = Image.FromFile(ofd.FileName); } private void buttonAdd_Click(object sender, EventArgs e) { string fname = ofd.FileName; //define a FileStream obj using img file as the source FileStream fs = new FileStream(fname, FileMode.Open, FileAccess.Read); //define a BinaryReader obj to read data in FileStream as binary data BinaryReader br = new BinaryReader(fs); //define a bit array variable byte[] barry = br.ReadBytes((int)fs.Length); int eventId = int.Parse(textBox1.Text); string title = textBox2.Text; DateTime date = dateTimePicker1.Value; string cs = @"Data Source=CAPU\SQLEXPRESS; database = PSDB;Integrated Security=SSPI"; SqlConnection cn = new SqlConnection(cs); SqlCommand cmd = new SqlCommand(); cmd.Connection = cn; cmd.CommandType = CommandType.Text; cmd.CommandText = "insert into Events values(@eid, @title, @eventDate, @coverpic)"; cmd.Parameters.AddWithValue("@eid", eventId); cmd.Parameters.AddWithValue("@title", title); cmd.Parameters.AddWithValue("@eventDate", date); cmd.Parameters.AddWithValue("@coverpic", barry); cn.Open(); cmd.ExecuteNonQuery(); cn.Close(); if (MessageBox.Show("Event added successfully..\n Do you want to add another event", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { ClearValue(); } else { Application.Exit(); }

ADO.NET (saideep)

} private void ClearValue() { //clear all } } }

Retrieving IMG: (Connection Oriented Model)

private void buttonGet_Click(object sender, EventArgs e) { int eventId = int.Parse(textBox1.Text); string cs = @"Data Source=CAPU\SQLEXPRESS; database = PSDB;Integrated Security=SSPI"; SqlConnection cn = new SqlConnection(cs); SqlCommand cmd = new SqlCommand(); cmd.Connection = cn; cmd.CommandType = CommandType.Text; cmd.CommandText = "select * from Events where EventId=@eventId"; cmd.Parameters.AddWithValue("@eventId", eventId); if (cn.State == ConnectionState.Closed) cn.Open(); SqlDataReader dr = cmd.ExecuteReader(); if(dr.Read()) { textBox2.Text = dr["Title"].ToString(); dateTimePicker1.Value = (DateTime)dr["EventDateTime"]; //to hold the value of image we define a byte arry variable byte[] barray = new byte[80000]; dr.GetBytes(3, 0, barray, 0, 8000); //create an image from the byte array string fname = String.Format("Img_{0}.bmp", eventId); FileStream fs = new FileStream(fname, FileMode.OpenOrCreate, FileAccess.Write); BinaryWriter bw = new BinaryWriter(fs); bw.Write(barray);

ADO.NET (saideep)

bw.Flush(); bw.Close(); fs.Close(); pictureBox1.Image = Image.FromFile(fname); } }

____________________________________________________________________________________

Implementing 3-Tier Architecture:

> User Interface: presentation logic (top-most logic)

> Functional process logic: business rules. Makes logical decisions, evaluations n performs calcualtions. Moves n

processes data betw 2 layers.

> Data tier: Data storage and Data access.

____________________________________________________________________________________

ADO.NET (saideep)

Transaction Management: used for data integrity- used to manage the interrelated transactions very efficiently by

either committing the entire transactions or reverting all the transactions.

That is, it either saves all the transactions or cancels all the transactions, where a transaction can be considered as any

data manipulation operation, such as Insert, Update, or Delete.

Eg. transferring the amount from one account to the other account when the user clicks on the Transfer button, and this

to happen, two update operations have to be executed. One, to detect the amount from account one, and the other to

credit the amount for account two. Now let us assume that when the user clicks on the Transfer button, if the first

update statement has executed successfully, and while processing the second update statement, assume that there is an

exception raised. Then, the transaction is halfway done. That is, the amount has been detected from account one, but it

is not credited to the account two, which leads in losing the data integrating, whereas Transaction Management ensures

ADO.NET (saideep)

that both update statements are succeeded, or if any one of the update statements is a failure, then Transaction

Management makes sure that the other successful transactions to rollback,which maintains the data integrity.

____________________________________________________________________________________

Instead of writing the entire business logic within the application, we can take the support of a class library, which acts

like a middle tier, and provide the business logic within it, such that the application can consume the business logic

present within the class library for interacting with the database. Once we have done with that, then we shall register

the class library with the GAC and create a web application to consume the definition.

ADO.NET (saideep)

> DB

> Class library (.dll)

ADO.NET (saideep)

> Create Windows Form

Note: Whenever a class library has been built, by default it will be considered as a private assembly. And hence,

whenever an application consumes a private assembly, then a copy of the assembly will be created and will be

maintained within the application folder. If a number of applications uses the private assembly, then that many numbers

of duplicate copies will be created, and hence, if there is a requirement such that the class library definition has to be

consumed for more than one application, then instead of using a private assembly, we can use shared assembly.

ADO.NET (saideep)

Whenever an assembly is registered with a GAC, that is, Global Assembly Cache, then that assembly is set to be shared

assembly. In order to register an assembly definition with the GAC, then it is mandatory that the assembly should be

bound with the strong name key file, where strong name key file is used to provide a unique identifier called as public

key token, which will be used for identification of the assembly.

In order to register an assembly with the GAC, the commands to be used are gacutil-i Assembly name. Once the

assembly is registered with the GAC, then if that assembly is referenced by any number of applications, duplicate copies

of the assembly will not be generated.

- Open class library defn and nav to:

ADO.NET (saideep)

- Choose a strong name key file n build solution:

- Open Visual Studio Command Prompt (admin) n register the assembly with the GAC as a shared assembly:

ADO.NET (saideep)

By typing- gacutil - i assmeblyName.dll

> Consuming the Class library from ASP.NET Web Site:

Add ref and then:

There will not be any additional class library files added to the solution (bcoz of shared assembly)

____________________________________________________________________________________

> Data Concurrency: When multiple users attempt to modify data at the same time, controls need to be established in

order to prevent one user's modifications from harmfully affecting modifications from simultaneous users. The system

of handling what happens in this situation is called data concurrency control.

Data concurrency control is of three types, pessimistic concurrency control, optimistic concurrency control, last in wins.

ADO.NET (saideep)

Pessimistic concurrency control- a row will be unavailable to users from the time the record is fetched until it's updated

in the database

Optimistic concurrency control- a row will be unavailable to other users only while the data is actually being updated.

The update examines the row in the database and determines whether any changes have been made attempting to

update a record that has already been changed results in concurrency violation

Last in wins- a row will be unavailable to other users, only while the data is actually being updated. However, no effort is

made to compare updates against the original record. The record is simply written out, potentially overriding any

changes made by other users since you last refreshed the records.

Visual Studio can implement optimistic concurrency with dynamic SQL. These concurrency exceptions must be handled

according to business needs.

To do:

Add a Windows Form to our application. Add a typed DataSet, Project menu, Add New Item, and select Data tab, select DataSet. Let

us provide a meaningful name, ConcurrencyDS. Open the Server Explorer, establish a data connection to the server, expand the

tables at the data connection. Drag and drop a table to the Designer. Now, right-click on the data table and click on Configure. Click

on Advanced Options button and verify if the following checkboxes, that is, Generate Insert, Update, and Delete statements use

optimistic concurrency. Refresh the table data table are checked. Click on the Next button and click on Finish. Now let us add a

Windows Form. Open the data sources, drag and drop the table present at the DataSet to the form. Set the doc property of the

DataGridView control. Let us open Solution Explorer and start two instances of our application. Let us provide the values at the first

instance.

Now let us update the values of the same record in another instance. When we click on Save, we can observe an error has been

raised, because of the concurrency. Now let us try to handle the exception DbConcurrencyException, and once again, let me start

the two instances of the application. Let us perform the same operation again. Now let me click on Save. We don't find much

changes. Instead of crashing the application, we will get an alert.

ADO.NET (saideep)

____________________________________________________________________________________