@Shazwazza

Shannon Deminick's blog all about web development

Umbraco CLI running on ASP.NET Core

October 26, 2016 14:13

TL;DR I’ve got Umbraco (the Core part) running on .NET Core (not just a .NET Core CLI wrapping a non .NET Core Umbraco). See below for a quick video of it working on Ubuntu and simple instructions on how to get it running yourself.

Over the past couple of years I’ve slowly been working on getting Umbraco to run on ASP.NET Core. Unlike many other ASP.NET frameworks and products that have rewritten their apps in ASP.NET Core, I’ve gone a different path and have updated Umbraco’s existing code to compile against both .Net Framework and .Net Core. This is a necessary transition for the Umbraco codebase, we don’t plan on rewriting Umbraco, just updating it to play nicely with both .Net Framework and .Net Core.

During my talk at CodeGarden this year I spoke about the Future of Umbraco Core. An important aspect of that talk was the fact that we need to build & release Umbraco version 8 before we can consider looking in to upgrading all of Umbraco to work with ASP.NET Core. A primary reason for this is because we need to remove all of the legacy code from Umbraco (including plenty of old Webforms views) and updated plenty of other things such as old libraries that are simply not going to work with ASP.NET Core.

I have been doing all of the work on updating Umbraco to work with ASP.NET Core on a fork on GitHub. It’s been a very tedious process made even more tedious due to the constant changes of ASP.NET Core over the last 2 years. I started this whole process by modifying the VS sln file to exclude all of the projects and only including the Umbraco.Core project, then starting with the most fundamental classes to include. I’d include one class at a time using the project.json file, compile, make changes if required until it built, include the next class, rinse/repeat.  I did this up until the point where I could compile the Umbraco.Core project to include Umbraco’s ApplicationContext object and CoreBootManager. This basically meant I had everything I needed in order to bootstrap Umbraco and perform the business logic operations for Umbraco on ASP.NET Core :)

I did start looking at updating the Umbraco.Web project but this is going to be a much more involved process due to the way that MVC and WebApi have changed with regards to ASP.NET Core. It is worth noting that I do have the routing working, even things like hijacked routes, SurfaceController’s, etc… !

But before I continued down that road I wanted to see if I could get the core part of Umbraco running cross platform, so I tinkered around with making an Umbraco .NET Core CLI

… And it just works :)

On a side note, the Git branch that this live in is a fork of Umbraco’s current source code and the branch that it exists in is a branch from v8 so it is fully merge-able. This means that as we continue developing on v7 and v8 all of these fixes/changes will merge up into this branch.

Umbraco Interactive CLI

I didn’t want to reinvent the wheel with a CLI argument parser so a quick Googling on what was available on .Net Core pointed me to a great framework that Microsoft had already built. What I wanted to make was an interactive CLI so I could either execute a single command line statement to perform an operation, or I could start the CLI and be prompted to work with Umbraco data until I exited. This Microsoft framework didn’t quite support that OOTB but it wasn’t difficult to make it work the way I wanted without modifying it’s source. From there I wrote the code to boot Umbraco and started implementing some commands. Here’s the commands and sub-commands so far (each command has a help option: –h):

  • db – Used to configure the database
    • install – used to install a new Umbraco db, schema and default data
    • connect – used to connect to an existing Umbraco db
  • schema – Used for manipulating schema elements
    • doctype – Used for Document type operations
      • create, del, list
      • groups – Used for property group operations (create + list)
      • props – Used for property type operations (create + list)
    • medtype– Used for Media type operations
      • create, del , list
      • groups – Used for property group operations (create + list)
      • props – Used for property type operations (create + list)

See it in action

Cross Platform

I was very interested to see if this would work on Linux so I got Ubuntu up and running and put MySql on there and created a new db to use. Then I updated the solution to build a standalone .NET Core app, published that using

dotnet publish -c release -r ubuntu.14.04-x64 

and unzipped that on my Ubuntu installation. Then I tried it by running

./Umbraco.Test.Console

and …. It worked !! There’s something quite magical about the whole thing, it really was very easy to get this to run on a non-windows environment. Very impressive :)

Try it out!

You should be able to get this working pretty easily – hopefully on any OS – here’s the steps:

I’ve not tested any of this with OSX, so hopefully it will ‘just work’ there too

You’ll need either an MS SQL or MySql empty database setup on your OS environment, then note the connection string since you’ll need to enter it in the CLI.

Clone the repo (It’s big, it’s the actual current Umbraco source):

git clone -b dev-v9 https://github.com/Shazwazza/Umbraco-CMS.git

Go to the project folder

cd Umbraco-CMS
cd src
cd Umbraco.Test.Console

Restore packages

dotnet restore

Build the project, depending on your OS

dotnet build -r win10-x64
dotnet build -r osx.10.10-x64
dotnet build -r ubuntu.16.04-x64

Publish it, depending on your OS

dotnet publish -c release -r win10-x64
dotnet publish -c release -r osx.10.10-x64
dotnet publish -c release -r ubuntu.16.04-x64

Run it, depending on your OS

bin\release\netcoreapp1.0\win10-x64\Umbraco.Test.Console.exe
./bin/release/netcoreapp1.0/osx.10.10-x64/Umbraco.Test.Console
./bin/release/netcoreapp1.0/ubuntu.16.04-x64/Umbraco.Test.Console

NOTE: On Linux you’ll probably have to mark it to be executable first by doing this:

chmod +x ./bin/release/netcoreapp1.0/ubuntu.16.04-x64/Umbraco.Test.Console

Next steps

I’m very excited about what has been achieved so far but there’s certainly a long way to go. As I mentioned above getting v8 completed is a requirement to getting a version of Umbraco fully working with ASP.NET Core. During that development time I do plan on continuing to tinker around with getting more stuff to work. I’d like to see some progress made with the web project, the first steps will require getting the website boot process working  (in progress) and I think a good first milestone will be getting the installer all working. From there, there’s updating the controllers and authentication/authorization mechanisms for the back office and then looking into actually getting content rendered on the front-end ( this part is actually the easiest and mostly done already ). 

Isolated WebApi attribute routing

January 17, 2016 12:39

Attribute routing in ASP.Net WebApi is great and makes routing your controllers quite a bit more elegant than writing routes manually. However one problem I have with it is that it is either “on” or “off” at an application level.  There is no way for a library developer to tell ASP.Net to create routes based on attributes for specific controllers or assemblies without forcing the consumer of that library to enable Attribute Routing for the whole application. In many cases this might not matter, but if you are creating a package or library of that contains it’s own API routes, you probably don’t want to interfere with a developers’ normal application setup. There should be no reason why they need to be forced to turn on attribute routing in order for your product to work, and similarly they might not want your routes automatically enabled.

The good news is that this is possible. With a bit of code, you can route your own controllers with attribute routing and be able to turn them on or off without affecting the default application attribute routes. A full implementation of this has been created for the Umbraco RestApi project so I’ll reference that source in this post for the following code examples.

Show me the code

They key to getting this to work is: IDirectRouteProvider, IDirectRouteFactory

The first thing we need is a custom IDirectRouteFactory which is actually a custom attribute. I’ve called this CustomRouteAttribute  but you could call it whatever you want.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class CustomRouteAttribute : Attribute, IDirectRouteFactory

This custom attribute just wraps the default WebApi RouteAttribute’s IDirectRouteFactory implementation so we don’t have to re-write any code for that.

(see full implementation here)

Next we’ll create a custom IDirectRouteProvider:

/// <summary>
/// This is used to lookup our CustomRouteAttribute instead of the normal RouteAttribute so that 
/// we can use the CustomRouteAttribute instead of the RouteAttribute on our controlles so the normal
/// MapHttpAttributeRoutes method doesn't try to route our controllers - since the point of this is
/// to be able to map our controller routes with attribute routing explicitly without interfering
/// with default application routes.
/// </summary>
public class CustomRouteAttributeDirectRouteProvider : DefaultDirectRouteProvider
{
    private readonly bool _inherit;

    public CustomRouteAttributeDirectRouteProvider(bool inherit = false)
    {
        _inherit = inherit;
    }

    protected override IReadOnlyList<IDirectRouteFactory> GetActionRouteFactories(HttpActionDescriptor actionDescriptor)
    {
        return actionDescriptor.GetCustomAttributes<CustomRouteAttribute>(inherit: _inherit);
    }
}

So far this is all pretty straight forward so far but here’s where things start to get interesting. Because we only want to create routes for specific controllers, we need to use a custom IHttpControllerTypeResolver. However, since the HttpConfiguration instance only contains a single reference to the IHttpControllerTypeResolver we need to do some hacking. The route creation process for attribute routing happens during the HttpConfiguration initialization so we need to create an isolated instance of HttpConfiguration, set it up with the services we want to use, initialize it to create our custom routes and assign those custom routes back to the main application’s HttpConfiguration.

Up first, we create a custom IHttpControllerTypeResolver to only resolve the controller we’re looking for:

public class SpecificControllerTypeResolver : IHttpControllerTypeResolver
{
    private readonly IEnumerable<Type> _controllerTypes;

    public SpecificControllerTypeResolver(IEnumerable<Type> controllerTypes)
    {
        if (controllerTypes == null) throw new ArgumentNullException("controllerTypes");
        _controllerTypes = controllerTypes;
    }

    public ICollection<Type> GetControllerTypes(IAssembliesResolver assembliesResolver)
    {
        return _controllerTypes.ToList();
    }
}

Before we look at initializing a separate instance of HttpConfiguration, lets look at the code you’d use to enable all of this in your startup code:

//config = the main application HttpConfiguration instance
config.MapControllerAttributeRoutes(
    routeNamePrefix: "MyRoutes-",
    //Map these explicit controllers in the order they appear
    controllerTypes: new[]
    {                    
        typeof (MyProductController),
        typeof (MyStoreController)
    });

The above code will enable custom attribute routing for the 2 specific controllers. These controllers will be routed with attribute routing but instead of using the standard [Route] attribute, you’d use our custom [CustomRoute] attribute. The MapControllerAttributeRoutes extension method is where all of the magic happens, here’s what it does:

  • Iterates over each controller type
  • Creates an instance of HttpConfiguration
  • Sets it’s IHttpControllerTypeResolver instance to SpecificControllerTypeResolver for the current controller iteration (The reason an instance of HttpConfiguration is created for each controller is to ensure that the routes are created in the order of which they are specified in the above code snippet)
  • Initialize the HttpConfiguration instance to create the custom attribute routes
  • Copy these routes back to the main application’s HttpConfguration route table

You can see the full implementation of this extension method here which includes code comments and more details on what it’s doing.  The actual implementation of this method also allows for some additional parameters and callbacks so that each of these routes could be customized if required when they are created.

 

There is obviously a bit of code involved to achieve this and there could very well be a simpler way, however this implementation does work rather well and offers quite a lot of flexibility. I’d certainly be interested to hear if other developers have figured this out and what their solutions were.

logo-powershell-umbracoSince I like using Powershell for my build scripts for various projects I thought it would be handy to create a Powershell script to create an Umbraco package in it’s native package format. I’ve added this script template to my GitHub Umbraco Scripts repository which you can see here: http://bit.ly/1kM9g9g

I’ve tried to add a bit of documentation to this script and in theory you should only need to set up the paths properly. You’ll also need to ensure that you initially create the package in the back office of Umbraco in order to generate the createdPackages.config as mentioned in the script notes.

I use this script in Articulate’s build script so at least I can also provide an example of using it which you can see here: https://github.com/Shazwazza/Articulate/blob/master/build/build.ps1

Using LinqPad with Umbraco

March 27, 2015 08:07

During some spare time last weekend I decided to look into booting up Umbraco outside of a web context. I know this has been done before in various different ways but for this I wanted to just try to use the Umbraco core. There are 2 things that are required to boot Umbraco:

  • IBootManager
  • UmbracoApplicationBase

In Umbraco source, there are a couple of these instances: CoreBootManager, WebBootManager & UmbracoApplication.  Essentially the WebBootManager starts up anything that has web requirements and inherits from CoreBootManager which starts up the rest of Umbraco and all of that is bootstrapped with UmbracoApplication, which is actually the instance of the global.asax in an Umbraco website. To boot just the core of Umbraco it would seem clear that I just want CoreBootManager and then bootstrap it myself with a custom UmbracoApplicationBase. All of this is actually very simple and the bare bones would look something like:

public class ConsoleApplication : UmbracoApplicationBase
{  
    public void StartApplication()
    {
        GetBootManager()
            .Initialize()
            .Startup(appContext => OnApplicationStarting(this, new EventArgs()))
            .Complete(appContext => OnApplicationStarted(this, new EventArgs()));
    }

    protected override IBootManager GetBootManager()
    {
        return new ConsoleBootManager();
    }
}

Then to use it could look something like:

public void Main()
{
    using (var app = new ConsoleApplication())
    {
        app.StartApplication();
        using (var appCtx = ApplicationContext.Current)
        {
            //do stuff
        }
    }
}

Let’s just say there are still some issues with this that we’ll iron out in the future. Almost all of the issues have to do with loading in plugins and plugins not being capable of running without web context, and various other things. The good news is that I got it working with only a tiny bit of reflection which basically just removes all IApplicationEventHandlers from starting up apart from the ones found in the Umbraco Core assembly.

LinqPad & Umbraco is real!

Knowing that I could boot Umbraco and interact with it’s data via the ApplicationContext, I figured the next best thing would be to see if I could get that working with LinqPad… and I did !  Awesome!! :)

So here you go, a shiny new v1.0 LinqPad driver for Umbraco and all of the source code:

Be sure to read the docs, there’s probably a lot of stuff it can’t do, but there’s certainly a lot of stuff it could do!!! The next version will hopefully have some proper IQueryable support which I’ve been working on as well.

See it in action:

Umbraco LinqPad driver

Articulate 1.0.4 released

October 10, 2014 06:18

I’ve finally got around to releasing Articulate 1.0.4 today. Want to say a big thanks to all those who submitted pull requests, you guys rock! There’s a few nice fixes in this release but most importantly it fixes the issues with multi-tenancy when domains are assigned in Umbraco.

Here’s the release notes on GitHub with links to each issue fixed:

https://github.com/Shandem/Articulate/releases/tag/1.0.4

You can download the Umbraco package from there or from Our here:

http://our.umbraco.org/projects/starter-kits/articulate

Unfortunately I haven’t got around to getting this on Nuget yet – That’s because it has it’s own challenges since I’d like to perform a full Umbraco data install via Nuget… coming soon I hope :)

Enjoy!

ASP.Net Identity for Umbraco

August 7, 2014 01:31

I’ve released version 1.0 of UmbracoIdentity which allows for ASP.Net Identity to be used with Umbraco for front-end members. I’ve tried to write enough documentation for you to get started, all of the code and docs are here: https://github.com/Shandem/UmbracoIdentity

It’s worth noting that this is not something that ‘everyone’ should just jump in with and start using. If you are not familiar with OWIN or ASP.Net Identity than none of this will really make any sense, I’ve added a bit of a disclaimer to the docs about this here: https://github.com/Shandem/UmbracoIdentity#owin-setup

There are some known issues and limitations that you should be aware of, and this will also not work currently with back office users (that will come eventually too though).

This package can be highly customized, it comes with many .cshtml views and c# classes that you can customize as you see fit – very similar to the Visual Studio 2013 Web Application templates that support ASP.Net Identity.

What about Asp.Net Membership with Umbraco?

The way that I’ve created this is to be 100% compatible with the current Membership structure in Umbraco. This means that this is not using EntityFramework to access data, it uses the Umbraco member services and providers using custom ASP.Net Identity user stores. This also means that the password formats are based on the current password formats of the membership provider. When the Nuget package is installed it will actually swap out the membership provider for a custom type: UmbracoIdentity.IdentityEnabledMembersMembershipProvider. This is required so that the password security can still be handled by the membership provider logic.

There is a note about passwords here, ASP.Net Identity normally will format and salt passwords different (slightly better) than how the membership providers current work, but if you need that functionality you’d have to implement your own IPasswordHasher.

Installation

It is absolutely essential you read the documentation before installing. Once you’ve done that, you can use Nuget:

PM> Install-Package UmbracoIdentity

I’ve recently decided to build a new open source blog engine powered by Umbraco called Articulate. There’s a few reasons why i wanted to do this:

  • Since my full time job is an Umbraco core developer, I spend most of my time building Umbraco and get very little time for using Umbraco. I wanted to change this dilemma and really use Umbraco and utilize many of the features we’ve been creating and try to push some of it’s boundaries. For me this is a perfect way to find inspiration for new Umbraco features and enhancements.
  • I’ve wanted to move my blog away from BlogEngine.Net to Umbraco for quite some time (dogfooding) but I really needed to have every feature that I use in BlogEngine.Net available
  • I wanted to make the blog experience as simple as possible in Umbraco
  • I wanted to be able to write blog posts directly from my mobile phone easily using the web

I’ve got some documentation written and I’ll keep updating this over time but hopefully there’s enough there to get you started. Since Articulate is open source and hosted on GitHub, any community contributions are hugely welcomed :) Whether that’s core code additions, fixes, documentation, etc… any contribution is a big help.

Articulate templates are based on themes and I think it would be super awesome if people started creating their own themes and releasing them as their own packages or including them in the Articulate core for release. Creating themes is really easy and in fact a few of the themes included with Articulate are open source MIT licensed themes migrated over from the Ghost blogging platform (which is also very easy to do).

The first version of Articulate is out and can be downloaded either from the Umbraco package repository or from GitHub. There are a few minor bugs in this release that have been reported and fixed and I’ll have a newer version out this week.

A while ago I wrote a post on how to do custom MVC routing in Umbraco, though the end result wasn’t quite ideal. There were a few tricks required and It wasn’t perfect since there were problems with rendering macros on the resulting view, etc… This was due to not having a PublishedContentRequest object assigned to the context. So then we went ahead and created a new attribute to assign to your MVC action to resolve this: [EnsurePublishedContentRequestAttribute]

Like the last post, you can read a lot about all of this in this Our thread. With the [EnsurePublishedContentRequestAttribute] attribute you could now assign any IPublishedContent instance to a PublishedContentRequest and be sure that it was assigned to the UmbracoContext. But this still isn’t the most ideal way to go about specifying MVC routes to work within the Umbraco pipeline… so I’ve created the following implementation which works quite well.

Background

A little bit of background in to custom MVC routes and Umbraco… The reason why it is not terribly straight forward to create a custom route and have it assigned to an Umbraco node is because the node doesn’t exist at your custom route’s location.

For example, if we have this route:

//Create a custom route
RouteTable.Routes.MapRoute(
    "test",
    "Products/{action}/{sku}",
    new
        {
            controller = "MyProduct", 
            action = "Product", 
            sku = UrlParameter.Optional
        });

Umbraco by default would have no idea what node (IPublishedContent) would be assigned to this. The way Umbraco relates a URL to an IPublishedContent instance is by a list of IContentFinder’s. A very easy way to relate a custom URL to an IPublishedContent instance is to create your own IContentFinder. Combine that with route hijacking and in many cases this would probably be enough for your custom routing needs. However, it does not solve how you would wire up custom route parameters to your controller like how MVC normally works. Like in the above routing example, you’d want to have the ‘sku’ parameter value wired up to your Action parameter.

The above route can work and be integrated into Umbraco by following some aspects of my previous blog post and use the [EnsurePublishedContentRequestAttribute], but we can make it easier…

Creating routes

The simplest way to demonstrate this new way to create MVC routes in Umbraco is to just show you an example, so here it is:

//custom route
routes.MapUmbracoRoute(
    "test",
    "Products/{action}/{sku}",
    new
    {
        controller = "MyProduct",
        sku = UrlParameter.Optional
    },
    new ProductsRouteHandler(_productsNodeId));

This is using a new extension method: MapUmbracoRoute which takes in the normal routing parameters (you can also include constraints, namespaces, etc….) but also takes in an instance of UmbracoVirtualNodeRouteHandler.

The instance of UmbracoVirtualNodeRouteHandler is responsible for associating an IPublishedContent with this route. It has one abstract method which must be implemented:

IPublishedContent FindContent(RequestContext requestContext, UmbracoContext umbracoContext)

It has another virtual method that can be overridden which will allow you to manipulate the PublishedContentRequest however you’d like:

PreparePublishedContentRequest(PublishedContentRequest publishedContentRequest)

So how do you find content to associate with the route? Well that’s up to you, one way (as seen above) would be to specify a node Id. In the example my ProductsRouteHandler is inheriting from UmbracoVirtualNodeByIdRouteHandler which has an abstract method:

IPublishedContent FindContent(RequestContext requestContext, UmbracoContext umbracoContext, 
    IPublishedContent baseContent);

So based on all this information provided in these methods, you can associate whatever IPublishedContent item you want to the request.

Virtual content

This implementation expects any instance of IPublishedContent, so this means you can create your own virtual nodes with any custom properties you want. Generally speaking you’ll probably have a real Umbraco IPublishedContent instance as a reference point, so you could create your own virtual IPublishedContent item based on PublishedContentWrapped, pass in this real node and then just override whatever properties you want, like the page Name, etc..

Whatever instance of IPublishedContent returned here will be converted to a RenderModel for use in your controllers.

Controllers

Controllers are straight forward and work like any other routed controller except that the Action will have an instance of RenderModel mapped to it’s parameter. Example:

public class MyProductController : RenderMvcController
{
    public ActionResult Product(RenderModel model, string sku)
    {
        //in my case, the IPublishedContent attached to this
        // model will be my products node in Umbraco which i 
        // can now use to traverse to display the product list
        // or lookup the product by sku
            
        if (string.IsNullOrEmpty(sku))
        {
            //render the products list if no sku
            return RenderProductsList(model);
        }
        else
        {
            return RenderProduct(model, sku);
        }
    }
}

I have this all working well in a side project of mine at the moment. This functionality will be exposed in an upcoming Umbraco version near you  :)

It’s also worth noting that all of this was accomplished outside of the Umbraco core with the publicly available APIs that currently exist. I will admit though there were a few hacks involved which of course won’t be hacks when moved into the core ;)

Custom MVC routing in Umbraco

July 4, 2013 23:00

This post will describe how you can declare your own custom MVC routes in order to execute your own custom controllers in Umbraco but still be able to render Umbraco views with the same model that Umbraco uses natively.

NOTE: This post is not about trying to execute a particular Umbraco page under a custom URL, that functionality can be accomplished by creating a custom IContentFinder (in v6.1), or by applying the umbracoUrlAlias

There’s a long (but very useful) thread on Our describing various needs for custom MVC routing inside of Umbraco, definitely worth a read. Here I’ll try to describe a pretty easy way to accomplish this. I’m using Umbraco v6.0.7 (but I’m pretty sure this will work in v4.10+ as well).

Create the route

This example will use an IApplicationEventHandler (in 6.1 you should use the base class ApplicationEventHandler instead). Here I’m defining a custom route for handling products on my website. The example URLs that I want handled will be:

  • /Products/Product/ProductA
  • /Products/Category/CategoryA

 

public class MyStartupHandler : IApplicationEventHandler
{
    public void OnApplicationStarted(
        UmbracoApplicationBase umbracoApplication, 
        ApplicationContext applicationContext)
    {
        //Create a custom route
        RouteTable.Routes.MapRoute(
            "test",
            "Products/{action}/{id}",
            new
                {
                    controller = "MyProduct", 
                    action = "Product", 
                    id = UrlParameter.Optional
                });           
    }
    public void OnApplicationInitialized(
        UmbracoApplicationBase umbracoApplication, 
        ApplicationContext applicationContext)
    {
    }
    public void OnApplicationStarting(
        UmbracoApplicationBase umbracoApplication, 
        ApplicationContext applicationContext)
    {
    }
}

Create the controller

With the above route in place, I need to create a controller called “MyProductController”. The base class it will inherit from will be “Umbraco.Mvc.PluginController”. This abstract class exposes many of the underlying Umbraco objects that I might need to work with such as an UmbracoHelper, UmbracoContext, ApplicationContext, etc… Also note that the PluginController doesn’t get auto-routed like a SurfaceController which is good because we only want to route our controller once. In 6.1 you can inherit from a different controller called Umbraco.Mvc.UmbracoController, which is what the PluginController will be inheriting from in the next version.

Constructor

First thing is to define the constructors since the PluginController doesn’t have an empty constructor but we want ours to (unless you have IoC setup).

public class MyProductController : PluginController
{
    public MyProductController()
        : this(UmbracoContext.Current)
    {            
    }

    public MyProductController(UmbracoContext umbracoContext) 
        : base(umbracoContext)
    {
    }
}

Actions

Next we need to create the controller Actions. These actions will need to lookup either a Product or a Category based on the ‘id’ string they get passed. For example, given the following URL: /Products/Category/CategoryA the id would be CategoryA and it would execute on the Category action.

In my Umbraco installation, I have 2 document types with aliases: “Product” and “ProductCategory”

image

To perform the lookup in the controller Actions we’ll use the UmbracoHelper.TypedSearch overload which uses Examine.

public ActionResult Category(string id)
{
    var criteria = ExamineManager.Instance.DefaultSearchProvider
        .CreateSearchCriteria("content");
    var filter = criteria.NodeTypeAlias("ProductCategory").And().NodeName(id);
    var result = Umbraco.TypedSearch(filter.Compile()).ToArray();
    if (!result.Any())
    {
        throw new HttpException(404, "No category");
    }
    return View("ProductCategory", CreateRenderModel(result.First()));
}

public ActionResult Product(string id)
{
    var criteria = ExamineManager.Instance.DefaultSearchProvider
        .CreateSearchCriteria("content");
    var filter = criteria.NodeTypeAlias("Product").And().NodeName(id);
    var result = Umbraco.TypedSearch(filter.Compile()).ToArray();
    if (!result.Any())
    {
        throw new HttpException(404, "No product");
    }
    return View("Product", CreateRenderModel(result.First()));
}

The Category action lookup uses Examine to lookup any document with:

  • A document type alias of “ProductCategory”
  • A name equal to the id parameter passed in

The Product action lookup uses Examine to lookup any document with:

  • A document type alias of “Product”
  • A name equal to the id parameter passed in

The result from TypedSearch is IEnumerable<IPublishedContent> and since we know we only want one result we pass in the first item of the collection in “result.First()”

If you didn’t want to use Examine to do the lookup, you could use a Linq query based on the result of Umbraco.TypedContentAtRoot(), but I wouldn’t recommend that since it will be much slower.

In v6.1 the UmbracoHelper exposes a couple of other methods that you could use to perform your lookup if you didn’t want to use Examine and wanted to use XPath instead:

  • TypedContentSingleAtXPath(string xpath, params XPathVariable[] vars)
  • TypedContentAtXPath(string xpath, params XPathVariable[] vars)
  • TypedContentAtXPath(XPathExpression xpath, params XPathVariable[] vars)

CreateRenderModel method

You will have noticed that I’m using a method called CreateRenderModel to create the model that is passed to the View. This method accepts an IPublishedContent object as an argument and creates a RenderModel object which is what a normal Umbraco view expects. This method isn’t complex but it does have a couple things worth noting:

private RenderModel CreateRenderModel(IPublishedContent content)
{
    var model = new RenderModel(content, CultureInfo.CurrentUICulture);

    //add an umbraco data token so the umbraco view engine executes
    RouteData.DataTokens["umbraco"] = model;

    return model;
}

The first thing is that you need to construct the RenderModel with an explicit culture otherwise you’ll get an exception. The next line adds the created RenderModel to the RouteData.DataTokens… this is because we want to render an Umbraco view which will be stored in either of the following places (based on Umbraco standard practices):

  • ~/Views/Product.cshtml
  • ~/Views/ProductCategory.cshtml

These locations are not MVC standard practices. Normally MVC will look in a controller specific folder for views. For this custom controller the locations would be:

  • ~/Views/MyProduct/Product.cshtml
  • ~/Views/MyProduct/ProductCategory.cshtml

But we want to use the views that Umbraco has created for us so we need to ensure that the built in Umbraco ViewEngine gets executed. For performance reasons the Umbraco RenderViewEngine will not execute for a view unless a RenderModel instance exists in the RouteData.DataTokens with a key of “umbraco”, so we just add it there before we return the view.

Views

The views are your regular Umbraco views but there’s a few things that might not work:

  • Macros. Sorry, since we’ve bypassed the Umbraco routing pipeline which macros rely upon, any call to Umbraco.RenderMacro will fail. But you should be able to achieve what you want with Partial Views or Child Actions.
  • Umbraco.Field. Actually this will work but you’ll need to upgrade to 6.0.7 or 6.1.2 based on this fixed issue: http://issues.umbraco.org/issue/U4-2324

One cool thing is that you can use the regular MVC UrlHelper to resolve the URLs of your actions, since this custom controller is actually just a regular old MVC controller after all.

These view example are nothing extraordinary, just demonstrating that they are the same as Umbraco templates with the same model (but using our custom URLs)

ProductCategory

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{
    Layout = null;
}
<html>
    <body>
        <h1>Product category</h1>
        <hr />
        <h2>@Model.Content.Name</h2>
        <ul>
            @foreach (var product in Model.Content.Children
                .Where(x => x.DocumentTypeAlias == "Product"))
            {
                <li><a href="@Url.Action("Product", "MyProduct", new { id = product.Name })">
                        @product.Name
                    </a>
                </li>
            }
        </ul>
    </body>
</html>

Which looks like this:

image

Product

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{
    Layout = null;
}
<html>
    <body>

        <h1>Product</h1>
        <hr />
        <h2>@Model.Content.Name</h2>
        <div>
            @(Model.Content.GetPropertyValue("Description"))
        </div>
    </body>
</html>

Which looks like this:

image

Whats next?

With the setup above you should be able to achieve most of what you would want with custom routing, controllers, URLs and lookups. However, as I mentioned before things like executing Macros and potentially other internal Umbraco bits that rely on objects like the PublishedContentRequest will not work.

Of course if there is a will, there is a way and I have some cool ideas that could make all of those things work seamlessly too with custom MVC routes. Stay tuned!

When you upload media in Umbraco it stores the absolute path to the media item in the database. By default the path will look something like:

/media/12335/MyImage.jpg

However, if you are running Umbraco in a virtual directory the path will also include the virtual directly prefix. For example:

/MyVirtualDirectory/media/12335/MyImage.jpg

So you can imagine that some issues might arise if you already have data in your Umbraco install and then wanted to change virtual directory paths, or even change the media location path (umbracoMediaPath) in the web.config.

Luckily it’s easily solved with a quick SQL script. These scripts will update the path stored in Umbraco created by any property type that is of a data type with an ‘upload control’ property editor.

When moving to a virtual directory

Here’s a quick script to run against your current install if you are moving from a normal installation to using a virtual directory. Note: You will need to replace all instances of ‘MyVirtualDirectory’ to be your vdir path!

update cmsPropertyData 
set dataNvarchar = '/MyVirtualDirectory' + dataNvarchar
where id in
(select cmsPropertyData.id from cmsPropertyData
inner join cmsPropertyType on cmsPropertyData.propertytypeid = cmsPropertyType.id
inner join cmsDataType on cmsPropertyType.dataTypeId = cmsDataType.nodeId
where cmsDataType.controlId = '5032a6e6-69e3-491d-bb28-cd31cd11086c'
and cmsPropertyData.dataNvarchar is not null
and SUBSTRING(cmsPropertyData.dataNvarchar, 0, LEN('/MyVirtualDirectory') + 1) <> '/MyVirtualDirectory')

When moving from a virtual directory

Here’s the script to run if you are currently running in a virtual directory and want to move to a non-virtual directory. Note: You will need to replace all instances of ‘MyVirtualDirectory’ to be your vdir path!

update cmsPropertyData 
set dataNvarchar = SUBSTRING(dataNvarchar, LEN('/MyVirtualDirectory') + 1, LEN(dataNvarchar) - LEN('/MyVirtualDirectory'))
where id in
(select cmsPropertyData.id from cmsPropertyData
inner join cmsPropertyType on cmsPropertyData.propertytypeid = cmsPropertyType.id
inner join cmsDataType on cmsPropertyType.dataTypeId = cmsDataType.nodeId
where cmsDataType.controlId = '5032a6e6-69e3-491d-bb28-cd31cd11086c'
and cmsPropertyData.dataNvarchar is not null
and SUBSTRING(cmsPropertyData.dataNvarchar, 0, LEN('/MyVirtualDirectory') + 1) = '/MyVirtualDirectory' )

Moving to a different virtual directory?

If you want to move to a different virtual directory, you can combine the above 2 scripts… first move from a virtual directory back to normal, then move to the new virtual directory.

The above procedures would work as well if you were to change the umbracoMediaPath app setting in the web.config … though most people wont change that or even know about it ;)