DD4T Continued: rendering component presentations

In my previous post I discussed how to get started with ASP.NET MVC3 and Tridion using the opensource DD4T framework.
In this post I want to show you how DD4T handles the rendering of ComponentPresentations on a page.

In my previous example, the whole HTML of the (Tridion)page was rendered by only 1 (razor)view. This is not a desired scenario, because it leads to big views and re-use is almost impossible.
Tridion handles this quite nicely by using Component Templates. These templates are responsible for rendering their own little piece of content. And this is exactly what you want in your webapplication.

So, how to implement this using the DD4T framework? Lets find out by creating a simple page.

First, create a page in Tridion with 2 (or more) ComponentPresentations and publish the page. (Make sure your Component Templates are DD4T templates and have a metadatafield called ‘view’ with the name of an existing view in it!. See my previous post on how to create a DD4T Component/Page Template)

DD4T needs to know which (default) Controller to use. This needs to be configured in your Web.config. Add the following 2 lines of code in your Web.config:

    <!-- Config values for the DefaultComponentPresentationRenderer-->
<add key="Controller" value="TridionComponent"/>
<add key="Action" value="Component"/>

Next, we have to write some code to handle the rendering of the ComponentPresentations.
1. Create a new controller and name it ‘TridionComponentController’.
2. Add the following code in this controller:

using System.Web.Mvc;
using DD4T.Mvc.Controllers;
using DD4T.ContentModel;

namespace Sample_WebApplication.Controllers
{
    public class TridionComponentController : TridionControllerBase
    {

        public ActionResult Component(ComponentPresentation componentPresentation)
        {
            return base.ComponentPresentation(componentPresentation.Component.Id);
        }
    }
}

This controller is used to render each ComponentPresentation on a page. The TridionControllerBase class reads the metadata from each ComponentPresentation to find out which razorview to use. The result of the Action-method is a rendered componentpresentation.

Now, create a folder ‘TridionComponent’ in the ‘Views’ folder, and create a new razoriew. Give this view the same name as you defined in the metadata of your ComponentTemplate. So, in my case that is ‘Article’.
Add your HTML to this new View. My Article view looks like this:

@using DD4T.ContentModel;
@using DD4T.Mvc.Html;
@model IComponentPresentation

Component title: @Model.Component.Title

<h1>@Model.Component.Fields["title"].Value</h1>
<p>@Html.Raw(Model.Component.Fields["summary"].Value)</p>
<p>
    @Html.Raw(Model.Component.Fields["body"].Value)
</p>

Now we have to adjust our main view to NOT render the ComponentPresentations inline, but to use our new controller and the DD4T ‘ComponentPresentation’ Action method.
Open your Page view (In the folder TridionPage, General.cshtml) and add the following code:

@using DD4T.ContentModel;
@using DD4T.Mvc.Html;
@model IPage

<html>
<head>
<title>@Model.Title</title>
</head>
<body>
<p>
Some info about this page:<br />
Filename: @Model.Filename<br />
Title: @Model.Title<br />
Publication Title: @Model.Publication.Title<br />
</p>

<h2>ComponentPresentations on this page</h2>
@Html.RenderComponentPresentations()
</body>
</html>

Notice the @Html.RenderComponentPresentations()? This is a HTML helper from the DD4T framework that renders all the componentpresentations on the page, using our newly created ‘TridionComponentController’.

This ‘RenderComponentPresentation’ HTML helper renders ALL the ComponentPresentations, but often you only want to render certain ComponentPresentations. For instance, you want to render ‘Banner’ components in another section on your page then your ‘Article’ elements.
This can be achieved by using one of the overloads from the ‘RenderComponentPresentations’ HTML helper.

To only render ComponentPresentations that are based on a certain schema, you can use this code:

@Html.RenderComponentPresentationsBySchema("ArticleSchema")

To render ComponentPresentations based on a certain ComponentTemlate, you can use this code:

 @Html.RenderComponentPresentationsByView("Article")

Or, if you want to render ComponentPresentations based on multiple ComponentTemplates, you can use this code:

 @Html.RenderComponentPresentationsByView(new[] {"Article", "FullArticle" })

I hope this helped you to understand how ComponentPresentations are handled by the DD4T .NET framework.
Let me know if you have more questions or problems using the above code.

Advertisement

Getting started with ASP.NET MVC3 and Tridion

Introduction

In this post I am going to explain how to set up and use the Dynamic Delivery For Tridion Framework. If you haven’t heared of this framework check out this site: http://code.google.com/p/dynamic-delivery-4-tridion/
In short: Dynamic Delivery For Tridion (DD4T) is an ASP.NET MVC3 framework specifically designed to build a web(site) application using SDL Tridion.

Prerequisites:
1. Visual Studio 2010 (With Entity Framework 4.1 installed and MVC3)
2. SDL Tridion 2011 Content Management Server
3. SDL Tridion 2011 Content Delivery Instance
(The DD4T Framework also supports SDL Tridion 2009. But in this post I use SDL Tridion 2011)

Also make sure that you are publishing everything to the Tridion Broker Database. (You can configure this in the cd_storage_conf.xml)

High level overview

For a highlevel overview of the framework, check out this url: http://prezi.com/tzxk2w9ic284/developing-with-aspnet-mvc-and-tridion/

To get your website up and running using the DD4T framework, the following steps are needed:

  1. Upload the Dynamic Delivery Template Building Blocks to your Content Management Server
  2. Create Component Templates and Page Templates using the Dynamic Delivery Template Building Blocks
  3. Create a webapplication that uses the DD4T DLL’s to show your published page

Getting started

Download the sources from code.google.com
(Use a SVN Client like TortoiseSvn in combination with a Visual Studio plugin like AnkhSvn)

The sources contain the Java version and the .NET MVC3 version of the project. We are only interested in the .NET MVC3 version of the framework.

Template Building Blocks

First, we have to upload the Template Building Blocks to the Tridion Content Management Server.
Check out this WIKI page on how to upload the templates

Component Templates and Page Templates

Once you uploaded the Template Building Blocks, you can use these to create Page- and Component Templates. To create a Component Template, open up the Templatebuilder tool and create a new Component Template. Drag and drop the following (DD4T) Building Blocks on your template:

  • Generate dynamic component
  • Publish binaries for component

Also, create a Page Template with the following (DD4T) Building Blocks:

  • Generate dynamic page
  • Publish binaries for page

Next, create a simple meta-data schema with one single line text (Preferably it’s a selectlist with values from a category) for usage on the newly created Component- and Page Template.
This schema allows you to tell the DD4T framework which View (visual representation, ASP.NET MVC3 Razor template) to use when this Page/Component is rendered in the browser.
Xml name of the field should be ‘view’.

Component Template for Articles, using the View ‘Article’:

Do the same for the Page Template: Give it a metadata-schema, with one field called ‘view’ and insert which view to use in the framework:

Visual Studio Projects setup

Open up Visual Studio and create new project of type ‘ASP.NET MVC3 Web Application’ (Make sure you are using the Razor view engine)

Next, we are going to add some projects (dll’s) from the just downloaded DD4T framework. Choose from the ‘File’ menu for ‘Add’ -> ‘Existing Project’. Add the following DD4T projects to your solution:

  • DD4T.ContentModel
  • DD4T.ContentModel.Contracts
  • DD4T.Factories
  • DD4T.Mvc
  • DD4T.Providers.SDLTridion2011 (Or DD4T.Providers.SDLTridion2009 if you are using SDL Tridion 2009)

Your solution looks something like this:

Remark: in a real life application you don’t want hard references to all these dlls. You want to load the dependencies by means of Dependency Injection (Unity, MEF, etc)
Next, we have to copy some Tridion dll’s into the following folder: %DD4T Install Path%\dependencies\Tridion 2011 DLLs. In here you find a file called ‘Missing files’. Read it, and copy-paste all the Tridion Dll’s into this folder.
Now, add all the DD4T projects as a reference to your MvcApplication. Your solution should build fine now.

The DD4T framework uses the web.config to find out from which publication to request content. Add the following 2 keys to the web.config. (Of course, fill in your publication id)

<add key="Site.ActiveWebsite" value="Corporate.En"/>
<add key="WebSite.Corporate.En.PublicationId" value="7"/>

Writing *some* code

Now we have added all the necessary framework parts, it’s time to wire up our first controller so we can view our page in the browser. Luckily for us, the DD4T framework has already done a lot for us. Al we have to do is to use the right methods and classes!
If you aren’t familiar with the .NET MVC pattern, this is roughly how it looks like:

  1. Url is typed into the browser
  2. Request is fired to the webserver and our webapplication. It goes through a ‘rout-engine’ (Global.asax) to find out what to do with this url (request)
  3. This route-engine looks at the url and based on the parts of the url it sends it to a controller
  4. The controller builds up the Model and passes this model on to the View
  5. The (razor)View renders the HTML and pushes the output back to the browser

First step is adding a rule to the Global.asax that makes sure that (for now) all requests are handled by the same controller. Add the following code to the ‘RegisterRoutes’ method from the Global.asax:

routes.MapRoute(
               "TridionPage", // Route name
               "{*PageId}",
               new { controller = "TridionPage", action = "Page" }, //Parameter defaults
               new { pageId = @"^(.*)?$" } //Parameter constraints
           );

This makes sure that every request is passed on to the TridionPageController.

Time to make the TridionPageController! Go to your MvcApplication and create a new controller. Right click on the ‘Controller’ folder in the solution explorer and choose ‘Add’-> ‘Controller’.
Name it: TridionPageController

By default all controllers from ASP.NET MVC inherit from the Microsoft Controller class. We don’t want this. We want to inherit from the TridionControllerBase class from the DD4T.Mvc project.
Make sure your TridionPageController inherits from the TridionControllerBase:

public class TridionPageController : TridionControllerBase
{
        public TridionPageController()
        {
            this.PageFactory = new DD4T.Factories.PageFactory();
            this.PageFactory.PageProvider = new DD4T.Providers.SDLTridion2011.TridionPageProvider();
        }
}

Remark about the above code: The factories and providers are created here for simplicity. In a real world scenario you don’t want to do this, but you want to load the Factories and Providers by means of Dependency Injection (Unity, MEF, etc). But for now it’s ok.

The TridionControllerBase defines a set of useful methods. We want our controller to look up the page (url) we requested in the browser from the Tridion Broker Database. Normally you would write code, using the Tridion dll’s to retrieve the Pagecontent from the Tridion Broker Database yourself, but the DD4T framework has already done this for us.

Add the following code to the TridionPageController:

public override ActionResult Page(string pageId)
{
    return base.Page(pageId);
}

This method retrieves the PageContent from the Tridion Broker Database by finding the Page by it’s Url (pageId = Url). So, make sure you published a page to the Tridion Broker Database using the DD4T Templates!

The View

The ‘Page’ method returns *something*, but we have to define of course how that ‘something’ needs to be visualed. In other words: we need to create a (razor) view.
ASP.NET MVC3 uses a pattern to find the right View to visualize this page and it uses (among others) the name of the Controller to find the view. So, in the ‘Views’ folder, create a new folder
‘TridionPage’. In here we have to define the View. Remeber the metadata schema we made for Component- and Page Templates? Well, your Pagetemplate has this metadata on it, and you gave it a meaningfull name. I named mine ‘General’. So I have to create a view named ‘General’. Here is how my folder structure looks like:

Views contain the HTML. Here we define how our page looks like. One of the advantages of the DD4T Framwork is, that you can have strongly typed views. This means that you tell your View that he (she) needs to render HTML for object of type IPage or IComponent or String (not very usefull) or MyArticleObject, etc. This gives you full intellisense when writing your View.

Your view needs to render the HTML for an IPage object. (IPage object comes from the DD4T Framework).
Add the following code to your view:

@using DD4T.ContentModel;
@model IPage</pre>
<h2>@Model.Title</h2>
<pre>
    Some info about this page:

    Filename: @Model.Filename

    Title: @Model.Title

    Publication Title: @Model.Publication.Title

Component presentations on this page:</pre>
<ul>
<ul>@{</ul>
</ul>
&nbsp;
<ul>
<ul>foreach (IComponentPresentation cp in Model.ComponentPresentations)</ul>
</ul>
&nbsp;
<ul>
<ul>{</ul>
</ul>
&nbsp;
<ul>
<ul>
	<li>@cp.Component.Fields["title"].Value</li>
</ul>
</ul>
&nbsp;
<ul>
<ul>}</ul>
</ul>
&nbsp;
<ul>}</ul>
<pre>

ASP.NET automatically wires up the properties from the IPage to the ‘Model’ keyword because we told this View that he (she) is destined to render HTML for an IPage object. (The ‘@model IPage’ directive).

And now: RUN! (F5)
Make sure you are requesting an Url that is published to the Tridion Broker Database 🙂

I hope this gives you enough information to get started with the DD4T Framework. The framework is actively developed and it is already running live in at least one big financial organisation.
So far everything runs just fine 🙂

Disclaimer:This example is provided as is and is simplified for the obvious reasons.

Tridion and ASP.NET MVC3

My current project involves (re)building a Intranet based on SDL Tridion 2009 and ASP.NET MVC3.
In this post I want to share how we set things up and how we build it.

The goal was to build a re-usable, flexible and -last but not least- opensource framework  on top of Tridion based on ASP.NET MVC3.
Re-usable so Tridion consultants can use it in all their projects. Flexible so functionality can be added easily and opensource so anybody can contribute.
Of course our first concern was to deliver a full-blown website based on SDL Tridion.

As you may know, MVC stands for Model, View, Controller and is a programming principle used in many languages, mostly in java based languages. Microsoft thought they couldn’t stand
at the sideline and watch, so they came up with their own implementation of MVC, and the called it, well ASP.NET MVC3. (3 being the version number. Version 4 is already in development)

To fulfill the 3 requirements for an MVC3 webapplication, you have to deliver/build the following parts:

  • Model          -> Can roughly be seen as the data coming from Tridion (Pages, components, etc.)
  • View             -> The markup to show the Data (Html)
  • Controller   -> The way how to get/build-up the Data and pass it to the View. In Tridion words: Connect to the Broker Database and build a Model.

To be able to build a Model from the data from Tridion on the Content Delivery side, this data must be stored in the Content Delivery Database. And this should be more than just meta-data because
we need to build a complete page, including ‘normal’ field-values to show on your website. To do this, we used the Tridion Dynamic Delivery Templating project. This (compound) templating project is developed by SDL Tridion and
creates XML from the components and pages. We then publish this XML to the broker database. Now the rough Model of our data (content) exists in the database and we need to pull it out in order to build a nice looking content-page.

How to get the data (content) and build a model

An ASP.NET MVC3 application uses a route-engine to route URL’s to Controllers. (based on the url-parts). In this Controller the Model is build and passed on to the View.
Since this paradigma goes for all URL’s the Dynamic Delivery Framework has a BaseController (inherits from Controller) which does this for you:
It uses the Factory’s project (to be precise the ‘PageFactory’) to query the broker for a page with a certain URL (the URL the user entered in the browser).
It then desirializes the XML returned from the broker into a Page (Dynamic Delivery Page) object and voila: you have your page model.
This Page contains all of the data needed to create a nice looking webpage. It contains for instance: Id, Title, FileName and last but not least: Componentpresentations.
The Page object almost looks like the Tridion Object Model Page-object. It contains most of the familiar properties.
Same goes for ComponentPresentation. This object contains the 2 most important properties: ComponentTemplate and Component.

How to visualize the Model

When you have build your Model in the controller, you have to pass it on to a view. A view is the visual representation of your Model.
ASP.NET Mvc3 ships with 2 view-engines: aspx and razor. We used the razor-engine to create our views.
Razor gives you the full power of C# to script your views. One of the main adavantages of razor-views
is that you can have typed-views. This means that you have full intellisense in your view!

You could write something like this in your view:

@model IComponentPresentation</pre>
<h1>@Model.Component.Fields["title"].value</h1>
<p>
@Model.Component.Fields["articlebody"].value
</p>

This looks pretty familiar right? This could easily be taken to the next level. It would be nicer if your view is of type, lets say: Article. Well, this could easily be achieved by building your own Model out of the ComponentPresentation Model. In your Controller you would write something like this:

Article homepageArticle = new Article();
homepageArticle.Title = ComponentPresentation.Component.Fields["title"].value;
homepageArticle.BodyText = ComponentPresentation.Component.Fields["articlebody"].value;

If you then pass this Article-model into the view,  you can write your View as follows:

@model IArticle
<h1>@Model.Title</h1>
<p>
@Model.BodyText
</p>

Pretty nice isn’t it?

The Framework

The framework we build does almost all of the ‘standard ASP.NET MVC3’ actions for you. For instance it does this for you out of the box:

  • Query the broker to find the right page (using the Url)
  • Ability to render the componentpresentations separately.
  • Build an ASP.NET sitemap by using the XML published to the broker (template to render sitemap XML not yet included. Can be downloaded from the forum)
  • Link resolving
  • and much more.

You can download the project here: http://code.google.com/p/dynamic-delivery-4-tridion/

Pro’s and con’s

Every development approach has it pro’s and con’s.

Pro’s

  • Separation of concerns (MVC)
  • Development
    Development is made easy because all you need is a Visual Studio environment and you are ready to go. You don’t need Tridion Content Delivery to be installed on every development machine.
    We build a WCF service which query’s the broker and returns all the XML we need. Developers only have to reference the WCF service and are ready to go. They don’t have to know much about
    Tridion. They can program as they are used to. Making Models, Views, etc.
  • Releasing
    Releasing changes is a copy-paste action. Copy some (versioned!) dll files into the bin-directory and you are done. Most of the time you don’t have to re-publish your whole site. If you have set up your views in a smart way (using master-views) you can for instance update your website layout by copy-pasting the new dll file and you are done. No need te re-publish.
  • Familiarity
    In ASP.NET MVC3 the same concepts as in Tridion are used. You can have a masterview (PageTemplate). You can have ‘partial views’ in a view (Placeholder in Pagetemplate where you render the ComponentPresentations).

Con’s

  • (Layout)Changes are not applied in the usual way of publishing pages/components. But by copy-ing dll files. This is (very) different from publishing changes with Tridion for instance. (What the business is used too)
  • Preview in Tridion does not work out of the box. (It is possible, but it requires some work)

Contributors

You are free to contribute. Just download the project from GitHub and get started! (There is a Quick start document in the Wiki)

There is a lot I didn’t tell because nobody wants to read a long, (boring) blogpost. If you need more info or want to ask questions: feel free to mail or make remarks in the comments.
I will add a follow up blogpost describing the framework in more detail if this is necessary. Let me know.

Updated to GA – Releasemanagement with SDL Tridion 2011

Finally I did find the time to update the releasemanagement extension to match the GA requirements.

I deleted a bunch of unnecessary files and updated the eXtension.config. Also updated part of the code to perform better.

You can download the new version here. There is an updated howto.txt included with install instructions.
(My previous post is also updated with the new downloadlink)

Releasemanagement with SDL Tridion 2011

One thing I always discover (again!) when I work on a Tridion project, is the lack of release management. We develop new schemas, templates, edit existing ones and maybe create (config)components.

Developers have to keep track of all these changed items, because when the release/project/fix is ready, it has to be installed on the other Tridion servers. Normally I kept track of the changed items using an excel sheet. But boy is that tedious.

After finishing development we always use Contentporter to port the new/edited items to the next environment. So I print the excel-sheet, open Contentporter and have to go through the list and select each item individually. This is besides annoying, also error prone.

I thought this could be automated. So I created an extension for the SDL Tridion 2011 CTP. It involves a context-menu extension and a ribbontoolbar extension.

Releasemanager context menu extension

You can add an item to a release by right-clicking on it. A popup is shown with all the available releases. You can select the release the item belongs to and you’re done.

When the release is ready to be installed on the other Tridion servers, all we have to do is create a Contentporter export- and import file. You can do this by clicking on the ‘Releasemanager’  button on the ribbontoolbar. It opens a popup which let you create the Contentporter files.

Releasesmanager SDL Tridion

With Contentporter 2009 you can easily use these Export- and Import settings file to create an export and later import this on the next Tridion environment.

When you open Contentporter 2009 you can choose from 4 options. If you select the 4th option ‘Load wizard settings from a file’, you can use the just created export/import files to create an export for your release.

After you are finished with the release there is an option to finalize the release. The items are removed from the Releasemanager DB (Xml file) and placed into an history folder. There is no functionality to restore the history or to look into the history. If this extension is something people need I will update it with this functionality. Also, the layout is just plain…well, there is none 😉 I just wanted this to work.

If you like this extension and you want to use it or you have enhancement request, please let me know. I may update this extension 🙂

Small note: Since Contentporter wasn’t installed on the CTP image, I could not test it fully. I did test it on another Tridion instance and it seemed to work 🙂

You can download the extension here. (Updated link) There is a howto.txt included with install instructions.