In this post we’ll continue Nuno’s series on Content Validation and create a GUI Extension using the Anguilla framework to validate a Component’s field content while exploring little-seen Anguilla JavaScript methods to inspect the field content and validate the Save events from the GUI.  Big thanks to Nuno Linhares for writing this article and allowing me to be the Editor.

Solution on Github:  https://github.com/rcurlette/ValidateTitleFieldPart2/

Summary:  Validate that the Component Title field contains an Uppercase letter as the first character after pressing the Save button and show a warning message if a number or lowercase letter is the first character.  We will use Anguilla JavaScript for the field validation.  The estimated time to complete this tutorial is around 90 minutes.  Here is what it will look like in the end:

Overview

  1. Create the Visual Studio Project , Folders and Files (empty)
  2. Create the GUI Extension configuration and setup IIS
  3. Add the Anguilla JavaScript code to Validate the Title Field
  4. Debugging

Create the Visual Studio Project and setup the file structure

We’re going to do this using the CME API (Anguilla) with a javascript alert, and we will extend the following 3 CME commands: “Save”, “Save and Close” and “Save and New”.
Let’s start by creating a Visual Studio Project for our requirements. I tend to start with an Empty Solution, then add the the “Editor” project.  In the next part of this tutorial we will also use a  “Model” project but not in this tutorial. (note that I use the project type “ASP.NET Empty Web Application”).

Delete the first project that Visual Studio always creates.

Now add 1 new project: ValidateTitleFieldEditor

Again, use the “Empty ASP.NET solution” template.

Let’s create the skeleton of our extension. In the Editor project, add the following folders:

  • Commands
  • Config

Under commands, let’s create a file named “ValidateTitleFieldCommand.js” – Visual Studio seems to believe people still use Jscript, let’s not get bothered by it.

Under Config create a file named “ValidateTitleFieldEditor.config”.  This will be used to configure our GUI Extension to ‘listen’ to the Save events.

You should have something similar to this in your project now:

Create the GUI Extension configuration and setup IIS

Here we will add the configuration to the ValidateTitleFieldEditor.config and much of it will not make any sense.  Please follow along and we will be at the fun part in no time.

Open the Configuration ValidateTitleFieldEditor.js file.

If you haven’t learned how to yet, make sure you add the Tridion Schemas to this editor. Right click anywhere on the config file, select properties.

Click on the … button for the Schemas, and add all schemas from [Tridion]\Web\WebUi\Core\Schemas

Tip: you may want to add these schemas to the default Visual Studio schemas, under “C:\Program Files (x86)\Microsoft Visual Studio 10.0\Xml\Schemas”

Let’s build our configuration file with the following:

<?xml version="1.0"?>
<Configuration xmlns="http://www.sdltridion.com/2009/GUI/Configuration/Merge"
               xmlns:cfg="http://www.sdltridion.com/2009/GUI/Configuration"
               xmlns:ext="http://www.sdltridion.com/2009/GUI/extensions"
               xmlns:cmenu="http://www.sdltridion.com/2009/GUI/extensions/ContextMenu">
  <resources cache="true">
    <cfg:filters />
    <cfg:groups>
      <cfg:group name="ValidateTitleField.CommandSet">
        <cfg:fileset>
          <cfg:file type="script">/Commands/ValidateTitleFieldCommand.js</cfg:file>
          <cfg:file type="reference">ValidateTitleField.Interface</cfg:file>
        </cfg:fileset>
        <cfg:dependencies>
          <cfg:dependency>Tridion.Web.UI.Editors.CME</cfg:dependency>
          <cfg:dependency>Tridion.Web.UI.Editors.CME.commands</cfg:dependency>
        </cfg:dependencies>
      </cfg:group>
    </cfg:groups>
  </resources>
  <definitionfiles />
  <extensions>
    <ext:dataextenders />
    <ext:editorextensions>
      <ext:editorextension target="CME">
        <ext:editurls />
        <ext:listdefinitions />
        <ext:taskbars />
        <ext:commands />
        <ext:commandextensions>
          <ext:commands>
            <ext:command name="Save" extendingcommand="ValidateTitleField"/>
          </ext:commands>
          <ext:dependencies>
            <cfg:dependency>ValidateTitleField.CommandSet</cfg:dependency>
          </ext:dependencies>
        </ext:commandextensions>
        <ext:contextmenus />
        <ext:lists />
        <ext:tabpages />
        <ext:toolbars />
        <ext:ribbontoolbars />
      </ext:editorextension>
    </ext:editorextensions>
  </extensions>
  <commands>
    <cfg:commandset id="ValidateTitleField.Interface">
      <cfg:command name="ValidateTitleField" implementation="Company.Extensions.ValidateTitleFieldCommand"/>
    </cfg:commandset>
  </commands>
  <contextmenus />
  <localization />
  <settings>
    <defaultpage />
    <editurls />
    <listdefinitions />
    <itemicons />
    <theme>
      <path />
    </theme>
    <customconfiguration>
    </customconfiguration>
  </settings>
</Configuration>

What are we doing in this configuration?

We’re defining 1 group of files:

<cfg:group name="ValidateTitleField.CommandSet">
        <cfg:fileset>
          <cfg:file type="script">/Commands/ValidateTitleFieldCommand.js</cfg:file>
          <cfg:file type="reference">ValidateTitleField.Interface</cfg:file>
        </cfg:fileset>
        <cfg:dependencies>
          <cfg:dependency>Tridion.Web.UI.Editors.CME</cfg:dependency>
          <cfg:dependency>Tridion.Web.UI.Editors.CME.commands</cfg:dependency>
        </cfg:dependencies>
      </cfg:group>

The group is a “CommandSet” and we’re basically telling Tridion to treat these files as a group, and that the files have dependencies on other Tridion items.

We’re also saying that this extension targets an existing editor: CME

<ext:editorextension target="CME">

 

And within this, we’re extending the “Save” Command with our own CommandSet.  Note:  This is where we wire up to the Save, Save and Close, and Save and New commands.

<ext:commandextensions>
          <ext:commands>
            <ext:command name="Save" extendingcommand="ValidateTitleField"/>
	    <ext:command name="SaveClose" extendingcommand="ValidateTitleField"/>
	    <ext:command name="SaveNew" extendingcommand="ValidateTitleField"/>
          </ext:commands>
          <ext:dependencies>
            <cfg:dependency>ValidateTitleField.CommandSet</cfg:dependency>
          </ext:dependencies>
        </ext:commandextensions>

 

And finally we’re registering a new CME Command:

<commands>
    <cfg:commandset id="ValidateTitleField.Interface">
      <cfg:command name="ValidateTitleField" implementation="Company.Extensions.ValidateTitleFieldCommand"/>
    </cfg:commandset>
  </commands>

That “implementation” attribute is the name of the Anguilla Class that we will use to implement the command.

 

Adding the extension to IIS and registering in Tridion

Let’s add our extension as a Virtual Directory to the CME’s “Editors” folder. I tend to point these directly to my development folder so that all code changes are immediate.

As you can see in the screenshot, the physical path should match the start of your “Editor” project.

Tridion Content Manager Explorer Configuration
The Tridion CME uses a file to hold all the editor and model configurations (plus quite a lot of other settings). You will find this file under [Tridion]\Web\WebUI\WebRoot\Configuration\System.Config

1. Make a backup copy of this file, and edit it with a proper XML Editor (like Visual Studio).
2. Find the Element named “<editors default=”CME”>” (around line 1000 in my system.config).
3. Add one editor configuration element with YOUR values to change the path:

<editor name="ValidateTitleFieldEditor">
      <installpath>D:\Tridion 2011\ValidateTitleField\ValidateTitleFieldEditor</installpath>
      <configuration>Config\ValidateTitleFieldEditor.config</configuration>
      <vdir>ValidateTitleField</vdir>
    </editor>

4. Restart IIS (iisreset) and reload the Tridion Content Manager Explorer.

Summary
We’re done with the boring part.  Now we can have some fun with the JavaScript action and doing something in the GUI.

 

Creating the JavaScript  for the Anguilla Save Event – The Command

Let’s create our Command. Open the “ValidateTitleFieldCommand.js” file.

For now, all that we want is to get our extension loading (and being able to verify it), so let’s add the following code:

Type.registerNamespace("Company.Extensions");

Company.Extensions.ValidateTitleFieldCommand = function ValidateTitleFieldCommand() {
    Type.enableInterface(this, "Company.Extensions.ValidateTitleFieldCommand");
    this.addInterface("Tridion.Cme.Command", ["ValidateTitleFieldCommand"]);
};

Company.Extensions.ValidateTitleFieldCommand.prototype._isAvailable = function ValidateTitleFieldCommand$_isAvailable(selection) {
    console.debug("Is Available called");
    return $cme.getCommand("Save")._isAvailable(selection);
};

Company.Extensions.ValidateTitleFieldCommand.prototype._isEnabled = function ValidateTitleFieldCommand$_isEnabled(selection) {
    console.debug("Is Enabled called");
    return $cme.getCommand("Save")._isEnabled(selection);
};

Company.Extensions.ValidateTitleFieldCommand.prototype._execute = function ValidateTitleFieldCommand$_execute(selection, pipeline) {
    console.debug("Execute called");
    return $cme.getCommand("Save")._execute(selection, pipeline);
};

This implements the _isAvailable, _isEnabled, and _execute functions required for every command. As you can see, all we’re doing is logging that the code was invoked (so we can verify it was loaded) and telling Tridion to go ahead and execute the “Save” Command.  The console.debug statement will write the output the the Firebug Console window or Console window in the Chrome Developer Tools.

We should now have enough to register this (Editor) extension with Tridion. To do this, we need to tell Tridion that we are an extension, and where the configuration for the extension is.

How do I know it’s working?

Well, there’s a few easy ways to do this. If you messed up something, chances are that your CME will look like this:

Open a Javascript console (Firebug is best here) and you’re likely to see this error:
Uncaught ReferenceError: Tridion is not defined

This is very generic, but usually comes with a very useful URL just before it:
http://t2011guruv3/WebUI/Editors/CME/Views/Dashboard/Dashboard_v6.1.0.55920.11_.aspx?mode=js
or http://$$SERVERNAME$$/WebUI/Editors/CME/Views/Dashboard/Dashboard_v$$TRIDION_CME_VERSION$$.$$CONFIGURATION_VERSION$$.aspx?mode=js

URL in FireBug GUI:

Open this url in your browser and you might have a lot more information (Chrome does not show the URL):

In this case, the error is caused because my Editor configuration in System.Config points to a vdir named “ValidateTitleFieldEditor” but the Virtual Directory in IIS is called “ValidateTitleField”. Changing the configuration to specify the correct vdir will fix the issue. If you had a different issue, chances are that opening this url in a browser will give you concrete error messages that should guide you into fixing your problem.

Once you fix your issue you should be able to load both the CME and the JS file:

Tip – if your Javascript is loading minified/obfuscated, you can change this setting.

If you were paying attention to any of this, you should know how to test if your command is being called. If you weren’t, here’s how.

  1. We configured our command as an extension to the “Save” Command (in ValidateTitleFieldEditor.config)
  2. We added 3 functions to our JS – _isAvailable, _isEnabled and _execute
  3. We added a “console.debug” instruction to all those functions.

So basically now we just need to:

  1. Clear your browser cache
  2. Reload the CME
  3. Open a Javascript debug console (I recommend chrome)
  4. Go somewhere in the CME where the Save command would be available (open a page or a component)

If you now open the console you should be able to see something like this:

This confirms our command is being called and our GUI Extension is working.

Now let’s tell our users about their mistake with a popup.  In the popup we will show them a message that the title field needs to start with a Captial letter.  This involves using the Anguilla API to inspect the field’s value when the Save, Save and Close, or Save and New button.

Before moving on, let’s do ‘Save All’ in Visual Studio.  Here’s a neat trick that might help you moving forward.  Instead of opening the project as we have defined now, try doing the following:

  1. Open Visual Studio
  2. Select File -> Open -> Website
  3. Select “Local IIS” on the left side, then search for the “SDL Tridion 2011” website, expand it and select “WebUI”.

Visual Studio is going to ask you if you want to upgrade your configuration to ASP.NET 2.0 – Select ‘No’ – do not ever say yes, unless you can safely claim you know what you’re doing.  If you have not yet saved all files, the first popup will ask if you want to ave files – for this select ‘yes’

Once it’s open you should now see your editor under “Editors”:

This loads the rest of the Tridion CME as well, which will:

  1. Make visual studio pretty slow at times
  2. Give you some small help with some IntelliSense (though you can’t trust the whole of it)

Now that we’re here, we’re going to try reading the current value of the “Title” field in the component you’re trying to save. So, just like with any other Tridion Extension, the first thing we’ll do is make sure we should be executing _at all_.

Conditions for executing are:

  1. Item you’re editing is a component
  2. Current component’s schema has a field named “Title”
  3. Value of this field does not start with an Uppercase letter.

Open the ValidateTitleFieldCommand.js file and modify the _execute method to determine if we should execute:

Company.Extensions.ValidateTitleFieldCommand.prototype._execute = function ValidateTitleFieldCommand$_execute(selection, pipeline) {
    console.debug("Execute called");
    var p = this.properties;
    var item = $display.getItem();
    if (item) {
        if (item.getItemType() == "tcm:16") {
            // We know it's a component
            var fieldBuilder = $display.getView().properties.controls.fieldBuilder;
            if (fieldBuilder.getField("Title")) {
                // We have a field named Title
                var titleField = fieldBuilder.getField("Title");
                if (titleField.getValues().length > 0) {
                    var fieldValue = titleField.getValues()[0];
                    console.debug("Current title value is " + fieldValue);
                    // Voodoo magic
                    var firstCharacter = fieldValue.substring(0, 1);
                    if (isNaN(firstCharacter)) {
                        if (firstCharacter != firstCharacter.toUpperCase()) {
                            console.debug("First character is NOT uppercase");
                        } else {
                            console.debug("First character is uppercase");
                        }
                    } else {
                        // Interestingly isNaN returns false on a space. Good to know, I guess
                        console.debug("First character is a number!");
                    }
                }
            }
        }
    }
    return $cme.getCommand("Save")._execute(selection, pipeline);
};

The fieldBuilder is the magic here that provides us the ability to read fields in the Tridion GUI.  Using the JavaScript FireBug Console we can set a breakpoint on this line and then go to the Console window and inspect the object for other properties and methods.

Also, notice the return statement where we allow the GUI to continue saving.

At this point we can start thinking about the real solution. You could, for instance, add an alert(“First letter of title must be Upper Case”) to your code and stop the execution of the Save command (commented the changes to the code):

Company.Extensions.ValidateTitleFieldCommand.prototype._execute = function ValidateTitleFieldCommand$_execute(selection, pipeline) {
    console.debug("Execute called");
    var item = $display.getItem();
    var failed = false;  // ** Added
    if (item) {
        if (item.getItemType() == "tcm:16") {
            // We know it's a component
            var fieldBuilder = $display.getView().properties.controls.fieldBuilder;
            if (fieldBuilder.getField("Title")) {
                // We have a field named Title
                var titleField = fieldBuilder.getField("Title");
                if (titleField.getValues().length > 0) {
                    var fieldValue = titleField.getValues()[0];
                    console.debug("Current title value is " + fieldValue);
                    // Voodoo magic
                    var firstCharacter = fieldValue.substring(0, 1);
                    if (isNaN(firstCharacter)) {
                        if (firstCharacter != firstCharacter.toUpperCase()) {
                            console.debug("First character is NOT uppercase");
                            // *** Show popup
                            alert("First character of 'Title' field must be uppercase");
                            failed = true;
                        } else {
                            console.debug("First character is uppercase");
                        }
                    } else {
                        // Interestingly isNaN returns false on a space. Good to know, I guess
                        console.debug("First character is a number!");
                        // *** Show popup
                        alert("First character of 'Title' field cannot be a number.");
                        failed = true;  // *** Stop save action
                    }
                }
            }
        }
    }
    if(!failed)
        // *** Continue saving
        return $cme.getCommand("Save")._execute(selection, pipeline);
};

Which would result in something like this showing up to your editors.  We did it!  Congratulations for making it this far!

Debugging

Let’s see if our GUI Extension code is firing:
– Open Firefox, FireBug, Script Tab
– Open a Component

Search for ‘ValidateTitleFieldCommand’ and around line 96404 you will see our new GUI Extension JavaScript code.  Here I place a breakpoint and then with pressing the Save button I can step through the code.

While stepping through code I can also go to the Console Window and see the other methods  and properties that are available for these objects.

Summary

The Tridion 2011 Anguilla Framework gives us the opportunity to provide friendlier feedback to the user and also increase the quality of content entered into Tridion by enforcing editorial guidelines.  We’ve used the Anguilla Framework to access the fieldBuilder object in the Tridion GUI and inspect the field contents, showing a warning if they do not meet our requirements.  In the next post we’ll update the popup and allow users to make changes to the content in the popup window itself.  Thanks again to Nuno for creating this awesome post.

Solution on Github:  https://github.com/rcurlette/ValidateTitleFieldPart2/

The SDL Tridion World Server connector bridges the world of Content Management and Translation Management.  Providing an easy to use interface that allows the author to directly send items for translation and review the translation process brings a boost in productivity and efficiency to multi-lingual websites.  In addition, it eliminates the overhead of creating and assigning tickets internally as the content items enter into workflow without any additional work.  Recently I had the opportunity to implement the SDL World Server connector and was impressed with the tight integration between the two platforms. In this article I will discuss installing, configuring and using the World Server connector. I will not go into any advanced topics such as using the Event System with World Server.

Tridion’s strength is the management of content across languages and sites using the BluePrint technology built into the core of the product. SDL bought Tridion in 2007 and integrated Tridion into its’ suite of translation products, introducing a Tridion connector for both World Server and the Translation Management Server. These products were made for each other – and putting them together feels like it was always meant to be.

Using the Tridion WorldServer Connector

Starting the Translation is as simple as right-clicking the content item and selecting Translate.  This creates a new Translation Job.

Creating a Translation Job

Adding another item to the translation job is easy

The translation job ends up in the ‘Translation Jobs’ section of the ‘Shortcuts’ menu.

We send the translation job out from the Translation Jobs menu.

Or the Ribbon

Once it has been accepted and started, we can track the progress from within the Tridion CMS. The listview has a % Complete column and opening a translation job shows which step of the workflow it is in. This is an amazing feature that allows our content managers can keep an overview of exactly where items are at in translation directly from Tridion – no need to go into SDL or other interfaces.  Finally, when content is translated and received back a Publication-configured email address is mailed that the item is back from translation.

 

Installing the World Server Connector

Installing the World Server connector involves 3 steps.  The CMS will store the translation jobs in a new database and use a Web Service to communicate with the World Server instance.

1.  Create the Translation Manager Server Database using the Tridion Database Manager tool

2.  Run the World Server Connector Install Wizard.  Next, go to SDL Tridion World and download the World Server hotfix rollup.  If you are using secure sessions in World Server you’ll need an additional hotfix from SDL to enable Tridion to talk to the secure connection on World Server.

3.  Create a repository in World Server and configure World Server for Tridion.
There are special permissions that the World Server user is required to have and these are documented in the Tridion Live Documentation site.  In addition to user permissions there are some specific settings the World Server Administrator must configure to have Tridion able to send translation jobs.

4.  Validating configuration and testing – Open the Publication Langauge Parent and tell it to connect to World Server.  This will use the settings in the configuration file and attempt to connect to World Server.  It will take a few minutes – but if it does not connect the ‘loading’ message will stay on the screen.  This likely means that the configuration is not valid.  Best to look at the configuration file and remote into your CMS and confirm that you can access the World Server URL from the CMS.  Also, you can run Fiddler on the CMS to see which ports the Tridion Web Service is using to talk with World Server.  Once connected configure the Parent Publication to the World Server equivalent.  Now, open a Child Publication and do the same, pointing to the World Server repository for the child language.

Summary

The World Server Connector is the ‘holy grail’ for large companies with multi-lingual websites.  Being able to send content for translation directly from the GUI and then leverage your existing Translation Network and Workflow is extremely efficient and time-saving.  The installation is fairly quick and with your local World Server administrator you should have it up and running without too much effort. The World Server configuration is very specific and needs to be carefully setup according to SDL’s requirements.  I hope this article gives you an idea of how this works.

 

All episodes of the Tridion Talk podcast are now available at TridionDialog.com. I sit down and talk with Quirijn Slings and many more Tridion experts about DD4T and many other topics in Tridion powered websites. This is my first time creating a podcast and it was a lot more work than I expected! I was also surprised how much I enjoyed editing the audio and learning this new domain of audio editing and encoding knowledge. Please take a moment, or more, to listen to the episode and let me know what you think!

 

Tridion 2011 brought us the ability to change the users experience in the GUI. This is something I wanted (and needed) to do for the last 10 years – but was not allowed to but was not comfortable doing with the lack of documentation and support. The ability to officially modify the Tridion GUI and modify the default experience for users arrived in Tridion 2011 Tridion 5.2 and was continually expanded on until fully embraced in 2011. Before 2011 it was possible, but the official response from Tridion was ‘It’s not supported’ and if a customer called Tridion with a modified GUI Tridion ASP system files and would not receive support.  Needless to say, we never modified the GUI as a general practice as part of an implementation – it felt too unsupported and undocumented.

This changed in Tridion 2011. One of the features added was to write our own ‘GUI Extensions’ and these new extensions were supported – and documented. Not only that, but we had a brand new javascript framework called Anguilla that we have available to use for extending the GUI. Next to the Anguilla framework we also have the ability to add buttons to the GUI, extra columns to the list view and even tabs to the Edit windows of item types. This is revolutionary in the Tridion world, where previously our GUI was locked down by R & D generally not open to edit except for specific extension points, and then not documented as in 2011, and I instantly fell in love with this new concept. After attempting to create my own extensions using existing blog posts and documentation I quickly got stuck – all guides showed how to add the buttons, etc – but what about functionality with Tridion? I found some great code samples on Tridion World – but no explanations. So, I decided to spend some serious quality time and dig into the Anguilla framework and GUI Extension technology. I was very lucky to have the full support of the Tridion Community and before too long I had a working GUI extension and started to make sense of the madness. I did it – and decided to share my newfound love with the world. What followed was a series of blog posts about creating GUI extensions. I tried to fill the gap between what documentation was available and what was possible. I tried to give a code sample and explanation for each type of new extension. I did this with the thought that everyone should be able to write this code, and do it with a good understanding of what it does.

Now Alvin wrote his post and it made me think – is it now understood as a common step in an implementation to modify the GUI? For me writing custom pages and modifying the GUI are always part of an implementation, but a small part with a big impact on daily usability, often saving users hours of time per week. Another way to save users time each week is to have a well-defined Schema, clear folder structure, solid Blueprint, and clear instructions. This is Alvin’s point and I 100% agree – this is the main goal of every implementation – clean, well-defined, and clear. These goals do not require GUI Extensions but they require a clear understanding of the business requirements and an architecture design that enables ease of use in the Tridion system. Indeed, Tridion is an open box and everything is possible- allowing customers and partners to misuse various features or not use them to full effect. An amazing GUI Extension will not compensate for this basic lack of a solid foundation.  GUI Extensions are the whipped cream on top. Not all implementations need it – but when it is there it gives a very nice finish to an already great product.

Tridion 2011 nicely displays the Item’s URI in the address bar.  This is one of many favorite features in the new version.

For example, http://Tridion2011Dev/WebUI/Editors/CME/Views/Dashboard/Dashboard.aspx#locationId=tcm:22-2902-2

I can change 22 to 131 and then hop down to the Web Publication where I publish from – or to 6 and hop up to the Blueprint parent.

Tip:  Refresh 1 more time after updating the URL – and your browser will take you there.  Not sure why it does not work on the first attempt.

Edit:  Puf added a great tip for not needing the refresh!  Thanks!

From Frank van Puffelen:

The behavior of what happens when you change just the so-called document fragment identifier (the part after the # sign) of a URL depends on your browser.

If you want it to work first try (and get the back/forward buttons of your browser picking up such changes), paste this JavaScript fragment into your JavaScript console:

window.onhashchange=function(){$display.getView().navigateTo(location.hash.match(/[&#]locationId=([^&]*)/)[1], true);}

Happy navigating!

 

Changing the Background of the Tridion GUI is a must when you work in different environments. We don’t want to be making changes in Prod when we intended to be logged into Dev.

The Tridion LiveDocumentation site has an excellent article on this called ‘Skinning the Content Manager Explorer’. It took me about 10 minutes to setup one server and less on additional servers.

Finding the right color is the first challenge. I used http://colorschemedesigner.com/ and installed the firefox extension ColorZilla to use the Color picker and choose the Tridion GUI background color. It gave me a nice set of choices.

The next challenge I had was that the text of the Breadcrumb faded into the background and disappeared. To set the text color we need to add 1 style rule to the Development.css file Tridion provides (thanks for the starter file!).

/* Breadcrumbs */
.addressbar .addressbaritem
{
color: white;
}

That’s it! Thanks to the SDL Tridion R&D Team for the nicely documented feature.

Adding a new Tab to the Tridion Edit window is a powerful and easy GUI Extension to implement. The tab will show in all Edit windows or only the ComponentEdit “view”. SDL recently used this approach to integrate the Translation Management System (TMS) and World Server into the interface – great example of the extension! 🙂 In this tutorial we will create a ‘Hello There’ GUI Extension and explain the concepts behind adding an extra tab to the edit screen.

Getting Started
We’ll need the following:

  • Filesystem access to your Tridion 2011 CMS Server (Program Files\Tridion\)
  • Editor for XML, HTML, and ASCX files
  • A Tridion CMS system with no other users logged in (since we will most likely break the GUI at some point)

Summary, we will:
In Visual Studio, create a new project and an ASCX control

In a JavaScript editor, create a simple JavaScript GUI Extension

In an XML editor, create a HelloTab.config file and configure IIS

Copy files to a new folder on the server C:\Program Files (x86)\Tridion\web\WebUI\Editors\HelloTab and update the System.config file

Tips for working with Anguilla Framework

Part 1: Create the GUI Extension Project and add the User Control ASCX File

1. Open Visual Studio 2010 and create a new Project, ASP.NET Empty Web Project.
2. Add a new Web User Control (ascx file) to the project. Name it HelloTab.ascx
3. Add a literal control to the ascx page and in the code behind set the text property to ‘Hello world’.

* Note: I could have created an HTML page, but instead wanted to use an ASCX page to show where the DLL from the bin folder would end up. In real life I prefer to keep the client simple with HTML and jQuery and the heavy lifting in a Web Services layer powered by ServiceStack.net.

HelloTab.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="HelloTab.ascx.cs" Inherits="HelloTab.HelloTab" %>
<asp:Literal ID="output" runat="server"></asp:Literal>
<div id="compUri"></div>

HelloTab.ascx.cs

protected void Page_Load(object sender, EventArgs e)
{
    output.Text = "Hello world";
}

Compile and Build the Solution. The DLL will be copied to C:\Program Files (x86)\Tridion\web\WebUI\WebRoot\bin

Part 2: Create the JavaScript

Type.registerNamespace("RC");

RC.HelloTab = function RC$HelloTab$HelloTab(element) {
    console.log('Constructor');
    Tridion.OO.enableInterface(this, "RC.HelloTab");
    this.addInterface("Tridion.Controls.DeckPage", [element]); //My extension is like this
};

RC.HelloTab.prototype.initialize = function HelloTab$initialize()
{
    console.log('init');
    this.callBase("Tridion.Controls.DeckPage", "initialize");
    $evt.addEventHandler($display.getItem(), "load", this.getDelegate(this.updateView));
};

RC.HelloTab.prototype.select = function HelloTab$select() {
    var c = $display.getItem();
    $j("#compUri").text(c.getId());
    console.log('select');
    this.callBase("Tridion.Controls.DeckPage", "select");
    this.updateView();
};

RC.HelloTab.prototype.updateView = function HelloTab$updateView()
{
    console.log('update');
    if (this.isSelected())
    {
        console.log('selected')
    }
};

Tridion.Controls.Deck.registerPageType(RC.HelloTab, "RC.HelloTab");

Order of Events:

  • constructor
  • select
  • initialize
  • updateView
  • selected

Part 3: GUI Extension Configuration and Setup IIS Copy files to server

Creating the config file HellotTab.config:

Create a new file called HelloTab.config. In this example the JavaScript, CSS, and ASPX files are all in the same folder, HelloTab. Here is the source:

<?xml version="1.0"?>
<Configuration xmlns="http://www.sdltridion.com/2009/GUI/Configuration/Merge"
               xmlns:cfg="http://www.sdltridion.com/2009/GUI/Configuration"
							 xmlns:ext="http://www.sdltridion.com/2009/GUI/extensions"
               xmlns:cmenu="http://www.sdltridion.com/2009/GUI/extensions/ContextMenu">

  <resources cache="true">
    <cfg:filters />
    <cfg:groups>
      <cfg:group name="RC.HelloTab" merge="always">
        <cfg:fileset>
          <cfg:file type="script">/HelloTab.js</cfg:file>
          <cfg:file type="script">/jquery.js</cfg:file>
        </cfg:fileset>
        <cfg:dependencies>
          <cfg:dependency>Tridion.Web.UI.Editors.CME</cfg:dependency>
          <cfg:dependency>Tridion.Web.UI.Editors.CME.commands</cfg:dependency>
        </cfg:dependencies>
      </cfg:group>
    </cfg:groups>
  </resources>
  <definitionfiles />
  <extensions>
    <ext:dataextenders/>
    <ext:editorextensions>
      <ext:editorextension target="CME">
        <ext:editurls/>
        <ext:listdefinitions/>
        <ext:taskbars/>
        <ext:commands/>
        <ext:commandextensions/>
        <ext:contextmenus/>
        <ext:lists />
        <ext:tabpages>
          <ext:add>
            <ext:extension assignid="HelloTab" name="Hi There!" insertbefore="InfoTab">
              <ext:control>~/HelloTab.ascx</ext:control>
              <ext:pagetype>RC.HelloTab</ext:pagetype>
              <ext:dependencies>
                <cfg:dependency>RC.HelloTab</cfg:dependency>
              </ext:dependencies>
              <ext:apply>
                <ext:view name="ComponentView">
                  <ext:control id="MasterTabControl"/>
                </ext:view>
              </ext:apply>
            </ext:extension>
          </ext:add>
        </ext:tabpages>
        <ext:toolbars/>
        <ext:ribbontoolbars/>
      </ext:editorextension>
    </ext:editorextensions>
  </extensions>
  <commands/>
  <contextmenus />
  <localization />
  <settings>
    <defaultpage/>
    <navigatorurl/>
    <editurls/>
    <listdefinitions />
    <itemicons/>
    <theme>
      <path>theme/</path>
    </theme>
    <customconfiguration />
  </settings>
</Configuration>

A few things to highlight:

Name the config group:

cfg:group name="RC.HelloTab"

Specify any js or css files needed by the extension:

<cfg:fileset>
  <cfg:file type="script">/HelloTab.js</cfg:file>
</cfg:fileset>

Define standard dependencies:

<cfg:dependencies>
  <cfg:dependency>Tridion.Web.UI.Editors.CME</cfg:dependency>
  <cfg:dependency>Tridion.Web.UI.Editors.CME.commands</cfg:dependency>
</cfg:dependencies>

Define the ID, text for the tab, and location:

<ext:extension assignid="HelloTab" name="Hi There!" insertbefore="InfoTab">

The GUI ASCX control with HTML for the tab:

<ext:control>~/HelloTab.ascx</ext:control>

Define the Namespace and method for the JS file. I missed this the first time and my JS file would not load. Thanks to the StackOverflow post here for the help.

<ext:dependencies>
    <cfg:dependency>RC.HelloTab</cfg:dependency>
</ext:dependencies>

Specify the Edit view the Tab will appear on:

<ext:apply>
    <ext:view name="ComponentView">
      <ext:control id="MasterTabControl"/>
    </ext:view>
</ext:apply>

More about the Views option
Views – Which edit screen we load our GUI Extension
We can tell Tridion to only load our new Tab when we are editing a Component and not when editing a Template. To do this we’ll need to add a magic View name to the

The Tridion GUI Views are stored on the server at C:\Program Files (x86)\Tridion\web\WebUI\Editors\CME\Views.

The views folder contains some obvious ones like PageView and ComponentView. However, I am not sure about the DashboardView or CustomPageView – and hope that the Tridion Documentation team might come to our rescue here and weed out the ones that are not valid.

  • BluePrintViewerView
  • CategoryView
  • ComponentView
  • ComponentTemplateView
  • CustomPageView
  • DashboardView
  • FolderView
  • KeywordView
  • ListFiltersView
  • MultimediaTypeView
  • PageView
  • PageTemplateView
  • PopupsView
  • PublicationView
  • PublicationTargetView
  • SchemaView
  • SplashScreenView
  • StructureGroupView
  • TargetGroupView
  • TargetTypeView
  • TemplateBuildingBlockView
  • TridionDashboardView
  • UserAccountsView
  • VirtualFolderView
  • WorkflowProcessView

Save the config file. Create a JS file HelloTab.js for the interaction with the Tridion GUI and Anguilla API. Below is a basic example:

Setup Virtual Directory in IIS
– Add VDIR to IIS, point to HelloTab Editor folder
– The name of the VDIR should match the VDIR node in the system.config file.

Part 4: Copy files to Server and update System.config

Create folder and copy files
– Create a new Folder in the Editors folder called ‘HelloTab’. Full path is ‘C:\Program Files (x86)\Tridion\web\WebUI\Editors\HelloTab’
– Copy HelloTab.ascx, HelloTab.js, and HelloTab.config files
– Copy the DLL file from the build output to ‘C:\Program Files (x86)\Tridion\web\WebUI\WebRoot\bin’. This is the location where all the DLLs associated with a GUI Extension are deployed. If you register the DLLs in the GAC then you could place them in another location.

Add Extension to System.config:

<editor name="HelloTab">
  <installpath>C:\Program Files (x86)\Tridion\web\WebUI\Editors\HelloTab\</installpath>
  <configuration>HelloTab.config</configuration>
  <vdir>HelloTab</vdir>
</editor>

Test
The new Tab should appear in the ComponentEdit screen. Great! But, we still need to do something in the tab.  Let’s add some JavaScript and talk with the Anguilla API.

Part 5: Working with the JS Anguilla API

Anguilla is the powerful Tridion JavaScript framework that makes the magic in the Tridion 2011 GUI possible.  Unfortunately, it is not well known and not too many code samples are available yet.  Some hints of methods and objects can be found in the Tridion 2011 Views folder at C:\Program Files (x86)\Tridion\web\WebUI\Editors\CME\Views. The Tridion 2011 PowerTools also use the Anguilla framework and provide additional opportunities to gain hints. SDL Tridion World has the Anguilla documentation available for download in the Documentation downloads section. With all that said – most Tridion developers that I know have a background in server-side Web development and writing OO JavaScript is not in the comfort zone of many, including me.  We have the option to do the minimum in Anguilla and then run to the Core Service to do the heavy lifting – but I hope in the future we can use more of the built-in methods in Anguilla.

Trick for jQuery

Tridion PowerTools use jQuery and have a trick to load it so it does not conflict with Outbound Email. Clever! After adding this then we use $j for our jQuery magic.

var addJquery = function ()
{
    // ... jQuery here ...
    //YM: to avoid conflict with the Outbound Email extension, we define a new shorthand for jQuery
	window.$j = jQuery.noConflict(true);
};
addJquery();

Using jQuery in the JS code:

 $j("#compUri").text("tcm:0-0-0");

Displaying the URI in the Tab

var c = $display.getItem();
$j("#compUri").text(c.getId());

Fun with the Chrome Developer Console and Anguilla:

  1. Set a breakpoint on the line after the var c =
  2. Open the Chrome Debugger
  3. Scripts tab
  4. Component…aspx script
  5. Scroll to bottom of script and find your code. Alternative use the find feature of Chrome. You should see console.log(‘select’);
  6. Add a breakpoint by clicking on the line #
  7. Now refresh and it will stop on that line when you’ve seelcted the new tab. Don’t hit continue yet.
  8. Go to the Console tab, hit c. and amaze at the amount of methods we have available – via the Anguilla JavaScript Framework – at our disposal.

The Tridion Live Documentation contains a very quick guide to Tab GUI Extensions here. Don’t forget to login first before clicking the link.

Summary

This GUI Extension is a simple one and is intended to give you the ideas and some confidence with creating your first one. With the Component URI and the power of the Anguilla Framework you can already do some magic via JavaScript in the tab with this example. However, it is also possible to make a webservice call from the js and do more server-side api work there. I hope you were able to follow along and that this inspires you to create your own extensions. A big thanks to the Tridion community on StackOverflow – without you the article would not be possible.

Get the code

https://github.com/rcurlette/GuiExtensionHelloTab

Tridion 2011 Favorites

May 10th, 2012 | Posted by Robert Curlette in Tridion - (1 Comments)

Tridion 2011 is full of small useful improvements. One of those is the addition of the ‘Favorites’ section next to Custom Pages in the tree menu. We can have shortcuts to Structure Groups, Folders, Pages, Components, and even Categories Keywords. This is very handy, especially for Demos and Tridion Webinars. Saves a lot of time!

Adding an Item to Tridion 2011 Favorites

Sending an item to Favorites is as easy as a right-click on any item.

Then the item is in the Favorites tree.

I use it for my Template Folders and common Structure Groups for publishing.

GUI Customizations with the Favorites

It is possible to use a Data Extender GUI Customization with a Favorites folder the same as we do for any list item in Tridion. Warner Soditus asked a question on SatckOverflow this week and with the help of Nuno (otherwise known as KnewKnow) and Puf we have another good solution for improving the Tridion experience.

Thanks a lot for adding another favorite feature to Tridion 2011!

Tridion 2011 provides too many benefits for the organization and development team to be overlooked any longer. I recently upgraded a system from Tridion 5.3 to Tridion 2011 and it was a lot less scary than I originally thought. Tridion has provided us a better installer and documentation than past versions and an amazing new product full of features. Having the right approach and knowing where to focus your efforts are a key to a successful upgrade. In this post I hope to share some of my experiences with the upgrade and provide some tips to help make it an easy one.

1. Read the install manual and upgrade manual.

No, really, please print it, sit in your favorite chair or lotus position, and read it – all. The Live Documentation site also has it online. Now, go back and circle or highlight things you need to double-check in your environment such as Java version installed on your Deployer or Broker, SQL Server SP version, and the version of Windows Server you are running on the CMS.

2. Upgrade the Database

Tridion provides a great DB tool for upgrading the database, located in the Installer/Database folder named ‘DatabaseManager.exe’.  My database was a 5.3 SP1 SQL Server 2005 DB and the upgrade ran perfectly and was done in around 15 minutes. This is a no risk step and in my experience always works.  Please backup your DB before you begin.

Upgrade both the CMS Database and the Broker Database.

The tool requires the SA account (or one with equivalent permissions) and the password of the TCMDBUser and other Tridion user accounts.

3. Upgrade the CMS

Very easy with the included installer.  The installer has been improved and adds more manual detail control over what is installed. Don’t check Audience Manager (Outbound Email) or Translation Manager (world Server / TMS) unless you are using them. Not nice to have unused Tridion pieces installed and not configured in your environment – and also not nice to configure something you’re not using. You can add them back later using the same installer files (not add/remove programs because this throws an error – just use the original installer file).

This is a next, next, next process and also very low risk. Great job by the installer team.

If you have SiteEdit code in your templates, first install and register SiteEdit extension DLL.   Then add the Extension to the Tridion MMC snap-in.

4. Test the CMS

Login to the CMS and you will see a new GUI Screen and a progress indicator. Be patient – the new Tridion GUI takes longer to load on the first time – but after it is about 20-30% faster on the same hardware. Sweet! 🙂

Things to test:

– Opening and saving Components. Do you use the Event System?  See below for tips on the Event System.

– Previewing. Do you use SiteEdit? You must re-register the SiteEdit DLL in the Tridion MMC SnapIn.

– Creating a new Component and new Page.

– Custom pages – The Tridion 2011 TOM API is fully supported and backwards compatible. These custom pages should just work. However, many of the original Powertools will not work because they re-used js from the old Tridion GUI. A new Powertools initiative has been started and a Page Publisher tool is already finished. Please join the fun and help us make the 2011 Powertools better.

– Publishing – not yet! Wait until the next step.

5. Installing the Broker and Deployer

There is not a nice installer here and it is a manual copy / paste action, especially if you’re using a Java based Content Delivery system. There are a lot of new 3rd party jar files and yes, you need them all.

– Add the SQL Server jar from Microsoft if using SQL Server. Please note there are different jar files for Java versions. Java 5 requires sqljdbc.jar and Java 6 requries sqljdbc4.jar. Tridion documentation for Content Delivery has more details.

– Create a cd_storage_conf file – The cd_broker_conf file is deprecated and replaced with a new cd_storage_conf. Grab the example one from the install folder, Tridion 2011 SP1\Content Delivery\resources\configurations, edit the connection string to the DB, and define the ItemTypes mapping.

– Update the logging config – Another new item here is the logback logger used. It has its own config file and has extensive documentation. This is one of many examples where Tridion took great, existing frameworks and put them under the new Tridion 2011 architecture – great job.

6. Test the Deployer

– Publish a Page with only a Page Template producing static HTML and no Component Presentations. This tests the basic ability to publish to the Filesystem. Try to view the published page from the website after. Works – yay! Doesn’t work – double check your deployer storage_config.

– Publish a Page with Component Presentations. This will add link data to the Broker and insert records in a DB or write new files on the filesystem, depending on your bindings in the config.

– Publish a dynamic Component Presentation to the Broker DB. This tests your Broker DB connection. If it does not work, go review the cd_storage_conf.

7. Test the Broker

The broker API is 100% improved and still is fully backwards compatible. All my 5.3 broker calls worked perfectly.  If you’ve written your own SQL against the broker db you should test it well.

– View one of your existing pages that queries the Broker. If you do not have any yet, you can see the Tridion Content Broker Query documentation or my JSP example for some inspiration.

– Configure cache channel support

– Load test all your pages using Broker Queries.  They’ve re-written the Broker and you want to confirm all performs as well as before.

Stop and congratulate yourself for performing a successful upgrade. However, we’re not yet finished since you’ve likely developed some custom code in custom pages, event system, or gui extensions that also needs to be reviewed and tested.

Now we know we can publish our site and our thousands of lines of templates work fine.

8. Custom Pages and GUI Customizations

If you wrote your own custom pages using the Tridion API there is a very good chance this works 100%.  For me I had around 20 custom pages and all worked perfectly.  For asp.net solutions you’ll want to update them to use the new Tridion 2011 dlls in the client folder.  Tridion TOM is 100% supported in the 2011 but has a deprecated status.  Our custom pages should work 100% unless the Tridion ASP or JS GUI files are required (most times not, except in cases like Powertools).

We’ve been warned not to change the existing Tridion GUI asp and js files and the warning was for times like this – when we upgrade and lose those very handy little icons in the GUI.  This is the tricky area where someone modified Tridion GUI js or asp files.  I would re-evaluate each customization and think if you really must have it, and if so if you could rewrite it using a Tridion 2011 GUI extension.

I have written a few articles to help you get started with 2011 GUI extensions.  Fear not – the Tridion R&D team has provided us a great new GUI Architecture that is more open and allows us to legally extend the GUI in many supported ways. 🙂 I have written a tutorial on creating your first GUI Extension and another about getting a quick start adapting the GUI Extension tutorial code for a new extension. The key here is expectations setting and planning. Do you really use all those extensions every day? Can the editors live without some of them while they’re being re-written in the new framework? Can you write an ASP custom page now in your old version (or also 2011) that does the same thing until the new shiny extension is ready?

9. Event System

Open the Cms config mmc, events section, what has a 1 is turned on.  For each of these it is a good idea to test it.  There can be complex logic, so take your time with this step.  Also you will need to configure the Cms to use your legacy event system.  Tridion re-wrote the event system for 2011 and I have a small article here about getting started.  But you can also keep running your old code.

– Tridion 2011 supports the old Event System and also provides a completely new framework for building a new one. The new Event System is really nice and the Tridion 2011 Delta Training is a good place to start learning more about it.

– Read about the old Event System support here.

– Use the Legacy Events Adapter for your old Event System. It is highly recommended to re-write the old Events to the Tridion 2011 Event System, but it is not mandatory before using Tridion 2011. This is something to be planned with the development team.

– You can also write a small script that resaves all components to trigger the oncomponentsave event, or to trigger other events.  This is a good idea in general as a way to test Event System functionality.

10. Templates

– All VBScript templates are 100% supported.

– SiteEdit?  I use SiteEdit and needed to register the SiteEdit dll using RegAsm (for SiteEdit 1.3) and also add it to the MMC snapin.

– Upgrade your templates to use the new Razor Mediator. It is very fast to write templates with Razor syntax, it is similar to VBScript but a lot more powerful, and much easier to learn than the DWT mediator or the XSLT mediator.  This assumes you know how to create a Compound Component Template.

Get the Razor Mediator

VBScript to Razor Guide

Razor introduction article

Summary

Upgrading the Tridion system is much easier with the new Tridion 2011 tools and support. The community is more active than ever and there are many nice Tridion 2011 extensions available from Tridion World.  In my experience the upgrade was a lot easier than previous upgrades – a real surprise when I think they replaced or upgraded a lot of the technologies under the platform.  Congrats to the installer and R & D teams!  We also have great new frameworks available in the new version, such as .NET 4.0, Solr, Logback, WCF, etc. With a sensible plan and step by step testing of various components we can perform the upgrade with ease and confidence. I hope this article gives you some hope that the upgrade is within reach and with some careful planning can be achieved with little risk.

The Tridion Razor Mediator brings all the goodness of the Razor template engine to Tridion.  The Razor mediator uses the official Microsoft Razor Engine and is dependent on .Net 4.0 or higher.  This is good news for us – any improvements in the script engine by Microsoft will be available to us.  Even better, the Razor Mediator is open source; we can see all the code and also update a dependency and recompile if we choose.

The Razor Mediator wraps the Tridion API and provides a more fluent interface to accessing items such as Components and Pages.  Not only that, but many helper functions are also included such as IsFirst, a method to get ComponentPresentations by template name, and super-easy access to Component Link fields and Embedded Fields.  You do not need to know C# or .NET to use it, but if you do then you can use existing .NET methods directly in the templates.  There are many other cool features that I will discuss here in the post.

What is a Mediator

The Tridion Mediator Framework enables developers to create alternative template engines for the Tridion CMS. In Tridion versions 4 and until version 5.2 there was no Mediator framework and we only had Tridion’s built-in “mediator” available and wrote templates in VBScript, JScript, or XSLT. Starting with version 5.3 with the introduction of Compound Templating any developer could create their own template engine, or Mediator, and use this instead of the built-in languages. The first Mediator was an XSLT mediator (for Compound Templating) created by Chris Summers and Yoav Niran. This is still a popular mediator today. However, the new Razor Mediator from Alex Klock promises to provide as much power as XSLT with a lot less sweating involved. 🙂

The Razor Mediator is built on top of the Razor syntax engine from Microsoft, released with ASP.NET MVC, and requries .NET 4.0 and Tridion 2011. If you have done any ASP.NET MVC development then you are familiar with the syntax. The Razor Mediator is not the first external template engine using Microsoft’s Razor engineUmbraco version 5 uses the Razor engine as its’ default template language, replacing the XSLT standard, and has been well received by the community, even by the XSLT die hards.

So, with all that said what are we waiting for?  Let’s dive in and start writing some Razor code.

10 Benefits of Razor Templating:

  • Lots of existing Razor code samples on the web
  • Great Razor Mediator documentation
  • Built on top of the official Microsoft Razor syntax engine. No custom coding or regex matches here! It’s all official! The Mediator is mostly a wrapper around Tridion’s object model with a few helper functions built-in.  Full .NET Framework available in Templates, including functions for Date/Time parsing.
  • Built-in helper functions for iterating over Component Presentations by Template Name (new in 1.2)
  • Smart rendering functionalities like auto-detecting RTF fields and calling ResolveXHTML for us.
  • Easy to access Component Link fields and Embedded Fields – no more looking up the Embedded Field syntax in the reference guide!
  • Logging to the Template Builder ouput window with @Debug(“”)
  • Best template import system of any mediator – can import standard libraries from the config file and not need to include them in each template.  Inline imports allow us to import any type of code – from HTML to CSS, JS, and Razor snippets (imports added in 1.2)
  • Clean syntax calls and requires less code than other mediators.  Less code = less typing = less bugs = happier.
  • Includes its’ own installer – a first for any Tridion Mediator

Getting started with the Tridion Razor Mediator

Getting started is easier than any other Mediator because it comes with its’ own Installer!

1. Download the latest Razor Mediator Installer here (http://code.google.com/p/razor-mediator-4-tridion/downloads/list)
2. Copy installer to the CMS Server
3. Run installer
4. Shut down COM+, restart Publisher

What does the installer do?
– Creates a new Template Building Block Type, Razor Mediator
– Updates the Tridion System.config file at /Tridion/config. If you want to modify the config and add your own default TBB includes this is the place to do it.

Try the new Razor Mediator

– In Tridion, create a new TBB, select Razor as the template language.  If you do not see it here, you may need to re-start your CMS.
– Type some Razor code, save. (ie. <h1>@Component.Title</h1>). Save in a new folder called Razor templates.  VBScript to Razor code samples
– Open Template Builder, create a new Compound Template, type Component Template.
– See if the Folder ‘Razor templates’ is there in the template list of the left. If not, then refresh the template list.
– Add your new Razor template, preview, and witness the magic.

Good news! We’re all ready to begin our small exercise to create a Detail Page using the Razor mediator. I want to highlight the new features from version 1.2, including the GetComponentPresentationsByTemplate, the TBB imports functionality and the IsFirst and IsLast methods.

Microsoft Razor syntax reference:

http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx
http://www.asp.net/web-pages/tutorials/basics/2-introduction-to-asp-net-web-programming-using-the-razor-syntax

Tridion Razor examples:

http://code.google.com/p/razor-mediator-4-tridion/wiki/VBScriptToRazorExamples
Razor helpers and functions
Razor 1.2 new features

I’ll show a few examples of the power and simplicity of the Razor engine highlighting new features from the 1.2 version. I will not cover Tridion dynamic links or navigation since it requires too much logic / detail for this overview.

The Example – A story of on Index page and a Detail page

We will create an Index Page and a Detail page using the Twitter Bootstrap style and HTML.  Our Index page will show 1 Large text banner and a max of 4 intro articles.  Our Detail page will show the article with the Detail Template and also a max of 4 articles in the right-side rail / sidebar.

Detail Page

The detail page will contain 1 news article and a list of related articles in the right sidebar. First we’re going to need HTML before we start coding the template. This is a pre-requisite for any Tridion template and most of the time the template developer is not a front-end HTML developer, and in my case this is also true. Thanks to the Twitter Bootstrap project we have the HTML and CSS done for us – we simply need to fill in some content.

Schema Article Fields:

Heading
Sub-heading
Summary
Body
Links (embedded schema)
Link Title
Link URL External
Link URL Component Link

Source:  Embedded Link Schema
Source:  Detail Schema

Page Template Detail

The Page Template’s primary goal is to write out all the Component Presentations in the right location. It will also include all necessary js and css files, as well as specify a header and meta tags for our page. Page Templates do not write out Component fields. In this example I will only focus on writing out the Component Presentations. Find the location of the Article Component HTML and cut it out – replace with a comment “Article CT Here”. We will do the same for the Sidebar. This leaves us a nice Page Template beginning that we’ll come back to later. Leave the other hard-coded stuff in the HTML file. Later we will replace all content in the HTML page with a Component Presentation or a key/value string. We should never have any hard-coded content in any template – if we do then we have to change the template to update content – something we never want to do.

Tridion Page Template Shell

 

Component Template Detail

The Detail Component Template displays almost all the fields from the Detail page. Notice how we effortlessly display the embedded fields.

Component Template Sidebar

The sidebar template has a special requirement that we need to add a special css class to the first element in the list. For this we’ll use the IsFirst helper method in the Razor Mediator. Other Mediator’s do not have this out of the box.

Index Page

Displays the Article with the ct_banner_text template and up to 4 ct_home_intro Components on the bottom of the screen.

Index Page Templates

Page Template Index

Write the Component Template Code

– Create new Razor TBBs
– Create new TBB. In source tab, first choose the TemplateType of ‘RazorTemplate’. If you forget to do this you will not see it appear in Template Builder since we cannot use VBScritp templates in Compound Templates (default is VBScript in this window).
– Write code in text editor (Notepad++ or VS 2010), copy / paste into the window. Save and close.
– Create new Compound Template in Template Builder, type Component Template. Select the View menu and choose ‘Reload Template Building Blocks. You should now see your new TBB.
– Add TBB. Test with Article.
– Choose File, ‘Close and Open in Content Manager’
– In the ‘Linked Schemas’ tab, Add the appropriate Linked Schema(s). Save and close.
– Save and close. Ready for use on PT now. Copy Component Template name to Page Template ‘GetComponentPresentationsByTemplate’ method.

ct_home_intro


ct_home_banner

Banner Text Template Source

Razor Imports

I have a common <head> section for both templates and would like to re-use the HTML. For this I will use the new Razor Mediator @importRazor(“tbb webdav url”) method.

Configuring the Razor Imports
To use this I need to open the System.config file (from Tridion/config) and in the <razor.mediator node I should add the adminUser attribute:

adminUser=”DOMAIN\Username”

The User account running te COM+ service is usually MTSUser. Make sure this user is an impersonation user in the Tridion MMC snap-in. In my case it was not and I needed to add it. After adding it I shutdown COM+ and it was working fine.

Now it looks like:

<razor.mediator cacheTime=”60″ extractBinaries=”true” adminUser=”Dev2011\curlette”>

Accessing other properties

From Alex, “Every *Model component has a property, .TridionObject, that returns the actual Tridion object (so ComponentModel will return a Component).”
To access the Revisor of a Component we can use:
@Component.TridionObject.Revisor

Better Error Messages

On save it tries to compile your template against the Razor engine. Syntax errors are caught here. Warning- unfortunately the line # does not correspond to the real line #.
When running in Template Builder, any invalid field names are reported as:
“DynamicItemFields: Key ‘subheader’ Not Found In ItemFields”

Much better than the old error “Object or method not found”

Summary

If you are using Tridion 2011 then please give the Razor Mediator a try.  With as little as 1 hour you can run the installer, wrie a sample CT, and experience the simplicity and power of the Mediator.  As you can see the Razor Mediator makes it very easy to write Tridion templates while at the same time using the standard Razor syntax of Microsoft. We handled embedded fields and IsFirst conditions with ease and it is this kind of approach that makes templates faster to write and easier to maintain in the future. We only covered some of the possibilities with the Mediator and did not go into using existing .NET classes in our templates. A big thanks to Alex Klock for creating the Razor Mediator and continuing to add new features to it. I look forward to what is coming next in version 1.3!