Exemplo n.º 1
0
 /// <summary>
 /// Creates a new TaskStatus. This constructor is designed for If/While and Switch flowchart tasks.
 /// </summary>
 /// <param name="status">Status.</param>
 /// <param name="condition">Condition value.</param>
 /// <param name="switchValue">Switch value.</param>
 public TaskStatus(Status status, bool condition, string switchValue, Task task, RequestModel model, string serviceResponse, WorkflowConfig workflowConfig)
 {
     _workflowConfig = workflowConfig;
     AddEndTaskLog(task, model, Status, TaskType.While, serviceResponse);
     Condition   = condition;
     SwitchValue = switchValue;
 }
        /// <summary>
        /// This function permits to create an instance
        /// </summary>
        /// <param name="workflowConfig">WorkflowConfig origne</param>
        /// <param name="dataSet">DataSet associé</param>
        /// <param name="UserSet">UserSet associé</param>
        /// <returns>Task</returns>
        public async Task <WorkflowInstance> CreateInstance(WorkflowConfig workflowConfig, DataSet dataSet, UserSet UserSet)
        {
            // Contrôles
            if (workflowConfig == null)
            {
                throw new InitialiseWorkflowException("Process: no WorkflowConfig! Impossible to continue.");
            }
            if (dataSet == null)
            {
                throw new InitialiseWorkflowException("Process: no DataSet! Impossible to continue.");
            }
            if (UserSet == null)
            {
                throw new InitialiseWorkflowException("Process: no UserSet! Impossible to continue.");
            }

            // On duplique la configuration du workflow (WOR-222)
            WorkflowConfig duplWf = await WorkflowConfig.CopyForStatic(workflowConfig);

            WorkflowInstance newInstance = await Add(
                new WorkflowInstance()
            {
                Name           = workflowConfig.Name,
                WorkflowConfig = duplWf,
                DataSetId      = dataSet.Id,
                UserSetId      = UserSet.Id,
                AddedDate      = DateTime.UtcNow,
                Status         = WorkflowStateEnum.Current,
            });

            // Initialise le DataSet
            int nbr = await DataSetDomain.InitializeData(dataSet);

            return(newInstance);
        }
Exemplo n.º 3
0
 public override TaskStatus Run(WorkflowConfig workflowConfig, RequestModel model = null)
 {
     return(new RunTask().Run(
                GetSetting("پارامتر"),
                GetSetting("مشخصات سرویس"),
                this,
                workflowConfig,
                model));
 }
Exemplo n.º 4
0
        public void Constructor_WorkflowConfigExists_ReturnsTrue()
        {
            var workflow = new WorkflowConfig("a", null);
            var runner   = new DaprWorkflowExecutor(new List <WorkflowConfig>()
            {
                workflow
            }, null);
            var exists = runner.WorkflowExists("a");

            Assert.True(exists);
        }
Exemplo n.º 5
0
        public void Constructor_WorkflowConfigDoesntExist_RetursFalse()
        {
            var workflow = new WorkflowConfig("a", null);
            var runner   = new DaprWorkflowExecutor(new List <WorkflowConfig>()
            {
                workflow
            }, null);
            var exists = runner.WorkflowExists("b");

            Assert.False(exists);
        }
Exemplo n.º 6
0
        public string GetWorkflowXML(string shortName)
        {
            //string workflowXml = workflowDef.GetWorkFlowDef(shortName).WD_CONTENT;
            //WorkflowConfig workflowConfig = XmlUtil.ReadFromString<WorkflowConfig>(workflowXml);
            //workflowConfig.Steps.ToList().ForEach(a => a.Parent = workflowConfig);

            var workflowConfig = WorkflowConfig.GetByName(shortName, context);

            Root root = WorkflowConfig2Root(workflowConfig);

            return(root.SaveString(Formatting.None));
        }
Exemplo n.º 7
0
        /// <summary>
        /// Creates a new instance of workflow engine.
        /// </summary>
        /// <param name="settingsFile">Settings file path.</param>
        public WorkflowEngine(Configuration configuration, WorkflowConfig workflowConfig, bool?doLoadHistory = null)
        {
            _workflowConfig = workflowConfig;
            _configuration  = configuration;
            Workflows       = new List <Workflow>();
            _workflowTimers = new Dictionary <int, List <workflowTimer> >();

            Logger.Info("");
            Logger.Info("Starting workflow Engine");

            LoadSettings();
            LoadWorkflows(doLoadHistory);
        }
Exemplo n.º 8
0
        private static WorkflowConfig GetConfig(string payload)
        {
            var tree = WorkflowConfigParser.ParseString(new System.Text.StringBuilder(payload));

            WorkflowConfigVisitor visitor = new WorkflowConfigVisitor()
                                            .AddRule("IsMajor", typeof(ParserUnitTest).GetMethod("IsMajor"))
                                            .AddRule("IsEmpty", typeof(ParserUnitTest).GetMethod("IsEmpty"))
            ;

            visitor.Filename = "memory text";
            WorkflowConfig config = (WorkflowConfig)tree.Visit <object>(visitor);

            return(config);
        }
Exemplo n.º 9
0
        private void InstallCustomWorkflow(SiteInitializer initializer)
        {
            WorkflowConfig workflowConfig = initializer.Context.GetConfig <WorkflowConfig>();

            if (!workflowConfig.Workflows.ContainsKey(typeof(RealEstateItem).FullName))
            {
                workflowConfig.Workflows.Add(
                    new WorkflowElement(workflowConfig.Workflows)
                {
                    ContentType     = typeof(RealEstateItem).FullName,
                    ServiceUrl      = WorkflowConfig.GetDefaultWorkflowUrl(typeof(RealEstateItem)),
                    Title           = "ModuleTitle",
                    ResourceClassId = typeof(RealEstateResources).Name
                });
            }
        }
Exemplo n.º 10
0
        //-1重名,-2 异常,返回其他(id)正常成功
        public string AddOrEditWorkflowDefine(WorkflowConfig config)
        {
            try
            {
                var workflow = context.WF_WORKFLOW_DEF.FirstOrDefault <WF_WORKFLOW_DEF>(m => m.WD_ID == config.Id);
                if (workflow != null)
                {
                    workflow.WD_DESCRIPTION = config.Description;
                    workflow.WD_CONTENT     = config.SaveString();
                    workflow.WD_DESCRIPTION = config.Description;
                    workflow.WD_NAME        = config.DisplayName;
                    workflow.WD_UPDATE_DATE = context.Now;
                    workflow.WD_UPDATE_ID   = GlobalVariable.UserId.ToString();
                    context.SaveChanges();
                    return(workflow.WD_ID);
                }
                else
                {
                    WF_WORKFLOW_DEF def = new WF_WORKFLOW_DEF();
                    //如重名,返回-1
                    if (context.WF_WORKFLOW_DEF.FirstOrDefault <WF_WORKFLOW_DEF>(m => m.WD_SHORT_NAME == config.Name) != null)
                    {
                        return("-1");
                    }
                    def.WD_ID          = context.GetUniId();
                    config.Id          = def.WD_ID;
                    def.WD_CONTENT     = config.SaveString();
                    def.WD_CREATE_DATE = context.Now;
                    def.WD_CREATE_ID   = GlobalVariable.UserId.ToString();
                    def.WD_DESCRIPTION = config.Description;
                    def.WD_IS_USED     = 1;
                    def.WD_NAME        = config.DisplayName;
                    def.WD_SHORT_NAME  = config.Name;
                    def.WD_UPDATE_DATE = context.Now;
                    def.FControlUnitID = GlobalVariable.FControlUnitID;
                    def.WD_UPDATE_ID   = GlobalVariable.UserId.ToString();

                    context.WF_WORKFLOW_DEF.Add(def);
                    context.SaveChanges();
                    return(def.WD_ID);
                }
            }
            catch
            {
                return("-2");
            }
        }
Exemplo n.º 11
0
        public static WorkflowConfig AddFilter(this WorkflowConfig self, string eventName, string targetStateName, Func <RunContext, bool> rule)
        {
            if (!self.Initializers.TryGetValue(eventName, out InitializationOnEventConfig o))
            {
                self.Initializers.Add(eventName, o = new InitializationOnEventConfig()
                {
                    EventName = eventName
                });
            }

            o.Switchs.Add(new InitializationConfig()
            {
                TargetStateName = targetStateName, WhenRule = rule
            });

            return(self);
        }
        /// <summary>
        /// Ajoute un WorkflowDimension à un WorkflowConfig
        /// </summary>
        /// <param name="workflowConfigId">Id du WorkflowConfig cible</param>
        /// <param name="workflowDimension">WorkflowDimension</param>
        /// <returns>Message de retour</returns>
        public async Task <WorkflowDimension> AddWorkflowDimension(long workflowConfigId, WorkflowDimension workflowDimension)
        {
            if (workflowDimension == null)
            {
                throw new WrongParameterException("WorkflowDimensionDomain.AddWorkflowDimension: WorkflowDimension is null!");
            }
            if (workflowDimension.Dimension == null)
            {
                throw new WrongParameterException("WorkflowDimensionDomain.AddWorkflowDimension: Dimension of WorkflowDimension is null!");
            }
            int cnt = await UnitOfWork.GetDbContext().Dimension
                      .Where(d => d.Id == workflowDimension.Dimension.Id)
                      .AsNoTracking()
                      .ToAsyncEnumerable()
                      .Count();

            if (cnt < 1)
            {
                throw new WrongParameterException($"WorkflowDimensionDomain.AddWorkflowDimension: No Dimension (id = {workflowDimension.Dimension.Id}) for WorkflowDimension!");
            }

            WorkflowConfig wfConf = await UnitOfWork.GetDbContext().WorkflowConfig
                                    .Where(wfc => wfc.Id == workflowConfigId)
                                    .FirstOrDefaultAsync();

            if (wfConf == null)
            {
                throw new WrongParameterException($"WorkflowDimensionDomain.AddWorkflowDimension: WorkflowConfig unknown for this id ({workflowConfigId})!");
            }

            UnitOfWork.WorkflowConfigRepository.PrepareUpdateForObject(wfConf);
            UnitOfWork.WorkflowDimensionRepository.PrepareAddForObject(workflowDimension);

            wfConf.WorkflowDimension.Add(workflowDimension);
            workflowDimension.WorkflowConfig = wfConf;

            int nbr = await UnitOfWork.GetDbContext().SaveChangesAsync();

            if (nbr <= 0)
            {
                throw new DatabaseException("WorkflowDimensionDomain.AddWorkflowDimension: impossible to save WorkflowDimension.");
            }

            return(workflowDimension);
        }
        private void InstallCustomWorkflow(SiteInitializer initializer)
        {
            WorkflowConfig workflowConfig = initializer.Context.GetConfig <WorkflowConfig>();

            if (!workflowConfig.Workflows.ContainsKey(typeof(AgentItem).FullName))
            {
                workflowConfig.Workflows.Add(
                    new WorkflowElement(workflowConfig.Workflows)
                {
                    ContentType     = typeof(AgentItem).FullName,
                    ServiceUrl      = WorkflowConfig.GetDefaultWorkflowUrl(typeof(AgentItem)),
                    Title           = "ModuleTitle",
                    ResourceClassId = typeof(AgentsResources).Name
                });
            }

            //initializer.InstallEmbeddedVirtualPath(WorkflowRelativeUrl, WorkflowEmbeddedPath, typeof(AgentsModule).Assembly);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Ajoute un configuration de grid.
        /// </summary>
        /// <param name="gridConfig">Nouvelle configuration de grid</param>
        /// <param name="workflowConfigId">Id du workflowConfig auquel lier la nouvelle configuration de grid</param>
        /// <returns>Message de retour</returns>
        public async Task <GridConfig> Add(long workflowConfigId, GridConfig gridConfig)
        {
            if (gridConfig == null)
            {
                throw new WrongParameterException("GridConfigurationDomain.Add : GridConfig is null.");
            }
            if (string.IsNullOrWhiteSpace(gridConfig.Name))
            {
                throw new WrongParameterException("GridConfigurationDomain.Add : GridConfig's name is null.");
            }
            int cnt = await UnitOfWork.GetDbContext().GridConfig
                      .Where(gc => gc.Name == gridConfig.Name)
                      .AsNoTracking()
                      .ToAsyncEnumerable()
                      .Count();

            if (cnt > 0)
            {
                throw new WrongParameterException($"GridConfigurationDomain.Add : GridConfig's name ({gridConfig.Name}) is not unique.");
            }

            WorkflowConfig wfConf = await UnitOfWork.GetDbContext().WorkflowConfig
                                    .Where(wfc => wfc.Id == workflowConfigId)
                                    .FirstOrDefaultAsync();

            if (wfConf == null)
            {
                throw new WrongParameterException($"GridConfigurationDomain.Add : WorkflowConfig don't exist (id = {workflowConfigId}).");
            }

            UnitOfWork.GridConfigRepository.PrepareAddForObject(gridConfig);

            gridConfig.WorkflowConfig = wfConf;

            int nbr = await UnitOfWork.GetDbContext().SaveChangesAsync();

            if (nbr <= 0)
            {
                throw new DatabaseException("GridConfigurationDomain.Add : impossible to save GridConfig.");
            }

            return(gridConfig);
        }
        /// <summary>
        /// Ajoute un SelectorConfig en base.
        /// </summary>
        /// <param name="selectConf">SelectorConfig à ajouter</param>
        /// <returns>Message du résultat</returns>
        /// <remarks>L'objet SelectorConfig doit connaitre l'id de son WorkflowConfig parent. De plus, il doit avoir un nom unique.
        /// L'opération sort en erreur si l'une des deux conditions, ou les deux, n'est pas respectée.</remarks>
        public override async Task <SelectorConfig> Add(SelectorConfig selectConf)
        {
            // Création de la transaction
            using (IDbContextTransaction transaction = UnitOfWork.GetDbContext().Database.BeginTransaction())
            {
                // Vérifications
                if (selectConf == null)
                {
                    throw new WrongParameterException("SelectorConfig object is null!");
                }
                if (selectConf.WorkflowConfig == null)
                {
                    throw new DataLoadingException("SelectorConfig.WorkflowConfig don't load!");
                }
                WorkflowConfig wfConf = await UnitOfWork.WorkflowConfigRepository.GetById(selectConf.WorkflowConfig.Id);

                if (wfConf == null)
                {
                    throw new WrongParameterException("WorkflowConfig id doesn't exist!");
                }
                if (string.IsNullOrWhiteSpace(selectConf.Name))
                {
                    throw new WrongParameterException("SelectorConfig haven't a name!");
                }
                IEnumerable <SelectorConfig> duplicata = await UnitOfWork.GetDbContext().Set <SelectorConfig>().Include(i => i.WorkflowConfig).Where(s => (s.WorkflowConfig != null && s.WorkflowConfig.Id == wfConf.Id) && s.Name == selectConf.Name).ToAsyncEnumerable().ToList();

                if ((duplicata != null) && (duplicata.Count() > 0))
                {
                    throw new WrongParameterException("SelectorConfig's name exist already for this WorkflowConfig!");
                }

                // Ajout
                SelectorConfig addedSelectConf = await UnitOfWork.SelectorConfigRepository.Insert(selectConf);

                transaction.Commit();
                return(addedSelectConf);
            }
        }
Exemplo n.º 16
0
        public WorkflowConfig Root2WorkflowConfig(Root root)
        {
            WorkflowConfig config = new WorkflowConfig();

            config.Id            = root.ID;
            config.Name          = root.Name;
            config.DisplayName   = root.DisplayName;
            config.Description   = root.Description;
            config.Priority      = root.Priority.Value <WorkflowPriority>();
            config.IsSaveContent = root.IsSave == "1" ? true : false;
            config.ContentChoice = root.ContentChoice.Value <ConfigChoice>();
            config.ContentXml    = root.ManualPageXml ?? "";
            if (root.ControllActions != null)
            {
                config.ControlActions = new RegNameList <ControlActionConfig>();
                ControlActionConfig controllAction;
                foreach (ControllAction ca in root.ControllActions)
                {
                    controllAction             = new ControlActionConfig();
                    controllAction.ActionName  = ca.ActionName;
                    controllAction.AreaName    = ca.AreaName;
                    controllAction.ControlName = ca.ControllName;
                    controllAction.Order       = ca.Order;
                    controllAction.Title       = ca.Title == null ? "" : ca.Title;
                    controllAction.ShowKind    = ca.ShowKind.Value <ShowKind>();
                    config.ControlActions.Add(controllAction);
                }
            }
            for (int i = 0; i < root.LineList.Count; i++)
            {
                CreateLineNode(config, root, root.LineList[i]);
            }
            string gg = config.SaveString(Formatting.None);

            return(config);
        }
Exemplo n.º 17
0
        /// <inheriteddoc />
        protected override IEnumerable<WorkflowFunc> GetFunctions()
        {
            var occuredErrors = new List<Exception>();

            var current = _start; 
            var hasBeenCanceled = false;
            Exception lastError = null;
            object previousValue = null;
            object result = null;
            var throwErrors = true;
            object value = null;
            while (!hasBeenCanceled &&
                   current != null)
            {
                yield return (args) =>
                    {
                        var ctx = new WorkflowExecutionContext()
                            {
                                Arguments = args,
                                LastError = lastError,
                                PreviousValue = previousValue,
                                Result = result,
                                ThrowErrors = throwErrors,
                                Value = value,
                            };

                        try
                        {
                            current.ACTION(ctx);

                            lastError = null;
                            current = current.Next;
                        }
                        catch (Exception ex)
                        {
                            ctx.LastError = lastError = ex;

                            occuredErrors.Add(ex);

                            var onError = current.OnError;
                            if (onError != null)
                            {
                                current = onError;
                            }
                            else
                            {
                                if (!ctx.ContinueOnError)
                                {
                                    throw;
                                }
                            }
                        }

                        var nextAction = ctx.Next;
                        if (nextAction != null)
                        {
                            current = new WorkflowConfig(current.Workflow, nextAction, current);
                        }

                        if (ctx.Cancel)
                        {
                            hasBeenCanceled = true;
                            ctx.HasBeenCanceled = hasBeenCanceled;
                        }

                        previousValue = ctx.NextValue;
                        throwErrors = ctx.ThrowErrors;
                        result = ctx.Result;
                        value = ctx.Value;

                        return ctx;
                    };
            }

            if (throwErrors &&
                occuredErrors.Count > 0)
            {
                throw new AggregateException(occuredErrors);
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Starts building the workflow.
        /// </summary>
        /// <param name="startAction">The start action.</param>
        /// <returns>The config of the start action.</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="startAction" /> is <see langword="null" />.
        /// </exception>
        public IWorkflowConfig StartWith(WorkflowAction startAction)
        {
            if (startAction == null)
            {
                throw new ArgumentNullException("startAction");
            }

            return _start = new WorkflowConfig(this, startAction);
        }
Exemplo n.º 19
0
 public WorkflowAction(Configuration configuration, int taskLoopInterval, WorkflowConfig workflowConfig)
 {
     _workflowConfig   = workflowConfig;
     _configuration    = configuration;
     _taskLoopInterval = taskLoopInterval;
 }
Exemplo n.º 20
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 Dictionary <String, Object> getaccessrequest(IAMDatabase database, Dictionary <String, Object> parameters)
        {
            Dictionary <String, Object> result = new Dictionary <String, Object>();

            if (!parameters.ContainsKey("requestid"))
            {
                Error(ErrorType.InvalidRequest, "Parameter requestid is not defined.", "", null);
                return(null);
            }

            Int64 requestid = 0;

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

            DbParameterCollection par = new DbParameterCollection();

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

            DataTable dtPlugins = database.ExecuteDataTable("select r.*, e.context_id, c.enterprise_id, e.full_name, e.login 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 where r.id = @request_id and c.enterprise_id = @enterprise_id", CommandType.Text, par, null);

            if ((dtPlugins == null) || (dtPlugins.Rows.Count == 0))
            {
                Error(ErrorType.InvalidRequest, "Access request not found.", "", null);
                return(null);
            }

            DataRow dr1 = dtPlugins.Rows[0];

            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("info", newItem);

            return(result);
        }
Exemplo n.º 21
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);
        }
Exemplo n.º 22
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> list(IAMDatabase database, Dictionary <String, Object> parameters)
        {
            List <Object> result = new List <Object>();

            String text = "";

            if (parameters.ContainsKey("text"))
            {
                text = (String)parameters["text"];
            }

            if (String.IsNullOrWhiteSpace(text))
            {
                text = "";
            }

            DbParameterCollection par = new DbParameterCollection();

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

            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);


            String sql = "";

            sql += "WITH result_set AS (";
            sql += "  SELECT ";
            sql += "    ROW_NUMBER() OVER (ORDER BY w.name) AS [row_number], w.id, request_qty = (select COUNT(*) from st_workflow_request wr with(nolock) where wr.workflow_id = w.id) ";
            sql += "     from st_workflow w with(nolock) inner join context c with(nolock) on c.id = w.context_id ";
            sql += "     where ((c.enterprise_id = @enterprise_id) " + (String.IsNullOrWhiteSpace(text) ? "" : " and w.name like '%'+@text+'%'") + ")";
            sql += ") SELECT";
            sql += "  *";
            sql += " FROM";
            sql += "  result_set";
            sql += " WHERE";
            sql += "  [row_number] BETWEEN " + rStart + " AND " + rEnd;

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

            if ((dtPlugins != null) && (dtPlugins.Rows.Count > 0))
            {
                foreach (DataRow dr1 in dtPlugins.Rows)
                {
                    using (WorkflowConfig wk = new WorkflowConfig())
                    {
                        wk.GetDatabaseData(database, (Int64)dr1["id"]);

                        Dictionary <string, object> newItem = wk.ToJsonObject();

                        newItem.Add("request_qty", dr1["request_qty"]);

                        result.Add(newItem);
                    }
                }
            }

            return(result);
        }
Exemplo n.º 23
0
 /// <summary>
 /// Creates a new TaskStatus. This constructor is designed for Switch flowchart tasks.
 /// </summary>
 /// <param name="status">Status.</param>
 /// <param name="switchValue">Switch value.</param>
 public TaskStatus(Status status, string switchValue, Task task, RequestModel model, string serviceResponse, WorkflowConfig workflowConfig) //: this(status, task, model)
 {
     _workflowConfig = workflowConfig;
     AddEndTaskLog(task, model, Status, TaskType.SwitchCase, serviceResponse);
     SwitchValue = switchValue;
 }
Exemplo n.º 24
0
 protected void bwConfig_DoWork(object sender, DoWorkEventArgs e)
 {
     Program.ConfigUploaders = UploadersConfig.Load(Program.ConfigUploadersFilePath);
     Engine.ConfigUploaders  = Program.ConfigUploaders;
     Program.ConfigWorkflow  = WorkflowConfig.Read();
 }
Exemplo n.º 25
0
        /// <summary>
        /// This method permits to open and start the workflow
        /// </summary>
        /// <param name="workflowConfig">WorkflowConfig Id</param>
        /// <param name="dataSet">DataSet Id</param>
        public async Task <HttpResponseMessageResult> Open(long workflowConfigId, long dataSetId, long idUserSet)
        {
            // Création de la transaction
            using (IDbContextTransaction transaction = UnitOfWork.GetDbContext().Database.BeginTransaction())
            {
                SessionStatsHelper.HttpHitSaveDBTransaction(transaction, _serviceProvider);

                // On récupére les entités
                WorkflowConfig wfConf = await UnitOfWork.GetDbContext().WorkflowConfig
                                        .Include(wf => wf.SelectorConfig)
                                        .ThenInclude(sc => sc.Criterias)
                                        .ThenInclude(c => c.Dimension)
                                        .Include(wf => wf.SelectorConfig)
                                        .ThenInclude(sc => sc.Modifiers)
                                        .ThenInclude(c => c.Dimension)
                                        .Include(wf => wf.SelectorConfig)
                                        .ThenInclude(sc => sc.Validators)
                                        .ThenInclude(c => c.Dimension)
                                        .Include(wf => wf.SelectorConfig)
                                        .ThenInclude(sc => sc.ModifyCriterias)
                                        .ThenInclude(c => c.Dimension)
                                        .Include(wf => wf.WorkflowDimension)
                                        .ThenInclude(wd => wd.Dimension)
                                        .Where(wf => wf.Id == workflowConfigId)
                                        .AsNoTracking()
                                        .ToAsyncEnumerable()
                                        .FirstOrDefault();

                DataSet dtSet = await UnitOfWork.GetDbContext().DataSet
                                .Include(d => d.DataSetDimensions)
                                .Where(d => d.Id == dataSetId)
                                .AsNoTracking()
                                .ToAsyncEnumerable()
                                .FirstOrDefault();

                UserSet usrSet = await UnitOfWork.GetDbContext().UserSet
                                 .Where(u => u.Id == idUserSet)
                                 .AsNoTracking()
                                 .ToAsyncEnumerable()
                                 .FirstOrDefault();

                if ((wfConf == null) || (dtSet == null) || (usrSet == null))
                {
                    return new HttpResponseMessageResult()
                           {
                               IsSuccess = false, Message = $"Can't get WorkflowConfig with id {workflowConfigId}, DataSet with id {dataSetId}, UserSet with id {idUserSet}"
                           }
                }
                ;

                if (!CheckDimensions(wfConf, dtSet, usrSet))
                {
                    throw new SequenceException("Process.Open: WorkflowDimensions are not equals to DataSetDimensions.");
                }

                // Create the workflow instance
                WorkflowInstance workflowInstance = await WorkflowInstanceDomain.CreateInstance(wfConf, dtSet, usrSet);

                // Générer les SelectorInstance.
                HttpResponseMessageResult res = await WorkflowInstanceDomain.StartSelectorsIntances(workflowInstance);

                transaction.Commit();
                return(res);
            }
        }
 public JsonResult GetConfigs()
 {
     return(JsonWrapper(WorkflowConfig.GetSettings()));
 }
 internal WorkflowConfig(ConfigurableWorkflow workflow, WorkflowAction action, WorkflowConfig parent = null)
 {
     Workflow = workflow;
     ACTION = action;
     PARENT = parent;
 }
Exemplo n.º 28
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);
            }
        }
            internal WorkflowConfig ContinueWith(WorkflowAction nextAction)
            {
                if (nextAction == null)
                {
                    throw new ArgumentNullException("nextAction");
                }

                return Next = new WorkflowConfig(Workflow, nextAction, this);
            }
Exemplo n.º 30
0
 public TaskStatus(Status status, Task task, RequestModel model, string serviceResponse, WorkflowConfig workflowConfig)
 {
     _workflowConfig = workflowConfig;
     AddEndTaskLog(task, model, status, TaskType.Task, serviceResponse);
     Status = status;
 }
Exemplo n.º 31
0
 public override TaskStatus Run(WorkflowConfig workflowConfig, RequestModel model = null)
 {
     return(new TaskStatus(Status.Success, this, model, "", workflowConfig));
 }
Exemplo n.º 32
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 Dictionary <String, Object> get(IAMDatabase database, Dictionary <String, Object> parameters)
        {
            Dictionary <String, Object> result = new Dictionary <String, Object>();

            if (!parameters.ContainsKey("workflowid"))
            {
                Error(ErrorType.InvalidRequest, "Parameter workflowid is not defined.", "", null);
                return(null);
            }


            String plugin = parameters["workflowid"].ToString();

            if (String.IsNullOrWhiteSpace(plugin))
            {
                Error(ErrorType.InvalidRequest, "Parameter workflowid is not defined.", "", null);
                return(null);
            }

            Int64 workflowid = 0;

            try
            {
                workflowid = Int64.Parse(plugin);
            }
            catch
            {
                Error(ErrorType.InvalidRequest, "Parameter workflowid is not a long integer.", "", null);
                return(null);
            }


            DbParameterCollection par = new DbParameterCollection();

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

            DataTable dtPlugin = database.ExecuteDataTable("select w.id, request_qty = (select COUNT(*) from st_workflow_request wr with(nolock) where wr.workflow_id = w.id) from st_workflow w with(nolock) inner join context c with(nolock) on c.id = w.context_id where c.enterprise_id = @enterprise_id and w.id = @workflow_id", CommandType.Text, par, null);

            if (dtPlugin == null)
            {
                Error(ErrorType.InternalError, "", "", null);
                return(null);
            }

            if (dtPlugin.Rows.Count == 0)
            {
                Error(ErrorType.InvalidRequest, "Workflow not found.", "", null);
                return(null);
            }


            DataRow dr1 = dtPlugin.Rows[0];


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

                Dictionary <string, object> newItem = wk.ToJsonObject();

                newItem.Add("request_qty", dr1["request_qty"]);

                result.Add("info", newItem);
            }

            return(result);
        }
Exemplo n.º 33
0
 /// <summary>
 /// Creates a new TaskStatus. This constructor is designed for If/While flowchart tasks.
 /// </summary>
 /// <param name="status">Status.</param>
 /// <param name="condition">Condition value.</param>
 public TaskStatus(Status status, bool condition, Task task, RequestModel model, string serviceResponse, WorkflowConfig workflowConfig)
 {
     _workflowConfig = workflowConfig;
     AddEndTaskLog(task, model, Status, TaskType.If, serviceResponse, condition);
     Condition = condition;
 }
Exemplo n.º 34
0
 public MergeStepConfig(WorkflowConfig workflowConfig)
     : base(workflowConfig)
 {
 }
            internal WorkflowConfig IfFails(WorkflowAction errorAction)
            {
                if (errorAction == null)
                {
                    throw new ArgumentNullException("errorAction");
                }

                return OnError = new WorkflowConfig(Workflow, errorAction, this);
            }