How I added a Custom Umbraco Member Type for CWS Reboot programmatically

Hello all,
I am currently in the progress of rebuilding and rebooting the CWS Starter Kit project for Umbraco built in MVC on Umbraco 6. For this it will contain a members area and there is no way currently to package up member types and its custom properties.

So read on how to find out how I managed to come up with a solution to this problem.

Continue reading “How I added a Custom Umbraco Member Type for CWS Reboot programmatically”

Don’t make the same mistake as I did when creating a custom Umbraco macro parameter type

In this blog post I will share with you some advice and a code example of a custom Umbraco macro parameter I built for a client Umbraco package.

This needed to be able to exclude document types, but the list shown to them needed to be filtered to begin with. By hiding document types that have no templates and by also excluding a predetermined list of document types such as configuration folders etc…

So read on to find out how I achieved it with some help of my colleague Anthony Dang to help debug an issue with it, which I will discuss later on.

Continue reading “Don’t make the same mistake as I did when creating a custom Umbraco macro parameter type”

Umbraco MVC: What on earth is a surface controller?

Continuing the Umbraco MVC blog post series we will look at Surface controllers in this post and find out what the heck they are why they are so important when building Umbraco MVC websites.

Read on to find out how to implement your very own surface controllers.

Continue reading “Umbraco MVC: What on earth is a surface controller?”

Umbraco MVC: Is the macro as useful in V6 with Partials?

Following on from my previous blog post on Umbraco MVC, where we got MVC setup in Umbraco and created nested templates. In this next post in this series, I will talk about adding dynamic functionality to your website such as a simple navigation and discuss that perhaps that the Umbraco Macro is no longer needed as much as we have used it before. So carry on reading to find out why that the Umbraco macro is perhaps on it last legs in my opinion.

Continue reading “Umbraco MVC: Is the macro as useful in V6 with Partials?”

Umbraco MVC: First Steps

Like most people we fear change, but that should not be the case with the switch from WebForms to MVC in Umbraco. I’ve made the switch and am glad I have done it. In this blog series I will go through common scenarios to make us all feel better about MVC with Umbraco.

So carry on reading on to find out how to take our initial baby steps towards a better and happier development life with Umbraco MVC.

Continue reading “Umbraco MVC: First Steps”

Umbraco & PetaPoco to store blog comments

What is PetaPoco?

PetaPoco is defined as tiny micro ORM (Object Relational Mapping) but for the non techy people like myself all this means is that we have an easy way to map objects in our code to custom tables in our database, to be able to do simple CRUD (Create, Read, Update & Delete) operations on that data in a very simple manner.

Read on to find out why you should use it and how you can use it in your Umbraco websites.

Why should I use it?

So you may ask yourself why would I ever use this and why would it benefit me? Well let’s take a scenario to help explain it better. If we have a blog site built on Umbraco and want to store comments for our blog posts. You may store them as child nodes of your blog post node in the content tree, but if your blog grows quickly or you have a lot of blog posts or comments then you will content tree will start to grow at a very rapid pace. Instead we could create a custom database table in our Umbraco website, where we could store our comments in and will keep our Umbraco content tree a lot more tidier. But there are many use cases for storing information in custom database tables as opposed to content nodes directly inside Umbraco.

How do I use it?

Rather than try to explain it without any code, I would much prefer to show you with some heavily commented working examples for you to read over.
So let’s carry on to the next section and show you the code!

Show me the code!

Firstly create a folder in your Umbraco website called pocos and add a class file called BlogComment.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

//These are the main namespaces we need to use
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.DatabaseAnnotations;

namespace MyWebsite.pocos
{
    [TableName("BlogComments")]
    [PrimaryKey("BlogCommentId", autoIncrement = true)]
    [ExplicitColumns]
    public class BlogComment
    {
        [Column("id")]
        [PrimaryKeyColumn(AutoIncrement = true)]
        public int BlogCommentId { get; set; }

        [Column("BlogPostUmbracoId")]
        public int BlogPostUmbracoId { get; set; }

        [Column("Name")]
        public string Name { get; set; }

        [Column("Email")]
        public string Email { get; set; }

        [Column("Website")]
        public string Website { get; set; }

        [Column("Message")]
        [SpecialDbType(SpecialDbTypes.NTEXT)]
        public string Message { get; set; }
    }
}

Next create a class file called RegisterEvents.cs this is used to hook into the Application Startup event of Umbraco, which will allow us to check if the custom database table exists or not and if it doesn’t then to create it for us.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using umbraco.cms.presentation;
using Umbraco.Core;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic;
using umbraco.cms.businesslogic.web;
using Umbraco.Core.Persistence;
using MyWebsite.pocos;

namespace MyWebsite
{
    public class RegisterEvents : ApplicationEventHandler
    {
        //This happens everytime the Umbraco Application starts
        protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
        {
            //Get the Umbraco Database context
            var db = applicationContext.DatabaseContext.Database;

            //Check if the DB table does NOT exist
            if (!db.TableExist("BlogComments"))
            {
                //Create DB table - and set overwrite to false
                db.CreateTable<BlogComment>(false);
            }

            //Example of other events (such as before publish)
            Document.BeforePublish += Document_BeforePublish;
        }

        //Example Before Publish Event
        private void Document_BeforePublish(Document sender, PublishEventArgs e)
        {
            //Do what you need to do. In this case logging to the Umbraco log
            Log.Add(LogTypes.Debug, sender.Id, "the document " + sender.Text + " is about to be published");

            //cancel the publishing if you want.
            e.Cancel = true;
        }
    }
}

The final part is for us to insert records into our custom database table and retrieve those values as well. There may be a few different approaches to this but normally in your Controllers or in our case with Umbraco it would be SurfaceControllers we would have a few methods in a controller to deal with a blog comment form post and also another for listing out the blog post comments to a partial view.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Umbraco.Web.Mvc;

namespace MyWebsite.controllers.SurfaceControllers
{
    // I don't encourage you to put your viewmodel class in your surface controller, only done for this example for readability
    public class BlogPostViewModel
    {
        [Required]
        public string Name { get; set; }

        [Required]
        [EmailAddress]
        public string Email { get; set; }

        [Url]
        public string Website { get; set; }

        [Required]
        public string Message { get; set; }
    }

    public class BlogSurfaceController : SurfaceController
    {
        [HttpGet]
        public ActionResult RenderComments()
        {
            //Connect to the Umbraco DB
            var db = ApplicationContext.DatabaseContext.Database;

            //Get the current Umbraco Node ID
            var currentNodeId = UmbracoContext.PageId.Value;

            //Get an IENumberable of BlogComment objects to iterate over
            var comments = db.Query("SELECT * FROM BlogComments WHERE BlogPostUmbracoId=@0", currentNodeId);

            //Return the view with our model and comments
            return PartialView("viewComments", comments);
        }

        [HttpPost]
        public ActionResult HandleCommentPost(BlogPostViewModel model)
        {
            //Check if the data on the model is valid
            if (!ModelState.IsValid)
            {
                //There was a validation error with the data
                return CurrentUmbracoPage();
            }

            //Continue processing the data...

            //Create new Blog Post object
            var blogPostToAdd = new BlogComment();

            //Set values from view model & grab the current node ID
            blogPostToAdd.UmbracoNodeId = UmbracoContext.PageId.Value;
            blogPostToAdd.Name          = model.Name;
            blogPostToAdd.Email         = model.Email;
            blogPostToAdd.Website       = model.Website;
            blogPostToAdd.Message       = model.Message;

            //Get the Umbraco db
            var db = ApplicationContext.DatabaseContext.Database;

            //Add the object to the DB
            db.Insert(blogPostToAdd);

            //All done - redirect to the page
            return RedirectToCurrentUmbracoPage();
        }
    }
}

Well that’s it apart from a Razor Partial View to loop over the IENumberable of Blog Comments so they can be displayed on the client side of the site.

Would love to hear your thoughts & ideas on this.

Thanks,
Warren 🙂

Why I think your doing it wrong: Umbraco AltTemplate & Data Views

Common sense warning

Before I start this post let me outline this is my opinion and you may or may not agree with it. However if you want to discuss it with me in the comments I will be more than happy to, but please respect each others opinions and views and don’t start an angry flame war.

OK enough of the common sense stuff lets get to it.

I personally think you are doing it wrong if you are using alternative templates in Version 6 of Umbraco to return JSON or XML for example.
So read on to find out why and the approach I think you should be using.

Continue reading “Why I think your doing it wrong: Umbraco AltTemplate & Data Views”

Highlight Errors in CodeMirror

Hello all,
With the release of Optimus for Umbraco that me & Tim Geyssens have built that allows you to create bundles and write Sass, Less, CoffeeScript & TypeScript files directly inside Umbraco.

We wanted a way to highlight any compiling errors with your code that you write, by highlighting the line number in the editor of the Umbraco back office.

The code editor inside Umbraco, uses the highly popular HTML & JavaScript code editor CodeMirror. My goal was to highlight the exact line number in the editor so we can visually highlight to the user where in their code that is the problem.

So I will take you through the small code snippet that was used to achieve this:

In the FileEditor.aspx page that we have I wrote the following JavaScript function

    function highlightLine(lineNumber) {

        //Line number is zero based index
        var actualLineNumber = lineNumber - 1;

        //Select editor loaded in the DOM
        var myEditor = $("#body_EditorSource .CodeMirror");

        //Write the item to the console window, for debugging
        console.log(myEditor);

        //Select the first item (zero index) just incase more than one found & get the CodeMirror JS object
        var codeMirrorEditor = myEditor[0].CodeMirror;

        //Write the item to the console window, for debugging
        console.log(myEditor[0].CodeMirror);

        //Set line CSS class to the line number & affecting the background of the line with the css class of line-error
        codeMirrorEditor.setLineClass(actualLineNumber, 'background', 'line-error');
    }

In addition to this I need a small chunk of CSS in order to style the error line in red for it to be easily noticed.

<style>
        .line-error {
            background: #FBC2C4 !important;
            color: #8a1f11 !important;
        }

</style>

The final thing that needs for this all to come together and work, is that when the save button is hit on our custom code editor page, that we check for any errors from the transformers such as Sass & CoffeeScript for example. Parse the line number and pass that to our Javascript function highlightLine().

        private bool SaveConfigFile(string filename, string contents)
        {
           //This gets the filename of the Sass, Less, CoffeeScript or TypeScript file
            var path = Request.QueryString["path"] + filename;

            //This gets the full path to the file (Server MapPath'd)
            var fullPath = Server.MapPath(Request.QueryString["path"]) + filename;

            //Open up the file on disk
            using (var text = File.CreateText(fullPath))
            {
                //Save the file contents
                text.Write(contents);

                //Close the text reader, as we are done with it
                text.Close();

                //Check the translation for errors
                var errors = transCore.ValidateTranslation(path);

                //If no errors then...
                if (errors == null || !errors.Any())
                {
                    //Save the translation to disk
                    transCore.SaveTranslation(path);
                    return true;
                }
                else
                {
                    //Get the first exception message out of the collection
                    var exceptionMessage = errors.First().Message;

                    //Set the panel on the page - it's an error type & show the exception message
                    Feedback.type = Feedback.feedbacktype.error;
                    Feedback.Text = exceptionMessage;
                    Feedback.Visible = true;

                    //Get Line number from the exception message - presumes messages always ends with
                    //Line number: 3
                    var lineNumber = exceptionMessage.Split(' ').Last().Replace("\r", "").Replace("\n", "");
                    int.TryParse(lineNumber, out ErrorLineNumber);

                    return false;
                }
            }

So that’s all the parts of our code that enables us to highlight the line number in the CodeMirror editor.

There is plenty more that could be done with the editor, as there are many options available to us when we have the CodeMirror object selected in JavaScript. So let your imagination go wild and start playing around with the code editor inside Umbraco.

Any questions please leave them in the comments.

Thanks,
Warren 🙂

Transformers! Robots in Disguise

Transformers! Robots in Disguise

Transformers, robots in disguise! Was part of the classic 80’s cartoon Transformers theme tune and has been inspiration for Tim Geyssens and mine latest Umbraco package, aptly named Optimus. After Optimus Prime, the lead transformers of the Autobots.

So what is Optimus and why did you call it that? Well read on to find out!
Continue reading “Transformers! Robots in Disguise”