Insight: AuthorizeAttribute Lifecycle

I’ve learned a valuable lesson about the AuthorizeAttribute Lifecycle recently, one which I feel should be shared with the world. Hopefully, someone will gain something from this, hopefully I can fix the issue I faced for others.

The Story

The situation is a simple one, I required that access to certain controllers and actions was subjected to the approval of an authorisation process. In MVC, we are provided with the AuthorizeAttribute to help us along our way. Not wanting to re-invent the wheel in any way, I implemented the AuthorizeAttribute filter, as I have many times before without ever fully understanding the AuthorizeAttribute Lifecycle, and went on my way, assuming the filter was doing it’s job because the tests passed and I could authorise against the attribute.

Continue Reading →

22. July 2014 by Adam Riddick
Categories: ASP.Net, C# | Leave a comment

Software Overengineering

Software Overengineering

How do you know when you are over thinking the architecture of a solution? Should we forget about the future and build for now, or should we focus our efforts on building for the future? Are we all Software Overengineering?

First, I want to define Software Overengineering. It may be natural towards thinking this means putting too much effort into a solution that requires less. Whilst it follows the same mold, it is not entirely the same.

By Software Overengineering, I refer to putting too many constraints on the architecture or design of a solution, constraints that we feel are required though never actually will be, we can build for the future without building the future. It’s an easy trap to fall in to, it’s among many people’s traits to over think a situation, and many developers over complicate solutions, a lot simply because they feel it makes them appear smarter and better at what they do.

Continue Reading →

15. July 2014 by Adam Riddick
Categories: Achitecture | Leave a comment

Backup All Databases SQL

Data is precious and for many companies data means money, directly or indirectly. More and more countries are taking up laws on the ownership storage and historical persistence of data, meaning companies need to pay attention to backups for multiple reasons. But whatever the reason for a backup, you should be able to backup all databases without it giving you a headache.

Of course we could use Sql Server Management Studio (SSMS) to create a maintenance plan, and that’s fine and easy when we have a handful of databases, or less, but what if there are dozens or hundreds of databases that require attention? Do we really want to maintain that may maintenance plans?

We can backup all databases in an Sql server using a T-Sql script, which will cycle our databases and create a dated backup at the  location of our choice. This script can be scheduled through a SQL Job to automatically backup all databases to a set schedule.

Backup All Databases Script

DECLARE @name VARCHAR(50) -- database name
 DECLARE @path VARCHAR(256) -- path for backup files
 DECLARE @fileName VARCHAR(256) -- filename for backup
 DECLARE @fileDate VARCHAR(20) -- used in file name
 SET @path = 'C:\backups\' --path to the backup folder

 SELECT name
 FROM master.dbo.sysdatabases
 WHERE name NOT IN ('tempdb')
 OPEN db_cursor
 FETCH NEXT FROM db_cursor INTO @name
 SET @fileName = @path + @name + '_' + @fileDate + '.BAK'
 BACKUP DATABASE @name TO DISK = @fileName
 FETCH NEXT FROM db_cursor INTO @name
 CLOSE db_cursor
 DEALLOCATE db_cursor

The power of T-SQL allows us to be flexible enough to include of exclude certain databases, in case they are archived already, their backups are handled by an existing maintenance plan or they are temporary databases. This can be achieved through a standard WHERE clause. The full power of T-SQL is at our disposal for handling backups, which allows us to be very dynamic in what we create backups of.

05. July 2014 by Adam Riddick
Categories: SQL | Leave a comment

MVC External Controllers

In my current role I am architecting and implementing an application platform that is flexible and dynamic enough to allow a full set of application features be loaded into the application without any outward dependencies from the central application block. This requires that each Service being loaded into the application is dependent only on the central applications functionality, using a separated data access layer to handle any data persistence. It also requires that a single MVC presentation layer handles the loading and routing of External Controllers. These External Controllers are to be located within the services, separate from the base presentation layer.

Effectively, this application is operating with an N-Tier architecture, in which N is only definable within a given deployment.

Each of the services that will be created for this application needs to be in a position to declare and handle it’s own Controllers, Views and Routes, three essential components of the MVC engine.

Handling External Controllers from a single presentation application has perhaps been the most complex part of the project to date.

The most obvious point approaching the problem of External Controllers was that the Routing table would need to be aware of the routes in order to pass a request to the controller in question. This was achieved by mapping all of the routes into the routing table on application startup. Using an interface implemented within each service, derivatives of the interface can be loaded on application start and there register method called to map the routes.

But it doesn’t stop there. Each of the routes mapped must set the Namespace parameter to declare the full namespace in which the controller can be found, otherwise the routing engine will stop after checking the default namespaces.

For example;

new { controller = "ExternalExample", action = "Index"},
new string[] { "MvcApplication.Controllers" });

The next step is to make sure every resource that will be rendered is set a an Embedded Resource and each of the External Controllers must return a view by the entire namespace name, I.E “MvcApplication1.Views.Home.Index”.

Next, there is a need to implement a custom VirtualPathProvider to tell the MVC engine where to find our resources, which is registered on application start. There are a lot of examples of this on the internet (Try Ian Mariano’s), it’s normally just a case of tweaking the path locations depending on the setup of your external controllers assemblies.

In order to handle media files (.css, .js, .png, .jpg …. etc), they must also be set as Embedded Resource’s, and can be called through the following method, within the Presentation layers controller;

public FileStreamResult Content(string id)
string resourceName = Assembly.GetExecutingAssembly().GetManifestResourceNames().ToList().FirstOrDefault(f => f.EndsWith(id));
return new FileStreamResult(Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName), GetMIMEType(id));

Finally, we must ensure that the separate services are locatable by the app domain. In order to do so, we have to use a PreApplicationStartupMethod (See This) in which we load a shadow copy of the assemblies into the app domain.

In order to do so, we must set the Probing PrivatePath property to the location we will shadow copy the assemblies to. This is done in the web.config <runtime><assemblyBinding> section;

<Probing PrivatePath="/ShadowCopies" />

Once we load the shadow copied folder into the private path, which is done using a standard file.copy from a dynamic directory search, the shadow copied assembly must be registered with the Build Manager, so MVC knows to reference this DLL as part of the application domain. This is done using;


The build manager requires that this is done in a PreApplicationStartupMethod. So we use our PreApplicationStartupMethod to make shadow copies of the DLL’s we are working with and registered the appropriate ones with the Build Manager.

And from there, the External Controllers can be accessed through the base application, without the application needing a reference to the external controllers assembly. This allows us to swap and change Services in a plugin fashion and the only requirement is that we restart the applications domain, which is a very straightforward operation, just have a controller action call the following;


The next steps will include allowing a Plugin architecture to be handled for the Modular services, so they themselves and have their functionality expanded without the need for updates. Unfortunately, this would require that the plugin dll’s are also loaded into the BuildManager pre-startup.

I plan on experimenting with holding an additional app-domain to hold plugins in a separate environment to the main application, one that would be started when the plugins are requested by the service itself, holding only the required lifecycle and not being present for the entire application lifecycle when they may not be used.

If I have much success, I may plan to implement this into the services, however it depends how nicely MVC plays with controllers in separate app domains, considering the setup required for External Controllers.

26. June 2014 by Adam Riddick
Categories: Achitecture, C# | Leave a comment

C# ?? Operator

Those of you who have used C# for a while will probably be familiar with the ?? operator, known as the null coalescing operator. The ?? Operator is used to check if a value is null, and will return the left hand operand if it isn’t, and the right hand if it is.

For example;

string myString = null;

string result = myString ?? "Empty String"; //Result is set to "Empty String"

myString = "A String";

result = myString ?? "Empty String"; //Result is set to "A String"

The reason for this post wasn’t to introduce anyone to the ?? Operator, which most of you will have seen at least in passing before. But it was because I discovered something new about the ?? Operator today, it can be chained.

The ?? Operator can be used multiple times in the same operation to determine if multiple operands are null.

An example usage;

string valueOne = null;

string valueTwo = null;

string valueThree = "Hello";

string result = valueOne ?? valueTwo ?? valueThree ?? "No Value"; //Result is set to "Hello"

valueOne = "Changed";

result = valueOne ?? valueTwo ?? valueThree ?? "No Value"; //Result is set to "Changed"

Sometimes it’s the simplest things that make our lives more concise!

Credit where credit is due, Rick Stahl.

16. June 2014 by Adam Riddick
Categories: Uncategorized | Leave a comment

c# Type Alias

C# comes with the using directive, which allows us to import namespaces in order to allow access to the members of namespace, but it can also be used to create a namespace or type alias.

When used as an Type Alias, the using statement allows us to simplify access to long-named namespaces, or to simplify access to types by creating an Alias of that type.

For example, we can setup a type alias using the following code;

using NestedDict = Dictionary<string, Dictionary<string, Dictionary<string, IEnumerable<int>>>>;

Setting the above code with the rest of the files Using statements allows us to use NestedDict instead of our large definition of a nested dictionary, so we can simply do the following;

NestedDict myDict = new NestedDict();

Calls to myDict are not calls to a NestedDict type, but to the complicated nested structure we defined with the Type Alias.

Using is not only able to make Type Aliases, but also to make Namespace Aliases.

This can be done in the same way, for example;

using space = myNamespace.anotherNamespaceWithAReallyLongName;

We can then access the members of the namespace by using the space alias, saving us repeating potentially long namespace names, especially if they become complicated and nested.


12. June 2014 by Adam Riddick
Categories: Bits & Bobs, C#, Tips | Leave a comment

c# Convert String To Enum

There are multiple techniques that can be employed for conversion of a String to Enum value, But which one should we be using? In the past, I’ve always done it the simple way and created a method “ToEnum” and used Enum.TryParse to gather the value. However, as I am currently leading a project in which performance at every stage is crucial, I thought I would explore this a little bit deeper.

Disclaimer: I am not prematurely optimising. It just happens I looked at my enum extensions and was curios if there was a faster way, knowing the method I was using in turn used reflection for resolution.

Enums are a great solution for holding information in a lightweight container. An enumeration can be used to hold the possible options to be passed into a method, such as a factory, or to be used to hold the possible states of a piece of information, such as the results of an Authentication attempt;

enum AuthResult





Continue Reading →

08. June 2014 by Adam Riddick
Categories: C#, Tips | Leave a comment

C# Initialize methods before app start

There often comes a time in development when some form of initialization is needed in an application, so we begin to implement Initialize methods. These are very handy, allowing developers to complete any pre-cursor work the application requires before it is run, setting up caches or loading external assemblies into the app domain.

But where do we set these Initialize methods?

No doubt you will have seen Initialize methods called in the Application_Startup path of a Global.asax file. If you haven’t, it’s almost a guarantee that you soon will.

I’m not criticising the approach. It’s what it is there for, it’s called very early in the pipeline and does allow for initialize methods to be called to setup the environment for the application to run. But it isn’t always available for use, though we have an alternative route.

Continue Reading →

01. June 2014 by Adam Riddick
Categories: ASP.Net, Bits & Bobs, C# | Leave a comment

The Parallel.Invoke Method

In the .Net Framework we can use Parallel.Invoke to call multiple methods in parallel, meaning they will begin to run at the same time across multiple threads. This can be useful when we have multiple long-running methods that don’t need to be called in a linear process.

For example, if we are running one method which takes 3 seconds, and then a second that takes 4 seconds in tandem, we are going to be waiting 7 seconds for the final output, but if we run these parallel to each other, the output will be faster.

The Options

Parallel.Invoke isn’t the only way to achieve parallelism of methods using the .Net framework. Here, we will explore the effects of running the methods linear, using Thread to manage the threads ourselves, and using Parallel.Invoke, the code will look something like the following;

For the linear process;



Continue Reading →

20. May 2014 by Adam Riddick
Categories: ASP.Net, C#, Tips | Leave a comment


I’ve never been very bothered by podcasts. I suppose it’s because I’ve never found the time to go through the ones available, find the ones I like, download the podcasts I want to listen to and the find time to listen to them as well.

I’m a bit different with blogs. I have a massive list of blog posts I’ve come across that I want to read, but I rarely find the time, though I do get through those at about the same rate I add to the list. I really enjoy getting the thoughts and opinions of others, but it’s difficult to spare the time sometimes.

As for podcasts, in addition to the timing, I don’t think I ever came across any that caught my eye. But that’s all changed recently.

I car share at work, in my current job, but due to workloads it’s becoming increasingly difficult to make that work, coupled with the fact I start a new job in two weeks. So I decided to invest some time into looking at podcasts, to listen too during the commute. I don’t like the idea of paying for new music all the time and I hate that the radio stations only play a song i’m interested to in every 3, with added adverts. podcasts seemed to offer me a more intellectually stimulating option that also get my mind into gear before the clock starts, so to speak.

And they do.

After first having a bit of a fight with Windows Phone over the podcasts, I got myself up and running and downloaded the historical casts from the podcasts that tickled my fancy. I find myself running through an average of 1 and a half podcasts a day and I’ve had a large boost to stimulation related to my field. I’m not sure I’ve discovered anything new yet, but even just hearing the experiences of those in the field on the other side of the world is massively interesting to me, and very stimulating.

I’ve been listening to Hanselminutes, .Net Rocks and This Developers Life, although unfortunately This Developers Life hasn’t been updated this side of 2014, but I’m only around halfway through those podcasts.

I’m on the lookout for some more, I’m getting through them at around 8 a week and I won’t listen to every historical podcast.

Overall, it’s been a pleasant change and I’d recommend those three podcasts to every developer, budding to expert.

As a side note, I’d like to express my disappointment at the Windows Phone 8.1 built-in Podcasts application, which cannot be removed.

I spent my time, naively, setting up the podcats I wanted to listen to and downloading a number of podcasts ready to go. Perhaps I should have explored further beforehand. I attempted to filter the casts to only show the ones I had downloaded, a View Later list per say, but no such functionality existed, which came as a shock to me.

Podcast2Go to the rescue! With it’s Playlist functionality and default Downloads playlist I got exactly the functionality I needed, and best of all, it didn’t cost me a penny. I removed the contact from the native app and set everything up in Podcast2Go, and I haven’t had a single problem in doing so.

I’m new to the developer podcast world, but if there are any podcasts out there you think I’d be a fool to ignore, please let me know about it and I’ll give it a go.

12. May 2014 by Adam Riddick
Categories: Experiences | Leave a comment

← Older posts