Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Pasang Tamang 258 posts 458 karma points
    Apr 21, 2012 @ 03:36
    Pasang Tamang
    0

    Umbraco 5 Date Folder

    Hi All,

    I've spend few times on playing around with Umbraco 5 API. Simply to know the real scenerio, just choose to create date folder using U5 API. And here I'm sharing the code.

    using System;
    using System.Linq;
    using Umbraco.Cms.Web;
    using Umbraco.Cms.Web.Context;
    using Umbraco.Cms.Web.Model;
    using Umbraco.Cms.Web.Model.BackOffice.Editors;
    using Umbraco.Framework;
    using Umbraco.Framework.Context;
    using Umbraco.Framework.Persistence.Model.Constants;
    using Umbraco.Framework.Tasks;
    using Umbraco.Hive;
    using Umbraco.Hive.RepositoryTypes;
    
    namespace U5DateFolder.Helper
    {
    
        [Task("c9888ab0-7e39-11e1-b0c4-0800200c9a66", TaskTriggers.Hive.Revisions.PostAddOrUpdateOnUnitComplete, ContinueOnFailure = false)]
        public class DateFolder : AbstractTask
        {
            private readonly IUmbracoApplicationContext _appContext;
            protected ContentEditorModel ContentModel;
            private HiveId _parentId;
    
    
            public DateFolder(IFrameworkContext context, IUmbracoApplicationContext appContext)
                : base(context)
            {
                _appContext = appContext;
            }
    
            /// Task execution.
            /// Current task execution context
            public override void Execute(TaskExecutionContext context)
            {
                var currendDocId = ((HiveRevisionPostActionEventArgs)context.EventArgs.CallerEventArgs).Entity.Item.Id;
                var contentNode = _appContext.Hive.Cms().Content.GetById(currendDocId);
    
                if (contentNode.ContentType.Alias != "newsItem") return;
    
                //Get the value of date properties to move date folder structure.
                var postDate = Convert.ToDateTime((contentNode.Attributes["date"].DynamicValue).Date);
    
                //Get the Date Folder document type.
                var doctype = _appContext.Hive.Cms()
                    .GetContentTypeByAlias("dateFolder");
    
                string[] strArray = {
                                        postDate.Year.ToString(), postDate.Month.ToString(),
                                        postDate.Day.ToString()
                                    };
    
                _parentId = contentNode.ParentContent().Id;
    
                if (strArray.Length != 3) return;
    
                foreach (var dateFolderDoc in from nodeName in strArray
                                              where CheckExist(_appContext.Hive.Cms().Content.GetById(_parentId), nodeName)
                                              select _appContext.Hive.Cms().NewRevision(nodeName, nodeName, doctype.Alias, false).SetParent(_parentId).Publish().Commit())
                {
                    _parentId = dateFolderDoc.Content.Id;
                }
    
                ChangeRelations(_appContext.Hive.Cms().Content.GetById(currendDocId),
                                _appContext.Hive.Cms().Content.GetById(_parentId), postDate.Month.ToString());
            }
    
    
            /// Check either the given year, month 
            /// or day is exist or not.
            /// Date folder content node
            /// Name of the content node to be compare
            /// true/false
            private bool CheckExist(Content model, string nodeName)
            {
                //Get child content node's Hive Id of the given content node.
                var dateFolder = model.AllChildIds();
                var rtnVal = true;
    
                foreach (var id in dateFolder.Where(id => _appContext.Hive.Cms().Content.GetById(id).Name == nodeName))
                {
                    rtnVal= false;
                    _parentId = id;
                }
    
                return rtnVal;
            }
    
    
            /// Move the current content node into date folder structure.
            /// Source content node.
            /// Destination parent content node.
            /// Node name of the destination content node.
            private void ChangeRelations(Content sourceDoc, Content destinationParentDoc, string parentNodeName)
            {
                var defRelation =
                    sourceDoc.RelationProxies.GetParentRelations(FixedRelationTypes.DefaultRelationType).First();
    
                if (defRelation == null) return;
    
                var parent = _appContext.Hive.Cms().Content.GetById(defRelation.Item.SourceId);
                var child = _appContext.Hive.Cms().Content.GetById(defRelation.Item.DestinationId);
    
                if (parent.Name == parentNodeName) return;
    
                using (var uow = _appContext.Hive.OpenWriter())
                {
                    var previousParents = uow.Repositories.GetParentRelations(child.Id,
                                                                              FixedRelationTypes.DefaultRelationType);
    
                    if (!previousParents.Any())
                        throw new InvalidOperationException(
                            "Could not find any parents for entity '{0}' with id {1}".InvariantFormat(
                                child.Name, child.Id));
    
                    var toChange = previousParents.FirstOrDefault();
                    var rest = previousParents.Skip(1);
    
                    uow.Repositories.ChangeRelation(toChange, destinationParentDoc.Id, toChange.DestinationId);
                    rest.ForEach(x => uow.Repositories.RemoveRelation(x));
                    uow.Complete();
                }
            }
        }
    }

    May be there is better solution than the above code. So hope if there is than you guys will also share the code.

    Thanks
    PTamang

Please Sign in or register to post replies

Write your reply to:

Draft