Beispiel #1
0
        public Item Calc(int[] program)
        {
            var stack = new Stack<Item>();
            for (long i = 0; i < program.Length; i++)
            {
                if (program[i] == 0)
                {
                    Item temp = new Item();
                    if (stack.Any())
                        temp.Add(stack.Pop());
                    if (stack.Any())
                        temp.Add(stack.Pop());

                    stack.Push(temp);
                }
                else if (program[i] == -1)
                {
                    stack.Push(new Item(0, 1));
                }
                else
                    stack.Push(new Item(program[i], 0));
            }

            return stack.Pop();
        }
Beispiel #2
0
        internal Item AddProductToBasket(Item basket, string productName, int quantity)
        {
            var product = GetProduct(basket, productName);
            if (product == null)
            {
                using (new SecurityDisabler())
                {
                    product = basket.Add(Sitecore.Context.Item.Name, ProductBasketTemplate);
                }

                UpdateProduct(product, quantity, true);
            }
            else
            {
                if (Sitecore.MainUtil.GetBool(product["Purchased"], false))
                {
                    using (new SecurityDisabler())
                    {
                        product.Editing.BeginEdit();
                        product.Name = product.Name + Sitecore.DateUtil.IsoNow;
                        product.Editing.EndEdit();
                    }

                    AddProductToBasket(basket, Sitecore.Context.Item.Name, 1);
                }
                else
                {
                    int amount = 1; // if the product is there there's a minumum of 1 - however this value should not be used anyway because of the next statement
                    int.TryParse(product["Quantity"], out amount);
                    UpdateProduct(product, amount + 1);
                }
            }

            return product;
        }
Beispiel #3
0
 public static BlogHomeItem CreateNewBlog(Item parentItem)
 {
     using (new UserSwitcher("sitecore\\admin", true))
     {
         var name = "blog " + ID.NewID.ToShortID();
         return parentItem.Add(name, Constants.Branches.BlogBranchId);
     }
 }
 public Comment(Item parent, string text, FeedItem feedItem)
     : base(parent.Add(ItemUtil.ProposeValidItemName(text), new Sitecore.Data.TemplateID(Comment.TEMPLATE_ID)))
 {
     using (new EditContext(Item, SecurityCheck.Disable))
     {
         Text = text;
         FeedItem = feedItem;
     }
 }
 public static Item CreateItemPath(Item parent, string itemName, BranchItem branch)
 {
     Item child = parent.Axes.GetChild(itemName);
      if (child == null)
      {
     return parent.Add(itemName, branch);
      }
      return child;
 }
    private static Item GetOrCreateDictionaryItem(string name, Item parent, ID templateID)
    {
      var item = parent.Axes.GetChild(name);
      if (item != null)
        return item;

      try
      {
        return parent.Add(name, new TemplateID(templateID));
      }
      catch (Exception ex)
      {
        throw new InvalidOperationException($"Could not create item {name} under {parent.Name}", ex);
      }
    }
        private Item CreateTree(Item parent, string name, int entryCount)
        {
            var db = parent.Database;
            var branchName = Sitecore.Configuration.Settings.GetSetting("Blog.BlogBranchTemplateID");
            var branchTemplate = (BranchItem)db.GetItem(branchName);

            var categoryTemplate = db.GetTemplate(Constants.CategoryTemplate);

            var blog = parent.Add(name, branchTemplate);
            var startDate = DateTime.Now;

            var categoriesRoot = blog.Axes.GetChild("categories");
            var category1 = categoriesRoot.Add("category 1", categoryTemplate);
            var category2 = categoriesRoot.Add("category 2", categoryTemplate);

            for (int i = 0; i < entryCount; i++)
            {
                startDate = startDate.AddDays(-2);
                var dateString = Sitecore.DateUtil.ToIsoDate(startDate);
                var xml = string.Format(Constants.EntryItemXmlTemplate, i, dateString, dateString);

                var entry = blog.PasteItem(xml, true, PasteMode.Undefined);

                if (i % 3 == 0)
                {
                    entry.Editing.BeginEdit();
                    entry["tags"] += "," + TAG_A;
                    entry.Editing.EndEdit();
                }

                if (i % 7 == 0)
                {
                    entry.Editing.BeginEdit();
                    entry["tags"] += "," + TAG_B;
                    entry.Editing.EndEdit();
                }

                if (i % 2 == 0)
                {
                    entry.Editing.BeginEdit();
                    ((MultilistField)entry.Fields["category"]).Add(category1.ID.ToString());
                    entry.Editing.EndEdit();
                }

                if (i % 4 == 0)
                {
                    entry.Editing.BeginEdit();
                    ((MultilistField)entry.Fields["category"]).Add(category2.ID.ToString());
                    entry.Editing.EndEdit();
                }
            }

            return blog;
        }
        /// <summary>
        /// Archives current poll to the pollItem.
        /// </summary>
        /// <param name="pollItem">The poll item.</param>
        public void ArchiveTo(Item pollItem)
        {
            //copy archive folder if exists
            foreach (Item item in InnerItem.Children)
            {
                if (item.TemplateID == PollConstants.PollArchiveTemplateID)
                {
                    item.CopyTo(pollItem, item.Name);
                    item.Delete();
                }
            }
            //or create archive folder
            if (pollItem.Children[PollConstants.PollArchiveFolderName] == null)
            {
                TemplateItem pollArhiveTemplate = PollConstants.DatabaseContext.Templates[PollConstants.PollArchiveTemplateID];
                Assert.IsNotNull(pollArhiveTemplate, "Poll archive template");

                pollItem.Add(PollConstants.PollArchiveFolderName, pollArhiveTemplate);
            }
            string itemName = string.Format("{0} {1}", InnerItem.Name, DateTime.Today.ToShortDateString().Replace('.', ' '));
            string displayName = itemName;

            if (ItemUtil.GetItemNameError(itemName).Length > 0)
                itemName = ItemUtil.ProposeValidItemName(itemName);

            Item currentPollCopy = InnerItem.CopyTo(pollItem.Children[PollConstants.PollArchiveFolderName], itemName, Data.ID.NewID, false);

            if (displayName != itemName)
            {
                PollItem archivedPoll = new PollItem(currentPollCopy) { DisplayName = displayName };
            }

            //copy all poll options
            foreach (Item item in InnerItem.Children)
            {
                item.CopyTo(currentPollCopy, item.Name);
                item.Delete();
            }
            InnerItem.Delete();
        }
 /// <summary>
 /// will begin looking for or creating letter folders to get a parent node to create the new items in
 /// </summary>
 /// <param name="parentNode">current parent node to create or search folder under</param>
 /// <param name="letter">the letter to folder by</param>
 /// <param name="folderType">folder template type</param>
 /// <returns></returns>
 public static Item GetNameParentNode(Item parentNode, string letter, TemplateItem folderType)
 {
     //get letter folder
     Item letterItem = parentNode.Children[letter];
     if (letterItem == null) {
         //build year folder if you have to
         letterItem = parentNode.Add(letter, folderType);
     }
     //set the parent to year
     return letterItem;
 }
        /// <summary>
        /// will begin looking for or creating date folders to get a parent node to create the new items in
        /// </summary>
        /// <param name="parentNode">current parent node to create or search folder under</param>
        /// <param name="dt">date time value to folder by</param>
        /// <param name="folderType">folder template type</param>
        /// <returns></returns>
        public static Item GetDateParentNode(Item parentNode, DateTime dt, TemplateItem folderType)
        {
            //get year folder
            Item year = parentNode.Children[dt.Year.ToString()];
            if (year == null) {
                //build year folder if you have to
                year = parentNode.Add(dt.Year.ToString(), folderType);
            }
            //set the parent to year
            parentNode = year;

            //get month folder
            Item month = parentNode.Children[dt.ToString("MM")];
            if (month == null) {
                //build month folder if you have to
                month = parentNode.Add(dt.ToString("MM"), folderType);
            }
            //set the parent to year
            parentNode = month;

            //get day folder
            Item day = parentNode.Children[dt.ToString("dd")];
            if (day == null) {
                //build day folder if you have to
                day = parentNode.Add(dt.ToString("dd"), folderType);
            }
            //set the parent to year
            parentNode = day;

            return parentNode;
        }
Beispiel #11
0
 private Item getOrCreateItem(String itemName, TemplateItem itemTemplate, Item ParentItem)
 {
     Item itmNewItem = ParentItem.Children[itemName];
     if (itmNewItem == null)
     {
         itmNewItem = ParentItem.Add(itemName, itemTemplate);
     }
     return itmNewItem;
 }
    private Item CreateLocalDatasourceFolder(Item contextItem)
    {
      var template = contextItem.Database.GetTemplate(Settings.LocalDatasourceFolderTemplate);
      if (template == null)
      {
        Log.Warn($"Cannot find the local datasource folder template '{Settings.LocalDatasourceFolderTemplate}'", this);
        return null;
      }

      using (new SecurityDisabler())
      {
        var datasourceFolder = contextItem.Add(Settings.LocalDatasourceFolderName, template);
        SetLocalDatasourceFolderSortOrder(datasourceFolder);
        return datasourceFolder;
      }
    }
Beispiel #13
0
        public void TestFixtureSetUp()
        {
            // Create test content
            var db = Sitecore.Configuration.Factory.GetDatabase("master");
            var home = db.GetItem("/sitecore/content/home");
            using (new SecurityDisabler())
            {
                home.Paste(File.ReadAllText(HttpContext.Current.Server.MapPath(@"~\test data\MetaBlog content.xml")), true, PasteMode.Overwrite);

                // Retrieve created content items
                m_testRoot = home.Axes.GetChild("test content");
                m_blog1 = m_testRoot.Axes.GetChild("blog1");
                m_blog2 = m_testRoot.Axes.GetChild("blog2");
                m_blog3 = m_testRoot.Axes.GetChild("blog3");

                // Ensure blog 1 entries. Current NewsMover has a bug which is removing them as they are created.
                // Remove the following section once the bug has been fixed
                // START: Workaround
                var template = m_blog1.Database.Templates[Settings.EntryTemplateID];
                var entry11Check = m_blog1.Axes.GetDescendant("Entry11");

                if (entry11Check == null)
                    m_blog1.Add("Entry11", template);

                var entry12Check = m_blog1.Axes.GetDescendant("Entry12");

                if (entry12Check == null)
                {
                    System.Threading.Thread.Sleep(2000);
                    m_blog1.Add("Entry12", template);
                }
                // END: Workaround

                // Create test users
                m_userAuthor = Sitecore.Security.Accounts.User.Create("sitecore\\user1", PASSWORD);
                m_userNothing = Sitecore.Security.Accounts.User.Create("sitecore\\user2", PASSWORD);

                // Add users to roles
                m_userAuthor.Roles.Add(Role.FromName("sitecore\\Sitecore Client Authoring"));

                var rules = new AccessRuleCollection();
                rules.Add(AccessRule.Create(m_userAuthor, AccessRight.ItemWrite, PropagationType.Descendants, AccessPermission.Allow));
                rules.Add(AccessRule.Create(m_userAuthor, AccessRight.ItemDelete, PropagationType.Descendants, AccessPermission.Allow));

                m_blog1.Security.SetAccessRules(rules);
                m_blog2.Security.SetAccessRules(rules);

                ContentHelper.PublishItemAndRequiredAncestors(m_blog1, Sitecore.Configuration.Factory.GetDatabase("web"));

                var entry11 = m_blog1.Axes.GetDescendant("Entry11");
                ContentHelper.PublishItemAndRequiredAncestors(entry11, Sitecore.Configuration.Factory.GetDatabase("web"));

                var entry12 = m_blog1.Axes.GetDescendant("Entry12");
                ContentHelper.PublishItemAndRequiredAncestors(entry12, Sitecore.Configuration.Factory.GetDatabase("web"));

                // Rebuild the search index to ensure all manager calls work as expected
                var index = SearchManager.GetIndex(Settings.SearchIndexName);
                index.Rebuild();
            }

            m_api = new Mod.MetaBlogApi();
        }
        private Item CreateDefaultLanguageItem(string itemName, Dictionary<string, string> fieldsToUpdate, Item newItem, TemplateItem template, Item parentItem) {
            // Add the item to the site tree
            newItem = parentItem.Add(RemoveSpecialCharacters(itemName.Trim()), template);
            //addVersion.
            // Set the new item in editing mode
            // Fields can only be updated when in editing mode
            // (It's like the begin tarnsaction on a database)
            if (fieldsToUpdate != null) {
                newItem.Editing.BeginEdit();
                try {
                    // Assign values to the fields of the new item
                    foreach (var fields in fieldsToUpdate) {
                        if (fields.Key == "Content Thumbnail") {
                            MediaItem mediaItem = DownloadImage(fields.Value);

                            Sitecore.Data.Fields.ImageField image = newItem.Fields[fields.Key];
                            image.Src = Sitecore.Resources.Media.MediaManager.GetMediaUrl(mediaItem);
                            image.Alt = mediaItem.Alt;
                            image.MediaID = mediaItem.ID;

                        }
                        else {
                            newItem.Fields[fields.Key].Value = fields.Value;
                        }
                    }
                    // End editing will write the new values back to the Sitecore
                    // database (It's like commit transaction of a database)
                    newItem.Editing.EndEdit();
                }
                catch (System.Exception ex) {
                    // The update failed, write a message to the log
                    Sitecore.Diagnostics.Log.Error("Could not update item " + newItem.Paths.FullPath + ": " + ex.Message, this);

                    // Cancel the edit (not really needed, as Sitecore automatically aborts
                    // the transaction on exceptions, but it wont hurt your code)
                    newItem.Editing.CancelEdit();
                    Response.Write(newItem.Paths.FullPath);
                    Response.Write(ex.Message);
                    Response.End();
                }
            }

            return newItem;
        }
        private void PopulateSections(Item homeItem)
        {
            using (new SecurityDisabler())
            {

                var sections = homeItem.GetChildren().ToArray();

                if (sections.Length == 0)
                {
                    sections =
                        Enumerable.Range(1, NumberOfSections).Select(
                            i => homeItem.Add("Section" + i, this.folderItemTemplateId)).ToArray();
                }

                foreach (var section in sections)
                {
                    Enumerable.Range(0, ItemsPerSectionPerRun).Select(
                        i =>
                            {
                                var now = DateTime.Now;
                                var hour = now.ToString("HH");
                                var minute = now.ToString("mm");
                                var second = now.ToString("ss");

                                var hourFolder = section.GetChildren().FirstOrDefault(item => item.Name == hour)
                                                 ?? section.Add(hour, this.folderItemTemplateId);

                                var minuteFolder = hourFolder.GetChildren().FirstOrDefault(item => item.Name == minute)
                                                   ?? hourFolder.Add(minute, this.folderItemTemplateId);

                                var secondFolder = minuteFolder.GetChildren().FirstOrDefault(
                                    item => item.Name == second) ?? minuteFolder.Add(second, this.folderItemTemplateId);

                                return secondFolder.Add(
                                    i.ToString(CultureInfo.InvariantCulture), this.sampleItemTemplateId);
                            }).ToArray();
                }
            }
        }
        protected virtual bool CreateItem(object importRow, Item parent, ref Item item, string itemName, ref LevelLogger logger)
        {
            var createItemLogger = logger.CreateLevelLogger();
            try
            {
                if (string.IsNullOrEmpty(itemName))
                {
                    createItemLogger.AddError("Item name could not be parsed", String.Format(
                            "The item name could not be parsed for importRow: {0}. Therefor the item could not be created.",
                            GetImportRowDebugInfo(importRow)));
                    logger.IncrementCounter(IncrementConstants.FailureItems);
                    return false;
                }
                if (parent == null)
                {
                    createItemLogger.AddError("Parent is null", String.Format(
                            "The 'parent' parameter is null. Therefor the item could not be created. ImportRow: {0}.",
                            GetImportRowDebugInfo(importRow)));
                    logger.IncrementCounter(IncrementConstants.FailureItems);
                    return false;
                }
                if (!ToWhatTemplates.Any())
                {
                    createItemLogger.AddError("The 'Import To What Template' item is null", String.Format(
                            "The 'Import To What Template' item is null. ImportRow: {0}. Therefor the item could not be created.",
                            GetImportRowDebugInfo(importRow)));
                    logger.IncrementCounter(IncrementConstants.FailureItems);
                    return false;
                }
                string errorMessage = String.Empty;
                var getToWhatLogger = createItemLogger.CreateLevelLogger();
                CustomItemBase toWhatTemplate = GetToWhatTemplateItem(importRow, ref getToWhatLogger);
                if (getToWhatLogger.HasErrors())
                {
                    getToWhatLogger.AddError("The 'GetToWhatTemplateItem' failed", String.Format(
                            "The 'GetToWhatTemplateItem' method failed with an error. ImportRow: {0}. Therefor the item could not be created. {1}",
                            GetImportRowDebugInfo(importRow), errorMessage));
                    logger.IncrementCounter(IncrementConstants.FailureItems);
                    return false;
                }

                if (toWhatTemplate == null)
                {
                    logger.IncrementCounter(IncrementConstants.FailureItems);
                    return false;
                }

                using (new LanguageSwitcher(ImportToLanguageVersion))
                {
                    var template = toWhatTemplate as TemplateItem;
                    if (template != null)
                    {
                        var templateItem = template;
                        item = parent.Add(itemName, templateItem);
                    }
                    var whatTemplate = toWhatTemplate as BranchItem;
                    if (whatTemplate != null)
                    {
                        var branchItem = whatTemplate;
                        item = parent.Add(itemName, branchItem);
                    }
                }
                if (item == null)
                {
                    createItemLogger.AddError("Created item was null", String.Format("The new item created was null. ImportRow: {0}.", GetImportRowDebugInfo(importRow)));
                    logger.IncrementCounter(IncrementConstants.FailureItems);
                    return false;
                }
                logger.IncrementCounter("Created Items");
                var addItemToCacheLogger = createItemLogger.CreateLevelLogger();
                var keyValue = GetValueFromFieldToIdentifyTheSameItemsBy(importRow, ref addItemToCacheLogger);
                CachingManager.AddItemToCache(Parent, IdentifyTheSameItemsByFieldDefinition.GetNewItemField(), item, keyValue, ref addItemToCacheLogger);
                if (addItemToCacheLogger.HasErrors())
                {
                    addItemToCacheLogger.AddError("The 'AddItemToCache' failed in the CreateItem", String.Format(
                            "The 'AddItemToCache' method failed with an error. ImportRow: {0}. The item was created, but not added to the cache. {1}",
                            GetImportRowDebugInfo(importRow), errorMessage));
                    logger.IncrementCounter(IncrementConstants.FailureItems);
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                createItemLogger.AddError("Exception in CreateItem", String.Format(
                        "An exception occured in CreateItem. Exception: {0}",
                        GetExceptionDebugInfo(ex)));
                logger.IncrementCounter(IncrementConstants.FailureItems);
                return false;
            }
        }
Beispiel #17
0
 private static Item getOrCreateItem(String itemName, TemplateItem itemTemplate, Item ParentItem)
 {
     Item itmNewItem = null;
       try
       {
     string strItemName = ItemUtil.ProposeValidItemName(itemName.Trim());
     itmNewItem = ParentItem.Children[strItemName];
     if (itmNewItem == null)
     {
       itmNewItem = ParentItem.Add(strItemName, itemTemplate);
       //PublishItem(itmNewItem);
     }
       }
       catch (Exception ex)
       {
     logError(ex.ToString());
       }
       return itmNewItem;
 }
Beispiel #18
0
        public void TestFixtureSetUp()
        {
            // Create test content
            using (new SecurityDisabler())
            {
                m_testContentRoot.Paste(File.ReadAllText(HttpContext.Current.Server.MapPath(@"~\test data\MetaBlog content.xml")), true, PasteMode.Overwrite);

              // Retrieve created content items
                m_testRoot = m_testContentRoot.Axes.GetChild("test content");
                m_blog1 = m_testRoot.Axes.GetChild("blog1");
                m_blog2 = m_testRoot.Axes.GetChild("blog2");
                m_blog3 = m_testRoot.Axes.GetChild("blog3");

                // Ensure blog 1 entries. Current NewsMover has a bug which is removing them as they are created.
                // Remove the following section once the bug has been fixed
                // START: Workaround
                var template = m_blog1.Database.Templates[Settings.EntryTemplateID];
                var entry11Check = m_blog1.Axes.GetDescendant("Entry11");

                if (entry11Check == null)
                {
                  var entry = m_blog1.Add("Entry11", template);
                  using (new EditContext(entry))
                  {
                    entry["Entry Date"] = "20120105T233207";
                  }
                }

                var entry12Check = m_blog1.Axes.GetDescendant("Entry12");

                if (entry12Check == null)
                {
                    System.Threading.Thread.Sleep(2000);
                    var entry = m_blog1.Add("Entry12", template);
                    using (new EditContext(entry))
                    {
                      entry["Entry Date"] = "20120106T233145";
                    }
                }

                // END: Workaround

                // Create test users
                // Use random usernames to ensure we're not trying to create users that might already exist
                m_userAuthor = Sitecore.Security.Accounts.User.Create("sitecore\\user" + m_random.Next(999999), PASSWORD);
                m_userNothing = Sitecore.Security.Accounts.User.Create("sitecore\\user" + m_random.Next(999999), PASSWORD);

                // Add users to roles
                m_userAuthor.Roles.Add(Role.FromName("sitecore\\Sitecore Client Authoring"));

                var rules = new AccessRuleCollection();
                rules.Add(AccessRule.Create(m_userAuthor, AccessRight.ItemWrite, PropagationType.Any, AccessPermission.Allow));
                rules.Add(AccessRule.Create(m_userAuthor, AccessRight.ItemDelete, PropagationType.Any, AccessPermission.Allow));
                rules.Add(AccessRule.Create(m_userAuthor, AccessRight.ItemCreate, PropagationType.Any, AccessPermission.Allow));

                m_blog1.Security.SetAccessRules(rules);
                m_blog2.Security.SetAccessRules(rules);

                ContentHelper.PublishItemAndRequiredAncestors(m_blog1, Sitecore.Configuration.Factory.GetDatabase("web"));

                var entry11 = m_blog1.Axes.GetDescendant("Entry11");
                ContentHelper.PublishItemAndRequiredAncestors(entry11, Sitecore.Configuration.Factory.GetDatabase("web"));

                var entry12 = m_blog1.Axes.GetDescendant("Entry12");
                ContentHelper.PublishItemAndRequiredAncestors(entry12, Sitecore.Configuration.Factory.GetDatabase("web"));

                // Rebuild the search index to ensure all manager calls work as expected
#if FEATURE_CONTENT_SEARCH
                var index = ContentSearchManager.GetIndex(Settings.SearchIndexName);
                index.Rebuild();
#else
                var index = SearchManager.GetIndex(Settings.SearchIndexName);
                index.Rebuild();
#endif
            }

            m_api = new Mod.MetaBlogApi();
        }
Beispiel #19
0
        private Item CreateTestContentItem(Item item, TemplateItem template, string name, string content)
        {
            var child = item.Add(name, template);
            child.Editing.BeginEdit();
            child["content"] = content;
            child.Editing.EndEdit();

            return child;
        }
 private Item CreateItemSimple(string itemName, Item parentItem, Item itemTemplate)
 {
     Item result;
     try
     {
         using (new SecurityDisabler())
         {
             Item item = parentItem.Add(itemName, new TemplateID(itemTemplate.ID));
             PhotoAlbumObject.PublishOneItem(item);
             result = item;
         }
     }
     catch (Exception exception)
     {
         Log.Error("Cannot create item", exception, this);
         result = null;
     }
     return result;
 }
Beispiel #21
0
        public void Run()
        {
            Log.Info("**** Starting Data Import ****", this);
            try
            {
                int iCntr = 0;

                if (tiTour != null)
                {
                    foreach (string strFileName in Directory.GetFiles("C:\\Sitecore\\Globus\\Website\\XmlData"))
                    {
                        iCntr = 0;
                        strDataFile = strFileName;
                        strGroup = strFileName.Substring(strFileName.LastIndexOf("\\") + 1).Split(new char[] { '.' })[0];
                        itmGroupFolder = getOrCreateItem(strGroup, tiFolder, itmDataRoot);

                        xmlData.Load(strDataFile);
                        XmlNodeList nlTours = xmlData.SelectNodes("//tour");
                        foreach (XmlNode xnTour in nlTours)
                        {
                            if (((xnTour["publish"]["au"].InnerText == "true" ? 1 : 0) + (xnTour["publish"]["nz"].InnerText == "true" ? 1 : 0) + (xnTour["publish"]["gsa"].InnerText == "true" ? 1 : 0) > 0))
                            {
                                itmSeasonFolder = getOrCreateItem(xnTour["season"].InnerText, tiFolder, itmGroupFolder);

                                //if ((int.Parse(xnTour["season"].InnerText) >= DateTime.Now.Year))
                                {
                                    iCntr++;
                                    LogThis(iCntr.ToString() + " " + xnTour["season"].InnerText + " : " + xnTour["code"].InnerText);
                                    itmTour = getOrCreateItem(xnTour["code"].InnerText, tiTour, itmSeasonFolder);
                                    setTourDetails(xnTour);
                                    itmPublish = getOrCreateItem("Publish", tiPublish, itmTour);
                                    setPublishDetails(xnTour["publish"]);

                                    itmItineraryFolder = itmTour.Children["Itinerary"];
                                    if (itmItineraryFolder == null)
                                    {
                                        itmItineraryFolder = itmTour.Add("Itinerary", tiFolder);
                                    }
                                    foreach (XmlNode xnDay in xnTour["itinerary"].ChildNodes)
                                    {
                                        itmItineraryDay = getOrCreateItem(String.Format("Day {0}", int.Parse(xnDay["day_no"].InnerText).ToString("X3")), tiItineraryDay, itmItineraryFolder);
                                        itmItineraryDay.Editing.BeginEdit();
                                        itmItineraryDay["Day No"] = xnDay["day_no"].InnerText;
                                        itmItineraryDay["Description"] = xnDay["description"].InnerText;
                                        itmItineraryDay["Text"] = xnDay["text"].InnerText;
                                        itmItineraryDay.Editing.EndEdit();
                                    }

                                    if (xnTour["departures"].HasChildNodes)
                                    {
                                        itmDeparturesFolder = getOrCreateItem("Departures", tiFolder, itmTour);
                                        foreach (XmlNode xnDeparture in xnTour["departures"].ChildNodes)
                                        {
                                            itmDeparture = getOrCreateItem(xnDeparture["start_date"].InnerText.Replace("-", "_"), tiDeparture, itmDeparturesFolder);
                                            itmDeparture.Editing.BeginEdit();
                                            itmDeparture["Start Date"] = String.Format("{0}T000000", xnDeparture["start_date"].InnerText.Replace("-", ""));
                                            itmDeparture["End Date"] = String.Format("{0}T000000", xnDeparture["end_date"].InnerText.Replace("-", ""));
                                            itmDeparture["Guaranteed"] = xnDeparture["guaranteed"].InnerText;
                                            itmDeparture.Editing.EndEdit();
                                            if (xnDeparture["coaches"] != null && xnDeparture["coaches"].HasChildNodes)
                                            {
                                                itmCoachesFolder = getOrCreateItem("Coaches and Vessles", tiFolder, itmDeparture);
                                                foreach (XmlNode xnCoach in xnDeparture["coaches"].ChildNodes)
                                                {
                                                    itmCoach = getOrCreateItem("CoachOrVessel", tiCoach, itmCoachesFolder);
                                                    itmCoach.Editing.BeginEdit();
                                                    itmCoach["Name"] = xnCoach["name"].InnerText;
                                                    itmCoach["Allotment Status"] = xnCoach["allotment_status"].InnerText;
                                                    itmCoach.Editing.EndEdit();

                                                    if (xnCoach["price"] != null && xnCoach["price"].HasChildNodes)
                                                    {
                                                        itmPricesFolder = getOrCreateItem("price", tiFolder, itmCoach);
                                                        foreach (XmlNode xnPrice in xnCoach["price"].ChildNodes)
                                                        {
                                                            itmPrice = getOrCreateItem(xnPrice.Name, tiPrice, itmPricesFolder);
                                                            itmPrice.Editing.BeginEdit();
                                                            itmPrice["au"] = xnPrice["au"].InnerText;
                                                            itmPrice["nz"] = xnPrice["nz"].InnerText;
                                                            itmPrice["gsa"] = xnPrice["gsa"].InnerText;
                                                            itmPrice.Editing.EndEdit();
                                                        }
                                                    }

                                                    if (xnCoach["departure_room_types"] != null && xnCoach["departure_room_types"].HasChildNodes)
                                                    {
                                                        itmRoomTypes = getOrCreateItem("Room Types", tiRoomTypes, itmCoach);
                                                        itmRoomTypes.Editing.BeginEdit();
                                                        itmRoomTypes["Single"] = xnCoach["departure_room_types"]["sgl"].InnerText == "true" ? "1" : "0";
                                                        itmRoomTypes["Twin"] = xnCoach["departure_room_types"]["twn"].InnerText == "true" ? "1" : "0";
                                                        itmRoomTypes["Tripple"] = xnCoach["departure_room_types"]["tpl"].InnerText == "true" ? "1" : "0";
                                                        itmRoomTypes.Editing.EndEdit();
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    LogThis("Template not found");
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.ToString(), this);
            }
        }
Beispiel #22
0
        /// <summary>
        /// Gets the or create child.
        /// </summary>
        /// <param name="parent">The parent.</param>
        /// <param name="childName">Name of the child.</param>
        /// <param name="template">The template.</param>
        /// <returns></returns>
        protected Item GetOrCreateChild(Item parent, TemplateItem template, string childName, SortOrder subItemSorting)
        {
            Item child = parent.Children[childName];
            if (child == null)
            {
                child = parent.Add(childName, template);
            }

            // enforce that sub-item sorting is set
            if (subItemSorting != SortOrder.None && child[FieldIDs.SubitemsSorting] != subItemSorting.ToDescription())
            {
                using (new Sitecore.Data.Items.EditContext(child))
                {
                    child.Fields[FieldIDs.SubitemsSorting].Value = subItemSorting.ToDescription();
                }
            }

            return child;
        }
 public static FakeTemplateItem Create(string name, Item parent)
 {
     return parent.Add(name, new TemplateID(ItemTemplateId)).As<FakeTemplateItem>();
 }
        private Item CreateTree(Item parent, string name, int entryCount, out int commentCount, int specificEntry, out int commentCountForEntry)
        {
            commentCount = 0;
            commentCountForEntry = 0;

            var db = parent.Database;
            var branchName = Settings.BlogBranchID;
            var branchTemplate = (BranchItem)db.GetItem(branchName);

            var blog = parent.Add(name, branchTemplate);
            var entryStartDate = DateTime.Now;

            for (var i = 0; i < entryCount; i++)
            {
                entryStartDate = entryStartDate.AddDays(-2);
                var dateString = Sitecore.DateUtil.ToIsoDate(entryStartDate);
                var entryXml = string.Format(Constants.EntryItemXmlTemplate, i, dateString, dateString);

                var entry = blog.PasteItem(entryXml, true, PasteMode.Undefined);

                var commentStartDate = entryStartDate;
                var entryCommentCount = (i % MOD) * MULTIPLIER;
                for (var j = 0; j < entryCommentCount; j++)
                {
                    commentStartDate = commentStartDate.AddDays(0.4);
                    var commentDateString = Sitecore.DateUtil.ToIsoDate(commentStartDate);
                    var commentXml = string.Format(Constants.CommentItemXmlTemplate, j, commentDateString, commentDateString);
                    entry.PasteItem(commentXml, true, PasteMode.Undefined);
                    commentCount++;

                    if (i == specificEntry)
                        commentCountForEntry++;
                }
            }

            return blog;
        }
        private Item CreateAndFillItem(string itemName, Hashtable itemFieldsData, Item destionationItem, Item itemTemplate, bool nameExact)
        {
            Item result;
            using (new SecurityDisabler())
            {
                try
                {
                    string text = this.CheckExistingItemName(destionationItem, itemName, nameExact);
                    if (nameExact && text == string.Empty)
                    {
                        if (itemName == string.Empty)
                        {
                            this.PageErrorMsg = "Enter album name, please";
                            result = null;
                        }
                        else
                        {
                            this.PageErrorMsg = "The album with name \"" + itemName + "\" already exists";
                            result = null;
                        }

                    }
                    else
                    {
                        Item item = destionationItem.Add(text, new TemplateID(itemTemplate.ID));
                        Language[] languages = item.Languages;
                        for (int i = 0; i < languages.Length; i++)
                        {
                            Language language = languages[i];
                            Item item2 = item.Database.GetItem(item.ID, language);
                            if (item2.Versions.Count == 0)
                            {
                                item2 = item2.Versions.AddVersion();
                            }
                            item2.Editing.BeginEdit();
                            foreach (string text2 in itemFieldsData.Keys)
                            {
                                string type;
                                if ((type = item2.Fields[text2].Type) != null && type == "Image")
                                {
                                    if (itemFieldsData[text2] is Item)
                                    {
                                        Item item3 = (Item)itemFieldsData[text2];
                                        MediaItem mediaItem = item3;
                                        ImageField imageField = item2.Fields[text2];
                                        imageField.Src = "~/media" + mediaItem.MediaPath + ".ashx";
                                        imageField.MediaPath = mediaItem.MediaPath;
                                        imageField.MediaID = mediaItem.ID;
                                        imageField.Alt = "photo image";
                                    }
                                }
                                else
                                {
                                    item2[text2] = (string)itemFieldsData[text2];
                                }
                            }
                            item2.Editing.EndEdit();
                        }
                        PhotoAlbumObject.PublishOneItem(item);
                        result = item;
                    }
                }
                catch (Exception exception)
                {
                    Log.Error("Cannot create or edit the item. Possible there are invalid fieds collection", exception, this);
                    result = null;
                }
            }
            return result;
        }