Tuesday, February 2, 2016

Add, update and delete Sitecore Items Programmatically

Cheat Sheat

Before we start below are the cheat sheat that can serve as starting point to understand sitecore item at ease

Sitecore.Data Library
  • Context
  • Configuration
  • Factory
  • Database
  • SecurityModel
  • Template
  • TemplateId
  • Items
  • Item
  • Field
  • Sitecore.SecurityModel
  • Sitecore.Configuration.Factory
  • Sitecore.Data.Managers.LanguageManager
  • Sitecore.Context.Language
  • Sitecore.Data.Items.Item
  • Sitecore.Publishing.Pipelines.PublishItem.PublishItemPipeline

***Each item exists in a database, and you can either use use the context database:

Sitecore.Data.Database context = Sitecore.Context.Database;
  • Item item= context.GetItem("/sitecore/content");
  • Sitecore.Data.Items.Item item = context.GetItem(Sitecore.ItemIDs.ContentRoot);

***Or you can explicitly reference a named database, such as the Master database:
Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master");
  • master.GetItem("/sitecore/content");
  • master.Items["/sitecore/content"];
  • master.GetTemplate();

***If needed, you can access a specific version of a specific language:
Sitecore.Data.Items.Item version = context.GetItem(item.ID,
  Sitecore.Data.Managers.LanguageManager.GetLanguage("en"),
  new Sitecore.Data.Version(1));

***You can also retrieve items by URI:
Sitecore.Data.ItemUri homeUri = new Sitecore.Data.ItemUri(
  "sitecore://master/{110D559F-DEA5-42EA-9C1C-8A5DF7E70EF9}?lang=en&ver=1");
Sitecore.Data.Items.Item home = Sitecore.Data.Database.GetItem(uri); 

***To retrieve a child with a specific key:
Sitecore.Data.Items.Item home = item.Children["home"];

1. Create Item Using Tempate
public void CreateItem()
{
  //Again we need to handle security
  //In this example we just disable it
  using (new Sitecore.SecurityModel.SecurityDisabler())
  {
    //First get the parent item from the master database
     Database masterDb = Sitecore.Configuration.Factory.GetDatabase("master");
    
//Get Parent Node.
     Item parentItem = masterDb.Items["/sitecore/content/home"];

 
    //Now we need to get the template from which the item is created
    TemplateItem template = masterDb.GetTemplate("sample/sample item");
 
 
    //Now we can add the new item as a child to the parent
    parentItem.Add("NewItemName", template);

  }
}

2. Update Item Field Value
public void UpdateItem()
{
  //Use a security disabler to allow changes
  using (new Sitecore.SecurityModel.SecurityDisabler())
  {
    //You want to alter the item in the master database, so get the item from there
    Database db = Sitecore.Configuration.Factory.GetDatabase("master");
    Item item = db.Items["/sitecore/content/home"];
 
 
    //Begin editing
    item.Editing.BeginEdit();
    try
    {
      //perform the editing
      item.Fields["Title"].Value = "This value will be stored";
    }
    catch (Exception ex)
    {
       Sitecore.Diagnostics.Log.Error("Could not update item " + item.Paths.FullPath + ": " + ex.Message, this);
       item.Editing.CancelEdit();
    }
    finally
    {
       //Close the editing state
       item.Editing.EndEdit();
    }
  }
}

3. Publish Item
public void PublishItem(Item item)
{
 //We need the target database
        Database webDb = Sitecore.Configuration.Factory.GetDatabase("web");

       //We need to know the language to publish. Here we use the context language
        Language language = Sitecore.Context.Language;

       //We set the publish date to now
        DateTime publishTime = DateTime.Now;
  
       //Now we can create the publish options
        Sitecore.Publishing.PublishOptions options = new PublishOptions(masterDb, webDb, PublishMode.SingleItem, language, publishTime);
 
       //Activate the publishpipeline
        Sitecore.Publishing.Pipelines.PublishItem.PublishItemPipeline.Run(item.ID, options);

}

If cache is a concern above pipeline option is required.
4. Publish with Options
 private void PublishItem(Sitecore.Data.Items.Item item)
{
  // The publishOptions determine the source and target database,
  // the publish mode and language, and the publish date
  Sitecore.Publishing.PublishOptions publishOptions =
    new Sitecore.Publishing.PublishOptions(item.Database,
                                           Database.GetDatabase("web"),
                                           Sitecore.Publishing.PublishMode.SingleItem,
                                           item.Language,
                                           System.DateTime.Now);  // Create a publisher with the publishoptions
  Sitecore.Publishing.Publisher publisher = new Sitecore.Publishing.Publisher(publishOptions);
 
  // Choose where to publish from
  publisher.Options.RootItem = item;
 
  // Publish children as well?
  publisher.Options.Deep = true;
 
  // Do the publish!
  publisher.Publish();
}
 
Key Notes:
  • Droplink vs Droplist-> Droplink store GUID whereas Droplist stores just name
Sitecore 8.0 higher- Multiple version in web database
 
Content testing Enabled.
 
By default the publishVersion pipeline contains two processors in order:
  • Sitecore.ContentTesting.Pipelines.PublishVersion.PublishTestingVersions, Sitecore.ContentTesting
  • Sitecore.Publishing.Pipelines.PublishVersion.Processors.RemoveOtherVersions, Sitecore.Kernel
 
Reference:
http://www.sitecore.net/learn/blogs/technical-blogs/john-west-sitecore-blog/posts/2011/04/accessing-items-in-the-sitecore-aspnet-cms.aspx

No comments :