Create and publish items in Sitecore

Sometimes Sitecore blogs tend to forget to describe the (for the experienced user) trivial tasks and jump right into the advanced (and fun) stuff. Today I got this (trivial?) question: How do you insert an item into Sitecore? Well that’s easy – if you know how to do it.

Let me start by describing when you should add items to the Sitecore database directly.

  • You should always write to the master database. Never write to the web database, as it will get overridden when publishing.
  • When developing Shell extensions you can access the Sitecore master database directly.
  • You should never access the master database from your web frontend. It might work for now, but if your website is moved into a staged environment you will not have access to the master database from your frontend anymore. Instead you should make a webservice that allows the front end server to write to the back end server.

OK, here is an example on how to create a new item:

// The SecurityDisabler overrides the current security model, allowing you
// to access the item without any security. It's like the user being an administrator
using (new Sitecore.SecurityModel.SecurityDisabler())
  // Get the master database
  Sitecore.Data.Database master = Sitecore.Data.Database.GetDatabase("master");
  // Get the template to base the new item on
  Items.TemplateItem template = master.GetItem("/sitecore/templates/Sample/Sample Item");

  // Get the place in the site tree where the new item must be inserted
  Item parentItem = master.GetItem("/sitecore/content/home");

  // Add the item to the site tree
  Item newItem = parentItem.Add("NameOfNewItem", template);

  // 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)
    // Assign values to the fields of the new item
    newItem.Fields["Title"].Value = "Value1";
    newItem.Fields["Text"].Value = "Value2";

    // End editing will write the new values back to the Sitecore
    // database (It's like commit transaction of a database)
  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)

A quick follow-through reveals the following steps:

  • Using the SecurityDisabler allows you to access the item as there were no security model. It is not required to disable security when updating items, and in some situations you would definitely not disable the security. I use the SecurityDisabler here to show how you can use it.
  • Adding items to the database requires a parent item. When adding an item, the new item is added to the database of the parent item. Make sure you have retrieved the parent item from the corrent database (the master database).
  • The new item can be based on a template or a branch. In this example I add a new item based on a templatem. Read about how to create items based on branches here.
  • In order to edit contents of an item you need to use the Editing.BeginEdit(), Editing.EndEdit() and Editing.CancelEdit(). These functions are similar to a SQL database begin/commit/abort transations. Nothing is written to the database before you call the Editing.EndEdit().
  • Different fields have different data types. The Value attribute of a field accesses the string representation of a field. If you shoud write to a lookup field or an image field, the text representation would look differently (the lookup field is a pipe-seperated list of GUIDs, and the image field is an XML document.

Now the item is created in the master database. Let’s publish it:

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,
                                           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!
  • The PublishOptions determines what and where to publish.
  • The RootItem determines from where you should publish. In this example I publish a single item. I could also have chosen incremental or smart publishing. If you choose Incremental you cannot set a root item as all items in the publish queue is published.

That’s it. You can read more about creating, reading and altering items on Learn Sitecore.

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in c#, General .NET, Sitecore 6 and tagged , , , , , . Bookmark the permalink.

25 Responses to Create and publish items in Sitecore

  1. David says:

    Rather than publishing the item in code-behind, what if you wanted a workflow to take over? Does the Editing.EndEdit() function automatically invoke workflow or is there other code needed?

    For example, I want to accept comments via an online form but provide moderation prior to publishing.

  2. briancaos says:

    The EndEdit() does not trigger the Workflow. The workflow is more of a user oriented shell-thing rather than a code-behind thing. If you look at the saveUI pipeline (the pipeline that is executed when you press [save] in the Sitecore Shell) you can see that it executes the Workflow (Sitecore.Pipelines.Save.WorkflowSaveCommand) after the contents has been saved (Sitecore.Pipelines.Save.Save).

    If you wish to start a workflow after you programatically has saved an item, you can do so simply by setting the values of the workflow fields to the workflow and workflow step of your choice, and then save the item.

  3. David says:

    Brian thanks for your reply. I understand how the workflow is set up in the shell – my question really is if an item is created and saved in code ending with Edit.EndEdit(), does Sitecore trigger the same events just as if the user pressed the [save] button in the shell?

  4. briancaos says:

    No, the EndEdit() does not trigger the workflow. You need to execute the saveUI pipeline in order to mimmick the save button.

  5. David says:

    Not to take advantage of your generosity, but how does one invoke the saveUI pipline from C# code?

  6. David says:

    Given your example above might it be:

    SaveArgs args = new Sitecore.Pipelines.Save.SaveArgs(newItem.GetOuterXml);
  7. briancaos says:

    This is the easiest way of starting a pipeline:

    SaveArgs args = new SaveArgs( someXmlData );
    Sitecore.Pipelines.CorePipeline.Run(“saveUI”, args);

    The saveUI pipeline uses a SaveArgs as parameter, which is constructed based on an XML format that is not the same as the serialized version of an item.
    It’s a little tricky to create. The easiest way of identifying the format is to use the Reflector and see how f.ex. Sitecore.Shell.Applications.WebEdit.Commands.Save does it.

    Please also note that the saveUI pipeline communicates with the SheerUI (the shell), so you might end up with some null references if calling it from codebehind.

  8. niels says:

    Your solution works fine – almost.
    I have a staged enviroment and have created a webservice.
    My problem is that I have to restart IIS before the created item is visible in sitecore content editor or posible to show in another webpage.

  9. briancaos says:

    Yes, that’s because Sitecore caches any item before rendering it. It’s way too slow to read items from the database every time you need it.
    When publishing the cache is cleared, but only on the server where you did the publish. Unless you use the staging module.
    Basically, the staging module consist of a web service on each of your front end web servers, and a publish:end event handler that calls the front end server’s webservice, thus clearing the cache.
    Make sure that your solution has the staging module installed and it’s configured correctly.

    Read more about the staging module here:

  10. Pingback: Interesting WCM Blog Posts from around the Web-Jan 20th « Blog posts from Oshyn, Inc

  11. bap says:

    great post!! i had a look at the webedit save command.

    @niels: did you use the source code ( Sitecore.Shell.Applications.WebEdit.Commands.Save.ProcessForm, Sitecore.Shell.Applications.WebEdit.Commands.Save.AddLayoutField) and refactered the web.Ui.Page to a sitecore.item? or how did you generate the packet?

    in case you can share you code i would be happy to have a look at it :)


  12. Michael Skov Jensen says:

    Can anyone tell me, how to schedule a publication for a certain time in Sitecore?

  13. briancaos says:

    I have provided an article on how to run a scheduled task at the same time every day:
    You should either create your own publish task and use the framework as described above, or contact Pentia and purchase the Sitecore Editors Tools ( which contains a “Monitor Next Pubiish”, a component that allows you to watch incremental publishings, and do a publish at a certain time each day.

  14. Pingback: Publish Items With the Sitecore Item Web API Using a Custom ResolveAction itemWebApiRequest Pipeline Processor «

  15. Hi Brian,

    When we publish items from code behind, in which mode it get published ? I mean Smart or Republish ? Can we decide this from Code behind.

    Thanks in advance.
    Vaibhao C

  16. briancaos says:

    You use the Sitecore.Publishing.PublishMode in the PublishOptions to determine the publish type.

  17. Bin Sun says:

    Hi Brian,
    I have a class implemented Sitecore.Form.Submit.ISaveAction and used Database.CreateItemPath(string path, TemplateItem template,) method to create item.
    And it recently only works on my CM instance an get request timeout on CD instance. Is it the right method to create an item or I have to add new item to its parent?


  18. briancaos says:

    The issue is probably that the form is running on the CD server in the WEB context, and you probably have no write access (or access at all) to the MASTER database from the CD server.
    In the case of staged environments, the best way to create items is to have a secure web service on the CM server that can only be access by the CD server(s) and call this service instead of creating the items directly from the CD server.

  19. bllue78 says:

    Thanks for your quick response. Actually I have CM and CD instance at same server and the login used to connect master/web database are same.
    After I put some tracking logs it turns to the Database.CreateItemPath(string path, TemplateItem template) method gives me the problem when execute it from CD instance it just hang there till requrest timeout. But very werid thing is CM instance execute it successfully and quickly.

    Items creating from CD instance ARE CREATED in content editor but they are all incomplete and only have basic information and lose all fields specified in template. In master database I can find the item but it doesn’t have any fileds related to it.

    I tried to compare config file and swapping CD and CM instance but it just not work on CD instance which drive me nuts.

  20. suraj says:

    How can i get publish date of an item in sitecore.

  21. Pingback: Sitecore Transfer items from one database to another | Brian Pedersen's Sitecore and .NET Blog

  22. gnicoll says:

    Thanks heaps for this post! I was able to use your PublishItem() function, it was exactly what I was looking for.

  23. Clem says:

    No using statements provided. What libraries are required?

  24. briancaos says:

    using Sitecore;
    using Sitecore.Data;
    using Sitecore.Data.Items;
    using Sitecore.Publishing;

  25. Pingback: Sitecore Publishing – Programmatically determine if item should be published | Brian Pedersen's Sitecore and .NET Blog

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s