Skip to content. | Skip to navigation

Personal tools
Log in
Sections
You are here: Home weblog

Dominic Cronin's weblog

Javascript for Tridion scripting

Posted by Dominic Cronin at Oct 09, 2010 07:30 PM |
Filed under: , ,

During the recent Tridion MVP summit, the subject of Javascript came up. That's not surprising, as we were busy with building some GUI extensions to run on the SDL Tridion 2011 CTP, which is a pretty Javascript intensive activity. Most Tridion people reading this won't be too surprised if I say that Javascript isn't really in the comfort zone for many of us. We've done templating in VBScript, and although Tridion has always supported Javascript (or more strictly, JScript) for templating, we've always avoided it. Tridion has never shipped a JavaScript version of the default templates, and I suspect that's why, very early on, VBScript became the VHS to JavaScript's BetaMax. Most people accept that Betamax lost to VHS despite being technologically better, and for the sake of this discussion I'm going to ignore the dissenting opinions that have surfaced recently. In my view JavaScript is a superior technology to VBScript in many ways, but VBScript achieved critical mass in our world, and that's that. Or is it?

Well to start with, I'm not about to suggest that anyone should start to write Tridion component templates in JavaScript. These days, if you're defecting from VBScript templating, you'll be going to a .NET language; probably C#, and I'm all in favour of that. On the other hand, for many of us, JavaScript clearly has a place in our future. If you're writing web applications these days, a solid grasp of js is essential, and as noted already, if you want to customise the Tridion GUI, you'll be elbow-deep in the stuff before you get anything useful done.

For myself, I started using Javascript for simple update scripts and the like quite some time ago, and this mostly means running the scripts from the command line on the server using the cscript processor built-in to Windows. (These days, I also use PowerShell scripting for some of the more ad hoc work, but that's another story.)

The first obvious point about the language is that it has several styles or idioms in common use. For those of you that are familiar with libraries such as JQuery, you'll know that the style can be very similar to what you might encounter in languages with a functional flavour. To gain expertise in this style, I'd strongly recommend jumping in the deep end with John Resig's "Learning Advanced Javascript". (It's a pretty deep deep end. Note to self: have another go soon, and try to understand it this time!)

The other two idioms I'd mention are the object-oriented style, and what I can only describe as Microsoft style. For the object-oriented style, and how to achieve it, you can do no better than to view Doug Crockford's lecture series hosted at Yahoo. I suppose the best place to learn the Microsoft style is MSDN. In the days of the Atlas project, Microsoft tried to use JavaScript as just another layer in the ASP.NET stack, and with some success. For Tridion guys, this style is most notable because some of this flavour is to be seen in the Tridion GUI - or at least that's how it appears to me based on a fairly peremptory poke around. (I'd love someone to tell me if if I'm wrong. Really! Although comments won't show up, as I have to moderate to prevent spam. That's my only moderation criterion, though. If you take the trouble to write a real comment, I'll publish it.)

I hope to return to to the subject of Tridion and Javascript in future posts, but for now, I'd just like to start with a simple example of why it works for me. But please be kind; I'm not a Resig or a Crockford.

It's fairly often useful to be able to recurse through a folder structure and process each item within a given hierarchy. Usually, the processing involves two parts. Firstly, filtering: am I interested in this item or not? Secondly, for the items I'm interested in, I want to run some code, either to report on the item or to alter it in some way. This pattern comes up a lot, and for a lot of the small- to medium-scale jobs, the recurse-filter-process logic is a significant part of the work. Maybe the actual payload only amounts to a couple of lines of code. If you had a simple way to re-use the recurse-filter-process part, you could do a lot of quick-and-dirty jobs, erm... pretty quickly.

In Javascript, I can paste the following function in to a template or a script file, and the recurse-filter-process part is done:

function recurseItems( orgItem, filter, process){
  var items = orgItem.GetItems();
  var eItems = new Enumerator(items);
  for (;!eItems.atEnd();eItems.moveNext()){
    var itemType = eItems.item().ItemType;
    if (itemType === TDSDefines.ItemType.Folder || itemType === TDSDefines.ItemType.StructureGroup){
        recurseItems(eItems.item(), filter, process)
    } else {
      if (filter(eItems.item())) {
          process(eItems.item());
      }
    }
  }
}

I'm quite sure you could tidy this up a bit, but whatever... What makes this so straightforward to re-use is the fact that in JavaScript, functions are first-class objects, and it's very easy to pass functions as arguments to another function, and invoke them from within that function. The recurseItems() function expects to be passed an organizational Item as its first argument. (OK - as written, this won't work for categories, or for the sake of argument, publications, but bear with me...)

The "filter", and "process" arguments are functions.

Let's say I want to list all the components in a given hierarchy. I could write something like this (by which I mean this code isn't tested, it's for illustration purposes, right?):

function isComponent(item){return item.ItemType === TDSDefines.ItemType.Component;}
function outputTitle(item){WScript.Echo(item.Title + "\n";))
var topFolder = tdse.GetObject("tcm:1-1234-2", TDSDefines.OpenMode.View);
recurseItems(topFolder, isComponent, outputTitle);

So with 4 lines of code, I've listed the items I'm interested in. Not bad, eh? OK - I cheated. But how? Take a look at the attached file TDSDefines.js. It's a port of the standard TDSDefines constants to JavaScript. The cheating part is that I instantiate the "tdse" object in there, which somewhat breaks the purity of having a TDSDefines file, but you're always going to want tdse, so wtf not? Anyway - this file is what allows me to type things like "TDSDefines.ItemType.Component", or TDSDefines.OpenMode.View, instead of 16, or 1. JavaScript lends itself very well to this kind of nested data structure, in ways that VBScript would struggle with.

Assuming you are using the cscript host on your Tridion server, and that TDSDefines.js is in the same directory as your script, you'll need to use a couple of lines of code to import your "defines".

    var fso = new ActiveXObject("Scripting.FileSystemObject");
    eval(fso.OpenTextFile(fso.BuildPath(fso.GetParentFolderName(WScript.ScriptFullName), "TDSDefines.js"), 1).ReadAll());

Inside Tridion, of course, TDSDefines.js just becomes a template building block, and gets included in the normal way.

Funnily enough, I never got round to porting the default template code to JavaScript, and now, presumably, I never will. All the same, using JavaScript for this kind of work has allowed me to practice and get more familiar with the language, and to have a toolkit that allows for very, very fast creation of quick-and-dirty recursion scripts among others. It doesn't end there. JavaScript, or perhaps JSON, allows you to take a script-as-data approach which will get you to your desired result much quicker than, for example, having to write scripts that crunch through XML data files. Perhaps that would make a good subject for a future post.

In the meantime, I hope this gives you yet another excuse to hone your JavaScript skills. Those skills will definitely come in useful.

Engineers and bloody fools

Posted by Dominic Cronin at Jul 22, 2010 11:35 PM |
Filed under:

"An engineer is a man who can do for five bob what any bloody fool can do for a quid."

I was scratching around today  for the origin of this quote, or even how the exact quote ought to go. A bit of googling this evening solved it. It was Neville Shute - apparently! At least the quote comes from one of his books, and is probably something he might have said.

http://www.nevilshute.org/Biography/alanbesterbio.php

Just in case anyone's struggling with the "old money" - there were twenty bob in a quid. If anyone is struggling with the social conventions of the day, well I don't suppose women were included in the bloody fools either, but take in any case, take it to your local chapter... nothing to see here.

Extending the boot partition of Windows 2003 Server

Posted by Dominic Cronin at Apr 04, 2010 08:25 PM |
Filed under: ,

In my work I quite commonly have servers on which over time I end up wanting to install more software, or simply upgrading what's there already, but in any case, consuming more disk space than originally envisaged by the person who set up the server. Today I was upgrading a Tridion development image to Tridion 2009 SP1. This was on a VMWare image whose C: drive was maxed out at 16GB. A while ago, I'd filled up the 16GB, and then gone though the rigmarole of trying to make it larger, and failed. At the time, it was more expedient to just add another disk and move some of the data off the C: drive. This approach only gets you so far, and sooner or later, you need a bigger C: drive.

So I'd already got as far as using the VMWare utilities to increase the size of the "physical" disk to 20GB, and then I'd booted the image from a GParted "live CD" .iso. and increased the size of the partition, also to 20GB. The problem was that although in the disk management snap-in you could see the full 20 GB, as far as Windows Explorer was concerned, there were only 16GB (and a pretty full 16GB at that!)

If you've ever been through this, you'll know that it can be about getting the magical incantations just right. The operating systems' own tools won't let you expand the boot partition, or a system partition, or the partition where the page file is or a whole bunch of other strange restrictions. (Yes - strange - even in 2003!) The reason for using gparted in the first place was that you definitely can't do it while Windows is running off the offending partition, and at some time in the past, I'd followed this approach, and it had just worked. Why not now? I don't know.

To cut a long story short, it just sat there staring at me, and wouldn't do what I wanted, when for no really good reason, I booted the system from gparted again, and this time used the "check and repair' utility. It duly checked and repaired, and I rebooted the system normally again, only to see that Windows had now decided that the disk was suspect and wanted to run CHKDSK. I let it run, and hey-presto, when the system came up, Windows Explorer could see the full 20GB. Job's a good'un, eh?

So while I don't have any solid explanation for it all, but in the hope that it helps someone - perhaps myself on some future occasion, I'm adding a blog entry. I don't know whether it was actually something that the gparted check/repair did that fixed the problem. In terms of probabilities, I'm leaning more in the direction that it was CHKDSK that did the actual fixing. If anyone is in the same boat, I'd be interested to know whether just running CHKDSK is sufficient.

How to treat and avoid burns

Posted by Dominic Cronin at Apr 01, 2010 12:05 AM |

I went to a talk this evening given by a lady from the Dutch foundation for burns. She showed a couple of shocking videos, but for me, as a parent of small children, what really caught my attention was the fact that 10 minutes after being poured out, half a cup of tea is sufficient to cause life-threatening burns to a toddler. Be careful out there!

Tweeting from powershell

Posted by Dominic Cronin at Mar 30, 2010 11:45 PM |
Filed under:

This evening, instead of hanging out at the Microsoft Dev Days Geek Night, I drove home, put the kids to bed, and sat down to figure out how to update my Twitter status from the Windows Powershell. This was inspired by the bash one-liner using curl that I learned about from Peteris Krumins’ blog (recommended). Well, it turns out not to be a one-liner in powershell, but FWIW - here's how!

 

function tweet([string] $status) {
   #http://blogs.msdn.com/shitals/archive/2008/12/27/9254245.aspx
  [System.Net.ServicePointManager]::Expect100Continue = $false
  try {
    $wc = new-object System.Net.WebClient
    $wc.BaseAddress = "http://twitter.com"
    $wc.Credentials = new-object System.Net.NetworkCredential
    $wc.Credentials.UserName = "Your account name"
    $wc.Credentials.Password = "password"
    $stream = $wc.OpenWrite("statuses/update.xml")
    $writer = new-object System.IO.StreamWriter -ArgumentList $stream
    $writer.Write("status=" + $status) 
  }
  finally {
    $writer.Dispose()
    $stream.Dispose()
    $wc.Dispose()
  }
}

A noteable namesake

Posted by Dominic Cronin at Mar 06, 2010 07:35 PM |

Apparently, I have a noteable namesake; there was a Dominic Cronin who played cricket for Ireland. Who knew?

http://www.cricketeurope4.net/CSTATZ/irelandall/bio/c/cronin_d.html

More on code re-use and libraries.

Posted by Dominic Cronin at Feb 28, 2010 07:30 PM |

Back in June, I wrote a blog post in reaction to Udi Dahan's "The fallacy of ReUse". Now Mark Needham has published a blog post with a very similar theme. One interesting insight is that sometimes sharing domain objects can be dangerous, because as he puts it "although we often do have the same domain concepts in different projects, it's quite rare that they mean exactly the same thing".

Definitely worth a read.

SDL Tridion MVP award

Posted by Dominic Cronin at Feb 24, 2010 10:30 PM |

Today the official announcement has been made of the awards in SDL's Tridion MVP (Most valued professional) programme.

I'm on the list. I'm now a Tridion MVP. [insert happy-dance here]

I'd like to say I'm surprised and honoured, but as I was on the committee responsible for making the awards, I'll have to settle for simply being honoured. (Of course, I wasn't allowed to vote for myself.) The award is given to those people who have been most visibly involved in community activities in the world of Tridon. This mostly means being willing to share ones knowledge and experience with others, for example on the Tridion technical forum, ideas site or building blocks exchange. Notwithstanding the fact that participating in these activities is a pleasure in itself, I am very pleased to receive the award, and to be counted in the same company as the other MVPs.

I really hope that now as a group we can go on to do even more, and that the whole will prove to be greater than the sum of the parts.

So to my fellow committee members, and to the Tridion community at large; thank you.

XML Namespaces aren't mandatory, and tools shouldn't assume that they are.

Posted by Dominic Cronin at Jan 02, 2010 11:40 PM |
Filed under: , ,

In his recent blog posting on XML Namespaces, James Clark questions the universal goodness of namespaces. Of course, there is plenty of goodness there, but he's right to question it. He says the following:

For XML, what is done is done.  As far as I can tell, there is zero interest amongst major vendors in cleaning up or simplifying XML. I have only two small suggestions, one for XML language designers and one for XML tool vendors:

  • For XML language designers, think whether it is really necessary to use XML Namespaces. Don’t just mindlessly stick everything in a namespace because everybody else does.  Using namespaces is not without cost. There is no inherent virtue in forcing users to stick xmlns=”…” on the document element.

  • For XML vendors, make sure your tool has good support for documents that don’t use namespaces.  For example, don’t make the namespace URI be the only way to automatically find a schema for a document

It's the second point that interests me. During a recent Tridion project, there was a requirement to accept data from an external source as an XML document. I wanted to use a Tridion component to store this data, as this would give me the benefits of XML Schema validation, and controlled publishing. The document didn't have a namespace, although it had a schema. In order to get this to work with Tridion, I had to go to the provider of the document, and get them to add a namespace. Tridion wouldn't allow me to create a schema whose target namespace was empty. It seemed a shame that even when hand-editing the schema (so presumably asserting that I knew what I was about) the system wouldn't let me make this choice.

At the time, I just got the other party to make the change, and went back to more important things. Maybe there's some internal constraint in the way Tridion works that prevents them from supporting this, or maybe it's such an edge case that no-one was ever bothered by it. If the former, then I can't think what the problem would be; there's no reason to abuse the namespace to locate the schema. Tridion's quite happy enough to allow several schemas targetting the same namespace, so what's so special about the "no" namespace? In Tridion components, XML attributes (quite correctly) are in no namespace, but as long as the correct schema gets used for validation, so what?

I suspect it's more likely that this just comes under the "edge case" heading, in which case, perhaps they can improve it in a future release.

Dilbert finder

Posted by Dominic Cronin at Jan 01, 2010 05:45 PM |

A long time ago, I worked in a job where the boss was "pointy-haired", and we habitually referred to some of the manifestations of his pointy-hairedness as "mauve". Why was this? Well it all came about as a reference to a specific Dilbert cartoon. Tioday I followed a link from Raymond Chen and ended up at the Dilbert strip finder. I typed in database (why not mauve?), and the second hit was the cartoon that explains it all. What's not to like?