Luke Warren Dev
Software Development Tips and Stories When I feel Like It

C# 6: Shorten all the things with expression-bodies

Let's see how you can use expression-bodies

C# 6: Shorten all the things with expression-bodies

Let's see how you can use expression-bodies to make your code a lot shorter and more readable.

If you are still writing code like this:

public string FullName 
{ 
    get 
    { 
        return String.Format("{0} {1}", First, Last); 
    } 
}

You really should read my string interpolation post , and write it like this:

public string FullName 
    {
         get 
         { 
               return $"{First} {Last}"; 
         }
     }

The thing is, it gets even better with expression-bodies:

public string FullName => $"{First} {Last}";

That is all.


Click here to comment

C# 6: Get rid of String.Format with Interpolated Strings

So I don't know about anyone else but I am loving Visual Studio 2015 and C# 6.

C# 6: Get rid of String.Format with Interpolated Strings

So I don't know about anyone else but I am loving Visual Studio 2015 and C# 6.

My current favourite feature is the string interpolation. Yes, yes, I know that PHP (and others) have had this for ages but here it is...

Often we would have to do stuff like this:

string first = "Luke"; 

string last = "Warren"; 

string fullName = String.Format("{0} {1}", first, last); 

What a pain!

Now, with string interpolation, we can shorten that last statement to:

string fullName = $"{first} {last}";

Simple but very handy! Just remember the dollar sign before the string. VS will show some nice syntax highlighting to help you out too.

More info: https://msdn.microsoft.com/en-us/library/dn961160.aspx


Click here to comment

Moving Blog from Wordpress to Umbraco

I have finally got around to porting my blog to Umbraco!

Moving Blog from Wordpress to Umbraco

I know I have said in the past that WordPress was probably the way to go for blogging, but in my recent whirlwind romance with Umbraco, I decided to port my blog over.

The main reason was based on the fact that I am much more comfortable in the ASP.NET based Umbraco and hope to make regular feature additions as the blog evolves. Although that is possible with Wordpress, I'd rather stick to my strengths.

In an effort to make my life easier I am also "outsourcing" some other sections of the site, such as the about and contact me sections. This means that the old and rather half-arsed vanilla MVC site that used to occupy this domain has been put down (in a humane and gentle fashion of course).

This site is fully geared towards blogging. The topics will be mainly programming related as usual but you might hear the occasional rambling/rant about the latest goings on in rugby (despite my best effort not to).

All you need to know about me is available via the links in the header of every page. The best place to find out more about me professionally will be via my LinkedIn page. To get hold of me, send me a message via LinkedIn, email or Twitter.

Over the course of the next few weeks I will be moving over my old blog content and killing my wordpress.com site. I will make a post notifying everyone when that takes place although I am sure neither you nor I will miss it.

For those wondering you can find my old blog at lukejkw.wordpress.com

Thanks for reading


Click here to comment

Web UI: Bootstrap is not the only UI Framework!

A Lot of people have been caught up in the Bootstrap hype. It has got to the point where nearly every website/theme was built using Bootstrap.

Web UI: Bootstrap is not the only UI Framework!

A Lot of people have been caught up in the Bootstrap hype. It has got to the point where nearly every website/theme was built using Bootstrap. Now that is all well and good and I use bootstrap myself on many projects but it is not the only UI framework out there. It is scary how many people think that it is.

This blog post serves as an archive of sorts to showcase my favourite web UI frameworks.

Semantic UI

Drawing

Semantic UI is an incredible framework with many feature rich components. The docs are great and the design language makes it easy to theme to your specific needs.

You denote semantic elements with a fluid and "semantic" class structure which make it really easy to learn too.

Materialize

Drawing

Materialize is an awesome little framework based off of Google's Material design.

It is not as feature rich as Semantic or Bootstrap but is a pleasure to use. It is particularly useful for building apps that need to look and feel like native Android apps.

Bootstrap

Drawing

Bootstrap, as previously mentioned, is obviously the most popular out there. If you are working in the web space you need to know how to use bootstrap. The great news is that their docs are great and when you get stuck there are lots of people to help you out on Stack Overflow and other

Have more that should be listed here?

 

Just list it in the comments and I will add it.


Click here to comment

My First Nuget Package: Rework

I am so tired of rewriting the same code over and over and over again

My First Nuget Package: Rework

So I have been wanting to do this for a while but finally got around to creating a reusable C# library.  

The library contains all the sort of helper functions that you tend to re-write, redo or "Rework". It is currently quite light but is fully unit tested and highly reliable. I am using AppVeyor for Continuous Integration and Deployment to Nuget.

I am hoping to do a video at some point on just how easy it is to setup a project in AppVeyor. For more info on the project, it's features and how to use it. Simple head over to Github.

If you like the library and want to add to it, feel free to contact me or put in a pull request.


Click here to comment

How to configure the Hangfire Dashboard in an ASP.NET App

Hangfire is an awesome little library to aid in the scheduling of recurring or deferred "jobs".

How to configure the Hangfire Dashboard in an ASP.NET App

Hangfire is an awesome little library to aid in the scheduling of recurring or deferred "jobs".

It comes with a handy dashboard that, when configured, allows you to easily monitor and take actions on your jobs.

The problem I have come across on StackOverflow and other sites is that many people battle to get the dashboard setup, so I thought that I would document here how it is done.

First we need to create an authorization filter

This will be used later to make sure that only authenticated and authorised users can access the dashboard.

This means making sure that users are both logged in and in the admin role before they can view the Hangfire dashboard.

using MyApp.Common;
using Hangfire.Dashboard;
using Microsoft.Owin;
using System.Collections.Generic;

namespace MyApp.Dashboard.Schedules
{
   public class HangfireAuthorizationFilter : IAuthorizationFilter
   {
          public HangfireAuthorizationFilter()
          {
          }

          public bool Authorize(IDictionary<string, object> owinEnvironment)
          {
             // Only admin users can access the dashboard
             var user = new OwinContext(owinEnvironment).Authentication.User;
             return user.Identity.IsAuthenticated &amp;&amp; user.IsInRole(RoleKeys.Admin);
          }
      }
}

All you need to do really is implement the IAuthorizationFilter interface and you are away.

Next, we need to configure our app to use the Hangfire dashboard

I usually just create a static method that sets up the dashboard and adds whatever jobs I need run.

We are using the authorization filter created previously.

public static class ScheduleConfig
{
    public static void ConfigureSchedules(IAppBuilder app)
    {
        // Configure Dashboard
        GlobalConfiguration.Configuration.UseSqlServerStorage("DefaultConnection");
        // I like to use "/jobs" as my endpoint
        // but your could change that to whatever you like
        app.UseHangfireDashboard("/jobs", new DashboardOptions
        {
            AuthorizationFilters = new[] { new HangfireAuthorizationFilter() }
        });
        app.UseHangfireServer();

        // Add jobs
        //...
    }
}

All we need to do now is call our method from within Startup.cs

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        // Other startup config
        //...

        // Call our method to configure hangfire.
        ScheduleConfig.ConfigureSchedules(app);
    }
}

Now (once logged in as admin) you will be able to navigate to the dashboard via http://yourappdomain.com/jobs


Click here to comment

How to get all Content by Document Type in Umbraco

This is probably going to be my shortest post yet. After having messed around with Umbraco for the last few weeks I thought that I would share some code!

How to get all Content by Document Type in Umbraco

OK, straight to it

Please note that on large sites you probably want to cache the results of the method to avoid a performance hit.

public static IEnumerable<IPublishedContent> GetAllNodesByType(IPublishedContent home, string docTypeAlias)
    {
        var foundNodes = new List<IPublishedContent>();
        foreach (var content in home.Children)
        {
            if (content.DocumentTypeAlias == docTypeAlias)
                foundNodes.Add(content);

            // Check recursive
            if (content.Children.Count() > 0)
                foundNodes.AddRange(GetAllNodesByType(content, docTypeAlias));
        }
        return foundNodes;
    }

Click here to comment

Enabling Migrations for Entity Framework with your DBContext in a Different Project

OK, so code first migrations in EF is flipping awesome.

Enabling Migrations for Entity Framework with your DBContext in a Different Project

OK, so code first migrations in EF is flipping awesome. That being said, I find keeping my data access layer in the same project as my MVC website... not awesome. It makes code sharing impossible when you have a few different presentation layers as well as making your MVC project bloated and ugly

Typically, when building an MVC website my project structure looks like this:

typical_project_structure

 

You will notice that my EF DBContext (DebonairsContext) is in a different directory to my MVC folder (where my migrations are). This makes the simple enable-migrations command not work. To enable migrations for a solution of this structure, all you need is to use the following package manager command (the one shown is the one I used for the solution above):

 

enable-migrations -ContextProjectName Debonairs.Data -StartUpProjectName Debonairs.Dashboard -ContextTypeName Debonairs.Data.DebonairsContext -ProjectName Debonairs.Dashboard

Note - The above will only work for EF 6 and up. Over and out


Click here to comment

Scheduled Job Runner in an ASP.NET MVC App

simple apps do not need the feature bloat

Scheduled Job Runner in an ASP.NET MVC App

I have finally had the chance to build a few apps in vanilla ASP.NET MVC recently. While we still prefer DNN for many use cases, simple apps do not need the feature bloat you get when building on top of DNN. Sometimes in this vanilla context you find yourself missing things that you get for free in DNN.

Scheduled jobs

DNN provides an extremely easy and configurable way to run a task or "job" on a schedule. I needed something similar in an MVC app.

Turns out that it is not as hard as it seems when you break it down.

Find a job runner

First we needed something to actually handle running our recurring jobs. While you could write something yourself, that would be a waste of time considering it is a solved problem. I found a few nifty little libraries and decided that the best one to use would be Hangfire.

Hangfire allows you to easily run code on a schedule as well as monitor them via a dashboard (Hangfire has many many more features).

Discover our jobs

Now you could just use hangfire to run whatever code you want on a schedule off the bat but I wanted my implementation to require no code changes when a new job is needed to be run. You should just be able to write you code and have it run itself.

If I want to create a new job, it would just need to adhere to a contract that I defined. This simply meant creating a interface to act as my "contract"

My Interface:

```

public interface IScheduledJob {

string Frequency { get; }

void DoWork(); }

```

Now that I had a contract, I needed a way to discover all the classes that inherited  from my interface - ie all the "jobs" to register on app startup.

The following method is called in the Startup.Configure method and essentially just finds all the jobs and adds them to a recurring job schedule:

```

private void ConfigureSchedules(IAppBuilder app) { // Configure Dashboard GlobalConfiguration.Configuration.UseSqlServerStorage("DefaultConnection"); app.UseHangfireDashboard("/jobs", new DashboardOptions { AuthorizationFilters = new[] { new HangfireAuthorizationFilter() } }); app.UseHangfireServer();

// Get all types that implement the scheduler interface var jobs = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(s => s.GetTypes()) .Where(p => typeof(IScheduledJob).IsAssignableFrom(p) && !p.IsInterface); foreach (var jobType in jobs) { // Create instance of job IScheduledJob job = (IScheduledJob)Activator.CreateInstance(jobType); // Add job to schedule RecurringJob.AddOrUpdate(() => job.DoWork(), job.Frequency); } }

```

*Note, for more information on the dashboard see the Hangfire docs *

Create a job

OK, now we are cooking on gas. We just need to create a class that inherits from our interface and it will automatically be added to the schedule

An example job:

```

public class TestSchedule : IScheduledJob
{
    public string Frequency
    {
        get
        {
            return Cron.Minutely();
        }
    }

    public void DoWork()
    {
        Debug.WriteLine($"Test Job Ran: {DateTime.Now}");
    }
}

```

Note that we use Hangfire's built in Cron class to define the frequency of our job. These methods simple return a string.

Happy scheduled-jobbing!


Click here to comment