I am trying to develop an application of inventory management, and for the moment I am trying to do a proof of concept of adding/removing items with transactions. The site will be hosted on Windows Azure so I have to use SqlTransation to perform transactions (no DTC).
Here is my POC library code :
public static void AddQuantityByProductId(int argProductId, int argQuantity)
{
UpdateQuantity(argProductId, argQuantity);
}
public static void ReduceQuantityByProductId(int argProductId, int argQuantity)
{
UpdateQuantity(argProductId, argQuantity * -1);
}
private static void UpdateQuantity(int argProductId, int argQuantity)
{
string conn = ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString;
using (SqlConnection connection = new SqlConnection(conn))
{
connection.Open();
using (SqlTransaction transaction =
connection.BeginTransaction(IsolationLevel.Serializable))
{
SqlCommand command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandTimeout = 30;
command.CommandText = "select [Quantity] from StockItems where [Id] = '" + argProductId + "'";
int quantity = (int)command.ExecuteScalar();
int newQuantity = quantity + argQuantity;
command.CommandText = "UPDATE StockItems SET [Quantity] = " + newQuantity + " WHERE [Id] = '" + argProductId + "'";
command.ExecuteNonQuery();
transaction.Commit();
}
}
}
The code that i use to test the system :
static void Main(string[] args)
{
int productId = 6; //hard coded Id , because the line already exists
for (int i = 0; i < 10; i++)
{
Parallel.For(0, 10, (j) =>
{
StockItemDal.AddQuantityByProductId(productId, 10);
StockItemDal.ReduceQuantityByProductId(productId, 10);
});
}
}
The exception :
Can you please help me to locate the problem ?