Simple JQuery Copyright Year script

angularjs logo featured image

How many websites do you see that have a copyright line with last year in it?! It’s just a sign of a lazy web developer who can’t be bothered either to update it every year, or (much better) add a simple bit of JQuery to automatically display the current year in the copyright line!

Here’s a code snippet that I use on all my websites to do just that!

In the markup add your copyright statement like this:

&copy; My Company <span id="year"></span>. All rights reserved.

And then add this script to your page (after your JQuery reference):

<script>
  $(function(){
    var theYear = new Date.getFullYear();
    $(“#year”).html(theYear);
  });
</script>

The end result (assuming you’re reading this in 2015…) will look like this:

© My Company 2015. All rights reserved.

Posted in Code samples, JQuery Tagged with: ,

Intercepting Umbraco Events

umbraco-logo

Umbraco allows you to extend the core functionality by exposing a number of back-office events through its API. It’s actually quite easy to do intercept and extend these events – the hardest part is knowing which event you want to intercept! There is more information about Umbraco Events, including a full list of the events you can intercept here.

In a recent project I worked on, I intercepted a number of Umbraco events to do the following things:

  • add extra information into the Examine search index for blocks of content that would otherwise not have been present in the search index
  • create a custom URL containing the year/month/title when a blog post is published
  • create new content items when a recurring event/meetup is set up

To intercept an event and extend it by adding your own logic, just follow these 3 steps.

Step 1: create a new class that inherits from ApplicationEventHandler:

using Umbraco.Core;

public class MyUmbracoEventInterceptor : ApplicationEventHandler
{
}

Step 2: add a parameterless constructor to your class and add the Umbraco event you want to intercept:

public MyUmbracoEventInterceptor()
{
  ContentService.Saving += Saving;
}

Step 3: create your extension method (in the above example it would be the “Saving” method):

private static void Saving(IContentService sender, SaveEventArgs<IContent> args)
{
  Your extra code goes here…
}

The arguments for your extension method will change depending on the Umbraco event you are extending. Intellisense should hopefully tell you the arguments you need to include. Put altogether it looks something like this:

using Umbraco.Core;

public class MyUmbracoEventInterceptor : ApplicationEventHandler
{
  public MyUmbracoEventInterceptor()
  {
    ContentService.Saving += Saving;
  }

  private static void Saving(IContentService sender, SaveEventArgs<IContent> args)
  {
    Your extra code goes here…
  }
}

So that’s it – pretty simple really! If you have any questions or want me to cover any other Umbraco areas, please add a comment below.

Posted in Code, Umbraco Tagged with: ,

Formatting Dates in AngularJS

angularjs logo featured image

Here’s a cheeky little trick for you – if you have a date property that you want to format in your view, you can use this simple bit of AngularJS markup to do just that:

{{MyObject.MyDate | date:"dd/MM/yyyy HH:mm"}}

This takes a pretty nasty-looking Json style date which looks like this:

2015-02-04T13:30:10Z

and turns it into a beautifully crafted date which looks like this:

04/02/2015 13:30

You’re welcome!

Posted in AngularJS, Code Tagged with: ,

Using Custom Routes in Umbraco

umbraco-logo

So if you come from a .Net MVC background and you’re building an Umbraco project, one of the first things you’re going to want to do is add your own custom routes. You create your custom controller and add your custom route into the RouteConfig.cs file and hit F5. Then you get an error saying that the route you just added can’t be found and you start to doubt everything you thought you knew (again).

This is because Umbraco hijacks the routing process of your once-familiar MVC project and puts its own routing engine in place! To add custom routing back in to your Umbraco project you have to do a bit of tinkering under the bonnet (like the bonnet of a car, not a bonnet you wear on your head).

I recently used my own controller and custom route on a project when I wanted to make AJAX calls from the site back to the server. I followed the instructions in the Umbraco documentation which got me 95% of the way, but there were a couple of gotchas. So here’s how you do it, gotchas included!

Step 1 – Set up your controller. This is the bit you already know and love – no change here. For my project the actions I added to my controller were JsonResult actions, as I was using Ajax, but you can use any controller actions. Here’s the basic code from my controller:

public class AjaxController : Controller
  {
    [HttpPost]
    public JsonResult OpinionPollPost(OpinionPollModel model)
    {
      RegisterVote(model, Response);

      var modelToReturn = GeneratePoll(model.Id, Request, model.Token);

      return Json(modelToReturn);
    }
  }

Step 2. Add the controller path to umbracoReservedPaths appSettings key in your web.config file. Any path added to this list will be ignored by Umbraco’s routing engine. My controller was called AjaxController, so I added “~/ajax/” to the umbracoReservedPaths list:

<add key="umbracoReservedPaths" value="~/umbraco,~/install/,~/ajax/" />

Step 3. Change your global.asax.cs to inherit from UmbracoApplication. Open up your global.asax.cs file and change this line:

public class MvcApplication : System.Web.HttpApplication

to this:

public class MvcApplication : UmbracoApplication

Step 4. Change your global.asax to inherit from your application. This was the big gotcha that caught me out and I had to do quite a bit of searching to find it! Open up your Global.asax file (right click on it and “View Markup”) and change this line:

<%@ Application Codebehind="Global.asax.cs" Inherits="Umbraco.Web.UmbracoApplication" Language="C#" %>

to this:

<%@ Application Codebehind="Global.asax.cs" Inherits="MyProject.MvcApplication" Language="C#" %>

where “MyProject” in this example is the base namespace of your project.

Step 5. Remove the default custom route from RouteConfig.cs – this is another gotcha! If you don’t remove this route, MVC will try and route every request and your website will show en empty page which may be a nice clean design, but not very functional!

Step 6. Register your custom route in the RegisterRoutes method of your RouteConfig.cs. You have to do this for each route you want use:

routes.MapRoute(
  name: "Ajax",
  url: "Ajax/OpinionPollPost",
  defaults: new { controller = "Ajax", action = "OpinionPollPost" }
);

Step 7. Finally you need to add an OnApplicationStarted override method to global.asax.cs. This will allow you to add your application to read the RegisterRoutes method in your RouteConfig.cs file when it starts, and add the custom route you just set up into your application:

protected override void OnApplicationStarted(object sender, EventArgs e)
  {
    base.OnApplicationStarted(sender, e);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
  }

Now you just need to build and run your application, and you will be able to access your custom routes and controllers and make even more awesome Umbraco websites!

Posted in Code, MVC, Umbraco Tagged with: , ,

How to create a login for a SQL Azure database

microsoft azure logo

I tend to use SQL Azure databases to power most of the Umbraco websites I build, and for each database I set up a new user account (security is king etc!).

However on SQL Azure you have to script them because it doesn’t let you set up user accounts through the Management Studio interface. This means that every time I set up a new database I always have to google how to script the user logins, as I always forget!

So here’s how to do it so that my future self can just come back here and read it in the comfort of my own blog…

Step 1 – connect to your SQL Azure DB Server either through SQL Management Studio or through the Azure Management portal.

Step 2 – connect to the Master database and execute this query:

CREATE LOGIN ['yourLoginName'] WITH password=['yourReallyStrongPassword'];

Step 3 – connect to your new database that you want to set up the login for, and execute this query:

CREATE USER [yourLoginName] FROM LOGIN ['yourLoginName'];

Step 4 – staying connected to your new database, execute this stored procedure:

EXEC sp_addrolemember 'db_owner', 'yourLoginName';

(you can add any role you want in this step, I’m just using db_owner for illustration…)

And that’s it – so simple that you will probably forget it the next time you want to create a user login for your SQL Azure database! 🙂

Posted in Code, SQL Azure Tagged with: ,

About Maff

Maff Rigby

I'm a certified .Net, Umbraco and AngularJS freelance developer with over 15 years experience in the IT industry. As well as writing code I love to teach; I run a number of workshops and 1-1 coaching sessions on Angular JS and Umbraco, and share what I know and learn here!

I’m social (ish)

Connect with me on LinkedIn, follow me on Twitter, or fail to find me on Facebook.