Level: 200
 

Programmatically reading, altering and creating items - Part 2

c# code

You often end up in a situation where you want alter or create an item from C# through the Sitecore API. This articles walks through the different possibilities provided by the Sitecore API for viewing content, altering and creating items in C#.

 

This is the second part of two articles. You can read the first part here: Programatically reading, altering and creating items - part 1.

Written by: Jens Mikkelsen
Fri, Jun 26 2009

Altering items

When altering items through the API you need to consider, which database you want to alter the item in. If you change an item retrieved from the web database, it will write the changes to the web database as well.

This means the changes will be overwritten as soon as you publish. Therefore you should make your changes to items retrieved from the master database. If you need the changes to appear right away, you need to publish the item programmatically. As another publish may be in progress, it still might take some time for the item to appear.

 

When altering an item in Sitecore, you need to set the item in an editing state. This is done by calling the Item.Editing.BeginEdit() and EndEdit() methods. As you are operating with a state you should always end the editing state, even though an exception occurs. Unfortunally the Sitecore API doesn’t provide a roll back, but the state should be closed anyway.

 

One more thing you want to pay attention to is security. The end user is normally logged in as the Extranet/Anonymous user, which by default isn’t allowed to change items. You can either setup proper security and make the user login or use the Sitecore.SecurityModel.SecurityDisabler, which disables security in a certain code block.

 

So when you want to alter an item, you should do something like this:

 

public void AlterItem()

{

  //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";

    }

    finally

    {

      //Close the editing state

      item.Editing.EndEdit();

    }

  }

}

 

Now the item is altered in the master database. If you want to publish the item programmatically, you need to setup some publish options and run the publish pipeline, as it is specified in the web.config. This can be done like this:

 

//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);

 

Note that publishing automatically isn’t the best solution. For instance there may be some caching issues. Every time you publish the frontend cache is cleared, which in this case would mean, that the web cache can be cleared by an end user.

 

 

Creating items

Programmatically creating items in Sitecore is rather easy. You need to retrieve the root item, where the new item is to created under and then create the item with the Item.Add method, where it is also possible to specify either a template or a branch:

 

public void CreateItem()

{

  //Again we need to handle security

  //In this example we just disable it

  using (new SecurityDisabler())

  {

    //First get the parent item from the master database

    Database masterDb = Sitecore.Configuration.Factory.GetDatabase("master");

    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);

 

 

    //We can now manipulate the fields and publish as in the previous example

  }

}

 

The add method also allows you to specify a branch, should you need that.

 

You should now have a fundamental idea on how you use the basic Item API, allowing you to read, alter and create items in Sitecore. Congratulations!

 

Please rate this article


15 rates / 4,27 avg.

  • About the author:

    Jens Mikkelsen

    Jens Mikkelsen is a partner at Inmento Solutions a Sitecore consulting firm. He works as a Sitecore specialist and consulting helping clients architect and build quality Sitecore solutions using the newest modules and tools. 

    Further he has been deeply envolved in various complex solutions and has built up a strong knowledge of Sitecore architecture and best practices. He has especially focused on and is specialized in debugging and analyzing Sitecore solutions.

     

    Jens is very interested in the technical mechanisms in the new marketing products such as Sitecore DMS and Sitecore ECM.

    My Sitecore Freelance CV

12 responses to "Programmatically reading, altering and creating items - Part 2"

great article... just to get started. But i have a question: i have created new item and published. But new item is not shown instantly, but only when i rebuild projects. I have heard that is problem with cache clearing. I have added samo code but is not working. Can someone help me?
Posted: Thursday, July 09, 2009 12:35 PM
Hi Bostian

It sounds like your site is in development.

Are you publishing on the same machine, that you are using for developing your solution?

When you publish, the cache is cleared on the server you are publishing on. But if you are working on your localhost its cache is not cleared, you would need the staging module for this.

When you rebuild your project, the website gets a new process and thereby data is loaded again.

Posted: Thursday, July 09, 2009 2:05 PM
It is just test site... i am using sitecore express 6. So everything is on localhost... so where can i found out more about this staging module?

For further work, i would like to know if this code for cache clearing is ok:

cache = Cache.Manager.GetHtmlCache(Sitecore.Context.Site);
cache.Clear();
Posted: Thursday, July 09, 2009 2:13 PM
Hmmmm... That sounds odd. Have you copied the code excactly? It works in this end. It sounds like your html cache isn't cleared on publish, have you altered something in the site section of your web.config?
Posted: Thursday, July 09, 2009 9:53 PM
Hate to bring up this old article, but the programmatic publish is really throwing me off. I have set up an automatic publish in the end of my workflow that will update certain items. However, the cache isn't cleared, and therefore I have to run a Control Panel>Database>Clean up Database to clear it and get my new items. Is there a way to either force this cache? Which cache is the culprit here?

Thanks
Posted: Friday, November 06, 2009 3:35 AM
Hi,

And how should I add the sub item(non string filed for item) to it?

Regards,
Szymon
Posted: Tuesday, August 24, 2010 1:33 PM
If the item that is being added has a workflow attached, does this line trigger the workflow events?

item.Editing.EndEdit();
Posted: Tuesday, January 18, 2011 9:53 PM
hi David,
when I am tyring to create items programmatically that time i am gettign an error Could not read Sitecore configuration
on Database masterDb = Sitecore.Configuration.Factory.GetDatabase("master"); statement.
Could you tell me why I am getting this error?

Thanks ,
Neeta
Posted: Thursday, March 31, 2011 10:37 AM
when I am tyring to create items programmatically that time i am gettign an error Could not read Sitecore configuration
on Database masterDb = Sitecore.Configuration.Factory.GetDatabase("master"); statement.
Could you tell me why I am getting this error?
Posted: Monday, December 10, 2012 6:58 AM
Hi

Your website has great tutorials and it's good for beginners.

I have tried your sample code in the visual studio[Console application].I am getting the following error continuously.

"Could not read sitecore configuration".Please help me on it.Thanks
Posted: Friday, October 25, 2013 3:06 PM
I am getting an error "could not read Sitecore Configuration" when using Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master");

Why this error occurs and how to resolve it. Please help me on this.
Posted: Friday, February 21, 2014 10:01 AM
put dll into website bin folder.it will work
Posted: Friday, February 21, 2014 1:46 PM

Leave a reply


Notify me of follow-up comments via email.
 
 
#nbsp;