Ejemplo n.º 1
0
        /// <summary>
        /// Changes the workflow state for the given item
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>ChangeWorkflowResponse.</returns>
        public ChangeWorkflowResponse ChangeWorkflow(ChangeWorkflowRequest request)
        {
            var response = new ChangeWorkflowResponse
            {
                IsSuccess = false
            };

            var item = this._workflowRepository.GetItem(request.ItemId, request.Language);

            Sitecore.Workflows.IWorkflow wf = this._workflowRepository.GetWorkflow(item);

            if (wf != null)
            {
                try
                {
                    var result = wf.Execute(request.CommandId, item, request.Comment, false, new object[] { string.Empty });

                    response.IsSuccess = result.Succeeded;
                    response.Message   = result.Message;
                }
                catch (Exception ex)
                {
                    response.Message = ex.Message;
                    this._logger.LogError(ex.Message, ex);
                }
            }

            return(response);
        }
Ejemplo n.º 2
0
        // add item version
        public static void UpdateItemInformation(Item item, Sitecore.Workflows.WorkflowState newState)
        {
            if (item == null || String.IsNullOrEmpty(item.Fields["__Default workflow"].Value))
            {
                return;
            }
            try
            {
                Item isIntialVersionInWeb = Sitecore.Configuration.Factory.GetDatabase("web").GetItem(item.ID);
                Sitecore.Workflows.IWorkflow currnetItemWorkflow = item.Database.WorkflowProvider.GetWorkflow(item);
                if (!currnetItemWorkflow.GetState(item).FinalState&& item.Fields["__Workflow state"].Value != ID.Parse(newState.StateID).ToString())
                {
                    using (new Sitecore.SecurityModel.SecurityDisabler())
                    {
                        // Update New Workflow state first
                        item.Editing.BeginEdit();
                        item.Fields["__Workflow state"].Value = ID.Parse(newState.StateID).ToString();
                        item.Locking.Unlock();
                        item.Editing.EndEdit();

                        // If it is final state
                        if (newState.FinalState)
                        {
                            Item updatedItem = item.Versions.AddVersion();
                            updatedItem.Editing.BeginEdit();
                            updatedItem.Fields["__Workflow state"].Value = ID.Parse(newState.StateID).ToString();
                            updatedItem.Locking.Unlock();
                            updatedItem.Editing.EndEdit();
                        }
                    }
                }
                Sitecore.Diagnostics.Log.Audit("HealthIS WP- Finish updating item \"" + item.Paths.FullPath + "\"", item);
            }
            catch (Exception ex)
            {
                Sitecore.Diagnostics.Log.Error("HealthIS WP- Error while updating item \"" + item.Paths.FullPath + "\"", ex, item);
            }

            try
            {
                // If it is final state, find any media item in the datasoure and publish
                if (newState.FinalState)
                {
                    foreach (Field field in item.Fields)
                    {
                        // Media Field
                        if (FieldTypeManager.GetField(field) is ImageField && !String.IsNullOrEmpty(field.Value))
                        {
                            ImageField imagePath = field;
                            Item       mediaItem = imagePath.MediaItem.Paths.Item;

                            // Publish image item
                            using (new Sitecore.SecurityModel.SecurityDisabler())
                            {
                                Database source  = Sitecore.Configuration.Factory.GetDatabase("master");
                                Database target  = Sitecore.Configuration.Factory.GetDatabase("web");
                                var      options = new Sitecore.Publishing.PublishOptions(source, target,
                                                                                          Sitecore.Publishing.PublishMode.SingleItem, mediaItem.Language,
                                                                                          DateTime.Now)
                                {
                                    RootItem = mediaItem,
                                    Deep     = false,
                                };
                                var publisher = new Sitecore.Publishing.Publisher(options);
                                publisher.PublishAsync();
                            }
                            Sitecore.Diagnostics.Log.Audit("HealthIS WP- Finish updating media item field \"" + field.Value + "\" in the item \"" + mediaItem.Paths.FullPath + "\"", mediaItem);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Sitecore.Diagnostics.Log.Error("HealthIS WP- Error while updating media item in \"" + item.Paths.FullPath + "\"", ex, item);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="i"></param>
        /// <param name="commandID">Optional: if included, the command will be executed</param>
        /// <returns>The workflow state of the item (after workflow command has executed, if given one)</returns>
        public ArticleWorkflowState ExecuteCommandAndGetWorkflowState(Item i, string commandID)
        {
            using (new Sitecore.SecurityModel.SecurityDisabler())
            {
                IWorkflow workflow = i.State.GetWorkflow();

                if (workflow == null)
                {
                    //uh oh
                    return(new ArticleWorkflowState());
                }

                if (commandID != null)
                {
                    //var oldWorkflow = workflow.WorkflowID;
                    // This line will cause the workflow field to be set to null... sometimes
                    workflow.Execute(commandID, i, "comments", false);
                    //var info = new WorkflowInfo(oldWorkflow, i.Fields[Sitecore.FieldIDs.WorkflowState].Value);
                    //i.Database.DataManager.SetWorkflowInfo(i, info);
                    //i.Fields[Sitecore.FieldIDs.Workflow].Value = oldWorkflow;
                }
                var state = new ArticleWorkflowState();

                var currentState = workflow.GetState(i);
                state.DisplayName = currentState.DisplayName;
                state.IsFinal     = currentState.FinalState;

                var commands = new List <ArticleWorkflowCommand>();
                foreach (Sitecore.Workflows.WorkflowCommand command in workflow.GetCommands(i))
                {
                    var wfCommand = new PluginModels.ArticleWorkflowCommand();
                    wfCommand.DisplayName = command.DisplayName;
                    wfCommand.StringID    = command.CommandID;

                    ICommand commandItem = _sitecoreMasterService.GetItem <ICommand>(new Guid(command.CommandID));

                    IState stateItem = _sitecoreMasterService.GetItem <IState>(commandItem.Next_State);

                    if (stateItem == null)
                    {
                        //_logger.Warn("WorkflowController.ExecuteCommandAndGetWorkflowState: Next state for command [" + command.CommandID + "] is null!");
                    }
                    else
                    {
                        wfCommand.SendsToFinal     = stateItem.Final;
                        wfCommand.GlobalNotifyList = new List <StaffStruct>();

                        foreach (var x in stateItem.Staffs)
                        {
                            var staffItem = _sitecoreMasterService.GetItem <IStaff_Item>(x._Id);
                            if (staffItem.Inactive)
                            {
                                continue;
                            }

                            var staffMember = new StaffStruct {
                                ID = staffItem._Id
                            };
                            //staffMember.Name = x.GetFullName();
                            //staffMember.Publications = x.Publications.ListItems.Select(p => p.ID.ToGuid()).ToArray();
                            wfCommand.GlobalNotifyList.Add(staffMember);
                        }

                        commands.Add(wfCommand);
                    }
                }

                state.Commands = commands;

                return(state);
            }
        }
        public override void Apply(T ruleContext)
        {
            SC.Diagnostics.Assert.ArgumentNotNull(ruleContext, "ruleContext");
            SC.Diagnostics.Assert.ArgumentNotNull(
                ruleContext.Item,
                "ruleContext.Item");

            if (ruleContext.Item.IsStandardValuesOrBranchTemplate())
            {
                return;
            }

            SC.Diagnostics.Assert.ArgumentNotNullOrEmpty(
                this.WorkflowCommandID,
                "WorkflowCommandID");
            SC.Diagnostics.Assert.ArgumentNotNullOrEmpty(
                this.Comment,
                "Comment");
            SC.Data.Items.Item workflowCommand =
                ruleContext.Item.Database.GetItem(this.WorkflowCommandID);
            SC.Diagnostics.Assert.IsNotNull(workflowCommand, "workflowCommand");
            SC.Data.Templates.Template checkTemplate =
                SC.Data.Managers.TemplateManager.GetTemplate(workflowCommand);
            SC.Diagnostics.Assert.IsTrue(
                checkTemplate.InheritsFrom(SC.TemplateIDs.WorkflowCommand),
                "workflow command template");
            SC.Data.Items.Item commandWorkflow = workflowCommand.GetAncestorWithTemplateThatIsOrInheritsFrom(
                SC.TemplateIDs.Workflow);

            // before invoking a workflow command,
            // put the item in the appropriate workflow and workflow state
            if (commandWorkflow == null)
            {
                throw new Exception("Unable to determine workflow from workflow command");
            }

            SC.Data.Items.Item commandState = workflowCommand.GetAncestorWithTemplateThatIsOrInheritsFrom(
                SC.TemplateIDs.WorkflowState);

            if (commandState == null)
            {
                throw new Exception("Unable to determine workflow state from workflow command");
            }

            if (ruleContext.Item[SC.FieldIDs.Workflow] != commandWorkflow.ID.ToString())
            {
                using (new SC.Data.Items.EditContext(ruleContext.Item))
                {
                    ruleContext.Item[SC.FieldIDs.Workflow] = commandWorkflow.ID.ToString();
                }
            }

            if (ruleContext.Item[SC.FieldIDs.WorkflowState] != commandState.ID.ToString())
            {
                using (new SC.Data.Items.EditContext(ruleContext.Item))
                {
                    ruleContext.Item[SC.FieldIDs.WorkflowState] = commandState.ID.ToString();
                }
            }

            SC.Workflows.IWorkflow workflow = ruleContext.Item.State.GetWorkflow();
            SC.Diagnostics.Assert.IsNotNull(workflow, "workflow");
            workflow.Execute(
                this.WorkflowCommandID,
                ruleContext.Item,
                this.Comment,
                false,
                new object[] {});
        }
Ejemplo n.º 5
0
        public ActionResult HealthIS_Blog_CreateNewPost(HealthIS.Apps.MVC.Blog.Models.CreateNewPost writeBlogPost)
        {
            if (ModelState.IsValid)
            {
                Item newArticle = null;

                //Database masterDb = Sitecore.Configuration.Factory.GetDatabase("master");
                Item         articleRoot           = writeBlogPost.MasterDb.GetItem(writeBlogPost.ArticleRootPath.ID);
                Item         authorProfileRoot     = writeBlogPost.MasterDb.GetItem(BlogSettings.AuthorProfileLibrary.ID);
                TemplateItem blogTemplate          = writeBlogPost.MasterDb.GetTemplate(writeBlogPost.TemplatePath.ID);
                TemplateItem authorProfileTemplate = writeBlogPost.MasterDb.GetTemplate(BlogSettings.AuthorProfileTemplate.ID);
                string       currentUsername       = writeBlogPost.UserInformation.Profile.UserName.Replace("\\", "");

                using (new SecurityDisabler())
                {
                    if (blogTemplate == null)
                    {
                        Sitecore.Diagnostics.Log.Audit(this, "Template: '" + writeBlogPost.ArticleRootPath.ID + "' is not available");
                        return(View(writeBlogPost));
                    }
                    if (articleRoot == null)
                    {
                        Sitecore.Diagnostics.Log.Audit(this, "Root Item: '" + writeBlogPost.ArticleRootPath.ID + "' is not available");
                        return(View(writeBlogPost));
                    }
                    if (authorProfileRoot != null && !authorProfileRoot.Axes.GetDescendants().Where(c => c.Name.Equals(currentUsername)).Any())
                    {
                        Item newAuthor = authorProfileRoot.Add(currentUsername.Trim(), authorProfileTemplate);
                    }

                    // Convert item name
                    string convertItemName = writeBlogPost.Title.Trim();
                    string ex        = @"[$@&+,:;/=?@#|~{}'`=+<>\[\].^*()\%!’" + "\"" + "]";
                    var    regexItem = new System.Text.RegularExpressions.Regex(ex);
                    if (regexItem.IsMatch(convertItemName))
                    {
                        convertItemName = System.Text.RegularExpressions.Regex.Replace(convertItemName, ex, "");
                    }

                    string preg = Sitecore.Configuration.Settings.GetSetting("ItemNameValidation");
                    Sitecore.Diagnostics.Error.Assert(System.Text.RegularExpressions.Regex.IsMatch(convertItemName, preg), "Item name is invalid.");

                    // Update Title field
                    newArticle = articleRoot.Add(convertItemName, blogTemplate);
                    newArticle.Editing.BeginEdit();
                    newArticle.Fields["__Display name"].Value = convertItemName + "_Draft";
                    newArticle.Fields["Title"].Value          = writeBlogPost.Title;
                    newArticle.Fields["Meta Title"].Value     = writeBlogPost.Title;
                    newArticle.Fields["Author"].Value         = writeBlogPost.GetUserFullName(writeBlogPost.UserInformation.Profile.UserName);
                    newArticle.Fields["pubDate"].Value        = newArticle.Fields["__Created by"].Value;
                    Sitecore.Workflows.IWorkflow workflow = writeBlogPost.MasterDb.WorkflowProvider.GetWorkflow(newArticle.Fields["__Default workflow"].Value);
                    workflow.Start(newArticle);
                    newArticle.Editing.EndEdit();
                }
                if (newArticle != null)
                {
                    //// Redirect to new article item as relative path
                    //string newArticlePath = newArticle.Paths.Path.ToString().ToLower();
                    //newArticlePath = newArticlePath.Replace(Sitecore.Context.Data.Site.RootPath.ToLower(), "");
                    //newArticlePath = newArticlePath.Replace(Sitecore.Context.Data.Site.StartItem.ToLower(), "");

                    return(Redirect("/?sc_mode=edit&sc_itemid=" + newArticle.ID.ToString() + "&sc_lang=en"));
                }
            }
            else
            {
                return(Redirect("/?sc_mode=preview&sc_itemid=" + Sitecore.Context.Item.ID.ToString() + "&sc_lang=en"));
            }
            return(View(writeBlogPost));
        }
        //public void PublishAuthorProfile(Item dataItem)
        //{
        //    // Match Created By field
        //    string createdBy = dataItem.Statistics.CreatedBy.Replace("\\", "");
        //    Item getUserProfileItem = BlogSettings.AuthorProfileLibrary.Axes.GetDescendants().Where(c => c.Name.Equals(createdBy)).FirstOrDefault();
        //    Item itemInWeb = targetDb.GetItem(getUserProfileItem.ID);
        //    if (getUserProfileItem != null && (itemInWeb == null || getUserProfileItem.Statistics.Revision != itemInWeb.Statistics.Revision))
        //    {
        //        Sitecore.Publishing.PublishOptions publishOptions = new Sitecore.Publishing.PublishOptions(masterDb,
        //            targetDb,
        //            Sitecore.Publishing.PublishMode.SingleItem,
        //            getUserProfileItem.Language,
        //            System.DateTime.Now);

        //        Sitecore.Publishing.Publisher publisher = new Sitecore.Publishing.Publisher(publishOptions);
        //        publisher.Options.RootItem = getUserProfileItem;
        //        publisher.Options.Deep = false;
        //        publisher.Options.PublishRelatedItems = true;
        //        publisher.Publish();
        //    }
        //}

        public void PublishPostItem(Item dataItem)
        {
            Item item = dataItem;

            // Add new version / Update Workflow / Keep inital created date for RSS Feed Sort
            using (new Sitecore.SecurityModel.SecurityDisabler())
            {
                if (Sitecore.Data.Database.GetDatabase("web").GetItem(item.ID) != null)
                {
                    Sitecore.Workflows.IWorkflow     workflow    = item.Database.WorkflowProvider.GetWorkflow(item);
                    Sitecore.Workflows.WorkflowState newState    = workflow.GetStates().FirstOrDefault(state => state.FinalState == true);
                    Sitecore.Data.Fields.DateField   pubDateTime = item.Fields["pubDate"];

                    string originalAuthor = dataItem.Fields["__Created by"].Value;

                    item = dataItem.Versions.AddVersion();
                    item.Editing.BeginEdit();
                    item.Fields["__Workflow state"].Value = newState.StateID.ToString();
                    item.Fields["__Created"].Value        = pubDateTime.Value;
                    item.Fields["__Created by"].Value     = originalAuthor;
                    item.Locking.Unlock();
                    item.Editing.EndEdit();
                }
            }

            //// Clearing master db cache
            //ClearCaches.ClearDatabaseCache(masterDb, item);

            // Author Profile - Republish
            if (BlogSettings.AuthorProfileLibrary != null)
            {
                PublihsingMethod(BlogSettings.AuthorProfileLibrary, Sitecore.Publishing.PublishMode.SingleItem, true, true);
            }

            // Media Library - Smart Publish
            Item imageLibrary = masterDb.GetItem(BlogSettings.ImageLibrary);

            if (imageLibrary != null)
            {
                PublihsingMethod(imageLibrary, Sitecore.Publishing.PublishMode.Smart, true);
            }

            // Tag Repository - Smart Publish
            if (BlogSettings.TagRepository != null)
            {
                PublihsingMethod(BlogSettings.TagRepository, Sitecore.Publishing.PublishMode.Smart, true);
            }

            // Post - Republish
            if (item != null)
            {
                PublihsingMethod(item, Sitecore.Publishing.PublishMode.SingleItem, false);
            }

            //// Clearing web db cache
            //ClearCaches.ClearDatabaseCache(targetDb, item);

            // Refresh the new post for search index web
            if (Sitecore.Data.Database.GetDatabase("web").GetItem(item.ID) != null)
            {
                var tempItem = (SitecoreIndexableItem)Sitecore.Data.Database.GetDatabase("web").GetItem(item.ID);
                // Replace master with web
                string searchIndexWeb = BlogSettings.SearchIndexName.Replace("master", "web");
                Sitecore.ContentSearch.ContentSearchManager.GetIndex(searchIndexWeb).Refresh(tempItem);
                Sitecore.Diagnostics.Log.Audit("Search Indexing: " + searchIndexWeb, this);
            }
        }