当前位置: 首页>>代码示例>>C#>>正文


C# Item.Add方法代码示例

本文整理汇总了C#中System.Item.Add方法的典型用法代码示例。如果您正苦于以下问题:C# Item.Add方法的具体用法?C# Item.Add怎么用?C# Item.Add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Item的用法示例。


在下文中一共展示了Item.Add方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Calc

        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();
        }
开发者ID:analyst74,项目名称:TopCoder,代码行数:25,代码来源:Suminator.cs

示例2: AddProductToBasket

        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;
        }
开发者ID:Trayek,项目名称:informa,代码行数:35,代码来源:BasketHelper.cs

示例3: Comment

 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;
     }
 }
开发者ID:hermanussen,项目名称:CompiledDomainModel,代码行数:9,代码来源:Comment.cs

示例4: CreateItemPath

 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;
 }
开发者ID:Refactored,项目名称:SitecoreCalendarModule,代码行数:9,代码来源:Utilities.cs

示例5: GetOrCreateDictionaryItem

    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);
      }
    }
开发者ID:GoranHalvarsson,项目名称:Habitat,代码行数:15,代码来源:CreateDictionaryEntryService.cs

示例6: CreateTree

        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;
        }
开发者ID:Quatra,项目名称:WeBlog,代码行数:54,代码来源:EntryManagerPerformance.cs

示例7: ArchiveTo

        /// <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();
        }
开发者ID:Warunika,项目名称:SitecorePollModule,代码行数:44,代码来源:PollItem.cs

示例8: GetNameParentNode

 /// <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;
 }
开发者ID:KoenHeye,项目名称:SitecoreDataImporter,代码行数:18,代码来源:BaseDataMap.cs

示例9: GetDateParentNode

        /// <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;
        }
开发者ID:KoenHeye,项目名称:SitecoreDataImporter,代码行数:38,代码来源:BaseDataMap.cs

示例10: getOrCreateItem

 private Item getOrCreateItem(String itemName, TemplateItem itemTemplate, Item ParentItem)
 {
     Item itmNewItem = ParentItem.Children[itemName];
     if (itmNewItem == null)
     {
         itmNewItem = ParentItem.Add(itemName, itemTemplate);
     }
     return itmNewItem;
 }
开发者ID:paul-at-gruden,项目名称:Test,代码行数:9,代码来源:DataImport.cs

示例11: CreateLocalDatasourceFolder

    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;
      }
    }
开发者ID:alinulms,项目名称:Habitat,代码行数:16,代码来源:GetLocalDatasourceLocation.cs

示例12: TestFixtureSetUp

        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();
        }
开发者ID:kaytee821,项目名称:WeBlog,代码行数:62,代码来源:MetaBlogApi.cs

示例13: CreateDefaultLanguageItem

        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;
        }
开发者ID:D0cNet,项目名称:UnderstoodDotOrg.sln,代码行数:44,代码来源:import.aspx.cs

示例14: PopulateSections

        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();
                }
            }
        }
开发者ID:ctekempel,项目名称:Solving-the-Scaling-Challenge-with-Lucene,代码行数:39,代码来源:RunExamples.aspx.cs

示例15: CreateItem

        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;
            }
        }
开发者ID:NetlabSharedSource,项目名称:SitecoreDataSync,代码行数:91,代码来源:BaseDataMap.cs


注:本文中的System.Item.Add方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。