Monthly Archives: January 2010

Adding icons to the PageTree in EPiServer CMS 6.

A feature I use heavily in Umbraco, and one I've missed in EPiServer CMS, is the use of icons for different page types in the tree. Although this functionality has been around for a while using PageTreeIcons, when using PageTypeBuilder it can be quite cumbersome to maintain a configuration with PageTypeId's, when we want to move away from that.

Heavily inspired (and with some borrowing), I've converted the PageTreeIcons project to a collection of attributes that you can use to alter the icons for page types and properties. It's still an early draft, but it works.

This way, it's really easy to keep track of the icons for your properties, and there's no need to keep an extra section in your web.config. Some features have been removed, since EPiServer CMS 6 already contains some of the functionality (i.e the PageLinkTypeHandler).

It's applied like this, on page types

[PageTypeIcon("~/UI/Images/PageTreeIcons/page.png", typeof(ContentPage))]
[PageType(AvailablePageTypes = new[] { typeof(ContentPage) },
   Filename = "~/UI/Pages/ContentPage.aspx",
   SortOrder = 20,
   Name = "[Public] ContentPage",
   DefaultSortIndex = 100,
   Description = "An ordinary content page.")]
public class ContentPage : PageTypeBuilder.TypedPageData { ... }

and like this, on a property

[PropertyEmptyIcon("~/UI/Images/PageTreeIcons/warning.png", 
   "/pagetreeicons/property/missingkeywords", 
   "MetaKeywords", 
   new [] { typeof(BaseModule), typeof(ModuleContainer), typeof(Contact) })]
[PageTypeProperty(EditCaption = "Keywords",
   HelpText = "A comma-separated string containing keywords used for this page.",
   Searchable = true,
   UniqueValuePerLanguage = true,
   Type = typeof(PropertyString),
   SortOrder = 10)]
public virtual string MetaKeywords {
   get;
   set;
}

Again, kudos to Henrik Nyström, http://thisisnothing.wordpress.com/, for writing this in the first place.

Please let me know if you have any comments, improvements, or questions.

Download the code here.

Don't have any icons? Try FamFamFam Silk!

Preemo!

We've just gotten the kid to go to bed without having to be breast fed at even intervals throughout the night, and all in time to go see DJ Premier at Berns on the 19th of May. I must've done something right. My mom will be babysitting, or, rather babysleeping, since my awesome kid will be sleeping through the whole ordeal. I love you mom. I love you Alfred. Daddy's going to see Chris Martin perform.

DJ Premier with Nic javas

Simple validation of property values, redux.

Stefan Forsberg wrote an excellent post on validating page data with Data Annotations, his solution is by far a more elegant way of validating data on a property than my ugly hack. So I rewrote my PageType validation hack to fit into his model instead. I converted my very specific code into a more generic ValidationAttribute. Works like a charm, and makes sure that the PageReference actually points to a page of the type you want, or nothing at all.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using EPiServer.Core;
using PageTypeBuilder;

namespace Development {

    ///
    /// Specifies the allowed type of pages selected in the property.
    ///
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
    public sealed class AllowedPageTypeAttribute : ValidationAttribute {

        ///
        /// The allowed types of pages.
        ///
        public Type[] AllowedPageTypes {
            get;
            set;
        }

        public AllowedPageTypeAttribute(Type[] allowedPageTypes)
            : base() {
            this.AllowedPageTypes = allowedPageTypes;
        }

        public override bool IsValid(object value) {
            var reference = value as PageReference;
            // Check if the property ReferenceContainer has a value
            if (PageReference.IsNullOrEmpty(reference))
                return true;

            var page = reference.GetPage();
            if (page == null)
                return false;

            var pageType = page.GetType();

            foreach (Type t in AllowedPageTypes) {
                if (pageType.IsAssignableFrom(t) || t.IsAssignableFrom(pageType) )
                    return true;
            }
            return false;
        }
    }
}

And it's simply implemented on the Page property thus:

///
/// Name: Office
/// Description: The office associated with this container.
///
[AllowedPageType(new[] { typeof(OfficePage) }, ErrorMessage = "/errors/OfficePagePageType")]
[PageTypeProperty(
EditCaption = "Office",
HelpText = "The office associated with this container.",
Searchable = false,
UniqueValuePerLanguage = true,
Type = typeof(PropertyPageReference),
SortOrder = 15,
Required=true)]
public virtual PageReference OfficePage {
        get {
                var value = this.GetPropertyValue(page => page.OfficePage);
                return value ?? PageReference.EmptyReference;
            }
        }
}

It's also very easy to do e-mail validation etc. on properties. Like this for example.

[RegularExpression(@"^\b[\w\.-]+@[\w\.-]+\.\w{2,4}\b$", ErrorMessage = "/errors/EmailFormat")]

It's so simple it almost hurts.

SEO lowercase urls, in EPiServer CMS 6, that actually work.

Last week I wrote a short blog post about how to create consistent, lowercase, URLs for your EPiServer CMS 6 site. While there has been some discussion wether or not the casing of the URLs affect indexing, this post is more of a correction on the code in the last post.

I did what I've been telling people not to do. I copied code, and I expected it to work as advertised. Needless to say, it didn't. The general idea was to hook into the UrlSegment.CreatedUrlSegment event, and make sure that the URL was lowercase. It works fine every time you edit a page, and alter the URLSegment property. However, if you go into admin mode, and decide to rebuild all URLs, you're in for a treat. The Rebuilding of URLs doesn't fire the UrlSegment.CreatedUrlSegment event, since it just alters the property on the PageData object, and creates a new version of the page. This circumvents the event model for URLSegements, I'd call it a bug, others might call it a feature, but I leave it up to more intelligent people than me to decide what to do. In the meantime, I've moved my logic to the DataFactory.Instance.SavingPage event, since that is fired every time the page is saved, no matter where you alter the page from. It's in the DataFactory, it's "unfuckwithable".

I copied code, I'm sorry. I will never do it again. Never. At least not without testing the results throughly first :)

Simple validation of propertyvalues in EPiServer CMS 6

Last week I blogged about SEO lowercase URLs, a concept known to many, and I blatantly stole the idea for the post from someone else. Today I'm gonna try to build on the other post, actually providing some input of my own, and show how one can easily do custom property validation, without having to write your own custom property. Having custom properties can be a tedious way to work, when all you essentially have is a string property, or a PageReference. The other post contains the code for hooking into events, so I suggest you get it from there if you have no idea where to put this.

First, we hook into the event DataFactory.Instance.SavingPage.


void Instance_SavingPage(object sender, PageEventArgs e) {

    // Check if the page is a ReferenceContainer
    if (e.Page is ReferenceContainer) {
        var refContainer = e.Page as ReferenceContainer;
        // Check if the property OfficePage has a value
        if (!PageReference.IsNullOrEmpty(refContainer.OfficePage)) {
            var office = refContainer.OfficePage.GetPage();
            // Check if the page selected in the OfficePage property is of the correct type.
            if (!(office is OfficePage)) {
                e.CancelAction = true;
                e.CancelReason = LanguageManager.Instance.Translate("/errors/validation/properties/OfficePage");
            }
        }
    }

    // Check if the page is an OfficePage
    if (e.Page is OfficePage) {
        var officePage = e.Page as OfficePage;
        // Check if the property ReferenceContainer has a value
        if (!PageReference.IsNullOrEmpty(officePage.ReferenceContainer)) {
            var refContainer = officePage.ReferenceContainer.GetPage();
            // Check if the page selected in the ReferenceContainer property is of the correct type.
            if (!(refContainer is ReferenceContainer)) {
                e.CancelAction = true;
                e.CancelReason = LanguageManager.Instance.Translate("/errors/validation/properties/ReferenceContainer");
            }
        }
    }
}

Basically, we try to get the page from the PageReference property, if it's set, and check if it's of the correct type using functionality in PageTypeBuilder. PageTypeBuilder, I love you.

As always, comments are welcome, maybe I've tried to solve this whole issue the wrong way. Please let me know if I did :)

SEO lowercase urls, in EPiServer CMS 6

Yesterday I read a blog post by Lars Timenes, describing how one could easily generate a bit more friendly URL Segments in EPiServer. (Just an observation, but the EPiServer site hosting the blog post, doesn't seem to use his code.) His example uses the CMS 5 style of hooking into events, so I thought I'd give an example of how to do it in CMS 6 and the new Initialization engine. The back story here, is that sites like Google, sees all lower case URLs, and mixed case URLs as different URLs. Although this can be fixed by adding a <link rel="canonical" /> tag to your markup, I like to have more than one solution to things.

In order to get this to work, you'll need to add references to the EPiServer.Framework.dll and the System.ComponentModel.Composition.dll, both installed with CMS 6 and located in the "C:\Program Files (x86)\EPiServer\Framework\6.0.x.x\bin" directory.

Oh, and as a side note, Yes, I do write all those tedious documentation comments in my production code. It's how I do things. Sorry for being a goody two-shoes.

Edit: After reading Magnus's comment, I added the simple code to detach the event.

Edit: Karl, case doesn't matter to the server, but search engines may or may not (it's entirely up to them, not me), index URLs with different casing as different pages, severly affecting the PageRank of the URL in question. That's why I want my URLs to display consistently, and if I always render them in lowercase, I doubt someone will try to link to my site using a mixed-case URL of their own device.

using System;
using EPiServer;
using EPiServer.Framework;
using EPiServer.Framework.Initialization;
using EPiServer.Web;

namespace Development {

/// <summary>
/// An <see cref="EPiServer.Framework.IInitializableModule" /> enabling hooking into EPiServer events.
/// </summary>
[ModuleDependency(typeof(EPiServer.Web.InitializationModule))]
public class ModuleInitializer : IInitializableModule {


#region IInitializableModule Members
/// <summary>
/// <para>Initializes the Module and attaches custom eventhandlers.</para>
/// <para>Attaches a <see cref="System.EventHandler" /> for the EPiServer.Web.UrlSegment.
/// CreatedUrlSegment event.</para>
/// </summary>
/// <param name="context">The current 
/// <see cref="EPiServer.Framework.Initialization.InitializationEngine"/></param>
public void Initialize(InitializationEngine context) {

UrlSegment.CreatedUrlSegment += 
new EventHandler<UrlSegmentEventArgs>(UrlSegment_CreatedUrlSegment);
}

/// <summary>
/// Makes sure that all URL Segments are always lowercase, for increased SEO performance.
/// </summary>
void UrlSegment_CreatedUrlSegment(object sender, UrlSegmentEventArgs e) {

e.PageData.URLSegment = e.PageData.URLSegment.ToLowerInvariant();
}

/// <summary>
/// Perform pre-loading tasks.
/// </summary>
public void Preload(string[] parameters) {

}

/// <summary>
/// <para>Uninitializes the Module.</para>
/// <para>Detaches the <see cref="System.EventHandler" /> for the EPiServer.Web.UrlSegment.
/// CreatedUrlSegment event added during Initialization.</para>
/// </summary>
/// <param name="context">The current 
/// <see cref="EPiServer.Framework.Initialization.InitializationEngine"/></param>
public void Uninitialize(InitializationEngine context) {
UrlSegment.CreatedUrlSegment -= 
new EventHandler<UrlSegmentEventArgs>(UrlSegment_CreatedUrlSegment);
}
#endregion
}
}

Sleep deprivation is the most powerful of tortures.

This weekend has been rough. My son, at a whooping age of 5 months, keeps waking up at around 5 AM. I try to go to bed early to make up for this fact, but it doesn't matter, it still feels horrible to be awake when the paper guy delivers the morning paper at 5.30.

To top thing off, this weekend has been full of work. We're trying to sell the apartment, so we've been homestyling it extensively. To those of you who don't know what homestyling is, it can easily be explained as the process of removing everything in your home that can seem offensive, crowding, or otherwise undesirable. To anyone. What it means is, get rid of everything. Clear it out. Hide it, sell it, or throw it away. Our storage unit in the attic is so full of stuff, it will probably burst any day. But the apartment looks nice and stylish. Hopefully it'll bring a pretty penny. But keep in mind, clearing out an apartment, while trying to look after a 5-moth-old, is no walk in the park.

Next weekend, we're going to Berlin, for a well deserved vacation. Any tips for sights in need of seeing is welcome. Hopefully, Alfred won't keep us awake the whole trip.

My take on "ASP.NET MVC 2 Bootcamp" Workshop at MIX10.

First off, I chose not to bring my PC laptop, since I thought it would just be in the way, and that I'd do fine with just my MacBook Pro. I installed MonoDevelop on it a few weeks ago, and it seemed fine, it even ran MVC, and had a built-in MVC Project template. However, it doesn't run .NET 4.0, so I had plenty of time to listen and blog, instead of doing coding. Yeah, I know. I suck. Next time, I'll bring a Windows computer to a Microsoft event, I should have figured as much.

The setup here at MIX10 isn't really optimized for attendees with laptops requiring power, there are 100 people in the room, and approximately 12 utility outlets. I chose to move my chair to the wall, where my power cord would reach. And as Jon Galloway said, "I was hoping that people would be sitting with laptops and typing along". That won't be happening for a three and a half hour long workshop, obviously.

I don't really feel that Jon had prepared his session very well, I get that it's hard to set a target audience level, when you know nothing about your audience, but, you could assume that when you're doing a workshop, you shouldn't use a Visual Studio version (2010), that isn't released yet, and provide samples for attendees that won't run on the currently released version, 2008. That's not cool at all.

Most attendees started out with their laptops in their laps, (since there were no tables, just chairs), but after about 40 minutes, most of them had put them down.

I might seem very negative, but I think the workshop content was very interesting, however, not very well delivered. I might be wrong here, but all of the attendees have actually paid an extra $295 for the workshops, and in my book, that sets a requirement of quality for workshop content.

You can watch the Workshop over at Channel 9.

My take on "Design Fundamentals for Developers (and Other Non-Designers)" Workshop at MIX10.

"Kill your babies."
- Robby Ingebretsen

I fully agree, and I believe this is the key component to the creative process, be it design, development, writing or whatever you may partake in. Having the courage to throw away, redo, or in other ways alter your work or parts of it, is a crucial ability if you want to be successful.

All-in-all, having participated in this workshop, I feel that I have been given a new set of communicational tools, that enable me to convey my thoughts to a designer, in a way that the designer hopefully can understand.

However, it should also be said, that I really think the workshop should be named "Design Fundamentals for Professionals That Need Structure and Arguments For Why They Do What They Do in The Creative Process". There are way too many people in the industry that just do things, and have no rationale as to why they do them. This workshop is for you. And anyone wanting to work with you.

You can watch the workshop at Channel 9.

Finally arrived at MIX10.

I arrived yesterday, after a long long ride on various airplanes. But I've learned a few things so far:

1. Chicago O'Hare airport, is HUGE, and an incredibly boring airport.

2. At McCarran International in Las Vegas, the slot machines start at the gate.

3. Las Vegas is INSANE!

 

Today is workshop day, and I'm attending two workshops.

Right now I'm sitting in the first one, "Design Fundamentals for Developers". Let's see what it'll bring.

However, the one I'm really looking forward too is the "ASP.NET MVC Bootcamp" this afternoon.