Kentico CMS 7.0 Developer's Guide

Using API and CMS Controls outside the CMS project

Using API and CMS Controls outside the CMS project

Previous topic Next topic Mail us feedback on this topic!  

Using API and CMS Controls outside the CMS project

Previous topic Next topic JavaScript is required for the print function Mail us feedback on this topic!  

This topic describes how to configure external ASP.NET applications so that they support the Kentico CMS API and Controls. Using Kentico CMS functionality outside of the CMS web project allows you to create scenarios such as:


Separate applications integrated with your main Kentico CMS website

Custom websites or applications that use Kentico CMS as a content repository


Start Visual Studio and open your external application's project.


Connecting to the Kentico CMS database


To be able to access the Kentico CMS database, you need to specify the appropriate connection string in your application's web config file.


Add the connection string into the configuration/connectionStrings section using an <add> element named CMSConnectionString.


   <add name="CMSConnectionString" connectionString="Persist Security Info=False;database=KenticoCMS;server=myserver;user id=username;password=mypassword;Current Language=English;Connection Timeout=120;" />


Note: It is recommended to copy the exact connection string from the web.config file of the Kentico CMS web project.


Adding references to Kentico CMS API libraries


Before you can use Kentico CMS functionality in your application, you need to add references to the libraries containing the required code:


1. Right-click your application's web project root in the Solution Explorer and select Add Reference.


2. Open the Browse tab and navigate to the bin folder of the Kentico CMS web project.


3. Select all dll files in the folder and click OK.




Initializing Kentico CMS


You need to initialize Kentico CMS before making calls to its API from an external project.


Execute the CMSContext.Init method in the code of your application:






You can call this method at any point in your application's life cycle, but it must occur before you use any other Kentico CMS API.


Enabling ASCX transformations in external applications


Registering the Virtual path provider:


Kentico CMS uses a virtual path provider to retrieve the code of ASCX transformations. If you wish to use ASCX transformations in your external project, you need to register the virtual path provider when the application starts.


1. If necessary, create the Global.asax file for your application.


2. Execute the following line from the Application_Start method in the Global.asax file.




void Application_Start(object sender, EventArgs e)





Running without the virtual path provider


If you cannot use the virtual path provider in your environment (e.g. when using medium trust and .NET 3.5), you need to:


1.Save your virtual objects to the local disk using the Site Manager -> Administration -> System -> Virtual objects interface.


2.Copy the ~/CMSVirtualFiles folder from the Kentico CMS project the to the root of your own project.


See also: Deployment and source control


Adding the CMSTransformation class:


The CMSTransformation partial class allows you to write your own methods for use in ASCX transformations. The system checks the CMSTransformation class for method definitions whenever listing controls load transformations and an error occurs if the class is not present in the given project.


If you plan to use ASCX transformations, you must add the class to your project:


1. Create a new class file in your project named CMSTransformation.cs.

oIn web site projects, you need to add the file into the App_Code folder.

oIn web application projects, you can create the class in any location.


2. Add the following code into the class:




namespace CMS.Controls
    /// <summary>
    /// Base class for transformation methods
    /// </summary>
    public partial class CMSTransformation : CMSAbstractTransformation


You can leave the class empty if you do not need to register any custom methods.


Example: Displaying content from the Kentico CMS database


Once you have completed the configuration described in the sections above, you can use the Kentico CMS API and Controls in your application. A typical example is loading and displaying data from Kentico CMS.


Using the Kentico CMS API


The Kentico CMS API allows you to perform any action available in the standard administration interface. You can also use the API to load or modify records in the database.


The following example shows how to retrieve document content from the Kentico CMS database and display it using a standard ASP.NET Repeater control.


1. Create a new page (web form) in your external web project using Visual Studio.


2. Add the standard ASP.NET Repeater control onto the page.


3. Insert the following item template markup into the <asp:Repeater> control element:


<asp:Repeater ID="Repeater1" runat="server">
      <%# Eval("NewsTitle") %>
       (<%# ((DateTime) Eval("NewsReleaseDate")).ToString("d") %>)
      <br />
      <i><%# Eval("NewsSummary") %></i>
      <br />


4. Switch to the page's code behind and add the following references to the beginning of the code:




using CMS.DocumentEngine;

using System.Data;


5. Add the following code into the page's Page_Load method:




protected void Page_Load(object sender, EventArgs e)
  // Creates a data set containing all released news documents from the Corporate Site
  TreeProvider tp = new TreeProvider();
  DataSet ds = tp.SelectNodes("CorporateSite", "/news/%", "en-us", true, "", " NewsReleaseDate <= GetDate() ", " NewsReleaseDate DESC ", -1, true);
  // Binds the news data to the Repeater control
   Repeater1.DataSource = ds;







When performing other types of document operations (editing, deleting etc.), you need to initialize the tree provider within the context of a specific user:




using CMS.SiteProvider;
// Gets an Info object representing the administrator user
UserInfo user = UserInfoProvider.GetUserInfo("administrator");

// Creates a tree provider instance using administrator context
TreeProvider tp = new TreeProvider(user);



If you run the website and open the new page, the Repeater control displays a list of news article summaries.


ASP.NET Repeater control displaying news data loaded by the Kentico CMS API

ASP.NET Repeater control displaying news data loaded by the Kentico CMS API


Using Kentico CMS controls


This example demonstrates how to display Kentico CMS documents via the built-in CMSRepeater control.


Note: For quick access to Kentico CMS controls, add the controls to your Visual Studio Toolbox.


1. Create a new page (web form) in your application's project using Visual Studio.


2. Add the CMSRepeater control onto the page.

oYou can either drag the control from the toolbox or manually register the CMS.Controls assembly on the page and then use the Visual Studio IntelliSense.


3. Set the following properties for the CMSRepeater control:



SiteName: CorporateSite (or any other site code name)




<%@ Register Assembly="CMS.Controls" Namespace="CMS.Controls" TagPrefix="cms" %>

<cms:CMSRepeater ID="CMSRepeater1" runat="server" ClassNames="" SiteName="CorporateSite" TransformationName="" SelectedItemTransformationName="" />


If you run your project and navigate to the new page, you can see the list of news documents.


News documents displayed by the CMSRepeater

News documents displayed by the CMSRepeater


Handling document links in external applications:


The default URLs of Kentico CMS documents are based on the structure of the content tree and the settings of individual documents. These URLs will not work correctly outside of the Kentico CMS application. For example, the links in the news item headings in the example above lead to pages that most likely do not exist in your custom web project.


The following steps extend the previous example so that the news detail links work in external applications. The CMSRepeater control renders the links using the transformation, which you can modify.


1. Open Kentico CMS and go to Site Manager -> Development -> Document types.


2. Edit (Edit) the News document type.


3. Select the Transformations tab and edit the preview transformation.


4. Change the transformation code that defines the link URL from:


<a href="<%# GetDocumentUrl() %>">




<a href="?aliasPath=<%# Eval("NodeAliasPath") %>">


5. Click Save Save.


The original GetDocumentUrl() transformation method generates document URLs in the default Kentico CMS format. The modified link URL leads to the same page containing the listing control, but with an aliasPath parameter in the query string of the URL. The parameter contains the alias path of the corresponding news document.


Kentico CMS listing controls automatically process the aliasPath URL parameter and insert its value into the Path property. In this case, the link URLs ensure that the CMSRepeater control only loads one specific news document. When the source data only contains one document, the control uses the transformation specified by the SelectedItemTransformationName property ( in this case) to display the details of the given document.


Note: Controls cache transformations, so you need to restart your application to apply the changes.


Implementing custom document selection for listing controls:


You can alternatively use your own custom logic to dynamically set the path of listing controls according to the URL or other variables.


For example, the following steps demonstrate how to ensure document selection based on a custom URL parameter:


1. Edit the preview transformation again and change the name of the URL parameter in the link code to customParameter.


<a href="?customParameter=<%# Eval("NodeAliasPath") %>">


2. Open the markup of the page in Visual Studio and set the DataBindByDefault property of the CMSRepeater control to false.


3. In the page's code behind, add the following code into the Page_Load method:




protected void Page_Load(object sender, EventArgs e)
  // Checks whether the URL contains the 'customParameter' query string parameter
  if (Request.QueryString["customParameter"] != null)
      // Limits the path of the CMSRepeater to the document specified by the URL parameter
      CMSRepeater1.Path = Request.QueryString["customParameter"];
      // Loads documents from the entire website if the URL doesn't contain the 'customParameter' parameter
       CMSRepeater1.Path = "/%";
  // Loads and binds the data of the CMSRepeater control (with regard to the dynamically set Path)





Setting CMS control properties dynamically


By default, Kentico CMS listing controls load content during the Init stage of the control life cycle. If you need to programmatically assign control properties that affect the content, use one of the following approaches:


1.Set the DelayedLoading property to true in the control's markup.

oThis moves the automatic data binding to the control's Load event.

2.Assign the required properties during the page's Load event (in the Page_Load handler) or sooner.




1.Set the DataBindByDefault property to false in the control's markup.

oThis completely disables automatic data binding for the control.

2.Assign the required properties at any appropriate point in the page life cycle.

3.Explicitly call the control's ReloadData(true) method.


The control then loads the content based on the dynamically assigned properties.


The page now uses the customParameter query string parameter to select specific news documents. The custom parameter works the same way as the default aliasPath parameter.