<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="http://jamessouth.me/blog/rss/xslt"?>
<rss xmlns:a10="http://www.w3.org/2005/Atom" version="2.0">
  <channel>
    <title>James Jackson-South</title>
    <link>http://jamessouth.me/blog/</link>
    <description>Microsoft MVP, Creator of ImageSharp, ImageProcessor and ResponsiveBP, Web developer, Lifter of heavy weights, and all round nice guy.</description>
    <generator>Articulate, blogging built on Umbraco</generator>
    <item>
      <guid isPermaLink="false">1140</guid>
      <link>http://jamessouth.me/archive/context-based-property-mapping-with-umbmapper/</link>
      <category>System.String[]</category>
      <title>Context based property mapping with UmbMapper</title>
      <description>&lt;h2&gt;Mo Mapping, Mo Problems&lt;/h2&gt;
&lt;p&gt;A few weeks ago I wrote an article about my new Umbraco mapping engine &lt;a href="http://jamessouth.me/archive/strong-typed-umbraco-mapping-with-umbmapper/"&gt;UmbMapper&lt;/a&gt;. If you haven't read that post please do, and better yet, please &lt;a href="https://www.nuget.org/packages/umbmapper/"&gt;download&lt;/a&gt; it and give it a try. &lt;/p&gt;
&lt;p&gt;There's been a longstanding puzzle I've been trying to solve for a while now with mapping engines. One that I couldn't crack with Ditto and until today I didn't think I could solve it with UmbMapper.&lt;/p&gt;
&lt;p&gt;I was wrong :)&lt;/p&gt;
&lt;h3&gt;The Problem&lt;/h3&gt;
&lt;p&gt;Consider the following POCO class.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class Page {

    public string Name { get; set; }

    public string Slug =&amp;gt; this.Name.ToUrlSegment();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Mapping this kind of class is impossible with conventional reflection-based run-time mappers as there is no way to guarantee that the &lt;code&gt;Name&lt;/code&gt; property has a value. You'll get a &lt;code&gt;NullReferenceException&lt;/code&gt; and a whole heap of frustration.&lt;/p&gt;
&lt;p&gt;You can workaround this with Umbraco but it's not pretty. You could either &lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Turn &lt;code&gt;Slug&lt;/code&gt; into a method which works but makes it impossible to serialize.&lt;/li&gt;
&lt;li&gt;Create an event handler to calculate and store the property when saving the doctype. This is oh-so-ugly and means spreading logic all over the place.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;The Solution&lt;/h3&gt;
&lt;p&gt;With UmbMapper you can map these properties in the following manner. &lt;/p&gt;
&lt;p&gt;First let's define our class.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class Page {

    public string Name { get; set; }

    public string Slug { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And our mapper.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class PageMap : MapperConfig&amp;lt;Page&amp;gt;
{
    public PageMap()
    {
        this.AddMap(p =&amp;gt; p.Name);
        this.AddMap(p =&amp;gt; p.Slug).MapFromInstance(i =&amp;gt; i.Name.ToUrlSlug());
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;MapFromInstance&lt;/code&gt; method is our friend here. This has the following signature.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;/// &amp;lt;summary&amp;gt;
/// Sets the property mapping predicate. Used for mapping from known values in the current instance.
/// &amp;lt;/summary&amp;gt;
/// &amp;lt;param name=&amp;quot;predicate&amp;quot;&amp;gt;The mapping predicate&amp;lt;/param&amp;gt;
/// &amp;lt;returns&amp;gt;The &amp;lt;see cref=&amp;quot;PropertyMap{T}&amp;quot;/&amp;gt;&amp;lt;/returns&amp;gt;
public PropertyMap&amp;lt;T&amp;gt; MapFromInstance(Func&amp;lt;T, object&amp;gt; predicate)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With this method we can map any combination of lazy/non-lazy properties at run-time and be guaranteed the correct result and we keep our mapping logic where it belongs.&lt;/p&gt;
&lt;p&gt;Fantastic!&lt;/p&gt;
&lt;h2&gt;Get it While it's Hot!&lt;/h2&gt;
&lt;p&gt;Give UmbMapper a whirl, it's simple to use but immensely powerful giving you the means to create flexible, scalable Umbraco websites with very little effort.&lt;/p&gt;
</description>
      <pubDate>Mon, 21 Aug 2017 10:15:26 Z</pubDate>
      <a10:updated>2017-08-21T10:15:26Z</a10:updated>
    </item>
    <item>
      <guid isPermaLink="false">1139</guid>
      <link>http://jamessouth.me/archive/strong-typed-umbraco-mapping-with-umbmapper/</link>
      <category>System.String[]</category>
      <title>Strong Typed Umbraco Mapping with UmbMapper</title>
      <description>&lt;h2&gt;Greetings and Salutations!&lt;/h2&gt;
&lt;p&gt;It's not often I write code I'm immediately happy with and proud of but this happened to me just recently so I thought I'd share it with the community. &lt;/p&gt;
&lt;p&gt;As I'm sure you know, dear reader, I'm a big fan of a pretty sweet CMS made by some fantastic friends of mine in Denmark called &lt;a href="https://umbraco.com/"&gt;Umbraco&lt;/a&gt;. If you haven't played around with it, please do, it stands out, in my opinion, as easily the most usable, flexible, and fun to work with CMS in the NET ecosystem by a country mile.&lt;/p&gt;
&lt;p&gt;I'm always looking for inventive ways to work with it and to make it even easier for others to do so as well so when I had a flash of inspiration lying, flu-ridden on my couch I had to pop a couple of pills, crank open the laptop, and furiously tap away to produce what I'm sharing.&lt;/p&gt;
&lt;h2&gt;A Little History&lt;/h2&gt;
&lt;p&gt;I've been writing mapping code for Umbraco for a few years now with two of the big guns in the Umbraco package scene, Lee and Matt. You might have heard of the package we produced together called &lt;a href="https://github.com/leekelleher/umbraco-ditto"&gt;Ditto&lt;/a&gt; &lt;/p&gt;
&lt;p&gt;I'm proud of what we achieved with Ditto. I think we've managed to push attribute based mapping about as far as it can go, crafting a very performant, very flexible system that has served me well (and I think many others) over the years. &lt;/p&gt;
&lt;p&gt;I even wrote an article about it a couple of years ago in the fantastic &lt;a href="http://skrift.io/articles/archive/ditto-the-friendly-poco-mapper-for-umbraco/"&gt;Skrift&lt;/a&gt; magazine.&lt;/p&gt;
&lt;p&gt;As my skill-set has grown though and my tastes have changed I have found myself curious about how far and fast I can push mapping. &lt;/p&gt;
&lt;h2&gt;Introducing UmbMapper&lt;/h2&gt;
&lt;p&gt;Not the most exciting name ever but definitely some of the most exciting code I've come up with. &lt;/p&gt;
&lt;p&gt;UmbMapper is a new, convention-based mapper that I've written for mapping &lt;code&gt;IPublishedContent&lt;/code&gt; to strong-typed POCO classes. Strong-typed? Let's quote my own words from a couple of years ago.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Opens dictionary… Strong typing involves the strict enforcement of type rules with no exceptions, allowing the detection of incorrect type usage either at run time or at compile time. Having strong typing catches more type errors than weak typing, resulting in fewer hard errors. It can cut down on many hours of painful debugging.&lt;/p&gt;
&lt;p&gt;Umbraco offers what I would call &amp;quot;Stringly Typing&amp;quot;. You can get your property type out of the API but you have to pass a string in order to do so. That’s pretty damn cool but it doesn’t quite feel natural and easy enough for me to use as a developer. I’m lazy and the last thing I want to do it type lots and learn how to spell things.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Clued up? Great, let's carry on.&lt;/p&gt;
&lt;h2&gt;The Elevator Pitch&lt;/h2&gt;
&lt;p&gt;Why use it? Well, let me explain.&lt;/p&gt;
&lt;p&gt;UmbMapper works in a completely different way to Ditto and ModelsBuilder. It uses the concept of convention-based mapping configuration classes to do the work for you which allows you to perform fine-grained mapping with very little overhead. &lt;/p&gt;
&lt;p&gt;I want my POCO's to be super lean and you should too. Imagine getting to write code like this in your Umbraco project to represent your document types.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class PublishedItem
{
    public int Id { get; set; }

    public string Name { get; set; }

    public DateTime CreateDate { get; set; }

    public DateTime UpdateDate { get; set; }

    public MyEnum MyEnumType{ get; set; }

    public Image Image { get; set; }

    public RelatedLink Link { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Ain't that pretty? No attributes, no inheriting of particular interfaces, nothing but pure, good old fashioned POCO goodness! This makes it great for larger projects (As well as small ones) where you can apply design patterns like DDD to maintain flexibility and help your application scale.&lt;/p&gt;
&lt;p&gt;So how do we map it? Here's where the magic happens.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class PublishedItemMap : MapperConfig&amp;lt;PublishedItem&amp;gt;
{
    public PublishedItemMap()
    {
        this.AddMap(p =&amp;gt; p.Id);
        this.AddMap(p =&amp;gt; p.Name);
        this.AddMap(p =&amp;gt; p.CreateDate);
        this.AddMap(p =&amp;gt; p.UpdateDate).SetAlias(p =&amp;gt; p.UpdateDate, p =&amp;gt; p.CreateDate);
        this.AddMap(p =&amp;gt; p.MyEnumType).SetMapper&amp;lt;EnumPropertyMapper&amp;gt;();
        this.AddMap(p =&amp;gt; p.Image).SetMapper&amp;lt;UmbracoPickerPropertyMapper&amp;gt;();
        this.AddMap(p =&amp;gt; p.Link);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Look at that API!! How crisp, how clean, how marvellous! But wait... It gets better. &lt;/p&gt;
&lt;p&gt;For simpler classes, there are more terse mapping methods available&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class PublishedItemMap : MapperConfig&amp;lt;PublishedItem&amp;gt;
{
    public PublishedItemMap()
    {
        this.AddMappings(
            x =&amp;gt; x.Id,
            x =&amp;gt; x.Name,
            x =&amp;gt; x.DocumentTypeAlias,
            x =&amp;gt; x.Level).ForEachIndexed((x, i) =&amp;gt; x.AsLazy());

        this.AddMappings(
            x =&amp;gt; x.SortOrder,
            x =&amp;gt; x.CreateDate,
            x =&amp;gt; x.UpdateDate).ForEach(x =&amp;gt; x.AsLazy());
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Or for really, really simple classes&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class LazyPublishedItemMap : MapperConfig&amp;lt;LazyPublishedItem&amp;gt;
{
    public LazyPublishedItemMap()
    {
        this.MapAll().ForEachIndexed((x, i) =&amp;gt; x.AsLazy());

        this.MapAll().ForEach(x =&amp;gt; x.AsLazy());
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Registering a mapper is as easy as follows&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;MapperConfigRegistry.AddMapper(new LazyPublishedItemMap());
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now that's what I call a nice API; super simple to use but powerful with a multitude of other mapping instructions available.&lt;/p&gt;
&lt;h3&gt;Configuration&lt;/h3&gt;
&lt;p&gt;The &lt;code&gt;AddMap()&lt;/code&gt; method and subsequent methods called in the mapper constructor each return a &lt;code&gt;PropertyMap&amp;lt;T&amp;gt;&lt;/code&gt; where &lt;code&gt;T&lt;/code&gt; is the class you want to map to. This allows us to use a simple fluent API to configure each property map.&lt;/p&gt;
&lt;p&gt;The various mapping configuration options are as follows:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;AddMap()&lt;/code&gt; Instructs the mapper to map the property.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;AddMappings()&lt;/code&gt; Instructs the mapper to map the collection of properties.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;MapAll()&lt;/code&gt; Instructs the mapper to map all the properties in the class.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;SetAlias()&lt;/code&gt; Instructs the mapper what aliases to look for in the document type. The order given is the checking order. Case-insensitive.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;SetMapper()&lt;/code&gt; Instructs the mapper what specific &lt;code&gt;IPropertyMapper&lt;/code&gt; implementation to use for mapping the property. All properties are initially automatically mapped using the &lt;code&gt;UmbracoPickerPropertyMapper&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;SetCulture()&lt;/code&gt; Instructs the mapper what culture to use when mapping values. Defaults to the current culture contained within the &lt;code&gt;UmbracoContext&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;AsRecursive()&lt;/code&gt; Instructs the mapper to recursively traverse up the document tree looking for a value to map.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;AsLazy()&lt;/code&gt; Instructs the mapper to map the property lazily using dynamic proxy generation. You need to mark your property with the &lt;code&gt;virtual&lt;/code&gt; keyword for that to work.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Available &lt;code&gt;IPropertyMapper&lt;/code&gt;implementations all inherit from the &lt;code&gt;PropertyMapperBase&lt;/code&gt; class and are as follows:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;UmbracoPickerPropertyMapper&lt;/code&gt; The default mapper. Maps directly from Umbraco's Published Content Cache via &lt;code&gt;GetPropertyValue&lt;/code&gt;. Runs automatically.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;EnumPropertyMapper&lt;/code&gt; Maps to enum values. Can handle both integer and string values.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;UmbracoPickerPropertyMapper&lt;/code&gt; Maps from all the Umbraco built-in pickers.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;DocTypeFactoryPropertyMapper&lt;/code&gt; Allows mapping from mixed &lt;code&gt;IPublishedContent&lt;/code&gt; sources like Nested Content. Inherits &lt;code&gt;FactoryPropertyMapperBase&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;These mappers handle most use cases since they rely initially on Umbraco's &lt;code&gt;PropertyValueConverter&lt;/code&gt; API. Additional mappers can be easily created by inheriting the &lt;code&gt;PropertyMapperBase&lt;/code&gt; class which give you all the properties you need.&lt;/p&gt;
&lt;p&gt;I've already built you mappers for Archetype and NuPickers though so you don't need to worry about those :)&lt;/p&gt;
&lt;h2&gt;In Summary&lt;/h2&gt;
&lt;p&gt;I'm hoping by now you can see how beneficial UmbMapper can be in your projects. It's fast, easy to use and should help you build flexible, scalable Umbraco websites giving you the freedom to spend less time boiler-plating and more time concentrating on the fun stuff. &lt;/p&gt;
&lt;p&gt;Please visit the &lt;a href="https://github.com/JimBobSquarePants/UmbMapper"&gt;Github&lt;/a&gt; repo and download the packages from Nuget and if you have any questions, just holler and I'll do my best to help you out. &lt;/p&gt;
&lt;p&gt;Thanks for reading!&lt;/p&gt;
&lt;h2&gt;Update&lt;/h2&gt;
&lt;p&gt;I was asked by my good friend Mads on &lt;a href="https://twitter.com/sniffdk/status/897102781575827456"&gt;Twitter&lt;/a&gt; to elaborate on how lazy mapping works so I thought I best do so.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Any sufficiently advanced technology is indistinguishable from magic. - Gandalf the Grey&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;If a mapper is configured using the &lt;code&gt;AsLazy()&lt;/code&gt; instruction and the class contains properties using the virtual keyword, the mapper will generate a dynamic proxy class at run-time to represent the type we are mapping to. This class actually inherits our target class and you'll be able to see it by attaching a debugger.&lt;/p&gt;
&lt;p&gt;The class looks something like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class LazyPublishedItemProxy : LazyPublishedItem, IProxy
{
    /// &amp;lt;summary&amp;gt;
    /// Gets or sets the &amp;lt;see cref=&amp;quot;IInterceptor&amp;quot;/&amp;gt; for intercepting 
    /// &amp;lt;see cref=&amp;quot;System.Reflection.MethodBase&amp;quot;/&amp;gt; calls.
    /// &amp;lt;/summary&amp;gt;
    IInterceptor Interceptor { get; set; }

    // Property interceptors are written below using Reflection.Emit
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Any properties configured with lazy mapping are not actually mapped until you specifically call the getter on the property. (Via means of &lt;code&gt;MethodInfo&lt;/code&gt; interception using the terribly complicated Reflection.Emit API).&lt;/p&gt;
&lt;p&gt;This means that we can map large collections with very little overhead. MEGAWHOOP!&lt;/p&gt;
&lt;p&gt;It was really interesting code to write so I encourage you to look through the &lt;a href="https://github.com/JimBobSquarePants/UmbMapper/tree/503f29ebd3b3955e758c729b2a35ac3f0045caed/src/UmbMapper/Proxy"&gt;source&lt;/a&gt; to see how it was all put together, it's very similar to how Entity Framework used to lazy map navigation properties.&lt;/p&gt;
&lt;h3&gt;When to use it?&lt;/h3&gt;
&lt;p&gt;I recommend using this when mapping any pickers or anything that requires significant work when mapped via the Property Value Converter API. You'll most likely be able to use it on all properties but I would always load test any large sites to strike the right performance balance.&lt;/p&gt;
</description>
      <pubDate>Sun, 13 Aug 2017 20:02:23 Z</pubDate>
      <a10:updated>2017-08-13T20:02:23Z</a10:updated>
    </item>
    <item>
      <guid isPermaLink="false">1120</guid>
      <link>http://jamessouth.me/archive/fun-with-umbracovirtualnoderoutehandler/</link>
      <category>System.String[]</category>
      <title>Fun with UmbracoVirtualNodeRouteHandler</title>
      <description>&lt;p&gt;This morning I answered a question on &lt;a href="https://our.umbraco.org/forum/umbraco-7/using-umbraco-7/64766-IIS-Rewrite-or-ContentFinder-UrlSegments"&gt;Our Umbraco&lt;/a&gt; regarding the best approach to provide a url allowing deep links for virtual nodes in Umbraco. In my answer I demonstrated how to use &lt;code&gt;UmbracoVirtualNodeRouteHandler&lt;/code&gt; as a means of telling Umbraco what node to pass as my &lt;code&gt;RenderModel&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Shannon talks about the &lt;code&gt;UmbracoVirtualNodeRouteHandler&lt;/code&gt; with custom routing on his &lt;a href="http://shazwazza.com/post/Custom-MVC-routes-within-the-Umbraco-pipeline"&gt;blog&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;I thought I'd expand on some of the functionality available to the developer by documenting  a trick I use with implementations of &lt;code&gt;UmbracoVirtualNodeRouteHandler&lt;/code&gt; to provide custom routing.&lt;/p&gt;
&lt;h3&gt;Use Case&lt;/h3&gt;
&lt;p&gt;Quite often I find myself reusing a single document type with multiple templates; I'm sure you have also. Most commonly a &lt;em&gt;LoginRegisterPage&lt;/em&gt; or similar. &lt;/p&gt;
&lt;p&gt;Now I don't know about you but one of the things I miss when using Umbraco is the ability to use &lt;code&gt;Url.Action&lt;/code&gt; to generate urls for my content. I like routing in MVC and I think it's important, especially with the type of page as above to be able to generate the correct urls from within your views or controllers.&lt;/p&gt;
&lt;p&gt;To understand what I am going to do here you first need to understand how routing works in Umbraco.&lt;/p&gt;
&lt;p&gt;If you have the &lt;em&gt;DocumentType&lt;/em&gt; &lt;code&gt;LoginRegisterPage&lt;/code&gt; with the assigned template &lt;code&gt;LoginPage&lt;/code&gt; this will map to a &lt;em&gt;RenderMvcController&lt;/em&gt; called &lt;code&gt;LoginRegisterPageController&lt;/code&gt; with an &lt;em&gt;ActionResult&lt;/em&gt; &lt;code&gt;LoginPage&lt;/code&gt;. This behaviour is standardised and predictable so we can utilise it.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;DocumentType == Controller&lt;/li&gt;
&lt;li&gt;Template == ActionResult&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Example&lt;/h3&gt;
&lt;p&gt;So let's start by creating some routes.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Custom routing for the membership pages so we can use
// proper redirects. 
RouteTable.Routes.MapUmbracoRoute(
&amp;quot;LoginPage&amp;quot;,
&amp;quot;Login/&amp;quot;,
new
{
    controller = &amp;quot;LoginRegisterPage&amp;quot;,
    action = &amp;quot;LoginPage&amp;quot;
},
new LoginRegisterPageNodeRouteHandler());

RouteTable.Routes.MapUmbracoRoute(
&amp;quot;RegisterPage&amp;quot;,
&amp;quot;Register/&amp;quot;,
new
{
    controller = &amp;quot;LoginRegisterPage&amp;quot;,
    action = &amp;quot;RegisterPage&amp;quot;
},
new LoginRegisterPageNodeRouteHandler());
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here I have created two routes that map to the relative urls &lt;em&gt;/Login&lt;/em&gt; and &lt;em&gt;/Register&lt;/em&gt;. They both map to the same controller but since two different templates are used it will map to two different &lt;em&gt;ActionResult&lt;/em&gt; methods. &lt;/p&gt;
&lt;div class="alert"&gt;

Note: I didn't use the word "virtual" in my handler names since I am mapping to actual nodes.

&lt;/div&gt;
&lt;p&gt;From here I will create a class that takes advantage of the predictability.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;/// &amp;lt;summary&amp;gt;
/// An Umbraco route handler that allows the retrieval of the template alias name from the route action. 
/// &amp;lt;/summary&amp;gt;
public abstract class TemplatedUmbracoVirtualNodeRouteHandler : UmbracoVirtualNodeRouteHandler
{
    /// &amp;lt;summary&amp;gt;
    /// Get the template from the current route.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name=&amp;quot;requestContext&amp;quot;&amp;gt;
    /// The &amp;lt;see cref=&amp;quot;RequestContext&amp;quot;/&amp;gt; containing information about the current HTTP request and route. 
    /// &amp;lt;/param&amp;gt;
    /// &amp;lt;returns&amp;gt;
    /// The &amp;lt;see cref=&amp;quot;string&amp;quot;/&amp;gt; representing the template alias.
    /// &amp;lt;/returns&amp;gt;
    protected virtual string GetTemplateAlias(RequestContext requestContext)
    {
        return requestContext.RouteData.GetRequiredString(&amp;quot;action&amp;quot;);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This class adds an additional method &lt;code&gt;GetTemplateAlias&lt;/code&gt; to our handler pulling in the &lt;em&gt;RouteData&lt;/em&gt; &lt;code&gt;action&lt;/code&gt; variable which we know matches the template name of the node we want in the content tree.&lt;/p&gt;
&lt;p&gt;And from here we can implement this our handler.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;/// &amp;lt;summary&amp;gt;
/// The generic login/register page node route handler.
/// &amp;lt;/summary&amp;gt;
public class LoginRegisterPageNodeRouteHandler : TemplatedUmbracoVirtualNodeRouteHandler
{
    /// &amp;lt;summary&amp;gt;
    /// returns the &amp;lt;see cref=&amp;quot;IPublishedContent&amp;quot;/&amp;gt; associated with the route.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name=&amp;quot;requestContext&amp;quot;&amp;gt;
    /// The request context.
    /// &amp;lt;/param&amp;gt;
    /// &amp;lt;param name=&amp;quot;umbracoContext&amp;quot;&amp;gt;
    /// The umbraco context.
    /// &amp;lt;/param&amp;gt;
    /// &amp;lt;returns&amp;gt;
    /// The &amp;lt;see cref=&amp;quot;IPublishedContent&amp;quot;/&amp;gt;.
    /// &amp;lt;/returns&amp;gt;
    protected override IPublishedContent FindContent(RequestContext requestContext, UmbracoContext umbracoContext)
    {
        UmbracoHelper helper = new UmbracoHelper(umbracoContext);
        string alias = typeof(LoginRegisterPage).Name;
        string templateAlias = this.GetTemplateAlias(requestContext);

        return helper.TypedContentAtRoot()
            .First()
            .Descendants()
            .First(d =&amp;gt; d.DocumentTypeAlias.InvariantEquals(alias)
                     &amp;amp;&amp;amp; d.GetTemplateAlias().InvariantEquals(templateAlias));
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;div class="alert"&gt;

Note: I use &lt;a href="https://github.com/leekelleher/umbraco-ditto"&gt;Ditto&lt;/a&gt; to create strong-typed models for my back office content. It's ace, you should give it a go!

&lt;/div&gt;
&lt;p&gt;If you look at the code in my handler you will see that I am searching the content for nodes that match both the name and template of the one I want.&lt;/p&gt;
&lt;p&gt;It's as simple as that really... I can now use &lt;code&gt;Url.Action(&amp;quot;LoginPage&amp;quot;, &amp;quot;LoginRegisterPage&amp;quot;)&lt;/code&gt; and &lt;code&gt;Url.Action(&amp;quot;RegisterPage&amp;quot;, &amp;quot;LoginRegisterPage&amp;quot;)&lt;/code&gt; throughout my code to provide the correct urls to my respective pages priding me with functionality I sorely missed.&lt;/p&gt;
</description>
      <pubDate>Wed, 13 May 2015 05:37:56 Z</pubDate>
      <a10:updated>2015-05-13T05:37:56Z</a10:updated>
    </item>
    <item>
      <guid isPermaLink="false">1119</guid>
      <link>http://jamessouth.me/archive/experiments-with-umbracos-icontentservice/</link>
      <category>System.String[]</category>
      <title>Experiments with Umbraco's IContentService</title>
      <description>&lt;p&gt;I haven't had very much experience with the Umbraco &lt;a href="https://our.umbraco.org/documentation/Reference/Management-v6/Models/Content"&gt;ContentService&lt;/a&gt;. I've only just started playing around with it so if I've missed something obvious please tell me in the comments.&lt;/p&gt;
&lt;h3&gt;A Confusing API&lt;/h3&gt;
&lt;p&gt;Reading through the documentation, it seems a shade basic considering the importance of the subject matter and really doesn't go out of it's way to explain what to do and what will happen. &lt;/p&gt;
&lt;p&gt;When saving an item using the content service, the methods signature for the first overload available for setting a property value is as follows.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;IContentBase.SetValue(string propertyAlias, object value);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;According to the documentation you should be able to set different types as the second argument. At time of writing they give the following example:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Given a `ContentService` object get Content by its Id, set a few values
// and saves the Content through the `ContentService`
var content = contentService.GetById(1234);
content.SetValue(&amp;quot;bodyText&amp;quot;, &amp;quot;This text will be added to by RTE field&amp;quot;);
content.SetValue(&amp;quot;date&amp;quot;, DateTime.Now);
contentService.Save(content);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note the &lt;code&gt;DateTime.Now&lt;/code&gt; instance there. Unfortunately support for the different types seems extremely limited. Passing a float causes the following exception.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The best overloaded method match for
'Umbraco.Core.Models.ContentBase.SetPropertyValue(string, string)' has
some invalid arguments.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Yowza! That really doesn't give a great developer experience.&lt;/p&gt;
&lt;h3&gt;Magic Strings&lt;/h3&gt;
&lt;p&gt;Not much in Umbraco when dealing with content is strong-typed. If I were to hazard a guess as to why, &lt;del&gt;I would imagine it was because the code tooling to do some of the conversion functionality we can now was not available when the API's were designed.&lt;/del&gt; (&lt;strong&gt;Update&lt;/strong&gt; Turns out it was just a design decision). I have, however, felt the distinct impression at times through conversation that strong-typing is not wanted in certain areas. &lt;/p&gt;
&lt;p&gt;I'm doing my best to provide it to developers when dealing with the cached  &lt;code&gt;IPublishedContent&lt;/code&gt; methods by contributing to &lt;a href="https://github.com/leekelleher/umbraco-ditto"&gt;Ditto&lt;/a&gt;. Content services, however, are not part of the scope for that project so having spent so much time developing with Umbraco in a strong-typed manner, coming across them here was a bit of a shock.&lt;/p&gt;
&lt;p&gt;Let's look at that method again.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;IContentBase.SetValue(string propertyAlias, object value);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The first parameter accepts a string. Now I don't know about you but the most common use case I would imagine for the method would be uploading a form or importing content through another service. &lt;/p&gt;
&lt;p&gt;That form or service would contain classes with properties and using the API in this format would require the developer to insert magic strings for every property or use reflection to loop through with the property info name manipulating them for each instance. &lt;/p&gt;
&lt;p&gt;Not code I want to write...&lt;/p&gt;
&lt;h3&gt;Expression Trees to the Rescue!&lt;/h3&gt;
&lt;p&gt;I wanted a way that I could call the method in the following format and not have to write those pesky strings:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;IContentBase.SetValue(() =&amp;gt; Class.Property);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In order to do that I will need to create an extension method that uses an &lt;a href="https://msdn.microsoft.com/en-us/library/bb397951.aspx?f=255&amp;amp;MSPPError=-2147217396"&gt;Expression Tree&lt;/a&gt;. This is done by  creating a Lambda Expression to represent the property.&lt;/p&gt;
&lt;p&gt;Once inside our method we check to see whether, a property is being passed, and if so, coerce the various property values to call the old method with sanitized values.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;/// &amp;lt;summary&amp;gt;
/// Sets the value of an &amp;lt;see cref=&amp;quot;IContentBase&amp;quot;/&amp;gt; property to the given value.
/// &amp;lt;/summary&amp;gt;
/// &amp;lt;param name=&amp;quot;contentBase&amp;quot;&amp;gt;
/// The &amp;lt;see cref=&amp;quot;IContentBase&amp;quot;/&amp;gt;.
/// &amp;lt;/param&amp;gt;
/// &amp;lt;param name=&amp;quot;propertyLambda&amp;quot;&amp;gt;
/// The &amp;lt;see cref=&amp;quot;Expression&amp;quot;/&amp;gt; designating the value to save.
/// &amp;lt;/param&amp;gt;
/// &amp;lt;typeparam name=&amp;quot;T&amp;quot;&amp;gt;
/// The &amp;lt;see cref=&amp;quot;Type&amp;quot;/&amp;gt; of the property value.
/// &amp;lt;/typeparam&amp;gt;
/// &amp;lt;exception cref=&amp;quot;ArgumentException&amp;quot;&amp;gt;
/// Thrown if the given &amp;lt;see cref=&amp;quot;Expression&amp;quot;/&amp;gt; is not in the correct form.
/// &amp;lt;/exception&amp;gt;
public static void SetValue&amp;lt;T&amp;gt;(this IContentBase contentBase, Expression&amp;lt;Func&amp;lt;T&amp;gt;&amp;gt; propertyLambda)
{
    MemberExpression expression = propertyLambda.Body as MemberExpression;

    if (expression == null)
    {
        throw new ArgumentException(&amp;quot;You must pass a lambda of the form: '() =&amp;gt; Class.Property' or '() =&amp;gt; object.Property'&amp;quot;);
    }

    PropertyInfo property = expression.Member as PropertyInfo;
    if (property != null)
    {
        MemberExpression member = (MemberExpression)expression.Expression;
        ConstantExpression constant = (ConstantExpression)member.Expression;
        object fieldInfoValue = ((FieldInfo)member.Member).GetValue(constant.Value);
        object value = property.GetValue(fieldInfoValue, null);
        string name = property.Name.ToSafeAlias(true);
        contentBase.SetValue(name, value.ToString());
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It's basic and doesn't take into account type conversion to and from strings, nor existing supported types but it's certainly a step in the right direction and better than what was there before.&lt;/p&gt;
&lt;p&gt;Obviously, also, there is a an element of assumption in that technique in that we cannot predict what the alias will be and can only go on the most likely name based on the property. Personally though I don't believe the alias should be human editable and should be abstracted away with greater convention. That allows greater predictability and better quality code.&lt;/p&gt;
&lt;p&gt;I would like to see more API signatures in Umbraco like the example I have created and would be more than happy to help try to tighten up the various APIs for the next major version.&lt;/p&gt;
&lt;p&gt;Let me know what you think.&lt;/p&gt;
</description>
      <pubDate>Wed, 25 Mar 2015 10:59:31 Z</pubDate>
      <a10:updated>2015-03-25T10:59:31Z</a10:updated>
    </item>
  </channel>
</rss>