Context and Databases

Sitecore data is stored in multiple databases. From a web developer’s perspective, the two most often used ones are master, which contains the data being edited in the Content Manager, and web which is storing the data used to display the web site.

 

Databases can be accessed through the Database class. 

To obtain a reference to a database, use the Factory class, as in:  

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

 

The database names and implementation details are specified in the web.config below the <databases> section.

 

Whenever the user code is invoked by Sitecore, a so called context database is automatically assigned. You can access this database by using the Context class, as in:

 

Sitecore.Data.Database current = Sitecore.Context.Database;

 

When the code executes on the web site (that is in a layout or an xsl extension), the context database will be web. When code is executing within the Content Manager, the context database will be core. The core database contains data needed by the Content Manager.

 

To access the database being edited within the Content Manager, you can use

 

Database content = Sitecore.Context.ContentDatabase;

           

The ContentDatabase property will be empty when executing in the web site context. Only content editors (such as the Content Manager) will normally support this property.

 

The link between contexts and databases is specified in the web.config below the <sites> section. For instance, the web site context is defined as

 

      <site 
        name="website" 
        virtualFolder="/" 
        physicalFolder="/" 
        rootPath="/sitecore/content" 
        startItem="/home" 
        language="en" 
        database="web" 
        domain="extranet" 
        allowDebug="true" 
        cacheHtml="true" />

 

Note that the database is set to point to the database named web.

 

The site definition for the Content Manager looks like this

      <site 
        name="shell" 
        virtualFolder="/sitecore/shell" 
        physicalFolder="/sitecore/shell" 
        rootPath="/sitecore/content" 
        startItem="/home" 
        language="en" 
        database="core" 
        content="master" 
        domain="sitecore" 
        enableWorkflow="true" />

 

Note that the database is set to point to the database named core and that the content is taken from the database master.

Items

 

A Sitecore database contains data elements called items. Programmatically, the data represented by Items is accessed through the class Item.

 

To obtain an Item from the current context database, you can use

 

  string itemPath = "/sitecore/content/home"; 

  Sitecore.Data.Items.Item item = Sitecore.Context.Database.Items[itemPath];

 

The itemPath is the path of Item names leading to a specific Item.

 

Items can be retreived using paths or IDs. Languages and versions can also be specified

 


  Sitecore.Data.ID itemID = Sitecore.Data.ID.Parse( 

    "{110D559F-DEA5-42EA-9C1C-8A5DF7E70EF9}");  

  Sitecore.Globalization.Language language =  

    Sitecore.Globalization.Language.Predefined.Danish;

  Sitecore.Data.Version version = Sitecore.Data.Version.Parse(1);  

  Sitecore.Data.Items.Item homeitemlanguage =  

    Sitecore.Context.Database.Items[itemID, language, version];

 

Fields

 

The data within an Item is organized in named fields. For instance, an Item to be displayed on a web site may contain a title and some text. To access the values of these fields, you can use an indexer on an Item

 

Sitecore.Data.Items.Item homeitem =

Sitecore.Context.Database.Items["/sitecore/content/home"];

 

string title = item["title"];

string text = item["text"];

 

 

To update field data, put the Item in the update mode. The easiest way is to embed the Item in an EditContext, like this

 

 

try

  Sitecore.Data.Items.Item itemtoupdate = 
    Sitecore.Context.Database.Items["/sitecore/content/home"]; 
 
  using(new Sitecore.Data.Items.EditContext(item)) 
  {
    itemtoupdate["title"] = "My new title";
    itemtoupdate["text"] = "My <b>new</b> text"; 
  }
}
catch (Exception ex) 

  lblupdateitemresult.Text = ex.Message; 
}

 

When the using block exits, the modified field data will be written to the database containing the Item.

 

NOTE! You should never update Items directly to the web database as the Item may be overridden with the next publishing. Rather, select the correct content database; then update the Item and, finally, programmatically publish the Item.

1.  Full Source

using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Data.Items;

// To make this example work, reference the following:
// sitecore.kernel, System.Web, System
namespace Examples
{
    
using System;
    

  
/// <summary>
  
/// This sublayout (ascx) applies to the article Context and databases.
  
/// </summary>
    public class DatabasesAndContext : System.Web.UI.UserControl
    {
    
protected System.Web.UI.WebControls.Label lblCurrentDBName;
    
protected System.Web.UI.WebControls.Label lblHomeItem;
    
protected System.Web.UI.WebControls.Label lblHomeItemVersion;
    
protected System.Web.UI.WebControls.Label lblHomeItemTitle;
    
protected System.Web.UI.WebControls.Label lblHomeItemText;
    
protected System.Web.UI.WebControls.Label lblupdateitemresult;
    
protected System.Web.UI.WebControls.Label lblMasterDBName;

        
private void Page_Load(object sender, System.EventArgs e)
        {
      
// Selects a specific database
      Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master");
      lblMasterDBName.Text
= "masterdatabase name: " + master.Name;
            
      
// Select context database.
      Sitecore.Data.Database current = Sitecore.Context.Database;
      lblCurrentDBName.Text
= "current context database name: " + current.Name;

      
// Get latest version of an item in current language
      string itemPath = "/sitecore/content/home";
      Sitecore.Data.Items.Item item
= Sitecore.Context.Database.Items[itemPath];
      lblHomeItem.Text
= "name of the '" + itemPath + "' node: " + item.Name;

      
// Extract item with right item (by guid), language and version.
      Sitecore.Data.ID itemID = Sitecore.Data.ID.Parse("{110D559F-DEA5-42EA-9C1C-8A5DF7E70EF9}");
      Sitecore.Globalization.Language language
= Sitecore.Globalization.Language.Predefined.Danish;
      Sitecore.Data.Version version
= Sitecore.Data.Version.Parse(1);
      Sitecore.Data.Items.Item homeitemlanguage
= Sitecore.Context.Database.Items[itemID, language, version];
      lblHomeItemVersion.Text
= "Home item in version 1 (in English): " + homeitemlanguage.Name;

      
// Extract field values
      Sitecore.Data.Items.Item homeitem = Sitecore.Context.Database.Items["/sitecore/content/home"];
      lblHomeItemTitle.Text
= "Title:" + homeitem["title"];
      lblHomeItemText.Text
= "Text:" + homeitem["text"];


      
// Attempts to write to the web database from the current context. If you are
      
// on a web site, this will fail as user is on the extranet domain and
      
// anonymous!
      try
          {
        Sitecore.Data.Items.Item itemtoupdate
=
          Sitecore.Context.Database.Items[
"/sitecore/content/home"];
        
using(new Sitecore.Data.Items.EditContext(item))
        {
          itemtoupdate[
"title"] = "My new title";
          itemtoupdate[
"text"] = "My <b>new</b> text";
        }
      }
      
catch (Exception ex)
      {
        lblupdateitemresult.Text
= ex.Message;
      }


      
// Attempts to write to the master database from the current context. If you are
      
// on a web site, this will fail as user is on the "wrong domain" (extranet) and
      
// even is anonymous!
          try
          {
            Database masterdb
= Factory.GetDatabase("master");
            Item itemtoupdate2
=        
              masterdb.Items[
"/sitecore/content/home"];
            
using(new EditContext(item))
            {
              itemtoupdate2[
"title"] = "My new title";
              itemtoupdate2[
"text"] = "My <b>new</b> text";
            }
          }
          
catch (Exception ex)
          {
            lblupdateitemresult.Text
= ex.Message;
          }

        }

        
#region Web Form Designer generated code
        
override protected void OnInit(EventArgs e)
        {
            
//
            
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
            
//
            InitializeComponent();
            
base.OnInit(e);
        }
        
        
/// <summary>
        
///        Required method for Designer support - do not modify
        
///        the contents of this method with the code editor.
        
/// </summary>
        private void InitializeComponent()
        {
      
this.Load += new System.EventHandler(this.Page_Load);

    }
        
#endregion
    }
}

Source code for this article

Source code. To use it, complete the steps below:

  1. Create the "databasesandcontext" sub layout.
  2. Download source and unzip it into your layouts folder, overriding the 'databasesandcontext' file, which Sitecore created by default.
  3. Assign the sub layout to an Item or a template.
  4. Open visual studio and add the sub layout to your project.