Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

115
Kentico 8.2

Transcript of Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

Page 1: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

Kentico 8.2

Page 2: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1. Integrating 3rd party systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.1 Integrating Kentico with other applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

1.1.1 Child web application fails to start . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41.1.2 Running .NET 4.0 child application under a .NET 2.0 or 3.5 parent application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

1.2 Kentico REST service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71.2.1 Configuring the REST service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71.2.2 Authenticating REST requests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111.2.3 Getting data using REST . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

1.2.3.1 Examples of data retrieved via the REST service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181.2.3.2 ODATA service documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

1.2.4 Manipulating data using REST . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211.2.4.1 Managing pages using REST . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231.2.4.2 Managing objects using REST . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

1.2.5 Sending REST requests from code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291.3 Using the integration bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

1.3.1 Integration bus overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311.3.2 Enabling the integration bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371.3.3 Creating integration connectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

1.3.3.1 Implementing outgoing synchronization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401.3.3.2 Implementing incoming synchronization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

1.3.4 Managing integration tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491.3.5 Example - Integration connector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501.3.6 Reference - Integration bus data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521.3.7 Integration bus database model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54

1.4 Using Kentico API and Controls externally . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 551.5 Data.com integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60

1.5.1 Mapping Data.com fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 621.5.2 Searching Data.com for contacts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 631.5.3 Buying contacts from Data.com . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 651.5.4 Customizing the Data.com integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66

1.6 Salesforce integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 671.6.1 Configuring Salesforce integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 671.6.2 Replicating contacts to Salesforce . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 711.6.3 Example - Replicating a contact into a Salesforce lead . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 721.6.4 Force.com integration API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74

1.7 Strands Recommender integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 811.7.1 Integrating the Strands Recommender service into your store . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 821.7.2 Placing Strands recommendations on a page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 841.7.3 Placing Strands recommendations into emails . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 871.7.4 Troubleshooting the Strands Recommender integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 871.7.5 Customizing how products are categorized in the Strands integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88

1.8 Integrating SharePoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 901.8.1 Configuring SharePoint integration connections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91

1.8.1.1 Connecting to SharePoint Online . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 921.8.2 Configuring SharePoint integration web part . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 931.8.3 Configuring SharePoint integration settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 961.8.4 Displaying SharePoint data in Kentico . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 961.8.5 Example - Displaying a SharePoint picture library in Kentico . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 991.8.6 Managing SharePoint libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104

1.8.6.1 Working with files from SharePoint libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1061.8.7 SharePoint integration (obsolete) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108

1.8.7.1 SharePoint integration web parts (obsolete) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1081.8.7.2 SharePoint integration examples (obsolete) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1091.8.7.3 Configuring SharePoint integration settings (obsolete) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115

Page 3: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

Integrating 3rd party systemsOut-of-the-box integrations

Integration tools

            

                       

Integrating Kentico with other applicationsIf you need to combine your Kentico website with an existing application, consider the issues described on this page.

Location of Kentico and your application

You can organize the Kentico web project and your application in the following ways:

Mixing both applications together

If you wish to share functionality, content, security information and session/application variables between Kentico and your application, youcan mix both applications into a single project. The easiest way is to use the Kentico web project as the main application, since it's alreadycorrectly configured. You can add your own assemblies, projects, ASPX pages and other files to the Kentico solution.

If you need to display your own ASPX pages on the actual website, you can register them as and then createASPX page templatesnew pages in the site's content tree based on the templates.If your website is built using the , see: , portal engine Using both ASPX and portal templates on a single site Adding custom code to

.portal engine page templatesTo integrate applications that extend the system's back-end administration interface, you can create .custom modules

Data.com

Keep your contacts and accounts up to date by comparing them with the Data.com business directory.

Salesforce

Automatically replicate contacts coming from your Kentico websites into your organization in SalesForce.

Product recommendations

Offer relevant products to your customers based on conditions that you define. The functionality uses the Strands Recommenderengine.

SharePoint

Display data from a SharePoint server on your website.

REST service

Access and manipulate Kentico data using a RESTful web API.

Integration bus

Synchronize data between Kentico and any other application in real time.

Other integration options

Use the Kentico API and controls externallyCombine the Kentico project with another application

Page 4: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

Using separate nested applications

If your application needs to run independently from Kentico, you can host separate applications in your IIS. There are two possible scenarios:

Kentico manages the main website - place the Kentico web project (CMS folder) into the root of the website and your externalapplication into a sub-directory. You need to create a virtual directory in IIS for the external application.Kentico only provides a sub-section of the website or serves as a content repository - install the Kentico web project into asub-directory under your application.

 

Sharing security information between Kentico and your application

If you wish to use shared authentication for both your application and Kentico, you need to configure your environment for single.sign-on

To use a single system of permissions (authorization), you can leverage and .permissions custom modules 

Child web application fails to startBy default, child web applications inherit the configuration of their parent application. This can prevent the child application from starting whencertain sections of the aren't compatible across applications. For example, if the child application doesn't share the sameweb.configlibraries, handlers, modules, master pages or themes with the parent application. This page describes how you can solve some of thesituations resulting from nesting different applications together.

Breaking web.config inheritance in child applications

Use the tag with the attribute set to to ensure that the configuration applies to the parent weblocation inheritInChildApplications false application only. This can be useful when you don't want to inherit the parent application's settings to the child application. The path attributeset to "." ensures that the location tag covers the default path.

<location path="." inheritInChildApplications="false" > <!-- Additional settings --></location>

Example

The following example shows how you can break inheritance for , , ,  , and in yourcontrols namespaces assemblies modules handlersweb.config file. None of the settings enclosed in the tag with set to are inherited by the childlocation inheritInChildApplications falseapplications.

By default, child applications inherit the configuration specified in the parent application's web.config file. This can make them fail tostart. See for more information.Child web application fails to start

Using the location tag break configuration inheritance

Page 5: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

<location path="." inheritInChildApplications="false" > <system.web> <controls> <!-- Removed for brevity --> </controls> <namespaces> <!-- Removed for brevity --> </namespaces> <assemblies> <!-- Removed for brevity --> </assemblies> </system.web></location>

<location path="." inheritInChildApplications="false" > <system.webServer> <modules> <!-- Removed for brevity --> </modules> <handlers> <!-- Removed for brevity --> </handlers> </system.webServer></location>

Specifying different web.config configurations for child applications

By specifying a value for the attribute in the tag, you can apply different configuration settings to specific folders and files. Thispath locationway, you can distribute parent or child application settings through one configuration file.

The default value for the attribute is ".". You can only specify one value in the attribute.path path

<location path="Folder1" > <section1 ... /> <section2 ... /></location><location path="Folder2" > <section1 ... /> <section2 ... /></location>

Example

The following example shows a configuration that specifies different settings for two specific folders. One of the folders belongs to a parentapplication and the nested folder belongs to a child application:

Using the location tag break configuration inheritance

A different approach to removing inheritance is using the and tags. The tags remove irrelevant modules in the<remove> <clear>child web application. However, this approach is not supported and implemented the same way across all the elements and itemsin the web.config file.

Page 6: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1. 2.

3.

<!-- Configuration for 'Default Web Site' --><location path="Default Web Site/ParentApplication" > <namespaces> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Routing" /> </namespaces></location>

<!-- Configuration for 'ChildApplication' --><location path="Default Web Site/ParentApplication/ChildApplication" > <namespaces> <add namespace="System.IO" /> <add namespace="System.Text" /> </namespaces></location>

 

Running .NET 4.0 child application under a .NET 2.0 or 3.5 parent applicationNOT PUBLISHED

Child .NET applications that are configured to run newer .NET version than their parent applications might fail to start due to compilation andconfiguration errors.

Running the child application fails because the final merged configuration includes the parent configuration as well. You can solve this bymoving the definition in the web.config file of the parent application into the root web.config file for the .NET Framework 2.0.configSections

Example

The following example shows how you can move the configSections of the .NET 2.0 or 3.5 application into the root config file for the .NET 2.0or 3.5 Framework.

Open the parent application's web.config file.Open the root web.config file for the .NET 2.0 and 3.5 Framework, located in:

for .NET 2.0 and 3.5.C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG

Move the  element from the parent application into the root application, directly after the initial elemenconfigSections configurationt.

Taken from ... Could cause too much trouble if misconfigured and customers would thenChild web application fails to startprobably contact us. They can google the solution and put it together from MS materials.

Examples of error messages returned by either IIS or the .NET compilation system:The configuration section 'configSections' cannot be read because it is missing a section declaration.The requested page cannot be accessed because the related configuration data for the page is invalid.

If you run a 64-bit operating system or 64-bit application pools, the root web.config file for .NET 2.0 and 3.5 is located in 

C:\Windows\Microsoft.NET\Framework64\v2.0.50727\CONFIG

If you run both 32-bit and 64-bit application pools, you have to move the  element up configSections into both the rootfiles.

Page 7: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

3.

4.

1. 2.

<?xml version="1.0" encoding="utf-8"?><configuration> <configSections> <sectionGroup name="webServices"type="System.Web.Configuration.ScriptingWebServicesSectionGroup,System.Web.Extensions, Version=3.5.0.0, Culture=neutral,PublicKeyToken=31BF3856AD364E35"> <section name="jsonSerialization"type="System.Web.Configuration.ScriptingJsonSerializationSection,System.Web.Extensions, Version=3.5.0.0, Culture=neutral,PublicKeyToken=31BF3856AD364E35" requirePermission="false"allowDefinition="Everywhere" /> <section name="profileService"type="System.Web.Configuration.ScriptingProfileServiceSection,System.Web.Extensions, Version=3.5.0.0, Culture=neutral,PublicKeyToken=31BF3856AD364E35" requirePermission="false"allowDefinition="MachineToApplication" /> </sectionGroup> </configSections>...

Save the web.config files.

 

Kentico REST serviceREST is an abbreviation of — a style of software architecture designed for distributed systems, typically forRepresentational state transferthe World Wide Web. Kentico has a built-in REST service, which can be used to read, create, update and delete virtually any object or pagewithin the system. These operations are performed by requesting specific URLs. The Kentico REST service is RESTful, which means that itsupports both directions of data transfer (from and into the system).

Kentico also provides the web part, which can be used to display data obtained from the REST service in a simpleGrid for REST servicegrid. You can find an example of this web part on the page on the sample ./Examples/API/REST-service Corporate Site   

Configuring the REST serviceREST prerequisites

Before you can enable the Kentico REST service, you must ensure the following:

In Windows

Go to and click in the left menu.Control Panel -> Programs and Features Turn Windows features on or off

Windows 7 / Windows Server 2008

Expand the node in the dialog window.Microsoft .NET Framework <version>Make sure that both of the following features are installed:

Windows Communication Foundation HTTP ActivationWindows Communication Foundation Non-HTTP Activation

Note that you may need to as well.break web.config inheritance for the child application

Page 8: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1. 2.

1. 2. 3.

4.

5. 6. 7.

Windows 8 / Windows Server 2012

Expand the node..NET Framework 4.5 Advanced ServicesMake sure that the feature is installed.WCF Services -> HTTP Activation

  

In IIS Manager

Select the website for which you want REST to be enabled.Open the configuration.AuthenticationEnsure that authentication is enabled. You can also have either or authentication enabled if requiredAnonymous Forms Windowsby your environment.Disable and other types of authentication.Basic

Select in the navigation tree.Application PoolsDouble-click the application pool used by your website.Make sure the pool uses Managed pipeline mode.Integrated

Page 9: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

7.

1. 2. 3.

4. 5. 6.

Once you have these prerequisites met, you can proceed to configuring the REST service in the Kentico instance.

Configuring the REST service

Once you meet the prerequisites for using the REST service, configure the following settings for the Kentico instance:

Edit your application's file.web.configFind the section directly under the root (i.e. not under a specific element).system.webServer <location>Add the following attribute to the element: <modules>

<modules runAllManagedModulesForAllRequests="true">

Log in to the Kentico administration interface.Open the application.SettingsSelect the category and configure the settings:Integration -> REST

REST setting Description

Service enabled Enables or disables the Kentico REST service.

Service enabled for Choose if the REST service allows access to objects, pages,or both.

Authentication type Determines which type of the REST serviceauthenticationuses. Supported types are and authentication.Basic Forms

Note: You can authenticate REST requests using the hashquery string parameter in both modes.

Always check page security If disabled, security is not checked when accessing publishedversions of pages. If enabled, security is always checked.

Page access is read only If enabled, the REST service only allows GET requests forpages (pages cannot be modified).

Object access is read only If enabled, the REST service only allows GET requests forobjects (objects cannot be modified).

Allowed page types Specifies a list of that the REST service is allowedpage typesto access. Enter the code names of page types separated bysemicolons.

If empty, all page types are allowed.

Allowed object types Specifies a list of objects types that the REST service isallowed to access. If empty, all object types are allowed.

Page 10: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

6.

1.

2.

Generate authentication hash for URL Click the link to generate an hash for specificauthenticationREST URLs.

Enter the full absolute URL of the REST request, including theprotocol, website domain name, virtual directory, ,REST pathand query string . For example:parameters

http://mywebsite.com/rest/content/currentsite/en-us/all/news?format=json

The system adds the authentication hash parameter to theURL. You can copy the URL and use it to perform the RESTrequest without any other type of authentication.

Restrictions:

Only works for GET requests (read only data retrieval)You cannot use hash parameter authentication for obj/allect retrieval requests ( ).~/rest/<object type>/all

Default encoding Sets the character encoding that the REST service uses forrequests that do not contain a supported headAccept-Charseter.

Allow sensitive fields for administrators If enabled, REST requests authenticated using the credentialsof users with the Global administrator areprivilege levelallowed to work with data fields that contain sensitiveinformation (for example fields related to passwords).

Requests authenticated under non-administrator users canNEVER access sensitive fields, regardless of this setting'svalue.

Enabling upload of large data

If you are planning to upload large-size data into Kentico through the REST service, it is necessary to specify the required data size limit inthe application's file. This can be done by adding the following pieces of code into the section at the endweb.config <system.serviceModel>of the web.config file:

Insert a element into the sub-section:<webHttpBinding> <bindings>

<webHttpBinding> <!-- Limits set to 10 MB (specified value in bytes) -->

<binding name="RESTQuotaBinding" maxReceivedMessageSize="10485760"maxBufferPoolSize="10485760" maxBufferSize="10485760" closeTimeout="00:03:00"openTimeout="00:03:00" receiveTimeout="00:10:00" sendTimeout="00:03:00"> <readerQuotas maxDepth="32" maxStringContentLength="10485760"maxArrayLength="10485760" maxBytesPerRead="10485760" /> <security mode="None" /> </binding></webHttpBinding>

Add a element under the sub-section:<service> <services>

<service name="CMS.WebServices.RESTService"> <host> <baseAddresses> <add baseAddress="http://localhost/KenticoCMS/rest" /> </baseAddresses> </host> <endpoint address="" bindingConfiguration="RESTQuotaBinding"binding="webHttpBinding" contract="CMS.WebServices.IRESTService" /></service>

Note: This sample sets all limits to 10 MB. You may need to enter different values according to your specific needs.

Page 11: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

2.

1.

2.

The in the code above only contains a sample value and needs to be replaced with the actual root address of thebaseAddressREST service (depending on your website's domain name).

 

Authenticating REST requestsEvery REST request needs to be authenticated. You can select the of the REST service in Authentication type Settings -> Integration ->

.REST

Basic authentication

With Basic authentication, you need to specify the username and password through the line in the header of every RESTAuthorizationrequest. The header line consists of:

The authentication type ( )BasicThe username and password connected by a colon ( ), encoded using the Base64 algorithmusername:password

For example, the following header line uses as the authentication credentials:RestClient:MyPassword

Authorization: Basic UmVzdENsaWVudDpNeVBhc3N3b3Jk

Once authenticated, the system allows the REST request to perform operations depending on the specified user's and privilege level permiss.ions

 

Forms authentication

When using of requests, the system identifies users based on the active session and the authentication ticket stored informs authenticationthe .ASPXFORMSAUTH cookie. You can use forms authentication to create a web interface with a login page, and allow users to sendREST requests through their browser.

You cannot use forms authentication for the Kentico REST service if you have enabled in IIS.Windows authentication

Forms authentication can pose a security threat, because logged in users may unknowingly click links that send malicious REST requests toyour site. To protect yourself from such attacks, take the following steps:

Immediately after creating the session (i.e. first authentication), set up an by sending a POST request to theauthentication tokenfollowing URL:

https://<your project URL>/rest/settoken?username=<your username>&password=<your password>&token=<your authentication token>

The authentication token can be an arbitrary string of characters, for example a GUID.

Include the authentication token in the HTTP header of every REST request:

Cms-Session-Token: <your authentication token>

Hash parameter authentication

You can authenticate individual REST requests by adding a hash parameter to the URL. The hash parameter allows you to prepare RESTrequests that can be executed by unauthenticated users. Requests that contain the hash parameter ignore the other types of authentication— the value of the setting does not affect hash authentication.Authentication type

Important: We strongly recommend using to protect the authentication credentials in the request headers. See also: SSL Configuring SSL

Note: The type of the Kentico REST service does not require Basic Authentication to be enabled in IIS. KeepBasic authenticationBasic Authentication disabled in IIS as described in .Configuring the REST service

Restrictions

Only works for GET requests (read only data retrieval)You cannot use hash parameter authentication for ( ). This is an/all object retrieval requests ~/rest/<object type>/allintentional security limitation that protects global data in the system.

Page 12: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1. 2. 3. 4. 5.

6.

To get the authentication hash for REST requests:

Prepare the URL of your REST request in advance.Open the application.SettingsSelect the category.Integration -> RESTClick .Generate authentication hashEnter the full absolute URL of the REST request, including the protocol, website domain name, virtual directory, , andREST pathquery string . For example: parameters http://mywebsite.com/rest/content/currentsite/en-us/all/news?format=jsonClick .Authenticate

The system adds the authentication hash parameter to the URL. You can copy the URL and use it to perform the REST request without anyother type of authentication. 

Getting data using RESTThe REST service allows you to retrieve page and object data from Kentico instances.

Send requests using the to a URL in format: GET HTTP method <REST base URL>/<resource path>

The base URL of the Kentico REST service is . For example, if your site is running at use <site domain name>/rest ,http://localhost/Kenticoas the base URL of the service. To learn about the available for pages and objects, see the http://localhost/Kentico/rest resource paths

tables in the sections below. The requests return data in either XML, JSON, RSS or Atom format (see Examples of data retrieved via the for more information).REST service

Character encoding

Data retrieval requests return the results in the server's default character encoding. To get the results in a different encoding type, set theencoding in the field of the GET request's HTTP header. If the specified encoding is not available, the system uses the Accept-Charset Defa

configured in .ult encoding Settings -> Integration -> Rest

GET http://localhost/Kentico/rest/cms.user/administrator HTTP/1.1Authorization: Basic UmVzdENsaWVudDpNeVBhc3N3b3JkAccept-Charset: utf-8Content-Type: text\xml

 

Getting page data

To load the data of pages from Kentico websites, send GET requests to the appropriate URL — append the described resource pathsbelow to the base URL of your REST service.

Resource format and example Description

Single page

/content/currentsite/<culture>/document/<alias path> /content/currentsite/en-us/document/company/careers______________________________________________________

A single page in the given culture from the site running on thedomain in the base URL.

Identify the page using its .alias path

/content/site/<site name>/<culture>/document/<alias path> /content/site/corporatesite/en-us/document/company/careers_

A single page in the given culture on the specified site.

Multiple pages

Warning: Only use hash parameter authentication for loading data that you want to make publicly available. REST requests withhash authentication can be executed by anyone who obtains the URL (for example by intercepting the web request).

REST base URL

Sending a GET request to the base URL of the REST service exposes the service document (for ODATA browsing). Thedocument contains a list of all available primary object types (without child and binding object types) and the URLs under which theobjects can be accessed. See also: ODATA service documents

Example

You can further configure the data retrieval by adding to the URL.query string parameters

Page 13: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

/content/currentsite/<culture>/all/<alias path> /content/currentsite/en-us/all/news

/content/site/<sitename>/<culture>/all/<alias path> /content/site/corporatesite/en-us/all/news_

All pages starting with the specified .alias path

/content/currentsite/<culture>/childrenof/<alias path> /content/currentsite/en-us/childrenof/news

/content/site/<site name>/<culture>/childrenof/<alias path> /content/site/corporatesite/en-us/childrenof/news_

All child pages under the specified parent page. Does not includethe parent page itself.

Getting object data

To load the data of objects from Kentico, send GET requests to the appropriate URL — append the described below to the resource pathsbase URL of your REST service.

Most object resources start with an name. To find the value for specific object types, view the of classes in the object type Code name Modul application, or the column of the database table.es ClassName CMS_Class

Resource format and example Description

Multiple objects

/<object type> /cms.country_

All objects of the given type assigned to the site running on thedomain in the base URL.

If the object type does not use site bindings, returns all objects ofthe given type.

/<object type>/site/<site name>/cms.country/site/corporatesite_

All objects of the given type assigned to the specified site.

If the object type does not use site bindings, returns all objects ofthe given type.

/<object type>/global /cms.emailtemplate/global_

All global objects of the given type (objects not assigned to anysite).

If the object type does not use site bindings, returns all objects ofthe given type.

/<object type>/all /cms.emailtemplate/all_________________________________________________________

All objects of the given type (site-related objects from all sites andglobal objects).

Note:

/all object retrieval requests only work if the user account usedfor has the .authentication Global administrator privilege levelThe REST service does not allow object retrieval for/allrequests that use the URL parameter for . hash authentication

These are intentional security limitations that protect global data.

Single object

/<object type>/<id or guid>/cms.country/271/cms.country/e431b7e6-9e6c-409d-a1d9-748cbf51b5d6_

Object of the given type with the specified identifier (ID or GUIDvalue).

Ignores site bindings – object IDs and GUIDs are unique across allsites in the system.

Culture constants

You can use the following constants instead of culture codes in page REST calls:

defaultculture - the page version in the site's default cultureallcultures - page versions in all available cultures

Example: /content/currentsite/defaultculture/document/company/careers

You can further configure the data retrieval by adding to the URL.query string parameters

Page 14: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

/<object type>/<code name> /cms.country/usa_

Object of the given type with the specified code name.

For object types with site bindings, always returns the objectassigned to the site running on the domain in the base URL.

/<object type>/site/<site name>/<object code name> /cms.emailtemplate/site/corporatesite/Blog.NotificationToModerators_

Object of the given type with the specified code name, assigned tothe specified site.

/<object type>/global/<object code name> /cms.emailtemplate/global/Blog.NotificationToModerators_

Global object of the given type with the specified code name.

Child objects

/<object type>/<id>/children/cms.country/271/children_

All that are supported as child types for the specifiedobject typesobject. Only ID values can be used to identify the parent object.

/<object type>/<id>/children/<child object type>/cms.country/271/children/cms.state_

All objects of the given type that are children of the specified parentobject. Only ID values can be used to identify the parent object.

Binding objects

/<object type>/<id>/bindings /cms.user/53/bindings_

All that are used as binding types (representobject typesrelationships with other objects) for the specified object. Only IDvalues can be used to identify the object.

/<object type>/<id>/bindings/<binding object type> /cms.user/53/bindings/cms.usersite_

All objects of the given binding type that exist for the specifiedobject. Only ID values can be used to identify the object.

Custom tables

/cms.customtable/<custom table code name>/cms.customtable/customtable.sampletable_

The class definition of the specified (includes datacustom tablesuch as the custom table's names, field definitions and searchsettings).

/customtableitem.<custom table code name> /customtableitem.customtable.sampletable_

The data records stored in the specified custom table.

Forms

/cms.form/<form code name>/cms.form/contactus_

The class definition of the specified (includes data such as theformform's names, basic settings and field definitions).

/bizformitem.bizform.<form code name> /bizformitem.bizform.contactus_

The data records stored for the specified form.

Other

/<object type>/site /cms.country/site_

Lists all sites on which the specified object type is available andprovides the REST URLs under which the object data can beretrieved for individual sites (for ODATA browsing).

/typeinfo/<object type> /typeinfo/cms.user_

The data for the specified object type. The TypeInfo is aTypeInfoset of properties that define the general behavior and basicproperties of object types (classes) in Kentico.

/macro/<expression>/macro/CurrentSite.SiteName

Evaluates the given and serializes the result.macro expressionOnly works for macros that return a serializable result.

When creating the macro expression:

Do NOT add the encapsulating bracket charactersUse URL encoding for forbidden URL characters

Data loading parameters

When loading data via REST, you can append the following query string parameters to the request URL:

Parameter Value (default bold) Description

Page 15: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

General

format xml/json/atom10/rss20 Sets the format of the retrieved data. Forexample, append to the?format=jsonrequest URL to get data in JSON format.

See also: Examples of data retrieved viathe REST service

localize______________________

culture code__________________________

If added, the system resolves all localizatio inside the returned data.n expressions

Without this parameter, requests alwaysreturn localization expressions inunresolved format. Supported by both pageand object retrieval requests.

Specify the target language by entering thecorresponding into theculture codeparameter's value. You can find theavailable culture codes in the Localizationapplication on the tab.Cultures

For example, append to the?localize=fr-frrequest URL to resolve all localizationexpressions into their French value (or thevalue in the default if theUI cultureexpression is not defined in French).

hash hash string Allows you to the requestauthenticatewithout requiring an authentication headeror Forms authentication.

See to learnAuthenticating REST requestshow to generate the hash value.

Pages

classnames page type code name ( )all Limits which the requestpage typesreturns. Specified as a list of page typecode names separated by semicolons.

For example, to retrieve only pacms.articleges, append to?classnames=cms.articlethe request URL.

coupleddata true/false Determines if the request retrieves datastored in the fields of specific page types(coupled data).

To load pages without coupled data,append to the request?coupleddata=falseURL.

combinewithdefaultculture true/false Indicates if the request loads the defaultlanguage versions of pages if they do notexist in the specified culture.

To load the default language versions ofpages, append ?combinewithdefaultculture

to the request URL.=true

selectonlypublished true/false Determines if the request loads only pagesthat are published on the live site.

To also retrieve unpublished pages ,append to the?selectonlypublished=falserequest URL.

version published/last Determines if the request returns the pageversions that are published on the live siteor the latest version that is being edited inthe application (when using Pages Workflo

).w

To load the latest page versions, append ?v to the request URL.ersion=last

Multiple pages or objects

Page 16: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

where SQL code ( )empty SQL WHERE condition for filtering theloaded data. The parameter only allows thefollowing types of SQL syntax:

column names, values and basicoperators: =, !=, >, <AND & OR operators, parenthesescolumn BETWEEN AND value valuecolumn LIKE valuecolumn IN (values)column IS NULLNOT keyword for the aboveexpressions (NOT BETWEEN, NOTLIKE, NOT IN, IS NOT NULL)

Other expressions and SQL functions arenot supported.

Example: ~/rest/cms.user?Where=UserIsEditor=1

orderby SQL code ( )empty SQL ORDER BY clause for modifying theorder of the items in the data. Theparameter allows the following values:

one or more column names (separatedby commas)the ASC and DESC keywords

Other SQL expressions and functions arenot supported.

Append to use?orderby=##default##alphabetical order based on the objectdisplay name.

columns column names ( )all columns Limits which data columns of the object orpage are loaded.

For example, to load only the anUserNamed columns when retrieving users,UserIDappend to?columns=UserName,UserIDthe request URL.

If you add the parameter, the columns binar parameter is ignored (you can choosey

whether to include binary columns byenumerating the corresponding columns).

topn integer ( )all records SQL TOP N clause for filtering the loadeddata.

For example, to load only the first 10records, append to the request?topn=10URL.

Multiple objects

offset integer ( )first record Sets the number of the first record that therequest returns (according to the order ofthe data). Allows you to implement pagingof the data.

For example, to load data starting from thethird item in the dataset, append t?offset=2o the request URL.

maxrecords integer ( )all records Limits the maximum number of retrievedrecords. You can use the paramaxrecordsmeter in combination with the parameoffsetter to retrieve a specific range of records.

For example, to load items 11–20 from thedata, append t?offset=10&maxrecords=10o the request URL.

Objects

Page 17: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

objectdata true/false Indicates whether the request retrieves thedata fields of objects.

To load only the metadata of an object,append t?objectdata=false&metadata=trueo the request URL.

metadata true/false Determines if the request retrieves themetadata of objects (type, list of properties /columns).

To load the metadata, append ?metadata=t to the request URL.rue

binary true/false Indicates whether the request retrievesbinary data (e.g. the data of files uploadedinto form fields). Binary data is retrieved in

format.Base64

To include the binary data in the response,append to the request URL.?binary=true

children true/false Indicates whether the result includes childobjects.

To load child objects, append ?children=tru to the request URL.e

maxrelativelevel integer ( )all levels If the parameter is true, thischildrenparameters sets the maximum depth of theexported object tree structure.

For example, to load all child objects downto the second level of the object tree,append ?children=true&maxrelativelevel=2to the request URL.

bindings true/false Determines if the retrieved data includesbindings to child objects and sites.Requests only return bindings if the objectd

parameter is true.ata

To load object data with its bindings,append to the request URL.?bindings=true

otherbindings true/false Determines if the retrieved data includesbindings to other objects (M:Nrelationships). Requests only returnbindings if the parameter is true.objectdata

To load object data with bindings to otherobjects, append to the?otherbindings=truerequest URL.

metafiles true/false Determines if the retrieved data includesmetafiles attached to the object

To load metafiles, append t?metafiles=trueo the request URL.

relationships true/false Determines if the retrieved data includesobject relationships.

To load relationships, append ?relationship to the request URL.s=true

categories true/false Determines if the retrieved data includesthe object's category structure (if the objectis stored in a hierarchical categorystructure).

To load the category structure, append ?cat to the request URL.egories=true

translations true/false Indicates whether the result includes atranslation table of foreign keys.

To load the translation table, append ?trans to the request URL.lations=true

Page 18: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

hierarchy true/false If true, the response data is exported in ahierarchical structure (if false, the children –bindings – parent structure is flat).

To export the data in a hierarchicalstructure, append to the?hierarchy=truerequest URL.

 

Examples of data retrieved via the REST serviceThis page shows examples of data (all objects) obtained from the REST service in various formats.cms.country

XML

All objects retrieved in format.cms.country XML

The data was obtained using the following URL: ~/rest/cms.country

 

JSON

The code below is an extract from data of the objects retrieved in format.cms.country JSON

The data was obtained using the following URL: ~/rest/cms.country?format=json

Page 19: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

{"cms_countries":[{"cms_country":[{"CountryDisplayName":"Afghanistan","CountryID":272,"CountryLastModified":"\/Date(1299419802000)\/","CountryName":"Afghanistan","CountryGUID":"12d61676-7541-4a4e-88f6-f02098b637fe"},{"CountryDisplayName":"Albania","CountryID":273,"CountryLastModified":"\/Date(1202723603000)\/","CountryName":"Albania","CountryGUID":"af056090-4477-4826-ad41-7ce8e8d45d3a"},{"CountryDisplayName":"Algeria","CountryID":274,"CountryLastModified":"\/Date(1205397300000)\/","CountryName":"Algeria","CountryGUID":"59f8718f-ff33-4376-bb18-c0d5b0d96786"},{"CountryDisplayName":"American Samoa","CountryID":275,"CountryLastModified":"\/Date(1205397300000)\/","CountryName":"AmericanSamoa","CountryGUID":"8a89a7b3-11ee-4cef-9770-22a88bc5e5d6"},{"CountryDisplayName":"Andorra","CountryID":276,"CountryLastModified":"\/Date(1205397300000)\/","CountryName":"Andorra","CountryGUID":"cbba23bb-43d5-4840-a797-a9e27f6018f4"},{"CountryDisplayName":"Angola","CountryID":277,"CountryLastModified":"\/Date(1314631085000)\/","CountryName":"Angola","CountryGUID":"503673e4-fc0e-40a3-9ff9-521f67680d3f"},{"CountryDisplayName":"Anguilla","CountryID":278,"CountryLastModified":"\/Date(1205397300000)\/","CountryName":"Anguilla","CountryGUID":"fe1c087d-6157-4f94-9745-39a49f981bfa"} ... ]},{"TotalRecords":[{"TotalRecords":"246"}]}]}

RSS 2.0

All objects retrieved in format.cms.country RSS 2.0

The data was obtained using the following URL: ~/rest/cms.country?format=rss20

Page 20: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

Atom 1.0

All objects retrieved in format.cms.country Atom 1.0

The data was obtained using the following URL: ~/rest/cms.country?format=atom10

 

ODATA service documentsThe Kentico REST service supports by providing service documents in a standard format for ODATA services. The serviceODATAdocuments provide information about the types of data available via the REST service and about the URLs under which the data can beaccessed.

The service documents are available under the following URLs:

~/rest - exposes the service document. The document contains a list of all available primary object types (without child and bindingobject types) and the URLs under which the objects can be accessed.

Page 21: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

 

~/rest/<object type>/site - lists all sites on which the specified object type is available and provides the REST URLs under whichthe object data can be retrieved for individual sites.

  

Manipulating data using RESTThe REST service allows you to manipulate the data of pages and objects on Kentico instances.

Send requests using the , or to the appropriate URL. See the following documentation pages for details:POST PUT DELETE HTTP method

Managing pages using RESTManaging objects using REST

 

General data manipulation parameters

When managing pages or objects via REST, you can append the following query string parameters to the request URL:

Parameter Value (default bold) Description

format xml/json Sets the format of the data submitted inPOST/PUT requests. For example, append

to the request URL to submit?format=jsondata in JSON format.

hash hash string___________________

Allows you to the requestauthenticatewithout requiring an authentication headeror Forms authentication.

See to learnAuthenticating REST requestshow to generate the hash value.

Setting fields to empty values

If you need to set a page or object field to an empty value using a REST request, use the following expression instead of an actual value:

Data validation

When inserting or updating data via the REST service, Kentico does not perform any validation. You need to ensure validation onthe side of the application sending the REST requests to prevent unwanted behavior.

Page 22: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1.

2. 3.

##null## (for data in XML format)null (for data in JSON format)

The null expression is particularly useful for non-string fields (typically fields storing foreign key IDs), where an empty string value would notproduce the desired results.

For example, the following request updates the page of the sample Corporate Site and ensures that it does not have a user specifiedHomein the field:Created by

HTTP method: PUTURL: ~/rest/content/site/corporatesite/en-us/document/HomeData (XML format):

<CMS_MenuItem> <DocumentCreatedByUserID>##null##</DocumentCreatedByUserID></CMS_MenuItem>

Uploading attachment files

When uploading files via the REST service, use the following format for the binary data:

base 64 encoding in requests using the XML data formatbyte array values in requests using the JSON data format (you can get the appropriate byte array by serializing your data via the Sy

method)stem.Web.Script.Serialization.JavaScriptSerializer.Serialize

Carefully consider the data type of the target field. Most page and object fields in Kentico do not store binary data directly, but instead containthe GUID of the corresponding attachment object. To find information about the requirements for your scenario, for ansend a GET requestexisting object of the given type and check the resulting data.

For example, use the following steps to create a new page, including an image file as an attachment:CMS.File

Send a request to create the attachment file itself ( object type, base64 encoding for the file binary in the cms.attachment Attachme field):ntBinary

HTTP method: POSTURL: ~/rest/cms.attachment/currentsiteData (XML format):

<CMS_Attachment> <AttachmentName>NewAttachmentFile.png</AttachmentName> <AttachmentExtension>.png</AttachmentExtension> <AttachmentSize>3180</AttachmentSize> <AttachmentMimeType>image/x-png</AttachmentMimeType> <AttachmentImageWidth>183</AttachmentImageWidth> <AttachmentImageHeight>47</AttachmentImageHeight> <AttachmentDocumentID>15</AttachmentDocumentID> <AttachmentBinary></AttachmentBinary> <!-- Insert base 64 encodedbinary data --></CMS_Attachment>

Store the value from the data of the response to the POST request that created the attachment.AttachmentGuidCreate the CMS.File page (set the field to the GUID of the new attachment object):FileAttachment

HTTP method: POSTURL: ~/rest/content/currentsite/en-us/document/ImagesData (XML format):

Note: To upload binary data using requests in the JSON format, you need to apply or newer.hotfix 8.1.1

Page 23: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

3.

<CMS_File> <NodeClassID>1685</NodeClassID> <DocumentExtensions>.png</DocumentExtensions> <DocumentType>.png</DocumentType> <FileName>NewAttachmentFile</FileName> <FileAttachment>96d6dfc9-4f3a-4a30-95af-4d7cc5a36f9a</FileAttachment><!-- Insert the GUID of the appropriate attachment object --></CMS_File>

 

Managing pages using RESTThe REST service allows you to manipulate the data of pages on Kentico websites. Send requests using the , orPOST PUT DELETE HTTP

to the appropriate URL — append the described below to the of your REST service.method resource paths base URL

The base URL of the Kentico REST service is . For example, if your site is running at use <site domain name>/rest ,http://localhost/Kenticoas the base URL of the service. http://localhost/Kentico/rest

Creating pages

HTTP method: POST

Resource format:

/content/currentsite/<culture>/document/<alias path> - creates a new page in the given culture for the site running on the domainin the base URL./content/site/<site name>/<culture>/document/<alias path> - creates a new page in the given culture on the specified site.

Use the to identify the under which you want to create the new page.alias path parent page

Set the name and other fields of the new page in the data of the POST request. Both and formats are supported for the data.XML JSON

 

Examples

Creates a page (CMS.MenuItem type) under the page New service Services

XML JSON

To learn more about working with pages, see .Managing pages using REST

Important:

When creating new pages, always set the field. To find the value for a page type, NodeClassID NodeClassID get a page using the REST service and check the data or view the column in the databaseof the given type ClassID CMS_Class

table.The request data must contain values for for the given .all fields that are set as required page typeThe service automatically sets the system fields of the new page (such as the ID and timestamp fields).Creating multiple pages in a single request is not supported. You need to send a separate POST request for each page.

Creating language versions of pages

You can use POST requests to create new of existing pages:language versions

Use the culture code in the resource path to set the desired language.Identify the page using the .alias pathSpecify the of the existing page in the request data. Do NOT manually set a for the new languageNodeID DocumentIDversion.Set any other required data for the page language version.

Page 24: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

URL: ~/rest/content/currentsite/en-us/document/Services

Data:

<CMS_MenuItem> <NodeClassID>4114</NodeClassID> <DocumentName>Newservice</DocumentName> <DocumentPageTemplateID>23438</DocumentPageTemplateID></CMS_MenuItem>

URL: ~/rest/content/currentsite/en-us/document/Services?format=json

Data:

{"NodeClassID":4114,"DocumentName":"New service","DocumentPageTemplateID":23438}

Creates a page (CMS.News type) under the pageNews article News

XML JSON

URL: ~/rest/content/currentsite/en-us/document/News

Data:

<CMS_News> <NodeClassID>4112</NodeClassID> <NewsTitle>Newsarticle</NewsTitle> <NewsReleaseDate>2014-06-05T00:00:00+02:00</NewsReleaseDate> <NewsSummary>Summary</NewsSummary> <NewsText>Text</NewsText></CMS_News>

URL: ~/rest/content/currentsite/en-us/document/News?format=json

Data:

{"NodeClassID":4112,"NewsTitle":"News article","NewsReleaseDate":"2014-06-05T00:00:00Z","NewsSummary":"Summary","NewsText":"Text"}

Creates a version of the existing page on the sample Corporate siteFrench Services

XML JSON

URL: ~/rest/content/site/CorporateSite/fr-fr/document/Services

Data:

<CMS_MenuItem> <NodeID>5</NodeID> <DocumentName>FrenchServices</DocumentName></CMS_MenuItem>

URL: ~/rest/content/site/CorporateSite/fr-fr/document/Services?format=json

Data:

{"NodeID":5,"DocumentName":"French Services"}

Updating existing pages

HTTP method: PUT

Updating page data

Resource format:

/content/currentsite/<culture>/document/<alias path> - updates the data of an existing page on the site running on the domain inthe base URL./content/site/<site name>/<culture>/document/<alias path> - updates the data of an existing page on the specified site.

Use the to identify the page that you want to update. Updating multiple pages in a single request is not supported. You need toalias path

Page 25: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

send a separate PUT request for each page.

Update the values of the page's fields using the data of the PUT request. Both and formats are supported for the data.XML JSON

Examples:

Updates the name of the page on the sample Corporate siteServices

XML JSON

URL: ~/rest/content/site/CorporateSite/en-us/document/Services

Data:

<CMS_MenuItem> <DocumentName>ServicesMODIFIED</DocumentName> <MenuItemName>ServicesMODIFIED</MenuItemName></CMS_MenuItem>

URL: ?f~/rest/content/site/CorporateSite/en-us/document/Servicesormat=json

Data:

{"DocumentName":"Services MODIFIED","MenuItemName":"Services MODIFIED"}

Updates the title, release date and summary of a news article on the sample Corporate site

XML JSON

URL: ~/rest/content/site/CorporateSite/en-us/document/News/New-Consulting-Services

Data:

<CMS_News> <DocumentName>Consultingavailable</DocumentName> <NewsTitle>Consultingavailable</NewsTitle> <NewsReleaseDate>2014-07-04T00:00:00+02:00</NewsReleaseDate> <NewsSummary>Updatedsummary</NewsSummary></CMS_News>

URL: ~/rest/content/site/CorporateSite/en-us/document/News/New-?format=jsonConsulting-Services

Data:

{"DocumentName":"Consultingavailable","NewsTitle":"Consulting available","NewsReleaseDate":"2014-07-04T00:00:00Z","NewsSummary":"Updated summary"}

Workflow actions

You can also use PUT requests to move pages through the life cycle, or check pages in and out when using .workflow content locking

Resource format:

/content/currentsite/<culture>/<workflow action>/<alias path> - performs the given workflow action for the specified page on thesite running on the domain in the base URL./content/site/<site name>/<culture>/<workflow action>/<alias path> - performs the given workflow action for the given page onthe specified site.

Workflow action Description

publish Publishes the page.

Updating page names

Many have a unique field that serves as the source for the page name (instead of the default field).page types DocumentNameWhen updating the names of such page types, always set the new value for both the field and the dedicatedDocumentNamepage type name field to ensure consistency.

Page 26: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

checkout Performs check-out for the page. The page is checked out underthe user account specified by the REST request's infauthenticationormation.

checkin Performs check-in for the page.

archive Archives the page.

movetonextstep Moves the page to the next workflow step.

movetopreviousstep Moves the page to the previous workflow step.

Use the to identify the page for which you want to perform the workflow action. Do not submit any data when sending workflowalias pathaction requests.

URL example: ~/rest/content/currentsite/en-us/checkout/Home

Deleting pages

HTTP method: DELETE

Resource format:

/content/currentsite/<culture>/document/<alias path> - deletes the given of the page for the site running on thelanguage versiondomain in the base URL./content/site/<site name>/<culture>/document/<alias path> - deletes the given language version of the page on the specifiedsite.

Use the to identify the page that you want to delete. Deleting multiple pages in a single request is not supported. You need to sendalias patha separate DELETE request for each page.

Page deletion parameters

When deleting pages via REST, you can append the following query string parameters to the request URL:

Parameter Value (default bold) Description

deleteallcultures true/false Indicates if the request also deletes all lang of the specified page.uage versions

To delete all language versions of a page,append to the?deleteallcultures=truerequest URL.

destroyhistory true/false Indicates if the request also deletes thepage's .version history

To delete the version history together withthe page, append to?destroyhistory=truethe request URL.

 

Managing objects using RESTTo manage objects in Kentico using the REST service, send requests using the POST, PUT or DELETE to the appropriateHTTP methodURL — append the described below to the of your REST service. resource paths base URL

The base URL of the REST service is . For example, if your site is running at use <site domain name>/rest ,http://localhost/Kentico http://locas the base URL of the service. alhost/Kentico/rest

Object resource paths start with an name. To find the value for specific object types, view the of classes in the object type Code name Modu application, or the column of the database table.les ClassName CMS_Class

Creating objects

HTTP method: POST

Resource format:

/<object type> - creates a new object of the specified type./<object type>/currentsite - creates a new object of the specified type and assigns it to the website running on the domain in thebase URL.

Important: Do NOT use object requests to create, update or delete the pages of Kentico websites. See Managing pages using for information about working with pages.REST

Page 27: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

/<object type>/site/<site name> - creates a new object of the specified type and assigns it to the specified website./customtableitem.<custom table code name> - creates a new data record inside the specified . custom table/bizformitem.bizform.<form code name> - creates a new data record inside the specified .form

Set the name and other fields of the new object in the data of the POST request. Both and formats are supported for the data.XML JSON

 

Examples

Creates a new user with the Editor privilege level and an empty password. Assigns the user to the site running on the domain inthe base URL.

XML JSON

URL: ~/rest/cms.user/currentsite

Data:

<CMS_User> <UserName>Editor</UserName> <FullName>Contenteditor</FullName> <Email>[email protected]</Email> <UserEnabled>true</UserEnabled> <UserIsEditor>true</UserIsEditor></CMS_User>

URL: ~/rest/cms.user/currentsite?format=json

Data:

{"UserName":"Editor","FullName":"Content editor","Email":"[email protected]","UserEnabled":true,"UserIsEditor":true}

Creates a new object with a child statecountry

XML JSON

URL: ~/rest/cms.country

Data:

<data> <CMS_Country> <CountryDisplayName>Newcountry</CountryDisplayName> <CountryName>NewCountry</CountryName> </CMS_Country> <CMS_State> <StateDisplayName>Newstate</StateDisplayName> <StateName>NewState</StateName> <StateCode>NS</StateCode> </CMS_State></data>

URL: ~/rest/cms.country?format=json

Data:

{"CountryDisplayName":"New country","CountryName":"NewCountry","CMS.State": [{ "StateDisplayName":"New state", "StateName":"NewState", "StateCode":"NS" }]}

Creates a for the page of the sample Corporate sitepage alias Home

XML JSON

Important:

The service automatically sets the system fields of the new object (such as the ID and timestamp fields).Creating multiple objects of the same type in a single request is not supported.You can create child or binding objects along with the primary object. When using the XML format for the data of suchrequests, enclose the data into the element to ensure valid syntax with a single root element.<data>

Page 28: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

URL: ~/rest/cms.documentalias/site/corporatesite

Data:

<CMS_DocumentAlias> <AliasNodeID>4</AliasNodeID> <AliasURLPath>/HomeAlias</AliasURLPath></CMS_DocumentAlias>

URL: ~/rest/ ?format=jsoncms.documentalias/site/corporatesite

Data:

{"AliasNodeID":4,"AliasURLPath":"/HomeAlias"}

Adds a new data record into the custom tableSample table

XML JSON

URL: ~/rest/customtableitem.customtable.sampletable

Data:

<customtable_SampleTable>  <ItemText>Record added viaREST</ItemText></customtable_SampleTable>

URL: ?format=jso~/rest/customtableitem.customtable.sampletablen

Data:

{"ItemText":"Record added viaREST"}

Updating existing objects

HTTP method: PUT

Resource format:

/<object type>/<id or guid> - updates the object with the specified identifier (ID or GUID value). /<object type>/<code name> - updates the object with the specified code name. For object types with site bindings, always updatesthe object assigned to the site running on the domain in the base URL./<object type>/site/<site name>/<code name> - updates the object with the specified code name on the specified website./<object type>/global/<code name> - updates the global object with the specified code name./customtableitem.<custom table code name>/<item id or guid> - updates the data record with the specified identifier (ID or GUIDvalue) inside the given . custom table/bizformitem.bizform.<form code name>/<item id or guid> - updates the data record with the specified identifier (ID or GUIDvalue) inside the given .form

Update the values of the object's fields using the data of the PUT request. Both and formats are supported for the data. UpdatingXML JSONmultiple objects in a single request is not supported.

Examples

Updates the email address of the useradministrator

XML JSON

URL: ~/rest/cms.user/administrator

Data:

<CMS_User> <Email>[email protected]</Email></CMS_User>

URL: ~/rest/cms.user/administrator?format=json

Data:

{"Email":"[email protected]"}

Updates a data record of the sample formContact us

XML JSON

Page 29: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

URL: ~/rest/bizformitem.bizform.contactus/1

Data:

<Form_ContactUs> <Email>[email protected]</Email>  <Message>Updatedmessage</Message></Form_ContactUs>

URL: ?format=json~/rest/bizformitem.bizform.contactus/1

Data:

{ "Email":"[email protected]", "Message":"Updated message"}

Deleting objects

HTTP method: DELETE

Resource format:

/<object type>/<id or guid> - deletes the object with the specified identifier (ID or GUID value)./<object type>/<code name> - deletes the object with the specified code name. For object types with site bindings, always deletesthe object assigned to the site running on the domain in the base URL./<object type>/site/<site name>/<code name> - deletes the object with the specified code name from the specified website./<object type>/global/<code name> - deletes the global object with the specified code name./customtableitem.<custom table code name>/<item id or guid> - deletes the data record with the specified identifier (ID or GUIDvalue) from the given .custom table/bizformitem.bizform.<form code name>/<item id or guid> - deletes the data record the specified identifier (ID or GUID value)from the given .form

URL examples:

~/rest/cms.user/53~/rest/cms.country/usa~/rest/cms.country/e431b7e6-9e6c-409d-a1d9-748cbf51b5d6 ~/rest/cms.emailtemplate/site/corporatesite/Blog.NotificationToModerators~/rest/customtableitem.customtable.SampleTable/5

Deleting multiple objects in a single request is not supported. You need to send a separate DELETE request for each object. 

Sending REST requests from codeBy sending requests to the , you can from the system or .Kentico REST service get data manipulate pages and objects

The following example demonstrates how to send REST requests using server-side code. The sample code is incomplete — you need toperform the following according to your requirements:

integrate the request sending into your custom logic or applicationsupply the required values (HTTP method, request URL and data)process the response dataensure exception handling

Page 30: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

using System;using System.Web;using System.Net;using System.IO;using System.Text;

...

string httpMethod; // "GET", "POST", "PUT" or "DELETE"string requestUrl; // The URL of the REST request (base URL + resource path)string requestData; // Data for POST or PUT requests

string responseDescription; // Stores the description of the response statusstring responseData; // Stores data retrieved by the request

// Creates the REST requestHttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);

// Sets the HTTP method of the requestrequest.Method = httpMethod;

// Authorizes the request using Basic authenticationrequest.Headers.Add("Authorization: Basic YWRtaW5pc3RyYXRvcjo=");

// Submits data for POST or PUT requestsif (request.Method == "POST" || request.Method == "PUT"){ request.ContentType = "text/xml";

Byte[] bytes = Encoding.GetEncoding("utf-8").GetBytes(requestData); request.ContentLength = bytes.Length;

using (Stream writeStream = request.GetRequestStream()) { writeStream.Write(bytes, 0, bytes.Length); }}

// Gets the REST responseHttpWebResponse response = (HttpWebResponse)request.GetResponse();

// Stores the description of the response statusresponseDescription = (Int32)response.StatusCode + " - " +response.StatusDescription;

// Gets the response datausing (Stream responseStream = response.GetResponseStream()){ if (responseStream != null) using (StreamReader reader = new StreamReader(responseStream)) { responseData = HttpUtility.HtmlEncode(reader.ReadToEnd()); }}

...

 

C# example

Page 31: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

Using the integration busThe integration bus allows developers to connect Kentico with third party systems, such as CRMs or ERPs. The purpose of the integration isto synchronize objects and pages (in both directions). The data exchange is ensured by . Each connector is a standard .NETconnectorsclass that needs to be implemented by a developer.

Information

Connecting Kentico with third party systems:

 

Integration bus overviewThe integration bus synchronizes objects and pages with third party systems. It provides a safer and more reliable way than other solutions,because the synchronization tasks can be ordered in a queue and recovered if they fail. You can realize the synchronization in bothdirections:

Outgoing tasks – perform synchronization from Kentico to external applications.Incoming tasks – perform synchronization from external systems to Kentico.

Outgoing tasks - From Kentico to external applications

Outgoing synchronization tasks are based on .subscriptions

Subscriptions

Subscriptions keep track of operations performed in Kentico, such as creating, updating or deleting objects and pages. Developers need toprepare subscriptions for operations that should be synchronized to external systems. When an operation that has a subscription occurs, thesystem passes the request to a connector, which processes the synchronization in one of two modes (depends on the subscription settings):

Asynchronously – the synchronization task is placed into a queue, where it waits until the task's processing is started by a scheduledtask or by a user manually.Synchronously – the synchronization task is passed directly to the connector.

Integration bus overview - learn about the options the integration bus offers.

Managing integration tasks - see how to manage the synchronization tasks used by the integration bus.

Example - Integration connector - inspect a sample integration connector.

Reference - Integration bus data types - refer to this page whenever you need more information about the classes, interfaces andenumerations related to the integration bus.

Integration bus database model - a reference page about the integration bus data model.

1. 2. 3. 4.

Enable the integration bus featuresCreate integration connectorsImplement outgoing synchronizationImplement incoming synchronization

Page 32: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

Data types for subscriptions

Subscriptions use one of three data types to specify which data is transferred:

Simple - this type synchronizes the content of objects.SimpleSnapshot - this type synchronizes whole objects and preserves foreign key bindings. This applies only when the 3rd partysystem has an architecture and database design similar to Kentico.Snapshot - synchronizes multiple objects at once. For example a main object with its children, such as polls together with pollanswers. Not supported for pages.

For details, refer to the enumeration.TaskDataTypeEnum

 

Asynchronous processing

With asynchronous processing of tasks, the data of the changed object or page is first stored in the database (the task is logged in the taskqueue). If the external system is not available, the tasks wait ordered in the queue until they can be reliably processed.

The of asynchronous processing: advantages

Synchronization data is not lost even if the processing of tasks fails.Asynchronous processing is highly scalable, all timeconsuming operations are performed one by one.Allows translation of column values using the method.TranslateColumnsToExternal()

The of asynchronous processing: disadvantages

No context is available during the object/page processing.

Otherwise, asynchronous processing does not have any major disadvantages, and can be used for most scenarios.

To ensure maximum performance, the system postpones the logging and processing of tasks until the event.EndRequest

Page 33: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

When the processing thread starts, the connector begins by fetching the first task in the queue (FIFO principle). Fetched tasks aretransformed to strongly typed objects and passed to the methods implemented in the connector class. In some cases, additional methods arecalled, for example when performing translation of foreign keys. When the task is processed, the result value (of type IntegrationProcessRes

) is returned to notify the connector. Depending on the result, the connector decides what to do next.ultEnum

Note: Processing doesn’t start on when the object or page has been changed in an asynchronous thread (forEndRequestexample when importing new sites with the option enabled).Log integration tasks

Page 34: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

Synchronous processing

When using synchronous processing, the changed object is passed directly to the connector for further processing.

The of synchronous processing include:advantages

You can manipulate objects within the context of Kentico — you can access properties like or of the currentlyParent Childrenprocessed object, and the data are fetched from the database just in time.With pages, you can access properties like , and .Tags Categories Attachments

The of synchronous processing include:disadvantages

The system does not store the synchronization data in the database — if an error occurs and the connector fails to process therequest, the data are lost.Synchronous processing of large or numerous tasks may slow down the application.No method.TransalteConlumnsToExternal()

It is recommended to use synchronous processing only if you need to leverage the advantages.

Note: The is already implemented. You only need to prepare the parts of the code shown in theBaseIntegrationConnectorinherited connector class ( in the figure above).CustomIntegrationConnector

Page 35: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

Processing of synchronous tasks starts immediately after an object or page matching a subscription is changed. Unlike asynchronousprocessing, where the logging and processing is postponed until the application reaches , synchronous processing sends theEndRequestdata instantly to the subscribed connectors.

Incoming tasks - From external applications to Kentico

The inbound direction allows you to transfer changes from external applications to Kentico by sending data to the Integration bus. Thesystem stores the data in a queue, later takes them from the queue, and processes them on a regular basis or on your request. Processingof incoming tasks is .always asynchronous

Your task as a developer is to implement methods that help the system log the correct data into the queue. You need to convert the externalobject to a corresponding internal object or page, and supply translation information if you want to preserve foreign key bindings:

Page 36: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

There are two ways to implement the synchronization connectors:

External connectorInternal connector

External connector

The connector is placed within the 3rd party system and references Kentico DLLs. The Kentico database is accessible from the externalsystem. The advantage is that even if the Kentico instance is not accessible for some reason, the synchronization data (integration tasks) arelogged to the queue and can be reliably processed later without loss of data.

Internal connector

The connector is located within the Kentico instance. The communication is ensured by a service (web or WCF). The advantage is that thereis no need to reference Kentico DLLs. On the other hand, you have to put extra effort into the implementation of the communication service.

Page 37: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

 

Enabling the integration busTo enable the , open the application in the Kentico administration interface and adjust the settings in the Integration bus Settings Integration

category.-> Integration bus

Setting Description

Enable system integration bus Allows logging and processing of incoming and outgoingintegration tasks.

Integration tasks represent individual synchronization operationsfor objects or pages (create, update, delete etc.). Thesynchronization process consists of two steps:

Logging - creation of integration tasks for actions that requiresynchronization.Processing - execution of the integration tasks.

You can enable or disable logging/processing of incoming/outgoingtasks separately through the other settings in the category.

Enable logging of incoming tasks Indicates if the integration bus logs integration tasks received fromexternal systems. To log tasks, the Enable system integration

setting must also be enabled.bus

Enable processing of incoming tasks Check to allow processing of integration tasks incoming fromexternal systems. To process tasks, the Enable system

setting must also be enabled.integration bus

Enable logging of outgoing tasks Indicates if the integration bus logs changes made to pages andobjects in Kentico as outgoing integration tasks. To log tasks, the E

setting must also be enabled.nable system integration bus

Enable processing of outgoing tasks Check to allow processing of outgoing integration tasks. Toprocess tasks, the setting mustEnable system integration busalso be enabled.

All sites in the system share the same settings for the integration bus. You need to select the option in the selector to(global) Siteconfigure the settings.

Page 38: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1. 2. 3. 4.

5.

6.

 

Creating integration connectorsYou can add integration connector classes into your application in two ways:

In the App_Code directoryIn a separate project or assembly

Creating connectors in the App_Code folder

Open your Kentico web project in Visual Studio.Create a new class in the folder (or if you installed Kentico as a web application project).App_Code Old_App_CodeSet the class to inherit from BaseIntegrationConnector.Override the method and set the property within this method.Init() ConnectorName

The value of the property must match the code name of the connector object registered in theConnectorNameadministration interface.

using CMS.Synchronization;using CMS.SynchronizationEngine;

public class CMSIntegrationConnector : BaseIntegrationConnector{ /// <summary> /// Initializes the connector name. /// </summary> public override void Init() { // Initializes the connector name (must match the code name of theconnector object in the system) // GetType().Name uses the name of the class as the ConnectorName ConnectorName = GetType().Name; }}

Ensure that the system loads the appropriate class when working with the connector using the assemblyRegisterCustomClassattribute. See for more information.Loading custom classes from App_Code

using CMS;

[assembly: RegisterCustomClass("CMSIntegrationConnector",typeof(CMSIntegrationConnector))]

On web application projects, build the solution.

Page 39: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1. 2.

3. a. b. c.

4. 5. 6.

1. 2. 3. 4.

5.

With the connector class prepared, you now need to:

Implement and/or synchronizationoutgoing incomingRegister the connector in the system

You can find an example of a basic connector class on the page.Example - Integration connector 

Creating connectors in a separate project or assembly

Open your Kentico web project in Visual Studio (using the or file).WebSite.sln WebApp.slnAdd a new project to the solution (name it e.g. ).Class Library CustomIntegrationConnector

This ensures that the connector has its own DLL assembly.Add references to the project:

Right-click the project and select Add reference...Click Browse...Add at least the following references from the project's directory:Lib

CMS.SynchronizationCMS.SynchronizationEngineCMS.DocumentEngineCMS.HelpersCMS.DataEngineCMS.SiteProviderCMS.WorkflowEngineCMS.Base

Edit and rename the default class in the project and set the class to inherit from BaseIntegrationConnector.Override the method and set the property within this method.Init() ConnectorNameBuild the solution.

With the connector class prepared, you now need to:

Implement and/or synchronizationoutgoing incomingRegister the connector in the system

Registering connectors in the system

Once the connector's class is ready, you need to register the connector as an object in the system:

In the Kentico administration interface, open the application.Integration busSelect the tab.ConnectorsClick .New connectorFill in the , and and select the check box.Display name Assembly name Class Enabled

Property Description

Display name The name of the connector displayed in the user interface.

Code name Sets a unique identifier for the connector. Must match thevalue of the property declared in theConnectorNameconnector's class.

Provider class_____________

Specifies the class where the connector class is implemented:

Assembly name - the assembly (project) containing theconnector class. Select for connectors(custom classes)implemented in the App_Code (or Old_App_Code) folder.Class - the exact class (including any namespaces) thatdefines the functionality of the connector. For App_Codeclasses, the value must match the first parameter of the R

attribute that loads the class.egisterCustomClass

Enabled Indicates if the connector logs and processes integration tasks.Logging and processing of tasks must also be in enabled Setti

.ngs -> Integration -> Integration bus

Click .Save

The system displays a warning icon ( ) next to connectors that are not registered correctly. The most common causes of problems are:

The value of the property in the connector class's method does not match the .ConnectorName Init Code nameIncorrect assembly or class name.App_Code classes are not loaded correctly. See for more information.Loading custom classes from App_Code

Note: When you add, edit or delete a connector, the system re-initializes all defined connectors.

Page 40: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1.

2.

3.

 

Implementing outgoing synchronizationTo synchronize data from Kentico to external applications, you need to decide:

which and you want to synchronizeobjects pages which you want to usedata typewhether you want to use or processing of integration taskssynchronous asynchronous whether you want to handle of foreign key bindingstranslations

Use this information to implement the outgoing synchronization in your :connector class

Prepare subscriptions for the Kentico objects that you want to synchronize:Use predefined subscription methods - allows you to easily subscribe to objects or pagesORBuild subscription objects - allows you to select exactly which objects are synchronized

Implement the method that converts objects or pages to the objects used by the external application.

(Optional) Implement :translation of foreign key bindingsGetExternalObjectID method - if the synchronized objects or pages have bindings to objects inheriting from BaseInfoGetExternalDocumentID method - if the synchronized objects or pages have bindings to pages ( )TreeNode

 

Creating subscriptions

Subscriptions keep track of actions that occur in Kentico, such as creating, updating or deleting objects and pages. Use subscriptions todetermine the scope of the changes that the connector synchronizes.

You need to implement subscriptions inside the method of your :Init() connector class

using CMS.SynchronizationEngine;using CMS.Synchronization;using CMS.DataEngine;

public class CMSIntegrationConnector : BaseIntegrationConnector{ public override void Init() { // Initializes the connector name ConnectorName = GetType().Name;

// Register your subscriptions here }}

Using predefined subscription methods

You can subscribe to pages or objects by calling the following methods:

SubscribeToAllDocumentsSubscribeToDocumentsSubscribeToAllObjectsSubscribeToObjects

See for information about the method parameters.Reference - Integration bus data types

Examples:

// Subscribes to all types of changes made to user objectsSubscribeToObjects(TaskProcessTypeEnum.AsyncSnapshot, UserInfo.OBJECT_TYPE);

You can if you need to define custom options for the subscription scope.create your own subscription class

Page 41: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1. 2.

// Subscribes to all types of changes made to all pages on all sitesSubscribeToAllDocuments(TaskProcessTypeEnum.AsyncSimpleSnapshot, TaskTypeEnum.All);

Building subscription objects

You can select exactly which objects are synchronized using subscription objects:

Create a new object of a subscription class.Call the method for the object.SubscribeTo

Subscription classes inherit from , and you can use the following predefined options:AbstractIntegrationSubscription

BaseIntegrationSubscriptionObjectIntegrationSubscriptionDocumentIntegrationSubscription

The subscription classes provide the following :filtering options

BaseIntegrationSubscription

ConnectorName - string; assigns the subscription to a connector. Use the property to enter the name of the currentConnectorNameconnector.TaskProcessType - enumeration; specifies the synchronization mode and data type. See for details.TaskProcessTypeEnumTaskType - enumeration; determines the type of the synchronized action (create, update, delete, etc.). See forTaskTypeEnumdetails.SiteName - string; determines the code name of the site where the objects or pages belong. You can use AbstractIntegrationSubscri

to subscribe only to global objects.ption.GLOBAL_OBJECTS

ObjectIntegrationSubscription

ObjectType - string; determines the type (class) of the synchronized object. You can either use the object type code name directly(for example ) or system constants ( ).cms.user UserInfo.OBJECT_TYPEObjectCodeName - string; determines the code name of one specific object, for example: administrator

DocumentIntegrationSubscription

DocumentNodeAliasPath - string; determines the alias path of the synchronized pages, for example: /Products/%DocumentCultureCode - string; determines the culture of the synchronized pages, for example: en-USDocumentClassName - string; determines the of the synchronized pages, for example: page type CMS.MenuItem

If you do not want to limit the synchronization scope through one of the properties, set the given value to in the subscription object'snullconstructor. For the enumeration, set the value.TaskType All

Examples:

Wildcard character %

You can use the percent character (%) as a wildcard representing any number of characters in the string parameter values.

For example, if you specify the as "en-%", the subscription covers all English cultures: , , etc.DocumentCultureCode en-US en-GB

Page 42: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1. 2. 3.

// Subscription that synchronizes the creation of object types starting with'poll.poll' - polls and poll answersObjectIntegrationSubscription objSub = newObjectIntegrationSubscription(ConnectorName, TaskProcessTypeEnum.AsyncSnapshot,TaskTypeEnum.CreateObject, "PersonalSite", "poll.poll%", null);SubscribeTo(objSub);

// Subscription that synchronizes all changes made to pages on 'NewSite', locatedunder the /Home/ path in the content treeDocumentIntegrationSubscription pageSub = newDocumentIntegrationSubscription(ConnectorName,TaskProcessTypeEnum.AsyncSimpleSnapshot, TaskTypeEnum.All, "NewSite", "/Home/%",null, null);SubscribeTo(pageSub);

// Subscribes to all changes made to the SETTINGS of a specific custom table, where'customtable.SampleTable' is the table's code nameObjectIntegrationSubscription customTableSub = newObjectIntegrationSubscription(ConnectorName,TaskProcessTypeEnum.AsyncSimpleSnapshot, TaskTypeEnum.All, null, null,"customtable.SampleTable");SubscribeTo(customTableSub);

// Subscribes to all changes made to the DATA of the 'customtable.SampleTable'custom tableObjectIntegrationSubscription customTableDataSub = newObjectIntegrationSubscription(ConnectorName,TaskProcessTypeEnum.AsyncSimpleSnapshot, TaskTypeEnum.All, null,CustomTableItemProvider.GetObjectType("customtable.SampleTable"), null);SubscribeTo(customTableDataSub);

Creating a custom subscription class

If you need to extend the filtering options of a connector's subscriptions, you can create your own subscription class:

Create a new class inheriting from one of the existing .subscription classesDefine the required properties and constructor for the class.Override the method:IsMatch()

public override bool IsMatch(ICMSObject obj, TaskTypeEnum taskType, refTaskProcessTypeEnum taskProcessType){ // Evaluate whether the subscription's properties match the properties of the'obj' parameter (TreeNode page or BaseInfo object) and the value of 'taskType' // Return a boolean value that indicates when objects match the subscriptionrequirements}

You can then use the custom subscription class to .build subscription objects

Implementing outgoing synchronization

To synchronize the objects covered by your to external applications, you need to override methods inside your :subscriptions connector class

ProcessInternalTaskAsync for  of integration tasksasynchronous processingProcessInternalTaskSync for synchronous processing

Asynchronous processing

Page 43: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

In all cases, the purpose of the method is to transform the or internal object into a corresponding object in theGeneralizedInfo TreeNodethird party system, and perform the action specified by . You also have to take the into account. WhenTaskTypeEnum TaskDataTypeEnumyou are done with the processing, set the error message and return an value.IntegrationProcessResultEnum

For example:

The  method ensures asynchronous processing of (users, roles, forums, etc.) or (contentProcessInternalTaskAsync objects pages tree nodes):

public override IntegrationProcessResultEnumProcessInternalTaskAsync(GeneralizedInfo infoObj, TranslationHelpertranslations, TaskTypeEnum taskType, TaskDataTypeEnum dataType, string siteName,out string errorMessage)

public override IntegrationProcessResultEnum ProcessInternalTaskAsync(TreeNodenode, TranslationHelper translations, TaskTypeEnum taskType, TaskDataTypeEnumdataType, string siteName, out string errorMessage)

Objects

Documents

Synchronous processing

The  method ensures synchronous processing of (users, roles, forums, etc.) or (content treeProcessInternalTaskSync objects pages nodes):

public override IntegrationProcessResultEnumProcessInternalTaskSync(GeneralizedInfo infoObj, TaskTypeEnum taskType, stringsiteName, out string errorMessage)

public override IntegrationProcessResultEnum ProcessInternalTaskSync(TreeNodenode, TaskTypeEnum taskType, string siteName, out string errorMessage)

Objects

Documents

Page 44: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1. 2. 3. 4.

public override IntegrationProcessResultEnum ProcessInternalTaskAsync(TreeNodenode, TranslationHelper translations, TaskTypeEnum taskType, TaskDataTypeEnumdataType, string siteName, out string errorMessage){

// Convert the TreeNode to an external page object

// Optional: Translate foreign key values

// Send the data to the target application  // Method result for successful processing errorMessage = null; return IntegrationProcessResultEnum.OK;}

The synchronous and asynchronous versions of the methods work in the same way. The only difference is that you cannot use the Translate method to inside the method. If you wish to translate foreign keysColumnsToExternal translate foreign key values ProcessInternalTaskSync

with synchronous processing, you need to manually .write the translation code

Sending data to the target application

Once you have converted the object or page to an external equivalent, there are several ways to synchronize the data with the target system:

Call the API of the external system (you need to add references to the required namespaces).Use and and perform a query against the external database.CMSConnectionScope GeneralConnectionPush the data to an external endpoint in a format that the target system can process. For example, the endpoint can be representedby a web service in the external system.

You can use any other approach, but you always need to be able to determine whether the processing succeeded on the external side. Boththe and methods must return the .ProcessInternalTaskAsync ProcessInternalTaskSync result status

Translating foreign keys to match external objects

The values of identifier columns may not always be the same for equivalent objects in Kentico and external systems. For usingsubscriptionsthe or and asynchronous processing, you can ensure consistency by translating the columns that storeSimpleSnapshot Snapshot data typeforeign key bindings to related objects.

To perform the translation, call inside your connector's method. TheTranslateColumnsToExternal ProcessInternalTaskAsyncTranslateColumnsToExternal method is inherited from and accepts the following parameters:BaseIntegrationConnector

TranslateColumnsToExternal(GeneralizedInfo infoObj, TranslationHelper translations,bool processChildren)

TranslateColumnsToExternal(TreeNode node, TranslationHelper translations, boolprocessChildren)

The last parameter determines whether to translate foreign keys of child objects. For the data type, always pass . TheSimpleSnapshot falseprocessChildren parameter is useful when using the data type, for example when you are processing an object that does not existSnapshotin the target system yet, and you do no have enough transformation to translate the foreign keys of child objects before you process the mainobject. We recommend using the following translation order:

Call .TranslateColumnsToExternal(infoObj, translations, )falseProcess the main object (send the data to the target system).Call .TranslateColumnsToExternal(infoObj, translations, )trueIterate through the collection of and process each object.Children infoObj

To ensure correct translation functionality, you need to override one or both of the following methods inside your :connector class

Objects

Documents

Page 45: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

GetExternalObjectID - implement if the synchronized objects or pages have bindings to objects inheriting from BaseInfoGetExternalDocumentID - implement if the synchronized objects or pages have bindings to pages ( )TreeNode

GetExternalObjectID method

Override the GetExternalObjectID method inside your connector class if you call for objects or pages that haveTranslateColumnsToExternalreferences to other objects inheriting from .BaseInfo

public override int GetExternalObjectID(string objectType, string codeName, stringsiteName, string parentType, int parentId, int groupId)

Parameters:

objectType - identifies the type of the synchronized internal object (class). For example, can match external objects suchcms.useras "person" or "member".codename - the unique identifier of the synchronized object.

siteName - the code name of the site where the object belongs (only for site-related objects).parentType - the type of the object's parent (if the object has a parent).parentId - the ID of the object's parent.groupId - the identifier of the object's group (if the object belongs to a group).

Use the parameters to find the corresponding object in the external system and (integer value).return the given object's identifier

GetExternalDocumentID method

Override the GetExternalDocumentID method inside your connector class if you call for objects or pages thatTranslateColumnsToExternalhave references to other pages ( ).TreeNode

public override int GetExternalDocumentID(Guid nodeGuid, string cultureCode, stringsiteName, bool returnDocumentId)

Parameters:

Page 46: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1. 2.

3.

nodeGuid - the page's identifier.GUIDcultureCode - the culture code of the page's language (for example ).en-USsiteName - the code name of the site where the page belongs.returnDocumentId - indicates which identifier you need to provide as the method's return value. If true, return the ,DocumentIDotherwise return the . The is an identifier of a tree node including all , while is uniqueNodeID NodeID language versions DocumentIDfor each language version.

  Identifier Alternative identification

Shared page data NodeID nodeGuid & siteName

Culture version of a page DocumentID nodeGuide & siteName & cultureCode

Use the parameters to find the corresponding page in the external system and (integer value).return the given page's identifier

Translating foreign keys in synchronous mode

If you need to translate ID column values to match external objects, we recommend using asynchronous processing. In synchronous mode,the only way to translate columns is to write custom code inside the method.ProcessInternalTaskSync

The following sample code indicates how to translate the identifier of a page's parent:

using CMS.DocumentEngine;using CMS.Membership;

public override IntegrationProcessResultEnum ProcessInternalTaskSync(TreeNode node,TaskTypeEnum taskType, string siteName, out string errorMessage){ ...

// Gets the Kentico parent node of the synchronized page TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser); TreeNode parentNode = DocumentHelper.GetDocument(node.NodeParentID, tree);

// Gets the properties of the parent node Guid parentGuid = parentNode.NodeGUID; string parentSiteName = parentNode.NodeSiteName;

int newParentId = 0;

// External code that finds the matching external page according to the parentNodeproperties, and fills the newParentID

// Assigns the new parent ID to the synchronized page node.NodeParentID = newParentId;

...

}

 

Implementing incoming synchronizationTo synchronize data from external applications to Kentico, you need to decide:

which and you want to synchronizeobjects pages which you want to usedata type

Based on this information, choose which methods to implement in your . Proceed with calling and implementing methodsconnector classaccording to the following list:

Call the method in your external application — it logs incoming tasks to the task queue.ProcessExternalTask Implement the method - handles transformations of objects and pages from the external application toPrepareInternalObject Kentico.Implement one or both of these methods:

GetInteralObjectParams - implement this method if you plan to synchronize objects or pages which have foreign keys refere

To learn how Kentico stores pages in the database, refer to .Page database structure

Page 47: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

3.

4.

.ncing objectsGetInternalDocumentParams - implement this method if you plan to synchronize objects or pages which have foreign keys r

.eferencing pages

(Optional) Call the method to remotely trigger processing of logged incoming tasks.RequestTasksProcessing  

Processing incoming tasks

ProcessExternalTask method

This method logs object or page tasks into the task queue. The system then takes the tasks out of the queue and processes them later. Themethod is located in the class:IntegrationHelper

void ProcessExternalTask(string connectorName, object obj,IntegrationProcessTypeEnum result, TaskTypeEnum taskType, TaskDataTypeEnumdataType, string siteName)

It has the following parameters:

connectorName - the code name of the connector which should process the tasks.obj - the external object which should be processed. If you have managed to prepare earlier, you can pass it as well.ICMSObjectresult - this value indicates how the system behaves when fetching the tasks from the database and how it reacts when an erroroccurs.taskType - by providing this value, you say whether the provided object or page should be created, updated, deleted, etc.dataType - indicates, whether the provided object contains child objects. The value also indicates whether the methods for collectingtranslation information will be called.siteName - if the processed object belongs to a site, provide a code name of this site.

You can find detailed descriptions of particular enumerations used in the parameters in .Enumerations

Use a reference to the namespace and call this method anywhere in the code of your external application.CMS.Synchronization

Implementing the incoming synchronization

Page 48: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

PrepareInternalObject method

Implement the  method in your connector class. This method transforms objects from the external application into thePrepareInternalObjectcorresponding objects or pages in Kentico. The method must return a valid page or object inheriting from (UserInfo,TreeNode BaseInfoRoleInfo, ForumPostInfo etc.).

public override ICMSObject PrepareInternalObject(object obj, TaskTypeEnum taskType,TaskDataTypeEnum dataType, string siteName){ ... return UserInfo;}

 

GetInternalObjectParams method

Implement the method if you need to synchronize objects that have foreign key bindings with other objects inGetInternalObjectParams Kentico. Based on the and parameters, you should be able to find the corresponding object in the external application, andid objectTypethen set the method's parameters. At the very least you need to supply the object's code name ( parameter). The  , out codeName siteName p

and parameters allow you to specify the object with more precision. The system then finds the related object in the KenticoarentId groupIddatabase according to the parameters, and translates the foreign key values.out

public override void GetInternalObjectParams(int id, string objectType, out stringcodeName, out string siteName, ref int parentId, ref int groupId)

GetInternalDocumentParams method

Implement the method if you need to synchronize objects that have foreign key bindings to pages in Kentico.GetInternalDocumentParamsBased on the  and parameters, you should be able to find the corresponding page in the external application, and then specifyid classNamethe page's , and through the method's parameters.  All of the parameters are mandatory. The systemnodeGuid cultureCode siteName outthen finds the related page in the Kentico database, and translates the foreign key values.

Page 49: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1. 2.

3.

1. 2. 3.

4. 5. 6.

public override void GetInternalDocumentParams(int id, string className, out GuidnodeGuid, out string cultureCode, out string siteName)

Requesting the processing of logged tasks

The offers two overloads of the method: BaseIntegrationConnector RequestTasksProcessing

HttpStatusCode RequestTasksProcessing(string serverUrl)HttpStatusCode RequestTasksProcessing(string serverUrl, string connectorName)

Call this method in your connector class. When this method is called, the application makes a HTTP request to the ~/CMSPages/Integration page, which starts the processing of incoming tasks logged in the Kentico project. Each connector will be processed in its ownNotify.aspx

thread.

As a parameter of this method, specify a URL leading to the root of the Kentico application (e.g. ). Thehttp://www.example.com/Kenticosecond overload allows you to also specify the connector whose tasks will be processed (usually the external connector). If you do not supplythe parameter, all connectors will be processed. 

Managing integration tasksThe integration bus allows you to monitor which synchronization tasks are waiting to be processed, and view tasks that failed while beingprocessed.

Open the application and select the or tabs.Integration bus Outgoing tasks Incoming tasks

Manually executing failed tasks

To manually execute synchronization tasks, which were not processed:

Open the application.Integration busChoose the or tab.Outgoing tasks Incoming tasks

Click ( ).Synchronize

The system executes the task immediately. 

Executing incoming tasks on a regular basis

Open the application.Scheduled tasksIn the selector, choose the option.Site (global)Find the scheduled task called . Process external integration tasks

This task processes incoming synchronization tasks.By default, the task is set to run once a day.

Edit ( ) the task.Set the task's scheduling options (Period, Start time, Every, Between, Days) according to the requirements of your integration.Click .Save

The system will now execute incoming tasks based on the specified task interval.

Check whether the and settings in Enable processing of incoming tasks Enable processing of outgoing tasks Settings ->

are enabled. Otherwise, the ( ) action is not available.Integration -> Integration bus Synchronize

Currently we do NOT provide a scheduled task for processing outgoing synchronization tasks.

Page 50: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1. 2. 3.

Automatically executing tasks using event handlers

You can leverage the API and to automatically synchronize integration tasks according to custom requirements.event handlers

To learn more, see .Automatically synchronizing staging and integration tasks

Viewing integration task details

Click ( ) next to integration tasks (both incoming and outgoing) to inspect the object or page data transferred within the task.View

 

Example - Integration connectorThe default installation of Kentico provides a sample integration connector. The connector implements two subscriptions for outgoing

:tasks

Synchronization of user objectsSynchronization of all pages on all websites in the system

The connector's purpose is purely demonstrative — it only logs events in the application for each creation, modification or deletion Event logof a user or page.

Adding the sample connector to your web project

Open your Kentico installation directory (by default ).C:\Program Files\Kentico\<version>Expand the sub-directory.CodeSamples\App_Code Samples\Copy the folder into the folder of your web project.Samples CMS\App_Code

 

Viewing the connector code

To see how the sample connector is implemented:

1. 2. 3.

Information for web application projects

If your Kentico project was installed as a web application, copy the samples into the folder instead.Old_App_Code

You must also manually include the sample class files into the project:

Open your application in Visual Studio.Click at the top of the Solution Explorer.Show all filesExpand the folder, right-click the new sub-folder and select .Old_App_Code Samples Include in Project

Page 51: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1. 2.

1. 2. 3. 4. 5.

Open your web project in Visual Studio.Expand the folder and edit the class.~/App_Code/Samples/Classes SampleIntegrationConnector.cs

public class SampleIntegrationConnector : BaseIntegrationConnector{ #region "Initialization (subscribing)"

/// <summary> /// Initializes the connector name and registers subscriptions. /// </summary> public override void Init() { // Initializes the connector name (must match the code name of the connectorobject in the system) ConnectorName = GetType().Name;

// Creates subscription for all user objects (predefined method) SubscribeToObjects(TaskProcessTypeEnum.AsyncSnapshot, UserInfo.OBJECT_TYPE);

// Create subscription for all pages on all sites (predefined method) SubscribeToAllDocuments(TaskProcessTypeEnum.AsyncSimpleSnapshot,TaskTypeEnum.All);

// Demonstrates how to create subscriptions manually // ObjectIntegrationSubscription objSubscription = newObjectIntegrationSubscription(ConnectorName, TaskProcessTypeEnum.AsyncSnapshot,TaskTypeEnum.All, null, PredefinedObjectType.USER, null); // SubscribeTo(objSubscription);

// DocumentIntegrationSubscription pageSubscription = newDocumentIntegrationSubscription(ConnectorName,TaskProcessTypeEnum.AsyncSimpleSnapshot, TaskTypeEnum.All, null, null, null, null); // SubscribeTo(pageSubscription); }

...

The sample connector is defined in the App_Code folder, so the file contains code that allows the system to load the class when working withthe connector — the assembly attribute declared above the class. See RegisterCustomClass SampleIntegrationConnector Loading custom

for more information.classes from App_Code

[assembly: RegisterCustomClass("SampleIntegrationConnector",typeof(SampleIntegrationConnector))]

The attribute accepts two parameters:RegisterCustomClass

The first parameter is a string identifier representing the name of the connector class. The name must match the value of the Class field specified for the given connector object in the system ( in this example).name SampleIntegrationConnector

The second parameter specifies the type of the class as a object.System.Type

Registering the connector

Log in to the Kentico administration interface.Open the application.Integration busSelect the tab.ConnectorsClick .New connectorFill in the following properties:

Display name: Sample integration connectorProvider class - Assembly name: (custom classes)

To be functional, every connector must have the property initialized in the method. The value must matchConnectorName Init()the code name of the connector object registered in the system. The sample connector uses the name of the ConnectorName – Sa

.mpleIntegrationConnector

Page 52: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

5.

6.

1. 2. 3.

4. 5. 6.

7.

8. 9.

a. b. c.

Provider class - Class: SampleIntegrationConnectorEnabled: Yes (checked)

Click .Save

Testing the connector

Open the application.SettingsSelect the category.Integration -> Integration busAdjust the as follows:settings

Enable system integration bus: yes (checked)Enable logging of incoming tasks: no (unchecked)Enable processing of incoming tasks: noEnable logging of outgoing tasks: yesEnable processing of outgoing tasks: no

Click .SaveTry creating and modifying some pages and .user accountsOpen the application. On the tab, you can see a list of tasks logged for your actions. The Integration bus Outgoing tasks Synchro

( ) action is grayed out, since processing of tasks is disabled in the system settings.nize

Go back to , check and click .Settings -> Integration -> Integration bus Enable processing of outgoing tasks Save

Return to . The ( ) action is now enabled.Integration bus -> Outgoing tasks SynchronizeTo execute all tasks:

Select in the first selector below the list.All tasksChoose the action.SynchronizeClick .OK

You can see the events logged by the integration tasks in the application.Event log

 

Reference - Integration bus data typesThis page describes the data types that you can work with when implementing integration connectors.

Classes

The sample connector only generates outgoing tasks, so you can leave handling of incoming tasks disabled. Disablingprocessing of outgoing tasks allows you to see the integration tasks in the user interface. If you enable processing, thesystem executes the tasks immediately and you only see the results in the .event log

Page 53: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

BaseInfo

Represents any siterelated or global data object in Kentico (for example a page template or a poll).

TreeNode

Represents a page in the content tree of a website.

Interfaces

ICMSObject

An interface implemented by both and objects. Allows you to identify Kentico data types.BaseInfo TreeNode

Enumerations

TaskTypeEnum

Namespace: CMS.DataEngine

Always accompanies processed objects and pages. The value has a slightly different meaning for outgoing and incoming tasks:

for outgoing tasks - used when creating subscriptions and determines which actions are handled as integration tasks. For example,when you subscribe to , the integration bus logs synchronization tasks when objects inheriting from areCreateObject BaseInfocreated.for incoming task - determines what happens to the target object when processing tasks. For example, when you pass a page objectand task type , the integration bus deletes the page.DeleteDocument

The most common values for are:objects

CreateObjectUpdateObjectDeleteObjectAddToSite (not applicable for global objects)RemoveFromSite (not applicable for global objects)All - only makes sense for the outbound direction (for subscriptions). Indicates that the integration bus creates tasks for all types ofobject operations and changes.

The most common values for are:pages

CreateDocumentUpdateDocumentDeleteDocumentPublishDocumentArchiveDocumentAll - only makes sense for the outbound direction (for subscriptions). Indicates that the integration bus creates tasks for all types ofpage operations and changes.

To see the whole list of values, explore the enumeration in Visual Studio.

 

TaskDataTypeEnum

Namespace: CMS.Synchronization

This enumeration determines the types of data which can be synchronized in the synchronization tasks:

Simple - this option synchronizes only the main object.SimpleSnapshot - synchronizes the main object along with the translation information.Snapshot - synchronizes the main object with its child objects and bindings.

Translation information enables translation of foreign keys between Kentico and external systems. When using synchronous processing, therequired data can be obtained directly within the context of the application.

Possible values and the data which they can synchronize:

Value Object data Page data Translation data (onlyfor asynchronous

processing)

Include child objects,bindings, categories,

etc.

Simple

Note: There is no task type that indicates transitions of pages between workflow steps (except for the and PublishDocument Archiv types).eDocument

Page 54: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

SimpleSnapshot

Snapshot

Note: Simple and SimpleSnapshot options do not support synchronous processing.

TaskProcessTypeEnum

Namespace: CMS.Synchronization

Values of this enumeration represent all supported combinations of synchronization modes and data types. When the system searches forconnectors with a subscription that matches an operation, and one connector has multiple subscriptions, the system selects the firstsubscription according to the following priority (highest to lowest):

SyncSnapshotAsyncSnapshotAsyncSimpleSnapshotAsyncSimple

There is only one synchronous option – SyncSnapshot. This is given by the nature of synchronous processing, where you can always accessrelated objects (parent, children, etc.) using the API.

IntegrationProcessResultEnum

Namespace: CMS.Synchronization

This enumeration stores possible results of outgoing tasks after being processed by external applications. The result determines whathappens after the processing of each task. Possible values are:

Value Meaning Asynchronous processingresult

Synchronous processingresult

OK Processing succeeded The system deletes the task (orthe relation between the taskand connector). Processingcontinues with the next task inthe queue.

Processing continues with thenext task in the queue.

Error Critical error occurred The system logs the error intothe synchronization log.Processing stops for the currentconnector.

The system logs the error intothe event log. Task data arelost. Processing stops for allconnectors.

ErrorAndSkip Noncritical error occurred The system logs the error intothe synchronization log.Processing continues.

The system logs the error intothe event log. Task data arelost. Processing stops for thecurrent connector.

SkipNow Process the task during nextiteration

Processing continues with thenext task in the queue.

Task data are lost.

IntegrationProcessTypeEnum

Namespace: CMS.Synchronization

Values of this enumeration are used during the processing of incoming tasks. The value determines whether to process the task immediatelyand how to proceed when an error occurs.

Value Meaning

Default Processes the task immediately. If an error occurs, the processingstops and the type is set to .Error

SkipOnce Does not process the task during the first processing (just sets thetype to , so it is processed during the next processing).Default

SkipOnError Processes the task immediately. If an error occurs, the task isskipped and the processing continues.

DeleteOnError Processes the task immediately. If an error occurs, the task isdeleted and the processing continues.

Error Processing does not continue after encountering a critical error.

 

Integration bus database model

Page 55: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

Database table Description

Integration_Connector Stores the data of integration connectors registered in the system.Maps connectors to their assemblies and classes.

Integration_Task Stores the data of outgoing and incoming integration tasks.

Integration_Synchronization Stores relationships between integration tasks and connectors.

Incoming tasks always have one matching record.Outgoing tasks can have multiple records (if there are multipleconnectors with the same subscriptions).

Integration_SyncLog Stores logs of any errors that occur when processing integrationtasks.

 

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

Separate applications integrated with your main Kentico websiteCustom 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 file.web config

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

 <configuration> <connectionStrings>

...

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

</connectionStrings>

 

  

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

Page 56: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1. 2. 3. 4.

1. 2.

1.

2.

3.

4.

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:

Right-click your application's project root in the and select .Solution Explorer Add -> ReferenceOn the tab, click and navigate to the folder of the Kentico project.Browse Browse LibSelect dll files in the Lib folder and click .all AddClick .OK

You also need to make the folder from the directory of the Kentico project available for your application:CMSDependencies CMS

For applications, copy the CMSDependencies folder into your project root.WebFor or applications, copy the CMSDependencies folder into the output folder containing the executable file.Console Windows

Initializing the Kentico application

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

Edit your application's file (create the file if necessary).Global.asaxExecute the method in the  method:CMSApplication.Init Application_BeginRequest

CMS.DataEngine.CMSApplication.Init();

Enabling ASCX transformations in external applications

Adding the CMSTransformation class:

The partial class allows you to write your own methods for use in ASCX . The system checks theCMSTransformation transformationsCMSTransformation class for method definitions when loading transformations — an error may occur if the class is not present in yourproject.

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

Create a new class file in your project named .CMSTransformation.csIn web site projects, add the file into the folder.App_CodeIn web application projects, you can create the class in any location.

Add the following code into the class:

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

If you wish to use E-commerce or Message board transformation methods, copy the default content of the partCMSTransformationial class from the Kentico project:

~/App_Code/CMSModules/Ecommerce/CMSTransformation.cs~/App_Code/CMSModules/MessageBoards/CMSTransformation.cs

Execute the following code in the method in your application's file (create the file ifApplication_BeginRequest Global.asaxnecessary).

Page 57: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

4.

1. 2.

1. 2. 3.

4.

5.

void Application_Start(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 . If you cannot use the virtual path provider in yourtransformationsenvironment (e.g. when using precompiled applications), you need to:

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

See also: Deployment mode for virtual objects

Example - Displaying content from Kentico

Once you have completed the configuration described in the sections above, you can use the Kentico API and in your application. AControlstypical 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 ormodify records in the database.

The following example shows how to retrieve page content from the Kentico database and display it using a standard ASP.NET Repeatercontrol.

Create a new page (web form) in your external web project using Visual Studio.Add the standard ASP.NET control onto the page.RepeaterInsert the following item template markup into the control element:<asp:Repeater>

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

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

using System.Data;using CMS.DocumentEngine;

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

Page 58: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

5.

1. 2.

3.

protected void Page_Load(object sender, EventArgs e){ // Creates a data set containing all released news pages from theCorporate 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();}

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

Using Kentico controls

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

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

Create a new page (web form) in your application's project using Visual Studio.Add the control onto the page.CMSRepeater

You can either drag the control from the toolbox or manually register the assembly on the page and then useCMS.Controlsthe Visual Studio IntelliSense.

Set the following properties for the control:CMSRepeaterClassNames: cms.newsSiteName: CorporateSite (or any other site code name)TransformationName: cms.news.previewSelectedItemTransformationName: cms.news.default

Note

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

using CMS.Membership;

...

// Gets an Info object representing the administrator userUserInfo user = UserInfoProvider.GetUserInfo("administrator");

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

Page 59: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

3.

1.

2. 3. 4.

5.

<%@ 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 pages.

 

Handling page links in external applications:

The of Kentico pages are based on the structure of the content tree and the settings of individual pages. These URLs will notdefault URLswork correctly outside of the Kentico application. For example, the links in the news item headings in the example above lead to pages thatmost 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 controlrenders the links using the , which you can modify.cms.news.preview transformation

Log in to the Kentico administration interface and open the application.Page types

Edit ( ) the page type.NewsSelect the tab and edit the transformation.Transformations PreviewChange the transformation code that defines the link URL from:

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

to:

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

Click .Save

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

Kentico listing controls automatically process the URL parameter and insert its value into the property. In this case, the linkaliasPath PathURLs ensure that the CMSRepeater control only loads one specific news page. When the source data only contains one page, the controluses the transformation specified by the property ( in this case) to display the detailsSelectedItemTransformationName cms.news.defaultof the given page.

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

Implementing custom page 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.

Page 60: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1.

2. 3.

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

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

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

Open the markup of the page in Visual Studio and set the property of the CMSRepeater control to .DataBindByDefault falseIn the page's code behind, add the following code into the method:Page_Load

protected void Page_Load(object sender, EventArgs e){ // Checks whether the URL contains the 'customParameter' query stringparameter if (Request.QueryString["customParameter"] != null) { // Limits the path of the CMSRepeater to the page specified by the URLparameter CMSRepeater1.Path = Request.QueryString["customParameter"]; } else { // Loads pages 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 thedynamically set Path) CMSRepeater1.ReloadData(true);}

The page now uses the query string parameter to select specific news pages. The custom parameter works the same waycustomParameteras the default parameter.aliasPath 

Data.com integrationData.com integration can help keep your Kentico and up-to-date. allows you to access a communitymanagedcontacts accounts Data.combusiness directory that is updated on a daily basis. You can look up your current contacts and match them with Data.com contacts. In thesame way, you can look up the accounts that you have in Kentico and compare them with Data.com company profiles.

The system provides two ways of updating your on-line marketing data using Data.com:

Manually - users can look for matching contacts or company profiles directly in the contact or account editing interface.Automatically - you can set up processes that automatically update your contacts according to matchingmarketing automationData.com contacts. You only need to add the to your automation processes.Update from Data.com action step

By combining these two methods, you can ensure that your contact and account data is up-to-date and accurate.

a.

b.

a.

b. c.

Setting control properties dynamically

By default, Kentico listing controls load content during the stage of the . If you need toInit control life cycleprogrammatically assign control properties that affect the content, use one of the following approaches:

Set the property to in the control's markup.DelayedLoading trueThis moves the automatic data binding to the control's event.Load

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

OR

Set the property to in the control's markup.DataBindByDefault falseThis completely disables automatic data binding for the control.

Assign the required properties at any appropriate point in the page life cycle.Explicitly call the control's method.ReloadData(true)

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

Data.com authentication

Page 61: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1.

2. 3.

1. 2.

3. 4.

To contacts, go to one of the following locations in the user interface:search and compare

Open the application.Contact management

Edit ( ) a contact.Switch to the tab.Data.com

To compare accounts, navigate to one of the following locations:

Open the application.Contact management Switch to .Accounts

Edit ( ) an account.Switch to the tab.Data.com

Kentico requires a valid Data.com account to communicate with the Data.com service. The system requests Data.comauthentication credentials for:

Users - users need to enter the credentials of a Data.com account when accessing the Data.com interface for the firsttime. The system stores the credentials in the settings of the user account, so the duration of the Data.com authenticationis unlimited.Automation steps - each step in an automation process uses its own Data.com account. YouUpdate from Data.comcan fill in the credentials when creating or editing the steps.

Page 62: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

 

Mapping Data.com fieldsYou can configure how the matches data fields between:Data.com integration

Kentico and Data.com contactsAccounts and Data.com company profiles

To access the mapping settings, go to (application) .Settings -> Integration -> Data.com

Page 63: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1.

2. 3.

1. 2.

1. 2. 3. 4.

To modify the default field mappings, click at the bottom of the or sections.Edit Contact Company

Once you have configured the Data.com integration, you can for contacts or accounts.search 

Searching Data.com for contactsYou can look up your Kentico in the Data.com business directory and update their information.contacts

Open the application.Contact management

Edit ( ) a specific contact.Open the tab.Data.com

Entering the Data.com credentials

When opening the Data.com tab for the first time, you need to enter the credentials of a valid Data.com account. The system uses theaccount to communicate with the Data.com service.

Fill in the and .E-mail address PasswordClick .Login

The duration of the Data.com authentication is unlimited. The system stores the Data.com credentials in the settings of your user account(the password is encrypted). You can now access the tab without authenticating for both contacts and accounts.Data.com

If you need to change your Data.com account:

Open the tab (either in the contact or account interface).Data.comClick  .Log out from Data.comFill in the authentication form with the e-mail address and password of the new Data.com account.Click .Login

Searching for contacts

Once your user account has valid Data.com credentials, the tab automatically searches the Data.com directory for the contact youData.comare currently editing. The integration tool makes its best effort to find the correct contact or at least narrow the search down as much as

Page 64: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1. 2.

1.

possible, saving you time compared to doing a manual search.

There are several possible results of the search.

  

An exact match is found for the contact

When the system finds an exact match for the selected contact, a comparison page opens. You can view the data of the Kentico contactside-by-side with the information from the Data.com directory.

Updating contact information

To update the contact's data using the Data.com information:

Check the boxes next to the fields that you want to update.Click  .Apply

The updated data is immediately visible for your contact. You can also switch to the contact's tab to view the full information.General

Too many matches are found

If the contact's search criteria are too general, the query can yield more than one result in the Data.com directory. For example, if you searchfor a contact with a commonly used name.

In these cases, you need to manually find the matching contact.

Click  .Search

The Data.com search uses the following contact attributes:

First nameLast nameCompanyE-mail

Note: If you can't see the and values of the found contact, then your Data.com account doesn't own theBusiness phone E-mailgiven contact. You can to view the values.buy the contact

Page 65: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1.

2.

3.

4.

1.

(Optional) Revise the search criteria in the filter dialog and click .Search

Select ( ) the listed contacts to view their information.

Click once you have selected the correct contact.Save & Close

You can now update the contact's information.

No matches are found

If your contact does not exist in the Data.com directory, the search does not return any results. You can click , manually revise theSearchsearch criteria and attempt to find the contact yourself. 

Buying contacts from Data.comData.com integration allows you to buy contacts from Data.com. If you own a Data.com contact, you can access additional information — the

and fields.Business phone Email

Use the following steps to buy contacts while for contact information on the tab:searching Data.com

Click .Buy this contactA confirmation dialog opens.

The system always buys contacts using the Data.com account associated with your Kentico user account — identified by thecredentials that you entered when accessing the tab for the first time. See for moreData.com Searching Data.com for contactsinformation.

When you buy a contact, it becomes available for all users who share the same Data.com account.

Page 66: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1.

2.

a. b. c.

3.

1. 2.

3.

4. 5.

If you don't have enough points to the contact right away:Buy

Click . The Data.com website opens.Purchase pointsLog in using your Data.com credentials.Specify the amount of points you would like to purchase.

When you have enough points to purchase the contact, click to complete the process.Buy

Once you own a contact in the Data.com business directory, the and attribute values become visible in the Business phone E-mail Data.co column.m has

 

Customizing the Data.com integrationIf you wish to customize any aspect of the , you need to from Data.com.Data.com integration request your own API access token

Using a custom Data.com API token

Follow the steps below if you need to work with a custom Data.com access token in your API:

Open your web project in Visual Studio.Create a new class:

In the project's folder (or  if the project is installed as a web application)App_Code CMSApp_AppCode -> Old_App_Code ORAs part of a custom assembly (Class library)

Add a reference to the namespace:CMS.DataCom

 using CMS.DataCom;

Make the class implement the interface.ITokenProviderAdd the method and return your Data.com token as a string:GetToken()

Important: Modifying or extending the default functionality without using your own Data.com token is a violation of the licensingterms.

Page 67: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

5.

1.

public class CustomDataComTokenProvider : ITokenProvider{ /// <summary> /// Gets the token used for Data.com communication. /// </summary> /// <returns>Token</returns> public string GetToken() { return "Your Data.Com API Token"; }}

Whenever you call the method in your custom code, add an instance of your class as aDataComHelper.CreateClient ITokenProviderparameter:

using CMS.DataCom;

...

DataComClient client = DataComHelper.CreateClient(newCustomDataComTokenProvider());

 

Salesforce integrationThe Salesforce integration currently allows you to replicate Kentico into your organization as leads.contacts Salesforce

The system replicates contacts to Salesforce leads based on requirements, which you can adjust according to your specific needs.scoreYou can then work with the leads within Salesforce itself.

You can configure the replication in the application in . To use the replication, you have to link theSettings Integration -> Salesforce.comKentico application with your Salesforce account.

Differences between contact management in Kentico and Salesforce

The following table briefly describes some of the differences between contacts in Kentico and leads in Salesforce.

Action Kentico contacts Salesforce leads

Deleting contacts Can be deleted Only marked for deletion

Merging contacts Can be merged, use the target's ID Can be merged

Splitting contacts Can be split, retrieve their original ID Can't be split

 

Configuring Salesforce integrationYou can access the Salesforce integration configuration in the application in . These settings allowSettings Integration -> Salesforce.comyou to authorize access to your Salesforce organization and modify how the system maps the attributes of Kentico to leads incontactsSalesforce.

Authorizing access to Salesforce

You need to authorize access of Kentico to your organization on behalf of a specific Salesforce user. This process requires you to generate a and in Salesforce itself.Consumer key Consumer secret

Click next to the setting. Authorize Organization access

Important!To be able to configure the authorization, you need to have SSL set up on your web site in IIS. You can find the detailed stepsdescribed on the .official IIS website

Page 68: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1.

2.

3.

4.

5.

6.

7.

8.

9.

An authorization dialog opens.

Log on to .Salesforce.com

Create a new remote access application in .Setup -> Create -> Apps In , click . Connected Apps New

Enter the following values for the remote access application:

Application: Type a name for the application. This name allows you to identify your application as the source of the requestwhen authorizing access to your organization.Enable OAuth

Callback URL: Use the following format: https://www.example.com/CMSModules/ContactManagement/Pages/Tools/SalesForce/AuthorizationSetup.aspx

Use digital signatures: Leave unchecked. The Salesforce integration does not use digital signatures for logging in.Select OAuth Scopes: 

Perform requests on your behalf at any time (refresh token, offline access)Full access (full)

Save the form and copy the and provided by Salesforce for your remote access application.Consumer Key Consumer Secret

Paste your consumer values into the corresponding fields in the Kentico authorization dialog and click .AuthorizeA Salesforce login screen opens in the current window.

Log in and click to grant permission to your Kentico application.Allow

Save the settings to finish the authorization process.

The section now shows the user and company name that the application uses to authorize access to Salesforce.Organization access 

Configuring the replication of contacts

Once the authorization is complete, you need to configure how the system replicates contacts into Salesforce leads. You can edit the settingsglobally or for specific websites.

Replication of contacts into Salesforce leads

Enabled Enables or disables replication of contacts into Salesforce leads.

Keep Salesforce leads updated If checked, the replication process includes contacts that havealready been replicated before. This ensures that the systemupdates the corresponding Salesforce leads based on the currentcontact data.

If disabled, contacts are only replicated once.

Mapping of contacts to SalesForce leads Determines how contact fields are mapped to the fields ofSalesforce leads.

See the Mapping contacts to Salesforce leads section below fordetails.

Batch size Applications can only make a limited number of API calls toSalesforce within a 24 hour window, so the replication processhandles contacts in batches. Each batch is processed using oneAPI call. The setting specifies the maximum number ofBatch sizecontacts that the system replicates in a single batch.

SecurityThe system uses the OAuth 2.0 protocol to authorize access to Salesforce. Your Salesforce login and password are neverdisclosed to Kentico. Access tokens are stored in encrypted format and the communication itself is encrypted using SSL.

Page 69: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1. 2.

3. 4. 5.

1.

2.

3.

Score Allows you to select the score that determines which contacts arereplicated. The system only replicates contacts that reach a certainvalue in the given score (specified via the Minimum number of

setting).points for replication

If you do not choose a score ( ), the system replicates allNonecontacts.

Note: The replication process is always performed separately foreach website, so you can only select a score for individual sites,not globally.

To learn more about scoring, refer to the chapter.Scoring contacts

Minimum number of points for replication Specifies the amount of points that contacts must reach in thescore selected through the setting. Once a contact reachesScore this value, the system marks it for replication as a Salesforce lead.

Lead description Defines a custom description for replicated contacts. To map thedescription to a specific field of Salesforce leads, select the Gener

source in the field mappings.ated lead description

You can insert the values of contact fields into the description using.macro expressions

The default description adds the of the contact that isLast namebeing replicated and the name of the current site:

{% Contact.ContactLastName %} from{% CurrentSite.SiteName %}

For example, to use the value instead of the lastBusiness phonename, enter the following expression:

 {% Contact.ContactBusinessPhone %}from {% CurrentSite.SiteName %}

Default company name All Salesforce leads require a company name value.

This setting allows you to specify a default company name, whichthe replication process uses for contacts who are not associatedwith any company.

The system attempts to retrieve the company name value fromsources in Kentico in the following order:

The value of the contact's fieldCompany nameThe name of the in which the contact is listed as a account primary contactThe account that lists the contact as a secondary contactThe first account that contains the contact as a regular contactThe value of the setting (if none ofDefault company namethe above steps are successful)

Mapping contact fields to Salesforce lead fields

The replication process transfers data from Kentico contacts to Salesforce leads based on field mapping settings.

Preparing the Salesforce mapping identifier field

Kentico stores the bindings between Salesforce leads and contacts in a custom Salesforce field. You need to create a dedicated field for yourSalesforce leads for this purpose.

Log on to .Salesforce.com

Navigate to .Setup -> Customize -> Leads -> Fields

Click in the section.New Lead Custom Fields & Relationships

Note: You need to authorize before you can adjust the field mappings.Organization access

Page 70: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

3.

4.

5.

6.

7.

8.

9.

Choose as the field type and click .Text Next

In the step, fill in the following values:Enter the details

Field Label: type any label for the field, for example: Kentico IDLength: 32Field Name: type any name for the field, for example: Kentico_IDUnique: Enabled

Enable .Treat "ABC" and "abc" as duplicate values (case insensitive)External ID: Enabled

Fill in the rest of the information as required and finish the wizard.New Custom Field

In Kentico, go to and click below the seSettings -> Integration -> Salesforce.com Edit Mapping of contacts to Salesforce leadsction.

Select your new Salesforce lead field as the .External identifier field

Click and  the settings.OK Save

You can now configure the mappings between the fields of Kentico contacts and Salesforce leads.

Setting up the field mappings

To access the field mapping dialog, go to and click below the Settings -> Integration -> Salesforce.com Edit Mapping of contacts to section.Salesforce leads

The mapping dialog offers a list of all standard and custom fields defined for your Salesforce leads. You can select sources for the fields fromthe following sections:

Field - the fields of Kentico contacts. Only fields containing relevant data are available (internal system fields of contacts are hidden).Custom - related values that cannot be loaded directly from contact fields, including the following:

Company name - ensures that each contact has a company name value. See the description of the Default company namesetting for details about the process.Generated lead description - loads the value of the website's setting.Lead descriptionCountry - provides the name of the contact's country as a text value.State name - provides the name of the contact's state as a text value.

Picklist entry - allows you to select from the values predefined in Salesforce for picklist type fields.

You can only select contact fields that fit the data type of the target Salesforce field. The following table shows which types of Kentico fieldsare supported by the available Salesforce data types:

Salesforce Data type Supported Kentico field data types

Checkbox Boolean (Yes/No)

Currency Replication does not support the Currency data type at this time.

Date Date and time

Date/Time Date and time

Email Text, Long text

Number Decimal number, Integer number, Long integer number

Page 71: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1. 2.

3.

4.

5.

Percent Decimal number, Integer number, Long integer number

Phone Text, Long text

Picklist Text, Long text

Picklist (Multi-Select) Text, Long text

Text Text, Long text

Text Area Text, Long text

Text (Encrypted) Text, Long text

URL Text, Long text

Once you configure all field mappings as required, you can start .Replicating contacts to Salesforce 

Replicating contacts to SalesforceThe system replicates contacts to Salesforce leads using the . This task runs separately for each siteSalesForce replication scheduled taskin Kentico, by default once per hour.

Prerequisite: Before the system can run the replication task, you need to configure the website for access to your Salesforce organizationand the related replication settings. See: Configuring Salesforce integration

Scheduling the replication process

You can configure the Salesforce replication task according to your own requirements, for example to change when and how often thereplication takes place.

Open the application.Scheduled tasks Select your site.

Click ( ) next to the task.Edit SalesForce replication

Set the properties of the task as required.Use the section to schedule the time and frequency of the Salesforce replication process.Task intervalWe recommend keeping the option enabled to maintain optimal replication performance.Run task in separate thread

Click  .Save

NoteThe system may modify values during the replication process according to the parameters of the target fields in Salesforce.

Text values - the replication process may shorten long text values (strings) to fit the maximum length of the target field.Decimal numbers - the fractional part of decimal numbers may be truncated based on the data type settings of the targetfield. For example, the number could be shortened to .2.45397 2.45Large numbers - replication of large numbers may result in an error if the target field has an insufficient length. Sucherrors block the related contact from replication until the contact's values are updated, or the field mapping settingschange.

Page 72: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1. 2. 3.

4.

1. 2. 3. 4.

5.

The system performs contact replication for the given website based on the settings of the task.

 

Checking the replication status of your contacts

You can view which contacts in Kentico have or have not been replicated to Salesforce leads.

Open the application.Contact management Click .Display advanced filterSelect one of the options on the second row in the filter:Search

Replicated into Salesforce leadsNot replicated into Salesforce leads

Click .Search

The list now only shows contacts that match the selected replication status.

Replication process specifics

When executed, the scheduled task attempts to replicate all contacts that meet the set for theSalesForce replication scoring requirementsgiven website.

The application can only make a limited number of API calls to Salesforce within a 24 hour window, so the replication process handlescontacts in batches. Each batch is processed using one API call. You can specify the maximum number of contacts that the systemreplicates in a single batch through the setting in .Batch size Settings -> Integration -> Salesforce.com

To view how many API requests your company has made and how close you are to the limit, refer to Setup -> System Overview -> API in the Salesforce interface.Usage

 

Example - Replicating a contact into a Salesforce leadThe following example demonstrates how the system replicates a sample contact into a Salesforce lead.

Important: The site must be for Salesforce access.authorized

Creating the replication score

First you need to define a to determine which contacts the system will replicate.score

Open the application.Scoring Click  .New scoreType as the score's and click  .SF Score Display name SaveSwitch to the tab of the new score and click  .Rules New rule

Set the following properties for the rule:

Display name: SF RuleScore value: 50Rule type: Attribute

Attribute: Job titleCondition: - ManagerContains

Tip: You can ( ) the Salesforce replication task manually at any time from the list of scheduled task.Execute

Note: The replication process runs separately for each site in the system. As a result, each site also has its own batch counter.

Replication error handlingErrors can occur during the replication of contacts. For example if a numeric value is too large for the target Salesforce field, or if acontact in Kentico doesn't have a field that is required by Salesforce filled in. In these cases, the process skips the related contactand continues with the replication.

You can find records of all replication errors in the application. Event log

The system flags all contacts that caused an error and blocks them from subsequent replication attempts. The replication block isautomatically removed for individual contacts when one of their fields is updated, or globally if the Mapping of contacts to

settings change (see the section for details).Salesforce leads Configuration

Page 73: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

5.

6.

1.

2.

3.

4.

1.

2.

3.

4.

5.

Click  .Save

This grants 50 points to all contacts who have the word in their job title.SF Score Manager 

Creating a new contact

Now you need to create a that fulfills the rule of the previously defined score. On live deployments, the system automatically createscontactand maintains contacts automatically for the website's visitors, but you can add a contact manually to try out the Salesforce replication.

Open the application.Contact management

Click  and fill in the following attributes:New contact

First name: KennyLast name: Weathers

Job title: OMF Manager

Address1: N 14th StCity: CottonwoodCountry: USAState: ArizonaBusiness phone: 1-575-123-456E-mail: [email protected]

Click  .Save

Go back to the application and the .Scoring Edit SF score

On the tab, you can see that your new contact has 50 points in the replication score. The system awarded the points because theContactscontact contains the word in the field.Manager Job title

Replicating the contact to Salesforce

You now need to configure the website's Salesforce replication settings.

Go to .Settings -> Integration -> Salesforce

Choose the site where you created the score.

Make sure that the match your requirements.field mapping settings

Specify the replication score requirements through the following settings:

Score: Select your replication score ( )SF ScoreMinimum number of points for replication: 50

Save the settings.

You now have a contact on the website that fulfills the replication criteria. By default, the system replicates contacts once every hour. Youcan however run the replication manually at any time.

Page 74: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1. 2.

3.

1. 2. 3. 4.

Starting the replication process manually:

Open the application. Scheduled tasksSelect the site where you configured Salesforce replication.

Click ( ) next to the task.Execute Salesforce replication

Result

After a couple minutes at most, your contact should appear as a lead in Salesforce. To check whether the replication was successful, log into Salesforce using your account, navigate to and choose .Leads Today's Leads

You should see the lead replicated from the Kentico contact. You can now work with the lead as with any other Salesforce lead.

You can also check the replication status of the contact in Kentico:

Open the application.Contact management Click .Advanced searchSelect in the second row.Replicated into Salesforce leads Search Click .Search

The list now shows only contacts that have been successfully replicated to Salesforce. 

Force.com integration APIIn addition to the built-in that automatically converts Kentico into Salesforce leads, Kentico also providesreplication process contactsintegration with the Force.com API. The integration allows you to develop custom logic for manipulating data inside your Salesforceorganization (query, create, update and delete).

This page introduces the Force.com integration API and presents basic examples to get you started.

The following content assumes you already have knowledge of the Force.com API and Salesforce Object Query Language (SOQL). SOQL isthe object language developed for querying data on the Force.com platform. Refer to the official Force.com documentation for moreinformation on the and .Force.com API SOQL

Kentico integrates the API using the Partner version of the web service, which is weakly typed. This means that the integration API does notuse classes such as Lead or Company. Only general classes are available: and . For example, to create a new contact in yourObject FieldSalesforce organization, you need to create a new Object and set its properties so that it represents a contact. The flexibility of this form ofintegration reduces the reliance on the Force.com data model.

Note: There are several basic naming differences between the default Force.com API and the integration API in Kentico:

Salesforce Kentico

Object Entity

Object Type Model

Object Field Entity Attribute

Object Field Type Entity Attribute Model

 

Salesforce API requirements and limitations

You can only use the integration API if your Salesforce organization has the API feature enabled. This feature is enabled by default for thefollowing editions:

UnlimitedEnterpriseDeveloperSome Professional Edition organizations may have the API enabled

Force.com also enforces a limit on the number of API calls your organization can make during a 24 hour window. If your organizationexceeds the limit, all calls result in an error until the number of calls over the last 24 hours drops below the limit. The ofmaximum numberallowed calls for your organization is determined by the edition you are using.

Reference requirementThe Salesforce integration API requires a reference to the namespace.CMS.SalesForce

Add the following directive to all files that access the integration API:using

Page 75: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1.

2.

1.

2.

Establishing a session with the Salesforce organization

Before you can start working with the data, you need to establish a session with your Salesforce organization.

Use the following code to create a session for your Salesforce organization based on your website's .Salesforce integration settingsEnter the code name of your Kentico site in place of ."MyCompanySite"

// Provides a Salesforce organization sessionISessionProvider sessionProvider = new ConfigurationSessionProvider { SiteName= "MyCompanySite" };Session session = sessionProvider.CreateSession();

Create a client to access the organization's data using the session.

// Creates a client to access Salesforce organization's dataSalesForceClient client = new SalesForceClient(session);

You can then use the client to perform specific operations.

Querying data

Describe the entity you will be working with.The following examples work with Salesforce entities, but you can use the same approach for other SalesforceContactobjects such as Leads or Accounts.

// Describes the Salesforce Contact entityEntityModel model = client.DescribeEntity("Contact");

// Displays basic information about the entity's attributesforeach (EntityAttributeModel attributeModel in model.AttributeModels){ Console.WriteLine("{0} is an attribute labeled {1} of type {2}",attributeModel.Name, attributeModel.Label, attributeModel.Type);}

Load the attributes of the entity using SOQL.

using CMS.SalesForce;

All examples in the sections below use the variable for this purpose.client

Page 76: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

2.

1.

2.

// Executes a query using SOQLSelectEntitiesResult result = client.SelectEntities("SELECT Id, Name,MobilePhone FROM Contact", model);

// Displays how many contacts were foundConsole.WriteLine("{0} contacts were found", result.TotalEntityCount);

// Displays basic information about each of the contactsforeach (Entity contact in result.Entities){ Console.WriteLine("Contact {0} with name {1} and phone number {2}",contact.Id, contact["Name"], contact["MobilePhone"]);}

Creating objects

Create a new contact.

// Describes the Contact entityEntityModel model = client.DescribeEntity("Contact");

// Creates a new contact entityEntity customContact = model.CreateEntity();

customContact["LastName"] = "Jones";customContact["Description"] = "Always has his wallet on him";

Entity[] customContacts = new Entity[] { customContact };CreateEntityResult[] results = client.CreateEntities(customContacts);

Use the following code to check whether the creation was successful or not.

// Checks if the contact was successfully created in Salesforceforeach (CreateEntityResult createResult in results){ if (createResult.IsSuccess) { Console.WriteLine("A contact with id {0} was inserted.",createResult.EntityId); } else { Console.WriteLine("A contact could not be inserted."); foreach (Error error in createResult.Errors) { Console.WriteLine("An error {0} has occurred: {1}",error.StatusCode, error.Message); } }}

Updating existing objects

To update an object, you first need to either prepare a new entity, or load an existing one using SOQL.

Custom Salesforce field requiredThe following examples use a custom external ID attribute for Salesforce contacts, so you first need to define the custom field in

Page 77: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1.

2.

1.

Update a contact and assign an external ID value.

// Describes the Contact entityEntityModel model = client.DescribeEntity("Contact");

// Updates an existing contactEntity updateContact = model.CreateEntity();

updateContact["Description"] = "Always has his satchel on him";updateContact["KenticoContactID"] = "D900172AABCE11E1BC6924C56188709B";

Entity[] updateContacts = new Entity[] { updateContact };UpdateEntityResult[] updateResults = client.UpdateEntities(updateContacts);

Use the following code to check whether the update was successful or not.

// Checks if the contact was successfully updatedforeach (UpdateEntityResult updateResult in updateResults){ if (updateResult.IsSuccess) { Console.WriteLine("The contact with id {0} was updated.",updateResult.EntityId); } else { Console.WriteLine("The contact could not be updated."); foreach (Error error in updateResult.Errors) { Console.WriteLine("An error {0} has occurred: {1}",error.StatusCode, error.Message); } }}

Upserting objects

The operation uses an external ID to identify already existing objects and then decides whether to the object or a newUpsert update createone:

If the external ID does not exist, a new record is .createdWhen the external ID matches an existing record, the given record is .updatedIf multiple external ID matches are found, the upsert operation reports an error.

Note: It is generally recommended to use upsert instead of directly creating entities if you plan on specifying an External ID attribute. Thisallows you to avoid creating duplicate records.

Create a new entity using the call.upsertIf you leave the value of the same as in the previous example, the existing contact will be .KenticoContactID updated

1. 2. 3. 4. 5.

Salesforce.

Log in to Salesforce.Navigate to .Setup -> Customize -> Contacts -> FieldsClick in the section.New Contact Custom Fields & Relationships Choose as the data type and click .Text NextIn the step, fill in the following values:Enter the details

Field label: KenticoContactIDLength: 32Field Name: KenticoContactIDExternal ID: enabled

Page 78: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1.

2.

1.

// Describes the Contact entityEntityModel model = client.DescribeEntity("Contact");

// Creates a new contact or updates an existing oneEntity upsertContact = model.CreateEntity();

upsertContact["Description"] = "Is a professor";upsertContact["KenticoContactID"] = "D900172AABCE11E1BC6924C56188709B";

Entity[] upsertContacts = new Entity[] { upsertContact };UpsertEntityResult[] upsertResults = client.UpsertEntities(upsertContacts,"KenticoContactID");

Use the following code to check for the results of the upsert call.

// Checks the results of the upsert callforeach (UpsertEntityResult upsertResult in upsertResults){ if (upsertResult.IsSuccess) { if (upsertResult.IsUpdate) { Console.WriteLine("The contact with id {0} was updated.",upsertResult.EntityId); } else { Console.WriteLine("A new contact with id {0} was inserted.",upsertResult.EntityId); } } else { Console.WriteLine("The contact could not be created nor updated."); foreach (Error error in upsertResult.Errors) { Console.WriteLine("An error {0} has occurred: {1}",error.StatusCode, error.Message); } }}

Deleting objects

The delete call takes an array of entity IDs as a parameter. The ID is generated by Salesforce and is unique for each object.

Use an upsert call to create several new contacts that you will later delete.

Page 79: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1.

2.

3.

// Describes the Contact entityEntityModel model = client.DescribeEntity("Contact");

// Creates new contactsEntity customContact1 = model.CreateEntity();Entity customContact2 = model.CreateEntity();Entity customContact3 = model.CreateEntity();

customContact1["LastName"] = "Drake";customContact1["Description"] = "Is a hunter";customContact1["KenticoContactID"] = "6C2L16B8W0ZXSU5SYPYRVE08QSKOR7F6";customContact2["LastName"] = "Croft";customContact2["Description"] = "Is an archeologist";customContact2["KenticoContactID"] = "N5XX8Z42ISTVYGPC98AH81T1RHVOSESR";customContact3["LastName"] = "Solo";customContact3["Description"] = "Is a pilot";customContact3["KenticoContactID"] = "N34VY7D5K677GKG8JOGDIA9UHVBHHVSL";

Entity[] newCustomContacts = new Entity[] { customContact1, customContact2,customContact3 };UpsertEntityResult[] createResults = client.UpsertEntities(newCustomContacts,"KenticoContactID");

Use the following example to check whether the creation was successful or not.

// Checks the results of the upsert callforeach (UpsertEntityResult upsertResult in createResults){ if (upsertResult.IsSuccess) { if (upsertResult.IsUpdate) { Console.WriteLine("The contact with id {0} was updated.",upsertResult.EntityId); } else { Console.WriteLine("A new contact with id {0} was inserted.",upsertResult.EntityId); } } else { Console.WriteLine("The contact could not be created nor updated."); foreach (Error error in upsertResult.Errors) { Console.WriteLine("An error {0} has occurred: {1}",error.StatusCode, error.Message); } }}

Select the new contacts using a SOQL query and list their IDs.

: Force.com returns an 18 character version of object IDs in API calls.Note

Page 80: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

3.

4.

5.

1.

2.

// Executes a query using SOQLSelectEntitiesResult queryResult = client.SelectEntities("SELECT Id, Name FROMContact WHERE description LIKE 'Is a%'", model);

// Displays how many contacts have been foundConsole.WriteLine("{0} contacts were found", queryResult.TotalEntityCount);

// Displays basic information about each of the contactsforeach (Entity contact in queryResult.Entities){ Console.WriteLine("Contact {0} with name {1}", contact.Id,contact["Name"]);}

Delete all of the contacts returned by the query.Identify the contacts using an array of ID values.Make sure you fill in the IDs returned by the previous selection query.

// Deletes contactsString[] contactIDs = new String[] { "a0BA0000000L2ZCMA0","a0BA0000000L2ZCMA1", "a0BA0000000L2ZCMA2" };DeleteEntityResult[] deleteResults = client.DeleteEntities(contactIDs);

Check whether the deletion was successful.

// Checks if the contact was successfully deletedforeach (DeleteEntityResult deleteResult in deleteResults){ if (deleteResult.IsSuccess) { Console.WriteLine("A contact with id {0} was deleted.",deleteResult.EntityId); } else { Console.WriteLine("A contact could not be deleted."); foreach (Error error in deleteResult.Errors) { Console.WriteLine("An error {0} has occurred: {1}",error.StatusCode, error.Message); } }}

Loading deleted objects

After you delete an object in Salesforce, its attribute is set to . You can't select deleted objects unless you enable the IsDeleted True IncludeD option for the query.eleted

Change the client options so that queries include deleted objects.

// Changes the client settingsclient.Options.IncludeDeleted = true;

Select the deleted contacts using a SOQL query.

Page 81: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

2.

// Describes the Contact entityEntityModel model = client.DescribeEntity("Contact");

// Executes a query using SOQL

SelectEntitiesResult includeDeletedQueryResult = client.SelectEntities("SELECTId, Name FROM Contact WHERE description LIKE 'Is a%'", model);

// Displays how many contacts were foundConsole.WriteLine("{0} contacts were found",includeDeletedQueryResult.TotalEntityCount);

// Displays the basic information of each contactforeach (Entity contact in includeDeletedQueryResult.Entities){ Console.WriteLine("Contact {0} with name {1}", contact.Id,contact["Name"]);} // Reverts the client settings to ignore deleted contacts againclient.Options.IncludeDeleted = false;

Call options

You can adjust Salesforce client calls through additional options. The options are similar to the available in the Force.comSOAP headersAPI.

Call option Type Description

TransactionEnabled Bool Specifies whether the command operationsrun in a transaction.

AttributeTruncationEnabled Bool Specifies whether truncation is allowed forstring values.

FeedTrackingEnabled Bool Specifies whether the changes made by thecall are tracked in feeds.

MruUpdateEnabled Bool Specifies whether the call updates the listof most recently used items in Salesforce.

IncludeDeleted Bool Specifies whether SOQL queries includedeleted entries.

ClientName String String identifier for the client.

DefaultNamespace String String that identifies a developernamespace prefix.

CultureName String Specifies the language of the returnedlabels.

BatchSize Int Specifies the maximum number of entitiesreturned by one query call.

 

Strands Recommender integrationThe integration allows you to provide personalized product recommendations. You can provide suchStrands Recommenderrecommendations to the and, if you have a Kentico license, the and visitors of your store EMS recipients of your email campaign marketing

emails.automation

The integration provides real time recommendations based on its ability to immediately learn how visitors behave when browsing your store.For example, what kind of products visitors look at, which products they buy or search for in the store. The Strands Recommender can thenshow universal and configurable recommendations to the store visitors, such as , , similar products most popular products products other

, and others.people bought

Page 82: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1. 2.

You can fully configure both the way the recommendations are displayed on your store or in your email communication, as well as the logicof the recommendations—the visitor behavior that is taken into account.

Learn more about the capabilities of the Strands Recommender.

Before your store can make use of Strands Recommender, you need to .set up the integration

A strands recommendation   

Integrating the Strands Recommender service into your storeChoose a pricing plan and sign up on the website.Strands RecommenderCopy your and from the Strands  page into the settings in (application) ->API ID Validation Token My account Settings Integration

.-> Strands Recommender

Kentico comes with a default Strands catalog transformation T. StrandsRecommender.Transformations.CatalogFeedTransformationhe handles which fields each of the items in the catalog contains. Optionally, you can configure how KenticoTransformationgenerates the further.Strands catalog feed

Minimum store sizeNote that it is recommended for your store to contain at least and have site traffic of at least 400 products 10,000 visitors a

for the Strands Recommender engine to work correctly.month

Multilingual and multiple currencies supportThe Strands recommender integration supports recommending products in as well as in .multiple languages multiple currenciesThe recommendations that the user sees are localized into the culture in which the user is viewing the website—each product's title, , and (url) can be localized. If the product's price is displayed as well, it is displayed in the user's currently selected description linkcurrency.

The price of products in different currencies is calculated based on the set .exchange rates

Page 83: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

2.

3. 4.

5.

6. 7. 8.

In , turn the check-box on.Automatic catalog upload Enable automatic catalog upload Set the frequency at which the system uploads the to .Strands catalog feed Strands

(Optional) In , insert a and for accessing the Strands catalog feed. This restrictsCatalog access restriction Username Passwordthe access to the , which can otherwise be with access to the site.Strands catalog feed viewed by anyone

Using Windows Authentication?

Note that doesn't work if you are using Windows Authentication to access Kentico.Catalog access restriction

 Save the settings. that using the button automatically starts a upload to Strands.Note Save Strands catalog feed Open the Strands page and set up your recommendation widgets.RecommendationsPlace Strands recommendation widgets onto pages by placing the web part.Strands recommendations – or –

.Place Strands recommendations into email campaigns 

The Strands catalog transformation

The default Strands catalog transformation, , handles which fields eachStrandsRecommender.Transformations.CatalogFeedTransformationof the items in the catalog contains.

You can always check how the looks with the current configuration by the configuration andStrands catalog feed Savingopening the catalog in your browser. The feed is generated in <site address>/CMSModules/StrandsRecommender/CMSP

. The whole of the feed is then, for example: ages/StrandsCatalogFeed.ashx URL

http://www.yoursite.com/CMSModules/StrandsRecommender/CMSPages/StrandsCatalogFeed.ashx

Page 84: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

<item> <id>{% ItemID %}</id> {% foreach (document in LanguageVersions) { %} {% cultureCode = document.DocumentCulture.Replace("-", "").ToLower();; #%} <title_{% cultureCode %}><![CDATA[{% document.DocumentName #%}]]></title_{%cultureCode %}> <link_{% cultureCode %}><![CDATA[{% document.AbsoluteUrl + "?lang=" +document.DocumentCulture #%}]]></link_{% cultureCode %}> <description_{% cultureCode %}><![CDATA[{% document.DocumentSKUDescription%}]]></description_{% cultureCode %}> {% } #%} {% foreach (currency in Currencies) { %} {% currencyCode = currency.CurrencyCode.ToLower();; #%} <price_{% currencyCode %}>{% Math.Round(SKU.GetPrice(currency),currency.CurrencyRoundTo, "AwayFromZero") %}</price_{% currencyCode %}> <cur_{% currencyCode %}>{% currency.CurrencyCode %}</cur_{% currencyCode %}> {% } #%} <price>{% SKU.SKUPrice #%}</price> <image_link><![CDATA[{% GetAbsoluteUrl(SKU.SKUImagePath) #%}]]></image_link> <category>{% ItemCategory %}</category> <SKUDepartmentID>{% SKU.SKUDepartmentID #%}</SKUDepartmentID> <SKUProductType><![CDATA[{% SKU.SKUProductType #%}]]></SKUProductType> <SKUSupplierID>{% SKU.SKUSupplierID #%}</SKUSupplierID> <SKUManufacturerID>{% SKU.SKUManufacturerID #%}</SKUManufacturerID></item>

Note the following properties used in the transformation:

ItemID - an ID of each of the items in the content tree. Same for each language version of the item. Sent to Strands as a uniqueidentifier of the item ( ).ID fieldItemCategory - a page type ID. Same for each language version. Sent to Strands as a . You can category field customize how

.products are categorizedSKU - items of the table, such as , , , and others.COM_SKU SKU.SKUPrice SKU.SKUDepartmentID SKU.SKUProductTypeLanguageVersions - a collection of every language version of a particular item. Each member of the collection is of typeTreeNode and contains columns from the and tables. Such as , , CMS_Document CMS Tree DocumentSKUName DocumentSKUDescription D

, , and others.ocumentPageTitle NodeAliasCurrencies - a collection of the available currencies. Each member is of type and contains columns from the CurrencyInfo COM_Cu

table, such as and .rrency CurrencyCode CurrencyName

 

Placing Strands recommendations on a pageYou can recommend products on pages using Strands via a widget or a web part. The recommendations are displayed based on thebehavior of the users visiting the site.

There are currently five types of that you can make the web part display:recommendations

Home - d The web part can display these recommendations on any type ofisplays recommendations from the Home category. pages.Category - displays recommendations from the category named . The web part displays recommendations of the sameCategoryproduct category (determined by page type by default—you can ) as the product the user iscustomize how products are categorizedcurrently viewing. If there are no other products in the category, no recommendations are displayed.Product Detail - displays recommendations from the Product detail category. The web part can display these recommendations onpages that are set to .represent a product typeShopping Cart / Wishlist - displays recommendations from the Shopping Cart / Wishlist category. The recommendations aredisplayed only to users who have a product in their shopping cart. The web part can display these recommendations on any type ofpages.Order Confirmation - displays recommendations from the category. Order Confirmation The recommendations are based on the

these recommendations on any type of pages.user's last purchase. The web part can display

The StrandsRecommender.Transformations.CatalogFeedTransformation transformation

The and elements must always contain the and properties. You can customize all the other tags<id> <category> ItemID ItemCategoryin the transformation.

Page 85: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1. 2.

3. 4.

 

A Strands recommendation web part placed on a product 

Placing Strands recommendations widget on a page

Open the application.Pages Choose the page on which you want to place the widget.

On the tab, open the  zone menu ( ).Page widgetClick  .Add new widget

Make sure you configure the integration before placing a widget orStrands recommendation Strands recommendationweb part.

Page 86: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

4.

5. 6. 7.

8. 9.

10.

1. 2. 3. 4. 5.

6.

7. 8. 9.

 Choose and click .Strands recommender -> Strands recommendations SelectUnder , use the drop-down list to choose the that you want to display.Template Choose a template Strands recommender widget(Optional) If you want to adjust how the recommendations look on the page further than what is offered on the Strands recommender

, specify a in the field.website transformation Custom layout

 (Optional) the rest of the widget properties.SpecifyClick . The system places the widget on the page.Save & CloseSave the page.

You have configured the widget to display recommendations based on visitor behavior.Strands recommendations

Placing Strands recommendations web part on a page

Open the application.Pages Choose the page on which you want to place the web part. Switch to the tab.Design Place the web part on the page.Strands recommendationsUnder , use the drop-down list to choose the that you want the web partTemplate Choose a template Strands recommender widgetto display.(Optional) If you want to adjust how the recommendations look on the page further than what is offered on the Strands recommender

, specify a in the field.website transformation Custom layout

 (Optional) the rest of the web part properties.SpecifyClick on to confirm. The system places the web part on the page.OK Save the page.

You have configured the web part to display recommendations based on visitor behavior.Strands recommendations

Custom Strands recommendations layout

By using a transformation to define a custom layout in the web part, you can fully control the way theStrands recommendationsrecommendations are displayed on the page. You only need to specify the amount of items you wish to display and the logic of therecommendation on the . You can handle the rest by the transformation. You can create your ownStrands recommender websitetransformation or edit one of the two predefined transformation:

- a transformation imitating the default recommendation template from the StrandsRecommender.Transformations.StrandsDefault St.rands recommender website

- a transformation displaying the recommendations in a vertical list.StrandsRecommender.Transformations.StrandsList 

Example transformation

One of the Strands recommendations transformations predefined in the system is the traStrandsRecommender.Transformations.StrandsList nsformation.

Note that Strands recommendations transformations need to be of . A jQuery transformation consists of HTML codejQuery typeand   that dynamically insert values of the object that is currently being processed. There are also tags that controltemplate tagsthe flow of the transformation. You can find more information on using jQuery transformations in Kentico in a topic describing their

in the Chat application.use

Page 87: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1.

a.

2. a. b. c.

d.

e.

<div class="strandsLinkTemplate"> <h1 class="uiLight"> Recommendation title </h1> <ul> {{each(i, rec) recommendations}} <li> <a href="${rec.metadata.link}"onclick="SBS.Tracking.onRecClick('${rec.itemId}','${tpl}','${rrq}');return true;" > <img src="${rec.metadata.picture}" alt="${rec.metadata.name}" /> <h2 class="uiLight">${rec.metadata.name}</h2> </a> <span clas="price">{% ECommerceContext.CurrentCurrency != null ?string.FormatString(ECommerceContext.CurrentCurrency.CurrencyFormatString,"${rec.metadata.price}") : "${rec.metadata.price}" #%}</span> </li> {{/each}} </ul></div>

The transformation displays recommendations in a vertical list. The CSS that you use with the transformation is automatically inserted on thepage.

You can find detailed documentation of the parameters of the methods used in the transformation in the .official documentation 

Placing Strands recommendations into emailsYou can personalize  and emails by placing the Strands recommendation widget into emails.email campaigns marketing automationRecipients of these emails then receive recommendations personalized based on their behavior on the website.

Note that apart from a Kentico EMS license, you need a that supports Email recommendations as well.Strands recommender plan

Learn how you can place .Strands recommendations into email campaigns   

Troubleshooting the Strands Recommender integrationThis topic describes how you can resolve some of the situations that you may come across when using the Strands recommender.

Unable to insert Strands recommendations into e-mails

When inserting a strands recommendation widget into e-mails, you can receive an Access Denied error. You need a Kentico EMS license toinsert Strands recommendation widgets into e-mails, as the functionality makes use of .contact management

Another reason why you may be unable to make use of Strands recommendations in e-mails is that you may not have a Strands that supports the functionality. Please make sure you contact if you need a Strands recommenderrecommender plan Strands support

feature turned on.

The Strands catalog feed isn't being uploaded to Strands

You can see, , that the Strands catalog feed isn't uploaded to Strands. If that is the case, make surefor example in catalog upload historyyou:

Update the Strands catalog feed upload settings. The button i (application) ->Save n Kentico's Settings Integration -> Strands immediately starts a upload to Strands. The button also propagates the upload settings toRecommender Strands catalog feed

Strands.You have to update the upload settings, for example, if your site . ByStrands catalog feed moved to a different addressupdating the settings, Strands will know at what address it should now request the catalog.

Try setting up the import manually:Open the Strands  page.Catalog formatSelect in the section.Feed Choose Import MethodEnter the of the feed. The feed is generated in <site address>URL /CMSModules/StrandsRecommender/CMSPages/StrandsCatalogFeed.ashx.Specify the —the number of products that each page that is being uploaded to Strands contains. The defaultPaginationvalue is 2000.

The StrandsRecommender.Transformations.StrandsList transformation

Page 88: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

2.

e. f.

3. a.

b. c. d.

1. 2. 3.

4.

5. 6.

7.

Check , and .Enabled Import now and at scheduled time Full catalogSave your catalog.

 Upload the catalog manually:

Download the feed generated in <site address>/CMSModules/StrandsRecommender/CMSPages/StrandsCatalogFeed.ashxas an . file.xmlOpen the Strands  page.Catalog formatSelect (for catalog files larger than 5MB) or in the section.FTP Manual Upload Choose Import MethodFollow the instructions on the screen to finish the upload.

 

System slowdown during Strands catalog feed upload

If you experience a when the , you may want to change how thenoticeable system slowdown Strands catalog feed is being uploadedcatalog is being split into pages (Pagination). . To change the paginationBy default, the Pagination is set to 000 products per page2value, you need to set the catalog import method on the Strands  page.Catalog format

To change Strands catalog Pagination: 

Open the Strands  page.Catalog formatSelect in the section.Feed Choose Import MethodEnter the of the feed. The feed is generated in <site address>URL /CMSModules/StrandsRecommender/CMSPages/StrandsCatalogFeed.ashx.Specify the —the number of products that each page that is being uploaded to Strands contains. The default value isPagination2000.Check , and .Enabled Import now and at scheduled time Full catalogSave your catalog.

Try different values to find the value at which your system performs best.Pagination

General Strands recommender troubleshooting

With issues related to configuring individual Strands recommender functionality and settings, please make sure you contact . Strands support 

Customizing how products are categorized in the Strands integrationBy default, Kentico uses page type IDs for categorizing products in the Strands integration — both in the Strands catalog feed and the Strand

. To fully customize the categorization on both the places, you need to create a custom implementation of the s recommendations web part IS interface. By customizing the categorization, you can have it better represent the structure of your site.trandsCatalogCategoryMapper

This page describes how you can create a custom class in which you perform such a customization. The page also provides two examplecustomizations for you to build on.

Page 89: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1.

2.

3. a.

Creating a custom Strands product categorization

Open your web project in Visual Studio and create a new class in the folder (or  iApp_Code CMSApp_AppCode -> Old_App_Codef the project is installed as a web application). For example, name the class .CustomStrandsCatalogCategoryMapper.csCopy the following code into the class:

using System;using System.Globalization;

using CMS.Base;using CMS.Core;using CMS.StrandsRecommender;using CMS.DocumentEngine;using CMS.Ecommerce; [CustomStrandsCategoryMappingAttribute]public partial class CMSModuleLoader{ private class CustomStrandsCategoryMappingAttribute : CMSLoaderAttribute { private class CustomStrandsCatalogCategoryMapper :IStrandsCatalogCategoryMapper { public string GetItemCategory(TreeNode catalogItem) {  // Body of your Strands catalog categorization customization method } }

/// <summary> /// Registers module methods. /// </summary> public override void Init() { ObjectFactory<IStrandsCatalogCategoryMapper>.SetDefaultObjectTypeTo<CustomStrandsCatalogCategoryMapper>(); } }}

Now that you have the structure of the class, you can create your own customization ofCustomStrandsCatalogCategoryMapper the Strands catalog feed customization. Customize the method as described in one of the following examples:GetItemCategory

Using an SKU department ID as the category field in the Strands catalog feedClick here to expand...

Page 90: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

3. a.

b.

4.

a.

b.

/// <summary>/// Retrieves SKUDepartmentID which will be used for categorizing thepage in the Strands integration./// </summary>/// <param name="catalogItem">Document</param>/// <returns>Category field</returns>public string GetItemCategory(TreeNode catalogItem){ SKUInfo skuInfo =SKUInfoProvider.GetSKUInfo(catalogItem.NodeSKUID); if (skuInfo != null) { returnskuInfo.SKUDepartmentID.ToString(CultureInfo.InvariantCulture); } throw newException("[CustomStrandsCategoryCatalogMapper.GetItemCategory]:SKUInfo was not found for specified TreeNode.");}

Using the path to the page as the category field in the Strands catalog feedClick here to expand...

/// <summary>/// Retrieves the path to the page, excluding the page's name. Thepath will be used for categorizing the page in the Strandsintegration./// </summary>/// <param name="catalogItem">Document</param>/// <returns>Category field</returns>public string GetItemCategory(TreeNode catalogItem){ string docName = catalogItem.DocumentName; string docNamePath = catalogItem.DocumentNamePath;

return docNamePath.Substring(0, docNamePath.Length -docName.Length);}

Once you have customized the method, the class file, build your solution, and view your Strands catalogGetItemCategory Savefeed. You should see the system categorizing products in the feed according to the new customization.

Note that you can view your Strands catalog feed at http://www.yoursite.com/CMSModules/StrandsRecommender/CMSPag.es/StrandsCatalogFeed.ashx

The same categorization is now used in the in the recommendation type.Strands recommendations web part Category

   

Integrating SharePointKentico allows you to (Microsoft SharePoint 2010/2013/Online), access data stored on a SharePoint server and display it on your

. You can achieve this by configuring a , and placing the , in combination withwebsite SharePoint integration connection SharePoint web partanother web part displaying the content, into a selected page.

Besides, using the dedicated , you can SharePoint application access and manage SharePoint data in the Kentico administration.interface

Configuring SharePoint integration settings further describes the system's configuration options for SharePoint integration.Example - Displaying a SharePoint picture library in Kentico provides a step-by-step description of how you can display a picture

Further customizationYou can create any implementation of the interface and register it in the system using the IStrandsCatalogCategoryMapper Object

class' method. Factory SetDefaultObjectTypeTo

Page 91: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1. 2. 3. 4. 5.

library stored on a SharePoint server on a Kentico website.

What you can do

Get lists and list item data from SharePoint, and display it on Kentico pages.Add, modify, and delete SharePoint files using the Kentico administration interface.Download documents and images.

   

Configuring SharePoint integration connectionsBefore you can browse or manage the contents of a SharePoint site in Kentico, you need to specify a connection to the SharePoint server.The system allows you to define multiple SharePoint integration connections for the current Kentico site. 

Managing SharePoint connections

To manage SharePoint integration connections, use the application. The  allows you to manage allSharePoint connections applicationSharePoint connections defined for the currently selected site.

To manage existing SharePoint connections, use the following basic actions:

Edit ( ) - opens the connection editing interface, where you can view and modify the connection details.

Delete ( )                 

SharePoint connection properties

Section Properties

General Display name - the name of the SharePoint connectionused in the system's administration interface, e.g. whileconfiguring the . web partSharePoint data sourceCode name - the string identifier of the SharePointconnection object used by developers in the code. Unlessthere is a reason to set a particular value, you can leave thedefault option, and the system generates an(automatic)appropriate code name.Site URL - specifies the URL of the SharePoint site.SharePoint version - the system supports MicrosoftSharePoint 2010, Microsoft SharePoint 2013, and MicrosoftSharePoint Online.

Authentication Authentication modeUsernameDomainPassword

 

Adding SharePoint connections

To add a new connection to a SharePoint server:

Open the application.SharePoint connections Click .New connectionEnter the SharePoint connection properties.Click .Save(Optional) In the section, click to verify that the connection is functional.Connection test Test connection

The system creates a new SharePoint connection. You can now use the connection when configuring the web partSharePoint data source

Page 92: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1.

2. 3.

1.

2. 3.

4.

5. a. b. c.

d.

or defining available .SharePoint libraries

Testing SharePoint connections

You can verify if the system can connect to the SharePoint server specified in a connection.

Open the application.SharePoint connections

Edit ( ) a connection.In the section, click .Connection test Test connection

The system informs you about the result of the connection test.

 

Connecting to SharePoint Online

Learn what you need to do if you cannot connect to SharePoint Online due to the missing runtime when:

running Kentico in a standard environmentrunning Kentico in a Microsoft Azure environment

Connecting to SharePoint Online in a standard environment

If you cannot connect to SharePoint Online when running Kentico in a standard environment, download and install SharePoint Server 2013, available on the Microsoft website.Client Components SDK

                      

Connecting to SharePoint Online in a Microsoft Azure environment

If you cannot connect to SharePoint Online when :running Kentico in a environmentMicrosoft Azure

Download the appropriate version of from the Microsoft website.SharePoint Server 2013 Client Components SDKFor example, if you are running Kentico on a 64 bit machine, download the installationsharepointclientcomponents_x64.msifile.

Open your Azure project in Visual Studio.Create the batch file containing the following block of code:startup.cmd

msiexec /i sharepointclientcomponents_VERSION.msi /q /logsharepointclientcomponentinstall.log

Replace _VERSION with the identification of the edition of your downloaded SharePoint Server 2013 client components, i.e._x32 or _x64.The code ensures that the system installs the client components.                            

Add the following files to your Azure project's directory.CMSstartup.cmdsharepointclientcomponents_VERSION.msi

Include these files into the project and set them to be copied to the output directory:Click in the Solution Explorer toolbar.Show All FilesRight-click the file and select .Include In ProjectRight-click the file again and select .Properties

If you cannot connect to SharePoint Online, see .Connecting to SharePoint Online

The contained in the SharePoint Server 2013 client components isidentity client runtime necessary for successful SharePoint.authorization

If you don't have the runtime installed on your server machine, you can experience an issue with the dynamic linkmsoidcliL.dlllibrary.

After installing the SharePoint Server 2013 client components, restart your application (by clicking in Restart application System).-> General

Page 93: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

5.

d. e.

6. 7.

8.

1. 2.

3. 4. 5.

a.

b.

c.

d.

In Properties, set to .Copy to Output Directory Copy alwaysRepeat also for the other file.

Open the CMSAzure\ file.ServiceDefinition.csdefAdd the following block of code to the file's WebRole tag:

<Startup> <Task commandLine="startup.cmd" executionContext="elevated"taskType="background" /></Startup>

The code ensures that the system executes the startup.cmd batch file on startup of the virtual machine on Azure.                                 

Save and close the file.

We apologize that we currently cannot provide a more straightforward solution. This is due to restrictions imposed on the distribution of thethird-party software components. 

Configuring SharePoint integration web partBesides specifying a , you need to configure the to be able to browseconnection to the SharePoint server SharePoint data source web partthe contents of a SharePoint site in Kentico.

Adding SharePoint integration web part

Open the application.PagesSelect a page in the content tree.

You are selecting a page where the system will display the requested SharePoint data.Switch to the tab.DesignAdd the web part to the selected web part zone.SharePoint data sourceConfigure the web part.SharePoint data source

Configuring SharePoint integration web part

Specify the SharePoint integration connection.Connection

Specify how the system retrieves the SharePoint data.Retrieve - indicates whether the system downloads all lists of the selected type (the property), or only List typeitems from a specified list (the property) of the selected type.List name

Specify the type of SharePoint data.List type - indicates whether the system downloads from the SharePoint server custom lists, picture libraries, ordocument libraries.                   

                                                                      Based on the selection of the data retrieval mode (the property), the system offers other web partRetrieveproperties.                                                                       

Specify other web part properties based on the selection of the data retrieval mode.Retrieve: All lists of type

(Optional) You can specify web part properties in the section. See forSystem settings Configuring cachingmore details.

Retrieve: Specified list's items

Section Properties

Page 94: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

d.

General List name - specifies the name of the list orlibrary on the SharePoint server from which thesystem loads the items.

Selection Field nameField typeField value

Properties in the section allowSelectionyou to specify which items the systemretrieves from the SharePoint server. Toachieve this, you can also use the Queryproperty in the section.Advanced

Properties in the section areSelectionoptional.

Page 95: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

d.

e.

f.

Advanced Relative URL of listed folder - allows you tospecify the server-relative URL of theSharePoint folder within a list or library.

If blank, the system lists the root folder.If the list or library does not supportfolders, keep blank.

Retrieval mode - allows you to specify whetherthe system retrieves files and folders, or onlyfiles. The system supports inclusion ofsubfolders.

Some lists and libraries do not supportfolders. In such case the listing of foldersor inclusion of subfolders has no effect.

Row limit - allows you to specify the maximumnumber of items (data rows) that the systemretrieves.Query - allows you to enter a conditiondetermining which items the system retrieves.You can use this property to change the items'order, too.

                           Retrieved fields - allows you to specifySharePoint list or SharePoint library fieldnames (internal names) that the systemretrieves. Separate the names by semicolons,or keep blank to retrieve all fields.

(Optional) You can specify web part properties in the section. See forSystem settings Configuring cachingmore details.

                                                                     (Optional) Select the property available in the section to display information suitableShow debugging information Debugfor debugging.

                             Click .Save & Close

You need to enter an inner XML ofCAML Query element. See a samplequery:

<Where> <Eq> <FieldRefName="ID"/><ValueType="Counter">1</Value> </Eq></Where><OrderBy> <FieldRefName="Modified"Ascending="false" /></OrderBy>

Properties in the section areAdvanced optional.

If selected, the system displays the SharePoint data in a table. The system informs you whether the data isretrieved from the SharePoint server, or from the system cache.

Debugging allows you to look for fields that contain valuable information, and are suitable for displaypurposes.

Page 96: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1. 2. 3. 4.

1. 2. 3.

4. a.

b.

You have configured the SharePoint integration web part. Because this web part serves as a data source for the SharePoint data, to display, you now need to add a content displaying web part to the same page.the data

 

 

Configuring SharePoint integration settingsYou can configure the system to cache files downloaded from a SharePoint server.

Open the application.SettingsSelect the category.Integration -> Microsoft SharePointEnter values into the and settings.Cache timeout (minutes) File size limit (kB) Click Save.

Within the specified time, the system caches all downloaded SharePoint files up to the specified size limit.

   

Displaying SharePoint data in KenticoThe system uses the web part to retrieve the requested SharePoint data, and displays this data SharePoint data source through another we

, e.g. the web part. placed on the same pageb part Basic repeater

The web part loads the data based on:SharePoint data source

specified SharePoint server connection

-AND-

specified data retrieval mode.

Displaying SharePoint data in Kentico

To display SharePoint data on a Kentico website, you need to:

Configure a SharePoint integration connection.Configure the web part.SharePoint data sourceAdd a content displaying web part into a page containing the web part.SharePoint data source

You can use the web part.                             Basic repeaterConfigure the content displaying web part.      

Specify the data source.The data source name must be the value of the property of the webWeb part control ID SharePoint data sourcepart.

Specify the .                                                  transformation                 

How it works - API

The system uses the web part to retrieve a data source object (DataSet), which contains a table with theSharePoint data sourcerequested SharePoint data. Another web part that uses the SharePoint web part as its data source, for example the Basic

web part, then displays the SharePoint data on the page through a selected transformation.repeater

Based on configuration of the web part, the system loads the data using the corresponding SharePointSharePoint data sourceintegration service.

SharePoint integration API uses the namespace.CMS.SharePointThe system contains a factory class for each supported SharePoint version, implementing the ISharePointServiceFactor

interface.yThe system gets the factory object corresponding to the target SharePoint version using the SharePointServiceFactoryP

method.rovider.Current.GetSharePointServiceFactoryTo create an instance of the required SharePoint service, the system calls the GetImplementationFor<ISharePointServi

method of this factory object.ce>

These settings can be overridden in the applied using optional parameters of the method.transformation GetSharePointFileUrlSee for more details.Displaying SharePoint data in Kentico

The settings available in the section are used by the legacy SharePoint web parts, and are consideredGeneral - related to...obsolete. Do not configure these settings unless you use the legacy SharePoint web parts.

Configuring SharePoint integration settings (obsolete) describes how to configure these settings.

Page 97: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

4.

If you now preview the page, the system displays the requested SharePoint data.

Example

 In the above example, the content displaying web part uses the following custom transformation.Picture library items

<h2><%# Eval("Title") %></h2><p><%# Eval("Description") %></p><%-- 'Author' is a lookup field containing ID and value separated by semicolon.--%>Author: <%# Eval("Author").ToString().Split(new[]{';'})[1] %><br />(Created on: <%# Eval("Created") %>)<br /><img src="<%# GetSharePointImageUrl() %>" /><h5>Keywords</h5><%# Eval("Keywords") %>

Based on the transformation definition and configuration of the web part, the system displays the following SharePoint data sourceSharePoint item information:

titledescriptionauthor (preceded by ' '; consists of and , separated by a backslash)Author: domain name user namedate of creation (in brackets; preceded by ' ')Created on:image filekeywords (preceded by the ' ' heading)Keywords                     

Available methods

The system allows you to call from the transformation the following methods with optional parameter values:

You can find SharePoint transformations in while editing the page typePage types -> Page types SharePoint - Transformationson the tab.Transformations

You can customize these transformations, and you can also add your custom ones.

See  for further details.Creating transformations for pages

Page 98: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

GetSharePointFileUrl()GetSharePointImageUrl()

If you need to resize images and control their caching, use the method. This is because the method's respectiveGetSharePointFileUrl()parameter values override the as configured in .settings Settings -> Integration -> Microsoft SharePoint -> Cache

GetSharePointFileUrl()

The full syntax of the method isGetSharePointFileUrl()

public string GetSharePointFileUrl(string fileRefColumnName = null, int?cacheMinutes = null, int? cacheFileSize = null, int? width = null, int? height =null, int? maxSideSize = null)

Parameter name Default value if not specified Description

fileRefColumnName "FileRef"  Specifies the name of the columncontaining the name of the file. 

cacheMinutes configured in Settings -> Integration ->Microsoft SharePoint -> Cache

Specifies how long the file is cached on theweb server machine.

cacheFileSize configured in Settings -> Integration ->Microsoft SharePoint -> Cache

Files bigger than kB are notcacheFileSizecached. For resized images, the size of theresized image is used.

width none Only affects images. The system resizesthe image to have maximum width equal to 

in pixels.width

height none Only affects images. The system resizesthe image to have maximum height equal to

in pixels. height

maxSideSize none Only affects images. The system resizesthe image to have maximum side sizeequal to in pixels.maxSideSize

Implementation example Description

<%# GetSharePointFileUrl() %>The system caches the files as configured in Settings ->

. The name of theIntegration -> Microsoft SharePoint -> Cachecolumn containing the name of the file is , which can beFileRefused, for example, while working with picture libraries.

<%#GetSharePointFileUrl("NameOfColumnContainingPathToFile") %>

The system caches the specified files as configured in Settings ->.Integration -> Microsoft SharePoint -> Cache

<%#GetSharePointFileUrl("NameOfColumnContainingPathToFile", 5, 1024) %>

The system caches the specified files up to the size of 1024 KB for5 minutes.

GetSharePointImageUrl()

The full syntax of the method isGetSharePointImageUrl()

public string GetSharePointImageUrl(string fileRefColumnName = null, int? width =null, int? height = null, int? maxSideSize = null)

Page 99: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1. 2. 3.

Parameter name Default value if not specified Description

fileRefColumnName "FileRef"  Specifies the name of the columncontaining the name of the image. 

width none The system resizes the image to havemaximum width equal to  in pixels.width

height none The system resizes the image to havemaximum height equal to in pixels. height

maxSideSize none The system resizes the image to havemaximum side size equal to imaxSideSizen pixels.

Implementation example Description

<%# GetSharePointImageUrl() %>The system caches the images as configured in Settings ->

. The name of theIntegration -> Microsoft SharePoint -> Cachecolumn containing the name of the image is , which can beFileRefused, for example, while working with picture libraries.

The system does not resize the images.

<%#GetSharePointImageUrl("NameOfColumnContainingPathToFile") %>

The system caches the specified images as configured in Settings.-> Integration -> Microsoft SharePoint -> Cache

The system does not resize the images.

<%#GetSharePointImageUrl("NameOfColumnContainingPathToFile", null, 200)%>

The system caches the specified images as configured in Settings.-> Integration -> Microsoft SharePoint -> Cache

The system resizes the images to have maximum height of 200pixels. The image width is determined dynamically to preserve theimage aspect ratio.

<%#GetSharePointImageUrl("NameOfColumnContainingPathToFile", null, null,300) %>

The system caches the specified images as configured in Settings.-> Integration -> Microsoft SharePoint -> Cache

The system resizes the images to have maximum size of any side300 pixels.

 

Example - Displaying a SharePoint picture library in KenticoThe example demonstrates how you can display a picture library stored on a SharePoint server on a Kentico website.

The example uses two custom transformations. If the URL of the page where you are viewing the SharePoint data contains a specialparameter value, the system displays the corresponding picture library item. Otherwise, it displays all items from the specified picture librarylist. You specify the name of the parameter in the section of the web part.Selection SharePoint data source

The example uses the sample Corporate Site, and consists of the following parts:

Configuring a SharePoint integration connectionConfiguring the SharePoint data source web partDefining the transformationsConfiguring the Basic repeater web partResult - Viewing the SharePoint data

Configuring a SharePoint integration connection

Open the application.SharePoint connections Click .New connectionEnter the following values for the connection's properties.

Display name: My connection

You can skip any parameter, or you can enter instead.null

Page 100: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

3.

4. 5.

1. 2.

3. 4.

5.

Site URL: Enter the URL of your SharePoint site.SharePoint version: Select the version of your SharePoint server.Based on your system configuration, specify connection properties in the section.                            Authentication

Click .SaveClick Test connection

If the connection is functional, the system displays a notification message in green color.

The system creates a new SharePoint connection.

You can now use the connection while configuring the .SharePoint data source web part 

Configuring the SharePoint data source web part

Open the application.PagesSelect a page in the content tree.

You are selecting a page where the system will display the requested SharePoint data.Switch to the tab.DesignAdd the web part to the selected web part zone.SharePoint data source

The system opens the dialog window.Web part properties (SharePoint data source)The dialog window allows you to specify web part properties.

Configure the web part.SharePoint data sourceConnection: My connectionRetrieve: Specified list's itemsList type: Picture libraryList name: Here you need to specify the name of the SharePoint picture library list whose items you want to display.Field name: ID

The value is the internal name of the SharePoint column the system uses for item(s) selection.Field type: CounterField value: {? selection ?}

If the URL of the current page contains the parameter, the system selects from the specified picture libraryselectionlist the item whose column contains the value.ID selectionIf the URL of the current page does not contain the parameter, the system lists all items from the specifiedselectionpicture library list.

Retrieval mode: List files only                    

Page 101: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

5.

6.

1.

2. 3. 4.

5.

                         Click .Save & Close

The system closes the dialog window.Web part properties (SharePoint data source)

The page where you want to display the SharePoint data now contains the web part. Next, you need to define the SharePoint data source tr, and add the web part to the same page.ansformations Basic repeater

Defining the transformations

Open the application.Page types

Edit ( ) the page type on the tab.SharePoint - Transformations TransformationsClick .New transformationEnter the following values for properties of the first transformation.

Transformation name: MyTransformationListingTransformation type: ASCX

Enter the following transformation code.

<h2><a href="<%# "?selection=" + Eval("ID") %>"><%# Eval("Title") %></a></h2><p><%# Eval("Description") %></p>

The transformation lists all items contained in the specified library. The items are displayed as links leading to the itemsdetails.

Page 102: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

5.

6. 7. 8.

9.

10.

1. 2. 3. 4.

5.

                                       Click .SaveGo back to the tab of the page type, and click .Transformations SharePoint - Transformations New transformationEnter the following values for properties of the second transformation.

Transformation name: MyTransformationDetailTransformation type: ASCX

Enter the following transformation code.

<h2><%# Eval("Title") %></h2><p><%# Eval("Description") %></p><%-- 'Author' is a lookup field containing ID and value separated bysemicolon. --%>Author: <%# Eval("Author").ToString().Split(new[]{';'})[1] %><br />(Created on: <%# Eval("Created") %>)<br /><img src="<%# GetSharePointImageUrl() %>" /><h5>Keywords</h5><%# Eval("Keywords") %>

The transformation displays item details.Click .Save

The system adds two custom transformations. One transformation displays a listing of items, the other displays details of a selected item.

Configuring the Basic repeater web part

Open the application.Pages In the content tree, select the page where you placed the web part.SharePoint data sourceSwitch to the tab.DesignAdd the web part to the selected web part zone.Basic repeater

The system opens the dialog window.Web part properties (Basic repeater)The dialog window allows you to specify web part properties.

Configure the web part.Basic repeaterData source name: SharePointDataSourceV2

You need to enter the value of the property of the web part.Web part control ID SharePoint data sourceTransformation name: MyTransformationListingSelected item transformation: MyTransformationDetail                             

Page 103: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

5.

6.

1. 2.

3.

                                         Click .Save & Close

The system closes the dialog window.Web part properties (Basic repeater)

You have configured the system to display the requested SharePoint data retrieved through the web part. You canSharePoint data sourcenow view this data on your website.

Result - Viewing the SharePoint data

Open the live website.Go to the page where you placed the and web parts.SharePoint data source Basic repeater

The system displays all items contained in the specified SharePoint picture library.                   

                                          Click the name of any listed item.

The system displays the details of the selected item.                           

Page 104: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

3.

 

Managing SharePoint librariesUsing the Kentico administration interface, you can manage selected types of SharePoint libraries, and available in thesework with fileslibraries.

The system allows you to work with files from:

SharePoint picture libraries,SharePoint document libraries.

Managing SharePoint libraries

To manage SharePoint libraries in Kentico, use the application. The  allows you to select libraries available inSharePoint applicationSharePoint, and open them in the Kentico administration interface. You can then work with files contained in these libraries as if you weredirectly connected to SharePoint.

To manage SharePoint libraries, use the following basic actions:

Edit ( ) - opens the SharePoint library editing interface, where you can view and modify library details and manage the containedfiles.

You can modify general properties of the library, e.g. its display name.You can modify the period when the system automatically reflects in Kentico any changes made to the content of the libraryin SharePoint (the property). To ensure correct functionality, other properties related toSynchronization periodsynchronization cannot be modified.

Delete ( )

Deleting connections to SharePoint

If you delete from the application a connection used in the definition of a SharePoint library inSharePoint connections Kentico (i.e. a connection used in the library's property), you can no longer synchronize the library.Connection

The downloaded content is further available but read-only, which means you can access the listed files (i.e.download the files to your computer or mobile device, and view images) but cannot update them or add new ones.

Deleting SharePoint libraries

If you delete a SharePoint library from the application in Kentico, the library is not affected in SharePoint. ToSharePoint delete libraries from SharePoint, you need to delete these libraries directly in SharePoint.If you delete a library from SharePoint, the library remains available in the application in Kentico but cannot beSharePoint synchronized. This means you can further access the already downloaded files but cannot update the files or add newones.

If you delete a library from SharePoint by moving it to the SharePoint recycle bin, the library cannot besynchronized with Kentico until restored in SharePoint.

Page 105: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1. 2. 3. 4.

                SharePoint library properties

Section Properties

General Display name - the name of the SharePoint library used inthe system's administration interface, e.g. in the list ofavailable SharePoint .librariesCode name - the string identifier of the SharePoint libraryobject used by developers in the code. Unless there is areason to set a particular value, you can leave the default (a

option, and the system generates an appropriateutomatic)code name.

Synchronization Connection - specifies a connection to SharePoint.You need to select a connection from connections avail

in the application.able SharePoint connections Library type - specifies the type of the SharePoint library.

You can use SharePoint picture libraries and documentlibraries.

Library name - specifies the name of the library asavailable in SharePoint.Synchronization period - specifies how often the systemautomatically checks the current state of the library inSharePoint and reflects the changes in Kentico.

                        

Adding SharePoint libraries

To add a new SharePoint library:

Open the application.SharePoint Click .Add SharePoint libraryEnter the SharePoint library properties.Click .Save

The system adds the library to the list of available SharePoint libraries, and starts downloading the files based on a newly added scheduled. You can carry on working with the system until the download has finished.task

When the files are downloaded to Kentico, they become available for viewing and downloading to your computer or mobile device. See Worki.ng with files from SharePoint libraries

Synchronizing SharePoint libraries

How synchronization of SharePoint libraries works

All changes that you make in Kentico to the content of SharePoint libraries take effect in Kentico and SharePoint at the same time.All changes made in SharePoint to the content of SharePoint libraries available in Kentico are reflected in Kentico with delay.

Changing the period when the system automatically reflects changes made in SharePoint

Page 106: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1.

2. 3. 4. 5.

1.

2.

3.

To change the period when the system automatically checks the current state of a selected library in SharePoint and reflects the changes inKentico:

Open the application.SharePoint

Edit ( ) a library.Switch to the tab.GeneralChange the value of the library's property as required.Synchronization periodClick .Save

The system now automatically checks the current state of the library in SharePoint and reflects the changes in Kentico at the new interval.

Manually reflecting changes made in SharePoint

To get the system to check the current state of a selected library in SharePoint and reflect the changes in Kentico instantly:

Open the application.SharePoint

Edit ( ) a library.The system opens the library on the tab.Files

Click .Synchronize

The system removes from the library all files deleted in SharePoint since the last synchronization (either automatic or manual) and startsdownloading ones that have been added to and modified in SharePoint since the last synchronization (either automatic or manual). You cancarry on working with the system until the download has finished. 

Working with files from SharePoint librariesThe application allows you to manage files contained in available SharePoint libraries. Using this application, you can: SharePoint

Access files from SharePoint librariesInsert files into SharePoint librariesUpdate files in SharePoint librariesDelete files from SharePoint libraries

                                                                  

Accessing files from SharePoint libraries

You can access files from SharePoint libraries in Kentico after the system finishes downloading content of these libraries from SharePoint.For each SharePoint library, the download of the contained files to Kentico starts when you add the library to the application.SharePoint

Later on, the system periodically checks if changes have been made to the libraries in SharePoint and reflects these changes in Kentico.

By default, the system checks if changes have been made in SharePoint to the content of available libraries every 12 hours.

If any such changes are identified, the system automatically removes from the libraries all deleted files and starts downloadingones that have been added and modified.

In the application, you can work with files:SharePoint

allowed in SharePoint

-AND-

allowed in Kentico, as specified in .Settings -> System -> Files                    

Working with locked or checked-out files, same as with files under a workflow is not supported.

You can change the period when the system automatically checks the current state of the libraries in SharePoint and reflects thechanges in Kentico.

Page 107: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1.

2.

3.

1.

2.

3.

1.

2.

3.

4.

5.

1.

2.

3.

4. 5.

1.

2.

3.

4.

When the system finishes downloading the files from SharePoint, you can download any of the files to your computer or mobile device.Besides, you can view images (if available).

Viewing images

To view images from available SharePoint libraries:

Open the application.SharePoint

Edit ( ) a library.The system opens the library on the tab and displays available files.Files

Click ( ) next to a selected image to view the image.ViewThe action is available only for image files.

The system displays the image.

Downloading files

To download files from available SharePoint libraries to your computer or mobile device:

Open the application.SharePoint

Edit ( ) a library.The system opens the library on the tab and displays available files.Files

Click ( ) next to a selected file to download the file to your computer or mobile device.Download

If you now modify the file, you can its existing version with the current version in the library.replace

Inserting files into SharePoint libraries

To insert files into a selected SharePoint library using the Kentico administration interface:

Open the application.SharePoint

Edit ( ) a library.The system opens the library on the tab, showing a list of all available files.Files

Click .Add filesThis opens a standard file selection dialog.

Select one or more files.You need to select files of supported types, i.e. documents and images.Selecting files of unsupported types results in a failure during upload of the files.

Click .Open

The system starts uploading the files to SharePoint. When the upload to SharePoint is finished, the files are available in the library in bothSharePoint and Kentico.

Updating files in SharePoint libraries

To update files in SharePoint libraries:

Open the application.SharePoint

Edit ( ) a library.The system opens the library on the tab, showing a list of all available files.Files

Click ( ) next to a selected file.UpdateThis opens a standard file selection dialog.

Select the current version of the file, or a different file.Click .OK

The system starts uploading the selected file to SharePoint. When the upload to SharePoint is finished, the file is available in the library inboth SharePoint and Kentico.

Deleting files from SharePoint libraries

To delete a file from a selected SharePoint library using the Kentico administration interface:

Open the application.SharePoint

Edit ( ) a library.The system opens the library on the tab, showing a list of all available files.Files

Click ( ) next to a selected file.DeleteThis opens a confirmation dialog.

Click .OK

The system deletes the file from the library in both Kentico and SharePoint, where it is moved to the recycle bin. This means you can later

You can also get the system to reflect in Kentico any changes made to the libraries in SharePoint instantly.

See for more details.Managing SharePoint libraries

Page 108: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

restore the file in SharePoint.

If you restore the file from the recycle bin in SharePoint, it is instantly available in SharePoint. However, in Kentico it is available only after sy with SharePoint, i.e. with delay.nchronization

 

SharePoint integration (obsolete)Kentico allows you to access data stored on a SharePoint server (Windows SharePoint Services 3.0 (WSS) or MOSS - Microsoft OfficeSharePoint Server) and display it on your website. You can achieve this by using the .SharePoint integration web parts (obsolete)

SharePoint integration examples (obsolete) contain sample tutorials on using the SharePoint web parts for various tasks.

You can configure default logon settings, used to access a SharePoint server, as described in Configuring SharePoint integration settings.(obsolete)

What you can do

Get lists and list item data from SharePoint and provide it to Kentico.Download documents or images.

What you cannot do

Modify SharePoint data.Display Kentico data in SharePoint.

 

How SharePoint integration works

SharePoint web parts use pre-generated proxy classes of selected SharePoint web services to get data from the server. The followingservices are used:

http://server/_vti_bin/Lists.asmx - methods for working with lists.http://server/_vti_bin/Imaging.asmx - methods for working with picture libraries.http://server/_vti_bin/Copy.asmx - methods for retrieving file content.

The returned data is in CAML (XML) format, which needs to be further processed to display the data in a meaningful way. You can use XSLTor ASCX for this purpose. For ASCX, the CAML response must be transformed to an ASP Dataset.transformations 

SharePoint integration web parts (obsolete)Web parts for connecting to SharePoint are stored in the category of the web part catalog:Microsoft SharePoint

SharePoint data sourceSharePoint datagridSharePoint datalistSharePoint repeater

The following text contains information about the properties of these web parts.

SharePoint

All web parts in the  category have the following properties:Microsoft SharePoint

Mode - determines what the web part does (what data is retrieved from the SharePoint server) and therefore which web serviceshould be used.SharePoint site URL - specifies the URL of the SharePoint site that should be used. Based on the value of the property, theModefull URL of the required web service is determined by this option (it is not configured directly).Username, Password - you can specify the username and password for authentication directly in the web part properties, or inheritglobal values from If you want to use the credentials from the , leave theSettings -> Integration -> Microsoft SharePoint. settingsfields empty.List name - if you use the or options, you must specify the list from which the items shouldDisplay list items Display list of picturesbe loaded. In the other two modes, you can leave it empty.

The web part displays the data and the web part provides the data, if properties in the SharePoint datagrid SharePoint datasource Share section are configured correctly.Point

                       

Transformations

The web part and web part need to have a specified in order to display theSharePoint datalist SharePoint repeater transformationretrieved data.

The system provides a number of pre-defined transformations. You can modify these transformations according to your needs. The

The field is case sensitive.List name

Page 109: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

transformations are stored under the page type (you can edit the page type in the application).SharePoint - Transformations Page typesThe names of the transformations correspond to the intended purpose.

Before you start using the transformations, you need to  used on yourreplace the sample server or field names with the real names SharePoint server.

Advanced

In the section, you can specify (limit) the data you want to retrieve. The properties only apply in the mode.Advanced Get list items

Row limit - sets the maximum number of retrieved items.Query - filters or sorts the returned items. Its purpose is similar to that of a WHERE condition in SQL, but has a completely differentsyntax based on CAML. For more information on how to construct such queries, search SharePoint documentation or use Googlewith keywords like "SharePoint query".View fields - directly specifies which fields (columns) of a SharePoint list should be retrieved.

Display

In the section, you can control how the system processes and displays the retrieved data.Display

Selected item querystring key name - if specified, items are selected based on the presence of this key in the URL query string.Selected item field name - allows you to specify a field used to select items. The default approach is to select items by ID - the webpart tries to get the query string parameter specified in the property and uses its value. ForSelected item querystring key name example, if you enter into the property above, selects the item with in its ID field.id aspx?id=2 2

                             Selected item field type - specifies the type of the field. For IDs, use the type. For strings, use the type. TheseItemID Counter Texttwo are sufficient in most cases, but you can search SharePoint documentation for other types.Use dataset - if enabled, the retrieved XML data is converted to a dataset that can be used with standard ASCX transformations. Ifdisabled, the data is not modified and can be converted directly to HTML using XSLT.Dataset fields - if you want to use the dataset format but you don’t need all fields, you can specify which fields should be included inthe dataset by entering their names separated by semicolons. This property can be particularly useful if you want to use caching.

Debug

Because it is sometimes hard to tell or remember how SharePoint addresses list fields, we implemented the functionalitShow raw responsey. It displays all retrieved SharePoint data in its raw XML form. You can look for fields which contain valuable information and can bedisplayed.

 

SharePoint integration examples (obsolete)This page demonstrates how you can use SharePoint integration in Kentico:

Site hierarchy - learn how you can display site lists.List items - learn how you can display items from lists.Picture libraries - learn how you can retrieve picture library type lists.List of pictures - learn how you can display pictures from picture libraries.

Site hierarchy

This section describes how you can display site lists resembling the site hierarchy panel on a SharePoint site.

The original field name is used here - without the prefix.ows_

This field is case sensitive.

Properties in the section are not available for the web part.Display SharePoint datagrid

If the data is fetched from the cache, the response cannot be printed.

Page 110: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

Add one of the SharePoint (e.g. the web part) into a page, and configure the web part in the following way:web parts SharePoint repeater

SharePoint site URL - enter the URL of your SharePoint server.Username and - enter your username and password, or leave the fields empty if you configured them in Password Settings ->

.Integration -> Microsoft SharePointMode: Display site listsTransformation - the system provides a transformation for displaying site hierarchies called , which you can find underSiteHierarchythe page type. For correct behavior, you need to edit the transformation and change the name of theSharePoint - Transformations SharePoint server in the transformation code.

Leave the default values for the remaining properties and click . The system creates a link to each of the lists on the SharePoint server.OK

 

List items

Using the mode, you can display items from any list from the SharePoint server.Display list items

The example uses a custom SharePoint list called . The list stores information about company customers in fields such as Customers Custom, , , , etc. You want to display data from this list on your Kentico website.er name Street City Phone

Page 111: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

Add one of the SharePoint  (e.g. ) into a page:web parts SharePoint repeater

1. Configure the web part in the following way:

SharePoint site URL - enter the URL of your SharePoint server.Username and - enter your username and password, or leave the fields empty if you configured them in Password Settings ->Integration -> Microsoft SharePoint.Mode: Display list itemsTransformation - the system provides a transformation for displaying item lists called , which you can find under the ListItems Share

page type. For correct behavior, you need to edit the transformation and change the name of the SharePointPoint - Transformations server in the transformation code.Show raw response: enabled; this is because you need to inspect the retrieved data and change the transformation to suit yourneeds.

Leave the default values for the remaining properties and click . You should see a result similar to the screenshot below.OK

To see the customers' name and city, look into the raw output and search for the respective fields. You can find them under the ows_Custom and attributes.erName ows_City

2. Now that you know the names of the attributes, you need to edit the transformation code or create a new transformation.

Replace the original transformation:

<%# Eval("ows_Title") %> (<%# Eval("ows_Created")%>) <br />

with something like this:

<%# Eval("ows_CustomerName") %> - <%# Eval("ows_City")%> <br />

The output now displays the desired values.

Page 112: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

3. To click individual items and see more details, you need to prepare the . The transformation may look likeSelected item transformationthe following code sample:

<strong><%# Eval("ows_CustomerName") %></strong><br/><%# Eval("ows_City")%> <br/><%# Eval("ows_Street")%> <br/><%# Eval("ows_Phone")%> <br/> 

4. In the web part properties, enter the name of the field by which you want to select items. In this case, it is the field. In the raw responseIDoutput, you can see it as . Enter the following values:ows_ID

Selected item querystring key name: idSelected item field name: IDSelected item field type: Counter

Finally, alter the original transformation to suit the values you entered. This means you need to create a link to customer details using the pidarameter in the query string. It can look like this:

<a href="<%#CMS.Helpers.URLHelper.AddParameterToUrl(CMS.Helpers.RequestContext.RawURL, "id",(string)Eval("ows_ID")) %>"><%# Eval("ows_CustomerName") %> - <%# Eval("ows_City")%> </a><br />

The final result, a simple text list of customers with links, looks like this:

After clicking a customer name, the system displays customer details.

5. Now configure the settings. You want that the system displays a maximum of 10 customers. Besides, the displayed customersAdvanced are from only.Queens

Enter number 10 into the field and use this code as the :Row limit Query

<Query><Where><Eq><FieldRef Name="City" /><Value Type="Text">Queens</Value></Eq></Where> </Query>

The tag means equals, the field name is , and its value of type equals to .<Eq> City Text Queens

Page 113: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

Click . Now you should see the filtered output as in the following screenshot:OK

Picture libraries

This section describes how you can use SharePoint to retrieve only a picture library type list. To achieve this, you need to configure thefollowing properties:

SharePoint site URL - enter the URL of your SharePoint server.Username and - enter your username and password, or leave the fields empty if you configured them in Password Settings ->

.Integration -> Microsoft SharePointMode: Display picture librariesTransformation - the system provides a transformation for displaying picture libraries called , which you can findPictureLibListsunder the page type. For correct behavior, you need to edit the transformation and change the nameSharePoint - Transformationsof the SharePoint server in the transformation code.

Leave the default values for the remaining properties and click . You should see a result similar to the screenshot below. The systemOKdisplays a list of picture libraries with links to the SharePoint server.

List of pictures

The mode allows you to display pictures from picture libraries on a SharePoint server.Display list of pictures

The example uses a SharePoint picture library called . To display the pictures on your Kentico website, you need to enter theImagesfollowing properties while configuring a suitable web part (for example, the web part):SharePoint repeater

SharePoint site URL - enter the URL of your SharePoint server.Username and - enter your username and password, or leave the fields empty if you configured them in Password Settings ->

.Integration -> Microsoft SharePointMode: Display list of picturesList name: Images

Page 114: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

Transformation - the system provides a transformation for displaying picture lists called , which you can find under the Pictures Sharpage type. For correct behavior, you need to edit the transformation and change the name of theePoint - Transformations

SharePoint server in the transformation code.

Leave the default values for the remaining properties and click . You should see a result similar to the screenshot below.OK

The transformation code looks like this:

<%# SharePointFunctions.SplitSharePointField((string)Eval("ows_FileLeafRef"),1)%><br/><img src="<%# SharePointFunctions.GetSharePointFileUrl("tester4",SharePointFunctions.SplitSharePointField((string)Eval("ows_FileRef"),1))%>&maxsidesize=200" /> <br />

The system downloads the images through the page, same as documents. So you need to create in theGetSharePointFile.aspxtransformation tags with attributes pointing to this page. For ease of use, the system provides the method<img> src GetSharePointFileUrlin the class, which takes two parameters and returns the URL that downloads the file. The first parameter is theSharePointFunctionsserver name (or website URL), the second one is the location of the file in SharePoint. The final URL looks like this:

~/CMSModules/Sharepoint/CMSPages/GetSharePointFile.aspx?server=server_name&name=Images/Sunset.jpg

The system provides another useful method in the class called . SharePoint, for some reason,SharePointFunctions SplitSharePointFieldcreates combined attribute values for certain fields, for example, .ows_FileLeafRef="2;#Blue hills.jpg"

However, you often need to use only a part of such a value. The method serves the purpose. The first argument is aSplitSharePointFieldcombined value and the second one is the index of the part you want to have in the output.

The GetSharePointFile.aspx page

The page is a special page located in the directory in your KenticoGetSharePointFile.aspx ~/CMSModules/Sharepoint/CMSPagesinstallation. The correct URL to access the page is:

~/ CMSModules/Sharepoint/CMSPages/GetSharePointFile.aspx?server=server_name&name=Images/Sunset.jpg

The page downloads a specified file from the SharePoint server and sends it further to the user. The credentials that you configured in Settin are used for authentication by the web service. You can control the Content-Disposition HTTPgs -> Integration -> Microsoft SharePoint

header using the query parameter.disposition

The credentials from the settings are always used for downloading the file when the page is used.GetSharePointFile

Page 115: Kentico 8 · Kentico 8.2. 1. Integrating 3rd ... 1.4 Using Kentico API and Controls externally ...

1. 2. 3. 4.

Images

The page supports , and parameters to control the size of the image, and the Kentico cache is used. You canmaxsidesize width heightconfigure the in : , .cache Settings -> System -> Performance Cache files (minutes) Client cache (minutes)

Servers

You can specify servers that the system can retrieve the files from. Enter names of the servers, separated by semicolons, into the Allowed setting in .servers Settings -> Integration -> Microsoft SharePoint

 

Configuring SharePoint integration settings (obsolete)You can configure the default logon credentials used to access the SharePoint server:

Open the application.SettingsSelect the category.Integration -> Microsoft SharePointEnter values into the and settings.Username PasswordClick Save.

The credentials are used by default if you leave the and properties blank for the SharePoint web parts.Username Password

 

The settings configured in are automatically used for authentication by the Settings -> Integration -> Microsoft SharePoint GetS page, and the URL to access the page can be entered manually.harePointFile.aspx

That's why we recommend that you enter the credentials of a user authorized to access only the files you want to display on yourwebsite.

If you enable the setting, the system uses the current user's Windows domain credentials to accessUse Windows Authenticationthe SharePoint server.

You must specify the address of the respective SharePoint server in the properties of the SharePoint web parts.

The automatically uses the credentials from the settings for authentication.GetSharePointFile.aspx page

Users can access the page manually by entering the URL. We therefore recommend that you enter the credentials of a user who isauthorized to access only files that you want to display on your website.