Go Back

Sitefinity API Tips & Tricks

These are the notes for the Sitefinity API Tips & Tricks Webinar.

Working with Sitefinity Pages Programmatically

Sitefinity - Working with Pages Programmatically

Sitefinity - Pages API Overview

Pages_API_Overview

Fetch All Pages

Sitefinity – Finding Pages

using System;
using System.Collections;
using Telerik.Cms;

public partial class test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        CmsManager manager = new CmsManager();
        IList pages = manager.GetPages();

        foreach (ICmsPage page in pages)
        {
            Response.Write(page.Title + "<br />");
        }

    }
}

Fetch some Pages

Sitefinity – Finding Pages

using System;
using System.Collections;
using Telerik.Cms;

public partial class test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        CmsManager manager = new CmsManager();
        int totalRows;
        IList pages = manager.GetPages(0, 5, "DateModified", System.ComponentModel.ListSortDirection.Ascending, out totalRows);

        Response.Write(totalRows + " pages found.<br /><br />");

        foreach (CmsPageInfo page in pages)
        {
            Response.Write(page.CmsPage.MenuName + "<br />");
        }
    }
}

Valid sort expressions for Pages:

  • Name
  • TemplateName
  • Modifier
  • DateModified
  • Status

Create a new Page

Sitefinity - Creating Pages

using System;
using Telerik.Cms;

public partial class test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        CmsManager manager = new CmsManager();
        ICmsPage page = manager.CreatePage("TestPage");
        manager.SavePage(page);
    }
}

Find a Page

Sitefinity – Finding Pages

using System;
using System.Collections;
using System.Web;
using Telerik.Cms;
using Telerik.Cms.Web;

public partial class test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        CmsManager manager = new CmsManager();
        IList pages = manager.GetPages();

        foreach (IPage page in pages)
        {
            if (page.Name == "TestPage")
            {
                Response.Write(page.ID + " " + page.Name + "<br />");
                break;
            }
        }
    }
}

Delete a Page

Sitefinity - Deleting Pages

using System;
using Telerik.Cms;

public partial class test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        CmsManager manager = new CmsManager();
        manager.DeletePage(new Guid("73a6f400-3340-4358-9104-09b615d7d8dc"));
    }
}

Create a Sitefinity Page with Content

Sitefinity - Creating Pages

using System;
using Telerik.Cms;
using Telerik.Cms.Engine.WebControls;

public partial class test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        CmsManager manager = new CmsManager();
        ICmsPage page = manager.CreatePage("TestPage");
        page.MenuName = "Test Page";
        page.Description = "This is my page description.";
        page.Navigable = true;
        page.Keywords = "Page,Keywords";
        page.DenyAnonymous = false;

        IStagedPage staged = page.Staged.CheckOut();
        IPageTemplate template = manager.GetTemplate("Inner");
        staged.SetTemplate(template.ID, "Emerald-Blue");

        GenericContent control1 = new GenericContent();
        control1.ID = "genericContent1";
        control1.Content = "<p>This is some content #1.</p>";

        GenericContent control2 = new GenericContent();
        control2.ID = "genericContent2";
        control2.Content = "<p>This is some content #2.</p>";

        // Get Page #1
        page = (ICmsPage)manager.GetPage(page.ID, true);
        page.Staged.AddControl("Content", control1);

        // Get Page #2
        page = (ICmsPage)manager.GetPage(page.ID, true);
        page.Staged.AddControl("Content", control2);

        // Get Page #3
        page = (ICmsPage)manager.GetPage(page.ID, true);
        page.Staged.CheckIn();
        page.Publish();
    }
}

Why are 3 GetPage calls required?

When you do an action with the persistent object (staged), like SetTemplate() or AddControl(), the transaction is committed and the object looses it.  Therefore, you have to get the object again. Actually, it is the same object from the Nolics cache, but joined to a new transaction.

Modify a Page

Sitefinity - Modifying Pages

using System;
using System.Collections;
using System.Collections.Generic;
using Telerik.Cms;
using Telerik.Cms.Engine.WebControls;

public partial class test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        CmsManager manager = new CmsManager();
        IList pages = manager.GetPages();

        foreach (IPage page in pages)
        {
            if (page.Name == "TestPage")
            {
                Response.Write("Updating page.<br />");

                ICmsPage editPage = (ICmsPage)manager.GetPage(page.ID, true);
                IStagedPage staged = editPage.Staged.CheckOut();
                IList<ICmsWebControl> pageControls = editPage.Staged.Controls;

                // Modify an existing control
                foreach (ICmsWebControl control in pageControls)
                {
                    if (control.ControlType == typeof(GenericContent))
                    {
                        GenericContent gc = (GenericContent)control.LoadControl();
                        if (gc.ID == "genericContent1")
                        {
                            gc.Content = "<p>Altered text.</p>";
                            manager.SaveControl(control);
                        }
                    }
                }

                // Add a new control
                GenericContent control3 = new GenericContent();
                control3.ID = "genericContent3";
                control3.Content = "<p>This is some content #3.</p>";
                editPage = (ICmsPage)manager.GetPage(page.ID, true);
                editPage.Staged.AddControl("Content", control3);

                editPage = (ICmsPage)manager.GetPage(page.ID, true);
                editPage.Staged.CheckIn();
                editPage.Publish();

                break;
            }
        }
    }
}

Rollback the Version of a Page

using System;
using System.Collections;
using Telerik.Cms;

public partial class test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        CmsManager manager = new CmsManager();
        IList pages = manager.GetPages();

        foreach (IPage page in pages)
        {
            if (page.Name == "TestPage")
            {
                IPage editPage = manager.GetPage(page.ID, true);
                IStagedPage staged = editPage.GetVersion(editPage.Version - 1);
                staged.Rollback();
                break;
            }
        }
    }
}

Generic Content Based Modules

Sitefinity – Overview of Generic Content API

  • Generic Content
  • News
  • Blogs
  • Images & Documents
  • Events
  • Wiki

Get Content (Generic Content)

using System;
using System.Collections;
using Telerik.Cms.Engine;

public partial class test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ContentManager manager = new ContentManager();

        IList items = manager.GetContent();
        foreach (IContent contentItem in items)
        {
            Response.Write(contentItem.Content + "<br />");
        }
    }
}

Provider Names Defined

Generic Content provider names are defined in the web.config:

<cmsEngine defaultProvider="Generic_Content">
  <providers>
    <clear />
    <add name="Generic_Content" urlRewriteFormat="[Publication_Date]/[Name].aspx" urlDateTimeFormat="yy-MM-dd" urlWhitespaceChar="_" visible="True" defaultMetaField="Name" securityProviderName="" allowLocalization="False" allowVersioning="True" allowWorkflow="False" allowComments="false" commentsModeration="true" versioningProviderName="" connectionStringName="GenericContentConnection" type="Telerik.Cms.Engine.Data.Providers.DefaultProvider, Telerik.Cms.Engine.Data" />
    <add name="News" urlRewriteFormat="[Publication_Date]/[Title].aspx" urlDateTimeFormat="yy-MM-dd" urlWhitespaceChar="_" visible="False" defaultMetaField="Title" securityProviderName="" allowVersioning="True" applicationName="/News" versioningProviderName="" commentsModeration="true" connectionStringName="GenericContentConnection" type="Telerik.News.Data.DefaultNewsProvider, Telerik.News.Data" />
    <add name="Blogs" urlRewriteFormat="[Publication_Date]/[Title].aspx" urlDateTimeFormat="yy-MM-dd" urlWhitespaceChar="_" visible="False" defaultMetaField="Title" applicationName="/Blogs" allowVersioning="True" allowComments="true" commentsModeration="false" allowLocalization="False" localizationProviderName="" allowWorkflow="False" securityProviderName="" versioningProviderName="" connectionStringName="GenericContentConnection" type="Telerik.Blogs.Data.DefaultBlogProvider, Telerik.Blogs.Data" />
    <add name="Libraries" urlRewriteFormat="~/{Provider}/{LibraryName}/[Name].sflb.ashx" urlDateTimeFormat="yy-MM-dd" urlWhitespaceChar="_" visible="False" defaultMetaField="Name" applicationName="/Libraries" allowVersioning="False" allowLocalization="False" localizationProviderName="" allowWorkflow="False" securityProviderName="" versioningProviderName="" connectionStringName="GenericContentConnection" type="Telerik.Libraries.Data.DefaultProvider, Telerik.Libraries.Data" tagEditorTemplate="~/Sitefinity/Admin/ControlTemplates/Libraries/BatchTagsEditor.ascx" />
    <!--Amazon Data Provider [First turn off the default one] url format can be urlRewriteFormat="~/{Provider}/{LibraryName}/[Name].s3lb" as well in that cae there will extra libraries in the url-->
    <!--<add name="Libraries" urlRewriteFormat="~/{LibraryName}/[Name].s3lb"  thumbnailExtension=".tmb" urlDateTimeFormat="yy-MM-dd" urlWhitespaceChar="_" visible="False" defaultMetaField="Name" applicationName="/Libraries" allowVersioning="True" allowLocalization="False" localizationProviderName="" allowWorkflow="False" securityProviderName="" versioningProviderName="" connectionStringName="GenericContentConnection" type="Telerik.Libraries.Data.AmazonProvider, Telerik.Libraries.Data" tagEditorTemplate="~/Sitefinity/Admin/ControlTemplates/Libraries/BatchTagsEditor.ascx" />-->
    <!--Viddler Data Provider Compatible with other libraries, must add a libraryInfo with type = "Viddler"-->
    <!--<add name="Libraries" urlRewriteFormat="~/{LibraryName}/[Name].sflb.ashx" thumbnailExtension=".tmb.ashx" urlDateTimeFormat="yy-MM-dd" urlWhitespaceChar="_" visible="False" defaultMetaField="Name" applicationName="/Libraries" allowVersioning="True" allowLocalization="False" localizationProviderName="" allowWorkflow="False" securityProviderName="" versioningProviderName="" connectionStringName="GenericContentConnection" type="Telerik.Libraries.Data.ViddlerProvider, Telerik.Libraries.Data" tagEditorTemplate="~/Sitefinity/Admin/ControlTemplates/Libraries/BatchTagsEditor.ascx"/>-->
    <add name="Events" urlRewriteFormat="[Publication_Date]/[Title].aspx" urlDateTimeFormat="yy-MM-dd" urlWhitespaceChar="_" visible="False" defaultMetaField="Title" securityProviderName="" allowVersioning="True" applicationName="/Events" versioningProviderName="" commentsModeration="true" connectionStringName="GenericContentConnection" type="Telerik.Events.Data.DefaultEventsProvider, Telerik.Events.Data" />
    <add name="Wiki" urlRewriteFormat="[Wiki]/[Name].aspx" urlWhitespaceChar="_" visible="False" defaultMetaField="Name" securityProviderName="" allowVersioning="True" applicationName="/Wiki" versioningProviderName="" allowComments="true" commentsModeration="true" connectionStringName="GenericContentConnection" type="Telerik.Cms.Engine.Data.Providers.DefaultProvider, Telerik.Cms.Engine.Data" />
  </providers>
</cmsEngine>

Get News using ContentManager

using System;
using System.Collections;
using Telerik.Cms.Engine;

public partial class test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ContentManager manager = new ContentManager("News");

        IList items = manager.GetContent();
        foreach (IContent contentItem in items)
        {
            Response.Write(contentItem.Content + "<br />");
        }
    }
}

Get News using NewsManager

using System;
using System.Collections;
using Telerik.Cms.Engine;
using Telerik.News;

public partial class test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        NewsManager manager = new NewsManager("News");

        IList items = manager.Content.GetContent();
        foreach (IContent contentItem in items)
        {
            Response.Write(contentItem.Content + "<br />");
        }
    }
}

Add Event with Category and Tags (ContentManager)

using System;
using System.Collections.Generic;
using Telerik.Cms.Engine;

public partial class test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ContentManager contentManager = new Telerik.Cms.Engine.ContentManager("Events");

        if (contentManager.GetCategory("Category1") == null)
        {
            ICategory category = contentManager.CreateCategory("Category1");
            contentManager.SaveCategory(category);
        }

        IContent content = contentManager.CreateContent("text/html");
        content.SetMetaData("Title", "Event Title");
        content.SetMetaData("Street", "1234 Test Street");
        content.SetMetaData("City", "Phoenix");
        content.SetMetaData("State", "AZ");
        content.SetMetaData("Country", "USA");
        content.SetMetaData("Publication_Date", DateTime.Now);
        content.SetMetaData("Expiration_Date", DateTime.Now.AddDays(10));
        content.SetMetaData("Contact_Name", "John Doe");
        content.SetMetaData("Contact_Email", "john@test.com");
        content.SetMetaData("Contact_Phone", "555-1234");
        content.SetMetaData("Contact_Cell", "555-4321");
        content.SetMetaData("Contact_Web", "http://www.sitefinity.com/");
        content.SetMetaData("Category", "Category1");
        content.SetMetaData("Event_Start", DateTime.Parse("2009/09/01 3:00PM"));
        content.SetMetaData("Event_End", DateTime.Parse("2009/09/01 5:00PM"));
        content.Content = "Event content";
        contentManager.SaveContent(content);

        List<string> listOfStringNames = new List<string>();
        listOfStringNames.Add("Tag1");
        listOfStringNames.Add("Tag2");
        contentManager.SaveTags(content.ID, listOfStringNames);
    }
}

Add Event with Category & Tags (EventsManager)

using System;
using System.Collections.Generic;
using Telerik.Cms.Engine;
using Telerik.Events;

public partial class test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        EventsManager manager = new EventsManager("Events");

        if (manager.Content.GetCategory("Category1") == null)
        {
            ICategory category = manager.Content.CreateCategory("Category1");
            manager.Content.SaveCategory(category);
        }

        IContent content = manager.Content.CreateContent("text/html");
        content.SetMetaData("Title", "Event Title 2");
        content.SetMetaData(manager.StreetField, "1234 Test Street");
        content.SetMetaData(manager.CityField, "Phoenix");
        content.SetMetaData(manager.StateField, "AZ");
        content.SetMetaData(manager.CountryField, "USA");
        content.SetMetaData(manager.PublicationDateField, DateTime.Now);
        content.SetMetaData(manager.ExpirationDateField, DateTime.Now.AddDays(10));
        content.SetMetaData("Contact_Name", "John Doe");
        content.SetMetaData("Contact_Email", "john@test.com");
        content.SetMetaData("Contact_Phone", "555-1234");
        content.SetMetaData("Contact_Cell", "555-4321");
        content.SetMetaData("Contact_Web", "http://www.sitefinity.com/");
        content.SetMetaData("Category", "Category1");
        content.SetMetaData(manager.EventStartField, DateTime.Parse("2009/09/01 3:00PM"));
        content.SetMetaData(manager.EventEndField, DateTime.Parse("2009/09/01 5:00PM"));
        content.Content = "Event content";
        manager.Content.SaveContent(content, ContentStatus.Published);

        List<string> listOfStringNames = new List<string>();
        listOfStringNames.Add("Tag1");
        listOfStringNames.Add("Tag2");
        manager.Content.SaveTags(content.ID, listOfStringNames);
    }
}

Finding Events by Title

Finding Generic Content items

using System;
using System.Collections;
using System.Collections.Generic;
using Telerik.Cms.Engine;
using Telerik.Events;

public partial class test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        EventsManager manager = new EventsManager("Events");

        List<IMetaSearchInfo> filter = new List<IMetaSearchInfo>();
        filter.Add(new MetaSearchInfo(MetaValueTypes.ShortText, "Title", "Event Title"));
        IList items = manager.Content.GetContent(filter.ToArray());

        Response.Write("Matches Found: " + items.Count + "<br />");

        foreach (IContent contentItem in items) 
        {
            Response.Write(contentItem.GetMetaData("Title") + "<br />");
        }
    }
}

Finding Events by Date

using System;
using System.Collections;
using System.Collections.Generic;
using Telerik.Cms.Engine;
using Telerik.Events;

public partial class test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        EventsManager manager = new EventsManager("Events");

        List<IMetaSearchInfo> filter = new List<IMetaSearchInfo>();
        filter.Add(new MetaSearchInfo(MetaValueTypes.DateTime, "Event_Start", DateTime.Now, SearchCondition.GreaterOrEqual));
        IList items = manager.Content.GetContent(filter.ToArray());

        Response.Write("Matches Found: " + items.Count + "<br />");

        foreach (IContent contentItem in items) 
        {
            Response.Write(contentItem.GetMetaData("Title") + "<br />");
        }
    }
}

Finding Events by Tag (GetContent)

using System;
using System.Collections;
using Telerik.Cms.Engine;
using Telerik.Events;

public partial class test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        EventsManager manager = new EventsManager("Events");
        IList items = manager.Content.GetContent(0, 0, "Title ASC", "Tag1");
        foreach (IContent contentItem in items) 
        {
            Response.Write(contentItem.GetMetaData("Title") + "<br />");
        }
    }
}

Finding Events by Tag (GetEvents)

using System;
using System.Collections;
using Telerik.Events;

public partial class test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        EventsManager manager = new EventsManager("Events");
        IList eventsList = manager.GetEvents(DateTime.Now, DateTime.Now.AddYears(1), "[Start] ASC", "Tag1");
        if (eventsList.Count > 0)
        {
            foreach (IEvent eventItem in eventsList)
            {
                Response.Write(eventItem.ContentItem.GetMetaData("Title") + "<br />");
                Response.Write(eventItem.Start.ToString() + "<br />");
                Response.Write(eventItem.End.ToString() + "<br />");
                Response.Write("<br />");
            }
        }
    }
}

Modifying an Event

using System;
using System.Collections;
using Telerik.Events;

public partial class test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        EventsManager manager = new EventsManager("Events");

        IList eventsList = manager.GetEvents(DateTime.Now, DateTime.Now.AddYears(1), "[Start] ASC");

        foreach (IEvent eventItem in eventsList)
        {
            if (eventItem.ContentItem.GetMetaData("Title").ToString() == "Event Title")
            {
                eventItem.ContentItem.SetMetaData("Title", "New Title");
                manager.Content.SaveContent(eventItem.ContentItem);
                break;
            }
        }
    }
}

--

Rollback to a Previous Version of an Event

using System;
using System.Collections;
using Telerik.Events;
using Telerik.Cms.Engine;
using Telerik.Versioning;

public partial class test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        EventsManager manager = new EventsManager("Events");
        IList eventsList = manager.GetEvents(DateTime.Now, DateTime.Now.AddYears(1), "[Start] ASC");

        foreach (IEvent eventItem in eventsList)
        {
            if (eventItem.ContentItem.GetMetaData("Title").ToString() == "New Title")
            {
                VersionManager versionManager = new VersionManager();
                int version = versionManager.GetVersion(eventItem.ContentID, null);
                versionManager.RollbackItem(eventItem.ContentID, null, version - 1);
                manager.Content.PublishContent(eventItem.ContentID);
                break;
            }
        }
    }
}

Non-Generic Content Based Modules

Sitefinity – Modules API Overview

  • Lists
  • Polls
  • Forums
  • Newsletters

Add a new List Item

Sitefinity - Lists API Overview

using System;
using Telerik.Lists;

public partial class test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ListManager listManager = new ListManager();
        INamedList newList = listManager.CreateList("New list");
        listManager.SaveList(newList);

        IListItem listItem1 = listManager.CreateListItem();
        listItem1.Headline = "List item 1 - headline";
        listItem1.Content = "List item 1 - full content";
        listItem1.Ordinal = 0;
        listItem1.Parent = newList;
        listManager.SaveListItem(listItem1);

        IListItem listItem2 = listManager.CreateListItem();
        listItem2.Headline = "List item 1 - headline";
        listItem2.Content = "List item 1 - full content";
        listItem2.Ordinal = 0;
        listItem2.Parent = newList;
        listManager.SaveListItem(listItem2);
    }
}

Comments  7

  • Peter 31 Aug

    I have used this excellent webinar as inspiration to build a conversion program. I can now import from our old CMS system and it saves me much time. The only thing I could not find is how to save a page directly into a folder such as "About Us". Can anyone help?
  • Peter 31 Aug

    Hi Gabe

    You has a section ("Create a Sitefinity Page with Content") where you shows how to save a new page in the root.

    When I import from another CMS-system with MS SQL DB to Sitefinity I want not only to import to root dir.

    I must import hundreds of pages and it would obviously be helpful if the pages could be imported into their virtual folders, as for example "About us".

    I would think that this line is the area of code that contains the solution:
    "ICmsPage page = manager.CreatePage("TestPage");"
    I've tried various combinations such as this line: "ICmsPage page = manager.CreatePage("About-us/TestPage");" without any luck.

    Can you help me with this?

    Best regards

    Peter
  • Gabe Sumner 31 Aug

    Hi Peter,

    If this page is a child of another page then you can specify the parent page by passing the parent's GUID:

    CmsManager manager = new CmsManager(); 
    ICmsPage page = manager.CreatePage("ChildPage", parentPage.ID); 

    Alternately you can specifiy additional URLs to apply to a page by using the AddUrl method:

    CmsManager manager = new CmsManager(); 
    ICmsPage page = manager.CreatePage("NewPage"); 
    page.AddUrl("~/AboutUs/MyNewUrl.aspx"); 

    Hopefully this helps.
  • Peter 31 Aug

    Hi Gabe
    Many thanks for your help. It will save me much time!
    I could not get "page.AddUrl ("~ /AboutUs/MyNewUrl.aspx ");" to work, but "ICmsPage page = manager.CreatePage (" Child Page ", parentPage.ID);" works fine for me.

    Best regards
    Peter
  • James Hearn 30 Nov

    Thanks for taking the time to write this, I refer to it again and again. Much appreciated.
  • Alain 04 Mar

    Dear,

    Is there any way to find list items (same as you did with Finding Events by Title)? 
    since it is a bad practice to loop on all the items in the list? 
    Please advise.

    Thank you,

  • Jerami Tainter 07 Apr

    Im doing an import of content and am creating multiple pages and adding a custom control through code behind following your tutorial here.

    This control basically sets a title and the content. Im using a Custom Control designer as well. Nothing complicated...dragging and dropping the control works fine...can add the Title and Content no problem without errors.

    When I run my script to do this through the code behind everything works fine...except when I go to the Edit View of the page. The control has an error "Index was outside the bounds of the Array". I can edit the control and it has the right data...i can view the page just fine as well...just in Edit Mode it has that error and will not display the control properly. Any ideas?
Post a comment!
  1. Formatting options
       
     
     
     
     
       
  2. I'm sorry for the CAPTCHA. You have spammers to thank for this: