public ProcessSnapShot readProcessSanpShot(string processName, string processId)
        {
            ProcessSnapShot aux               = null;
            CloudTable      table             = tableClient.GetTableReference(Configuration.ButlerWorkflowStatus);
            TableOperation  retrieveOperation = TableOperation.Retrieve <ProcessSnapShot>(processName, processId);
            TableResult     retrievedResult   = table.Execute(retrieveOperation);

            if (retrievedResult.Result != null)
            {
                aux = (ProcessSnapShot)retrievedResult.Result;
            }
            return(aux);
        }
 public void PersistProcessStatus(ProcessSnapShot processSnapshot)
 {
     try
     {
         CloudTable     table           = tableClient.GetTableReference(Configuration.ButlerWorkflowStatus);
         TableOperation insertOperation = TableOperation.InsertOrReplace(processSnapshot);
         table.CreateIfNotExists();
         table.Execute(insertOperation);
     }
     catch (Exception X)
     {
         string txtMessage = string.Format("[{0}] Persist Process Status Error at process {1} instance {2}: error messagase  {3}", this.GetType().FullName, processSnapshot.RowKey, processSnapshot.PartitionKey, X.Message);
         Trace.TraceError(txtMessage);
         throw new Exception(txtMessage);
     }
 }
        public void PersistProcessStatus(ChainRequest request)
        {
            ProcessSnapShot mysh = new ProcessSnapShot(request.ProcessTypeId, request.ProcessInstanceId);

            try
            {
                Newtonsoft.Json.JsonSerializerSettings x = new Newtonsoft.Json.JsonSerializerSettings();
                x.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
                mysh.jsonContext        = Newtonsoft.Json.JsonConvert.SerializeObject(request, Newtonsoft.Json.Formatting.None, x);

                mysh.CurrentStep = request.CurrentStepIndex;

                PersistProcessStatus(mysh);
            }
            catch (Exception X)
            {
                string txtMessage = string.Format("[{0}] Persist Process Status Error at process {1} instance {2}: error messagase  {3}", this.GetType().FullName, request.ProcessInstanceId, request.ProcessTypeId, X.Message);
                Trace.TraceError(txtMessage);
                throw new Exception(txtMessage);
            }
        }
        /// <summary>
        /// Send back to watcher a "Posion messsage" and delete from in queue
        /// </summary>
        /// <param name="poisonMessage">the poison message</param>
        /// <returns>Sueccess or not</returns>
        private bool SendPoisonMessage(CloudQueueMessage poisonMessage)
        {
            bool sw = false;

            try
            {
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_Configuration.ProcessConfigConn);
                CloudQueueClient    queueClient    = storageAccount.CreateCloudQueueClient();
                CloudQueue          poisonQueue    = queueClient.GetQueueReference(_Configuration.poisonQueue);
                poisonQueue.CreateIfNotExists();
                Common.ResourceAccess.IButlerStorageManager storageManager = Common.ResourceAccess.BlobManagerFactory.CreateBlobManager(_Configuration.ProcessConfigConn);


                //1. Create Butler Response
                ButlerRequest  myButlerRequest  = Newtonsoft.Json.JsonConvert.DeserializeObject <ButlerRequest>(poisonMessage.AsString);
                ButlerResponse myButlerResponse = new ButlerResponse();

                myButlerResponse.MezzanineFiles = myButlerRequest.MezzanineFiles;
                ////Add to Mezzamine Files the control File URL if it exist
                //Becouse it is needed to move/delete the control file from processing to succes or fail
                if (!string.IsNullOrEmpty(myButlerRequest.ControlFileUri))
                {
                    myButlerResponse.MezzanineFiles.Add(myButlerRequest.ControlFileUri);
                }
                myButlerResponse.TimeStampProcessingCompleted = DateTime.Now.ToString();
                myButlerResponse.TimeStampProcessingStarted   = DateTime.Now.ToString();
                myButlerResponse.WorkflowName = myButlerRequest.WorkflowName;
                myButlerResponse.MessageId    = myButlerRequest.MessageId;
                myButlerResponse.TimeStampRequestSubmitted = myButlerRequest.TimeStampUTC;
                myButlerResponse.StorageConnectionString   = myButlerRequest.StorageConnectionString;
                myButlerResponse.Log = "Poison Message";

                //2. Lookin for Errors in Table Status
                string processId   = myProcessHandler.getProcessId(myButlerRequest.ControlFileUri, myButlerRequest.MessageId.ToString());
                var    processSnap = storageManager.readProcessSanpShot(myButlerRequest.WorkflowName, processId);

                if (processSnap != null)
                {
                    //2.1 Load Erros
                    dynamic dynObj    = Newtonsoft.Json.JsonConvert.DeserializeObject((processSnap).jsonContext);
                    var     errorList = Newtonsoft.Json.JsonConvert.DeserializeObject <List <string> >((dynObj.Exceptions.ToString()));
                    foreach (var errorTxt in errorList)
                    {
                        myButlerResponse.Log += "\r\n" + errorTxt;
                    }
                    //2.2 Update status
                    processSnap.CurrentStep = MBFConfiguration.poisonFinishProcessStep;
                    storageManager.PersistProcessStatus(processSnap);
                }
                else
                {
                    //No process execution, fatal error
                    //Update satus no process Status
                    ProcessSnapShot psPoison = new ProcessSnapShot(myButlerResponse.WorkflowName, processId);
                    psPoison.CurrentStep = MBFConfiguration.workflowFatalError;
                    storageManager.PersistProcessStatus(psPoison);
                }

                //3. Send Poison Mesagge
                CloudQueueMessage poison = new CloudQueueMessage(Newtonsoft.Json.JsonConvert.SerializeObject(myButlerResponse));
                poisonQueue.AddMessage(poison);
                sw = true;

                //4. Send On Error HTTP Callback Notification
                try
                {
                    var    StorageManager           = ResourceAccess.BlobManagerFactory.CreateBlobManager(_Configuration.ProcessConfigConn);
                    string jsonProcessConfiguration = StorageManager.GetButlerConfigurationValue(
                        ProcessConfigKeys.DefualtPartitionKey,
                        myButlerRequest.WorkflowName + ".config");

                    var processConfiguration = new ResourceAccess.jsonKeyValue(jsonProcessConfiguration);

                    if (processConfiguration.Read(ProcessConfigKeys.MediaButlerHostHttpCallBackOnError) != "")
                    {
                        //POST
                        string url = processConfiguration.Read(ProcessConfigKeys.MediaButlerHostHttpCallBackOnError);
                        using (var client = new HttpClient())
                        {
                            var content = new StringContent(
                                StorageManager.readProcessSanpShot(myButlerRequest.WorkflowName, processId).jsonContext,
                                Encoding.UTF8, "application/json");
                            var result = client.PostAsync(url, content).Result;
                            Trace.TraceInformation("Http Post Notification Result: " + result.ToString());
                        }
                    }
                }
                catch (Exception X)
                {
                    Trace.TraceError("HTTP CALLBACK ERROR " + X.Message);
                }
            }
            catch (Exception X)
            {
                string txt = string.Format("[{0}] at {1} has an error: {2}", this.GetType().FullName, "GetNewMessage", X.Message);
                Trace.TraceError(txt);
            }
            return(sw);
        }