protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        // Disable confirm changes checking
        DocumentManager.RegisterSaveChangesScript = false;

        // Init node
        workflowElem.Node = Node;

        workflow = DocumentManager.Workflow;
        if (workflow != null)
        {
            menuElem.OnClientStepChanged = ClientScript.GetPostBackEventReference(pnlUp, null);

            // Backward compatibility - Display Archive button for all steps
            menuElem.ForceArchive = workflow.IsBasic;
        }

        // Enable split mode
        EnableSplitMode = true;

        // Mark selected tab
        UIContext.ProductTab = ProductTabEnum.Workflow;
    }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerUIElement("CMS.Content", "Properties.Workflow"))
        {
            RedirectToUIElementAccessDenied("CMS.Content", "Properties.Workflow");
        }

        DocumentManager.OnCheckPermissions += DocumentManager_OnCheckPermissions;

        // Disable confirm changes checking
        DocumentManager.RegisterSaveChangesScript = false;

        // Init node
        workflowElem.Node = Node;

        workflow = DocumentManager.Workflow;
        if (workflow != null)
        {
            menuElem.OnClientStepChanged = ClientScript.GetPostBackEventReference(pnlUp, null);

            // Backward compatibility - Display Archive button for all steps
            menuElem.ForceArchive = workflow.IsBasic;
        }

        // Enable split mode
        EnableSplitMode = true;

        SetPropertyTab(TAB_WORKFLOW);
    }
Ejemplo n.º 3
0
    protected void btnNewFolder_OnComplete(object source, WorkflowInfo info)
    {
        int selectedFolderId = -1;
        if (chkTreeview.Checked) {
            if (contentTree.GetSelectedCount() > 0) {
                selectedFolderId = new CKeyNLR(contentTree.GetSelectedValues().GetFirst()).NodeId;
            }
        }

        CKeyNLRC key = (CKeyNLRC)info.OutputParameters["NewContentKeyC"];
        if (key != null) {
            ContentBase newContent = WAFContext.Session.GetContent<ContentBase>(key);
            if (newContent is ContentFile && selectedFolderId > -1) {
                ((ContentFile)newContent).Folder.Set(selectedFolderId);
                newContent.UpdateChanges();
            }
            if (newContent is FileFolder && selectedFolderId > -1) {
                ((FileFolder)newContent).ParentFolder.Set(selectedFolderId);
                contentTree.DataBind();
                newContent.UpdateChanges();
            }
            contentTree.SetSelected(key.NodeId);
            contentTree.DataBind();
        }
    }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        // Check UIProfile
        if (!CMSContext.CurrentUser.IsAuthorizedPerUIElement("CMS.OnlineMarketing", new string[] { "OMCMGroup", "ContactsFrameset", "PendingContacts" }, CMSContext.CurrentSiteName))
        {
            RedirectToCMSDeskUIElementAccessDenied("CMS.OnlineMarketing", "OMCMGroup;ContactsFrameset;PendingContacts");
        }

        bool dialogMode = QueryHelper.GetBoolean("dialogmode", false);
        if (dialogMode)
        {
            RegisterModalPageScripts();
        }

        autoMan.OnAfterAction += AutomationManager_OnAfterAction;
        autoMan.StateObjectID = QueryHelper.GetInteger("stateid", 0);

        workflow = autoMan.Process;
        if (workflow != null)
        {
            menuElem.OnClientStepChanged = ClientScript.GetPostBackEventReference(pnlUp, null);
        }
    }
Ejemplo n.º 5
0
 /// <summary>
 /// Saves new wokflow's data into DB.
 /// </summary>
 /// <returns>Returns ID of created wokflow</returns>
 protected int SaveNewWorkflow()
 {
     WorkflowInfo wi = new WorkflowInfo();
     wi.WorkflowDisplayName = txtWorkflowDisplayName.Text;
     wi.WorkflowName = txtWorkflowCodeName.Text;
     WorkflowInfoProvider.SetWorkflowInfo(wi);
     return wi.WorkflowID;
 }
Ejemplo n.º 6
0
        bool WorkflowStatusChanged(WorkflowInfo workflow)
        {
            var changed = _workflowsPerId[workflow.Id].IsRunning != workflow.IsRunning || _workflowsPerId[workflow.Id].IsPaused != workflow.IsPaused;

            _workflowsPerId[workflow.Id].IsRunning = workflow.IsRunning;
            _workflowsPerId[workflow.Id].IsPaused  = workflow.IsPaused;
            return(changed);
        }
Ejemplo n.º 7
0
    /// <summary>
    /// Moves the document to the previous step in the workflow process. Called when the "Move to previous step" button is pressed.
    /// Expects the "CreateExampleObjects" and "MoveToNextStep" method to be run first.
    /// </summary>
    private bool MoveToPreviousStep()
    {
        TreeProvider tree = new TreeProvider(CMSContext.CurrentUser);

        // Prepare parameters
        string siteName  = CMSContext.CurrentSiteName;
        string aliasPath = "/API-Example";
        string culture   = "en-us";
        bool   combineWithDefaultCulture = false;
        string classNames = TreeProvider.ALL_CLASSNAMES;

        string where = null;
        string orderBy             = null;
        int    maxRelativeLevel    = -1;
        bool   selectOnlyPublished = false;
        string columns             = null;

        // Get the document
        TreeNode node = DocumentHelper.GetDocument(siteName, aliasPath, culture, combineWithDefaultCulture, classNames, where, orderBy, maxRelativeLevel, selectOnlyPublished, columns, tree);

        if (node != null)
        {
            WorkflowManager workflowManager = WorkflowManager.GetInstance(tree);

            WorkflowInfo workflow = workflowManager.GetNodeWorkflow(node);

            // Check if the document uses workflow
            if (workflow != null)
            {
                // Check if the workflow doesn't use automatic publishing, otherwise, documents can't change workflow steps.
                if (!workflow.WorkflowAutoPublishChanges)
                {
                    // Check if the current user can move the document to the next step
                    if (workflowManager.CheckStepPermissions(node, WorkflowActionEnum.Reject))
                    {
                        // Move the document to the previous step
                        workflowManager.MoveToPreviousStep(node, null);

                        return(true);
                    }
                    else
                    {
                        apiMoveToPreviousStep.ErrorMessage = "You are not authorized to reject the document.";
                    }
                }
                else
                {
                    apiMoveToPreviousStep.ErrorMessage = "The document uses versioning without workflow, changes are published automatically.";
                }
            }
            else
            {
                apiMoveToPreviousStep.ErrorMessage = "The document doesn't use workflow.";
            }
        }

        return(false);
    }
        /// <summary>
        /// 验证
        /// </summary>
        /// <param name="returnInfo">返回信息</param>
        /// <param name="workflow">工作流</param>
        /// <param name="comData">通用数据</param>
        protected override void Vali(ReturnInfo <bool> returnInfo, WorkflowInfo workflow, CommonUseData comData = null)
        {
            var user = UserTool <int> .GetCurrUser(comData);

            if (workflow.CreaterId != user.Id)
            {
                returnInfo.SetFailureMsg("Sorry,您不是此流程的发起者,故不能撤消");

                return;
            }
            switch (workflow.FlowStatus)
            {
            case FlowStatusEnum.DRAFT:
                returnInfo.SetFailureMsg("Sorry,此流程是草稿状态不能撤消");

                return;

            case FlowStatusEnum.REVERSED:
                returnInfo.SetFailureMsg("Sorry,此流程已经撤消,不能重复撤消");

                return;

            case FlowStatusEnum.AUDIT_PASS:
                returnInfo.SetFailureMsg("Sorry,此流程已经审核通过,不能撤消");

                return;

            case FlowStatusEnum.AUDIT_NOPASS:
                returnInfo.SetFailureMsg("Sorry,此流程已经审核不通过,不能撤消");

                return;

            case FlowStatusEnum.AUDITING:
                // 只有所有审核者未读才允许撤消
                foreach (var h in workflow.Handles)
                {
                    // 本人处理忽略
                    if (h.HandlerId == user.Id)
                    {
                        continue;
                    }

                    if (h.IsReaded)
                    {
                        returnInfo.SetFailureMsg("Sorry,此流程已经被审核者读过,不能撤消");

                        return;
                    }
                }

                return;

            default:
                returnInfo.SetFailureMsg("Sorry,此流程未知状态,不能撤消");

                return;
            }
        }
Ejemplo n.º 9
0
        public static string ExtractWorkflowInfoJson(Diagram diagram)
        {
            var info = new WorkflowInfo()
            {
                Key = diagram.Tag.ToString()
            };

            return(JsonConvert.SerializeObject(info));
        }
Ejemplo n.º 10
0
    /// <summary>
    /// Saves new wokflow's data into DB.
    /// </summary>
    /// <returns>Returns ID of created wokflow</returns>
    protected int SaveNewWorkflow()
    {
        WorkflowInfo wi = new WorkflowInfo();

        wi.WorkflowDisplayName = txtWorkflowDisplayName.Text;
        wi.WorkflowName        = txtWorkflowCodeName.Text;
        WorkflowInfoProvider.SetWorkflowInfo(wi);
        return(wi.WorkflowID);
    }
Ejemplo n.º 11
0
        //更新工作流
        public int UpdateWorkflow(WorkflowInfo flow)
        {
            if (flow.CreateTime < DateTime.Now.AddYears(-10))
            {
                flow.CreateTime = DateTime.Now;
            }
            flow.LastUpdateTime = DateTime.Now;
            if (flow.AuditSteps != null && flow.AuditSteps.Count > 0)
            {
                if (SqlHelper.Update(flow) > 0)
                {
                    DeleteWorkfowSteps(flow.FlowType);

                    foreach (var step in flow.AuditSteps)
                    {
                        step.FlowType = flow.FlowType;
                        if (step.AuditUserId < 1 && step.AuditUser != null)
                        {
                            step.AuditUserId = step.AuditUser.UserId;
                        }
                        if (step.AuditRoleId < 1 && step.AuditRole != null)
                        {
                            step.AuditRoleId = step.AuditRole.RoleId;
                        }
                        if (string.IsNullOrEmpty(step.AuditOrgId) && step.AuditOrganization != null)
                        {
                            step.AuditOrgId = step.AuditOrganization.Id;
                        }
                        if (step.AuditType == AuditType.JointCheckup)
                        {
                            if (step.JcUsers != null && step.JcUsers.Count > 0)
                            {
                                SqlHelper.Insert(step);
                                foreach (var jcu in step.JcUsers)
                                {
                                    jcu.StepId = step.StepId;
                                    if (jcu.UserId < 1 && jcu.UserInfo != null)
                                    {
                                        jcu.UserId = jcu.UserInfo.UserId;
                                    }
                                    SqlHelper.Insert(jcu);
                                }
                            }
                        }
                        else
                        {
                            SqlHelper.Insert(step);
                        }
                    }

                    return(1);
                }
                return(-1);
            }
            return(-2);
        }
Ejemplo n.º 12
0
 //删除工作流
 public int DeleteWorkflow(WorkflowInfo flow)
 {
     if (flow != null)
     {
         flow.LastUpdateTime = DateTime.Now;
         flow.Status         = ActiveStatus.Deleted;
         return(SqlHelper.Update(flow));
     }
     return(-2);
 }
Ejemplo n.º 13
0
    /// <summary>
    /// Deletes process. Called when the "Delete process" button is pressed.
    /// Expects the CreateProcess method to be run first.
    /// </summary>
    private bool DeleteProcess()
    {
        // Get the process
        WorkflowInfo deleteProcess = WorkflowInfoProvider.GetWorkflowInfo("MyNewProcess", WorkflowTypeEnum.Automation);

        // Delete the process
        WorkflowInfoProvider.DeleteWorkflowInfo(deleteProcess);

        return(deleteProcess != null);
    }
Ejemplo n.º 14
0
        /// <summary>
        /// 将 流程图形 信息转化成 info 信息
        /// </summary>
        /// <param name="link"></param>
        /// <returns></returns>
        public static WorkflowInfo ExtractWorkflowInfo(DiagramPageViewModel diagram)
        {
            WorkflowInfo wfInfo = new WorkflowInfo()
            {
                Key  = diagram.Key,
                Name = diagram.Name
            };

            return(wfInfo);
        }
Ejemplo n.º 15
0
        public void Test_GettersSetters()
        {
            const string file           = "test-file";
            var          actionWorkflow = new ActionWorkflow();
            var          wfi            = new WorkflowInfo(file, actionWorkflow);

            Assert.NotNull(wfi.File);
            Assert.Equal(file, wfi.File.FilePath);
            Assert.Same(actionWorkflow, wfi.Workflow);
        }
Ejemplo n.º 16
0
    /// <summary>
    /// Deletes workflow. Called when the "Delete workflow" button is pressed.
    /// Expects the CreateWorkflow method to be run first.
    /// </summary>
    private bool DeleteWorkflow()
    {
        // Get the workflow
        WorkflowInfo deleteWorkflow = WorkflowInfoProvider.GetWorkflowInfo("MyNewWorkflow", WorkflowTypeEnum.Approval);

        // Delete the workflow
        WorkflowInfoProvider.DeleteWorkflowInfo(deleteWorkflow);

        return(deleteWorkflow != null);
    }
Ejemplo n.º 17
0
        public static void ProcessDatetime(WorkflowInfo wfInfo)
        {
            wfInfo.StartTime = wfInfo.StartTime.ToLocalTime();
            wfInfo.EndTime   = wfInfo.EndTime.ToLocalTime();

            foreach (ActivityInfo act in wfInfo.Activities)
            {
                act.StartTime = act.StartTime.ToLocalTime();
                act.EndTime   = act.EndTime.ToLocalTime();
            }
        }
Ejemplo n.º 18
0
        private static string GetWorkflowID(Item item)
        {
            Assert.ArgumentNotNull(item, "item");

            WorkflowInfo workflowInfo = item.Database.DataManager.GetWorkflowInfo(item);

            if (workflowInfo != null)
            {
                return(workflowInfo.WorkflowID);
            }
            return(string.Empty);
        }
        private static void DoProcessCallbackAction(WorkflowInfo workflowInfo, Action <IWfProcess> action)
        {
            (workflowInfo != null).FalseThrow(Translator.Translate(Define.DefaultCulture, "不能获取到当前流程信息"));

            IWfProcess currentProcess = WfRuntime.GetProcessByProcessID(workflowInfo.Key);

            WfClientContext.Current.ChangeTo(currentProcess.CurrentActivity);

            WfClientContext.Current.InAdminMode.FalseThrow(Translator.Translate(Define.DefaultCulture, "您没有权限执行此操作"));

            action(currentProcess);
        }
Ejemplo n.º 20
0
        private bool WorkflowStatusChanged(WorkflowInfo workflow)
        {
            if (_workflowsPerId.ContainsKey(workflow.Id))
            {
                var changed = _workflowsPerId[workflow.Id].IsRunning != workflow.IsRunning || _workflowsPerId[workflow.Id].IsPaused != workflow.IsPaused;
                _workflowsPerId[workflow.Id].IsRunning = workflow.IsRunning;
                _workflowsPerId[workflow.Id].IsPaused  = workflow.IsPaused;
                return(changed);
            }

            return(false);
        }
Ejemplo n.º 21
0
            public override bool Equals(object obj)
            {
                WorkflowInfo other = obj as WorkflowInfo;

                if (other != null)
                {
                    return(other.AssemblyFullName.Equals(this.AssemblyFullName) && other.TypeFullName.Equals(this.TypeFullName));
                }
                else
                {
                    return(false);
                }
            }
Ejemplo n.º 22
0
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        autoMan.OnAfterAction += AutomationManager_OnAfterAction;
        autoMan.StateObjectID  = QueryHelper.GetInteger("stateid", 0);

        workflow = autoMan.Process;
        if (workflow != null)
        {
            menuElem.OnClientStepChanged = ClientScript.GetPostBackEventReference(pnlUp, null);
        }
    }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        autoMan.OnAfterAction += AutomationManager_OnAfterAction;
        autoMan.StateObjectID = QueryHelper.GetInteger("stateid", 0);

        workflow = autoMan.Process;
        if (workflow != null)
        {
            menuElem.OnClientStepChanged = ClientScript.GetPostBackEventReference(pnlUp, null);
        }
    }
        private WorkflowInfo GetPostedProcessInfo()
        {
            string data = this.Page.Request.Form[this.WfRuntimeViewerWorkflowInfoHiddenFieldID];

            WorkflowInfo result = null;

            if (data.IsNotEmpty())
            {
                result = JSONSerializerExecute.Deserialize <WorkflowInfo>(data);
            }

            return(result);
        }
Ejemplo n.º 25
0
        void IInitializeWorkflowManager.Initialize(WorkflowInfo input)
        {
            if (WorkflowNotContainsWithoutParametersConstructor(input))
            {
                throw new Exception("У типа задающего ворклфоу должен быть безпараметрический конструктор");
            }

            var services = input.WorkflowName.GetNestedTypes().Select(_serviceProvider.GetService).ToList();

            var chainMethodParameter = services.Select(x => new
            {
                method    = x.GetType().GetMethod("Handle"),
                parameter = x.GetType().GetParametersByMethodName("Handle").FirstOrDefault()
            })
                                       .Where(x => x.parameter != default)
                                       .ToList();

            var parameterInfosList = chainMethodParameter.ToList();

            ChainTypes = chainMethodParameter.SkipLast(1)
                         .Aggregate(new[] { typeof(TIn) }.AsEnumerable(), (a, c) =>
            {
                var currentHandlerInChain = parameterInfosList.First(x => x.parameter == a.Last());
                return(a.Concat(currentHandlerInChain.method.GetGenericTypesReturnValue()));
            })
                         .Concat(new[] { typeof(TOut) })
                         .ToList();


            foreach (var service in services)
            {
                var voidHandler = _voidHandlersFactory.Create((dynamic)service);
                if (voidHandler != null)
                {
                    _voidHandlersExecutor.AddHandler(voidHandler);
                    continue;
                }

                var rollBackHandler = _rollBackHandlerFactory.Create((dynamic)service);
                if (rollBackHandler != null)
                {
                    _rollBackHandlersExecutor.AddHandler(rollBackHandler);
                }

                var resultHandler = _resultHandlersFactory.Create((dynamic)service);
                if (resultHandler != null)
                {
                    _resultHandlersExecutor.AddHandler(resultHandler);
                }
            }
        }
Ejemplo n.º 26
0
    /// <summary>
    /// Reverts back the changes made in the latest version if check-in/check-out is used. Called when the "Undo check-out" button is pressed.
    /// Expects the "CreateExampleObjects" and "CheckOut" methods to be run first.
    /// </summary>
    private bool UndoCheckout()
    {
        TreeProvider tree = new TreeProvider(CMSContext.CurrentUser);

        // Prepare parameters
        string siteName  = CMSContext.CurrentSiteName;
        string aliasPath = "/API-Example";
        string culture   = "en-us";
        bool   combineWithDefaultCulture = false;
        string classNames = TreeProvider.ALL_CLASSNAMES;

        string where = null;
        string orderBy             = null;
        int    maxRelativeLevel    = -1;
        bool   selectOnlyPublished = false;
        string columns             = null;

        // Get the document
        TreeNode node = DocumentHelper.GetDocument(siteName, aliasPath, culture, combineWithDefaultCulture, classNames, where, orderBy, maxRelativeLevel, selectOnlyPublished, columns, tree);

        if (node != null)
        {
            WorkflowManager workflowmanager = WorkflowManager.GetInstance(tree);

            // Make sure the document uses workflow
            WorkflowInfo workflow = workflowmanager.GetNodeWorkflow(node);

            if (workflow != null)
            {
                if (node.IsCheckedOut)
                {
                    VersionManager versionmanager = VersionManager.GetInstance(tree);

                    // Undo the checkout
                    versionmanager.UndoCheckOut(node);

                    return(true);
                }
                else
                {
                    apiUndoCheckout.ErrorMessage = "The document hasn't been checked out.";
                }
            }
            else
            {
                apiUndoCheckout.ErrorMessage = "The document doesn't use workflow.";
            }
        }

        return(false);
    }
Ejemplo n.º 27
0
        public ResultModel <WorkflowInfo> GetLastVersionWorkflow(int id)
        {
            var result = new ResultModel <WorkflowInfo>();

            try
            {
                var workflowEngine = new WorkflowEngine(_configuration, _workflowConfig, true);
                var wf             = workflowEngine.GetLastVersionWorkflow(id);
                if (wf != null)
                {
                    var workflowInfo = new WorkflowInfo
                    {
                        Id                    = wf.Id,
                        Name                  = wf.Name,
                        LaunchType            = (workflow.Core.Service.Contracts.LaunchType)wf.LaunchType,
                        IsEnabled             = wf.IsEnabled,
                        Description           = wf.Description,
                        IsRunning             = wf.IsRunning,
                        IsPaused              = wf.IsPaused,
                        Period                = wf.Period.ToString(@"dd\.hh\:mm\:ss"),
                        Path                  = wf.WorkflowFilePath,
                        IsExecutionGraphEmpty = wf.IsExecutionGraphEmpty,
                        DeadLine              = wf.DeadLine,
                        Version               = wf.Version,
                        VersionDescription    = wf.VersionDescription,
                        Graph                 = workflowEngine.GetJsonGraph(wf.Name + "_" + wf.Version + ".json"),
                        Tasks                 = wf.Tasks.Select(x => new TaskInfo
                        {
                            Description = x.Description,
                            Id          = x.Id,
                            IsCommon    = x.IsCommon,
                            IsEnabled   = x.IsEnabled,
                            Name        = x.Name,
                            DeadLine    = x.DeadLine,
                            Settings    = x.Settings.Select(y => new SettingInfo
                            {
                                Name  = y.Name,
                                Value = y.Value
                            }).ToList()
                        }).ToList()
                    };
                    result.Data = workflowInfo;
                }
            }
            catch (Exception ex)
            {
                result.Succeed      = false;
                result.ErrorMessage = ex.Message.ToString();
            }
            return(result);
        }
        private static void DoProcessCallbackOp(WorkflowInfo workflowInfo, Func <IWfProcess, WfExecutorBase> getExecutor)
        {
            (workflowInfo != null).FalseThrow(Translator.Translate(Define.DefaultCulture, "不能获取到当前流程信息"));

            IWfProcess currentProcess = WfRuntime.GetProcessByProcessID(workflowInfo.Key);

            WfClientContext.Current.ChangeTo(currentProcess.CurrentActivity);

            WfClientContext.Current.InAdminMode.FalseThrow(Translator.Translate(Define.DefaultCulture, "您没有权限执行此操作"));

            WfExecutorBase executor = getExecutor(currentProcess);

            WfClientContext.Current.Execute(executor);
        }
Ejemplo n.º 29
0
        public string GetSelectedProcessInfo()
        {
            string strResult = "";

            TabItem selectedItem = this.tabControl.SelectedItem as TabItem;

            if (selectedItem != null)
            {
                WorkflowInfo selectedInfo = (selectedItem.DataContext as DiagramPageViewModel).WfInfo;
                strResult = JsonConvert.SerializeObject(selectedInfo);
            }

            return(strResult);
        }
Ejemplo n.º 30
0
        private void CreateWorkflow(int wfId)
        {
            var w1 = new WorkflowInfo();

            w1.Name       = $"workflow{wfId}";
            w1.ConfigFile = $"workflow{wfId}.xml";
            var evlog1 = new EVLogInfo()
            {
                Description    = "EV1 Description ",
                ConfigFilePath = "",
            };

            w1.EVLogs.Add(evlog1);
        }
Ejemplo n.º 31
0
        private void AddNewCommandExecuted(WorkflowInfo info)
        {
            if (info == null)
            {
                throw new ArgumentNullException("WorkflowInfo不能为空");
            }
            WorkflowUtils.ProcessDatetime(info);
            DiagramPageViewModel vw = new DiagramPageViewModel(info);

            vw.RequestClose += this.Item_RequestClose;
            this.DiagramDataSource.Add(vw);

            this.OnPropertyChanged("DiagramDataSource");
        }
Ejemplo n.º 32
0
 private void ExecuteCreateAction(int templateId)
 {
     if (templateId == CREATE_FROM_SCRATCH_ID)
     {
         mWorkflow = AutomationHelper.CreateEmptyWorkflow();
     }
     else
     {
         var template = AutomationTemplateInfo.Provider.Get(templateId);
         if (template != null)
         {
             mWorkflow = AutomationTemplateManager.CreateAutomationProcessFromTemplate(template, MacroIdentityOption.FromUserInfo(CurrentUser));
         }
     }
 }
Ejemplo n.º 33
0
        public string GetSelectedCurrentProcessWfInfo()
        {
            string strResult = "";

            TabItem selectedItem = this.tabControl.SelectedItem as TabItem;

            if (selectedItem != null)
            {
                WorkflowInfo selectedInfo = (selectedItem.DataContext as DiagramPageViewModel).WfInfo;
                strResult = string.Format("{0},{1}", selectedInfo.ResourceID, selectedInfo.Key);
                //strResult = JsonConvert.SerializeObject(selectedInfo);
            }

            return(strResult);
        }
Ejemplo n.º 34
0
        private void AddNewCommandExecuted(WorkflowInfo info)
        {
            if (info == null)
            {
                throw new ArgumentNullException("WorkflowInfo不能为空");
            }

            DiagramPageViewModel vw = new DiagramPageViewModel(info, WebInterAct);

            vw.RequestClose += this.Item_RequestClose;
            this.DiagramDataSource.Add(vw);
            WebInterAct.LoadProperty(WorkflowUtils.CLIENTSCRIPT_PARAM_WORKFLOW,
                                     vw.Key,
                                     WorkflowUtils.ExtractWorkflowInfoJson(vw));
        }
Ejemplo n.º 35
0
    /// <summary>
    /// Converts existing workflow to advanced workflow. Called when the "Convert to advanced workflow" button is pressed.
    /// Expects the CreateWorkflow method to be run first.
    /// </summary>
    private bool ConvertToAdvancedWorkflow()
    {
        // Get the workflow
        WorkflowInfo convertWorkflow = WorkflowInfoProvider.GetWorkflowInfo("MyNewWorkflow");

        if (convertWorkflow != null)
        {
            // Convert to advanced workflow
            WorkflowInfoProvider.ConvertToAdvancedWorkflow(convertWorkflow.WorkflowID);

            return(true);
        }

        return(false);
    }
Ejemplo n.º 36
0
        /// <summary>
        /// 验证
        /// </summary>
        /// <param name="returnInfo">返回信息</param>
        /// <param name="workflow">工作流</param>
        protected override void Vali(ReturnInfo <bool> returnInfo, WorkflowInfo workflow)
        {
            if (workflow.CreaterId != UserTool.CurrUser.Id)
            {
                returnInfo.SetFailureMsg("Sorry,您不是此流程的发起者,故不能移除");

                return;
            }
            if (workflow.FlowStatus != FlowStatusEnum.DRAFT)
            {
                returnInfo.SetFailureMsg("Sorry,只有草稿状态才能移除");

                return;
            }
        }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        // Check UIProfile
        if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerUIElement("cms.onlinemarketing", "MyContacts" , SiteContext.CurrentSiteName))
        {
            RedirectToUIElementAccessDenied("cms.onlinemarketing", "MyContacts");
        }

        autoMan.OnAfterAction += AutomationManager_OnAfterAction;
        autoMan.StateObjectID = QueryHelper.GetInteger("stateid", 0);

        workflow = autoMan.Process;
        if (workflow != null)
        {
            menuElem.OnClientStepChanged = ClientScript.GetPostBackEventReference(pnlUp, null);
        }
    }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        // Init node
        workflowElem.Node = Node;

        workflow = DocumentManager.Workflow;
        if (workflow != null)
        {
            menuElem.OnClientStepChanged = ClientScript.GetPostBackEventReference(pnlUp, null);

            // Backward compatibility - Display Archive button for all steps
            menuElem.ForceArchive = workflow.IsBasic;
        }

        // Enable split mode
        EnableSplitMode = true;
    }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        // Check UIProfile
        if (!CMSContext.CurrentUser.IsAuthorizedPerUIElement("CMS.MyDesk", new string[] { "MyDeskDocuments", "Pending", "Contacts" }, CMSContext.CurrentSiteName))
        {
            RedirectToCMSDeskUIElementAccessDenied("CMS.MyDesk", "MyDeskDocuments;Pending;Contacts");
        }

        autoMan.OnAfterAction += AutomationManager_OnAfterAction;
        autoMan.StateObjectID = QueryHelper.GetInteger("stateid", 0);

        workflow = autoMan.Process;
        if (workflow != null)
        {
            menuElem.OnClientStepChanged = ClientScript.GetPostBackEventReference(pnlUp, null);
        }
    }
Ejemplo n.º 40
0
    /// <summary>
    /// Creates workflow. Called when the "Create workflow" button is pressed.
    /// </summary>
    private bool CreateWorkflow()
    {
        // Create new workflow object
        WorkflowInfo newWorkflow = new WorkflowInfo();

        // Set the properties
        newWorkflow.WorkflowDisplayName = "My new workflow";
        newWorkflow.WorkflowName = "MyNewWorkflow";

        // Save the workflow
        WorkflowInfoProvider.SetWorkflowInfo(newWorkflow);

        // Create the three default workflow steps
        WorkflowStepInfoProvider.CreateDefaultWorkflowSteps(newWorkflow);

        return true;
    }
Ejemplo n.º 41
0
    /// <summary>
    /// Gets and bulk updates workflows. Called when the "Get and bulk update workflows" button is pressed.
    /// Expects the CreateWorkflow method to be run first.
    /// </summary>
    private bool GetAndBulkUpdateWorkflows()
    {
        // Prepare the parameters
        string where = "WorkflowName LIKE N'MyNewWorkflow%'";

        // Get the data
        DataSet workflows = WorkflowInfoProvider.GetWorkflows(where, null, 0, null);
        if (!DataHelper.DataSourceIsEmpty(workflows))
        {
            // Loop through the individual items
            foreach (DataRow workflowDr in workflows.Tables[0].Rows)
            {
                // Create object from DataRow
                WorkflowInfo modifyWorkflow = new WorkflowInfo(workflowDr);

                // Update the properties
                modifyWorkflow.WorkflowDisplayName = modifyWorkflow.WorkflowDisplayName.ToUpper();

                // Save the changes
                WorkflowInfoProvider.SetWorkflowInfo(modifyWorkflow);
            }

            return true;
        }

        return false;
    }
Ejemplo n.º 42
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Initialize form and controls
        Title = "Workflow Edit - General";

        rfvCodeName.ErrorMessage = GetString("Development-Workflow_New.RequiresCodeName");
        RequiredFieldValidatorDisplayName.ErrorMessage = GetString("Development-Workflow_New.RequiresDisplayName");

        if (QueryHelper.GetInteger("saved", 0) == 1)
        {
            lblInfo.Visible = true;
            lblInfo.Text = GetString("General.ChangesSaved");
        }

        // Get ID of workflow from querystring
        workflowId = QueryHelper.GetInteger("workflowid", 0);

        if (workflowId > 0)
        {
            currentWorkflow = WorkflowInfoProvider.GetWorkflowInfo(workflowId);
            // Set edited object
            EditedObject = currentWorkflow;
        }

        if (!RequestHelper.IsPostBack() && (currentWorkflow != null))
        {
            txtCodeName.Text = currentWorkflow.WorkflowName;
            TextBoxWorkflowDisplayName.Text = currentWorkflow.WorkflowDisplayName;
            chkAutoPublish.Checked = currentWorkflow.WorkflowAutoPublishChanges;

            bool? useCheckInCheckOut = currentWorkflow.WorkflowUseCheckinCheckout;

            // Is enabled or disabled check-in/check-out
            if (useCheckInCheckOut.HasValue)
            {
                radYes.Checked = useCheckInCheckOut.Value;
                radNo.Checked = !useCheckInCheckOut.Value;
            }
            // Inherit from global settings
            else
            {
                radSiteSettings.Checked = true;
            }
        }
    }
Ejemplo n.º 43
0
        public void StartWorkflow(Type workflowType,Dictionary<string,object> inparms,Guid caller,IComparable qn)
        {
            WorkflowRuntime wr = this.Runtime;
            WorkflowInstance wi = wr.CreateWorkflow(workflowType,inparms);
            wi.Start();

            var instanceId = wi.InstanceId;
            _WorkflowQueue[instanceId] = new WorkflowInfo { Caller = caller, qn = qn };

            ManualWorkflowSchedulerService ss = wr.GetService<ManualWorkflowSchedulerService>();
            if (ss != null)
                ss.RunWorkflow(wi.InstanceId);
        }
Ejemplo n.º 44
0
 protected void openContent_Complete(object sender, WorkflowInfo info)
 {
     if (info.OutputParameters.ContainsKey("SelectedValues")) {
         UniqueList<CKeyNLRC> selectedValues = (UniqueList<CKeyNLRC>)info.OutputParameters["SelectedValues"];
         if (selectedValues.Count > 0) {
             CKeyNLRC key = selectedValues.GetFirst();
             contentForm.NodeId = key.NodeId;
             contentForm.Refresh();
         }
     }
 }
Ejemplo n.º 45
0
        public override DataUri[] GetItemsInWorkflowState(WorkflowInfo info, CallContext context)
        {
            Guid workflowStateId;

            if (Guid.TryParse(info.StateID, out workflowStateId))
            {
                var items = Provider.GetItemsInWorkflowState(workflowStateId);
                var result = items.Select(x => x.FieldValues
                                                   .Where(y => y.Id == FieldIDs.WorkflowState.Guid)
                                                   .Select(y => new DataUri(new ID(x.Id), LanguageManager.GetLanguage(y.Language), new Version(y.Version ?? 1)))
                    ).ToList();

                if (result.Any())
                {
                    return result.Aggregate((x, y) => (x ?? new DataUri[] {}).Concat(y ?? new DataUri[] {})).ToArray();
                }

                return new DataUri[] {};
            }

            return new DataUri[] {};
        }
Ejemplo n.º 46
0
 public override bool SetWorkflowInfo(ItemDefinition item, VersionUri version, WorkflowInfo info, CallContext context)
 {
     return base.SetWorkflowInfo(item, version, info, context);
 }
        /// <summary>
        /// Provides operations necessary to create and store new cms file.
        /// </summary>
        /// <param name="args">Upload arguments.</param>
        /// <param name="context">HttpContext instance.</param>
        private void HandleContentUpload(UploaderHelper args, HttpContext context)
        {
            bool newDocumentCreated = false;
            string name = args.Name;

            try
            {
                if (args.FileArgs.NodeID == 0)
                {
                    throw new Exception(ResHelper.GetString("dialogs.document.parentmissing"));
                }
                // Check license limitations
                if (!LicenseHelper.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.Documents, VersionActionEnum.Insert))
                {
                    throw new Exception(ResHelper.GetString("cmsdesk.documentslicenselimits"));
                }

                // Check user permissions
                if (!CMSContext.CurrentUser.IsAuthorizedToCreateNewDocument(args.FileArgs.NodeID, "CMS.File"))
                {
                    throw new Exception(string.Format(ResHelper.GetString("dialogs.newfile.notallowed"), "CMS.File"));
                }

                // Check if class exists
                DataClassInfo ci = DataClassInfoProvider.GetDataClass("CMS.File");
                if (ci == null)
                {
                    throw new Exception(string.Format(ResHelper.GetString("dialogs.newfile.classnotfound"), "CMS.File"));
                }

                #region "Check permissions"

                // Get the node
                using (TreeNode parentNode = TreeProvider.SelectSingleNode(args.FileArgs.NodeID, args.FileArgs.Culture, true))
                {
                    if (parentNode != null)
                    {
                        if (!DataClassInfoProvider.IsChildClassAllowed(ValidationHelper.GetInteger(parentNode.GetValue("NodeClassID"), 0), ci.ClassID))
                        {
                            throw new Exception(ResHelper.GetString("Content.ChildClassNotAllowed"));
                        }
                    }
                    // Check user permissions
                    if (!CMSContext.CurrentUser.IsAuthorizedToCreateNewDocument(parentNode, "CMS.File"))
                    {
                        throw new Exception(string.Format(ResHelper.GetString("dialogs.newfile.notallowed"), args.AttachmentArgs.NodeClassName));
                    }
                }

                #endregion

                args.IsExtensionAllowed();

                if (args.FileArgs.IncludeExtension)
                {
                    name += args.Extension;
                }

                // Make sure the file name with extension respects maximum file name
                name = TreePathUtils.EnsureMaxFileNameLength(name, ci.ClassName);

                node = TreeNode.New("CMS.File", TreeProvider);
                node.DocumentCulture = args.FileArgs.Culture;
                node.DocumentName = name;
                if (args.FileArgs.NodeGroupID > 0)
                {
                    node.SetValue("NodeGroupID", args.FileArgs.NodeGroupID);
                }

                // Load default values
                FormHelper.LoadDefaultValues(node.NodeClassName, node);

                node.SetValue("FileDescription", "");
                node.SetValue("FileName", name);
                node.SetValue("FileAttachment", Guid.Empty);
                node.SetValue("DocumentType", args.Extension);

                node.SetDefaultPageTemplateID(ci.ClassDefaultPageTemplateID);

                // Insert the document
                DocumentHelper.InsertDocument(node, args.FileArgs.NodeID, TreeProvider);
                newDocumentCreated = true;

                // Add the attachment data
                DocumentHelper.AddAttachment(node, "FileAttachment", args.FilePath, TreeProvider, args.ResizeToWidth, args.ResizeToHeight, args.ResizeToMaxSide);

                // Create default SKU if configured
                if (ModuleEntry.CheckModuleLicense(ModuleEntry.ECOMMERCE, URLHelper.GetCurrentDomain(), FeatureEnum.Ecommerce, VersionActionEnum.Insert))
                {
                    node.CreateDefaultSKU();
                }

                DocumentHelper.UpdateDocument(node, TreeProvider);

                // Get workflow info
                wi = node.GetWorkflow();

                // Check if auto publish changes is allowed
                if ((wi != null) && wi.WorkflowAutoPublishChanges && !wi.UseCheckInCheckOut(CMSContext.CurrentSiteName))
                {
                    // Automatically publish document
                    node.MoveToPublishedStep(null);
                }
            }
            catch (Exception ex)
            {
                // Delete the document if something failed
                if (newDocumentCreated && (node != null) && (node.DocumentID > 0))
                {
                    DocumentHelper.DeleteDocument(node, TreeProvider, false, true, true);
                }

                args.Message = ex.Message;

                // Log the error
                EventLogProvider.LogException("MultiFileUploader", "UPLOADATTACHMENT", ex);
            }
            finally
            {
                // Create node info string
                string nodeInfo = ((node != null) && (node.NodeID > 0) && args.IncludeNewItemInfo) ? String.Format("'{0}', ", node.NodeID) : "";

                // Ensure message text
                args.Message = HTMLHelper.EnsureLineEnding(args.Message, " ");

                // Call function to refresh parent window
                if (!string.IsNullOrEmpty(args.AfterSaveJavascript))
                {
                    // Calling javascript function with parameters attachments url, name, width, height
                    args.AfterScript += string.Format(@"
                    if (window.{0} != null)
                    {{
                        window.{0}();
                    }}
                    else if((window.parent != null) && (window.parent.{0} != null))
                    {{
                        window.parent.{0}();
                    }}", args.AfterSaveJavascript);
                }

                // Create after script and return it to the silverlight application, this script will be evaluated by the SL application in the end
                args.AfterScript += string.Format(@"
                if (window.InitRefresh_{0} != null)
                {{
                    window.InitRefresh_{0}('{1}', false, false, {2});
                }}
                else {{
                    if ('{1}' != '') {{
                        alert('{1}');
                    }}
                }}",
                                                  args.ParentElementID,
                                                  ScriptHelper.GetString(args.Message.Trim(), false),
                                                  nodeInfo + (args.IsInsertMode ? "'insert'" : "'update'"));

                args.AddEventTargetPostbackReference();
                context.Response.Write(args.AfterScript);
                context.Response.Flush();
            }
        }
Ejemplo n.º 48
0
        /// <summary>
        /// Gets a list of matching commands
        /// </summary>
        /// <param name="pattern">command pattern</param>
        /// <param name="commandOrigin"></param>
        /// <param name="context"></param>
        /// <param name="rediscoverImportedModules"></param>
        /// <param name="moduleVersionRequired"></param>
        /// <returns></returns>
        internal static IEnumerable<CommandInfo> GetMatchingCommands(string pattern, ExecutionContext context, CommandOrigin commandOrigin, bool rediscoverImportedModules = false, bool moduleVersionRequired = false)
        {
            // Otherwise, if it had wildcards, just return the "AvailableCommand"
            // type of command info.
            WildcardPattern commandPattern = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase);

            CmdletInfo cmdletInfo = context.SessionState.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\\Get-Module");
            PSModuleAutoLoadingPreference moduleAutoLoadingPreference = CommandDiscovery.GetCommandDiscoveryPreference(context, SpecialVariables.PSModuleAutoLoadingPreferenceVarPath, "PSModuleAutoLoadingPreference");

            if ((moduleAutoLoadingPreference != PSModuleAutoLoadingPreference.None) &&
                    ((commandOrigin == CommandOrigin.Internal) || ((cmdletInfo != null) && (cmdletInfo.Visibility == SessionStateEntryVisibility.Public))
                    )
                )
            {
                foreach (string modulePath in GetDefaultAvailableModuleFiles(true, false, context))
                {
                    // Skip modules that have already been loaded so that we don't expose private commands.
                    string moduleName = Path.GetFileNameWithoutExtension(modulePath);
                    var modules = context.Modules.GetExactMatchModules(moduleName, all: false, exactMatch: true);
                    PSModuleInfo tempModuleInfo = null;

                    if (modules.Count != 0)
                    {
                        // 1. We continue to the next module path if we don't want to re-discover those imported modules
                        // 2. If we want to re-discover the imported modules, but one or more commands from the module were made private, 
                        //    then we don't do re-discovery
                        if (!rediscoverImportedModules || modules.Exists(module => module.ModuleHasPrivateMembers))
                        {
                            continue;
                        }

                        if (modules.Count == 1)
                        {
                            PSModuleInfo psModule = modules[0];
                            tempModuleInfo = new PSModuleInfo(psModule.Name, psModule.Path, null, null);
                            tempModuleInfo.SetModuleBase(psModule.ModuleBase);

                            foreach (var entry in psModule.ExportedCommands)
                            {
                                if (commandPattern.IsMatch(entry.Value.Name))
                                {
                                    CommandInfo current = null;
                                    switch (entry.Value.CommandType)
                                    {
                                        case CommandTypes.Alias:
                                            current = new AliasInfo(entry.Value.Name, null, context);
                                            break;
                                        case CommandTypes.Workflow:
                                            current = new WorkflowInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context);
                                            break;
                                        case CommandTypes.Function:
                                            current = new FunctionInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context);
                                            break;
                                        case CommandTypes.Filter:
                                            current = new FilterInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context);
                                            break;
                                        case CommandTypes.Configuration:
                                            current = new ConfigurationInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context);
                                            break;
                                        case CommandTypes.Cmdlet:
                                            current = new CmdletInfo(entry.Value.Name, null, null, null, context);
                                            break;
                                        default:
                                            Dbg.Assert(false, "cannot be hit");
                                            break;
                                    }

                                    current.Module = tempModuleInfo;
                                    yield return current;
                                }
                            }

                            continue;
                        }
                    }

                    string moduleShortName = System.IO.Path.GetFileNameWithoutExtension(modulePath);
                    var exportedCommands = AnalysisCache.GetExportedCommands(modulePath, false, context);

                    if (exportedCommands == null) { continue; }

                    tempModuleInfo = new PSModuleInfo(moduleShortName, modulePath, null, null);
                    if (InitialSessionState.IsEngineModule(moduleShortName))
                    {
                        tempModuleInfo.SetModuleBase(Utils.GetApplicationBase(Utils.DefaultPowerShellShellID));
                    }

                    //moduleVersionRequired is bypassed by FullyQualifiedModule from calling method. This is the only place where guid will be involved.
                    if (moduleVersionRequired && modulePath.EndsWith(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase))
                    {
                        tempModuleInfo.SetVersion(ModuleIntrinsics.GetManifestModuleVersion(modulePath));
                        tempModuleInfo.SetGuid(ModuleIntrinsics.GetManifestGuid(modulePath));
                    }

                    foreach (var pair in exportedCommands)
                    {
                        var commandName = pair.Key;
                        var commandTypes = pair.Value;

                        if (commandPattern.IsMatch(commandName))
                        {
                            bool shouldExportCommand = true;

                            // Verify that we don't already have it represented in the initial session state.
                            if ((context.InitialSessionState != null) && (commandOrigin == CommandOrigin.Runspace))
                            {
                                foreach (SessionStateCommandEntry commandEntry in context.InitialSessionState.Commands[commandName])
                                {
                                    string moduleCompareName = null;

                                    if (commandEntry.Module != null)
                                    {
                                        moduleCompareName = commandEntry.Module.Name;
                                    }
                                    else if (commandEntry.PSSnapIn != null)
                                    {
                                        moduleCompareName = commandEntry.PSSnapIn.Name;
                                    }

                                    if (String.Equals(moduleShortName, moduleCompareName, StringComparison.OrdinalIgnoreCase))
                                    {
                                        if (commandEntry.Visibility == SessionStateEntryVisibility.Private)
                                        {
                                            shouldExportCommand = false;
                                        }
                                    }
                                }
                            }

                            if (shouldExportCommand)
                            {
                                if ((commandTypes & CommandTypes.Alias) == CommandTypes.Alias)
                                {
                                    yield return new AliasInfo(commandName, null, context)
                                    {
                                        Module = tempModuleInfo
                                    };
                                }
                                if ((commandTypes & CommandTypes.Cmdlet) == CommandTypes.Cmdlet)
                                {
                                    yield return new CmdletInfo(commandName, implementingType: null, helpFile: null, PSSnapin: null, context: context)
                                    {
                                        Module = tempModuleInfo
                                    };
                                }
                                if ((commandTypes & CommandTypes.Function) == CommandTypes.Function)
                                {
                                    yield return new FunctionInfo(commandName, ScriptBlock.EmptyScriptBlock, context)
                                    {
                                        Module = tempModuleInfo
                                    };
                                }
                                if ((commandTypes & CommandTypes.Configuration) == CommandTypes.Configuration)
                                {
                                    yield return new ConfigurationInfo(commandName, ScriptBlock.EmptyScriptBlock, context)
                                    {
                                        Module = tempModuleInfo
                                    };
                                }
                                if ((commandTypes & CommandTypes.Workflow) == CommandTypes.Workflow)
                                {
                                    yield return new WorkflowInfo(commandName, ScriptBlock.EmptyScriptBlock, context)
                                    {
                                        Module = tempModuleInfo
                                    };
                                }
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 49
0
    private void ReloadForm()
    {
        lblWorkflowInfo.Text = "";

        if ((node != null) && !newdocument && !newculture)
        {
            // Check read permissions
            if (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Read) == AuthorizationResultEnum.Denied)
            {
                RedirectToAccessDenied(String.Format(GetString("cmsdesk.notauthorizedtoreaddocument"), node.NodeAliasPath));
            }
            // Check modify permissions
            else if (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Denied)
            {
                formElem.Enabled = false;
                lblWorkflowInfo.Text = String.Format(GetString("cmsdesk.notauthorizedtoeditdocument"), node.NodeAliasPath);
            }
            else
            {
                // Setup the workflow information
                wi = WorkflowManager.GetNodeWorkflow(node);
                if ((wi != null) && (!newculture))
                {
                    // Get current step info, do not update document
                    WorkflowStepInfo si = null;
                    if (node.IsPublished && (node.DocumentCheckedOutVersionHistoryID <= 0))
                    {
                        si = WorkflowStepInfoProvider.GetWorkflowStepInfo("published", wi.WorkflowID);
                    }
                    else
                    {
                        si = WorkflowManager.GetStepInfo(node, false) ??
                             WorkflowManager.GetFirstWorkflowStep(node, wi);
                    }

                    bool canApprove = WorkflowManager.CanUserApprove(node, CMSContext.CurrentUser);
                    string stepName = si.StepName.ToLower();
                    if (!(canApprove || (stepName == "edit") || (stepName == "published") || (stepName == "archived")))
                    {
                        formElem.Enabled = false;
                    }

                    bool useCheckInCheckOut = wi.UseCheckInCheckOut(CMSContext.CurrentSiteName);
                    if (!node.IsCheckedOut)
                    {
                        // Check-in, Check-out
                        if (useCheckInCheckOut)
                        {
                            // If not checked out, add the check-out information
                            if (canApprove || (stepName == "edit") || (stepName == "published") || (stepName == "archived"))
                            {
                                lblWorkflowInfo.Text = GetString("EditContent.DocumentCheckedIn");
                            }
                            formElem.Enabled = newculture;
                        }
                    }
                    else
                    {
                        // If checked out by current user, add the check-in button
                        int checkedOutBy = node.DocumentCheckedOutByUserID;
                        if (checkedOutBy == CMSContext.CurrentUser.UserID)
                        {
                            // Document is checked out
                            lblWorkflowInfo.Text = GetString("EditContent.DocumentCheckedOut");
                        }
                        else
                        {
                            // Checked out by somebody else
                            string userName = UserInfoProvider.GetUserNameById(checkedOutBy);
                            lblWorkflowInfo.Text = String.Format(GetString("EditContent.DocumentCheckedOutByAnother"), userName);
                            formElem.Enabled = newculture;
                        }
                    }

                    // Document approval
                    switch (stepName)
                    {
                        case "edit":
                        case "published":
                        case "archived":
                            break;

                        default:
                            // If the user is authorized to perform the step, display the approve and reject buttons
                            if (!canApprove)
                            {
                                lblWorkflowInfo.Text += " " + GetString("EditContent.NotAuthorizedToApprove");
                            }
                            break;
                    }
                    // If workflow isn't auto publish or step name isn't 'published' or 'check-in/check-out' is allowed then show current step name
                    if (!wi.WorkflowAutoPublishChanges || (stepName != "published") || useCheckInCheckOut)
                    {
                        lblWorkflowInfo.Text += " " + String.Format(GetString("EditContent.CurrentStepInfo"), HTMLHelper.HTMLEncode(ResHelper.LocalizeString(si.StepDisplayName)));
                    }
                }
            }
        }
        pnlWorkflowInfo.Visible = (lblWorkflowInfo.Text != "");
    }
    /// <summary>
    /// Creates process. Called when the "Create process" button is pressed.
    /// </summary>
    private bool CreateProcess()
    {
        // Create new process object and set its properties
        WorkflowInfo newProcess = new WorkflowInfo()
        {
            WorkflowDisplayName = "My new process",
            WorkflowName = "MyNewProcess",
            WorkflowType = WorkflowTypeEnum.Automation,
            WorkflowRecurrenceType = ProcessRecurrenceTypeEnum.Recurring
        };

        // Save the process
        WorkflowInfoProvider.SetWorkflowInfo(newProcess);

        // Create default steps
        WorkflowStepInfoProvider.CreateDefaultWorkflowSteps(newProcess);

        // Get the step with codename 'Finished' and allow Move to previous
        WorkflowStepInfo finishedStep = WorkflowStepInfoProvider.GetWorkflowStepInfo("Finished", newProcess.WorkflowID);
        finishedStep.StepAllowReject = true;

        // Save the 'Finished' step
        WorkflowStepInfoProvider.SetWorkflowStepInfo(finishedStep);

        return true;
    }
Ejemplo n.º 51
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Workflow" /> class.
 /// </summary>
 /// <param name="client"><see cref="T:TcmCoreService.Client" /></param>
 /// <param name="workflowInfo"><see cref="T:Tridion.ContentManager.CoreService.Client.WorkflowInfo" /></param>
 internal Workflow(Client client, WorkflowInfo workflowInfo)
     : base(client)
 {
     mWorkflowInfo = workflowInfo;
 }
    /// <summary>
    /// Provides operations necessary to create and store new content file.
    /// </summary>
    private void HandleContentUpload()
    {
        string message = string.Empty;
        bool newDocumentCreated = false;

        try
        {
            if (NodeParentNodeID == 0)
            {
                throw new Exception(GetString("dialogs.document.parentmissing"));
            }

            // Check license limitations
            if (!LicenseHelper.LicenseVersionCheck(RequestContext.CurrentDomain, FeatureEnum.Documents, ObjectActionEnum.Insert))
            {
                throw new Exception(GetString("cmsdesk.documentslicenselimits"));
            }

            // Check if class exists
            DataClassInfo ci = DataClassInfoProvider.GetDataClassInfo(SystemDocumentTypes.File);
            if (ci == null)
            {
                throw new Exception(string.Format(GetString("dialogs.newfile.classnotfound"), SystemDocumentTypes.File));
            }

            #region "Check permissions"

            // Get the node
            TreeNode parentNode = TreeProvider.SelectSingleNode(NodeParentNodeID, LocalizationContext.PreferredCultureCode, true);
            if (parentNode != null)
            {
                // Check whether node class is allowed on site and parent node
                if (!DocumentHelper.IsDocumentTypeAllowed(parentNode, ci.ClassID) || (ClassSiteInfoProvider.GetClassSiteInfo(ci.ClassID, parentNode.NodeSiteID) == null))
                {
                    throw new Exception(GetString("Content.ChildClassNotAllowed"));
                }
            }

            // Check user permissions
            if (!RaiseOnCheckPermissions("Create", this))
            {
                if (!MembershipContext.AuthenticatedUser.IsAuthorizedToCreateNewDocument(parentNode, SystemDocumentTypes.File))
                {
                    throw new Exception(string.Format(GetString("dialogs.newfile.notallowed"), NodeClassName));
                }
            }

            #endregion

            // Check the allowed extensions
            CheckAllowedExtensions();

            // Create new document
            string fileName = Path.GetFileNameWithoutExtension(ucFileUpload.FileName);
            string ext = Path.GetExtension(ucFileUpload.FileName);

            if (IncludeExtension)
            {
                fileName += ext;
            }

            // Make sure the file name with extension respects maximum file name
            fileName = TreePathUtils.EnsureMaxFileNameLength(fileName, ci.ClassName);

            node = TreeNode.New(SystemDocumentTypes.File, TreeProvider);
            node.DocumentCulture = LocalizationContext.PreferredCultureCode;
            node.DocumentName = fileName;
            if (NodeGroupID > 0)
            {
                node.SetValue("NodeGroupID", NodeGroupID);
            }

            // Load default values
            FormHelper.LoadDefaultValues(node.NodeClassName, node);
            node.SetValue("FileDescription", "");
            node.SetValue("FileName", fileName);
            node.SetValue("FileAttachment", Guid.Empty);

            // Set default template ID
            node.SetDefaultPageTemplateID(ci.ClassDefaultPageTemplateID);

            // Insert the document
            DocumentHelper.InsertDocument(node, parentNode, TreeProvider);

            newDocumentCreated = true;

            // Add the file
            DocumentHelper.AddAttachment(node, "FileAttachment", ucFileUpload.PostedFile, TreeProvider, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize);

            // Create default SKU if configured
            if (ModuleManager.CheckModuleLicense(ModuleName.ECOMMERCE, RequestContext.CurrentDomain, FeatureEnum.Ecommerce, ObjectActionEnum.Insert))
            {
                node.CreateDefaultSKU();
            }

            // Update the document
            DocumentHelper.UpdateDocument(node, TreeProvider);

            // Get workflow info
            wi = node.GetWorkflow();

            // Check if auto publish changes is allowed
            if ((wi != null) && wi.WorkflowAutoPublishChanges && !wi.UseCheckInCheckOut(SiteContext.CurrentSiteName))
            {
                // Automatically publish document
                node.MoveToPublishedStep(null);
            }
        }
        catch (Exception ex)
        {
            // Delete the document if something failed
            if (newDocumentCreated && (node != null) && (node.DocumentID > 0))
            {
                DocumentHelper.DeleteDocument(node, TreeProvider, false, true);
            }

            message = ex.Message;
        }
        finally
        {
            // Create node info string
            string nodeInfo = "";
            if ((node != null) && (node.NodeID > 0) && (IncludeNewItemInfo))
            {
                nodeInfo = node.NodeID.ToString();
            }

            // Ensure message text
            message = HTMLHelper.EnsureLineEnding(message, " ");

            string containerId = QueryHelper.GetString("containerid", "");

            // Call function to refresh parent window
            string afterSaveScript = null;
            if (!string.IsNullOrEmpty(AfterSaveJavascript))
            {
                afterSaveScript = String.Format(
        @"
        if (window.{0} != null){{
        window.{0}(files);
        }} else if ((window.parent != null) && (window.parent.{0} != null)){{
        window.parent.{0}(files);
        }}",
                    AfterSaveJavascript
                );
            }

            afterSaveScript += String.Format(
        @"
        if (typeof(parent.DFU) !== 'undefined') {{
        parent.DFU.OnUploadCompleted({0});
        }}
        if ((window.parent != null) && (/parentelemid={1}/i.test(window.location.href)) && (window.parent.InitRefresh_{1} != null)){{
        window.parent.InitRefresh_{1}({2}, false, false{3}{4});
        }}
        ",
                ScriptHelper.GetString(containerId),
                ParentElemID,
                ScriptHelper.GetString(message.Trim()),
                ((nodeInfo != "") ? ", '" + nodeInfo + "'" : ""),
                (InsertMode ? ", 'insert'" : ", 'update'")
            );

            ScriptHelper.RegisterStartupScript(this, typeof(string), "afterSaveScript_" + ClientID, ScriptHelper.GetScript(afterSaveScript));
        }
    }
Ejemplo n.º 53
0
 private void LoadFromStore_Load(object sender, EventArgs e)
 {
     if (WorkflowProfiles.Rows.Count > 0)
     {
         foreach (DataRow row in WorkflowProfiles.Rows)
         {
             //Add a row for each workflow type found in the store
             WorkflowInfo wi = new WorkflowInfo();
             wi.AssemblyFullName = (string)row["AssemblyFullName"];
             wi.TypeFullName = (string)row["TypeFullName"];
             if (!workflowList.Items.Contains(wi))
             {
                 workflowList.Items.Add(wi);
             }
         }
     }
     else
     {
         workflowList.Items.Add(NoWorkflowsAvailable);
     }
 }
Ejemplo n.º 54
0
 protected void btnNewContent_OnComplete(object source, WorkflowInfo info)
 {
     contentTree.DataBind();
     contentList.DataBind();
 }