Пример #1
0
        public override PipelineProcessorResponseValue ProcessRequest()
        {
            var itemTitle = RequestContext.Argument;

            if (ItemUtil.IsItemNameValid(itemTitle))
            {
                var currentItem = RequestContext.Item;
                var currentBlog = ManagerFactory.BlogManagerInstance.GetCurrentBlog(currentItem);
                if (currentBlog != null)
                {
                    var template   = new TemplateID(currentBlog.BlogSettings.CategoryTemplateID);
                    var categories = ManagerFactory.CategoryManagerInstance.GetCategoryRoot(currentItem);
                    var newItem    = ItemManager.AddFromTemplate(itemTitle, template, categories);

                    return(new PipelineProcessorResponseValue
                    {
                        Value = newItem.ID.Guid
                    });
                }
            }
            return(new PipelineProcessorResponseValue
            {
                Value = null
            });
        }
Пример #2
0
 public static Item AddFromTemplateSynchronized([NotNull] this Database database, [NotNull] string itemName, [NotNull] ID templateId, [NotNull] Item destination, [NotNull] ID newItemId)
 {
     lock (SyncRoot)
     {
         return(ItemManager.AddFromTemplate(itemName, templateId, destination, newItemId));
     }
 }
Пример #3
0
        public string newPost(string blogid, string username, string password, XmlRpcStruct rpcstruct, bool publish)
        {
            Authenticate(username, password);
            CheckUserRights(blogid, username);

            var entryTitleRaw = rpcstruct["title"];

            if (entryTitleRaw == null)
            {
                throw new ArgumentException("'title' must be provided");
            }

            var entryTitle  = entryTitleRaw.ToString();
            var currentBlog = GetContentDatabase().GetItem(blogid);

            if (currentBlog != null)
            {
                BlogHomeItem blogItem = currentBlog;
                var          template = new TemplateID(blogItem.BlogSettings.EntryTemplateID);
                var          newItem  = ItemManager.AddFromTemplate(entryTitle, template, currentBlog);

                SetItemData(newItem, rpcstruct);

                if (publish)
                {
                    ContentHelper.PublishItemAndRequiredAncestors(newItem.ID);
                }

                return(newItem.ID.ToString());
            }
            else
            {
                return(string.Empty);
            }
        }
Пример #4
0
        private Item HandleDelete(Item newItem, string newItemName, CustomItemBase nItemTemplate, Item parent, object importRow)
        {
            if (PreserveChildren)
            {
                var temp = parent.Add("temp", new TemplateID(TemplateIDs.StandardTemplate));
                foreach (Item child in newItem.Children.Where(x => x.TemplateID != ComponentsFolderTemplateId))
                {
                    child.MoveTo(temp);
                }
                newItem.Delete();
                newItem = ItemManager.AddFromTemplate(newItemName, nItemTemplate.ID, parent, ((Item)importRow).ID);

                foreach (Item child in temp.Children)
                {
                    child.MoveTo(newItem);
                }
                temp.Delete();
            }
            else
            {
                newItem.Delete();
                newItem = null;
            }
            return(newItem);
        }
Пример #5
0
        public string newPost(string blogid, string username, string password, XmlRpcStruct rpcstruct, bool publish)
        {
            Authenticate(username, password);
            CheckUserRights(blogid, username);

            var entryTitle  = rpcstruct["title"].ToString();
            var currentBlog = ContentHelper.GetContentDatabase().GetItem(blogid);

            if (currentBlog != null)
            {
                // test
                var access = Sitecore.Security.AccessControl.AuthorizationManager.GetAccess(currentBlog, Sitecore.Context.User, Sitecore.Security.AccessControl.AccessRight.ItemCreate);
                // end test

                BlogHomeItem blogItem = currentBlog;
                var          template = new TemplateID(blogItem.BlogSettings.EntryTemplateID);
                var          newItem  = ItemManager.AddFromTemplate(entryTitle, template, currentBlog);

                SetItemData(newItem, rpcstruct);

                if (publish)
                {
                    ContentHelper.PublishItemAndRequiredAncestors(newItem.ID);
                }

                return(newItem.ID.ToString());
            }
            else
            {
                return(string.Empty);
            }
        }
Пример #6
0
        protected Item CreateTargetItem(SyncItem syncItem, Item destinationParentItem)
        {
            Database database = Factory.GetDatabase(syncItem.DatabaseName);

            if (destinationParentItem == null)
            {
                throw new ParentItemNotFoundException
                      {
                          ParentID = syncItem.ParentID,
                          ItemID   = syncItem.ID
                      };
            }

            var templateId = ID.Parse(syncItem.TemplateID);
            var itemId     = ID.Parse(syncItem.ID);

            AssertTemplate(database, templateId, syncItem.ItemPath);

            Item targetItem = ItemManager.AddFromTemplate(syncItem.Name, templateId, destinationParentItem, itemId);

            if (targetItem == null)
            {
                throw new DeserializationException("Creating " + syncItem.DatabaseName + ":" + syncItem.ItemPath + " failed. API returned null.");
            }

            targetItem.Versions.RemoveAll(true);

            return(targetItem);
        }
        protected MediaItem HandleMediaItem(IDataMap map, Item parentItem, string itemPath, MediaItem item)
        {
            var itemName = StringUtility.GetValidItemName(item.Name, 100);
            //date info
            string newFilePath = string.Format("{0}/{1}", parentItem.Paths.FullPath, itemName);

            // see if it exists in med lib

            IEnumerable <Item> matches = parentItem.Axes.GetDescendants()
                                         .Where(a => a.Paths.FullPath.EndsWith(itemName));

            if (matches != null && matches.Any())
            {
                if (matches.Count().Equals(1))
                {
                    return(new MediaItem(matches.First()));
                }

                map.Logger.Log("MediaFileMapping.HandleMediaItem", string.Format("Sitecore image lookup matched {0} for item {1}", matches.Count(), itemPath));
                return(null);
            }

            ItemManager.AddFromTemplate(itemName, TemplateIDs.UnversionedImage, BuildMediaPath(map.ToDB, item.InnerItem.Paths.ParentPath), item.ID);

            MediaItem m = ImportMediaItem(item.GetMediaStream(), itemName + "." + item.Extension, newFilePath);

            if (m == null)
            {
                map.Logger.Log("MediaFileMapping.HandleMediaItem", string.Format("Image Not Found for item '{0}'", itemPath));
            }

            return(m);
        }
Пример #8
0
        protected Item CreateTargetItem(IItemData serializedItemData, Item destinationParentItem)
        {
            Database database = Factory.GetDatabase(serializedItemData.DatabaseName);

            if (destinationParentItem == null)
            {
                throw new ParentItemNotFoundException
                      {
                          ParentID = new ID(serializedItemData.ParentId).ToString(),
                          ItemID   = new ID(serializedItemData.Id).ToString()
                      };
            }

            AssertTemplate(database, new ID(serializedItemData.TemplateId), serializedItemData.Path);

            Item targetItem = ItemManager.AddFromTemplate(serializedItemData.Name, new ID(serializedItemData.TemplateId), destinationParentItem, new ID(serializedItemData.Id));

            if (targetItem == null)
            {
                throw new DeserializationException("Creating " + serializedItemData.DatabaseName + ":" + serializedItemData.Path + " failed. API returned null.");
            }

            targetItem.Versions.RemoveAll(true);

            return(targetItem);
        }
Пример #9
0
        private void UpdateSection([NotNull] Template template, [NotNull] Section section)
        {
            Debug.ArgumentNotNull(template, nameof(template));
            Debug.ArgumentNotNull(section, nameof(section));

            if (section.Item == null)
            {
                if (string.IsNullOrEmpty(section.ID))
                {
                    section.ID = Guid.NewGuid().ToString("B").ToUpperInvariant();
                }

                section.Item = ItemManager.AddFromTemplate(section.Name, new TemplateID(TemplateIDs.TemplateSection), template.Item, new ID(section.ID));
            }
            else
            {
                if (section.Item.ParentID != template.Item.ID)
                {
                    section.Item.MoveTo(template.Item);
                }

                if (section.Item.Name != section.Name)
                {
                    section.Item.Editing.BeginEdit();
                    section.Item.Name = section.Name;
                    section.Item.Editing.EndEdit();
                }
            }

            foreach (var field in section.Fields)
            {
                UpdateField(section, field);
            }
        }
Пример #10
0
        private void UpdateField([NotNull] Section section, [NotNull] Field field)
        {
            Debug.ArgumentNotNull(section, nameof(section));
            Debug.ArgumentNotNull(field, nameof(field));

            if (field.Item == null)
            {
                if (string.IsNullOrEmpty(field.ID))
                {
                    field.ID = Guid.NewGuid().ToString("B").ToUpperInvariant();
                }

                field.Item = ItemManager.AddFromTemplate(field.Name, new TemplateID(TemplateIDs.TemplateField), section.Item, new ID(field.ID));
            }
            else if (field.Item.ParentID != section.Item.ID)
            {
                field.Item.MoveTo(section.Item);
            }

            field.Item.Editing.BeginEdit();

            field.Item.Name           = field.Name;
            field.Item["Type"]        = field.Type;
            field.Item["Shared"]      = field.Shared ? "1" : string.Empty;
            field.Item["Unversioned"] = field.Unversioned ? "1" : string.Empty;
            /* field.Item["Title"] = field.Title; */
            field.Item["Source"]        = field.Source;
            field.Item["Validator Bar"] = field.ValidatorBar;

            field.Item.Editing.EndEdit();
        }
Пример #11
0
        protected void Run(ClientPipelineArgs args)
        {
            if (args.IsPostBack)
            {
                if (args.HasResult)
                {
                    var itemTitle = args.Result;

                    var db = Sitecore.Configuration.Factory.GetDatabase(args.Parameters["database"]);
                    if (db != null)
                    {
                        var currentItem = db.GetItem(args.Parameters["currentid"]);
                        if (currentItem != null)
                        {
                            var currentBlog = ManagerFactory.BlogManagerInstance.GetCurrentBlog(currentItem);
                            if (currentBlog != null)
                            {
                                var  template = new TemplateID(currentBlog.BlogSettings.EntryTemplateID);
                                Item newItem  = ItemManager.AddFromTemplate(itemTitle, template, currentBlog);

                                ContentHelper.PublishItem(newItem);
                            }
                            else
                            {
                                Log.Error("Failed to locate blog root item", this);
                            }
                        }
                    }
                }
            }
            else
            {
                var db = Sitecore.Configuration.Factory.GetDatabase(args.Parameters["database"]);
                if (db == null)
                {
                    return;
                }
                var currentItem = db.GetItem(args.Parameters["currentid"]);
                if (currentItem == null)
                {
                    return;
                }

                if (!currentItem.TemplateIsOrBasedOn(Settings.BlogTemplateID) && !currentItem.TemplateIsOrBasedOn(Settings.EntryTemplateID))
                {
                    Context.ClientPage.ClientResponse.Alert("Please create or select a blog first");
                }
                else
                {
                    SheerResponse.Input("Enter the title of your new entry:", "", Configuration.Settings.ItemNameValidation, Translator.Text("'$Input' is not a valid title."), 100);
                    args.WaitForPostBack(true);
                }
            }
        }
Пример #12
0
        private void CreateNewTemplate([NotNull] Database database, [NotNull] Template template)
        {
            Debug.ArgumentNotNull(database, nameof(database));
            Debug.ArgumentNotNull(template, nameof(template));

            Item root = null;

            if (!string.IsNullOrEmpty(template.ParentPath))
            {
                root = database.GetItem(template.ParentPath);

                if (root == null && !ID.IsID(template.ParentPath))
                {
                    var innerItem = database.GetItem(TemplateIDs.TemplateFolder);
                    if (innerItem != null)
                    {
                        var templateFolder = new TemplateItem(innerItem);
                        root = database.CreateItemPath(template.ParentPath, templateFolder, templateFolder);
                    }
                }
            }

            if (root == null)
            {
                root = database.GetItem(ItemIDs.TemplateRoot);
                if (root == null)
                {
                    return;
                }

                var item = root.Children["User Defined"];
                if (item != null)
                {
                    root = item;
                }
            }

            if (string.IsNullOrEmpty(template.ID))
            {
                template.ID = Guid.NewGuid().ToString("B").ToUpperInvariant();
            }

            template.Item = ItemManager.AddFromTemplate(template.Name, new TemplateID(TemplateIDs.Template), root, new ID(template.ID));

            template.Item.Editing.BeginEdit();
            template.Item[FieldIDs.BaseTemplate] = template.BaseTemplates;
            template.Item.Appearance.Icon        = template.Icon;
            template.Item.Editing.EndEdit();

            foreach (var section in template.Sections)
            {
                UpdateSection(template, section);
            }
        }
Пример #13
0
        internal static void ImportPosts(Item blogItem, List <WpPost> listWordpressPosts, Database db, Action <string, int> logger = null)
        {
            BlogHomeItem customBlogItem = blogItem;
            var          entryTemplate  = TemplateManager.GetTemplate(customBlogItem.BlogSettings.EntryTemplateID, db);

            var processCount = 0;

            foreach (WpPost post in listWordpressPosts)
            {
                processCount++;

                if (!string.IsNullOrEmpty(post.Content))
                {
                    var name = ItemUtil.ProposeValidItemName(post.Title);

                    if (logger != null)
                    {
                        logger(name, processCount);
                    }

                    EntryItem entry = ItemManager.AddFromTemplate(name, entryTemplate.ID, blogItem);

                    entry.BeginEdit();
                    entry.Title.Field.Value        = post.Title;
                    entry.Introduction.Field.Value = string.Empty;
                    entry.Content.Field.Value      = post.Content;
                    entry.Tags.Field.Value         = string.Join(", ", post.Tags.ToArray());

                    var categorieItems = new List <string>();

                    foreach (string categoryName in post.Categories)
                    {
                        var categoryItem = ManagerFactory.CategoryManagerInstance.Add(categoryName, blogItem);
                        categorieItems.Add(categoryItem.ID.ToString());
                    }

                    if (categorieItems.Count > 0)
                    {
                        entry.Category.Field.Value = string.Join("|", categorieItems.ToArray());
                    }

                    foreach (WpComment wpComment in post.Comments)
                    {
                        ManagerFactory.CommentManagerInstance.AddCommentToEntry(entry.ID, wpComment);
                    }

                    var publicationDate = DateUtil.ToIsoDate(post.PublicationDate);
                    entry.InnerItem.Fields[FieldIDs.Created].Value = publicationDate;
                    entry.InnerItem.Fields["Entry Date"].Value     = publicationDate;
                    entry.EndEdit();
                }
            }
        }
 protected virtual Item Create(string itemName, ID templateId, Item rootItem, ID itemId)
 {
     try
     {
         return(ItemManager.AddFromTemplate(itemName, templateId, rootItem, itemId));
     }
     catch (Exception ex)
     {
         LogHelper.Error("Error during item creation. ItemId:" + itemId, this, ex);
     }
     return(null);
 }
        private void CreateEaPlans()
        {
            var database = Context.ContentDatabase ?? Database.GetDatabase("master");

            foreach (var plan in _eaPlanInfos)
            {
                var item = database.GetItem(ID.Parse(plan.EaPlanId));

                if (item != null)
                {
                    plan.Name = $"Storefront {item.DisplayName}";
                    ItemManager.AddFromTemplate(plan.Name, ID.Parse(plan.EaPlanId), database.GetItem(CommerceConnectEaPlanParentId), ID.Parse(plan.ItemId));
                    continue;
                }

                Log.Error($"Error creating engagement plan '{plan.Name}'.", this);
            }
        }
        /// <summary>
        /// Creates the Engagement Plans
        /// </summary>
        protected virtual void CreateEaPlans()
        {
            var database = Context.ContentDatabase ?? Database.GetDatabase("master");

            foreach (var plan in this._eaPlanInfos)
            {
                var item = database.GetItem(ID.Parse(plan.EaPlanId));

                if (item != null)
                {
                    plan.Name = string.Format(CultureInfo.InvariantCulture, EaPlanFormatString, StorefrontConstants.Settings.WebsiteName, item.DisplayName);
                    var result = ItemManager.AddFromTemplate(plan.Name, ID.Parse(plan.EaPlanId), database.GetItem(StorefrontConstants.KnownItemIds.CommerceConnectEaPlanParentId), ID.Parse(plan.ItemId));
                    continue;
                }

                CommerceLog.Current.Error(string.Format(CultureInfo.InvariantCulture, "Error creating engagement plan '{0}'.", plan.Name), this);
            }
        }
Пример #17
0
        protected void Run(ClientPipelineArgs args)
        {
            var db          = ContentHelper.GetContentDatabase();
            var currentItem = db.GetItem(args.Parameters["currentid"]);

            if (args.IsPostBack)
            {
                if (args.HasResult)
                {
                    string itemTitle = args.Result;

                    var blogItem = ManagerFactory.BlogManagerInstance.GetCurrentBlog(currentItem);

                    if (blogItem == null)
                    {
                        SheerResponse.Alert("Failed to locate the blog item to add the category to.", true);
                        return;
                    }

                    var template   = new TemplateID(blogItem.BlogSettings.CategoryTemplateID);
                    var categories = ManagerFactory.CategoryManagerInstance.GetCategoryRoot(currentItem);
                    var newItem    = ItemManager.AddFromTemplate(itemTitle, template, categories);

                    ContentHelper.PublishItem(newItem);

                    SheerResponse.Eval("scForm.browser.getParentWindow(scForm.browser.getFrameElement(window).ownerDocument).location.reload(true)");

                    args.WaitForPostBack(true);
                }
            }
            else
            {
                if (!currentItem.TemplateIsOrBasedOn(Settings.BlogTemplateID) && !currentItem.TemplateIsOrBasedOn(Settings.EntryTemplateID))
                {
                    Context.ClientPage.ClientResponse.Alert("Please create or select a blog first");
                }
                else
                {
                    SheerResponse.Input("Enter the name of your new category:", "", Configuration.Settings.ItemNameValidation, Translator.Text("'$Input' is not a valid name."), 100);
                    args.WaitForPostBack(true);
                }
            }
        }
Пример #18
0
        public void ShouldAddVersionOneWhenAddFromTemplate()
        {
            // arrange
            using (var db = new Db {
                new DbTemplate("Sample", this.templateId)
                {
                    "Title"
                }
            })
            {
                var root = db.GetItem("/sitecore/content");

                // act
                var item = ItemManager.AddFromTemplate("home", this.templateId, root);

                // assert
                item.Versions.Count.Should().Be(1);
            }
        }
Пример #19
0
        public static Item CreateIntegrationItem([NotNull] string itemName, [NotNull] Item destination, [NotNull] ID templateId, [NotNull] ID newId)
        {
            Assert.ArgumentNotNull(itemName, "itemName");
            Assert.ArgumentNotNull(destination, "destination");
            Assert.ArgumentNotNull(templateId, "templateId");
            Assert.ArgumentNotNull(newId, "newId");

            if (!IntegrationDisabler.CurrentValue &&
                (IsActiveIntegrationConfigItem(destination) ||
                 IsActiveIntegrationFolder(destination)))
            {
                using (new IntegrationDisabler())
                {
                    return(ItemManager.AddFromTemplate(itemName, templateId, destination, newId));
                }
            }

            return(null);
        }
Пример #20
0
        /// <summary>
        /// Adds a new category.
        /// </summary>
        /// <param name="categoryName">Name of the category.</param>
        /// <param name="item">The item.</param>
        /// <returns></returns>
        public CategoryItem Add(string categoryName, Item item)
        {
            Item blogItem = item;
            var  template = GetDatabase().GetTemplate(Settings.BlogTemplateID);


            if (template != null)
            {
                //Check if current item equals blogroot
                while (blogItem != null && !blogItem.TemplateIsOrBasedOn(template))
                {
                    blogItem = blogItem.Parent;
                }

                // Get all categories from current blog
                CategoryItem[] categories = GetCategories(blogItem);

                // If there are categories, check if it already contains the categoryName
                if (categories.Count() > 0)
                {
                    var resultList = categories.Where(x => x.Title.Raw.ToLower() == categoryName.ToLower());
                    var result     = resultList.Count() == 0 ? null : resultList.First();

                    // If category is found return ID
                    if (result != null)
                    {
                        return(result);
                    }
                }

                // Category doesn't exist so create it
                var categoriesFolder = blogItem.Axes.GetChild("Categories");

                CategoryItem newCategory = ItemManager.AddFromTemplate(categoryName, new ID(CategoryItem.TemplateId), categoriesFolder);
                newCategory.BeginEdit();
                newCategory.Title.Field.Value = categoryName;
                newCategory.EndEdit();

                return(newCategory);
            }
            return(null);
        }
Пример #21
0
        public void ShouldAddFromTemplate()
        {
            // arrange
            using (var db = new Db {
                new DbTemplate(this.templateId)
            })
            {
                var destination = db.GetItem("/sitecore/content");

                // act
                var result = ItemManager.AddFromTemplate(ItemName, this.templateId, destination, this.itemId);

                // assert
                db.GetItem("/sitecore/content/home").Should().NotBeNull();

                result.Name.Should().Be(ItemName);
                result.ID.Should().Be(this.itemId);
                result.TemplateID.Should().Be(this.templateId);
                result.Parent.Should().Be(destination);
            }
        }
Пример #22
0
        /// <summary>
        /// Adds a new category.
        /// </summary>
        /// <param name="categoryName">Name of the category.</param>
        /// <param name="item">The item.</param>
        /// <returns></returns>
        public virtual CategoryItem Add(string categoryName, Item item)
        {
            if (item == null)
            {
                Logger.Warn("Could not create a new category item because paremater 'item' was null", this);
                return(null);
            }

            // Get all categories from current blog
            var categories = GetCategories(item);

            // If there are categories, check if it already contains the categoryName
            if (categories.Any())
            {
                var existingCategory = categories.Where(x => x.Title.Raw.CompareTo(categoryName) == 0);
                if (existingCategory.Any())
                {
                    return(existingCategory.First());
                }
            }

            // Category doesn't exist so create it
            var categoryRoot = GetCategoryRoot(item) ?? CreateCategoryRoot(item);

            if (categoryRoot == null)
            {
                Logger.Warn("New category item cannot be created. Could not find the category root item.", this);
                return(null);
            }

            CategoryItem newCategory = ItemManager.AddFromTemplate(categoryName, Settings.CategoryTemplateIds.First(), categoryRoot);

            newCategory.BeginEdit();
            newCategory.Title.Field.Value = categoryName;
            newCategory.EndEdit();

            return(newCategory);
        }
Пример #23
0
        public void ShouldCreateAndEditItemUsingItemManager()
        {
            // arrange
            using (var db = new Db {
                new DbTemplate("Sample", this.templateId)
                {
                    "Title"
                }
            })
            {
                var root = db.GetItem("/sitecore/content");

                // act
                var item = ItemManager.AddFromTemplate("home", this.templateId, root);
                using (new EditContext(item))
                {
                    item["Title"] = "Hello";
                }

                // assert
                item["Title"].Should().Be("Hello");
            }
        }
Пример #24
0
        public override PipelineProcessorResponseValue ProcessRequest()
        {
            var itemTitle   = RequestContext.Argument;
            var currentItem = RequestContext.Item;
            var currentBlog = ManagerFactory.BlogManagerInstance.GetCurrentBlog(currentItem);

            if (currentBlog != null)
            {
                var  template = new TemplateID(currentBlog.BlogSettings.EntryTemplateID);
                Item newItem  = ItemManager.AddFromTemplate(itemTitle, template, currentBlog);

                ContentHelper.PublishItem(newItem);

                return(new PipelineProcessorResponseValue
                {
                    Value = newItem.ID.Guid
                });
            }
            return(new PipelineProcessorResponseValue
            {
                Value = null
            });
        }
        public static Item CreateItem(
            [NotNull] ID integrationItemID,
            [NotNull] ID integrationItemTemplateID,
            [NotNull] SharepointBaseItem sourceSharepointItem,
            [NotNull] SynchContext synchContext)
        {
            Assert.ArgumentNotNull(integrationItemID, "integrationItemID");
            Assert.ArgumentNotNull(integrationItemTemplateID, "integrationItemTemplateID");
            Assert.ArgumentNotNull(sourceSharepointItem, "sourceSharepointItem");
            Assert.ArgumentNotNull(synchContext, "synchContext");

            var validName = MediaPathManager.ProposeValidMediaPath(sourceSharepointItem.Title);

            Item integrationItem = ItemManager.AddFromTemplate(validName, integrationItemTemplateID, synchContext.ParentItem, integrationItemID);

            var folderItem = sourceSharepointItem as FolderItem;

            if (folderItem != null && integrationItem != null)
            {
                UpdateIntegrationConfigData(integrationItem, folderItem, synchContext);
            }

            return(integrationItem);
        }
Пример #26
0
        public string Execute([NotNull] string databaseName, [NotNull] string itemId, [NotNull] string name, [NotNull] string location, [NotNull] string templateId)
        {
            var database = Factory.GetDatabase(databaseName);

            if (database == null)
            {
                throw new InvalidOperationException("Database not found");
            }

            var owner = database.GetItem(itemId);

            if (owner == null)
            {
                throw new InvalidOperationException("Item not found");
            }

            var templateItem = database.GetItem(templateId);

            if (owner == null)
            {
                throw new InvalidOperationException("Template item not found");
            }

            Item parentItem;

            if (ID.IsID(location))
            {
                parentItem = database.GetItem(location);
            }
            else
            {
                string path;
                if (string.IsNullOrEmpty(location))
                {
                    path = owner.Paths.Path;
                }
                else
                {
                    path = location.StartsWith("/") ? location : owner.Paths.Path + "/" + location;
                }

                parentItem = database.GetItem(path);
                if (parentItem == null)
                {
                    var folderTemplate = new TemplateItem(database.GetItem(TemplateIDs.Folder));
                    parentItem = database.CreateItemPath(path, folderTemplate);
                }
            }

            if (parentItem == null)
            {
                throw new InvalidOperationException("Location item not found");
            }

            var newItemName = name + " Data Source";
            var index       = 2;

            while (parentItem.Children[newItemName] != null)
            {
                newItemName = name + " Data Source " + index;
                index++;
            }

            var newItem = ItemManager.AddFromTemplate(newItemName, templateItem.ID, parentItem);

            if (newItem == null)
            {
                throw new InvalidOperationException("Could not create data source item");
            }

            return(newItem.ID + "," + parentItem.ID);
        }
Пример #27
0
        internal ImportSummary ImportPosts(Item blogItem, TemplatesMapping mapping, Action <string, int> logger = null)
        {
            var summary = new ImportSummary();

            var entryTemplate = TemplateManager.GetTemplate(mapping.BlogEntryTemplate, _db);

            foreach (WpPost post in Posts)
            {
                summary.PostCount++;

                if (!string.IsNullOrEmpty(post.Content))
                {
                    var title = post.Title;
                    title = String.IsNullOrEmpty(title) ? $"Post {Posts.IndexOf(post)}" : title;
                    var name = ItemUtil.ProposeValidItemName(title);

                    if (logger != null)
                    {
                        logger(name, summary.PostCount);
                    }

                    EntryItem entry = ItemManager.AddFromTemplate(name, entryTemplate.ID, blogItem);

                    entry.BeginEdit();
                    entry.Title.Field.Value        = post.Title;
                    entry.Introduction.Field.Value = string.Empty;
                    entry.Content.Field.Value      = post.Content;
                    entry.Tags.Field.Value         = string.Join(", ", post.Tags.ToArray());

                    var categorieItems = new List <string>();

                    foreach (string categoryName in post.Categories)
                    {
                        var categoryItem = ManagerFactory.CategoryManagerInstance.Add(categoryName, blogItem);
                        categoryItem.InnerItem.ChangeTemplate(categoryItem.Database.GetItem(mapping.BlogCategoryTemplate));
                        categorieItems.Add(categoryItem.ID.ToString());
                        summary.CategoryCount++;
                    }

                    if (categorieItems.Count > 0)
                    {
                        entry.Category.Field.Value = string.Join("|", categorieItems.ToArray());
                    }

                    foreach (WpComment wpComment in post.Comments)
                    {
                        var commentId = ManagerFactory.CommentManagerInstance.AddCommentToEntry(entry.ID, wpComment, blogItem.Language);
                        var comment   = entry.Database.GetItem(commentId, blogItem.Language);
                        comment?.ChangeTemplate(comment.Database.GetItem(mapping.BlogCommentTemplate));

                        summary.CommentCount++;
                    }

                    var publicationDate = DateUtil.ToIsoDate(post.PublicationDate);
                    entry.InnerItem.Fields[FieldIDs.Created].Value = publicationDate;
                    entry.InnerItem.Fields["Entry Date"].Value     = publicationDate;
                    entry.EndEdit();
                }
            }

            return(summary);
        }
Пример #28
0
        private void ProcessComponents(Item parent, object importRow, IEnumerable <ComponentMapping> componentMappings)
        {
            using (new LanguageSwitcher(ImportToLanguage))
            {
                //get the parent in the specific language
                foreach (var componentMapping in componentMappings ?? Enumerable.Empty <ComponentMapping>())
                {
                    try
                    {
                        if (!string.IsNullOrEmpty(componentMapping.Rendering) && !string.IsNullOrEmpty(componentMapping.Placeholder))
                        {
                            CleanRenderings(parent, componentMapping.Rendering, componentMapping.Placeholder);
                        }
                        var items = componentMapping.GetImportItems((Item)importRow);
                        foreach (var item in items)
                        {
                            if ((componentMapping.RequiredFields.Any()))
                            {
                                var requiredValues = GetFieldValues(componentMapping.RequiredFields, item);
                                if (requiredValues.Any(x => string.IsNullOrEmpty(x)))
                                {
                                    Logger.Log("SitecoreDataMap.ProcessComponents", string.Format("Missing required field for component {0} on item {1}", componentMapping.ComponentName, ((Item)item).ID));
                                    continue;
                                }
                            }
                            Item folder = parent;
                            if (!string.IsNullOrEmpty(componentMapping.FolderName))
                            {
                                var folderPath = parent.Paths.FullPath + "/" + componentMapping.FolderName;
                                folder = ToDB.GetItem(folderPath);
                                if (folder == null)
                                {
                                    Logger.Log("SitecoreDataMap.ProcessComponents", string.Format("Could not find component Folder at {0}", folderPath));
                                    folder = parent;
                                }
                            }


                            var  nItemTemplate = GetComponentItemTemplate(item, componentMapping);
                            Item newItem;
                            //search for the child by name
                            var name = componentMapping.ComponentName;
                            switch (name)
                            {
                            case "$name":
                            case "@@name":
                                name = item.Name;
                                break;

                            case "$outcomePostQuestionName":
                                var questionName = item.Name.Replace('P', 'B');
                                name = GetChild(folder, questionName) != null ? questionName: item.Name;
                                break;
                            }
                            newItem = GetChild(folder, name);
                            if (newItem != null)                             //add version for lang
                            {
                                if (componentMapping.PreserveComponentId && newItem.ID != item.ID)
                                {
                                    UpdateReferences(newItem, item.ID);
                                    newItem.Delete();
                                    newItem = null;
                                }
                                else
                                {
                                    newItem = newItem.Versions.AddVersion();
                                }
                            }
                            //if not found then create one
                            if (newItem == null)
                            {
                                if (componentMapping.PreserveComponentId)
                                {
                                    newItem = ItemManager.AddFromTemplate(name, nItemTemplate.ID, folder, item.ID);
                                }
                                else
                                {
                                    newItem = ItemManager.AddFromTemplate(name, nItemTemplate.ID, folder);
                                }
                            }

                            if (newItem == null)
                            {
                                throw new NullReferenceException("the new item created was null");
                            }

                            using (new EditContext(newItem, true, false))
                            {
                                ProcessFields(item, newItem, componentMapping);
                            }

                            using (new EditContext(newItem, true, false))
                            {
                                ProcessReferenceFields(ref newItem, item, componentMapping.ReferenceFieldDefinitions);
                            }
                            using (new EditContext(newItem, true, false))
                            {
                                ProcessComponents(newItem, item, componentMapping);
                            }
                            using (new EditContext(newItem, true, false))
                            {
                                //calls the subclass method to handle custom fields and properties
                                ProcessCustomData(ref newItem, item, componentMapping);
                            }
                            if (!string.IsNullOrEmpty(componentMapping.Rendering) && !string.IsNullOrEmpty(componentMapping.Placeholder))
                            {
                                AddRendering(parent, componentMapping.Rendering, componentMapping.Placeholder, newItem);
                            }

                            Logger.Log("SitecoreDataMap.CreateNewItem", $"Import ID:{item.ID.Guid}, Import Path:{item.Paths.FullPath}, New ID:{newItem.ID.Guid}, New Path:{newItem.Paths.FullPath}");
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Log("SitecoreDataMap.ProcessComponents", string.Format("failed to import component {0} on item {1}", componentMapping.ComponentName, parent.Paths.FullPath));
                    }
                }
            }
        }
Пример #29
0
        protected virtual void Run(ClientPipelineArgs args)
        {
            //Cancel button
            if (args.IsPostBack && !args.HasResult)
            {
                return;
            }

            Database db = Factory.GetDatabase(args.Parameters["database"]);

            TemplateItem templateItem = db.Templates[this.GetTemplateId(args)];
            Item         parent       = db.GetItem(this.GetParentId(args));

            if (templateItem == null || parent == null)
            {
                return;
            }

            if (string.IsNullOrEmpty(this.GetEntityName(args)))
            {
                if (args.HasResult)
                {
                    this.SetEntityName(args, args.Result);

                    args.Result = "undefined";
                }
                else
                {
                    Context.ClientPage.ClientResponse.Input(
                        Translate.Text(Texts.ENTER_THE_NAME_OF_THE_NEW_ITEM),
                        templateItem.DisplayName,
                        Settings.ItemNameValidation,
                        Translate.Text(Texts.INPUT_IS_NOT_A_VALID_NAME),
                        100);
                    args.WaitForPostBack();
                }
            }

            if (!string.IsNullOrEmpty(this.GetEntityName(args)) && string.IsNullOrEmpty(this.GetEntityId(args)))
            {
                if (args.HasResult)
                {
                    this.SetEntityId(args, args.Result);

                    args.Result = "undefined";
                }
                else
                {
                    Context.ClientPage.ClientResponse.Input(
                        Translate.Text(Translations.EnterTheEntityId),
                        string.Empty,
                        this.EntityIdValidation,
                        Translate.Text(Texts.INPUT_IS_NOT_A_VALID_NAME),
                        100);
                    args.WaitForPostBack();
                }
            }

            string entityName = this.GetEntityName(args);
            string entityId   = this.GetEntityId(args);

            if (string.IsNullOrEmpty(entityName) || string.IsNullOrEmpty(entityId))
            {
                return;
            }

            Item accountItem = AccountManager.GetAccountItemForDescendant(parent);

            if (accountItem == null)
            {
                return;
            }

            ID itemId = this.GenerateItemId(args, accountItem);

            Item item = ItemManager.AddFromTemplate(entityName, templateItem.ID, parent, itemId);

            if (item == null)
            {
                return;
            }

            using (new EditContext(item))
            {
                string entityIdField = this.GetEntityIdField(args);

                Assert.IsNotNullOrEmpty(entityIdField, "entityIdField is null or empty");

                item[entityIdField] = entityId;

                string entityNameField = this.GetEntityNameField(args);

                if (!string.IsNullOrEmpty(entityNameField))
                {
                    item[entityNameField] = entityName;
                }
            }
        }
Пример #30
0
        public override Item CreateNewItem(Item parent, object importRow, string newItemName)
        {
            CustomItemBase nItemTemplate = GetNewItemTemplate(importRow);

            newItemName = RewritePath(newItemName);
            using (new LanguageSwitcher(ImportToLanguage))
            {
                //get the parent in the specific language
                parent = ToDB.GetItem(parent.ID);

                Item newItem;
                //search for the child by name
                if (AllowItemNameMatch)
                {
                    newItem = GetChild(parent, newItemName);
                }
                else
                {
                    newItem = ToDB.GetItem(((Item)importRow).ID);
                }
                if (newItem != null)                 //add version for lang
                {
                    if (DeleteOnOverwrite)
                    {
                        newItem = HandleDelete(newItem, newItemName, nItemTemplate, parent, importRow);
                    }
                    else
                    {
                        if (newItem.ParentID != parent.ID)
                        {
                            newItem.MoveTo(parent);
                        }
                        newItem = newItem.Versions.AddVersion();
                    }
                }

                //if not found then create one
                if (newItem == null)
                {
                    newItem = ItemManager.AddFromTemplate(newItemName, nItemTemplate.ID, parent, GetItemID(((Item)importRow)));
                }

                if (newItem == null)
                {
                    throw new NullReferenceException("the new item created was null");
                }

                //if found and is default template, change it to the correct one
                if (newItem.TemplateID == ImportToWhatTemplate.ID && nItemTemplate.ID != ImportToWhatTemplate.ID)
                {
                    using (new EditContext(newItem, true, false))
                    {
                        newItem.ChangeTemplate(new TemplateItem(nItemTemplate.InnerItem));
                    }
                }

                using (new EditContext(newItem, true, false))
                {
                    ProcessFields(importRow, newItem);
                }
                using (new EditContext(newItem, true, false))
                {
                    ProcessReferenceFields(ref newItem, importRow);
                }
                using (new EditContext(newItem, true, false))
                {
                    ProcessComponents(newItem, importRow);
                }
                using (new EditContext(newItem, true, false))
                {
                    //calls the subclass method to handle custom fields and properties
                    ProcessCustomData(ref newItem, importRow);
                }

                Logger.Log("SitecoreDataMap.CreateNewItem", $"Import ID:{((Item) importRow).ID.Guid}, Import Path:{((Item)importRow).Paths.FullPath}, New ID:{newItem.ID.Guid}, New Path:{newItem.Paths.FullPath}");

                return(newItem);
            }
        }