Exemple #1
0
        private Task Resume <T>(WorkflowRequest <T> request)
        {
            var resumePoint = (FormSubmissionActivity <T>)Flow.Activities.FirstOrDefault(a => a.Ref == request.ResumeFrom);

            resumePoint.Data = request.Data;
            return(Context.Execute(request.Data, request.Api, request.AuthToken, resumePoint));
        }
Exemple #2
0
        public async Task <WorkflowsVM> CompletedWorkflows(string projectId, string user)
        {
            ExistingWorkflows existingWorkflows = new ExistingWorkflows(_ampRepository.GetWorkflowMastersByProject(projectId));

            WorkflowsVM workflowsVm = new WorkflowsVM();
            List <CompletedWorkflowVM> completedWorkflowVms = new List <CompletedWorkflowVM>();
            List <Tuple <WorkflowMaster, WorkflowMaster> > completedTupleList = new List <Tuple <WorkflowMaster, WorkflowMaster> >();

            List <WorkflowMaster> completedRequests  = existingWorkflows.CompletedRequests().OrderByDescending(x => x.WorkFlowID).ToList();
            List <WorkflowMaster> completedResponses = existingWorkflows.CompletedResponses().OrderByDescending(x => x.WorkFlowID).ToList();

            for (int i = 0; i < completedRequests.Count(); i++)
            {
                WorkflowRequest  request  = new WorkflowRequest(_personService);
                WorkflowResponse response = new WorkflowResponse(_personService);
                request.workflow  = completedRequests.ElementAt(i);
                response.workflow = completedResponses.ElementAt(i);

                CompletedWorkflow completed = new CompletedWorkflow(_ampRepository, _documentService);

                await completed.Construct(request, response);

                completedWorkflowVms.Add(completed);
            }

            workflowsVm.workflows = completedWorkflowVms;

            return(workflowsVm);
        }
Exemple #3
0
        public async Task Run(WorkflowRequest msg)
        {
            await ConnectToHub(msg);

            try
            {
                await Log(WorkflowLogLevel.Info, "Request received by workflow, processing ...", msg.InstanceId);
                await Log(WorkflowLogLevel.Debug, msg.ToJson(ObjectExtensions.JSONSettings, Formatting.Indented), msg.InstanceId);

                // construct the flow instance
                var instance = msg.ResumeFrom == null
                    ? await FlowHelper.Get(msg.FlowId, msg.Api, msg.AuthToken, (WorkflowLogLevel level, string message) => Log(level, message, msg.InstanceId))
                    : await FlowHelper.GetInstance(msg.InstanceId, msg.Api, msg.AuthToken, (WorkflowLogLevel level, string message) => Log(level, message, msg.InstanceId));

                // execute the flow
                await ExecuteRequest(msg, instance);
            }
            catch (Exception ex)
            {
                await Log(WorkflowLogLevel.Fatal, $"Failed to process request, abandoning execution\n{ex.Message}\n{ex.StackTrace}", msg.InstanceId);
            }
            finally
            {
                await Log(WorkflowLogLevel.Info, "Done!", msg.InstanceId);
            }
        }
Exemple #4
0
        /// <summary>
        /// Método privado para processamento do método 'user.resetpassword'
        /// </summary>
        /// <param name="sqlConnection">Conexão com o banco de dados MS-SQL</param>
        /// <param name="parameters">Dicionário (String, Object) contendo todos os parâmetros necessários</param>
        private Boolean accessrequestdeny(IAMDatabase database, Dictionary <String, Object> parameters)
        {
            if (!parameters.ContainsKey("requestid"))
            {
                Error(ErrorType.InvalidRequest, "Parameter requestid is not defined.", "", null);
                return(false);
            }

            Int64 requestid = 0;

            try
            {
                requestid = Int64.Parse(parameters["requestid"].ToString());
            }
            catch
            {
                Error(ErrorType.InvalidRequest, "Parameter requestid is not a long integer.", "", null);
                return(false);
            }

            WorkflowRequest         req  = new WorkflowRequest(requestid);
            WorkflowRequestProccess proc = req.SetStatus(database, WorkflowRequestStatus.Deny, Acl.EntityId);

            if (!proc.Success)
            {
                Error(ErrorType.InvalidRequest, proc.Message, proc.Debug, null);
                return(false);
            }
            else
            {
                return(true);
            }
        }
Exemple #5
0
        async Task ExecuteRequest(WorkflowRequest msg, FlowInstance instance)
        {
            var result = await(Task <FlowInstanceData>) instance
                         .GetType()
                         .GetMethod("Execute")
                         .MakeGenericMethod(msg.GetType().GenericTypeArguments)
                         .Invoke(instance, new[] { msg });

            await FlowHelper.SaveResult(result, msg.Api, msg.AuthToken);
        }
 public virtual JsonResult TestRequest(WorkflowRequest workflowRequest)
 {
     workflowRequest.ReturnURL   = Url.Action("Test", "Workflows", new { area = "Global" });
     workflowRequest.Whit2k      = false;
     TempData["workflowRequest"] = workflowRequest;
     return(this.Json(new ResponseBase()
     {
         IsValid = true
     }));
 }
 public WorkflowDTO Post(WorkflowRequest req)
 {
     context.WorkFlow.Add(new WorkflowDTO()
     {
         Data   = req.Data,
         Steps  = req.Steps,
         UUID   = req.UUID,
         Status = StatusWF.Inserted
     });
     context.SaveChanges();
     MessageHandler.Send(MYQUEUE, req.UUID.ToString());
     return(context.WorkFlow.Find(req.UUID));
 }
Exemple #8
0
        public void Test_WorkflowRequest()
        {
            // Ensures that we can serialize and deserialize workflow request messages.

            WorkflowRequest message;

            using (var stream = new MemoryStream())
            {
                // Empty message.

                message = new WorkflowRequest();

                stream.SetLength(0);
                stream.Write(message.SerializeAsBytes(ignoreTypeCode: true));
                stream.Seek(0, SeekOrigin.Begin);

                message = ProxyMessage.Deserialize <WorkflowRequest>(stream, ignoreTypeCode: true);
                Assert.NotNull(message);
                Assert.Equal(0, message.ClientId);
                Assert.Equal(0, message.RequestId);
                Assert.Equal(0, message.ContextId);

                // Round-trip

                message.ClientId  = 444;
                message.RequestId = 555;
                message.ContextId = 666;

                Assert.Equal(444, message.ClientId);
                Assert.Equal(555, message.RequestId);
                Assert.Equal(666, message.ContextId);

                stream.SetLength(0);
                stream.Write(message.SerializeAsBytes(ignoreTypeCode: true));
                stream.Seek(0, SeekOrigin.Begin);

                message = ProxyMessage.Deserialize <WorkflowRequest>(stream, ignoreTypeCode: true);
                Assert.NotNull(message);
                Assert.Equal(444, message.ClientId);
                Assert.Equal(555, message.RequestId);
                Assert.Equal(666, message.ContextId);

                // Clone()

                message = (WorkflowRequest)message.Clone();
                Assert.NotNull(message);
                Assert.Equal(444, message.ClientId);
                Assert.Equal(555, message.RequestId);
                Assert.Equal(666, message.ContextId);
            }
        }
Exemple #9
0
        public async Task <WorkflowVM> WorkflowByProjectIdAndTaskId(string projectId, Int32 taskId, string user)
        {
            if (string.IsNullOrEmpty(projectId))
            {
                throw new ArgumentException("String is null or empty", "projectId");
            }

            if (string.IsNullOrEmpty(user))
            {
                throw new ArgumentException("String is null or empty", "user");
            }

            ExistingWorkflows     existingWorkflows = new ExistingWorkflows(_ampRepository.GetWorkflowMastersByProjectandTask(projectId, taskId));
            WorkflowRequest       workflowRequest   = new WorkflowRequest(_personService);
            WorkflowResponse      workflowResponse  = new WorkflowResponse(_personService);
            WorkflowConfiguration configuration     = new WorkflowConfiguration();
            WorkflowObject        workflowObj       = new WorkflowObject(_ampRepository, taskId, _documentService);

            string projectStage = _ampRepository.GetProject(projectId).Stage;
            string userRole     = "";

            if (taskId == Constants.PlannedEndDate) // set up the message to workflow screen for planned end date
            {
                ProjectPlannedEndDate projectPlannedEndDate = _ampRepository.GetProjectPlannedEndDate(projectId);
                string message = WorkflowMessages.PlannedEndDatePendingApprovalMessage(projectPlannedEndDate.NewPlannedEndDate);
                workflowObj.WfMessage = message;
            }

            if (existingWorkflows.HasActiveWorkflow())
            {
                workflowRequest.workflow = existingWorkflows.ActiveWorkflowRequest();
                workflowResponse.CreateResponse(workflowRequest.workflow);
                userRole = SetUserRole(user, projectId, workflowRequest.workflow.Recipient);
            }
            else if (existingWorkflows.LastWorkflowWasRejected())
            {
                workflowRequest.workflow  = existingWorkflows.LastRejectedWorkflowRequest();
                workflowResponse.workflow = existingWorkflows.LastRejectedWorkflowResponse();
                userRole = SetUserRole(user, projectId, workflowRequest.workflow.Recipient);
            }
            else
            {
                workflowRequest.CreateRequest(projectId, taskId, user);
                workflowResponse.response = new WorkflowMaster();
                userRole = SetUserRole(user, projectId, null);
            }

            await workflowObj.Construct(workflowRequest, workflowResponse, userRole);

            return(workflowObj);
        }
Exemple #10
0
        public static async Task <HttpResponseMessage> WorkflowOneHttpStartAsync(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestMessage req,
            [DurableClient] IDurableOrchestrationClient starter,
            ILogger log)
        {
            WorkflowRequest request = await req.Content.ReadAsAsync <WorkflowRequest>();

            // Function input comes from the request content.
            string instanceId = await starter.StartNewAsync("WorkflowOneOrchestrator", request);

            log.LogInformation($"Started orchestration with ID = '{instanceId}', requestWait: {request.WaitSeconds}.");

            return(starter.CreateCheckStatusResponse(req, instanceId));
        }
Exemple #11
0
        public async Task <FlowInstanceData> Execute <T>(WorkflowRequest <T> request)
        {
            Start   = DateTimeOffset.UtcNow;
            Id      = request.InstanceId;
            Context = new WorkflowContext(Flow, this);

            if (request.ResumeFrom == null)
            {
                await Context.Execute(request.Data, request.Api, request.AuthToken);
            }
            else
            {
                await Resume(request);
            }

            return(Complete());
        }
Exemple #12
0
        async Task ConnectToHub(WorkflowRequest msg)
        {
            try
            {
                // connect to the signalr hub on the source API
                con = new HubConnectionBuilder().WithUrl(msg.Api + "Hubs/Workflow").Build();
                con.On <Exception>("error", (ex) => Console.WriteLine(ex.Message + "\n" + ex.StackTrace));
                await con.StartAsync();
                await Log(WorkflowLogLevel.Info, $"Workflow Instance {msg.InstanceId} Connected.", msg.InstanceId);
            }
            catch (Exception ex)
            {
                await con.DisposeAsync();

                con = null;
                await Log(WorkflowLogLevel.Error, "Failed to connect to the hub because: " + ex.Message, msg.InstanceId);
            }
        }
        /// <summary>
        /// Processes the specified workflow, executing the specified <paramref name="transition"/> with the given <paramref name="request"/>
        /// </summary>
        /// <param name="workflow">The workflow.</param>
        /// <param name="transition">The transition.</param>
        /// <param name="request">The request.</param>
        public void Process(IWorkflow workflow, WorkflowTransition transition, WorkflowRequest request)
        {
            Log.DebugFormat("Process({0}, {1}, {2})", workflow, transition, request);
            //TODO: Block concurrent calls to Start/Process?
            Unloaded.Reset();
            Result      = new WorkflowResult();
            Application = CreateWorkflowApplication(null);
            if (!CheckForRunnableInstance())
            {
                Application.Load(workflow.WorkflowInstanceId);
            }
            else
            {
                Application.LoadRunnableInstance();
            }

            Application.ResumeBookmark(transition.Name, request);
        }
        /// <summary>
        ///     Sends the thread request.
        /// </summary>
        private void SendRequest( )
        {
            if (_multiplexer != null)
            {
                var subscriber = _multiplexer.GetSubscriber( );

                var request = new WorkflowRequest
                {
                    Enabled = IsEnabled
                };

                var channelMessage = ChannelMessage <WorkflowRequest> .Create(request);

                byte[] serializedObject = ChannelHelper.Serialize(channelMessage);
                byte[] compressedObject = ChannelHelper.Compress(serializedObject);

                subscriber.Publish("ReadiNowDiagnosticRequests", compressedObject, CommandFlags.FireAndForget);
            }
        }
Exemple #15
0
        public static async Task <List <string> > WorkflowOneOrchestratorAsync(
            [OrchestrationTrigger] IDurableOrchestrationContext context)
        {
            var outputs = new List <string>();

            WorkflowRequest request = context.GetInput <WorkflowRequest>();


            // Replace "hello" with the name of your Durable Activity Function.
            outputs.Add(await context.CallActivityAsync <string>("HelloActivity", "Tokyo"));
            outputs.Add(await context.CallActivityAsync <string>("HelloActivity", "Seattle"));

            outputs.Add((await context.CallActivityAsync <WorkflowResponse>("FirstActivity", request)).ToString());

            outputs.Add(await context.CallActivityAsync <string>("HelloActivity", "London"));

            // returns ["Hello Tokyo!", "Hello Seattle!", "Hello London!"]
            return(outputs);
        }
Exemple #16
0
        public virtual JsonResult WorkflowFinancialPlan(WorkflowRequest workflowRequest)
        {
            _financialPlanService.UpdateFPLastSubmitted(workflowRequest.EntityId);

            workflowRequest.ReturnURL = @Url.Action(
                "Index",
                "FinancialPlan",
                new { area = "FinancialPlan" });

            workflowRequest.WorkflowCode = WorkflowInformationConst.WorkflowCode;
            workflowRequest.ModuleName   = WorkflowInformationConst.ModuleName;

            TempData["workflowRequest"] = workflowRequest;
            return(this.Json(new ResponseBase()
            {
                IsValid = true,
                ErrorMessage = "Workflow was not executed"
            }));
        }
Exemple #17
0
        public virtual ActionResult InitContractAmendmentWorkflow(string operationNumber, int procurementId, string entityType, int entityId)
        {
            var arrayWorkflowInfo = entityType.Split(';');

            WorkflowRequest workflowRequest = new WorkflowRequest()
            {
                OperationNumber      = operationNumber,
                WorkflowCode         = arrayWorkflowInfo[0],
                EntityType           = string.Format("{0}-{1}-{2}", ProcurementDetailNavigation.WORKFLOW_TYPE_CONTRACT_AMENDMENT, arrayWorkflowInfo[1], DateTime.Now.Ticks.ToString()),
                EntityId             = entityId,
                ModuleName           = "Submit for Non Objection",
                ReturnURL            = Url.Action("ChangeStatusInitialContractAmendment", "ProcurementDetail", new { area = "SGP", tabName = ProcurementDetailNavigation.TAB_NAME_CONTRACTS, procurementId = procurementId, contractId = arrayWorkflowInfo[1] }),
                ReturnURLCancel      = Url.Action("Read", "ProcurementDetail", new { area = "SGP", tabName = ProcurementDetailNavigation.TAB_NAME_CONTRACTS, procurementId = procurementId, contractId = arrayWorkflowInfo[1] }),
                InstructionsIncluded = false,
                CanAddValidator      = false,
            };

            TempData["workflowRequest"] = workflowRequest;

            return(RedirectToAction("New", "Workflows", new { area = "Global", operationNumber = operationNumber }));
        }
        public virtual ActionResult InitGeneralNoticeWorkflow(string operationNumber, int planId, int entityId, string entityType)
        {
            var arrayWorkflowInfo = entityType.Split(';');

            WorkflowRequest workflowRequest = new WorkflowRequest()
            {
                OperationNumber      = operationNumber,
                WorkflowCode         = arrayWorkflowInfo[0],
                EntityType           = string.Format("{0}-{1}-{2}", ProcurementPlanNavigation.WORKFLOW_TYPE_GENERAL_NOTICE, planId, DateTime.Now.Ticks.ToString()),
                EntityId             = entityId,
                ModuleName           = "Submit for Non Objection",
                ReturnURL            = Url.Action("SaveGeneralNoticeWF", "ProcurementPlan", new { area = "SGP", tabName = ProcurementPlanNavigation.TAB_NAME_OPERATION_LEVEL, planId = planId }),
                ReturnURLCancel      = Url.Action("Read", "ProcurementPlan", new { area = "SGP", tabName = ProcurementPlanNavigation.TAB_NAME_OPERATION_LEVEL, planId = planId }),
                InstructionsIncluded = false,
                CanAddValidator      = false,
            };

            TempData["workflowRequest"] = workflowRequest;

            return(RedirectToAction("New", "Workflows", new { area = "Global", operationNumber = operationNumber }));
        }
Exemple #19
0
        public virtual ActionResult InitDeclareInegibilityWorkflow(string operationNumber, int procurementId, string entityType, int entityId, string workflowCode, int reasonType, string reason)
        {
            var arrayWorkflowInfo = entityType.Split(';');

            WorkflowRequest workflowRequest = new WorkflowRequest()
            {
                OperationNumber      = operationNumber,
                WorkflowCode         = arrayWorkflowInfo[0],
                EntityType           = string.Format("{0}-0-{1}", workflowCode, DateTime.Now.Ticks.ToString()),
                EntityId             = entityId,
                ModuleName           = "Submit for Non Objection",
                ReturnURL            = Url.Action("SaveDeclareInitialDeclareWF", "ProcurementDetail", new { area = "SGP", tabName = ProcurementDetailNavigation.TAB_NAME_PROCUREMENT_DETAIL, procurementId = procurementId, reasonType = reasonType, reason = reason }),
                ReturnURLCancel      = Url.Action("Read", "ProcurementDetail", new { area = "SGP", tabName = ProcurementDetailNavigation.TAB_NAME_PROCUREMENT_DETAIL, procurementId = procurementId }),
                InstructionsIncluded = false,
                CanAddValidator      = false,
            };

            TempData["workflowRequest"] = workflowRequest;

            return(RedirectToAction("New", "Workflows", new { area = "Global", operationNumber = operationNumber }));
        }
Exemple #20
0
        public async Task <WorkflowVM> WorkflowByWorkflowId(Int32 workflowId, string user)
        {
            string userRole;
            Int32  taskId;
            string projectId;

            ExistingWorkflows existingWorkflows = new ExistingWorkflows(_ampRepository.GetWorkflowMasters(workflowId));

            if (existingWorkflows.HasWorkflows())
            {
                WorkflowRequest       request       = new WorkflowRequest(_personService);
                WorkflowResponse      response      = new WorkflowResponse(_personService);
                WorkflowConfiguration configuration = new WorkflowConfiguration();
                WorkflowObject        workflowObj;
                request.workflow  = existingWorkflows.WorkflowRequest(workflowId);
                response.workflow = existingWorkflows.WorkflowResponse(workflowId);

                taskId    = request.workflow.TaskID;
                projectId = request.workflow.ProjectID;
                string projectStage = _ampRepository.GetProject(projectId).Stage;

                workflowObj = new WorkflowObject(_ampRepository, request.workflow.TaskID, _documentService);
                userRole    = SetUserRole(user, request.workflow.ProjectID, request.workflow.Recipient);

                await workflowObj.Construct(request, response, userRole);

                if (taskId == Constants.PlannedEndDate && response.workflow.StageID != 3)// set up the message to workflow screen for planned end date only if approved
                {
                    ProjectPlannedEndDate projectPlannedEndDate = _ampRepository.GetProjectPlannedEndDatForWorkflowHistory(workflowId);
                    string message = WorkflowMessages.PlannedEndDateWorkflowHistoryMessage(projectPlannedEndDate.CurrentPlannedEndDate, projectPlannedEndDate.NewPlannedEndDate);
                    workflowObj.WfMessage = message;
                }



                return(workflowObj);
            }

            return(null);
        }
Exemple #21
0
        public virtual ActionResult InitRequestForPublishing(string operationNumber, int procurementId, string entityType, int entityId, int publishtypeId)
        {
            var arrayWorkflowInfo = entityType.Split(';');
            var workflowCode      = GetPublishType(publishtypeId);

            WorkflowRequest workflowRequest = new WorkflowRequest()
            {
                OperationNumber      = operationNumber,
                WorkflowCode         = arrayWorkflowInfo[0],
                EntityType           = string.Format("{0}-{1}-{2}", workflowCode, arrayWorkflowInfo[1], DateTime.Now.Ticks.ToString()),
                EntityId             = entityId,
                ModuleName           = "Submit for Non Objection",
                ReturnURL            = Url.Action("ChangeStatusRequestForPublishing", "ProcurementDetail", new { area = "SGP", tabName = ProcurementDetailNavigation.TAB_NAME_BINDING_DOCUMENTS, procurementId = procurementId, packageId = arrayWorkflowInfo[1] }),
                ReturnURLCancel      = Url.Action("Read", "ProcurementDetail", new { area = "SGP", tabName = ProcurementDetailNavigation.TAB_NAME_BINDING_DOCUMENTS, procurementId = procurementId, packageId = arrayWorkflowInfo[1] }),
                InstructionsIncluded = false,
                CanAddValidator      = false,
            };

            TempData["workflowRequest"] = workflowRequest;

            return(RedirectToAction("New", "Workflows", new { area = "Global", operationNumber = operationNumber }));
        }
        /// <summary>
        /// Processes the specified activity.
        /// </summary>
        /// <param name="activity">The activity.</param>
        /// <param name="workflow">The workflow.</param>
        /// <param name="transition">The transition.</param>
        /// <param name="request">The request.</param>
        /// <param name="timeout">The timeout.</param>
        public void Process(Activity activity, Version version, WorkflowInstance workflow, WorkflowTransition transition, WorkflowRequest request, int timeoutInSeconds = 60)
        {
            //Guard.AgainstNull(() => activity);
            //Guard.AgainstNull(() => workflow);
            //Guard.AgainstNull(() => transition);
            //Guard.AgainstNull(() => request);
            var timeout  = new TimeSpan(0, 0, timeoutInSeconds);
            var instance = new WorkflowInstanceService(activity, version, Log);

            /*
             * Cannot use transaction scope as this causes locks not be created
             * with Windows workflow store procedures
             *
             * using (new TransactionScope(TransactionScopeOption.Suppress))
             * {
             *  instance.Process(workflow, transition, request);
             *  if (!instance.WaitOne(timeout))
             *      throw new TimeoutException("Timeout waiting for unload from workflow engine");
             * }
             *
             */

            instance.Process(workflow, transition, request);

            if (!instance.WaitOne(timeout))
            {
                throw new TimeoutException("Timeout waiting for unload from workflow engine");
            }

            UpdateWorkflowState(workflow, instance.Result, transition);
        }
        /// <summary>
        /// Processes the specified workflow, executing the specified <paramref name="transition"/> with the given <paramref name="request"/>
        /// </summary>
        /// <param name="workflow">The workflow.</param>
        /// <param name="transition">The transition.</param>
        /// <param name="request">The request.</param>
        public void Process(WorkflowInstance workflow, WorkflowTransition transition, WorkflowRequest request)
        {
            Log.Debug($"Process({workflow}, {transition}, {request})");
            //TODO: Block concurrent calls to Start/Process?
            Unloaded.Reset();
            Result      = new WorkflowResult();
            Application = CreateWorkflowApplication(workflow, false);
            //UnloadApplication(Application);
            if (!CheckForRunnableInstance())
            {
                Application.Load(workflow.InstanceId);
            }
            else
            {
                Application.LoadRunnableInstance();
            }

            Application.ResumeBookmark(transition.Name, request);
        }
        public virtual ActionResult New(string operation,
                                        string workflowTypeCode = "",
                                        string workflowTypeName = "",
                                        string entityType       = "",
                                        int entityId            = 0)
        {
            Logger.GetLogger().WriteDebug("WorkflowController",
                                          "Method: New | operation number " + operation);
            WorkflowRequest workflowRequest     = new WorkflowRequest();
            var             validatorsHappyRoad = new List <DetailValidatorModel>();
            var             Mapper               = new ValidatorsViewModelMapper();
            var             validatorTaskStart   = new List <ValidatorViewModel>();
            var             getHappyRoadResponse = new ResponseBase()
            {
                IsValid = false
            };
            var responseWokflowType = new WorkflowTypeResponse();

            responseWokflowType.WorkflowType = new WorkflowViewModel
            {
                InstructionsIncluded = true,
                CanAddValidator      = true,
                Validators           = new List <ValidatorViewModel>(),
                UserComments         = new List <UserCommentViewModel>(),
            };

            if (!TempData.ContainsKey("workflowRequest"))
            {
                if (string.IsNullOrEmpty(workflowTypeCode) ||
                    string.IsNullOrEmpty(entityType) ||
                    entityId != 0)
                {
                    workflowRequest.WorkflowCode    = workflowTypeCode;
                    workflowRequest.EntityType      = entityType;
                    workflowRequest.EntityId        = entityId;
                    workflowRequest.ModuleName      = K2IntegrationWorkflowConst.External;
                    workflowRequest.Whit2k          = false;
                    workflowRequest.OperationNumber = operation;
                    workflowRequest.ReturnURL       = Request.UrlReferrer.ToString();
                    workflowRequest.ReturnURLCancel = Request.UrlReferrer.ToString();
                }
                else
                {
                    workflowRequest = new WorkflowRequest()
                    {
                        OperationNumber = operation,
                        WorkflowCode    = string.Empty,
                        EntityType      = string.Empty,
                        EntityId        = 0,
                        ModuleName      = string.Empty
                    };
                    ViewData["message"] = new MessageConfiguration()
                    {
                        Message   = "workflowRequest is not Contains in TempData",
                        Type      = "error",
                        AutoClose = false.ToString(),
                        Duration  = "5",
                    };
                    Logger.GetLogger().WriteError("WorkflowController", "workflowRequest is not Contains in TempData", new Exception("workflowRequest is not Contains in TempData"));
                }
            }
            else
            {
                workflowRequest = (WorkflowRequest)TempData["workflowRequest"];
            }

            var workflowType = WorkflowHelper.GetWorkflowTypeByCode(workflowRequest.WorkflowCode);

            if (!workflowType.IsValid)
            {
                workflowRequest = new WorkflowRequest()
                {
                    OperationNumber = operation,
                    WorkflowCode    = string.Empty,
                    EntityType      = string.Empty,
                    EntityId        = 0,
                    ModuleName      = string.Empty
                };
                ViewData["message"] = new MessageConfiguration()
                {
                    Message   = workflowType.ErrorMessage,
                    Type      = "error",
                    AutoClose = false.ToString(),
                    Duration  = "5",
                };
                Logger.GetLogger().WriteError("WorkflowController", workflowType.ErrorMessage, new Exception("Workflow Type no found"));
            }
            else
            {
                getHappyRoadResponse = WorkflowHelper.GetHappyRoad(null, workflowRequest.EntityType, operation, 1, workflowType.WorkflowType, ref validatorsHappyRoad);
            }

            if (getHappyRoadResponse.IsValid)
            {
                responseWokflowType = _workflowsService.GetWorkflowType(workflowRequest);
                responseWokflowType.WorkflowType.Validators = Mapper.ConvertHappyRoadValidatorsToViewModel(validatorsHappyRoad);
                var roles = _viewModelMapperHelper.GetListMasterData(CONVERGENCE_ROLES);
                validatorTaskStart.Add(responseWokflowType.WorkflowType.Validators.First());
                ViewBag.RetrieveListRoles   = _viewModelMapperHelper.RemoveUsedRole(validatorTaskStart, roles);
                ViewBag.firstTaskName       = responseWokflowType.WorkflowType.Validators.First().TaskName;
                ViewBag.SerializedViewModel = IDB.Presentation.MVC4.Helpers.PageSerializationHelper.SerializeObject(responseWokflowType.WorkflowType);
                responseWokflowType.WorkflowType.ContractNumber = workflowRequest.ContractNumber;
            }
            else
            {
                ViewBag.RetrieveListRoles   = new List <SelectListItem>();
                ViewBag.firstTaskName       = string.Empty;
                ViewBag.SerializedViewModel = string.Empty;

                ViewData["message"] = new MessageConfiguration()
                {
                    Message   = getHappyRoadResponse.ErrorMessage,
                    Type      = "error",
                    AutoClose = false.ToString(),
                    Duration  = "5",
                };
                Logger.GetLogger().WriteError("WorkflowController", workflowType.ErrorMessage, new Exception("Error getting the happy road"));
            }

            return(View("WorkflowNew", responseWokflowType.WorkflowType));
        }
        /// <summary>
        /// Processes the specified activity.
        /// </summary>
        /// <param name="activity">The activity.</param>
        /// <param name="workflow">The workflow.</param>
        /// <param name="transition">The transition.</param>
        /// <param name="request">The request.</param>
        /// <param name="timeout">The timeout.</param>
        public void Process(Activity activity, IWorkflow workflow, WorkflowTransition transition, WorkflowRequest request, TimeSpan timeout)
        {
            //Guard.AgainstNull(() => activity);
            //Guard.AgainstNull(() => workflow);
            //Guard.AgainstNull(() => transition);
            //Guard.AgainstNull(() => request);

            var instance = new IntellitideWorkflowInstance(activity, FrameworkEnvironment.Instance.Container);

            using (new TransactionScope(TransactionScopeOption.Suppress))
            {
                instance.Process(workflow, transition, request);
                if (!instance.WaitOne(timeout))
                {
                    throw new TimeoutException("Timeout waiting for unload from workflow engine");
                }
            }
            UpdateWorkflowState(workflow, instance.Result, transition);
        }
Exemple #26
0
        private void WorkflowTimer(Object state)
        {
            if (executing)
            {
                return;
            }

            executing = true;

            startTime = DateTime.Now;

            try
            {
                IAMDatabase db = null;
                try
                {
                    db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);
                    db.openDB();
                    db.Timeout = 900;

                    DataTable dtRequests = db.ExecuteDataTable("select id, workflow_id from [st_workflow_request] r with(nolock) where r.deployed = 0 order by r.create_date");
                    if ((dtRequests != null) && (dtRequests.Rows.Count > 0))
                    {
                        try
                        {
                            TextLog.Log("WorkflowProcessor", "Starting workflow processor timer");

                            foreach (DataRow dr in dtRequests.Rows)
                            {
                                try
                                {
                                    WorkflowRequest request = new WorkflowRequest((Int64)dr["id"]);
                                    request.GetInicialData(db);

                                    WorkflowConfig workflow = new WorkflowConfig();
                                    workflow.GetDatabaseData(db, (Int64)dr["workflow_id"]);

                                    switch (request.Status)
                                    {
                                    case WorkflowRequestStatus.Deny:
                                    case WorkflowRequestStatus.Expired:
                                    case WorkflowRequestStatus.UserCanceled:
                                        //Somente atualiza como deployed, para não ficar verificando
                                        db.ExecuteNonQuery("update [st_workflow_request] set deployed = 1 where id = " + dr["id"]);
                                        continue;
                                        break;

                                    case WorkflowRequestStatus.Waiting:
                                        //Verifica escalation
                                        DateTime escalation = request.ActivityCreated.AddDays(request.Activity.EscalationDays);
                                        DateTime expired    = request.ActivityCreated.AddDays(request.Activity.ExpirationDays);
                                        if (expired.CompareTo(DateTime.Now) < 0)
                                        {
                                            request.SetStatus(db, WorkflowRequestStatus.Escalated, request.UserId);
                                            db.ExecuteNonQuery("update [st_workflow_request] set deployed = 1 where id = " + dr["id"]);
                                        }
                                        else if (escalation.CompareTo(DateTime.Now) < 0)
                                        {
                                            request.SetStatus(db, WorkflowRequestStatus.Escalated, request.UserId);
                                            db.ExecuteNonQuery("update [st_workflow_request] set deployed = 1 where id = " + dr["id"]);
                                        }
                                        break;

                                    case WorkflowRequestStatus.Escalated:
                                        //Verifica escalation
                                        DateTime expired2 = request.ActivityCreated.AddDays(request.Activity.ExpirationDays);
                                        if (expired2.CompareTo(DateTime.Now) < 0)
                                        {
                                            request.SetStatus(db, WorkflowRequestStatus.Expired, request.UserId);
                                            db.ExecuteNonQuery("update [st_workflow_request] set deployed = 1 where id = " + dr["id"]);
                                        }
                                        break;

                                    case WorkflowRequestStatus.Approved:
                                        //Somente executa alguma ação quando não há mais nenhuma atividade a ser executada
                                        if (request.NextActivity == null)
                                        {
                                            switch (workflow.AccessType)
                                            {
                                            case WorkflowAccessType.RoleGrant:
                                                WorkflowAccessRoleGrant rg = (WorkflowAccessRoleGrant)workflow.Access;
                                                //Seleciona todas as identidades do usuário e adiciona na role

                                                DataTable drIdent = db.ExecuteDataTable("select i.* from [identity] i with(nolock) inner join resource_plugin rp with(nolock) on i.resource_plugin_id = rp.id where rp.enable_import = 1 and rp.permit_add_entity = 1 and i.entity_id = " + request.UserId);
                                                if ((drIdent == null) || (drIdent.Rows.Count == 0))
                                                {
                                                    using (DbParameterCollection par2 = new DbParameterCollection())
                                                    {
                                                        par2.Add("@workflow_request_id", typeof(Int64)).Value   = request.RequestId;
                                                        par2.Add("@status", typeof(String)).Value               = (Int32)request.Status;
                                                        par2.Add("@description", typeof(String)).Value          = "No inbound identity found for allow access";
                                                        par2.Add("@activity_id", typeof(Int64)).Value           = request.Activity.ActivityId;
                                                        par2.Add("@executed_by_entity_id", typeof(Int64)).Value = request.LastExecutedBy;

                                                        db.ExecuteNonQuery("INSERT INTO [st_workflow_request_status]([workflow_request_id],[status],[description],[executed_by_entity_id],[activity_id])VALUES(@workflow_request_id,@status,@description,@executed_by_entity_id,@activity_id)", CommandType.Text, par2, null);
                                                    }
                                                }
                                                else
                                                {
                                                    //Lista o nome e id de todas as roles que serão utilizadas
                                                    List <String> roleList = new List <String>();
                                                    foreach (Int64 r in rg.Roles)
                                                    {
                                                        roleList.Add(r.ToString());
                                                    }

                                                    DataTable drRoles = db.ExecuteDataTable("select * from [role] where id in (" + String.Join(",", roleList) + ")");
                                                    if ((drRoles == null) || (drRoles.Rows.Count == 0))
                                                    {
                                                        using (DbParameterCollection par2 = new DbParameterCollection())
                                                        {
                                                            par2.Add("@workflow_request_id", typeof(Int64)).Value   = request.RequestId;
                                                            par2.Add("@status", typeof(String)).Value               = (Int32)request.Status;
                                                            par2.Add("@description", typeof(String)).Value          = "No role found for allow access";
                                                            par2.Add("@activity_id", typeof(Int64)).Value           = request.Activity.ActivityId;
                                                            par2.Add("@executed_by_entity_id", typeof(Int64)).Value = request.LastExecutedBy;

                                                            db.ExecuteNonQuery("INSERT INTO [st_workflow_request_status]([workflow_request_id],[status],[description],[executed_by_entity_id],[activity_id])VALUES(@workflow_request_id,@status,@description,@executed_by_entity_id,@activity_id)", CommandType.Text, par2, null);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        String roleNames = "";

                                                        //Adiciona as roles
                                                        foreach (DataRow dr2 in drIdent.Rows)
                                                        {
                                                            foreach (DataRow drRole in drRoles.Rows)
                                                            {
                                                                DbParameterCollection par = new DbParameterCollection();
                                                                par.Add("@identity_id", typeof(Int64)).Value = dr2["id"];
                                                                par.Add("@role_id", typeof(Int64)).Value     = drRole["id"];

                                                                Boolean added = db.ExecuteScalar <Boolean>("sp_insert_identity_role", CommandType.StoredProcedure, par);

                                                                if (added)
                                                                {
                                                                    roleNames += drRole["name"] + Environment.NewLine;
                                                                }
                                                            }
                                                        }

                                                        if (roleNames != null)
                                                        {
                                                            db.AddUserLog(LogKey.User_IdentityRoleBind, null, "Workflow", UserLogLevel.Info, 0, 0, 0, 0, 0, request.UserId, 0, "Entity bind to roles by workflow access request", roleNames);
                                                        }


                                                        using (DbParameterCollection par2 = new DbParameterCollection())
                                                        {
                                                            par2.Add("@workflow_request_id", typeof(Int64)).Value   = request.RequestId;
                                                            par2.Add("@status", typeof(String)).Value               = (Int32)request.Status;
                                                            par2.Add("@description", typeof(String)).Value          = "Entity bind to roles";
                                                            par2.Add("@activity_id", typeof(Int64)).Value           = request.Activity.ActivityId;
                                                            par2.Add("@executed_by_entity_id", typeof(Int64)).Value = request.LastExecutedBy;

                                                            db.ExecuteNonQuery("INSERT INTO [st_workflow_request_status]([workflow_request_id],[status],[description],[executed_by_entity_id],[activity_id])VALUES(@workflow_request_id,@status,@description,@executed_by_entity_id,@activity_id)", CommandType.Text, par2, null);
                                                        }
                                                    }
                                                }

                                                db.ExecuteNonQuery("update [st_workflow_request] set deployed = 1 where id = " + dr["id"]);
                                                break;
                                            }
                                        }
                                        break;

                                    case WorkflowRequestStatus.Revoked:
                                        //Remove as permissões dadas
                                        switch (workflow.AccessType)
                                        {
                                        case WorkflowAccessType.RoleGrant:
                                            WorkflowAccessRoleGrant rg = (WorkflowAccessRoleGrant)workflow.Access;

                                            //Lista o nome e id de todas as roles que serão utilizadas
                                            List <String> roleList = new List <String>();
                                            foreach (Int64 r in rg.Roles)
                                            {
                                                roleList.Add(r.ToString());
                                            }

                                            String log = "";

                                            DataTable drRoles = db.ExecuteDataTable("select distinct ir.*, r.name role_name from [role] r with(nolock) inner join identity_role ir with(nolock) on ir.role_id = r.id inner join [identity] i with(nolock) on ir.identity_id = i.id where i.entity_id = " + request.UserId + " and r.id in (" + String.Join(",", roleList) + ")");
                                            if ((drRoles != null) && (drRoles.Rows.Count > 0))
                                            {
                                                foreach (DataRow dr2 in drRoles.Rows)
                                                {
                                                    log += "Identity unbind to role " + dr2["role_name"] + Environment.NewLine;

                                                    db.AddUserLog(LogKey.User_IdentityRoleUnbind, null, "Workflow", UserLogLevel.Info, 0, 0, 0, 0, 0, request.UserId, (Int64)dr2["identity_id"], "Identity unbind to role " + dr2["role_name"]);
                                                    db.ExecuteNonQuery("delete from identity_role where identity_id = " + dr2["identity_id"] + " and role_id = " + dr2["role_id"], CommandType.Text, null);
                                                }

                                                using (DbParameterCollection par2 = new DbParameterCollection())
                                                {
                                                    par2.Add("@workflow_request_id", typeof(Int64)).Value   = request.RequestId;
                                                    par2.Add("@status", typeof(String)).Value               = (Int32)request.Status;
                                                    par2.Add("@description", typeof(String)).Value          = log;
                                                    par2.Add("@activity_id", typeof(Int64)).Value           = request.Activity.ActivityId;
                                                    par2.Add("@executed_by_entity_id", typeof(Int64)).Value = request.LastExecutedBy;

                                                    db.ExecuteNonQuery("INSERT INTO [st_workflow_request_status]([workflow_request_id],[status],[description],[executed_by_entity_id],[activity_id])VALUES(@workflow_request_id,@status,@description,@executed_by_entity_id,@activity_id)", CommandType.Text, par2, null);
                                                }
                                            }
                                            else
                                            {
                                                using (DbParameterCollection par2 = new DbParameterCollection())
                                                {
                                                    par2.Add("@workflow_request_id", typeof(Int64)).Value   = request.RequestId;
                                                    par2.Add("@status", typeof(String)).Value               = (Int32)request.Status;
                                                    par2.Add("@description", typeof(String)).Value          = "No permission to remove";
                                                    par2.Add("@activity_id", typeof(Int64)).Value           = request.Activity.ActivityId;
                                                    par2.Add("@executed_by_entity_id", typeof(Int64)).Value = request.LastExecutedBy;

                                                    db.ExecuteNonQuery("INSERT INTO [st_workflow_request_status]([workflow_request_id],[status],[description],[executed_by_entity_id],[activity_id])VALUES(@workflow_request_id,@status,@description,@executed_by_entity_id,@activity_id)", CommandType.Text, par2, null);
                                                }
                                            }

                                            db.ExecuteNonQuery("update [st_workflow_request] set deployed = 1 where id = " + dr["id"]);
                                            break;
                                        }
                                        break;

                                    case WorkflowRequestStatus.UnderReview:
                                        //Nada
                                        break;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    db.AddUserLog(LogKey.Workflow, null, "Workflow", UserLogLevel.Info, 0, 0, 0, 0, 0, 0, 0, "Workflow proccess error", ex.Message);
                                }
                            }
                        }
                        finally
                        {
                            if (db != null)
                            {
                                db.Dispose();
                            }

                            TextLog.Log("WorkflowProcessor", "Finishing workflow processor timer");
                        }
                    }

                    db.closeDB();
                }
                finally
                {
                    if (db != null)
                    {
                        db.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                TextLog.Log("WorkflowProcessor", "Error on message timer " + ex.Message);
            }
            finally
            {
                executing   = false;
                last_status = "";
                startTime   = new DateTime(1970, 1, 1);
            }
        }
        public static void ProcessWorkflow(this RigOapChecklist rigOapChecklist, IRigOapChecklistWorkflowService rigOapChecklistWorkflowService, IWorkflowEngineService workflowEngineService, IWorkflowService workflowService, WorkflowTransition transition, WorkflowRequest request, ILog log)
        {
            var workflow = workflowService.GetActiveWorkflow(rigOapChecklist.OapChecklist.OapType.ChecklistLayoutId.Value);

            //Create the Workflow Activity
            var workflowActivity = workflow.GetActivity(rigOapChecklist.Id);

            if (workflowActivity == null)
            {
                log.Error($" Workflow Activity was not found for checklist : { rigOapChecklist.Id}");
                return;
            }

            //Create the RigOapChecklistWorkflow instance
            var rigChecklistWorkflow = rigOapChecklistWorkflowService.GetWorkflowByChecklist(rigOapChecklist.Id);

            if (rigChecklistWorkflow == null)
            {
                log.Error($" Workflow instance was not found for checklist : { rigOapChecklist.Id}");
                return;
            }

            var version = new Version(workflow.Major, workflow.Minor);

            //Start the Workflow Instance and All the store the instance details

            //Get the Current Principal And Assign Him to Workflow to
            workflowEngineService.Process(workflowActivity, version, rigChecklistWorkflow, transition, request);
        }
Exemple #28
0
        /// <summary>
        /// Método privado para processamento do método 'user.resetpassword'
        /// </summary>
        /// <param name="sqlConnection">Conexão com o banco de dados MS-SQL</param>
        /// <param name="parameters">Dicionário (String, Object) contendo todos os parâmetros necessários</param>
        private List <Object> accessrequestlist(IAMDatabase database, Dictionary <String, Object> parameters)
        {
            List <Object> result = new List <Object>();

            DbParameterCollection par = new DbParameterCollection();

            par.Add("@enterprise_id", typeof(Int64)).Value = this._enterpriseId;

            Int32 page     = 1;
            Int32 pageSize = 10;

            if (parameters.ContainsKey("page"))
            {
                Int32.TryParse(parameters["page"].ToString(), out page);
            }

            if (parameters.ContainsKey("page_size"))
            {
                Int32.TryParse(parameters["page_size"].ToString(), out pageSize);
            }

            if (pageSize < 1)
            {
                pageSize = 1;
            }

            if (page < 1)
            {
                page = 1;
            }

            Int32 rStart = ((page - 1) * pageSize) + 1;
            Int32 rEnd   = rStart + (pageSize - 1);

            /*
             * select * from st_workflow_request r with(nolock)
             * inner join entity e  with(nolock) on e.id = r.entity_id
             * inner join context c  with(nolock) on c.id = e.context_id
             * */
            String sql = "";

            sql += "WITH result_set AS (";
            sql += "  SELECT ";
            sql += "    ROW_NUMBER() OVER (ORDER BY r.create_date) AS [row_number], r.*, e.context_id, c.enterprise_id, e.full_name, e.login";
            sql += "     from st_workflow_request r with(nolock)  ";
            sql += "     inner join entity e  with(nolock) on e.id = r.entity_id   ";
            sql += "     inner join context c  with(nolock) on c.id = e.context_id  ";
            sql += "     where (c.enterprise_id = @enterprise_id ";

            if ((parameters.ContainsKey("filter")) && (parameters["filter"] is Dictionary <String, Object>))
            {
                Dictionary <String, Object> filter = (Dictionary <String, Object>)parameters["filter"];
                foreach (String k in filter.Keys)
                {
                    switch (k.ToLower())
                    {
                    case "text":
                        if (!String.IsNullOrWhiteSpace(filter["text"].ToString()))
                        {
                            par.Add("@text", typeof(String)).Value = filter["text"].ToString();
                            sql += " and (e.full_name like '%'+@text+'%' or e.login like '%'+@text+'%' or r.description like '%'+@text+'%')";
                        }
                        break;

                    case "contextid":
                        if (!String.IsNullOrWhiteSpace(filter["contextid"].ToString()))
                        {
                            try
                            {
                                Int64 tmp = Int64.Parse(filter["contextid"].ToString());
                                par.Add("@context_id", typeof(Int64)).Value = tmp;
                                sql += " and c.id = @context_id";
                            }
                            catch { }
                        }
                        break;

                    case "workflowid":
                        if (!String.IsNullOrWhiteSpace(filter["workflowid"].ToString()))
                        {
                            try
                            {
                                Int64 tmp = Int64.Parse(filter["workflowid"].ToString());
                                par.Add("@workflow_id", typeof(Int64)).Value = tmp;
                                sql += " and r.workflow_id = @workflow_id";
                            }
                            catch { }
                        }
                        break;

                    case "status":
                        if (!String.IsNullOrWhiteSpace(filter["status"].ToString()))
                        {
                            try
                            {
                                WorkflowRequestStatus tmp = (WorkflowRequestStatus)Int32.Parse(filter["status"].ToString());
                                par.Add("@status", typeof(Int32)).Value = (Int32)tmp;
                                sql += " and r.status = @status";
                            }
                            catch { }
                        }
                        break;
                    }
                }
            }

            sql += "     )";
            sql += ") SELECT";
            sql += "  *";
            sql += " FROM";
            sql += "  result_set";
            sql += " WHERE";
            sql += "  [row_number] BETWEEN " + rStart + " AND " + rEnd;

            DataTable dtRequest = database.ExecuteDataTable(sql, CommandType.Text, par, null);

            if ((dtRequest != null) && (dtRequest.Rows.Count > 0))
            {
                foreach (DataRow dr1 in dtRequest.Rows)
                {
                    using (IAMRBAC rbac = new IAMRBAC())
                        if (!rbac.UserAdmin(database, Acl.EntityId, this._enterpriseId))
                        {
                            using (WorkflowRequest request = new WorkflowRequest((Int64)dr1["id"]))
                            {
                                WorkflowRequestProccess proc = request.GetInicialData(database);
                                if (!proc.Success)
                                {
                                    Error(ErrorType.InternalError, proc.Message, proc.Debug, null);
                                    return(null);
                                }

                                if (!database.ExecuteScalar <Boolean>("select case when COUNT(*) > 0 then CAST(1 as bit) else CAST(0 as bit) end from entity e with(nolock) where e.id = " + Acl.EntityId + " and (e.id in (" + request.Workflow.Owner + "," + request.Activity.ManualApproval.EntityApprover + ") or e.id in (select i.entity_id from identity_role ir with(nolock) inner join [identity] i with(nolock) on i.id = ir.identity_id where ir.role_id = " + request.Activity.ManualApproval.RoleApprover + "))", CommandType.Text, null))
                                {
                                    continue;
                                }
                            }
                        }

                    Dictionary <string, object> newItem = new Dictionary <string, object>();
                    newItem.Add("access_request_id", dr1["id"]);
                    newItem.Add("userid", dr1["entity_id"]);
                    newItem.Add("context_id", dr1["context_id"]);
                    newItem.Add("enterprise_id", dr1["enterprise_id"]);
                    newItem.Add("workflow_id", dr1["workflow_id"]);
                    newItem.Add("status", dr1["status"]);
                    newItem.Add("description", dr1["description"]);
                    newItem.Add("entity_full_name", dr1["full_name"]);
                    newItem.Add("entity_login", dr1["login"]);
                    newItem.Add("deployed", dr1["deployed"]);
                    newItem.Add("start_date", (dr1["start_date"] != DBNull.Value ? (Int32)((((DateTime)dr1["start_date"]) - new DateTime(1970, 1, 1)).TotalSeconds) : 0));
                    newItem.Add("end_date", (dr1["end_date"] != DBNull.Value ? (Int32)((((DateTime)dr1["end_date"]) - new DateTime(1970, 1, 1)).TotalSeconds) : 0));
                    newItem.Add("create_date", (dr1["create_date"] != DBNull.Value ? (Int32)((((DateTime)dr1["create_date"]) - new DateTime(1970, 1, 1)).TotalSeconds) : 0));

                    WorkflowConfig wk = new WorkflowConfig();
                    wk.GetDatabaseData(database, (Int64)dr1["workflow_id"]);

                    newItem.Add("workflow", wk.ToJsonObject());

                    result.Add(newItem);
                }
            }

            return(result);
        }