Sunday, 12 December 2010

N2CMS MVC and how to create a configurable MasterPage option

One of the most common questions on the N2CMS forums seems to be how to make it possible to be able to select a master page. In the past when I've worked on cms driven sites the templates have been relatively straightforward - the homepage has had a unique design whilst the others have had a set template. This was quite easy to do as I just created my own class which derived from the StartPage class and then created it's own HTML without using the main MasterPage. Simple, but effective.

However, recently I've been asked to convert an existing Sharepoint site to the MVC version of N2. This has been quite interesting to do and one of the areas I've had to work on is how to give the user the option of which master page template to use. I can't do this statically and because there are a number of templates on the current Sharepoint site it's possible that users may need to change page templates "on the fly".

I'm not going to go to deep in to the workings of this - it's probably easier to fire up N2 MVC and step through the code. I'm going to give you a step-by-step tutorial to get it working!

I'd like to thank the guys on this discussion on the N2CMS forum (n2cms.codeplex.com/discussions?size=2147483647) for providing the inspiration for this. I can't find the exact post however.

Step 1:
Make sure you download the latest v2.1rc MVC version of the site and make sure you copy the DLLs in the library folder into the bin folder of the N2CMS folder. If you don't do this with then you might get an error when you first try to start the site.

Step 2:


In the services folder, open the ThemedMasterViewEngine.cs file. In that there's a method which tries to determine which Master page to use based on theme or uses the  there's a class which checks to see what master page to use.



public class ThemedMasterViewEngine : WebFormViewEngine
{
        // You should change the "TwoColumnLayout.master" to be your default template
        string masterPageFile = "~/Views/Shared/TwoColumnLayout.master";

public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
{
if (!controllerContext.IsChildAction)
{
if (string.IsNullOrEmpty(masterName))
masterName = masterPageFile;

var root = Find.Closest<StartPage>(controllerContext.RouteData.CurrentPage()) ?? Find.ClosestStartPage;
if (root != null)
{
string theme = root.Theme;
if (!string.IsNullOrEmpty(theme))
{
string potentialMaster = string.Format("~/Views/Shared/{0}.master", theme);
if (base.FileExists(controllerContext, potentialMaster))
{
masterName = potentialMaster;
}
}
}
}

return base.FindView(controllerContext, viewName, masterName, useCache);
}
}

Step 3:

In the models/pages folder there's a ContentPageBase.cs class. We're going to change this to add an enum for the name of the page templates and add a property for any page which derives from the ContentPageBase (which is all of them) which allows you to select a template and puts it under the Advanced tab.

Open /Models/Pages/ContentPageBaseup and add this code:

        public enum PageTemplates
        {
            MyHomePage,
            TwoColumnLayout
        }

        [EditableEnum("Page layout", 60, typeof(PageTemplates), ContainerName = Tabs.Advanced)]
        public virtual PageTemplates PageLayout
        {
            get { return (PageTemplates)(GetDetail("PageLayout") ?? PageTemplates.TwoColumnLayout); }
            set
            {
                SetDetail("PageLayout", value, PageTemplates.TwoColumnLayout);
            }
        }

Step 4:

In the controllers folder, open up the TemplatesControllerBase.cs file. We're going to add some code in here which tries to get the name of the PageLayout from the page and sets the master page. Find the method below (be careful - there's a few overloads of it) and replace the method with this code:

protected override ViewResult View(string viewName, string masterName, object model)
{
CheckForPageRender(model);

            model = model ?? CurrentItem;
            if (model != null)
            {
                var item = model as N2.Templates.Mvc.Models.Pages.ContentPageBase;
                if (!string.IsNullOrEmpty(item.PageLayout.ToString()))
                {
                    masterName = item.PageLayout.ToString();
                }
            }

return base.View(viewName, masterName, model ?? CurrentItem);
}

Step 5:

I think this might be an oversight in the n2 release, but I've found I have to add this line into the web.config in the n2 editing folder:

<httpRuntime requestValidationMode="2.0" />

Otherwise I get an error when I try to change the page layout.

Step 6:

If you start up your site, and select "Edit" on any page you will find that under the "Advanced" tab you have a drop down list of layouts. If you change this you will be able to change the master page used on the site!

Friday, 3 December 2010

New version of N2CMS released

I don't know if you've seen on http://n2cms.codeplex.com/releases but v2.1rc has been released. I'd strongly recommend anyone to sign up for the release notifications on Codeplex for the code as this way you will get the latest versions as soon as they come out. On the page for the releases if you look on the right you'll see the button to set notification settings.

As you know, I've been doing tutorials for the web forms version of N2. If you read my earlier posts you'll have read that for beginners I'd recommended the web forms version to get started with because of the better templates that came with it - it was simply easier/quicker to create pages and items. This looks like it has changed with the new release and I am currently investigating the new changes so that I'll be able to comment on the web forms vs MVC projects.

Another reason to download the new version is that it now ships with documentation! Now, I've read the documentation and it's still not perfect nor complete but it's far better than the array of wikis, pages and dead pages that are on the web. So, if nothing else you have a much better starting point for v2.1 than you did with the earlier versions.

All that said, I still aim to continue writing on this blog. There's some new features in the new version which look very interesting such as templates. This will allow you to create templates of pages and subpages with pre-populated content. Very useful.

I think however, my focus will broaden somewhat to include my experiences of the N2 MVC. I also am intrigued by how we can extend the editor with jQuery and similar technologies.

For now though, have a look at the new version!

Thursday, 25 November 2010

Enhancing the editor

I realise I've not updated the blog for a while, so apologies for that. A mixture of work and other engagements has meant that I've not had the time to get some thoughts down for a while!

One area of N2 I've had to look at in recent months are the editor pages. At first glimpse it might seem that there's not a great deal you can do with them to specialise them seeing as they are to cater for the creating and editing of every single page type in your website. I've not needed to go into the guts of how the editor works as yet, but I've found a few things that might be of interest and certainly may help you get round a few tricky areas.

You will have to bear with me on this whilst I explain the background to the problem. On one recent project, I had a simple hierarchy similar to this:

Suppliers 

  • WH Smith (all our books cost £10 and our magazines £5)
  • News International (all our books cost £12 and our magazines £3)

Products

  • Books
    • Call of the wild
    • The Hobbit
    • Lord of the Rings
  • Magazines
    • FMH
    • Shoot
    • Radio Times
So each supplier has a set price list and when you create a book or a magazine you have to select a supplier and then display the "summary" of that supplier including the prices. In effect the problem we have then is to take something that is generic (the creator/editor) yet add code to handle specifics. I appreciate there is ways to do this, but I didn't really want (for time reasons primarily) to get my hands dirty in the source code of N2. 

The way I did this though was to use jQuery to make Ajax calls to a web handler (ASHX files).  I'd written which returned XML with details of the supplier. My jQuery code detected the type of page we're creating and then hooked in the calls to update the supplier summary if the supplier changed. When I get more time, I will try to package a simple example of this to demonstrate the principle. In effect it is just  a jQuery/Ajax solution but it certainly allows the N2 editor to potentially become even more responsive and powerful. Taken further, maybe we can add some jQuery features to the editor to check for the uniqueness of page titles, maybe even preview the page you're working as you type!

I am not saying this method is perfect at all, but in future it's certainly a technique  I'd definitely consider again.

Tuesday, 14 September 2010

More room for the editor labels

This is just a quick tip for an N2CMS MVC site that I've found literally as I'm just making a few changes to a site I'm doing at the moment so it's short and sweet!


One of my clients says that when they are editing a page the descriptive labels next to the textboxes, checkboxes and dropdownlists are a bit "squashed" and I have to say I agree. There's very little space given for the labels before they roll onto the next line.


Just change the /N2/Resources/Css/Edit.css file where it says:-
body.framed .itemEditor .editorLabel { width:110px; float:left; clear:left; padding:5px 5px 0 0; margin:0 0 5px 0; }
to
body.framed .itemEditor .editorLabel { width:210px; float:left; clear:left; padding:5px 5px 0 0; margin:0 0 5px 0; }
Your labels are now twice as wide and it looks much neater. I think I will include this is all my future N2 sites.

Cheers!

Friday, 3 September 2010

Hosting companies that work with N2CMS

I just thought I'd share this with you and it may be something I revisit a few times in the coming months. I've seen a few people asking on the forums about which web hosts work with N2CMS.

I have a few clients where they had an existing web site that is maintained by an external company and they want a CMS site which they can maintain themselves. Usually they are likely to be non-technical users in smaller companies. As a result of this, they are generally reluctant to move hosting companies for a variety of reasons such as the cost to terminate a contract and set up a new one, previous good service and also having to do other things like changing DNS records and migrating emails.

The problem I then have is that I don't get to specify which hosting company to use, it's given to me! Obviously, I know which ones will work from previous experience.


As a result of this, one of the first things I do is my "one hour" test. Basically if I can't download the code, deploy a "vanilla site", configure a few settings, create and edit a couple of pages within the hour I think that it will be problematic later on. I may well be able to fix all the issues if I had more time, but this is my rule of thumb. 


I have worked with three hosting providers and one intranet so far and here's my findings.


  • ukfast.co.uk
    I had a few issues with them that I couldn't resolve in my hour which I suspect may have been related to medium trust. Luckily the client was moving to a new hosting provider anyway so it didn't matter in the end, but if you're going to deploy an N2CMS site to ukfast, double check it first! They may have upgraded their hosting services since, but check first.
  • discountasp.net
    I have had no problems with these at all - the only slight "gotcha" I had was that I had to make sure IIS7 to work in "integrated mode" with the N2CMS MVC project, but I suspect this was because I upgraded from IIS6 to IIS7. I used a SQL Server database server on these projects and it all worked no problem. I'd also say that when I emailed support about non-N2 matters they were very helpful and prompt which gave me confidence.
  • FastHosts.co.uk
    I have had no problems with these at all - everything worked out of the box. The only slight issue I had (although I suspect it wasn't a FastHost issue as such) was that we had to get them to set IIS to work on ASP.NET v2 which is something I'd have expected out of the box. I suspect this could just have been because the server was a few years old, but again it's something to double check. I used a MySQL database server on two projects and had no problems at all. I had to email support a question about MySQL database and again this was answered promptly.
  • Intranet server running IIS6
    Just make sure that the ASPNET account can write to the upload directory or similar if you plan to allow users to upload documents or images but overall, n
    o problems here - deployed the site onto the server and it worked no problem :)

The databases work no problem and there's no difference from I (or the client!) can tell with regards to speed with either SQL Server or MySQL.

I am sure that some of these issues may well be specific to the projects I worked on - especially as the servers had been used on older sites, but if you experience a couple of problems then it's worth just double checking that the settings are correct. If you have problems with you current host then from my own personal experience as someone who's created and deployed working N2CMS sites onto live servers, these hosts will work for you too! :)

Thursday, 2 September 2010

Resizing images on N2

One of the main issues you have with CMS systems is clients uploading images. Usually they take some pictures on their cameras and just want to upload the images without having to edit it in Photoshop or some other editing software.

The parameters

The parameters are pretty self explanatory, but let's run through them to make sure.Remember these are all done via the querystring e.g image.ashx?img=picture.jpg&w=100&h=75

  • img - this is the url of your image and can be a url from anywhere on the site
  • w - this is the width of the image.
  • h - This is the height of the image. 
You can pass in the width, height or both parameters. If you only specified either the width or the height though then the handler will automatically resize your image to the correct proportions.

Note if you're using an N2 image property that you may need to remove the ~ at the start of the url. Also, you will need to URLEncode this so that spaces etc are handled correctly. If you don't see the image appearing on your page or it appears as a broken link, it's most likely to be because the handler cannot load the image.

I have found this really helpful when automatically resizing an image depending on where it is dropped on a page. For example, if we had a standard two-column page with a small left hand column and a wider main column on the right, we'd want to size the image so that it wasn't too big - or small - for the column.

If we had a "Photograph" part, you could check which parent Zone it was in and then pass in different values to the image.ashx handler!

Sunday, 29 August 2010

Tip: Configuration settings on your website

Just a little tip today, but one I've had to use on all the N2 work I've done.

For most sites I've had to do, I've had to add general configuration settings that can be access by any page. The current N2 site has these - if you right click/edit on your homepage and then click on the "Site" tab, you'll see a few there such as 404settings and the like.

I like to put all my config values in here as it's then all in the one place, but accessing them is a bit of a pain. If you try to access them by N2.Find.StartPage then the object returned is a ContentItem, not a StartPage.

To get round this, I create a static class and have a static method to return any property in the configuration settings:

public static StartPage SiteConfigurationSettings
{
        get
        {
                StartPage sp = N2.Find.StartPage as StartPage;
                if (sp == null) 
                {
                        throw new Exception("Cannot find the N2 Start page");
                }
                else
                {
                        return sp;
                }

        }
}

Now you can then access this property across the site in code as well as allow the end users to be able to update the value!

This is just a simple bare-bones example, but of course, you can cache this property too :)