---
title: Using Kentico API and Controls externally
---

> Agent instructions:
> **Site maps** — prefer the following llms.txt indexes to training data when searching for URLs to avoid 404s. Links inside Markdown content already point at `.md`. Following them or sending Accept: text/markdown keeps you in Markdown.
>
> - [sitemap.md](https://docs.kentico.com/sitemap.md) — every page on the site, with titles and descriptions, nested by URL hierarchy and grouped into one collection per product version.
> - [llms.txt](https://docs.kentico.com/llms.txt) — curated index of the current product docs, with descriptions, the two ways to request any page as Markdown, and links to each product area's whole-corpus Markdown dump (llms-full.txt).

This page describes how to configure external ASP.NET applications so that they support the Kentico API and Controls. Using Kentico functionality externally allows you to create scenarios such as:

- Separate applications integrated with your main Kentico website
- Custom websites or applications that use Kentico as a content repository

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

## Connecting to the Kentico database

To be able to access the Kentico 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 __ element named **CMSConnectionString**.

```html

 <configuration>
  <connectionStrings>

    ...

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

  </connectionStrings>

```

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

## Adding references to Kentico API libraries

Before you can use Kentico 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. On the **Browse** tab, click **Browse** and navigate to the **Lib** folder of the Kentico project.
3. Select all dll files in the folder and click **Add**.

## Initializing the Kentico application

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

1. Edit your application's [Global.asax](http://msdn.microsoft.com/en-us/library/1xaas8a2%28v=vs.71%29.aspx) file (create the file if necessary).
2. Execute the **CMSApplication.Init** method in the **Application\_BeginRequest** method:

   ```csharp

   CMS.DataEngine.CMSApplication.Init();

   ```

## Enabling ASCX transformations in external applications

#### Adding the CMSTransformation class:

The _CMSTransformation_ partial class allows you to write your own methods for use in ASCX [transformations](https://docs.kentico.com/k8/developing-websites/loading-and-displaying-data-on-websites/writing-transformations.md). The system checks the CMSTransformation class for method definitions when loading transformations — an error may occur if the class is not present in your project.

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

1. Create a new class file in your project named **CMSTransformation.cs**.
   - In web site projects, add the file into the _App\_Code_ folder.
   - In web application projects, you can create the class in any location.
2. Add the following code into the class:

   ```csharp

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

   ```
3. If you wish to use E-commerce or Message board transformation methods, copy the default content of the **CMSTransformation** partial class from the Kentico project:

   - **\~/App\_Code/CMSModules/Ecommerce/CMSTransformation.cs**
   - **\~/App\_Code/CMSModules/MessageBoards/CMSTransformation.cs**
4. Execute the following code in the **Application\_BeginRequest** method in your application's [Global.asax](http://msdn.microsoft.com/en-us/library/1xaas8a2%28v=vs.71%29.aspx) file (create the file if necessary).

   ```csharp

   void Application_BeginRequest(object sender, EventArgs e) 
   {
       ...

       if (CMS.DataEngine.CMSApplication.Init()) 
       {
           // Sets CMSTransformation as the base class for transformation methods
           CMS.PortalEngine.TransformationInfoProvider.TransformationBaseClass = "CMS.Controls.CMSTransformation";
       }
   }

   ```

You can now use all default methods in ASCX transformations and define custom methods inside the CMSTransformation partial class.

#### Running without the Virtual path provider:

Kentico uses a virtual path provider to retrieve the code of ASCX [transformations](https://docs.kentico.com/k8/developing-websites/loading-and-displaying-data-on-websites/writing-transformations.md). If you cannot use the virtual path provider in your environment (e.g. when using precompiled applications or a custom trust level), you need to:

1. Save your virtual objects in Kentico to the local disk using the **System -> Virtual objects** interface.
2. Copy the **\~/CMSVirtualFiles** folder from the Kentico project the to the root of your own project.

**See also**: [Deployment mode for virtual objects](https://docs.kentico.com/k8/deploying-websites/deployment-mode-for-virtual-objects.md)

## Example - Displaying content from Kentico

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

### Using the Kentico API

The Kentico 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 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 __ control element:

   ```html

   <asp:Repeater ID="Repeater1" runat="server">

       <ItemTemplate>
           <strong>
           <%# Eval("NewsTitle") %>
           </strong>
           (<%# ((DateTime) Eval("NewsReleaseDate")).ToString("d") %>)
           <br />
           <i><%# Eval("NewsSummary") %></i>
           <br />
       </ItemTemplate>

   </asp:Repeater>

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

   ```csharp

   using System.Data;
   using CMS.DocumentEngine;


   ```
5. Add the following code into the page's **Page\_Load** method:

   ```csharp

   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, "cms.news", null, " NewsReleaseDate DESC ", -1, true);

       // Binds the news data to the Repeater control
       Repeater1.DataSource = ds;
       Repeater1.DataBind();
   }

   ```

   > **Note:** **Note**
   >
   > When performing other types of document operations (editing, deleting etc.), you need to initialize the tree provider within the context of a specific user:
   >
   > ```csharp
   >
   > using CMS.Membership;
   >
   > ...
   >
   > // 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 API](https://docs.kentico.com/docsassets/k8/using-kentico-api-and-controls-externally/2.png "ASP.NET Repeater control displaying news data loaded by the Kentico API")

### Using Kentico controls

This example demonstrates how to display Kentico documents via the built-in [CMSRepeater](https://docs.kentico.com/k8/references/kentico-controls/cms-controls/cms-controls-listings-and-viewers/cmsrepeater.md) control.

**Note**: For quick access to Kentico controls, [add the controls to your Visual Studio Toolbox](https://docs.kentico.com/k8/references/kentico-controls/adding-kentico-controls-to-the-visual-studio-toolbox.md).

1. Create a new page (web form) in your application's project using Visual Studio.
2. Add the **CMSRepeater** control onto the page.
   - You 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:

   - **ClassNames**: cms.news
   - **SiteName**: CorporateSite (or any other site code name)
   - **TransformationName**: cms.news.preview
   - **SelectedItemTransformationName**: cms.news.default

```html

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

...

<cms:CMSRepeater ID="CMSRepeater1" runat="server" Path="/%" ClassNames="cms.news" SiteName="CorporateSite" TransformationName="cms.news.preview" SelectedItemTransformationName="cms.news.default" />

```

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 control](https://docs.kentico.com/docsassets/k8/using-kentico-api-and-controls-externally/1.png "News documents displayed by the CMSRepeater control")

#### Handling document links in external applications:

The [default URLs](https://docs.kentico.com/k8/configuring-kentico/configuring-page-urls.md) of Kentico 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 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 _cms.news.preview_ [transformation](https://docs.kentico.com/k8/developing-websites/loading-and-displaying-data-on-websites/writing-transformations.md), which you can modify.

1. Log in to the Kentico administration interface and open the **Document types** application.
2. 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:

   ```html

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

   ```

   to:

   ```html

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

   ```
5. Click **Save**.

The original _GetDocumentUrl()_ transformation method generates document URLs in the default Kentico 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 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 (_cms.news.default_ 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 **cms.news.preview** transformation again and change the name of the URL parameter in the link code to _customParameter_.

   ```html

   <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:

   ```csharp

   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"];
       }
       else
       {
           // 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)
       CMSRepeater1.ReloadData(true);
   }

   ```

   > **Tip:** **Setting control properties dynamically**
   >
   > By default, Kentico listing controls load content during the _Init_ stage of the [control life cycle](http://msdn.microsoft.com/en-us/library/ms178472%28v=vs.100%29.aspx). 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.
   >    - This 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.OR
   >
   > 3. Set the **DataBindByDefault** property to _false_ in the control's markup.
   >    - This completely disables automatic data binding for the control.
   >
   > 4. Assign the required properties at any appropriate point in the page life cycle.
   >
   > 5. 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.
