1

I have a large application based on Dynamics CRM 2011 that in various places has code that must query for a record based upon some criteria and create it if it doesn't exist else update it.

An example of the kind of thing I am talking about would be similar to this:

stk_balance record = context.stk_balanceSet.FirstOrDefault(x => x.stk_key == id);
if(record == null)
{    
    record = new stk_balance();
    record.Id = Guid.NewGuid();
    record.stk_value = 100;

    context.AddObject(record);
}
else
{
    record.stk_value += 100;

    context.UpdateObject(record);
}

context.SaveChanges();

In terms of CRM 2011 implementation (although not strictly relevant to this question) the code could be triggered from synchronous or asynchronous plugins. The issue is that the code is not thread safe, between checking if the record exists and creating it if it doesn't, another thread could come in and do the same thing first resulting in duplicate records.

Normal locking methods are not reliable due to the architecture of the system, various services using multiple threads could all be using the same code, and these multiple services are also load balanced across multiple machines.

In trying to find a solution to this problem that doesn't add massive amounts of extra complexity and doesn't compromise the idea of not having a single point of failure or a single point where a bottleneck could occur I came across the idea of using SQL Server application locks.

I came up with the following class:

public class SQLLock : IDisposable
{
    //Lock constants
    private const string _lockMode = "Exclusive";
    private const string _lockOwner = "Transaction";
    private const string _lockDbPrincipal = "public";

    //Variable for storing the connection passed to the constructor 
    private SqlConnection _connection;

    //Variable for storing the name of the Application Lock created in SQL
    private string _lockName;

    //Variable for storing the timeout value of the lock
    private int _lockTimeout;

    //Variable for storing the SQL Transaction containing the lock
    private SqlTransaction _transaction;

    //Variable for storing if the lock was created ok
    private bool _lockCreated = false;

    public SQLLock (string lockName, int lockTimeout = 180000)
    {
        _connection = Connection.GetMasterDbConnection();
        _lockName = lockName; 
        _lockTimeout = lockTimeout;

        //Create the Application Lock
        CreateLock();
    }

    public void Dispose()
    {
        //Release the Application Lock if it was created
        if (_lockCreated)
        {
            ReleaseLock();
        }

        _connection.Close();
        _connection.Dispose();
    }

    private void CreateLock()
    {
        _transaction = _connection.BeginTransaction();

        using (SqlCommand createCmd = _connection.CreateCommand())
        {
            createCmd.Transaction = _transaction;
            createCmd.CommandType = System.Data.CommandType.Text;

            StringBuilder sbCreateCommand = new StringBuilder();
            sbCreateCommand.AppendLine("DECLARE @res INT");
            sbCreateCommand.AppendLine("EXEC @res = sp_getapplock");
            sbCreateCommand.Append("@Resource = '").Append(_lockName).AppendLine("',");
            sbCreateCommand.Append("@LockMode = '").Append(_lockMode).AppendLine("',");
            sbCreateCommand.Append("@LockOwner = '").Append(_lockOwner).AppendLine("',");
            sbCreateCommand.Append("@LockTimeout = ").Append(_lockTimeout).AppendLine(",");
            sbCreateCommand.Append("@DbPrincipal = '").Append(_lockDbPrincipal).AppendLine("'");
            sbCreateCommand.AppendLine("IF @res NOT IN (0, 1)");
            sbCreateCommand.AppendLine("BEGIN");
            sbCreateCommand.AppendLine("RAISERROR ( 'Unable to acquire Lock', 16, 1 )");
            sbCreateCommand.AppendLine("END");

            createCmd.CommandText = sbCreateCommand.ToString();

            try
            {
                createCmd.ExecuteNonQuery();
                _lockCreated = true;
            }
            catch (Exception ex)
            {
                _transaction.Rollback();
                throw new Exception(string.Format("Unable to get SQL Application Lock on '{0}'", _lockName), ex);
            }
        }
    }

    private void ReleaseLock()
    {
        using (SqlCommand releaseCmd = _connection.CreateCommand())
        {
            releaseCmd.Transaction = _transaction;
            releaseCmd.CommandType = System.Data.CommandType.StoredProcedure;
            releaseCmd.CommandText = "sp_releaseapplock";

            releaseCmd.Parameters.AddWithValue("@Resource", _lockName);
            releaseCmd.Parameters.AddWithValue("@LockOwner", _lockOwner);
            releaseCmd.Parameters.AddWithValue("@DbPrincipal", _lockDbPrincipal);

            try
            {
                releaseCmd.ExecuteNonQuery();
            }
            catch {}
        } 

        _transaction.Commit();
    }
}

I would use this in my code to create a SQL Server application lock using the unique key I am querying for as the lock name like this

using (var sqlLock = new SQLLock(id))
{
    //Code to check for and create or update record here
}

Now this approach seems to work, however I am by no means any kind of SQL Server expert and am wary about putting this anywhere near production code.

My question really has 3 parts

1. Is this a really bad idea because of something I haven't considered?

Are SQL Server application locks completely unsuitable for this purpose?

Is there a maximum number of application locks (with different names) you can have at a time?

Are there performance considerations if a potentially large number of locks are created? What else could be an issue with the general approach?

2. Is the solution actually implemented above any good?

If SQL Server application locks are usable like this, have I actually used them properly?

Is there a better way of using SQL Server to achieve the same result?

In the code above I am getting a connection to the Master database and creating the locks in there. Does that potentially cause other issues? Should I create the locks in a different database?

3. Is there a completely alternative approach that could be used that doesn't use SQL Server application locks?

I can't use stored procedures to create and update the record (unsupported in CRM 2011).

I don't want to add a single point of failure.

1 Answer 1

2

You can do this much easier.

//make sure your plugin runs within a transaction, this is the case for stage 20 and 40
//you can check this with IExecutionContext.IsInTransaction
//works not with offline plugins but works within CRM Online (Cloud) and its fully supported
//also works on transaction rollback

var lockUpdateEntity = new dummy_lock_entity(); //simple technical entity with as many rows as different lock barriers you need
lockUpdateEntity.Id = Guid.parse("well known guid"); //well known guid for this barrier
lockUpdateEntity.dummy_field=Guid.NewGuid(); //just update/change a field to create a lock, no matter of its content

//--------------- this is untested by me, i use the next one
context.UpdateObject(lockUpdateEntity);
context.SaveChanges(); 
//---------------

//OR

//--------------- i use this one, but you need a reference to your OrganizationService
OrganizationService.Update(lockUpdateEntity);
//---------------

//threads wait here if they have no lock for dummy_lock_entity with "well known guid"

stk_balance record = context.stk_balanceSet.FirstOrDefault(x => x.stk_key == id);
if(record == null)
{    
    record = new stk_balance();
    //record.Id = Guid.NewGuid(); //not needed
    record.stk_value = 100;

    context.AddObject(record);
}
else
{
    record.stk_value += 100;

    context.UpdateObject(record);
}

context.SaveChanges(); 

//let the pipeline flow and the transaction complete ...

For more background info refer to http://www.crmsoftwareblog.com/2012/01/implementing-robust-microsoft-dynamics-crm-2011-auto-numbering-using-transactions/

2
  • Thanks for the reply, we actually use that method in other parts of our code. Your code is much better explained and commented than other places I have seen it! Unfortunately we can't use that in the specific area of our product as the code can be called from outside of plugins as well. It would take a great deal of re-architecture to enable it to be trigger by creating a record in a dummy entity and passing the parameters into it that I need would be problemativ May 9, 2014 at 16:21
  • So when you update the dummy_lock_entity, can no other thread update the same entity until your transaction (i.e. plugin) has completed?
    – Daryl
    Jul 17, 2014 at 13:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.