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

I attended the Umbraco Examine Course & you won’t believe what happened next

If you were at this year annual Umbraco developer conference CodeGarden, you may have seen a lightning talk with a click-bait title in the scheduled and then it magically disappeared like one of Damiaan’s magic tricks

So you may be wondering what the hell happened to it?!

I will be honest & frank with you, during CodeGarden I was having a crap time on the inside whilst I battled dealing with the large crowds with depression & anxiety and was using drink as a coping mechanism to try suppress my emotions.

I woke up on day two of CodeGarden in a mess physically with a crap hangover and mentally with the exhaustion of feelings. After a chat with my lovely bosses at the HQ, who always ensure we are looked after. It was decided it was best I jump on the first plane and get home as soon as possible for rest, recovery & to sort myself out. Unfortunately I have been in a similar place before and I did not want the same state of  psychosis and being back in hospital. 

So I wanted to share this story, to try and help reduce the stigma and help others who may be experiencing similar problems to let them know they are not alone and that it’s super important to look after yourself and talk to someone, as Ravi mentions in his lightning talk.

OK i’ll wrap up that short summary there…

Enough of that, just show me the talk; Warren!

Without further a do, I present to you the talk that I didn’t give from my kitchen, so if my talk is a terrible mess I’ve decided I am going to start doing a cooking YouTube channel ­čśŤ

Slides

Are you one of those people who like to refer to slides, if so I got your back and you can download and view them here.

Questions?

Watched or read through the slides and have some questions, then leave a comment on this post or send me a message on twitter @warrenbuckley

Why did the Umbraco pet project uHangout die?

Why did the Umbraco pet project uHangout die?

Hello I am back!
It’s been a while since I wrote something & I think blogging in general is slowly dying out, so I am gonna try & make a more conscious effort to blog quick snippets or things I learn as I enjoyed doing this in the past, so hopefully you can see more in the future.

So where have I been for the last 18 months or so… well I started working for Umbraco HQ helping to build great software be it the core CMS product, the Cloud platform or the addon products such as Forms & Deploy (TAFKA Courier), with a very talented & passionate team┬áthat I am so lucky to work alongside and learn so much from.

Previous to working at Umbraco HQ, I would actively work on pet projects be it small packages coded in a few evenings or lunchtimes to larger projects such as uHangout.

What is uHangout?

uHangout was a project I decided to create one lunchtime around September of 2013, I fired up a Google Hangout On Air session and invited someone in the Umbraco community to come talk about their┬áUmbraco project & why it was so neat, where we streamed it live on YouTube. From there the idea just grew into a community show & tell. This was mostly involving new packages being built, as at the time & still today the Umbraco community site our.umbraco.org has a rapidly increasing amount of packages and it’s hard to keep up with whats new.

Why did the project die?

So you may be wondering why the project came to an abrupt end? With the last episode being aired last August. Well this happened due to a number of different things:

Continue reading “Why did the Umbraco pet project uHangout die?”

Time to say goodbye…for now

Hello all
I have not written a blog post for a little while but I thought I’ll cobble this together on the commute into London.

It’s time to say goodbye to uHangout for this year, but don’t worry it’s not going away permanently it’s that uHangout & me will be taking a little well deserved break.

This is mainly because I am stepping away from the lovely Umbraco Gold Partner gang that is The CogWorks and in doing so I am taking a little ‘me’ time between now; well tomorrow & when my new role starts in January.

So it made sense for uHangout to take a break so that I can recharge my batteries, pump up that enthusiasm and ensure the uHangout pet project gets a bit more love and that the annoying tech issues become less frequent than they currently are!

So in the new year I am so happy to announce that I will be returning to work with the awesome guys & gals over at Umbraco to help continuing to deliver a great CMS that we all love to use.

I am sad to be leaving my CogWorks family and has been loads of fun, so if you are on the lookout for a new Umbraco role and want to work with a great team building some neat websites then make sure to get in touch with Anthony Dang or Adam Shallcross

With me joining Umbraco the uHangout project will not turn into a corporate marketing show; not that Umbraco is even ‘corporate’ in that sense that of the way. This will still a pet project of mine which I will still be talking with the fantastic members of the Umbraco community about their packages & latest contribution in this show & tell format.

So with me taking a bit of hiatus I will be spending some good family time and going completely dark, so don’t expect me to reply to tweets and emails so that I can fully disconnect from our busy world that we all work in to become a fully rested & recharged Warren ready to deliver great stuff in the new year!

So don’t panic I have not run away or got hit by a bus!

With that all said & done it’s time to say goodbye….for now.
Warren x

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”

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 ­čÖé