How do you handle data concurrency in .NET ?

Answers were Sorted based on User's Feedback



How do you handle data concurrency in .NET ?..

Answer / ravikumar

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 adversely affecting
modifications from simultaneous users. The system of
handling what happens in this situation is called
concurrency control.

Types of Concurrency Control
In general, there are three common ways to manage
concurrency in a database:

Pessimistic concurrency control: A row is unavailable to
users from the time the record is fetched until it is
updated in the database.

Optimistic concurrency control: A row is 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 a
concurrency violation.

"Last in wins": A row is 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
overwriting any changes made by other users since you last
refreshed the records.

Pessimistic Concurrency
Pessimistic concurrency is typically used for two reasons.
First, in some situations there is high contention for the
same records. The cost of placing locks on the data is less
than the cost of rolling back changes when concurrency
conflicts occur.

Pessimistic concurrency is also useful for situations where
it is detrimental for the record to change during the
course of a transaction. A good example is an inventory
application. Consider a company representative checking
inventory for a potential customer. You typically want to
lock the record until an order is generated, which would
generally flag the item with a status of ordered and remove
it from available inventory. If no order is generated, the
lock would be released so that other users checking
inventory get an accurate count of available inventory.

However, pessimistic concurrency control is not possible in
a disconnected architecture. Connections are open only long
enough to read the data or to update it, so locks cannot be
sustained for long periods. Moreover, an application that
holds onto locks for long periods is not scalable.

Is This Answer Correct ?    12 Yes 0 No

How do you handle data concurrency in .NET ?..

Answer / sureshsamatham

ADO.NET and Visual Studio use optimistic concurrency,
because the data architecture is based on disconnected data.
Therefore, you need to add business logic to resolve issues
with optimistic concurrency.
(1.optimistic 2.pessimistic 3.Last in wins)
If you choose to use optimistic concurrency, there are two
general ways to determine if changes have occurred: the
version approach (true version numbers or date-time stamps)
and the saving-all-values approach.
The Version Number Approach
In the version number approach, the record to be updated
must have a column that contains a date-time stamp or
version number. The date-time stamp or a version number is
saved on the client when the record is read. This value is
then made part of the update.
One way to handle concurrency is to update only if value in
the WHERE clause matches the value on the record. The SQL
representation of this approach is:
Copy Code
UPDATE Table1 SET Column1 = @newvalue1, Column2 = @newvalue2
WHERE DateTimeStamp = @origDateTimeStamp
Alternatively, the comparison can be made using the version
number:
Copy Code
UPDATE Table1 SET Column1 = @newvalue1, Column2 = @newvalue2
WHERE RowVersion = @origRowVersionValue
If the date-time stamps or version numbers match, the record
in the data store has not changed and can be safely updated
with the new values from the dataset. An error is returned
if they don't match. You can write code to implement this
form of concurrency checking in Visual Studio. You will also
have to write code to respond to any update conflicts. To
keep the date-time stamp or version number accurate, you
need to set up a trigger on the table to update it when a
change to a row occurs.
The Saving-All-Values Approach
An alternative to using a date-time stamp or version number
is to get copies of all the fields when the record is read.
The DataSet object in ADO.NET maintains two versions of each
modified record: an original version (that was originally
read from the data source) and a modified version,
representing the user updates. When attempting to write the
record back to the data source, the original values in the
data row are compared against the record in the data source.
If they match, it means that the database record has not
changed since it was read. In that case, the changed values
from the dataset are successfully written to the database.
Each data adapter command has a parameters collection for
each of its four commands (DELETE, INSERT, SELECT, and
UPDATE). Each command has parameters for both the original
values, as well as the current (or modified) values.
Note: use time stamps to avoid concurrency violations

Is This Answer Correct ?    6 Yes 0 No

How do you handle data concurrency in .NET ?..

Answer / jigar

The answer given above is not answer of the question.
Please provide the correct answers.

Is This Answer Correct ?    6 Yes 1 No

How do you handle data concurrency in .NET ?..

Answer / debasish

concuracy is handled by the help of timestamp..
or checking the original data onece again before edit or
delete.

Is This Answer Correct ?    6 Yes 1 No

How do you handle data concurrency in .NET ?..

Answer / suresh

Pessimistic locking, last-win-approach and optimistic
locking

Is This Answer Correct ?    4 Yes 0 No

How do you handle data concurrency in .NET ?..

Answer / narasimhareddy

1)consuraancy can be done with the help of dataset
methods like acceptchanges().
2)using timestamp

Is This Answer Correct ?    4 Yes 1 No

How do you handle data concurrency in .NET ?..

Answer / 1647264

One of the key features of the ADO.NET DataSet is that it can be a self-contained and disconnected data store. It can contain the schema and data from several rowsets in DataTable objects as well as information about how to relate the DataTable objects-all in memory. The DataSet neither knows nor cares where the data came from, nor does it need a link to an underlying data source. Because it is data source agnostic you can pass the DataSet around networks or even serialize it to XML and pass it across the Internet without losing any of its features. However, in a disconnected model, concurrency obviously becomes a much bigger problem than it is in a connected model.

In this column, I'll explore how ADO.NET is equipped to detect and handle concurrency violations. I'll begin by discussing scenarios in which concurrency violations can occur using the ADO.NET disconnected model. Then I will walk through an ASP.NET application that handles concurrency violations by giving the user the choice to overwrite the changes or to refresh the out-of-sync data and begin editing again. Because part of managing an optimistic concurrency model can involve keeping a timestamp (rowversion) or another type of flag that indicates when a row was last updated, I will show how to implement this type of flag and how to maintain its value after each database update.

Is Your Glass Half Full

There are three common techniques for managing what happens when users try to modify the same data at the same time: pessimistic, optimistic, and last-in wins. They each handle concurrency issues differently.

The pessimistic approach says: "Nobody can cause a concurrency violation with my data if I do not let them get at the data while I have it." This tactic prevents concurrency in the first place but it limits scalability because it prevents all concurrent access. Pessimistic concurrency generally locks a row from the time it is retrieved until the time updates are flushed to the database. Since this requires a connection to remain open during the entire process, pessimistic concurrency cannot successfully be implemented in a disconnected model like the ADO.NET DataSet, which opens a connection only long enough to populate the DataSet then releases and closes, so a database lock cannot be held.

Another technique for dealing with concurrency is the last-in wins approach. This model is pretty straightforward and easy to implement-whatever data modification was made last is what gets written to the database. To implement this technique you only need to put the primary key fields of the row in the UPDATE statement's WHERE clause. No matter what is changed, the UPDATE statement will overwrite the changes with its own changes since all it is looking for is the row that matches the primary key values. Unlike the pessimistic model, the last-in wins approach allows users to read the data while it is being edited on screen. However, problems can occur when users try to modify the same data at the same time because users can overwrite each other's changes without being notified of the collision. The last-in wins approach does not detect or notify the user of violations because it does not care. However the optimistic technique does detect violations. Contd....

Is This Answer Correct ?    0 Yes 0 No

How do you handle data concurrency in .NET ?..

Answer / 1647264

One of the key features of the ADO.NET DataSet is that it can be a self-contained and disconnected data store. It can contain the schema and data from several rowsets in DataTable objects as well as information about how to relate the DataTable objects-all in memory. The DataSet neither knows nor cares where the data came from, nor does it need a link to an underlying data source. Because it is data source agnostic you can pass the DataSet around networks or even serialize it to XML and pass it across the Internet without losing any of its features. However, in a disconnected model, concurrency obviously becomes a much bigger problem than it is in a connected model.

In this column, I'll explore how ADO.NET is equipped to detect and handle concurrency violations. I'll begin by discussing scenarios in which concurrency violations can occur using the ADO.NET disconnected model. Then I will walk through an ASP.NET application that handles concurrency violations by giving the user the choice to overwrite the changes or to refresh the out-of-sync data and begin editing again. Because part of managing an optimistic concurrency model can involve keeping a timestamp (rowversion) or another type of flag that indicates when a row was last updated, I will show how to implement this type of flag and how to maintain its value after each database update.

Is Your Glass Half Full

There are three common techniques for managing what happens when users try to modify the same data at the same time: pessimistic, optimistic, and last-in wins. They each handle concurrency issues differently.

The pessimistic approach says: "Nobody can cause a concurrency violation with my data if I do not let them get at the data while I have it." This tactic prevents concurrency in the first place but it limits scalability because it prevents all concurrent access. Pessimistic concurrency generally locks a row from the time it is retrieved until the time updates are flushed to the database. Since this requires a connection to remain open during the entire process, pessimistic concurrency cannot successfully be implemented in a disconnected model like the ADO.NET DataSet, which opens a connection only long enough to populate the DataSet then releases and closes, so a database lock cannot be held.

Another technique for dealing with concurrency is the last-in wins approach. This model is pretty straightforward and easy to implement-whatever data modification was made last is what gets written to the database. To implement this technique you only need to put the primary key fields of the row in the UPDATE statement's WHERE clause. No matter what is changed, the UPDATE statement will overwrite the changes with its own changes since all it is looking for is the row that matches the primary key values. Unlike the pessimistic model, the last-in wins approach allows users to read the data while it is being edited on screen. However, problems can occur when users try to modify the same data at the same time because users can overwrite each other's changes without being notified of the collision. The last-in wins approach does not detect or notify the user of violations because it does not care. However the optimistic technique does detect violations. Contd....

Saving Changes

Now that the Employees table has the tracking field (LastUpdateDateTime) and the stored procedure has been created to use both the primary key and the tracking field in the WHERE clause of the UPDATE statement, let's take a look at the role of ADO.NET. In order to trap the event when the user changes the values in the textboxes, I created an event handler for the TextChanged event for each TextBox control:

private void txtLastName_TextChanged(object sender, System.EventArgs e)

{

// Get the employee DataRow (there is only 1 row, otherwise I could

// do a Find)

dsEmployee.EmployeeRow oEmpRow =

(dsEmployee.EmployeeRow)oDsEmployee.Employee.Rows[0];

oEmpRow.LastName = txtLastName.Text;

// Save changes back to Session

Session["oDsEmployee"] = oDsEmployee;

}

This event retrieves the row and sets the appropriate field's value from the TextBox. (Another way of getting the changed values is to grab them when the user clicks the Save button.) Each TextChanged event executes after the Page_Load event fires on a postback, so assuming the user changed the first and last names, when the user clicks the Save button, the events could fire in this order: Page_Load, txtFirstName_TextChanged, txtLastName_TextChanged, and btnSave_Click.

The Page_Load event grabs the row from the DataSet in the Session object; the TextChanged events update the DataRow with the new values; and the btnSave_Click event attempts to save the record to the database. The btnSave_Click event calls the SaveEmployee method (shown in Figure 3) and passes it a bLastInWins value of false since we want to attempt a standard save first. If the SaveEmployee method detects that changes were made to the row (using the HasChanges method on the DataSet, or alternatively using the RowState property on the row), it creates an instance of the Employee class and passes the DataSet to its SaveEmployee method. The Employee class could live in a logical or physical middle tier. (I wanted to make this a separate class so it would be easy to pull the code out and separate it from the presentation logic.)

Notice that I did not use the GetChanges method to pull out only the modified rows and pass them to the Employee object's Save method. I skipped this step here since there is only one row. However, if there were multiple rows in the DataSet's DataTable, it would be better to use the GetChanges method to create a DataSet that contains only the modified rows.

If the save succeeds, the Employee.SaveEmployee method returns a DataSet containing the modified row and its newly updated row version flag (in this case, the LastUpdateDateTime field's value). This DataSet is then merged into the original DataSet so that the LastUpdateDateTime field's value can be updated in the original DataSet. This must be done because if the user wants to make more changes she will need the current values from the database merged back into the local DataSet and shown on screen. This includes the LastUpdateDateTime value which is used in the WHERE clause. Without this field's current value, a false concurrency violation would occur.

Reporting Violations

If a concurrency violation occurs, it will bubble up and be caught by the exception handler shown in Figure 3 in the catch block for DBConcurrencyException. This block calls the FillConcurrencyValues method, which displays both the original values in the DataSet that were attempted to be saved to the database and the values currently in the database. This method is used merely to show the user why the violation occurred. Notice that the exDBC variable is passed to the FillConcurrencyValues method. This instance of the special database concurrency exception class (DBConcurrencyException) contains the row where the violation occurred. When a concurrency violation occurs, the screen is updated to look like Figure 1.

The DataSet not only stores the schema and the current data, it also tracks changes that have been made to its data. It knows which rows and columns have been modified and it keeps track of the before and after versions of these values. When accessing a column's value via the DataRow's indexer, in addition to the column index you can also specify a value using the DataRowVersion enumerator. For example, after a user changes the value of the last name of an employee, the following lines of C# code will retrieve the original and current values stored in the LastName column:

string sLastName_Before = oEmpRow["LastName", DataRowVersion.Original];

string sLastName_After = oEmpRow["LastName", DataRowVersion.Current];

The FillConcurrencyValues method uses the row from the DBConcurrencyException and gets a fresh copy of the same row from the database. It then displays the values using the DataRowVersion enumerators to show the original value of the row before the update and the value in the database alongside the current values in the textboxes.

User's Choice

Once the user has been notified of the concurrency issue, you could leave it up to her to decide how to handle it. Another alternative is to code a specific way to deal with concurrency, such as always handling the exception to let the user know (but refreshing the data from the database). In this sample application I let the user decide what to do next. She can either cancel changes, cancel and reload from the database, save changes, or save anyway.

The option to cancel changes simply calls the RejectChanges method of the DataSet and rebinds the DataSet to the controls in the ASP.NET page. The RejectChanges method reverts the changes that the user made back to its original state by setting all of the current field values to the original field values. The option to cancel changes and reload the data from the database also rejects the changes but additionally goes back to the database via the Employee class in order to get a fresh copy of the data before rebinding to the control on the ASP.NET page.

The option to save changes attempts to save the changes but will fail if a concurrency violation is encountered. Finally, I included a "save anyway" option. This option takes the values the user attempted to save and uses the last-in wins technique, overwriting whatever is in the database. It does this by calling a different command object associated with a stored procedure that only uses the primary key field (EmployeeID) in the WHERE clause of the UPDATE statement. This technique should be used with caution as it will overwrite the record.

If you want a more automatic way of dealing with the changes, you could get a fresh copy from the database. Then overwrite just the fields that the current user modified, such as the Extension field. That way, in the example I used the proper LastName would not be overwritten. Use this with caution as well, however, because if the same field was modified by both users, you may want to just back out or ask the user what to do next. What is obvious here is that there are several ways to deal with concurrency violations, each of which must be carefully weighed before you decide on the one you will use in your application.

Wrapping It Up

Setting the SqlDataAdapter's ContinueUpdateOnError property tells the SqlDataAdapter to either throw an exception when a concurrency violation occurs or to skip the row that caused the violation and to continue with the remaining updates. By setting this property to false (its default value), it will throw an exception when it encounters a concurrency violation. This technique is ideal when only saving a single row or when you are attempting to save multiple rows and want them all to commit or all to fail.

I have split the topic of concurrency violation management into two parts. Next time I will focus on what to do when multiple rows could cause concurrency violations. I will also discuss how the DataViewRowState enumerators can be used to show what changes have been made to a DataSet.

Is This Answer Correct ?    0 Yes 0 No

How do you handle data concurrency in .NET ?..

Answer / swapna

One of the key features of the ADO.NET DataSet is that it
can be a self-contained and disconnected data store. It can
contain the schema and data from several rowsets in
DataTable objects as well as information about how to
relate the DataTable objects-all in memory.

The DataSet neither knows nor cares where the data came
from, nor does it need a link to an underlying data source.
Because it is data source agnostic you can pass the DataSet
around networks or even serialize it to XML and pass it
across the Internet without losing any of its features.
However, in a disconnected model, concurrency obviously
becomes a much bigger problem than it is in a connected
model.

Is This Answer Correct ?    1 Yes 7 No

Post New Answer

More ADO.NET Interview Questions

i making a project using windows application c#, i want to show user name, password, and one button login. i wanna make it with sealed class .how its possible . when i clicked my login button all project should be open. pls cleare me.

1 Answers  


What does executequery return?

0 Answers  


How to pass values into a datatable?

0 Answers  


Which property is used to check whether a DataReader is closed or opened?

0 Answers  


What are the drawbacks of using ado.net?

0 Answers  






Does executenonquery return a value?

0 Answers  


Which object holds only data and does not interact with data source?

0 Answers  


What is ado rdo dao in visual basic?

0 Answers  


What is executenonquery ado.net?

0 Answers  


What are major difference between classic ADO and ADO.NET?

2 Answers  


How is entity framework different from ado.net?

0 Answers  


What are the advantages using ado.net?

0 Answers  


Categories