EPiWiki.se  - EPiServer notes shared with others
 

Using EPiServer ObjectStore

[Edit]
Easy samples how to use EPiServer CMS ObjectStore functionality.

***This functionality is not documented and probably not supported by EPiServer***


The easiest way to investigate how to use the EPiServer CMS ObjectStore functionality is to lock at the analyzer TimeSpanAnalyzer in the LogService implementation(you can get the source code from EPiServer support).

Create a class


The class has to be serializable and implement the interface IItem

using System;
using EPiServer.BaseLibrary;

[Serializable]
public class MyItem : IItem
{
    public string Title { get; set; }

    #region IItem Members
    private Guid _id;
    public object Id
    {
        get
        {
            if (_id == Guid.Empty)
            {
                _id = Guid.NewGuid();
            }

            return _id;
        }
    }

    public string Name
    {
        get { return String.Format("MyItem_{0}", Id); }
    }

    #endregion
}


Register a schema for the class


The register schema needs a reference to the EPiserver.Implementation assembly, so add it to your project.

public partial class TestPage : TemplatePage
{
    static TestPage()
    {
        if (EPiServer.BaseLibrary.Context.Repository.SchemaForType(
               typeof(MyItem)) == null)
        {
            TypeSchemaBuilder.RegisterSchemaAndType(
               "EPiServer.Templates.MyItem",
               typeof(MyItem));
        }
    }


Working with the ObjectStore functionality



protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        DataBind();
    }


    ISession session = null;
    try
    {
        session = EPiServer.BaseLibrary.Context.Repository.CreateSession();

        //Create/load a root item
        IItem rootItem = session.LoadPath("/MyItems");
        if (rootItem == null)
        {
            rootItem = session.CreatePath("/MyItems");
        }

        MyItem newItem = new MyItem();
        newItem.Title = String.Format("Created: {0}", DateTime.Now);
        //Save a new Item
        session.Save(newItem);
        //Connect it to the root path
        session.AddRelation(rootItem.Id, newItem.Id);

        //List saved items
        foreach (MyItem item in session.RelatedItemsFrom<MyItem>(rootItem.Id))
        {
            Response.Write(item.Title);
            Response.Write("<br/>");
        }
    }
    finally
    {
        if (session != null)
        {
            session.Close();
        }
    }
}

Result


This code is going to produce the following structure in Object store
/MyItems
   MyItem_038c61f7-447a-44aa-932a-6006498bad9b

Version author:
Mattias Lövström

EPiServer version

All