Umbraco V8 – Bye bye ApplicationEventHandler, Hello Umbraco Components!

Hello all,
OK I wanted to get the ball rolling on trying to get some bits on Umbraco V8 out into the wild and for the tinkerers, hackers and early adopters to play & experiment.

So here is something NEW in Umbraco V8 that you most likely will be using a lot. If you ever used one of Umbraco Services event handlers such as ContentService.Saved or similar, then you would most likely set this up using a class that inherits ApplicationEventHandler.

Show me an example!

I will show a brief example of the old approach using ApplicationEventHandler and then doing the exact same with a shiny new Umbraco Component approach.

Old approach – ApplicationEventHandler

using Umbraco.Core;
using Umbraco.Core.Events;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Services;

namespace MyProject.EventHandlers
{
    public class RegisterEvents : ApplicationEventHandler
    {
        protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
        {
            //Listen for when content is being saved
            ContentService.Saving += ContentService_Saving;     
        }
        
        /// <summary>
        /// Listen for when content is being saved, check if it is a new item and fill in some
        /// default data.
        /// </summary>
        private void ContentService_Saving(IContentService sender, SaveEventArgs e)
        {                
            foreach (var content in e.SavedEntities
                //Check if the content item type has a specific alias
                .Where(c => c.Alias.InvariantEquals("MyContentType"))
                //Check if it is a new item
                .Where(c => c.IsNewEntity()))
            {
                //check if the item has a property called 'richText'
                if (content.HasProperty("richText"))
                {
                    //get the rich text value
                    var val = c.GetValue("richText");
                    
                    //if there is a rich text value, set a default value in a 
                    // field called 'excerpt' that is the first
                    // 200 characters of the rich text value
                    c.SetValue("excerpt", val == null
                        ? string.Empty 
                        : string.Join("", val.StripHtml().StripNewLines().Take(200)));
                }
            }
        }
    }
}

New approach – Umbraco Components

using System.Linq;
using Umbraco.Core;
using Umbraco.Core.Components;
using Umbraco.Core.Events;
using Umbraco.Core.Models;
using Umbraco.Core.Services;
using Umbraco.Core.Services.Implement;

namespace MyProject.Components
{
    /// <summary>
    /// All IUmbracoUserComponents run after all IUmbracoCoreComponent have run
    /// This way we can ensure Umbraco is all setup and stuff is available for us to use
    /// </summary>
    public class ExampleComponent : UmbracoComponentBase, IUmbracoUserComponent
    {
        public void Initialize()
        {
            ContentService.Saving += ContentService_Saving;
        }

        /// <summary>
        /// Listen for when content is being saved, check if it is a 
        /// new item and fill in some default data.
        /// </summary>
        private void ContentService_Saving(IContentService sender, SaveEventArgs e)
        {
            foreach (var content in e.SavedEntities
                //Check if the content item type has a specific alias
                .Where(c => c.ContentType.Alias.InvariantEquals("MyContentType"))
                //Check if it is a new item
                .Where(c => c.IsNewEntity()))
            {
                //check if the item has a property called 'richText'
                if (content.HasProperty("richText"))
                {
                    //get the rich text value
                    var val = content.GetValue("richText");

                    //if there is a rich text value, set a default value in a 
                    // field called 'excerpt' that is the first
                    // 200 characters of the rich text value
                    content.SetValue("excerpt", val == null
                        ? string.Empty
                        : string.Join("", val.StripHtml().StripNewLines().Take(200)));
                }
            }
        }
    }
}

You can see very little has changed to the code, where we inherit from UmbracoComponentBase and IUmbracoUserComponentinstead instead of ApplicationEventHandler.

Why has it changed?

I will try my best to explain this, after I chatted with the brains behind it aka Stephan. This is mostly to help with the future and to avoid some confusion.

because app event handler means… “handles events” and although it’s true, it’s misleading. a component is a part of the whole app, so you add components to “compose” your ideal application – your component can handle events if they want – it’s just a more general notion

What benefits does it have over the old approach?

Again after a quick chat with Stephan on trying to get to know the in’s & out’s of how this works.

For ex when you wanted to change how things where composed (register a new finder etc) you would have to remember to do it in the proper “event” – and people were always confused – now there’s the Composemethod explicitly for this usage – same for Initialize, more explicit + manages dependencies & injection

Also components can depend on each other and this ensures they run one after another, whereas ApplicationEventHandlers were in random order and are easy to enable/disable components, which could not be done with app handlers.

oh and components also terminate meaning they are notified when Umbraco stops

So an example that Stephan explained to me could be

so you create a component, and in Compose you tell Umbraco that it should use MyCache as a content cache. In Initialize you load your cache from wherever you want. In Terminate you flush changes to disk.

Further Examples

Here is an example of a component registering my own custom LastChanceFinder

using Umbraco.Core.Components;

namespace MyProject.Components
{
    /// <summary>
    /// All IUmbracoUserComponents run after all IUmbracoCoreComponent have run
    /// This way we can ensure Umbraco is all setup and stuff is available for us to use
    /// </summary>
    public class MyLastChanceFinderComponent : UmbracoComponentBase, IUmbracoUserComponent
    {
        public override void Compose(Composition composition)
        {
            base.Compose(composition);
            composition.SetContentLastChanceFinder();
        }
    }
}

So that’s it for now and I will share more insights into Umbraco V8 when I can or that I know that code for a piece of functionality is unlikely to change after checking with the brains of the project aka Stephan or Shannon 🙂

Thanks again Stephan for the 101 questions I have had on this!

Until next time, happy hacking & exploring !

Advertisements

IIS Express for VS Code

So time for another blog post, this time for something new (well kinda, it’s been out a little while)

Today I am releasing version 1.0.0 of IIS Express for Visual Studio Code editor, after having smaller releases over the last year or so. It’s time to give it a bit more polish & love and to give the release a 1.0.0 tag.

What is it?

This extension gives you the power to run a folder open in Visual Studio Code as a website using IIS Express. Allowing websites to be quickly and easily run without having to remember the command line query to run in order to have a folder run as a website.

Continue reading “IIS Express for VS Code”

How to use Visual Studio Android Emulator on VMWare Fusion

Hello
I thought I would share a quick blog post for others who may have recently downloaded Visual Studio 2015 this week who use a Mac as their main machine & VMWare Fusion to run a copy of Windows on it.

So after downloading the new Visual Studio 2015 release, I am quite keen to do some mobile development so I was keen to look at the Visual Studio Android Emulator, but upon opening the application & starting one of the emulators that are already come pre installed, I was greeted with an error.

The error was as follows:

Visual Studio Android Emulator

So the first thing I done was hit the lovely smiley face in the main window, to give the Visual Studio team feedback on this and within 3 to 4 hours I received a reply on how to resolve this.

So what’s the solution?

The following solution is not a supported & official response from the Visual Studio Team but does allow you to use it inside of VMWare Fusion.

He is the response from Visual Studio team:

Hi Warren
Thanks for using our emulator. Our emulator is not officially supported in a nested virtualization environment (like when running under VMWare Fusion).

You can try to enable it if you do not need OpenGL support, but running in this mode is unsupported as some features are not functional in this mode.

In VMWare Fusion, under General settings, for the OS Type, you’ll need to change it from Windows 8.1 to “Hyper-V (unsupported)”. I would also suggest at least 2 processors and 4gb of ram (6gb is better depending on the Android VMs you want to run)

In Windows, you’ll need to edit the c:\program files (x86)\Microsoft XDE\10.0.10240.0\skus\android\xdesku.xml file and remove the following line from the file: GuestDisplayProvider=”VsEmulator.OpenGLGuestDisplay”

Well I have done that & managed to get the emulator to spin up and work. Hopefully this will change in the future and that this modification will no longer be needed, we will just have to wait & see.

Thank You Umbraco Community

Hello,
So last week was the annual Umbraco developer conference; CodeGarden 15 that is hosted in the homeland of the Umbraco project Copenhagen.

This was the first year I was unable to attend the conference to catch up with the Umbraco community, which I like to call my second family, due to a recent new arrival to my family of my wonderful little daughter!

So with the first CodeGarden that I have missed since I started attending back in 2007 the one & only time it left Copenhagen & came to London that year & was a little gutted to not be able to come this year

If you was at this years CodeGarden you would have seen in the keynote or watched it back online, that I had a lovely surprise from the man himself, Niels Hartvig aka Chief Unicorn turning up unannounced at my front door and was presented with t fantastic LifeTime Umbraco MVP award, which is very touching & nice to hear that my contributions & efforts are noticed.

Rather than me drone on too much I thought I would create a short video instead, but once again a BIG, BIG Thank You Umbraco community for the LifeTime award & for giving me such a lovely reception. It did give me a nice warm happy feeling & a slight happy tear to the eye on Monday morning when I watched it back.

But before I go & wrap up, I want to say congratulations to my fellow MVPs at this years Umbraco CodeGarden that include the lovely bunch of people who continually work hard to make the community a friendlier & happier place, so again congrats to the following:

  • Lee Kelleher – Umbrella Inc
  • Matt Brailsford – The Outfield
  • Jeavon Leopold – Crumpled Dog
  • Jan Skovgaard
  • Jeroen Breuer

Umbraco 2015-2016 MVPS
The Umbraco 2015 MVPs. Photo: Doug Robar

Thanks again Niels for a fantastic surprise!

Securing Umbraco Web APIs using JSON Web Tokens

Hello all,
First off a very happy new year to you all. I hope you had a good time off over the festive period and relaxed.

Over this festive period in between our baby girl arriving during late night feeds and insomnia kicking in, I managed to find a little time to polish off my new pet project for the wonderful Umbraco CMS. So I herby introduce you to UmbracoAuthTokens!

What is Umbraco Auth Tokens?

Umbraco Auth Tokens is a project that I have built that allows you to secure Umbraco WebAPI Controllers using a token based authentication using JSON Web Tokens aka JWT; pronounced jot. This is ideal for securing WebAPIs that require using a backoffice Umbraco user.

For example you may want to securely from a third party client be it a mobile application or similar create a new page or any other action that a backofficer Umbraco user may do.

What are JWTs?

They are an auth token that allows you to send a piece of JSON encoded as a token and are the more modern approach to deal with auth in applications especially as we build applications across different devices. The videos below will do a lot better trying to explain it than I can do.

Continue reading “Securing Umbraco Web APIs using JSON Web Tokens”

My Development Setup. What’s yours?

Hello all,
It’s a Sunday evening and I am sipping an ice cold G&T now that my DIY bits are done for the weekend.

I saw a tweet from my good friend & Aussie Peter Gregory today, saying:

I replied to Pete saying I have never had any issues and that I would write about my experiences, hence this post.

Pete and other people have asked me before about my setup of my machine I use for coding and I want to discuss about my particular setup and start a wider discussion with the community about their setups.

Continue reading “My Development Setup. What’s yours?”

Quick Snippet: Toggle Tree Navigation in Umbraco Backoffice using JavaScript

Hello,
Here is a very quick blog post on how to toggle the tree navigation in the Umbraco 7 (aka Belle) back office using JavaScript with some AngularJS services that the Umbraco core team has given to us to use.

First of all you may be wondering why you would want to toggle the display of the tree navigation, considering that this is the main & primary navigation when using the Umbraco backoffice, however on a project I am doing at work a new property editor that is being developed requires more screen real estate and toggling the tree navigation allows the content editor to see & use this property editor a lot easier, as it involves plotting objects on a canvas. So as much space as possible is useful in this case.

So enough of the why and I will get straight down to the very simple JavaScript code snippet that allows us to do this:

angular.module('umbraco').controller('demo.toggler', function($scope, appState, eventsService) {
  //Create an Angular JS controller and inject Umbraco services appState & eventsService

  //Button Click - ToggleUmbracoNavigation
  $scope.toggleUmbracoNavigation = function() {

    //Get the current state of showNavigation
    var currentNavigationState = appState.getGlobalState('showNavigation');

    //console.log("currentNavigationState", currentNavigationState);
    //console.log("Inverse of currentNavigationState", !currentNavigationState);

    //Toggle the tree visibility
    appState.setGlobalState("showNavigation", !currentNavigationState);
  }

  //The eventService allows us to easily listen for any events that the Umbraco applciation fires
  //Let's listen for globalState changes...
  eventsService.on("appState.globalState.changed", function (e, args) {
    //console.log("appState.globalState.changed (args)", args);

    if (args.key === "showNavigation") {
      //console.log("showNavigation value", args.key, args.value);

      //If false (So hiding navigation)
      if(!args.value) {
        //Set css left position to 80px (width of appBar)
        document.getElementById("contentwrapper").style.left = "80px";
      }
      else {
        //Remove the CSS we set so default CSS of Umbraco kicks in
        document.getElementById("contentwrapper").style.left = "";
      }
    }
  });

});

Hopefully the JavaScript is commented enough and is easy to follow, but the ensence of this is that we have a button or anchor link in our view with the Angular directive of ng-click applied to it calling out method, i.e ng-click=”toggleUmbracoNavigation()” this toggles the value stored in Umbraco’s globabl settings in this case these values & settings are stored in an AngularJS service called appState, that allows us to get & set values stored in here. I recommend you look at the source code on GitHub to see what other values are stored in appState for you to use in your customisations to the Umbraco back office.

I would be interested to hear what other people think of this and should this tree toggle become part of the core by doing a Pull Request and if was to become part of the main UI, where should the button go or by double clicking the grey area with the application/section icons toggle this action?

Well let me know by leaving your thoughts in the comments.

Thanks,
Warren 🙂