public HttpResponseMessage Post(JObject jcommand)
       {
           
           var responseBasic = new ResponseBasic();
           responseBasic.Status = false;
           HttpStatusCode returnCode = HttpStatusCode.OK;
           try
           {
              
               responseBasic.ResultInfo = "invalid jsoncommand";
               string json = jcommand.ToString();
               CommandEnvelope envelope = JsonConvert.DeserializeObject<CommandEnvelope>(json);
               responseBasic.ResultInfo = "valid jsoncommand";
                bool isValid = envelope != null;
                _log.Info("responseBasic.ResultInfo " + responseBasic.ResultInfo);
               if (isValid)
               {
                   if (!_costCentreApplicationService.IsCostCentreActive(envelope.GeneratedByCostCentreApplicationId))
                   {
                       responseBasic.Status=false;
                       returnCode = HttpStatusCode.OK;
                       responseBasic.Result = "Inactive CostCentre Application Id";
                       _log.InfoFormat("Cost centre is not active for envelope id {0} ccId {1} ccid",envelope.Id, envelope.GeneratedByCostCentreApplicationId,envelope.GeneratedByCostCentreId);
                     return Request.CreateResponse(returnCode, responseBasic);
                   }
                   _log.InfoFormat("EnvelopeId {0} " ,envelope.Id.ToString());
               
                   envelope.EnvelopeArrivedAtServerTick = DateTime.Now.Ticks;

                   var message = new EnvelopeBusMessage
                                 {
                                     DocumentTypeId = envelope.DocumentTypeId,
                                     MessageId = envelope.Id,
                                     BodyJson = JsonConvert.SerializeObject(envelope),
                                     SendDateTime = DateTime.Now.ToString(),
                                     IsSystemMessage = envelope.IsSystemEnvelope
                                 };
                   var envelopeProcessingAudit = new CommandEnvelopeProcessingAudit
                                                 {

                                                     GeneratedByCostCentreApplicationId =
                                                         envelope.GeneratedByCostCentreApplicationId,
                                                    
                                                     DateInserted = DateTime.Now,
                                                     Id = envelope.Id,
                                                     JsonEnvelope = message.BodyJson,
                                                     RetryCounter = 0,
                                                     Status = EnvelopeProcessingStatus.OnQueue,
                                                     SendDateTime = message.SendDateTime,
                                                     DocumentId = envelope.DocumentId,
                                                     ParentDocumentId = envelope.ParentDocumentId,
                                                     DocumentType = (DocumentType) envelope.DocumentTypeId,
                                                     EnvelopeGeneratedTick = envelope.EnvelopeGeneratedTick,
                                                     EnvelopeArrivalAtServerTick = envelope.EnvelopeArrivedAtServerTick,
                                                     EnvelopeProcessOnServerTick = 0,
                                                     GeneratedByCostCentreId = envelope.GeneratedByCostCentreId,
                                                     RecipientCostCentreId = envelope.RecipientCostCentreId,
                                                     LastExecutedCommand = 0,
                                                     NumberOfCommand = envelope.CommandsList.Count

                                                 };
                   envelopeProcessingAudit.DocumentTypeName = envelopeProcessingAudit.DocumentType.ToString();
                   if (_commandEnvelopeProcessingAuditRepository.IsConnected())
                   {
                       var exist = _commandEnvelopeProcessingAuditRepository.GetById(envelope.Id);
                       if (exist == null)
                       {
                           _commandEnvelopeProcessingAuditRepository.AddCommand(envelopeProcessingAudit);
                           _busPublisher.Publish(message);
                       }
                       else
                       {
                           _log.InfoFormat("EnvelopeId {0}  Already Published", envelope.Id.ToString());
                       }
                       _log.InfoFormat("EnvelopeId {0}  Published", envelope.Id.ToString());
                       responseBasic.Status = true;
                       responseBasic.Result = "Envelope Processed";
                       _log.Info("  responseBasic.Result " + responseBasic.Result);
                   }
                   else
                   {
                       responseBasic.Result = "Processing Failed";
                       responseBasic.ErrorInfo = "Mongo down";
                       _log.Info("   responseBasic.ErrorInfo " + responseBasic.ErrorInfo);
                   }
               }
           }
           catch (Exception ex)
           {
               responseBasic.Result = "Processing Failed";
               responseBasic.ErrorInfo = ex.Message;
               _log.Info("   responseBasic.Result" + responseBasic.Result);
               _log.Info("   responseBasic.ErrorInfo " + responseBasic.ErrorInfo);
               
                
           }
           HttpResponseMessage response = Request.CreateResponse(returnCode, responseBasic);

           return response;
       }
 public void AddCommand(CommandEnvelopeProcessingAudit processingAudit)
 {
     _commandEnvelopeProcessingAuditCollection.Save(processingAudit);
 }
        void Save(CommandEnvelopeProcessingAudit envelopeAudit, List<CommandEnvelopeRouteOnRequestCostcentre> rorCCs, List<CommandEnvelopeRoutingStatus> envRoutingStatus)
        {
            ICommandEnvelopeProcessingAuditRepository auditRepository = settings.MongoCommandEnvelopeProccessingAuditRepository;
            CommandEnvelopeRouteOnRequestCostcentreRepository rorRepository = settings.MongoCommandEnvelopeRORCostCentreRepository as CommandEnvelopeRouteOnRequestCostcentreRepository; ;
            MongoCollection<CommandEnvelopeRouteOnRequestCostcentre> repCERORCC = rorRepository._commandEnvelopeRouteOnRequestCostcentreCollection;
            MongoCollection<CommandEnvelopeRoutingStatus> routingStatus = rorRepository._commandEnvelopeRoutingStatusCollection;
           
            auditRepository.AddCommand(envelopeAudit);
            
            if (rorCCs != null)
            {
                foreach (var rorCC in rorCCs)
                {
                    repCERORCC.Save(rorCC);
                }
            }

            if (envRoutingStatus != null)
            {
                foreach (var stat in envRoutingStatus)
                {
                    routingStatus.Save(stat);
                }
            }
            
        }
 Tuple<CommandEnvelopeProcessingAudit, long?> MapAuditAndResolveRORId(Guid documentId, List<CommandProcessingAudit> commands)
 {
     CommandProcessingAudit initialCommandAudit = commands.OrderBy(n => n.CostCentreCommandSequence).First();
     DocumentCommand initialCommand = JsonConvert.DeserializeObject<DocumentCommand>(initialCommandAudit.JsonCommand);
     IResolveCommand resolver = new ResolveCommand();
     ResolveCommandItem rci = resolver.Get(initialCommand);
     DocumentType dt = rci.DocumentType;
     Guid envelopeId = Guid.NewGuid();
     long generatedTick = initialCommandAudit.DateInserted.Ticks;
     long? rorId = GetCommandRORId(initialCommandAudit.Id);
     Guid? recipientCostCentreId = null;
     if (rorId != null)
     {
         recipientCostCentreId = ResolveReceipientCostCentre(initialCommandAudit.Id, initialCommand.CommandGeneratedByCostCentreId, rorId.Value);
     }
     if (recipientCostCentreId == null)
     {
         log.WarnFormat("Failed to resolve recipient cost centre for document id {0} command id {1}, saving envelope without recipient cost centre ", documentId, initialCommandAudit.Id);
     }
     DocumentCommand[] deserialisedCommands = commands.OrderBy(n => n.CostCentreCommandSequence).Select(n => JsonConvert.DeserializeObject<DocumentCommand>(n.JsonCommand)).ToArray();
     CommandEnvelope ce = CommandsToEnvelope(envelopeId, documentId, dt, generatedTick, initialCommandAudit.ParentDocumentId, recipientCostCentreId, deserialisedCommands);
     var cpa = new CommandEnvelopeProcessingAudit
     {
         Id = envelopeId,
         DocumentId = documentId,
         DocumentTypeName = dt.ToString(),
         DocumentType = dt,
         LastExecutedCommand = 0,
         NumberOfCommand = commands.Count(),
         GeneratedByCostCentreApplicationId = initialCommand.CommandGeneratedByCostCentreApplicationId,
         GeneratedByCostCentreId = initialCommand.CommandGeneratedByCostCentreId,
         RecipientCostCentreId = recipientCostCentreId ?? Guid.Empty,
         ParentDocumentId = initialCommandAudit.ParentDocumentId,
         JsonEnvelope = JsonConvert.SerializeObject(ce)
     };
     return Tuple.Create(cpa, rorId);
 }
        private List<CommandEnvelopeRouteOnRequestCostcentre> MapRORCC(long? rorId, CommandEnvelopeProcessingAudit envelopeAudit)
        {
            if (rorId == null)
                return null;
            var rorcc = settings.MongoCollection_Command_CommandRouteOnRequestCostCentre
                .AsQueryable()
                .Where(n => n.CommandRouteOnRequestId == rorId.Value)
                .ToList();
            var rorEnvCCs = rorcc.Select(n => new CommandEnvelopeRouteOnRequestCostcentre
            {
                Id = Guid.NewGuid(),
                EnvelopeId = envelopeAudit.Id,
                EnvelopeArrivalAtServerTick = n.DateAdded.Ticks,
                CostCentreId = n.CostCentreId,
                IsValid = true,
                DateAdded = n.DateAdded,
                IsRetired = n.IsRetired,
                DocumentType = envelopeAudit.DocumentType.ToString(),
                EnvelopeRoutedAtServerTick = n.DateAdded.Ticks,
                EnvelopeRoutePriority = EnvelopeRoutePriority.Level1

            });
            if (rorEnvCCs.Count() == 0)
                log.WarnFormat("No CommandEnvelopeRouteOnRequestCostcentres added for RORId {0}", 0);
            return rorEnvCCs.ToList();
        }
        private void AddToMongoDB(CommandEnvelope envelope)
        {
            envelope.EnvelopeArrivedAtServerTick = DateTime.Now.Ticks;

            var envelopeProcessingAudit = new CommandEnvelopeProcessingAudit
            {

                GeneratedByCostCentreApplicationId =Guid.Empty,
                   

                DateInserted = DateTime.Now,
                Id = envelope.Id,
                JsonEnvelope = JsonConvert.SerializeObject(envelope),
                RetryCounter = 0,
                Status = EnvelopeProcessingStatus.OnQueue,
               
                DocumentId = envelope.DocumentId,
                ParentDocumentId = envelope.ParentDocumentId,
                DocumentType = (DocumentType)envelope.DocumentTypeId,
                EnvelopeGeneratedTick = envelope.EnvelopeGeneratedTick,
                EnvelopeArrivalAtServerTick = DateTime.Now.Ticks,
                EnvelopeProcessOnServerTick = 0,
                GeneratedByCostCentreId = envelope.GeneratedByCostCentreId,
                RecipientCostCentreId = envelope.RecipientCostCentreId,
                LastExecutedCommand = 0,
                NumberOfCommand = envelope.CommandsList.Count

            };
            envelopeProcessingAudit.DocumentTypeName = envelopeProcessingAudit.DocumentType.ToString();
            _commandProcessingAuditRepository.AddCommand(envelopeProcessingAudit);
            var message = new EnvelopeBusMessage
            {
                DocumentTypeId = envelope.DocumentTypeId,
                MessageId = envelope.Id,
                BodyJson = JsonConvert.SerializeObject(envelope),
                SendDateTime = DateTime.Now.ToString(),
                
            };
            _busPublisher.Publish(message);
        }
        private void RouteDocumentExternalRef(Guid documentId, Guid generatedByCostCentreId, Guid recipientCostCentreId, CommandEnvelopeItem envelopeItem)
        {
                _documentHelper.GetExternalRef(envelopeItem.Command);
                var command = GetExternalCommnandRef(envelopeItem.Command);
                if (command != null)
                {
                    var env = new CommandEnvelope();
                    env.Id = Guid.NewGuid();
                    env.EnvelopeGeneratedTick = DateTime.Now.Ticks;
                    env.GeneratedByCostCentreId = generatedByCostCentreId;
                    env.RecipientCostCentreId = recipientCostCentreId;
                    env.DocumentTypeId = (int)DocumentType.Order;
                    env.GeneratedByCostCentreApplicationId = Guid.Empty;
                    env.ParentDocumentId = documentId;
                    env.DocumentId = documentId;
                    env.CommandsList.Add(new CommandEnvelopeItem(1, command));
                    env.EnvelopeArrivedAtServerTick = DateTime.Now.Ticks;
                    var audit = new CommandEnvelopeProcessingAudit
                    {

                        GeneratedByCostCentreApplicationId =
                            env.GeneratedByCostCentreApplicationId,

                        DateInserted = DateTime.Now,
                        Id = env.Id,
                        JsonEnvelope = JsonConvert.SerializeObject(env),
                        RetryCounter = 0,
                        Status = EnvelopeProcessingStatus.OnQueue,

                        DocumentId = env.DocumentId,
                        ParentDocumentId = env.ParentDocumentId,
                        DocumentType = (DocumentType)env.DocumentTypeId,
                        EnvelopeGeneratedTick = env.EnvelopeGeneratedTick,
                        EnvelopeArrivalAtServerTick = DateTime.Now.Ticks,
                        EnvelopeProcessOnServerTick = 0,
                        GeneratedByCostCentreId = env.GeneratedByCostCentreId,
                        RecipientCostCentreId = env.RecipientCostCentreId,
                        LastExecutedCommand = 1,
                        NumberOfCommand = env.CommandsList.Count,
                       
                        

                    };
                    audit.EnvelopeArrivalAtServerTick = DateTime.Now.Ticks;

                    audit.DocumentTypeName = audit.DocumentType.ToString();
                    _runCommandOnRequestInHostedEnvironment.RunCommandInHostedenvironment(command);
                    _envelopeProcessingAuditRepository.AddCommand(audit);
                    _commandEnvelopeRouteOn.AddCommandEnvelopeRouteCentre(env);
                }
           
        }