Retrieving, Archiving, and Disposing Messages with Anguilla’s MessageCenter

Inspired by yet another question on StackExchange, I’ve decided to do a follow up on a previous post on using MessageCenter. While in the previous post we focused on the creation and registration of new messages and notifications, today we are going to discuss the retrieval, archiving, and disposing (removing) of messages within the message center. Before we continue, you should know that archiving a message in Anguilla means that is shows up as dark grey (ones that you’ve read) in the list of messages, while disposing means that it doesn’t show up in the list at all.

Retrieving

You can get an Array of all the messages using the getMessages() method of MessageCenter.

$messages.getMessages().forEach(function (message) {
    // do cool things with each message
});

The getMessages method does return ALL messages, including those that are inactive (archived) or disposed. If instead you want to get only the active messages, you could use the getActiveMessages() method.

$messages.getActiveMessages().forEach(function (message) {
    // do cool things with your active messages
});

But what if you wanted to get a list of all disposed messages… or a list of all archived messages? Although we’ll talk about how to dispose and archive individual messages later in the article, one thing to understand is that when a message gets archived, the message.properties.inactive property gets set to true, and when a message gets disposed, the message.properties.disposed property gets set to true. Knowing this, we can now filter our results based on those properties:

$messages.getMessages().forEach(function (message) {
    if (!message.properties.disposed) {
        console.log("This message has not been disposed yet!");
    }
    if (!message.properties.inactive) {
        console.log("This message has not been archived yet!");
    }
    if (!message.isActive()) {
        console.log("The isActive method can also be used to check the .properties.inactive property!  There is no isDiposed one though!");
    }
});

You can even filter on other things, like the type of messages or dates!

$messages.getMessages().forEach(function (message) {
    if (!message.properties.disposed && message.isActive()) {
        if (message.getClassName() === "error") {
            console.log("We have an error message that was given on " + message.getDate() + "!");
        }
    }
});

Archiving

When a message is archived, it shows up as gray in the message center. A message gets archived when you acknowledge it (clicking the “close” button), automatically (like with progress messages), or when you programatically archive it. You can do this with a message’s doArchive() method. The following snippet will archive any active messages that are out there:

$messages.getActiveMessages().forEach(function (message) {
    message.doArchive();
});

Disposing

Disposing of a message makes it so that it doesn’t show up in the GUI list at all. Besides marking the message.properties.disposed property as true, it also seems to clean up some of the other properties and data that existed on the message. So this means that even though the message is still in the list of messages after being disposed, there’s really no useful data on it except for that disposed property. You can easily dispose of a message by calling its dispose() method.

$messages.getActiveMessages().forEach(function (message) {
    message.doArchive();
    message.dispose();
});

You’ll notice that in the above example we are calling doArchive() first. This is VERY important to do, because if you dispose of an active method without first archiving it, the message will remain counted as “unread” in the message center’s counter. This will leave our users in a confused state as they are being notified that they have new messages, but there is nothing in this list.

Show/Hide Archived Messages

You’ve probably noticed the checkbox in your Message Center that allows you to “Show Archived Messages”. Unchecking this box will hide any archived messages in the list. The anguilla API also allows you to view and manipulate this setting.

if ($messages.getIsShowArchivedMessages()) {
   // the checkbox is checked!
   $messages.setIsShowArchivedMessages(false); // but not anymore!
}

And with that I leave you with more power and knowledge to manipulate and bend the Message Center to your will!

Searching and Modifying Output In Tridion Template Building Blocks With HtmlAgilityPack

In your Tridion career, you’ve probably written countless of C# Template Building Blocks. You’ve probably rolled your own custom Link Resolver, your own “Add or Extract Binaries From…”, your own cleanup templates… dozens of Building Blocks where the goal was to search for specific html patterns and attributes or modify the output in some way. And, if you’re like me, you’ve probably had to write numerous regex expressions to accomplish your tasks. I’ll admit that I’m no regex ninja or anything, its usually through trial and error that I get my regular expressions working correctly. Recently however, I attempted to write an expression that handled nested elements that could go any number of levels deep, with possibility to have several different variations of the pattern that I was looking for. My regex skills was just not good enough, and I thought for sure there must be a better way to parse the html output string of these patterns.

The search was short, but I found exactly what I was looking for: Html Agility Pack

Using HtmlAgilityPack in your Tridion Template Building Block is simple… just reference the DLL, and make sure you install the DLL into the GAC on the CMS and Publishing servers.

Now that we are set up and ready to run, let’s go ahead and write some code that will take the output from the package, and load it into an HtmlDocument.  Your code should look something like the following:

using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Tridion.ContentManager.Templating;
using Tridion.ContentManager.Templating.Assembly;
using HtmlAgilityPack;

namespace CodedWeapon.Samples
{
    [TcmTemplateTitle("HtmlAgilityPack Tester")]
    public class HtmlAgilityPackTester : ITemplate
    {
        private TemplatingLogger _logger = null;

	protected TemplatingLogger Logger
	{
		get
		{
			if (_logger == null) 
                            _logger = TemplatingLogger.GetLogger(this.GetType());

			return _logger;
		}
	}

        public override void Transform(Engine engine, Package package)
        {
            Item outputItem = package.GetByName(Package.OutputName);
            string outputString = outputItem.GetAsString();

            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(outputString);
        }
    }
}

If you’re familiar with XmlDocument, then HtmlDocument should not look so strange to you. All we are doing in the above is grabbing the output, and passing the output (as a string) into our HtmlDocument instance. Simple enough right? And now for the fun… seeing how simple it is to use this library to get the exact elements that we are looking for. Since a lot of the time we work with links, I’ll show some examples of grabbing some anchor tags.

Grabbing Every Anchor

Lets say we want to grab every anchor element present on the output:

HtmlNodeCollection nodes = doc.DocumentNode.Descendants("a");

You can loop over each of the nodes and perform any necessary operations that you want:

foreach (var node in nodes)
{
    Logger.Debug("Found node with url: " + anchor.Attributes["href"].Value); 
}

Just like with XmlDocument, you can also use XPath:

HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//a");

Querying for Specific Elements

You can use XPath to search for the specific elements that you are looking for. For example, if we wanted to match all links with a specific url:

HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//a[@href=\"http://www.example.com\"]");

Or what if we wanted to grab every link that actually contains a title attribute:

HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//a[@title]");

Or better yet… what if we want check any node that does not contain the title attribute at all?

HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//a[not(@title)]")

If you’re not a fan of XPath, then you’ll be happy to know that you can also use LINQ like in this following example where we are looking for any link that has an href attribute of “#”:

var nodes = doc.DocumentNode.Descendants()
    .Where(n => n.Attributes["href"] != null && n.Attributes["href"].Value.Equals("#"));

Modifying Output

Normally when we’re searching for elements it’s because we may need to modify the markup in someway, either by adding attributes, removing elements, etc. In the following example, we are adding a custom attribute onto our anchors that contain a value of “#” in the href attribute:

foreach (var node in doc.DocumentNode.SelectNodes("//a[@href=\"#\"]"))
{
    node.Attributes.Add("data-my-custom-attribute", "true");
}

But what if we have a more complicated requirement where we need to strip a <tcdl:ComponentPresentation> tag (but ensure that we keep the inside markup). One may be tempted to try the following:

foreach (var node in doc.DocumentNode.Descendants("tcdl:ComponentPresentation"))
{
    node.ParentNode.RemoveChild(node, true); // this strips the tcdl tag while preserving the children... but its modifying the collection...
}

package.Remove(outputItem);
outputItem.SetAsString(doc.DocumentNode.OuterHtml);
package.PushItem(Package.OutputName, outputItem);

However, while running the above, you’ll get an error that says Collection was modified; enumeration operation may not execute. This is because you cannot modify the collection (add/remove) while enumerating it. But, we can keep a record of the nodes and operate on them after:

List nodesToChange = new List();
foreach (var node in doc.DocumentNode.Descendants("tcdl:ComponentPresentation"))
{
    nodesToChange.Add(node);
}

// Now we strip the wrapping tags...
foreach (var node in nodesToChange)
{
    node.ParentNode.RemoveChild(node, true);
}

package.Remove(outputItem);
outputItem.SetAsString(doc.DocumentNode.OuterHtml);
package.PushItem(Package.OutputName, outputItem);

Hopefully this will end the regex blues out there for anyone who may be struggling!

Reloading/Refreshing Lists in the Shortcuts Area

A recent question on stack exchange regarding the ability to refresh or reload the favorites section using the Anguilla API has sparked this post, where I thought I would expand a little bit on the answer.  What the asker was doing was modifying the favorites (in this case the names), but needed the favorites section to be reloaded in order to reflect these changes. The shortcuts area is within an iFrame, so my first thought was to use some regular JavaScript to reload the iFrame itself via:

$('#FavoritesTree iframe').contentWindow.location.reload(true);

But as the asker of the question realized, this actually causes the entire Tridion GUI to be loaded into the shortcuts area!  Definitely not what we want to do!

Luckily for us, Anguilla has a way for us to unload the lists which will automatically cause them to reload. If we want to refresh all of the lists inside of the shortcuts area, we can do the folllowing:

$models.getItem("cme:userfavs").unloadLists();

So what’s going on in the above statement? $models.getItem("cme:userfavs") retrieves the shortcuts area which is represented by the type Tridion.Cme.Model.FavoritesFolder. This object contains the method unloadLists() which does the magic for us. But suppose you only want to refresh a specific list in the shortcuts area?

$models.getItem("cme:shortcuts").unloadLists();
$models.getItem("cme:custompgs").unloadLists();
$models.getItem("cme:usrtsks").unloadLists();

Again, with each of these items you can just call the unloadLists() method to refresh that specific list. You can even target the child lists of these lists… for example, $models.getItem("cme:chklst"); which would get the Checked-out Items from the My Tasks. If you’re trying to figure out how you can get the identifier to pass to $models.getItem(), a good place to look is the address bar after clicking on the list you wish to target with your code. For example, after clicking on the “Checked-out Items”, you should see “Dashboard.aspx#locationId=cme:chklst” at the end of the address bar. The value of the locationId is what you want to use.

Happy coding everyone!

Crocodoc .NET API Out Of Beta

My colleague Frank Taylor and I are happy to announce that Crocodoc v1.0 for .NET is now out of Beta testing and can be downloaded from its Google Code site. Thanks to everyone who has participated in the 1.0 Beta testing and who has provided feedback or reported any issues.

And for those who may be reading this article wondering what this .NET library is for, check out my previous blog post about its beta release, Frank’s blog entry, or even the Crocodoc site itself.

Besides fixes, only one (overloaded) method has been added to this release. While the previous CrocodocDocument.Upload(string filePath) allowed you to specify a complete file path for you to upload, the method CrocodocDocument.Upload(string fileName, byte[] binary) allows you to upload a document’s byte array directly. This could be useful for when uploading files not from the file system, but say a database or content management system.

Please continue to either contact Frank or myself with any feedback, suggestions, or further issues found. And happy document embedding everyone!

Changing Components’ Schemas With Core Service

Besides making new extensions and applications to extend the features of Tridion, sometimes the Core Service API is a great tool for scripting something that would otherwise take a long time to do manually. A colleague of mine is in need of such a script, and has never worked with the Core Service API before, so I thought I would write this tutorial to help him get on the right track.

The project he’s in has the need to change the schema for a bunch of multi-media components. The GUI does not provide a way to change the schema, as changing schemas for components could lead to data loss. For example, if your metadata values have different names than the schema that you are switching to, data in those fields would be gone. Fortunately for my colleague, there is no metadata on the old schemas.

As my colleague is somewhat new to the world of .NET as well, this tutorial may explain some of the basics of .NET and Visual Studio as well.

The Project Setup

To start, create a new .NET Console Application project in Visual Studio (for this tutorial, I am using Visual Studio 2010 Professional Edition). Lets call it “Examples.ComponentSchemaChanger”. Visual Studio will create a new project with a Program class that contains a static void Main(string[] args) method. This Main method is the entry point for your console application. The args parameter is arguments that you can pass to your application from the command line.

Next, create a folder in Windows in the Solution folder that was created called “Resources”. Here we’ll include all referenced assemblies that our project will use. Since this is a fairly simple script, only one will be needed.

On a Tridion server (or VM), from the /bin/client/ directory of the location where Tridion is installed. Copy “Tridion.ContentManager.CoreService.Client.dll.config” and “Tridion.ContentManager.CoreService.Client.dll” from this location to the Resources folder you created in the previous step. The DLL contains the Core Service API that you will use for this script, and the config contains the configuration bindings that your application will use to connect to Tridion.

Next, lets add the reference to the DLL. Right click the References folder in your Visual Studio project, and select “Add Reference”. Select the “Browse” tab, and then browse to your Resources folder. Select “Tridion.ContentManager.CoreService.Client.dll” and click “Ok”.

You’ll also need to add several of other references. Right click and add references, but this time select the “.NET” tab and add references to “System.Configuration”, “System.ServiceModel” and “System.Runtime.Serialization”.

Now that we have referenced the Core Service library, lets modify the configuration. Right click the project, and select “Add -> New Item”. Under the General section, select “Application Configuration File”. Next copy the contents of “Tridion.ContentManager.CoreService.Client.dll.config” to your “App.config” folder. Right underneath the <configuration> element in your App.config file, add the following:

  <appSettings>
    <add key="CoreServiceEndpoint" value="netTcp_2011" />
    <add key="TridionUsername" value="YOUR TRIDION USERNAME" />
    <add key="TridionPassword" value="YOUR TRIDION PASSWORD"/>
  </appSettings>

The above will let you set the username and password that your script will use to authenticate with the Core Service, as well as which endpoint name to use (more on that later).

The SchemaChanger Class

Let’s add a new class to the project called “SchemaChanger”. Right click the project, click “Add -> Class” and then give it the name “SchemaChanger”.

Now add the following field to your new class:

private SessionAwareCoreServiceClient _client;

You’ll see an error squiggly line and a message of “The type or namespace name ‘SessionAwareCoreServiceClient’ could not be found (are you missing a using directive or an assembly reference?)”. This is because we have not referenced the namespace in a using statement. Let’s let Visual Studio do this automatically for us. Click the squiggly lined “SessionAwareCoreServiceClient”, and when the down arrow appear, click that, and then “using Tridion.ContentManager.CoreService.Client;“. You’ll see the using statement automatically added to the top, and your error message has gone away. For the rest of this tutorial, do the same to any similar errors you encounter to automatically add the the namespaces with the using directive.

Next, let’s add a property to our class that will use a getter accessor for getting our client.

public SessionAwareCoreServiceClient Client
{
    get
    {
        if (_client == null)
        {
            string endpointName = ConfigurationManager.AppSettings["CoreServiceEndpoint"];
            if (String.IsNullOrEmpty(endpointName))
            {
                throw new ConfigurationErrorsException("CoreServiceEndpoint missing from appSettings");
            }

            _client = new SessionAwareCoreServiceClient(endpointName);

            string username = ConfigurationManager.AppSettings["TridionUsername"];
            string password = ConfigurationManager.AppSettings["TridionPassword"];

            if (!String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(password))
            {
                _client.ClientCredentials.Windows.ClientCredential = new NetworkCredential(username, password);
            }
        }
        return _client;
    }
}

What the above is doing is, if our _client variable is null, to create a new instance of SessionAwareCoreSerivceClient using the endpoint that we supply in our appSettings. If _client has already been instanciated, it’ll return it without creating a new instance. We’ll also be using the TridionUsername and TridionPassword appSettings that we set up earlier. If the appConfig does not have these settings, or if they are empty, the application will attempt to use the user that will be running the script. It also checks to make sure the CoreServiceEndpoint appSetting exists, and throws an error if its missing.

Next, lets add a method that’s going to be doing the work for us. Let’s call this method “ChangeSchemasForComponentsInFolder”, and allow it to take 4 arguments: one for the TcmUri of the folder we want to search in, one to allow the operation to happen recursively, the third one for the TcmUri of the schema that we want to change from, and the forth one for the TcmUri of the schema that we want to change the components to.

public void ChangeSchemasForComponentsInFolder(string folderUri, bool recursive, string fromSchemaUri, string schemaUriToChangeTo)
{

}

We can only modify components that aren’t already checked out, so lets create a variable that will keep track of components that we are not able to edit.

    List<ComponentData> failedItems = new List<ComponentData>();

Next we’ll want to open the folder that we are going to search in. We can use the CoreService client’s Read method for this.

    FolderData folder = Client.Read(folderUri, null) as FolderData;

We’ll also want to grab the Schema that we’ll be switching to, and the namespace of that schema.

    SchemaData schema = Client.Read(schemaUriToChangeTo, null) as SchemaData;
    XNamespace ns = schema.NamespaceUri;

Now we’ll create a filter to actually query for multimedia items. We’ll want to make sure to only grab Components, and to only grab components of a Multimedia type. We’ll also want to check for components recursively if we’ve supplied to do so in the passed argument.

    OrganizationalItemItemsFilterData filter = new OrganizationalItemItemsFilterData();
    filter.ItemTypes = new ItemType[] { ItemType.Component };
    filter.ComponentTypes = new ComponentType[] { ComponentType.Multimedia };
    filter.Recursive = recursive;

And finally the actual work of switching the schema of the component. We’ll open up the component in read mode first, and only check it out to modify if the component’s current schema ID matches the schema we want to change from. If the component doesn’t match, we’ll attempt to check it out. If we are successful on checking it out, we’ll change its schema, save, and check back in. If we weren’t successful on checking the item out, we’ll make note of that item to report at the end.

    XElement items = Client.GetListXml(folder.Id, filter);
    foreach (XElement item in items.Elements())
    {
        ComponentData component = Client.Read(item.Attribute("ID").Value, null) as ComponentData;

        if (!component.Schema.IdRef.Equals(fromSchemaUri))
        {
            // If the component is not of the schmea that we want to change from, do nothing...
            continue;
        }

        component = Client.TryCheckOut(component.Id, new ReadOptions()) as ComponentData;

        if (component.IsEditable.Value)
        {
            component.Schema.IdRef = schemaUriToChangeTo;
            component.Metadata = new XElement(ns + "Metadata").ToString();
            Client.Save(component, null);
            Client.CheckIn(component.Id, null);
            Console.WriteLine(String.Format(" - changed schema for {0} ({1}) ", component.Title, component.Id));
        }
        else
        {
            failedItems.Add(component);
        }
    }

This is where the namespace of the schema comes into play with the component.Metadata = new XElement(ns + "Metadata").ToString() Here we are setting up an empty metadata section using the namespace from the Schema that we are switching to. Without this line, you might see an error like “Root element must be in namespace”.

What about that failedItems variable that we were keeping track of? Good catch. Let’s go ahead and report the items that we weren’t able to change by adding the following to the end of our method.

    if (failedItems.Count > 0)
    {
        Console.WriteLine();
        Console.WriteLine("The following items could not be converted. Please have them checked in and try again.");
        foreach (ComponentData component in failedItems)
        {
            Console.WriteLine(component.Id + " :" + component.LocationInfo.WebDavUrl);
        }
    }

Our SchemaChanger class is now complete, and should look something like the following:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net;
using System.Xml.Linq;
using Tridion.ContentManager.CoreService.Client;

namespace Examples.ComponentSchemaChanger
{
    /// <summary>
    /// Script example of changing schemas for multi media components.
    /// </summary>
    class SchemaChanger
    {
        /// <summary>
        /// The session aware core service client.
        /// </summary>
        private SessionAwareCoreServiceClient _client;

        /// <summary>
        /// Gets the SessionAware Core Service client.
        /// </summary>
        public SessionAwareCoreServiceClient Client
        {
            get
            {
                if (_client == null)
                {
                    string endpointName = ConfigurationManager.AppSettings["CoreServiceEndpoint"];
                    if (String.IsNullOrEmpty(endpointName))
                    {
                        throw new ConfigurationErrorsException("CoreServiceEndpoint missing from appSettings");
                    }

                    _client = new SessionAwareCoreServiceClient(endpointName);

                    string username = ConfigurationManager.AppSettings["TridionUsername"];
                    string password = ConfigurationManager.AppSettings["TridionPassword"];

                    if (!String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(password))
                    {
                        _client.ClientCredentials.Windows.ClientCredential = new NetworkCredential(username, password);
                    }
                }
                return _client;
            }
        }

        /// <summary>
        /// Changes schemas for multimedia components located in a specific folder.
        /// </summary>
        /// <param name="folderUri">The tcm uri of the folder to change the items in.</param>
        /// <param name="recursive">Whether or not to perform this recursively on child folders.</param>
        /// <param name="fromSchemaUri">The tcm uri of the schema that we are changing from.</param>
        /// <param name="schemaUriToChangeTo">The tcm uri of the schema to change the components to.</param>
        public void ChangeSchemasForComponentsInFolder(string folderUri, bool recursive, string fromSchemaUri, string schemaUriToChangeTo)
        {
            // Let's keep track of items that couldn't be checked out and report at the end.
            List<ComponentData> failedItems = new List<ComponentData>();

            // Open the folder to check
            FolderData folder = Client.Read(folderUri, null) as FolderData;

            // Open up the schema that we will be changing to.
            SchemaData schema = Client.Read(schemaUriToChangeTo, null) as SchemaData;
            XNamespace ns = schema.NamespaceUri;

            // Create a filter to get all multi-media components.
            OrganizationalItemItemsFilterData filter = new OrganizationalItemItemsFilterData();
            filter.ItemTypes = new ItemType[] { ItemType.Component };
            filter.ComponentTypes = new ComponentType[] { ComponentType.Multimedia };
            filter.Recursive = recursive;

            XElement items = Client.GetListXml(folder.Id, filter);
            foreach (XElement item in items.Elements())
            {
                ComponentData component = Client.Read(item.Attribute("ID").Value, null) as ComponentData;

                if (!component.Schema.IdRef.Equals(fromSchemaUri))
                {
                    // If the component is not of the schmea that we want to change from, do nothing...
                    continue;
                }

                if (component.Schema.IdRef.Equals(schema.Id))
                {
                    // If the component already has this schema, don't do anything.
                    continue;
                }

                component = Client.TryCheckOut(component.Id, new ReadOptions()) as ComponentData;

                if (component.IsEditable.Value)
                {
                    component.Schema.IdRef = schemaUriToChangeTo;
                    component.Metadata = new XElement(ns + "Metadata").ToString();
                    Client.Save(component, null);
                    Client.CheckIn(component.Id, null);
                    Console.WriteLine(String.Format(" - changed schema for {0} ({1}) ", component.Title, component.Id));
                }
                else
                {
                    failedItems.Add(component);
                }
            }

            if (failedItems.Count > 0)
            {
                Console.WriteLine();
                Console.WriteLine("The following items could not be converted. Please have them checked in and try again.");
                foreach (ComponentData component in failedItems)
                {
                    Console.WriteLine(component.Id + " :" + component.LocationInfo.WebDavUrl);
                }
            }
        }
    }
}

The Program Class

Now lets go back to the Program class’ Main method and put our code to work. We’ll allow the user to pass into the command line the arguments for the folder’s tcm uri, whether or not to perform this recursively, the schema uri of the components we want to change from, and the schema uri of the schema to change the components to. We’ll also display some a usage message when an incorrect # of arguments is supplied, a message showing the error if one pops up, and finally a message letting the user know that the script has completed.

static void Main(string[] args)
{
    if (args.Length < 4)
    {
        Console.WriteLine("Usage: Examples.ComponentSchemaChanger  <y/n for recursive>  ");
        Console.WriteLine("Example:");
        Console.WriteLine("Examples.ComponentSchemaChanger tcm:100-12345 y tcm:100-987-8 tcm:100-1234-8");
    }
    else
    {
        string folderUri = args[0];
        string recursive = args[1].ToLower();
        string schemaUriFrom = args[2];
        string schemaUriTo = args[3];

        try
        {
            SchemaChanger changer = new SchemaChanger();
            changer.ChangeSchemasForComponentsInFolder(folderUri, recursive.Equals("y"), schemaUriFrom, schemaUriTo);
        }
        catch (Exception ex)
        {
            Console.WriteLine("There was an error:");
            Console.WriteLine(ex);
        }
    }

    Console.WriteLine();
    Console.WriteLine(" press <ENTER> to continue");
    Console.ReadLine();
}

Building and Deploying

Right click the project and select “Build”. This will compile and build the project for you, putting the files you need in %Project Directory%\bin\Debug\ (or %Project Directory%\bin\Release\ if you are targeting Release). The 3 files that you’ll need are Examples.ComponentSchemaChanger.exe, Examples.ComponentSchemaChanger.exe.config (this is the file containing your app settings), and Tridion.ContentManager.CoreService.Client.dll.

Executing Our Script

Our script is setup to work either on the CMS Server or remotely with a simple configuration change. Remember that CoreServiceEndpoint application config setting that we added? When this setting is “wsHttp_2011″, you’ll be able to run your script remotely (as long as you have access to contact the CMS server from your location), and when this setting is “netTcp_2011″, you’ll be able to run locally on the CMS Server. You can actually run the wsHttp_2011 binding from the CMS Server, but the netTcp binding will perform faster for you.

Whether deployed locally or remotely, open up the command prompt, navigate to the folder you deployed to, and enter the following command:
Examples.ComponentSchemaChanger tcm:12-3456-2 y tcm:12-1000-8 tcm:12-1234

Sit back, and watch magic happen. :)

Again a Warning

Remember as mentioned, changing a component’s schema can lead you to lose data from fields if the field definitions are different. Before trying out the following code, make sure the components you are changing doesn’t contain any such fields that will be lost.

Checking If An Item Is In Workflow With Core Service

During your quest of making custom applications using Tridion’s Core Service API, you may have come across the need to check whether or not an item is currently in a Workflow Process. Luckily, unlike some other tasks you may need to do with the Core Service API, this task is easily done by checking the WorkflowInfo property that is included in the PageData and ComponentData classes.

// Open a page in Core Service.
PageData page = client.Read(yourPageUri, new ReadOptions()) as PageData;

if (page.WorkflowInfo != null)
{
    // Ladies and gentlemen, WorkflowInfo property was not null, this page is in workflow
}
else
{
    // WorkflowInfo property is null, the page is not in workflow
}

Great, but now that you know that your item is in workflow, you’ll probably be wanting to grab some Workflow related items. The good news is, the WorkflowInfo class contains most of the data you’ll need to interact with the Workflow for that item. Here are some common things you’ll probably do with this property:

// Get the ProcessInstanceData from the WorkflowInfo property
ProcessInstanceData processInstance = 
    (ProcessInstanceData)client.Read(page.WorkflowInfo.ProcessInstance.IdRef, null);

// Get the ProcessDefinitionData from the process instnace
ProcessDefinitionData processDefinition =
    (ProcessDefinitionData)client.Read(processInstance.ProcessDefinition.IdRef, null);

// Getting the ActivityInstanceData from the WorkflowInfo property...
ActivityInstanceData activityInstance = 
    (ActivityInstanceData)client.Read(page.WorkflowInfo.ActivityInstance.IdRef, null);

// Get the ActivityDefinitionData from the activity instance
ActivityDefinitionData activityDefinition =
    (ActivityDefinitionData)client.Read(activityInstance.ActivityDefinition.IdRef, null);

// Note that if you only wanted to get the ActivityDefinition's Description, you can get that from the WorkflowInfo's ActivityDefinitionDescription property.
if (page.WorkflowInfo.ActivityDefinitionDescription.Equals(activityDefinition.Description))
{
    // true of course...
}

// Check how long its been since the activity was started...
if (page.WorkflowInfo.StartDate.HasValue)
{
    TimeSpan timeSinceStart = DateTime.Now - page.WorkflowInfo.StartDate.Value;
}

Other Useful Properties of WorkflowInfo

Here are the other properties of WorkflowInfo that wasn’t included in the samples above:

ActivityState: The enum value of the activity’s current state.
Assignee: The Link<TrusteeData> of the assignee.
CreationDate: The Nullable<DateTime> that the activity was created.
FinishDate: The Nullable<DateTime> that the previsou activity instance was finished.
Performer: The Link<UserData> of the activity’s performer.
PreviousMessage: The FinishMessage of the previous Activity.

Crocodoc .NET API Library Released

For those of you reading the title and asking, “What is this Crocodoc???”, Crocodoc is a tool that “converts Microsoft Office and PDF documents to HTML5 so your users can view and collaborate right in your web app.” What that means is, you can present your customers documents such as Word docs, PDFs, and Power Point presentations… embedded and viewable within your web pages. Long are the days where your customers must download your PDFs in order to view them.

That being said, my colleague and friend, Frank Taylor, needed to interact with the Crocodoc v2 REST API, but discovered Crocodoc was missing the .NET API. So after working together, we are now happy to announce that the Beta version of 1.0 for a .NET Wrapper has been released on its Google Code site. If you just want to jump straight into the action, you can download the binaries here. For those of you who might have worked with the Crocodoc Java or PHP API’s, you should feel comfortable with the .NET API.

Although the project’s Google Code site has plenty of samples (and there’s even an Examples project you can download and run as well), here’s a quick sample of its usage.

Crocodoc.ApiToken = "your-unique-api-token-right-here";
string sessionID;

try
{
    // Here, documentUUID is the uuid for the Document that you want to create a session for.
    sessionID = CrocodocSession.Create(documentUUID);
}
catch (CrocodocException ex)
{
    // Log or show error message if the Crocodoc server threw a web exception.
}

The above creates a unique session for a given document so that you can then embed it onto your webpage. The session allows you to set properties such as copyrighted, admin privies, or even allow the writing of annotations for your editors.

Here’s an example of uploading a new document to crocodoc.

try
{
    string newDocUUID = CrocodocDocument.Upload(@"C:\Documents\YourPDF.pdf");
}
catch (CrocodocException ex)
{

}

Your Help?

We have released it as version 1.0 Beta as we would like some of your help and feedback with the library. If you use Crocodoc and have been looking for a .NET API, try it out, and let us know any issues that you run into, or if you have any feature requests.

Quick Links

Crocodoc API Reference
Crocodoc .NET
Crocodoc .NET Binaries

Getting Using and Used Items With Core Services

A while back I posted about how to get Using and Used Items from Tridion using the TOM.NET API. Today I thought I would share again those same examples, only this time using the Core Service API. For those of you who may not know, the TOM.NET API is read only when used in Template Building Blocks, and read/write when used in the Tridion Event System. But, when you want to create custom applications or processes, you’ll want to create them using the Core Service API.

One of the major differences if you’re comparing this article with the TOM.NET one, is that the Core Service API doesn’t actually have a GetWhereUsed() or GetWhereUsing() method on object classes. Instead, we’ll be retrieving XML using the Core Service Client’s GetListXml(string identifier, SubjectRelatedListFileterData filter) method.

You may notice there’s a GetList(id, filter) method too and may be tempted to bypass working with the XML returned from GetListXml… however, as of Tridion 2011 SP1, if you look at the API’s documentation, currently the only filter supported by this method is the OrganizationalItemAncestorsFilterData, so trying to use that method with our UsingItemsFilterData or UsedItemsFilterData from the examples below will fail, and you’ll probably get an error stating “Unexpected List Type”.

Get Using Items (UsingItemsFilterData)

To get using items with Core Services, you just need to pass the GetListXml(id, filter) a filter of type UsingItemsFilterData, and the tcm uri of the item that you want to get the using items for.

GETTING ALL PAGES USED BY A COMPONENT:

SessionAwareCoreServiceClient client = new SessionAwareCoreServiceClient("netTcp_2011");

UsingItemsFilterData filter = new UsingItemsFilterData();
filter.ItemTypes = new [] { ItemType.Page };
filter.IncludedVersions = VersionCondition.OnlyLatestVersions;

XElement pages = client.GetListXml("tcm:12-3456", filter); // Pass in a Component ID

XML Sample Returned By GetListXml:

<tcm:ListUsingItems xmlns:tcm="http://www.tridion.com/ContentManager/5.0">
    <tcm:Item ID="tcm:17-384-64" Title="Some Page Title" Type="64" OrgItemID="tcm:17-107-4" Path="\040 Web Publication\Root\030 - Work" Icon="T64L1P0" Publication="040 Web Publication"></tcm:Item>
    <tcm:Item ID="tcm:31-871-64" Title="Another Page Title" Type="64" OrgItemID="tcm:31-206-4" Path="\050 Another Web\Root\030 - Work" Icon="T64L1P1" Publication="050 Another Web"></tcm:Item>
</tcm:ListUsingItems>

GETTING ALL COMPONENTS USED BY A SCHEMA:

SessionAwareCoreServiceClient client = new SessionAwareCoreServiceClient("netTcp_2011");
                
UsingItemsFilterData filter = new UsingItemsFilterData();
filter.ItemTypes = new ItemType[] { ItemType.Component };
filter.IncludedVersions = VersionCondition.OnlyLatestVersions;
filter.InRepository = new LinkToRepositoryData { IdRef = "tcm:0-31-1" };

XElement components = client.GetListXml("tcm:2-572-8", filter); // Pass in a Schema ID

GETTING ALL SCHEMAS THAT USED A GIVEN EMBEDDED SCHEMA:

UsingItemsFilterData filter = new UsingItemsFilterData
{
    ItemTypes = new ItemType[] { ItemType.Schema },
    IncludedVersions = VersionCondition.OnlyLatestVersions
};

XElement schemas = client.GetListXml("tcm:2-345-8", filter); // Pass in a Schema ID

GETTING ALL COMPONENTS USING A GIVEN KEYWORD:

UsingItemsFilterData filter = new UsingItemsFilterData
{
    ItemTypes = new ItemType[] { ItemType.Component },
    IncludedVersions = VersionCondition.OnlyLatestVersions
};

XElement components = client.GetListXml("tcm:2-213-1024", filter); // Pass in a Keyword ID

Note that the above could have just been retrieved using ClassifiedItemsFilterData.

XElement components = client.GetListXml("tcm:2-213-1024", new ClassifiedItemsFilterData());

Get Used Items (UsedItemsDataFilter)

Getting Used items from Core Service works in the same manner as getting Using items, except that you pass in a UsedItemsDataFilter as the filter instance.

GET THE EMBEDDED SCHEMAS USED IN A GIVEN SCHEMA:

SessionAwareCoreServiceClient client = new SessionAwareCoreServiceClient("netTcp_2011");
XElement schemas = client.GetListXml("tcm:2-184-8", new UsedItemsFilterData { ItemTypes = new[] { ItemType.Schema } });

GET COMPONENTS WITHIN COMPONENTLINKS OF A GIVEN COMPONENT:

UsedItemsFilterData filter = new UsedItemsFilterData
{
    ItemTypes = new ItemType[] { ItemType.Component }
};

XElement components = client.GetListXml("tcm:21-543", filter);

Happy coding everyone!

Getting Using and Used Items With TOM.NET

Periodically I will receive an e-mail from someone in the Tridion community asking questions like “How do I get the pages where a component is used?” or “How do I get all the components using a particular schema?”. Although there is already some good examples out there on retrieving Where Using and Where Used, I figured some more Tridion samples out there could never hurt.

GetUsingItems

The Tridion.ContentManager.IdentifiableObject (the base class that most of the other items in Tridion inherits) has a method called “GetUsingItems” that allows you to get all items using this item. Note that these are the items you see in the “Used in” tab when you use the “Where Used” functionality in the GUI. The UsingItemsFilter argument allows you to refine your query of using items even further.


IdentifiableObject.GetUsingItems()
IdentifiableObject.GetUsingItems(UsingItemsFilter filter)

Getting all pages used by a component:

UsingItemsFilter filter = new UsingItemsFilter(component.Session);
filter.ItemTypes = new List<ItemType> { ItemType.Page };
filter.IncludedVersions = VersionCondition.OnlyLatestVersions;

IEnumerable<IdentifiableObject> pages = component.GetUsingItems(filter);

Getting all components used by a schema:

UsingItemsFilter filter = new UsingItemsFilter(schema.Session);
filter.ItemTypes = new List<ItemType> { ItemType.Component };
filter.IncludedVersions = VersionCondition.OnlyLatestVersions;
filter.InRepository = (Repository)publication; // assuming variable publication is of type Tridion.ContentManager.CommunicationManagement.Publication and the only publication you want the results to return components for

IEnumerable<IdentifiableObject> components = schema.GetUsingItems(filter);

Getting all schemas that used a given embedded schema:

UsingItemsFilter filter = new UsingItemsFilter(embeddedSchema.Session);
filter.ItemTypes = new ItemType[] { ItemType.Schema }; // Note can be an array too
filter.IncludedVersions = VersionCondition.OnlyLatestVersions;

IEnumerable<Schema> schemas = (IEnumerable<Schema>)embeddedSchema.GetUsingItems(filter);

Getting all components using a gien keyword:

UsingItemsFilter filter = new UsingItemsFilter(keyword.Session);

filter.ItemTypes = new List<ItemType> { ItemType.Component };
filter.IncludedVersions = VersionCondition.OnlyLatestVersions;

IEnumerable<IdentifiableObject> components = keyword.GetUsingItems(filter);

Note that the above could have just been retrieved using the keyword’s GetClassifiedItems() method:

IEnumerable<RepositoryLocalObject> components = keyword.GetClassifiedItems();

GetUsedItems

The “GetUsedItems” method of IdentifiableObject works very similarly to the “GetUsingItems” method, but in reverse: it’ll grab items that this item uses. This is the same functionality as the “Uses” tab in the “Where Used” functionality of the GUI.


IdentifiableObject.GetUsedItems();
IdentifiableObject.GetUsedItems(UsedItemsFilter filter);

Get the embedded schemas used in a given schema:

UsedItemsFilter filter = new UsedItemsFilter(schema.Session);
filter.ItemTypes = new ItemType[] { ItemType.Schema };

IEnumerable<IdentifiableObject> embeddedSchemas = schema.GetUsedItems(filter);

Get Components Within ComponentLinks of a given component:

UsedItemsFilter filter = new UsedItemsFilter(component.Session);
filter.ItemTypes = new ItemType[] { ItemType.Component };

var compLinks = component.GetUsedItems(filter);

Getting the List as XML

When working with a pretty large set of items that may get returned, you may want to work with an XML of the used items instead for performance reasons. The following methods return a type of XmlElement:


IdentifiableObject.GetListUsedItems();
IdentifiableObject.GetListUsedItems(UsedItemsFilter filter);
IdentifiableObject.GetListUsingItems();
IdentifiableObject.GetListUsingItems(UsingItemsFilter filter);

Anguilla Framework: Getting Items From Tridion With $tcm.getItem() And Load Events

For anyone wondering if you can get items from Tridion using the Anguilla Framework in your GUI Extensions, the answer is yes, yes you can.

var yourPage = $tcm.getItem("tcm:10-1234-64");

Simple, no? Unfortunately your work is not done here. The getItem() method loads data from a cached state. That means, if the properties that you are looking for hasn’t been loaded already, they will return undefined.

var templateID = yourPage.getPageTemplateId();
// templateID is "undefined".

To load the data, you can call the load() method. You’ll also want to create an event handler for when the event has been triggered.

var yourPage = $tcm.getItem("tcm:10-1234-64");
$evt.addEventHandler(yourPage, "load", function (event) {
    doSomethingWithYourPage(yourPage); // event.source also contains the page instance.
});
yourPage.load();

Remember to take advantage of how Tridion handles the caching. The above script is inefficient, because you’ll always load the item regardless of whether or not it is in the cache. To check if the items has already been loaded, you could do the following:

var yourPage = $tcm.getItem("tcm:10-1234-64");
if (yourPage.isLoaded()) {
    doSomethingWithYourPage(yourPage);
} else {
    $evt.addEventHandler(yourPage, "load", function (event) {
        doSomethingWithYourPage(yourPage); // event.source also contains the page instance.
    });
    yourPage.load();
}

Another possible gotcha is that .load() doesn’t load everything. For example, the WebDav URL. After the .load() call, the following will still not return anything.

var webDavUrl = yourPage.getWebDavUrl();

To get the data you need in the above example, you would have to do something along the lines of:

var yourPage = $tcm.getItem("tcm:10-1234-64"),
    webDavUrl = yourPage.getWebDavUrl();

if (!webDavUrl) {
    $evt.addEventHandler(yourPage, "loadwebdavurl", function (event) {
        webDavUrl = yourPage.getWebDavUrl(); // also could do event.source.getWebDavUrl()
    });
    yourPage.loadWebDavUrl();
}

There are other load functions that load different types of data, each with their own events. Here is a list of them with their associated load and fail event names.

Function Name Load Event Load Fail Event
load() load loadfailed
loadBlueprintInfo() loadblueprintinfo loadblueprintinfofailed
loadItemCompareInfo() compareinfoload compareinfoloadfailed
loadRollBackComment() rollbackcommentload rollbackcommentloadfailed
loadWebDavUrl() loadwebdavurl loadwebdavurlfailed
staticLoad() staticload staticloadfailed