asp tutorials, asp.net tutorials, sample code, and Microsoft news from 15Seconds
Data Access  |   Troubleshooting  |   Security  |   Performance  |   ADSI  |   Upload  |   Email  |   Control Building  |   Component Building  |   Forms  |   XML  |   Web Services  |   ASP.NET  |   .NET Features  |   .NET 2.0  |   App Development  |   App Architecture  |   IIS  |   Wireless
 
Pioneering Active Server
 Power Search








Active News
15 Seconds Weekly Newsletter
• Complete Coverage
• Site Updates
• Upcoming Features

More Free Newsletters
Reference
News
Articles
Archive
Writers
Code Samples
Components
Tools
FAQ
Feedback
Books
Links
DL Archives
Community
Messageboard
List Servers
Mailing List
WebHosts
Consultants
Tech Jobs
15 Seconds
Home
Site Map
Press
Legal
Privacy Policy
internet.commerce














internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

HardwareCentral
Compare products, prices, and stores at Hardware Central!

Handling Optimistic Concurrency Issues in ASP
By Waqar A. Cheema
Rating: 4 out of 5
Rate this article


  • email this article to a colleague
  • suggest an article

  • download source code
  • With optimistic locking becoming the first choice when implementing web applications, handling concurrency violations is becoming more and more important. This is due to the fact the when we use optimistic locking we are not maintaining a lock on the record at the DB or application level. Therefore, we either need to develop our own custom logic or depend on the functionality offered by ADO to avoid creating inconsistencies in our data.

    While it's true that ADO has the ability to detect that a record has changed since it was last read and raise an exception, in the case of classic ASP based web applications, we can't rely on ADO. This is due to the fact that in order to achieve performance and scalability, the state of ADO objects is almost never maintained in a web application. For each read request, we create the ADO objects, get the data we need, and then immediately destroy those objects. Similarly for write requests, we create ADO objects, build a query or recordset, and update/execute against the data source. When used in this manner, ADO has no way of knowing whether we are writing over someone else's writes or not.

    There are several approaches to handle concurrency violations. I will be covering two of them in this article: Record Time Stamping and Blocking Multiple Logins.

    Record Time Stamping

    This solution is applicable in the context where you want to avoid optimistic concurrency violations between multiple users. The idea is to introduce an extra column in each data entry table of the type "Time Stamp" which is updated with each record write. This column value is read by the record read requests and accompanies the save requests. The save request is only allowed if it's time stamp matches that of the record in the database - implying that no one else has updated the data since it was read. Otherwise, the save is disallowed and an exception is raised. The complete solution could look something like this:

    1. Add a Time Stamp type column in data entry tables
    2. Introduce logic to update Time Stamps on each record update. SQL Server offers a built-in datatype named TimeStamp specifically for this purpose and updates it automatically on each record modification.
    3. Read the Time Stamp values with all record reads for editing and persist it to be used by subsequent save requests. The time stamps can be persisted by including a hidden field on the data entry form offered to the user or maintained in session state.
    4. Save requests shall include the time stamp value (received by their read request).
    5. If the save request time stamp matches the time stamp of record in database, we allow the update otherwise we deny it and raise an exception like: "The record you are trying to modify has already been updated by someone else".

    Implementation of this type of time stamping system is relatively simple and straightforward and yet very effective.

    Block Multiple Logins by the Same User

    This solution is applicable in the context where the application itself is logging and maintaining data of currently logged in users and multiple instances of the same user having seperate sessions with the application may cause problems. Record time stamping may be used, but in many case for a single user, blocking multiple logins makes more sense. An example of such an application would be an online assessment system which allows learners to take online assessments set up by their training supervisors. Here multiple instances of same user taking the same assessment at the same time will create serious concurrency problems.

    Blocking multiple logins may seem a very simple problem at surface, but it is not. You may set a bit in the database or maintain a collection of currently logged in users in an Application variable and compare each login request against the DB bits or values in application variable. This works as long as user uses your logout button or link to logout from application (on which you reset the bit or remove the username from application variable), but what if the user's session expires, browser window crashes, machine reboots, or internet connection drops. In these cases, the user's account will be locked indefinately until unlocked by an admin. This is not a very elegant solution, but unfortunately many implementations are set up this way.

    The challenge here is that we can not possibly add handlers for each and every possible way a user's session can end. It is the same problem that must be faced by a web server: how to detect that a user is no longer using an application in order to terminate his/her session to free up resources? The answer is simple, the web server does not need to worry about the multitude of scenerios in which a user exits - it simply maintains a session timeout counter, which runs from 0 to the Session.Timeout value set for the application. This counter restarts from 0 on each page load by the user, allowing him/her another Session.Timeout time. If this counter completes (i.e. Session.Timeout time elapses since user accessed any page in the application), it implies that user has finished interacting, and web server can safely terminate the session.

    We can develop our own logic based on the same principle used by a webserver to detect session completion. We can detect the expiration / completion of a session with the use of the same Session.Timeout property. What we need to do is to maintain in the database the last access datetime per user. Now for each login request, we just need to perform the following check:

    Pseudo Code

    LoginValidate() Function
    {
    If (Current DateTime - User's Last Access DateTime in DB) > Session.Timeout
        allow login;
    Else
        disallow login;
    }
    

    Now even if the user's session expires by close of a browser, expiration of session, machine crash, or internet disconnect, his account locks only until the session expiration time elapses. After that, the subsequent request to login will succeed. If you implement blocking multiple logins in this manner, you will no longer have to worry about user accounts getting locked indefinitely – the lock will last only until the session expires or the users logs out.

    What do you need to do in terms of implementation to develop this functionality? There are 4 main requirements:

    1. A datastructure to maintain Last Access DateTime value for each user
    2. Mechanism to determine whether to allow a login request or not on the basis of comparison between difference of Current DateTime and Last Access DateTime with Session Timeout
    3. Mechanism to update Last Access DateTime value for currently logged in users on each page load
    4. Mechanism to reset Last Access DateTime value on logout to allow subsequent login for same user

    There is a complete working sample implementation of this block multiple login functionality available for download at the end of the article. Refer to the readme.txt file included in the zip file for steps to setup the sample on your machine.

    In the sample implementation I am using a table named UserSession to maintain the Last Access Date Time for each user which satisfys the first requirement listed above.

    In order to determine whether or not to allow a login request, I am using a stored procedure named GetSession which is called from Login ASP page (default.asp). It takes two input parameters (@username and @session_timeout) and returns one output parameter (@allowlogin) that contains either 0 or 1. This return value is used by the ASP script to determine whether to allow a login or not.

    I am using another stored procedure named UserSessionRefresh in order to update the Last Access DateTime value. In order to do this, the stored procedure needs to be called on each page load. The sample has only one page (home.asp) so the call to this procedure is on this page, and a link is provided to reload the page which also refreshes the session.

    For the final requirement of resetting the Last Access DateTime value on logout, I am using a stored procedure named UserSessionClear which is called from my logout page. A link is provided on home.asp for logout that redirects you to logout.asp. Additionally if your session expires, and you try to reload the home.asp page it will automatically redirect you to logout.asp which in turn will clear your session in db, call Session.Abandon and then redirect back to login screen.

    All the common functions called from the individual asp pages can be found in the includes\commmon_function.asp file also included in the download zip file.

    Download the Code

    The sample code that accomanies this article is available for download in a zip file from here. Please refer to the readme.txt file included in the zip file for the steps required to setup the sample on your machine.

    About the Author

    Waqar A Cheema has been involved in architecting and developing web applications based on Microsoft Technologies for over five years. He is currently working as Software Architect at Knowledge Plaform Pvt Ltd. He can be reached at waqarcheema@gmail.com.

  • Rate This Article
    Not HelpfulMost Helpful
    1 2 3 4 5
    Supporting Products/Tools
    Proposion N2N
    Proposion N2N connects Microsoft .NET applications to Lotus Notes and Lotus Domino databases. This ADO.NET managed data provider allows you to perform blindingly fast queries and updates of Notes data from ASP.NET pages, .NET web services, Windows, or Mobile applications. An innovative SQL-like query language leverages the unique features of Notes and makes collaborative software accessible to relational database programmers.
    [Top]
    Other Articles
    Sep 15, 2005 - Building an Image Keyword System
    Unlike text-based file formats image files aren't made up of words, which makes searching for an image file by keyword difficult. Instead of being able to simply open the file to see what it contains, we're stuck looking at the text around it and other metadata to determine the image's meaning. In this article, Ziran Sun shows you how to build a simple database-based image keyword system that allows you to associate keywords with images and use these keywords to make finding images easier.
    [Read This Article]  [Top]
    Apr 7, 2005 - A Step-by-Step Guide To Using MySQL with ASP.NET - Part 2
    In the second part of of his article on using MySQL with ASP.NET, Ziran Sun covers how to add a new MySQL user to the database server, assign the user the appropriate permissions, connect to the database, and build a simple ASP.NET page to perform a query.
    [Read This Article]  [Top]
    Feb 10, 2005 - A Step-by-Step Guide To Using MySQL with ASP.NET - Part 1
    Back in the days of classic ASP, if you were building a database-driven web site, your choice was either to invest a lot of money to get a copy of Microsoft SQL Server (or some other enterprise-ready database) or invest a lot of time finding a way to deal with the performance and scalability limitations of Microsoft Access. Luckily these days there's another viable alternative: MySQL.
    [Read This Article]  [Top]
    Jan 27, 2005 - Moving a Database from SQL Server 7.0 to SQL Server 2000
    Moving or copying a SQL Server database from one machine to another requires a lot of preparation in order to ensure a smooth transfer. In this article, Dina Fleet Berry examines the different methods and highlights the different issues associated with each of them.
    [Read This Article]  [Top]
    Jan 6, 2005 - Debugging a SQL Stored Procedure from inside SQL Server 2000 Query Analyzer
    There are many times when using SQL Server 2000 Query Analyzer to debug SQL statements is a better choice than debugging in Visual Studio .NET. In this article, Dina Fleet Berry explains why and walks you through the debugging process step-by step.
    [Read This Article]  [Top]
    Nov 24, 2004 - Persisting .NET Objects to SQL Server Using SQLXML and Serialization
    As a follow up to his article on retrieving objects from SQL Server using SQLXML and serialization, Gianluca Nuzzo discusses saving objects back to SQL Server using a schema definition file and updategrams.
    [Read This Article]  [Top]
    Sep 14, 2004 - Transaction Processing in ADO.NET 2.0
    One area that stands out when comparing ADO.NET 1.x to ADO.NET 2.0 is transaction processing. Bill Ryan shows just how easy transaction processing has become with the TransactionScope object in ADO.NET 2.0.
    [Read This Article]  [Top]
    Sep 8, 2004 - Custom Object Data Binding with .NET
    Developers often use brute force coding to marshal data between the GUI and application objects. In this article, Luther Stanton explains how to use .NET's out-of-the box data-binding functionality to make this job much easier.
    [Read This Article]  [Top]
    Sep 2, 2004 - Queue MSMQ Messages from SQL Server
    Learn how to create a console application to queue a message in Microsoft Message Queuing (MSMQ) and then use an extended stored procedure to call the console application from a SQL Server trigger.
    [Read This Article]  [Top]
    Aug 30, 2004 - Tuning Up ADO.NET Connection Pooling in ASP.NET Applications
    Connection pooling increases the performance of Web applications by reusing active database connections instead of creating a new connection with every request. This article shows how to monitor the connection pool, diagnose a potential problem, and apply the appropriate fix.
    [Read This Article]  [Top]
    Mailing List
    Want to receive email when the next article is published? Just Click Here to sign up.

    Support the Active Server Industry



    JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

    Solutions
    Whitepapers and eBooks
    Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
    Avaya Article: How to Feed Data into the Avaya Event Processor
    Microsoft Article: Install What You Need with Win Server ‘08
    HP eBook: Putting the Green into IT
    Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
    Avaya Article: Setting Up a SIP A/S Development Environment
    IBM Article: How Cool Is Your Data Center?
    Microsoft Article: Managing Virtual Machines with Microsoft System Center
    HP eBook: Storage Networking , Part 1
    Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
    MORE WHITEPAPERS, EBOOKS, AND ARTICLES
    Webcasts
    Intel Video: Are Multi-core Processors Here to Stay?
    On-Demand Webcast: Five Virtualization Trends to Watch
    HP Video: Page Cost Calculator
    Intel Video: APIs for Parallel Programming
    HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
    Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
    MORE WEBCASTS, PODCASTS, AND VIDEOS
    Downloads and eKits
    Sun Download: Solaris 8 Migration Assistant
    Sybase Download: SQL Anywhere Developer Edition
    Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
    Red Gate Download: SQL Compare Pro 6
    Iron Speed Designer Application Generator
    MORE DOWNLOADS, EKITS, AND FREE TRIALS
    Tutorials and Demos
    How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
    eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
    IBM Article: Collaborating in the High-Performance Workplace
    HP Demo: StorageWorks EVA4400
    Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
    Microsoft How-to Article: Get Going with Silverlight and Windows Live
    MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES