mercredi 7 juin 2017

Manage transaction which span across multiple method

I have a method which call Web Api from it. Data get inserted into multiple tables, so added transaction. Below is layout of code.

{

    TransactionObject objTransaction = new TransactionObject(); 
    try
    {

    //Create Order
    order.insert(objTransaction);

    //Create Delivery
    address.insert(objTransaction);

    //Call Generic Web API method to calculate TAX.
    using (HttpClient client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:85766/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var response = client.PostAsJsonAsync("api/Tax/UpdateTax", order).Result;

            if (response.IsSuccessStatusCode)
            {    
                //Commit transactio     
                 objTransaction.EndTransaction(true);                                            
            }
            else
            {
                //Commit transactio 
                objTransaction.EndTransaction(false);   
            }

        }
    }
}
catch(Exception ex)
{
    //Commit transactio 
    objTransaction.EndTransaction(false);   
}

This method call a web api to do another database operation. Below Web Api is a generic method called form multiple places.

        [HttpPost]
        public HttpResponseMessage UpdateTax(Order order)
        {            
            TransactionObject objTransaction = new TransactionObject();            
            try
            {

                //DO calculation logic
                .
                .
                //Insert Invoice 
                invoice.insert(objTransaction);
                objTransaction.EndTransaction(true);
                return Request.CreateResponse(HttpStatusCode.Created, "Invoice data added successfully");
            }
            catch (Exception ex)
            {
                objTransaction.EndTransaction(false);
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Erorr while adding invoice");
            }

        }

Now if exception occur before Web API getting called , then all transaction will be rolled back. It is fine. Same for if exception occur in Web Api.

If exception will occur after Web API get executed successfully, while committing transaction in main method, how to handle it, I mean in below code

if (response.IsSuccessStatusCode)
   {    
     //Commit transactio        
      objTransaction.EndTransaction(true);                                            
   }

Is there any better approach to handle the logic?

Aucun commentaire:

Enregistrer un commentaire