Kentico CMS 7.0 Developer's Guide

Registering custom macro methods

Registering custom macro methods

Previous topic Next topic Mail us feedback on this topic!  

Registering custom macro methods

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

In addition to the macro methods available by default, you can also define your own custom methods. Users can then call these methods in their macro expressions.

 

Code samples

 

The Kentico CMS installation includes code examples of custom macro method registration that you can add directly to your web project. To access these samples:

 

1. Open your Kentico CMS installation directory (by default C:\Program Files\KenticoCMS\<version>).

2. Expand the CodeSamples\App_Code Samples\ sub-directory.

3. Copy the Samples folder into the App_Code folder of your web project.

 

 

InfoBox_Exclamation

 

Web application installations

 

If your Kentico CMS project was installed in the web application format, copy the samples into the Old_App_Code folder instead.

 

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

 

1. Open your application in Visual Studio.

2. Click Show all files at the top of the Solution Explorer.

3. Expand the Old_App_Code folder, right-click the new Samples sub-folder and select Include in Project.

 

You can find the macro method examples in the following classes:

 

Samples/Classes/CustomMacroMethods.cs - class containing the sample macro methods.

Samples/Modules/SampleMacroModule.cs - initializes the custom method registration.

 

Creating custom macro methods

 

1. Open your web project in Visual Studio and add a new class into the App_Code folder (or Old_App_Code if the project is installed as a web application). For example, name the class CustomMacroMethods.cs.

 

2. Edit the class and add the following references:

 

[C#]

 

using CMS.SettingsProvider;
using CMS.GlobalHelper;

 

3. Implement all overloads of your custom method, so that it performs the required functionality and returns the correct value.

 

[C#]

 

/// <summary>
/// Appends "default" to the specified string.
/// </summary>
public static string MyMethod(string param1)
{
    return MyMethod(param1, "default");
}
 
/// <summary>
/// Concatenates two strings.
/// </summary>
public static string MyMethod(string param1, string param2)
{
    return param1 + " " + param2;
}

 

4. Create a wrapper suitable for registration as a macro method. The signature and return type of the wrapper method must be exactly the same as shown in the following code:

 

[C#]

 

/// <summary>

/// Wrapper for MyMethod suitable for registration as a macro method.

/// </summary>

/// <param name="parameters">Parameters of the method</param>
public static object MyMethod(params object[] parameters)
{
    switch (parameters.Length)
    {
        case 1:
            // Overload with one parameter
            return MyMethod(ValidationHelper.GetString(parameters[0], ""));

 
      case 2:
          // Overload with two parameters
          return MyMethod(ValidationHelper.GetString(parameters[0], ""), ValidationHelper.GetString(parameters[1], ""));

 
        default:
            // No other overload is supported
            throw new NotSupportedException();
    }
}

 

5. (Optional) Add another method with an additional MacroResolver parameter:

 

[C#]

 

public static object MyComparisonMethod(MacroResolver resolver, params object[] parameters)
{  
  switch (parameters.Length)
   {
      case 2:
          // Compares the string parameters. Ignores case if the resolver is not case sensitive.
          return ValidationHelper.GetString(parameters[0], "").EqualsCSafe(ValidationHelper.GetString(parameters[1], ""), !resolver.IsCaseSensitiveComparison);
 
      default:          
          throw new NotSupportedException();
   }
}

 

The parameter allows you to access the macro resolver used for the context in which the method was called. The sample method above checks if the resolver is case sensitive and then compares the string parameters accordingly.

 

6. Add a registration method for your custom macro methods:

 

[C#]

 

public static void RegisterMethods()
{
  // Registers MyMethod with two parameter overloads.
  MacroMethod myMethod = new MacroMethod("MyMethod", MyMethod)
   {
       Comment = "Returns a concatenation of two strings.",
       Type = typeof(string),
       AllowedTypes = new List<Type>() { typeof(string) },
       MinimumParameters = 1
   };
   myMethod.AddParameter("param1", typeof(string), "First string to concatenate.");
   myMethod.AddParameter("param2", typeof(string), "Second string to concatenate.");      
  MacroMethods.RegisterMethod(myMethod);
 
  // Registers a code snippet for MyMethod.
  MacroMethod myMethodSnippet = new MacroMethod("MyMethodSnippet", MyMethod)
   {
       Comment = "Calls MyMethod for the current user's name in lower case.",
       Type = typeof(string),
       AllowedTypes = new List<Type>() { typeof(string) },
       Snippet = "MyMethod(ToLower(CurrentDocument.DocumentName), |);"
   };      
  MacroMethods.RegisterMethod(myMethodSnippet);

 
  // Registers MyComparisonMethod, which uses a resolver object parameter.
  MacroMethod myComparisonMethod = new MacroMethod("MyComparisonMethod", MyComparisonMethod)
   {
       Comment = "Compares two strings according to resolver IsCaseSensitiveComparison setting.",
       Type = typeof(string),
       AllowedTypes = new List<Type>() { typeof(string) },
       MinimumParameters = 2
   };      
   myComparisonMethod.AddParameter("param1", typeof(string), "First string to compare.");
   myComparisonMethod.AddParameter("param2", typeof(string), "Second string to compare.");
  MacroMethods.RegisterMethod(myComparisonMethod);
}

 

Register each macro method through the following steps:

 

a. Prepare a CMS.GlobalHelper.MacroMethod object representing the custom macro method.

 

The first parameter of the MacroMethod constructor sets the name used for the method in macro expressions.

The second parameter specifies the method delegate (wrapper method) containing the definition in the code.

 

b. Specify the following basic properties:

 

Property

Description

Comment

Comment displayed for the method in the macro autocompletion.

Type

The return type of the method.

Allowed types

List of object types for which the method can be called. Set to null for all types to be allowed. If unspecified, the method is applicable to objects of the type specified for the first parameter.

Minimum parameters

The minimum number of parameters that must be entered when calling the method (minimum overload).

Snippet (optional)

Allows you to define methods with a code snippet. Users can insert the snippet by pressing the TAB key when they have the method selected in the macro autocompletion. Use the pipe character "|" to determine the cursor position after the insertion of the snippet.

 

c. Define the method's parameters one-by-one through the AddParameter method of the MacroMethod object. You must specify the name, data type and comment text of each parameter. When the system needs to resolve the custom method in a macro expression, it passes the values of these parameters to the parameter array of the wrapper method.

 

d. Register the method by calling MacroMethods.RegisterMethod(MacroMethod methodName).

 

Initializing the custom method registration

 

To complete the registration, you also need to ensure that the system calls the RegisterMethods method of the CustomMacroMethods class created in the previous section.

 

1. Create another class in the App_Code folder (or Old_App_Code if the project is installed as a web application). For example, name the class MacroMethodLoader.cs.

 

2. Edit the class and add the following reference:

 

[C#]

 

using CMS.SettingsProvider;

 

3. Delete the default class declaration and its content. Instead, extend the CMSModuleLoader partial class and define a new attribute inheriting from CMS.SettingsProvider.CMSLoaderAttribute:

 
[C#]

 

[MacroMethodLoader]
public partial class CMSModuleLoader
{
    /// <summary>
    /// Attribute class ensuring the registration of custom macro methods.
    /// </summary>
    private class MacroMethodLoader : CMSLoaderAttribute
    {
        /// <summary>
        /// Called automatically when the application starts.
        /// </summary>
        public override void Init()
        {
            // Calls the registration method.
            CustomMacroMethods.RegisterMethods();
        }
    }
}

 

When the CMS application starts, it automatically executes the override of the Init method, which registers your custom methods.

 

Result

 

Your methods are now ready to be used in macro expressions. Open any macro code editor in the Kentico CMS interface and enter a macro with a string data type. The autocompletion box offers the new methods.

 

devguide_clip0401

 

The second parameter in the MyMethod signature (String param2) is displayed in italic letters. This means that the method is overloaded and the parameter is optional.

 

You can also select the MyMethodSnippet method and press the TAB key to insert the defined code snippet.