Using .NET code in your Tridion Templates

Introduction

This article shows you how to create template code in .NET (using C#) and then make it available to your Tridion Templates.

Prerequisites

Installed and configured Tridion Content Manager.

1. Creating your code

Using Visual Studio (.NET 2003 or 2005) create a new project. For simplicity reasons we'll just call it Templates.

Now, let's create a very simple method you could use in your templates:

using System; 
using System.Collections.Generic; 
using System.Text; 

namespace Templates 
{ 

public    class    Code 
{ 

public    string TurnToBold( string input) 
{ 

return    "<strong>"   string   "</strong>" ; 

} 

} 

}

As you can easily see, this method will magically transform any string that is passed to it to XHTML-compliant BOLD strings!

Next, we'll see how you can use this code from within your Tridion templates.

2. Making your code visible to COM

In order to use your classes from within Tridion, you must make it visible to COM. Follow the next steps to do this:

1st, tell Visual Studio you want it to be available to COM by going to Project -> <ProjectName> Properties -> Build and selecting "Register for COM Interop" (this might be differently worded in Visual Studio .NET 2003, but it is in the same location).

2nd, tell .NET which ProgID should your code use so that you can set some VBScript object to an instance of that class by adding the following code before the class declaration:

 [System.Runtime.InteropServices.ComVisible( true)]
 [System.Runtime.InteropServices.ProgId("Templates.Code")]

This will give your code a ProdId of "Templates.Code". You can of course use any other word.

Compile your code at this stage.

3. Telling Tridion where to find your code

If you're running Visual Studio on the same machine where Tridion is installed your assembly will already be registered for COM Interop. If this is not the case, you can use regasm to register it.

Now, open the Tridion MMC Snap-In and browse to Tridion -> Content Manager Settings -> Script Extensions. You should see a SiteEdit script extension (if SiteEdit has been installed) and nothing else.