Friday 14 August 2009

Write to Sitecore log file from XSLT

It is simple to write to the Sitecore log file from within an XSLT file without having to write any custom code. We can just hook up to the Sitecore.Diagnostics.Log class and call one of its methods.

In the web.config, define the extension under <xslextensions>:

<extension mode="on"
type="Sitecore.Diagnostics.Log, Sitecore.Kernel"
namespace="http://www.sitecore.net/log"
singleInstance="true" />

Within the XSLT file, add a prefix that matches the namespace you used in the above step:

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:sc="http://www.sitecore.net/scReal"
xmlns:dot="http://www.sitecore.net/dot"
xmlns:log="http://www.sitecore.net/log"
exclude-result-prefixes="dot sc log">

The Log class contains a number of overloads for Info, Warn, Error and so on. Some of these expect an exception as a parameter, so we cannot call these direct from XSLT. We can, however match the overloads that expect a string and an object (eg. Warn( String, Object )):

<xsl:value-of select="log:Warn('Warning message', 'Another string... perhaps the name of your rendering file')" />

That's it! Now you can log whatever you like from within your renderings.

Thursday 6 August 2009

Using Linq lambda expressions to retrieve XML elements based on the value of an attribute

The following example program loads an XML file, then selects all the elements named "field" within it. It then uses a lambda expression to get the inner text of the "alternativeTitle" element.

class Program
{
static void Main( string[] args )
{
XDocument xd = XDocument.Load( "..\\..\\file.xml" );

var fields = from el in xd.Descendants()
where el.Name.ToString().StartsWith( "field" )
select el;

Console.WriteLine( GetElementValue(fields, "alternativeTitle") );
Console.ReadLine();
}

static string GetElementValue( IEnumerable<XElement> elements, string attributeName )
{
return elements.Single( p => p.Attributes().Single( q => q.Name == "name" ).Value == attributeName ).Value;
}
}

The XML file used in the example is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<add>
<doc>
<field name="id">some_id</field>
<field name="readableid">interesting_publications</field>
<field name="name">Interesting Publications</field>
<field name="alternativeTitle">Online publications</field>
</doc>
</add>

The program outputs the text:

Online publications