Skip to content

Getting started with DD4T and .NET

Quirijn edited this page Dec 31, 2019 · 3 revisions

This page describes how to get started with the .NET version of the DD4T 2.0 framework. If you would prefer to use the Java version, we refer to this blog post.

This manual assumes familiarity with ASP.NET MVC. If you are not familiar with the MVC concepts and framework you should start there before attempting to implement DD4T. You should also have an installation of SDL Tridion Sites / SDL Web (version 8.1 or higher), and at least some schemas and components.

Before you can start building a .NET Web Application with Tridion and DD4T, you need to install the templates.

Creating a DD4T Web Application with MVC

  • Open Visual Studio
  • Create a new ASP.NET Web Application
    • Select Empty as a template
    • Under "Add folders and core references for:" select MVC
    • Uncheck "Host in the cloud" (Unless you want to create an Azure hosted application)
    • If you want Unit Tests, select the option
    • Click OK
  • Now your project is created, go to Tools > NuGet Package Manager > Manage NuGet Packages for Solution
    • If you forgot to (or on purpose) didn't check the MVC files, the following library will install it for you.
    • If you want an alpha or beta release select "Include prerelease".
    • Search for DD4T.MVC5 and install it
    • This will automatically install the DD4T.Core and the DD4T.Model as well
    • Choose a Dependency Injection provider my either searching and installing one of the following packages:
      • DD4T.DI.Autofac
      • DD4T.DI.Ninject
      • DD4T.DI.Unity
    • Depending on your Tridion version also search for and install one of the following packages:
      • DD4T.Providers.SDLWeb8.CIL
      • DD4T.Providers.SDLWeb8.5.CIL
      • DD4T.Providers.Tridion9.CIL
      • DD4T.Providers.Tridion9.1.CIL
        • Note: providers for older Tridion versions (2011, 2013) are still available but are no longer actively supported. There are also providers for the legacy (in-process) API for SDL Web 8.1 and 8.5.
    • Optionally install one of the loggers: DD4T.Logging.Log4net, DD4T.Logging.NLog, DD4T.Logging.Serilog
    • These are the DD4T dependencies you need.

Wire up your application

The next thing to do is to configure dependency injection for your application. This is done in the Global.asax.cs (which should be in the root folder of your web application).

This example uses Autofac, and also relies on the Autofac.Mvc5 NuGet package.

Add the following code to this class:

    public class MvcApplication : HttpApplication
    {
        private ILifetimeScope DD4T_Start()
        {
            var builder = new ContainerBuilder();
            builder.UseDD4T();

            // register MVC controllers
            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            return builder.Build();
        }

        protected void Application_Start()
        {
            var diContainer = DD4T_Start();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(diContainer));
            XmlConfigurator.Configure();
        }
    }

Change your configuration

Open the Web.config and make the following changes:

  • Add the following to the appSettings section:
<add key="discovery-service-uri" value="http://my-tridion-cd-server:port/discovery.svc" />
<add key="oauth-enabled" value="true" />
<add key="oauth-client-id" value="cd-username" />
<add key="oauth-client-secret" value="cd-clientsecret" />

Obviously you need to replace these dummy values with real ones. Consult the SDL documentation for more details.

Add one more key to the appSettings, like this:

<add key="DD4T.PublicationId" value="3"/>

This tells DD4T which publication you want to serve your pages from. The PublicationID is the middle number of the URI of the publication (e.g. tcm:-0-3-1 is 3).

Look for the system.webServer element in the Web.config, and set the runAllManagedModulesForAllRequests attribute on the modules element to true. This allows you to route URLs ending with a file extensions (like a Tridion page) to your web application.

<system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="true">
    </modules>
</system.webServer>

Add a controller

Add a PageController with the following code:

using DD4T.ContentModel.Factories;
public class PageController : Controller
{
    private IPageFactory _pageFactory;
    public PageController(IPageFactory pageFactory)
    {
        _pageFactory = pageFactory;
    }

    public ActionResult Page(string url)
    {
        var page = _pageFactory.FindPage("/" + url);
        var viewName = page.PageTemplate.MetadataFields?["view"]?.Value ?? page.PageTemplate.Title.Replace(" ", "");
        return View(viewName, page);
    }
}

Some explanation:

  • the Page method takes the url of the current request and uses the page factory to retrieve the Tridion page corresponding with this url
    • A slash is added to the beginning because MVC will pass the url without the leading slash, and Tridion expects it.
  • The view name is retrieved either from the metadata field 'view' or from the title of the page template (without spaces).
  • The page is rendered with the view

Add a view

Create a folder called Page inside the Views folder in your web application. In this folder, create a Razor view with the name you put in the 'view' metadata field of the page template. Add the following code to this view:

@model DD4T.ContentModel.IPage

<div>
    <h1>@Model.Title</h1>
    This page contains @Model.ComponentPresentations.Count component presentations.
</div>

Configure the routing

Open the file RouteConfig in the App_Start folder and add the following route right above the Default route that's already there:

routes.MapRoute(
    name: "TridionPage",
    url: "{*url}",
    defaults: new { controller = "Page", action = "Page" }
);

Note: the mask '{*url}' matches the entire url, including all slashes (except the leading slash, as mentioned above).

Run the application

You are now ready to run the application. If all went well, you should be getting a page that looks like this:

Of course, this is just a very simple starting point for your website. You need to add your own HTML, CSS, JS, add navigation, create lists of dynamic content, perhaps country and/or language switchers, etc.

The first thing you probably want to do, is to start using ViewModels. This is a great feature of DD4T: it allows you map Tridion schemas to C# classes, and consume your components as objects based on those classes. See http://blog.trivident.com/dd4t-page-and-content-viewmodels/ for more information.