Latest Blog Posts

Personal targets and goals for 2016

Posted on Monday, 01 Feb 2016

Around this time last year I set out a list of goals and targets for myself in my Personal targets and goals for 2015 blog post which, with 2015 coming to a close, I reflected on last month in my Reflecting on 2015 post.

I feel formally setting yourself yearly goals is a great way to focus a set of specific, well thought out targets as opposed to spending the year moving from one subject to another with no real aim. So without further ado, here are my personal targets for 2016.

Goal 1: Speak at more conferences and meet-ups

Those of you that know me will know that when I start talking about programming and software development it's hard to shut me up. Software and web development is a subject I've been hugely passionate about from a young age and since starting this blog I've found sharing knowledge and documenting progress a great way to learn, memorise get involved in the community. This desire to talk about software has ultimately led me to start speaking at local meet-ups (including a lunchtime lightning talk at DDD South West) which I've really enjoyed. This year I'd like to continue to pursue this by speaking at larger events and meet-ups that are further afield. I already plan on submitting a few talks to this year's DDD South West event so we'll see if they get accepted.

Goal 2: Start an Exeter based .NET User Group

Living in a rather quiet and rural part of United Kingdom has its pros and cons and whilst Somerset is a great place to live, it suffers from a lack of meet-ups, specifically .NET ones - this is something I'm hoping to rectify by starting up a .NET user group.

Whilst I don't live in Exeter, it's the closest place where I feel there will be enough interest for setting up a .NET specific user group, so I'm currently in the process of looking for a location on the outskirts of the city to make it easier for commuters living in some of the nearby towns and cities.

Goal 3: Continue contributing to the .NET OSS ecosystem

One of last year's goals was to contribute to more opens source libraries, and whilst I felt I made good progress in achieving this goal I'm keen to continue working in this area. Not only do I want to continue to contribute to existing projects but I'm also keen to help others get involved in contributing to projects. It's a really rewarding activity that can really help develop your skill set as a software developer, with this in mind I've been thinking of a few satellite sites that will help people get started.

I'm also thinking about a few talks that talk about how someone can get started and the lessons you can learn by contributing to open source software.

In addition to the above, I'm also keen on contributing some of my own libraries to the .NET open source ecosystem. More often than not I've found myself creating a few classes to encapsulate certain behaviour or abstract a third party API, yet I've never turned it into its own library. This year I'm keen to take that extra step and turn it into a fully fledged library that can be downloaded via NuGet.

Bonus Goal: F#

Having been watching the F# community closely for some time now I'm really interested in what it has to offer, so this year I'm considering jumping in and committing myself to learning it and becoming proficient in it. I've got a few side projects I plan on working on that I feel will be a great place to use F# so we'll see how that goes.

Conclusion

This concludes my personal targets for 2016. Whilst it's not an exclusive list of what I will be focusing on, it's certainly a list that I wish to feel I've made some progress on by the end of the year. I shall see how it goes and keep people updated.

Angular 2 based Piano Note Training game side project

Posted on Sunday, 24 Jan 2016

With Angular 2 hitting beta I decided to take it for a test drive and give it a spin. As a huge, (and vocal!) fan of TypeScript I was keen to see what the Angular team had done with it and was really interested to see how the component based approach to Angular 2 made writing Angular applications different to that of the first Angular.

The application

After playing with Angular 2 for a few evenings and liking what I was seeing, I decided I wanted to build something more real life than a throw-away To-Do list. Don't get me wrong, there's nothing wrong with building to-do lists, they're a great way to get to grips with a framework, but nothing beats a real world project - with this in mind I decided to cross a side project off of my "apps to build" list and build a piano note trainer (source code available on GitHub).

As someone who is currently learning to play the piano and isn't a great sight reader, I've been keen to develop a note trainer that records your progress over time to give you indicators as to just how well your sight reading is progressing.

So far the application is going well and I'm extremely impressed with Angular 2's component based approach (heavily inspired by React if I'm not mistaken - but more on that in a moment). At the time of writing the application will generate random notes and draw them to the HTML 5 canvas whilst monitoring the user's input to see if they press the appropriate key on the CSS based piano (credit to Taufik Nurrohman for the paino, it looks great and has saved me a tonne of time!). If the user presses the correct key then the application informs them of the correct key press and then moves onto another key. If the user fails to press the correct key then the application lets the user know and waits for them to try again.

As I continue to build the piano note trainer I'm finding Angular 2 feel more and more intuitive, and whilst Angular 2 is structurally different to Angular 1, it still feels quite similar in many ways - bar no controllers and the dreaded scope object.

Angular 2's component based approach feels really nice, because we've learned over time that composition over inheritance the best way to build software

One of my main gripes with Angular 1 is the $scope object that was passed throughout an application and all too easily became a dumping ground of functions and data. This often inadvertently resulted in controllers taking on dependencies and quickly becoming tightly coupled to one another. Alternatively, the component based approach in Angular 2 naturally encourages encapsulated building blocks that contain the behaviour, HTML and CSS specific to the component and its role - the component can then expose a strict surface to its consuming components. This component based model follows the all too important "composition over inheritance" approach and allows you to build your application out of a bunch of easily testable units.

For instance, if you were to take the following screenshot of the application in its current state and break it down into the various components it looks like this:

Overall I've been really happy with Angular 2 so far and can't wait to see what tooling we start to see appear for it now that it's using TypeScript. I can't help but feel 2016 is going to be a big year for Angular.

The source code for the application is available on my GitHub profile and once finished I plan on submitting it to builtwithangular2.com. I'm hoping to have a live link once the application has reached a point that I'm happy with it to be used (I've still got to add sharp and flat notes which are causing some issues). In the mean time, feel free to give it a try via my GitHub profile.

An often overlooked reason why you should be on Stack Overflow

Posted on Saturday, 16 Jan 2016

Stack Overflow is a fantastic resource for developers of all ability. Gone are the days of having to trawl through blog posts, mailing lists or forums looking for solutions to issues.

These days the answer to the majority of a developer's day to day questions are just a few clicks away and often rank quite highly on Google for the search term(s) making them even easier to find. And whilst the majority of us developers use it more than a few times a day I'm always quietly surprised when I see a developer browsing Stack Overflow looking for, or at, a solution to a problem they're having yet they don't have an account (its fairly easy to spot when someone doesn't have an account from a distance as advertisements are visible between the answers).

When you ask someone who regularly uses Stack Overflow why they don't have an account the response you usually get is "I usually find the answer to my question so have no need to ask", or "I don't plan on answering questions" - which are all perfectly valid reasons. But as developers when have we ever had an issue, fixed it and then remembered the solution to the problem the next time we ran into the same issue - days, weeks, months of ever years later? I feel I would be fairly safe in saying we've all had problems or questions we've needed to look for on more than one occasion. This is where Stack Overflow can be a huge help (not to mention you'll be giving back to the community).

Leaving yourself upvote breadcrumbs to your technical issues

Next time you're on Stack Overflow I would encourage you to take a moment to create an account, even if you don't wish to fill out your profile - and the next time you find an answer to the problem you're facing - simply upvote it. It takes a split second to do but that split second can save you minutes or potentially hours over your programming career. I can't remember the number of times I've had an technical issue, gone searching for a solution on Stack Overflow and noticed I'd upvoted an answer a few months or years earlier.

Ultimately isn't that one of the things we enjoy doing as developers? Look for ways to make difficult things simple? Next time make it easier to see signals through the noise by upvoting the solutions to your problems.

How to setup Google Analytics and event tracking in your Angular application

Posted on Saturday, 09 Jan 2016

Google have made installing Google Analytics on a website extremely easy, simply copy and paste the tracking code provided into your website and you're done. But what happens when you want to set Google Analytics up on a single page application, say an Angular app? Having recently worked on an Angular application where I was tasked with registering page views and other various events within Google Analytics, I thought I'd take a moment to document how it was done and what I'd learned whilst doing it.

The problem with tracking code and single page applications

Traditionally, as your user navigates a normal website each page raises the Google Analytics pageview event (highlighted below).

<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-xxxxxxxx-x', 'auto');
  ga('send', 'pageview'); // Pageview event
</script>

However within the single page application space things are slightly different. Once your initial page has loaded, all subsequent pages or views are rendered within the application without the need for a page refresh or page load - this means no further pageview events will be raised. This would result in very inaccurate visitor data as Google Analytics would capture the initial page load, and then ignore the duration of their session.

The solution

Having had to deal with this very same issue (though I needed to raise multiple custom events when certain functionality was used) just recently the solution I eventually settled with was a simple one.

First of all we want to break our Analytics code into two, allowing our Google Analytics tracking code to be registered (notice how I've removed the pageview event - we will call this later).

This code should be added into your main index.html page or your base Layout/template page.

...
</head>
<body>
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-xxxxxxxx-x', 'auto');
 // Pageview event removed so we can call it once the view has loaded.
</script>
<div class="wrapper">
...

Next we're going to create a Google Analytics service (well call it GoogleAnalyticsService.js) that will be responsible for encapsulating our Analytics behaviour and used to manually raise our pageview event (and other events for that matter!) once the page has loaded. We can then inject our service into the appropriate Angular controllers and invoke the functions that will raise our Google Analytics events.

Take a moment to look at the Google Analytics page tracking documentation to see that we're passing in a page path (excluding the domain - ie: /checkout/) to uniquely identify the page within our Analytics reports.

(function (angular, window) {

    "use strict";

    var ngModule = angular.module("ourAppModule");

    ngModule.factory("googleAnalyticsService", [
        "$window", function ($window) {

            var ga = $window.ga;

            var _pageView = function(page) {			
                ga("send" "pageview", {
                    page: page
                });
            };

            return {
                pageView: _pageView,
            };
        }
    ]);

})(window.angular);

Now that we've created our GoogleAnalyticsService we can simply inject it into our application's controllers and invoke the pageView() function which in turn raises the Google Analytics pageview event.

Single page application version:

If your Angular application is a single page application then we can go one further and automatically call the pageview function once our view has loaded by adding the event to Angular's $viewContentLoaded event listener, like so:

(function (angular, window) {

    "use strict";

    var ngModule = angular.module("ourAppModule");

    ngModule.factory("googleAnalyticsService", [
        "$window", function ($window) {

            var ga = $window.ga; //Google Analytics

            var _pageView = function(page) {			
                ga("send" "pageview", {
                    page: page
                });
            };
            
            var _viewChangePageView = function(scope, page) {
                if (scope){
                    scope.$on('$viewContentLoaded', function(event) {
                        _pageView(page)
                    });
                }
            };

            return {
                pageView: _pageView,
                viewChangePageView: _viewChangePageView // used for SPA
            };
        }
    ]);

})(window.angular);

From here all we need to do is invoke our method from our application's controllers:

(function(angular, window) {

    'use strict';

    var app = angular.module('ourAppModule');
    app.controller('CheckoutController', ['$location', 'googleAnalyticsService', function($location, googleAnalyticsService) {
		...
		  
		googleAnalyticsService.pageView($location.path());
		  
		...
	}]);
	

})(window.angular);

Now when our user's visit our application we should start seeing our visitors browsing data flooding into our Google Analytics account. You can verify this by setting Google Analytics into debug mode and using your browser's console to see the events being raised. To do this simply replace the script source from analytics.js to analytics_debug.js.

<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics_debug.js','ga'); //debug mode

  ga('create', 'UA-xxxxxxxx-x', 'auto');
</script>

Once we've verified that our events are being raised then switch your analytics path back to analytics.js and you're good to go!

Reflecting on 2015

Posted on Saturday, 02 Jan 2016

With 2015 behind us and 2016 to look forward to it's that time of year again where I take a moment reflect on the events of last year and set myself some targets for the year ahead.

2015 has been a fantastic year for me for many reasons. Looking back at the targets I set myself for 2015 I'm happy with my progress, and whilst I've only met two of the four goals I set myself, I'm not going to be too hard on myself as I feel I've made up for it in other areas (which I'll go through in a moment) to make up for the two targets missed.

Last year's goals

Before setting my goals for 2016, let me take a moment to review last year's targets and achievements:

Goal #1: Get dangerous with Javascript

During 2015 I've spent a great deal of time working on my Javascript knowledge, this includes:

  • A Javascript based shooting game (written in TypeScript, but for those that are familiar with TypeScript will know that it's essentially Javascript decorated with types)
  • I've also spent a great deal of time really getting to grips with some of the fundamental design patterns commonly used in libraries such as the IIFE, Module Reveal pattern and so forth.
  • In addition to the above, I've also had the opportunity to write a lot of Javascript in my previous job, and have recently started working in a web services based role that involves a lot of Javascript via Angular.
  • Whilst learning Javascript I've also become a huge fan of TypeScript - so much so that I've given various workshops and talks at local user groups on the subject (more on this later though).

Whilst I wouldn't consider myself 'dangerous' with Javascript, I feel I've reached a level where I'm confident in my ability and comfortable writing it. This is a goal I will continue to pursue in 2016.

Goal #2: Contribute to more open source projects

Shortly after committing to this goal I stumbled upon an awesome C# assertion framework called Shoudly via a tweet by its owner Jake Ginnivan (@JakeGinnivan). Jake was very welcoming of first time contributors and helped a great deal with any Git related issues encountered as I stumbled my way through getting to grips with both the Shoudly codebase and contributing to it.

Today I still enjoy contributing to Shoudly and have been honoured to be added as a core contributor to the project. Jake's been paving the way with some truly inspiring work (including DNX support!) on the library and I look forward to continuing to contribute to it this year.

As a slight aside - if anyone is interested, as I was this time last year, in getting involved in contributing to an open source library then we're an extremely friendly bunch always looking for new contributors. I'd be happy to help you make your first contribution to Shouldly.

Goal #3: Increase the frequency of my blog posts

As many developers will know, blogging isn't easy. It takes time, effort and a log of research to write blog posts that are of any real value to people and whilst I've remaind consistent with my blogging throughout the year, the frequency of my posts isn't at a level that I am happy with. This is something I'm looking to rectify in 2016.

Bonus Goal: Achieve over 8,000 points on Stack Overflow

When writing about this goal last year, I felt aiming to achieve over 8,000 points on StackOverflow was a little ambitious - especially considering the scope of the other (what I considered to be more important) goals, so suffice to say I fell short of the 8,000 points mark.

Other noticable achievements in 2015

In addition to the above goals, 2015 was also an exciting year for me for the following reasons:

.NET Rocks Interview

When writing my 2015 goals, if you'd told me I'd be appearing on .NET Rocks by the end of the year I'd have told you to stop pulling my leg. But on December 10th my interview discussing Visual Studio shortcuts and productivity boosts was published. You can read more about the episode here.

I started talking regularly at local meet ups

Whilst I've been attending local meet ups for a little while now, I've also started talking at them too. Originally it started with a TypeScript talk at a local gathering, then moved to the same talk but in a lighting talk format at DDD South West, to a TypeScript workshop and a further talk on JavaScripts IFFE pattern. This is certainly something I wish to continue doing in 2016.

Overall I've been very satisfied with 2015; the highlight(s) of the year have got to go to being made a core contributor to Shoudly, alongside being featured on .NET Rocks. I hope everyone else has had a great year and I wish everyone the best for 2016!

Stay tuned for my goals for 2016!

A deeper look at C# 6's nameof expression

Posted on Tuesday, 29 Dec 2015

Like many developers I'm somewhat reluctant to use string literals or magic strings to reference variables, types or members due to the increased chances of introducing bugs into a codebase and the cost of maintainability. Wherever possible I will always try my best to avoid using them if the solution doesn't outweigh the cost. Whilst string literals can most often be avoided, one area that C# never had an easy solution for the problem was in areas such as referencing variables when throwing exceptions.

With the release of C# 6 this problem and instances like can be easily avoided with the introduction of the nameof expression.

C#6 nameof expression

The nameof expression is a simple solution to the problem, see the follow snippets from the MSDN docs for an example of how the nameof expression can be is used:

void f(string s) {
    if (s == null) throw new ArgumentNullException(nameof(s));
}

Using the nameof expression in Razor becomes especially helpful:

<%= Html.ActionLink("Sign up", @typeof(UserController), @nameof(UserController.SignUp)) %>

What's happening under the hood?

As it's always a good idea to understand how things are interpreted when compiled, let's take a look and see exactly what happens to the following code sample:

public class Class1
{
    public void Output(string myString)
    {
        if (myString == null)
        {
            throw new ArgumentNullException(nameof(myString));
        }
    }
}

When we use a tool like JetBrain's free decompiler DotPeek to take a look at the decompiled source you can see that the property passed into the nameof expression has now been evaluated at compile time and converted into a string literal representation of the parameter:

public class Class1
{
	public void Output(string myString)
	{
		bool flag = myString == null;
		if (flag)
		{
			throw new ArgumentNullException("myString");
		}
	}
}

The result is the exact equivalent of what you'd normally do without the nameof expression - except this time you have the added benefit of compile time safety, rather than having to rely on magic strings (something that's extremely helpful when using refactoring tools to rename classes, properties or methods).

With this in mind, that means if we were to take the following with and without nameof examples and view the IL code generated then they should be exactly the same:

// With nameof expression:
string myString = "Hello World";
throw new ArgumentNullException(nameof(myString));
// Without nameof expression:
string myString = "Hello World";
throw new ArgumentNullException("myString");

IL code generated when using the nameof expression:

IL_0000:  nop
IL_0001:  ldstr      "Hello World"
IL_0006:  stloc.0
IL_0007:  ldstr      "myString"
IL_000c:  newobj     instance void [mscorlib]System.ArgumentNullException::.ctor(string)
IL_0011:  throw

IL code generated when not using the nameof expression:

IL_0000:  nop
IL_0001:  ldstr      "Hello World"
IL_0006:  stloc.0
IL_0007:  ldstr      "myString"
IL_000c:  newobj     instance void [mscorlib]System.ArgumentNullException::.ctor(string)
IL_0011:  throw

We can see that the output is identical.

If that isn't proof enough that you should favour using the nameof expression over magic strings then I don't know what is!

Update:
If you're keen to go even further into the nameof expression then @ErikSchierboom has written an extremely indepth look at what's happening under the bonnet in his C# 6 under the hood: nameof operator article that I'd highly recommend reading.

Visual Studio 2015 Shortcuts interview with .NET Rocks

Posted on Monday, 30 Nov 2015

Last week I had the pleasure of speaking with both Carl Franklin and Richard Campbell as part of a .NET Rocks episode talking about areas of a subject I have a great interest in - mastering your toolset. In this particular show we spent most of the time covering the most important shortcuts you can learn to increase your productivity but also touched on some of the finer details about the what, where and why you should spend time dedicated to turning these shortcuts into habits and ultimately muscle memory; to the point where you perform them instinctively.

If you've read my 9 ways I improved my productivity in Visual Studio 2013 blog post then some of the shortcuts and features will be familiar to you, however we discuss some that aren't on the list that I'd highly recommend checking out.

The show is published on the 10th of December and can be downloaded via the .NET Rocks website or most Podcast aggregators.

Update

You can now download my talk with Carl and Richard via the .NET Rocks website.

I'm overwhelmed with the amount of positive feedback I've had from the show via Twitter, emails and the sheer number of comments it has received on the .NET Rocks Show website. Going into the show I had my concerns listeners may not find it an interesting subject from the outset, but to the contrary it seems like it resonates with a lot of developers which is fantastic to see!

Using the Surface Pro 4 Type Cover on the Surface Pro 3

Posted on Wednesday, 11 Nov 2015

Last September I made the decision to trade in my Macbook Pro and upgrade to a Surface Pro 3. This decision wasn't an easy one to make but I'm a sucker for portability and loved the hybrid approach of the Surface Pro 3 and its ability to act both as a laptop and a tablet.

After a week of programming on my new Surface Pro 3 I decided to put together a rather lengthy post detailing my thoughts and experiences of using the device as a development machine, and whilst the I was, and still am extremely happy with the Surface Pro 3, one aspect that I felt was really lagging was the keyboard - my main criticism being that the keys were too close together and the trackpad wasn't accurate enough, and slightly on the small side for my liking. It seems that these criticisms weren't just ones shared by me, but by many others - but with the release of the Surface Pro 4 and the backwards compatible Surface Pro 4 Type Cover it's clear that Microsoft have been listening to the feedback as the 4's Type Cover goes a long way in correcting these niggles.

In addition to improvements over the existing Type Cover Microsoft released a version that includes a fingerprint scanner - however it doesn't look like it's going to be released in the UK any time soon so being the impatient person I am, I went ahead and ordered myself a standard Type Cover.

The keyboard

The biggest improvement between the Surface Pro 3 keyboard and the 4 is the keyboard size. The keyboard itself has increased further to the edges of the Type Cover with the additional room allowing for much needed gaps between the keys. As someone with rather fat fingers this gap between the keys has gone a long way to increasing my typing accuracy, and thus speed - something extremely important for someone who does  a lot of programming on the Surface Pro 3.

I addition to the aforementioned key spacing, the keys feel a lot more solid than the previous keyboard - it's minor but it definitely lends to the typing experience on the new keyboard.

Other improvements that have been made to the keyboard are:

  • The FN (function) key now features a small light so you know whether your function keys are active or not.
  • The keyboard now features a dedicated print screen button and insert key.

The Trackpad

The next major improvement the Surface Pro 4 Type Cover has undergone in comparison to predecessor is the track pad. Not only is the track pad larger (Microsoft say 40% larger) but it's also made of glass - resulting in it being far smoother and FAR MORE responsive. Whilst the Surface Pro 3's track pad was enough to get the job done, I would never have said it was pleasurable to use. It always felt like hard work - however these recent changes have resulted in a much better experience.

Overall, if you're an owner of a Surface Pro 3 and you want to give your device a brand new lease of life then I'd highly recommend upgrading to the Surface Pro 4 Type Cover.

Podcasts for .NET Developers

Posted on Tuesday, 03 Nov 2015

With an hour long commute to and from work each day I find myself listening to a lot of podcasts. Not only do they make my car journey go much faster but listening to them also help me keep upto date with all of the latest goings on in the software industry. With this in mind I thought it would be beneficial to collate the .NET (or web development related) podcasts that I would recommend.

Before I continue if there are any podcasts that any readers of my blog would recommend then I'm always keen to be introduced to new ones, so please feel free to comment!


.NET Rocks!

Website URL: http://www.dotnetrocks.com
Release Frequency: 3 times a week (Tuesday, Wednesday and Thursday)
Average Episode Duration: 60 minutes

.NET Rocks! is easily the staple of my podcasts. With over 1159 episodes in their show archive hosts Carl Franklink and Richard Campbell do a fantastic job of delivering a great, high-production value podcast that features a broad range of .NET (and on occasion not do .NET) focused podcasts. Carl and Richard travel around creating their podcasts, presenting opporunities to interview some really high profile members of the .NET community. .NET Rocks especially deserves my number 1 spot for the sheer number of episodes they've released over the years and the regularity of their releases.


MS Dev Show

Website URL: http://msdevshow.com
Release Frequency: Once a week
Average Episode Duration: 60 minutes

MS Dev Show is a recent addition to my long list of favourite development related podcasts but has certainly left a good impression. Since first learning about MS Dev Show just a few weeks ago I've already made a good start on burning my way through their archive.


Hanselminutes

Website URL: http://hanselminutes.com
Release Frequency: Once a week
Average Episode Duration: 30 - 40 minutes

Along with the aforemention podcasts, I would also highly recommend Scott Hanselman's Hanselminutes podcast. Having been listening to Hanselminutes long before I got into the .NET world, I've always been a great admirer of Scott Hanselman's ability effortlessly communicate concepts, ideas and thoughts in a clear manner - if he has the ability to slow down time to find the perfect word or sentence that expresses what he's trying to communicate. Whilst not all episodes are development related, they're always insightful and interesting.


Developer On Fire

Website: http://developeronfire.com
Release Frequency: Twice a week
Average Episode Duration: 30 - 60 minutes

Developer On Fire is a recent addition to my podcast list (when I say recent, I mean 6/8 months) but has quickly become one of my favourites due to presentation format and the topics discussed. Where as a lot of the podcasts listed are more technology focused (where a guest comes on to discuss a particular topic), Developer On Fire does something a little different and talks about the guests more personal relation with the software industry, encouraging them to share experiences and tips with a real focus on delivering value.

The host, Dave Rael presents the show really well and does a great job of keeping the guests talking, teasing interesting stories, tips and recommendations out of them throughout - often ending with a great question where he asks for two or three book recommendations for the listeners - books that on occasion I've actually gone and purchased as a direct result of the recommendation. 


Eat, Sleep, Code

Website URL: http://developer.telerik.com/community/eat-sleep-code/​
Release Frequency: Twice a month
Average Episode Duration: 30 - 40 minutes

Eat Sleep Code is a podcast created by the guys and girls over at Telerik and is certainly worth adding to your podcast aggregator of choice. Each episode spans between 30 to 40 minutes and is a healthy mix of programming related subjects ranging from .NET to Javascript and mobile development.


Herding Code

Website URL: http://herdingcode.com
Release Frequency: Once a month, sometimes longer
Average Episode Duration: 20 - 30 minutes

Herding Code is another get .NET focused podcast that regularly features a variety of subjects ranging from software architecture to mobile phones and javascript libraries. Whilst I would definitely recommend adding it to your podcast aggregator of choice be aware that the eposide release cycle is rather inconsistent.


Software Engineering Radio

Website URL: http://www.se-radio.net
Release Frequency: 2 or 3 times a month
Average Episode Duration: 60 minutes

Whilst not specifically .NET focused (more Java) but often featuring more advanced subjects that apply to general application development, Software Engineering Radio deserves a mention for its sheer technical depth of discussions.


Javascript Jabber

Website URL: https://devchat.tv/js-jabber
Release Frequency: Once a week
Average Episode Duration: 1 hour

Whilst Javascript Jabber is not a .NET focused podcast, with way the .NET and application development landscape is changing most of us .NET (specifically ASP.NET) developers are no doubt familiar with Javascript or will become increasingly familiar with it over the next few years - especially with tooling changes we're seeing in ASP.NET MVC 6. For this reason I feel Javascript Jabber deserves a place on the list. Javascript Jabber regularly features a variety of guests, most often Ruby related, however the hosts do a great job of keeping it Javascript focused. Personally I've found Javascript Jabber a great way to keep upto date with the never ending emergence of Javascript libraries.

 

That's it for now. I'm always on the lookout for new podcasts to ease my commute so feel free to mention any I've missed in the comments below and I'll be sure to add them to the list!

Using Roslyn to look for code smells

Posted on Friday, 09 Oct 2015

Since first hearing about Roslyn I was instantly excited about its application in being able to easily parse C# and could clearly see the benefits it could bring anyone wishing to perform analysis on an existing codebase - not to mention the great things it can do for the Visual Studio plugins and extensions.

Having been playing around with Roslyn for a couple of days now I thought I'd share a cool snippet of code I put together to demonstrate how easy it is to parse C# code using the power of just a few Roslyn NuGet packages.

In this using Roslyn to analyse an existing codebase and flag any classes that are guilty of the 'Too many parameters' code smell.

First, let's load the solution:

First of all we're going to need to load our solution...

public static class WorkspaceSolution
{
    public static IEnumerable<Document> LoadSolution(string solutionDir)
    {
        var solutionFilePath = Path.GetFullPath(solutionDir);

        MSBuildWorkspace workspace = MSBuildWorkspace.Create();
        Solution solution = workspace.OpenSolutionAsync(solutionFilePath).Result;
        
        var documents = new List<Document>();
        foreach (var projectId in solution.ProjectIds)
        {
            var project = solution.GetProject(projectId);
            foreach (var documentId in project.DocumentIds)
            {
                Document document = solution.GetDocument(documentId);
                if (document.SupportsSyntaxTree) documents.Add(document);
            }
        }

        return documents;
    }
}

As you can see from the above snippet this is actually quite simple thanks to the Microsoft.CodeAnalysis.MSBuild package, more specifically the MSBuildWorkspace class. This allows us to scan our solution and create a collection of any documents within it.

Analysing the documents (aka. class files)

Now we've got a list of all of the documents within our solution we can begin to iterate through them, parsing the syntax tree until we come to the method parameters (though performing the same analysis on constructors is equally as easy - but for the sake of this demonstration we'll look at methods).

At this point we can check to see if the number of parameters exceeds our threshold.

List<MethodDeclarationSyntax> methods = documents.SelectMany(x => x.GetSyntaxRootAsync().Result.DescendantNodes().OfType<MethodDeclarationSyntax>()).ToList();

var smellyClasses = new Dictionary<string, int>();
int paramThreshold = 5;
foreach (MethodDeclarationSyntax methodDeclarationSyntax in methods)
{
    ParameterListSyntax parameterList = methodDeclarationSyntax.ParameterList;
    if (parameterList.Parameters.Count >= 5)
    {
        smellyClasses.Add(methodDeclarationSyntax.Identifier.SyntaxTree.FilePath, parameterList.Parameters.Count);
    }
}

Let's put it to use

If you're still not sold on how powerful this can be, let's move this into a unit test that can easily be included as a base suite of unit tests - allowing us to easily enforce rules on our development teams.

[TestCase(5)]
public void Methods_ShouldNotHaveTooManyParams(int totalParams)
{
    List<MethodDeclarationSyntax> methods = this.documents.SelectMany(x => x.GetSyntaxRootAsync().Result.DescendantNodes().OfType<MethodDeclarationSyntax>()).ToList();
    foreach (MethodDeclarationSyntax methodDeclarationSyntax in methods)
    {
        ParameterListSyntax parameterList = methodDeclarationSyntax.ParameterList;

        // Assert
        parameterList.Parameters.Count.ShouldBeLessThanOrEqualTo(totalParams, "File Location: " + methodDeclarationSyntax.Identifier.SyntaxTree.FilePath);
    }
}

As you'll see in the code snippet below we then use Shouldly unit testing framework and its awesome error messages to inform us of the class that's currently violating our code smell rule!

If you're interested in having a play with this then you can find the code up on GitHub here. I'd also recommend checking out this post if you're interested in learning more about Roslyn and how it works. Another great resource that gave me the idea for using Roslyn to create tests is this strathweb.com blog post by @filip_woj.

About Me

I'm a software and web application developer living in Somerset within the UK and I eat/sleep software and web development. Programming has been a passion of mine from a young age and I consider myself extremely lucky that I am able to do what I love doing as profession. If I’m not found with my family then you’ll see me at my keyboard writing some form of code.

Read More

Feel free to follow me on any of the channels below.

 
 
profile for JoeMighty at Stack Overflow, Q&A for professional and enthusiast programmers

Recent Blog Posts