Skip to main content

A DD4T.net Implementation - Navigation

Most of the websites I have worked on already existed before upgrading them to DD4T. This means the navigation has already been implemented, usually as means of publishing an XML file from Tridion (most always called navigation.xml ;-) ), and then rendered dynamically at request time by means of XSLT transformation.

This setup makes it quite easy to implement navigation in DD4T. I always try to reuse what I have, and the existing navigation.xml is a perfect candidate. We can reuse the Tridion template and Template Building Block that generates the navigation without any modification.

The generated navigation.xml can be even published to file-system, so other parts of the website can still use it. Alternatively, we can store it in the Content Delivery DB.

The approach for generating navigation in DD4T relies in creating an object model from the navigation XML by deserialization, then caching it for faster performance. Everything is wrapped inside a singleton factory wired through Ninject (or whatever other dependency injection framework you happen to use), and voilà -- you've got navigation.

Object Model

First we need a model to hold the navigation objects. We have the navigation XML, which usually represents a structure of very similar nested nodes.

<root>
  <nav uri="tcm:1-2-4" title="Root" url="/default.aspx">
    <nav uri="tcm:1-3-4" title="Products" url="/products/default.aspx">
      <nav uri="tcm:1-4-64" title="Product 1" url="/products/product-1.aspx"/>
      <nav uri="tcm:1-5-64" title="Product 2" url="/products/product-2.aspx"/>

We need to create model classes with properties for each attribute in the XML. Luckily, Visual Studio has already a tool that does that automatically -- xsd.exe.

C:\Temp>xsd navigation.xml
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 4.0.30319.33440]
Copyright (C) Microsoft Corporation. All rights reserved.
Writing file 'C:\Temp\navigation.xsd'.

C:\Temp>xsd navigation.xsd /classes
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 4.0.30319.33440]
Copyright (C) Microsoft Corporation. All rights reserved.
Writing file 'C:\Temp\navigation.cs'.

The execution of the xsd.exe program above generates model class navigation.cs, which after some beautification, looks something like this:

using System.Xml.Serialization;

public partial class nav
{
    private nav[] nav1Field;
    private string uriField;
    private string titleField;
    private string urlField;

    [XmlElementAttribute("nav")]
    public nav[] nav1
    {
        get { return this.nav1Field; }
        set { this.nav1Field = value; }
    }

    [XmlAttributeAttribute()]
    public string uri
    {
        get { return this.uriField; }
        set { this.uriField = value; }
    }

    [XmlAttributeAttribute()]
    public string title
    {
        get { return this.titleField; }
        set { this.titleField = value; }
    }

    [XmlAttributeAttribute()]
    public string url
    {
        get { return this.urlField; }
        set { this.urlField = value; }
    }
}

And after some more beautification, the code looks like this (note that I added property ParentItem and marked it ignorable while deserialization -- this will hold a reference to the parent navigation item):

using System.Xml.Serialization;

[XmlRoot(Namespace = "", ElementName = "root", IsNullable = false)]
public partial class Navigation
{
    [XmlElement("nav")]
    public NavigationItem[] Items { get; set; }
}

[XmlRoot(Namespace = "", IsNullable = false)]
public partial class NavigationItem
{
    [XmlElement("nav")]
    public NavigationItem[] ChildItems { get; set; }

    [XmlIgnore]
    public NavigationItem ParentItem { get; set; }

    [XmlAttribute("uri")]
    public string Uri { get; set; }

    [XmlAttribute("title")]
    public string Title { get; set; }

    [XmlAttribute("url")]
    public string Url { get; set; }
}

Deserialization

Next, we need to deserialize the XML into our model class. The method below performs the deserialization of an XML navigation file. Similar code could be used to deserialize a String representing navigation XML coming from the database.

private T ParseXml<T>(string filePath) where T : class
{
    try
    {
        using (XmlReader reader = XmlReader.Create(filePath,
            new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Document }))
        {
            return new XmlSerializer(typeof(T)).Deserialize(reader) as T;
        }
    }
    catch (IOException ioe)
    {
        LOG.Error("Can't read navigation file " + filePath, ioe);
        return null;
    }
}

The ParseXml method is to be called from the NavigationFactory, but more about that in a follow-up post.

    Navigation navigation = ParseXML<Navigation>(navigationFilePath);

Check out the follow-up post Navigation (part 2) for a showcase of the NavigationFactory and a way of creating a fully-linked navigation object model.


Comments

Popular posts from this blog

Running sp_updatestats on AWS RDS database

Part of the maintenance tasks that I perform on a MSSQL Content Manager database is to run stored procedure sp_updatestats . exec sp_updatestats However, that is not supported on an AWS RDS instance. The error message below indicates that only the sa  account can perform this: Msg 15247 , Level 16 , State 1 , Procedure sp_updatestats, Line 15 [Batch Start Line 0 ] User does not have permission to perform this action. Instead there are several posts that suggest using UPDATE STATISTICS instead: https://dba.stackexchange.com/questions/145982/sp-updatestats-vs-update-statistics I stumbled upon the following post from 2008 (!!!), https://social.msdn.microsoft.com/Forums/sqlserver/en-US/186e3db0-fe37-4c31-b017-8e7c24d19697/spupdatestats-fails-to-run-with-permission-error-under-dbopriveleged-user , which describes a way to wrap the call to sp_updatestats and execute it under a different user: create procedure dbo.sp_updstats with execute as 'dbo' as

Content Delivery Monitoring in AWS with CloudWatch

This post describes a way of monitoring a Tridion 9 combined Deployer by sending the health checks into a custom metric in CloudWatch in AWS. The same approach can also be used for other Content Delivery services. Once the metric is available in CloudWatch, we can create alarms in case the service errors out or becomes unresponsive. The overall architecture is as follows: Content Delivery service sends heartbeat (or exposes HTTP endpoint) for monitoring Monitoring Agent checks heartbeat (or HTTP health check) regularly and stores health state AWS lambda function: runs regularly reads the health state from Monitoring Agent pushes custom metrics into CloudWatch I am running the Deployer ( installation docs ) and Monitoring Agent ( installation docs ) on a t2.medium EC2 instance running CentOS on which I also installed the Systems Manager Agent (SSM Agent) ( installation docs ). In my case I have a combined Deployer that I want to monitor. This consists of an Endpoint and a

Debugging a Tridion 2011 Event System

OK, so you wrote your Tridion Event System. Now it's time to debug it. I know this is a hypothetical situtation -- your code never needs any kind of debugging ;) but indulge me... Recently, Alvin Reyes ( @nivlong ) blogged about being difficult to know how exactly to debug a Tridion Event System. More exactly, the question was " What process do I attach to for debugging even system code? ". Unfortunately, there is no simple or generic answer for it. Different events are fired by different Tridion CM modules. These modules run as different programs (or services) or run inside other programs (e.g. IIS). This means that you will need to monitor (or debug) different processes, based on which events your code handles. So the usual suspects are: dllhost.exe (or dllhost3g.exe ) - running as the MTSUser is the SDL Tridion Content Manager COM+ application and it fires events on generic TOM objects (e.g. events based on Tridion.ContentManager.Extensibility.Events.CrudEven