Monday, May 18, 2009
web: Detecting Concurrency Violation in aspnet
Being a stateless protocol, it is very hard to detect concurrency violation and alert users in a web application. I was burned couple of times by 2 or more users simultaneously updating the same data and over writing the first update. I was able to solve this problem with an aspnet custom control and some back end logic to detect and show the user if somebody else updated the data after you fetched the data from the database.
[This is written in Sql Server, but can easily ported to any database]
1. Create a table to hold a reference number
2. SPROC to create the reference record anytime a row is updated in a relevant table. You can use a trigger or call this sproc from the business layer in applications.
3. Function to check if the reference number is still valid.
4. Create aspnet custom control to render a div if we detect a concurrency violation.
5. A non-intrusive pop up layer to alert the user that the data is out of scope when we detect a concurrency violation.
6. Create a derived class from System.Web.Page to expose CreateConcurrency, TrackConcurrency and HandleConcurrency methods. TrackConcurrency retrieves the last reference number for the relevant data object name and stores it in the viewstate. HandleConcurrency method takes this reference number and checks the database for any updates to this data object. If an update is detected, throw an error.
If you just want to detect the concurrency violation in business layer or sproc and don't bother to display a visual alert, you can do that by adding a timestamp column to the table and compare the timestamp value with what is passed from the view page and then throw an exception from the business layer or sproc.
download Framework, Sql, aspx and code behind files
That is it.
--paul