SSO with Windows Identity Foundation: Part IV - STS

Welcome back to keep on building on our understanding of an STS. This part is fully about creating a response message to the message we previously sent from the relying party.

Last time we were able to make our forms authentication application automatically redirect to our STS, and we were able to successfully receive and log the contents of the message that we were getting from our RP.

Read More

SSO with Windows Identity Foundation: Part I - The basics

The road to understanding the security and technical details of any security system is a truly perilous one with steep learning curves along the way. Toss in a side dish of single sign on and achieving that securely, and you're in for a ride. What I aim to do here is to challenge myself with a multipart blog post and try to shed some light on Windows Identity Foundation in an understandable way. Here's part one, and an introduction to the basics.

Read More

Generating CSV files with .NET using the Razor Engine

There comes a time in almost every business related application, where a client has a requirement for you to have your data export into CSV.

Well, simple, I hear you say - I'll just make this amazing contraption with .NET Reflection that goes through my class - checks what properties they have, and serializes that data into a CSV.

All good, and you send your beautifully elegantly produced CSV to the client, and they respond with: "Well, that looks good, but I don't want that bit of the data, and could you format this data in this way, and do this and that".

So here's my solution - a solution that I've really liked, and have used succesfully and that delivers on both separating the actual CSV-generation from the code and not having to deal with string replacements or regex or anything. Also, if your client wishes to change the implementation, as they always do - you'll be fine.

On with the the how to:

Fire up Visual Studio, and install through Tools -> Extensions and addon called RazorGenerator - make sure to restart Visual Studio for your addon to be installed.


Create a new file in your project called CSVGenerator.chtml - your file could be called anything and your project can be any type, but the file has to be .cshtml

Go to the Properties view of the file you just created and set RazorGenerator in the Custom Tool input box.


Now as you'll probably notice, the custom tool will run and create a code file from the Razor template you've created. In this file you'll get the auto generated code to create your CSV.

To get started, let's also make a class that contains some business entity, so we can use that as our data to generate the CSV from:

With our class in place, let's start with our Razor Template - open up your file and put this in:

So what we're telling the template engine is that we want our generated file to be a regular template file, and we want a public member in the generated class called model, which we can set to whatever we want. This is essentially exactly what you'll see happen in MVC, but just behind the scenes. In this case, we can give our template multiple parameters and just set those in our code.

Our template is done, and now is only the business of executing it and generating the final form of our beautiful CSV:

As you input that code, you'll find that TransformText is not found in the CSVGenerator implementation, and to achieve that you need to install a NuGet package called RazorGenerator.Templating

Note that the member in our CSVGenerator class called "model" is the one we defined earlier and that could literally be anything. We're giving it a list of BusinessClasses, but you could have a tree or hierarchy of absolutely anything or multiple different parameters if you liked.

In addition to this, we are using Trim at the end of our call on the output from our generated template, to remove any leading line feeds caused by the initialization code in our template.

And here's our output:

4,Joel,0:00 3,Pete,0:00 1,Susannah,0:00 2,Max,0:00

Download sample code

There you have it - a simple, fairly elegant way of achieving CSV files or other template based files such as html or pdf files.

For pdf files, I've used a method similar to this - if you'd like for me to make a post about that, leave a comment.


Scrum requires the full organisation to commit

I got myself scrum certified.

Getting the certificate is easy, it's enjoyable - it's very useful, and most importantly, it doesn’t actually help you very much.

As many of us know, an organisation can be anything from super rigid to flexible and all shades in between. You can have people with various backgrounds and predispositions.

You might be taking on Scrum because you have an organisational requirement to do so, or you may be finding yourself lost in projects or maybe doing it to pre-emptively to prepare for growth.

It is truly a jungle of things and if my experience is anything to go by, people’s motivation and the management hold all the keys to actually making it work.

If you have a combination of these factors, you will find yourself struggling to Scrum properly:

  • If you do not have work that can be planned for two weeks ahead.
  • If the team has no external direction and/or the Product Owner does not put effort into the backlog.
  • No matter what management thinks, if you clearly have a group of people rather than a team of people (distinction is that more than one person works on the same thing in a team).
  • Team members are not fine with going out of their comfort zone.
  • Team members work on stuff alone.
  • One or more of the following management disasters is what you’re under:
    • Management had no clear vision on what the team is going to do.
    • Your team has more projects to manage than you have toes and fingers.
    • Every team in the organisation is essentially competing for projects.
    • Your team has to function as a support team and a development team in the snap of a finger.
    • Most of the team’s work is support work, and the management still views it as a development team.
    • Scrum was imposed on the team because of organisation guidelines.

Bottom-line is that Scrum can help a team in a lot of ways, but for it to work, the whole organisation needs to commit to it including stakeholders, and you need to find intrinsically motivated open minded people.

There is a lot of scenarios where it won’t work or where it becomes more overhead than it’s worth. These scenarios, if my work experience can be any precursor, are easily the majority. Regardless, it is important to get real about the situation you’re in, and accept the fact that Scrum might, sometimes not work for your scenario – and that is fine.

Do not let management tell you otherwise.

Four things I learned playing World of Warcraft

I have a confession to make. I love World of Warcraft, and I've spent a fair deal of time on it. 

I've been a raid leader and a guild master - this was before my real life career took off. Now it's time to look back at the time spent and analyze what I was left with.

First of all, what WoW allows is a binary arbitration of a group of people who are geographically distributed on multiple time zones, then has a huge amount of them work together with a latency of about 30ms, no matter where they are in Europe - all this in a virtual world where a single misclick or a bad move means instant failure and devastating consequences for a lot of the participants. Nerd rage is commonplace.

Stepping back on that thought, it is a mind boggling technical feat. I'm pretty sure the back-end servers do not host a lot of managed code or layers of arbitration. It would be impossible, although I am certain the hardware those servers run on are bordering on ridiculous. 30ms latency - think about that for a second. It's about a single blink of an eye, which means that latency gives you almost no room for error. The game, though, takes advantage of that low latency.

Pressure and managing your state

At work, you'll sometimes (more often than I'd like) run into a situation where your boss and any amount of co-workers are standing next to you, having an argument behind your back, while seven servers are on fire - and the only one who knows how to fix them is you. They're all going insane trying to find the one to blame and what the problem is, usually ending up with the wrong culprit and an issue that isn't even there. Getting upset is the worst thing you can do.

These situations need a clear head, determination and the guts to keep yourself focused on the important things. Taking a step back and thinking about what you're doing even when you're in a hurry is the key thing. Dealing with the feeling that a lot of people are breathing down your neck is something you learn to deal with well while playing WoW. Lose your own state, and you lose your direction. For software development - be it managers or super corporate magnates demanding you need to be done by yesterday - it is a developers personal responsibility and matter of pride to still take the time needed to make things work reliably, and to fight for the right to do that. Otherwise it'll all just creep back on you.

For the game as well, doing something 200 times over just to get progress on it can have its effect on your state of mind and the state of minds of other people. People get super annoyed, and they will not hold their feelings back. Managing your own state while trying to keep the spirits of the group up and focused on the things that matter is a really difficult endeavour, but it has to be done - because losing the spirit to get things done means losing all chance of victory.

Multi-tasking and delegation

In WoW the raid leader is in a unique position where they need to be coordinating the effort and the timings of when people do what and call all that out precise to the second, while doing exactly the same things everyone else is doing. This often leads to a situation where the ability to perform is severely impaired. Noticing when you become this bottle neck to the group is key and delegating the high load moments among your people is what brings you victory. In my experience, people must be told that they suck before they notice it - but being good at something means you scrutinize yourself and what you do, thus enabling you to work better.

In the work life I am not in a position where I could delegate, but I am certainly able to ask for help if I so require which is the next best thing. Knowing when you'll be at your wits' end before you get there is a valuable skill. Moreover, self reflecting on what you are doing is the most important thing ever.

Skills matter

Just like ol' Sturgeon phrased it, 90% of everything is crud. This is equally true for work, for the game and for all things organic. Surrounding yourself with likeminded people and people with their hearts and motivation in the right place is the only way to fight this. Making that leftover 10% the only 10% you know about is a way out. Finding people you can work with and challenging your mind against theirs makes you that much richer.

Skill really matters - guild or corporation.

Objects in mirror are closer than they appear

I feel like I've learnt the most important things about myself though.

From my perspective most people live in denial about how important their goals and ambitions are - by that I mean they highly over-estimate their own importance.

There is a huge amount of pressure on people to succeed at this day and age and it is not uncommon to find yourself feeling bad when you spend time doing something that seems menial or nonvaluable. I look back at all those days spent on that game, and I feel bad - I honestly do. The only reason I can figure for that is how society states you should be doing socially accepted things.

In the game I met hundreds of different people and learned that people handle differently and given anonymity are also much more volatile. I also learned that about myself.

I came out of that experience with a lot of likeminded friends, fond memories, and as a person with a lot of real people skills in my back pocket. Time not wasted!

Most importantly, I learned that becoming too entangled with something can be detrimental to the way you think about it, and sometimes stepping back to see the bigger picture can lead to better things. 

It could be a solution I've created or a choice I've made or problem I'm stuck with - stepping back might just put it all into perspective.

To summarize: sometimes you have to go far to see what is near, and vice versa.

Long running batch jobs using a plugin architecture


I'm sure you're all familiar with that pesky case which occurs in many enterprise applications where you need to have batch run processes in your ASP.NET website. Because of the way the Application Pool can have scheduled restarts as well as being recycled and suspended on no traffic moments, it is usually not the best place to have your long running processes in.

Now, often the answer is to make a Windows service project and make some sort of contraption of timer facilities inside that Windows service. 

As for deployment, usually ASP.NET sites are deployed with MSDeploy or by using publish profiles aka. WebDeploy.

It becomes an immense pain to always have to go and shut down your Windows service before you can web deploy again, if you've included the deployment of your Windows service to your publish profile.

Not only that, your code base gets separated into multiple entities which may feel unrelated.

So I thought, how about making a Windows service that just runs plugins and autodetects changes in them.

That way I never need to bring the Windows service down or redeploy it. All I need to do, is deploy the DLLs into the plugins directory that the Windows service is watching. They will be auto detected by the service, and reloaded in runtime.

Not only that, but this kind of generic service is nice in the enterprise world where sharing code and solutions is often very difficult and avoiding duplication is very important.

Without further ado, let's get down to it.

I decided up front to use Quartz.NET for scheduling and Managed Extensibility Framework to achieve plugins.

First off, let's define an interface for a plugin:

Plugin Interface:

public interface IScheduledJob { ITrigger GetTrigger(); IJobDetail GetJob(); }

With that defined in an external project from the Windows service, we can simply implement that in a Class Library project, build it and then copy that into the Windows service's plugin directory to get it running.

Let's make an implementation of that by creating a new class library project and adding this class in there:


[Export (typeof(IScheduledJob))] public class TestJob : IScheduledJob { public ITrigger GetTrigger() { var trigger = TriggerBuilder.Create() .WithIdentity("trigger1", "group1") .WithSimpleSchedule(x => x.WithIntervalInSeconds(1).RepeatForever()) .StartNow() .Build(); return trigger; } public IJobDetail GetJob() { return JobBuilder.Create<StupidJob>() .WithIdentity("job1") .Build(); } } public class StupidJob : IJob { public void Execute(IJobExecutionContext context) { Console.WriteLine("Doing stupid things."); } }

If you are unfamiliar with the Quartz.NET fluent API, check this documentation.

Now, this class library will need a reference to the interface project (which contains IScheduledJob) as well as MEF and Quartz. Building it should produce a DLL under the Debug directory. Let's get back to using that later.

Finally on to the thing that makes it all tick, the Windows service. I'm going to just make a console application as an example to avoid cluttering it with the boilerplate code that would be required to make a Windows service work.

So, we shall put this code into our console application project:

"Windows Service" (Console app)

class Program { private const string PluginFolder = "plugins"; private static ISchedulerFactory _schedFact; private static IScheduler _sched; static void Main(string[] args) { var s = new Program(); s.Run(); Console.Read(); } private void Run() { // Watch the plugins folder var fileSystemWatcher = new FileSystemWatcher(PluginFolder) { Filter = "*.dll", NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size, EnableRaisingEvents = true }; fileSystemWatcher.Changed += FileSystemWatcherOnChanged; // Initialize Quartz scheduler _schedFact = new StdSchedulerFactory(); _sched = _schedFact.GetScheduler(); _sched.Start(); } private void FileSystemWatcherOnChanged(object sender, FileSystemEventArgs fileSystemEventArgs) { // Always resolve all the MEF plugins inside our plugins folder var components = new DirectoryCatalog(PluginFolder); var timers = new CompositionContainer(components); timers.ComposeParts(this); var scheduledJobs = timers.GetExportedValues().ToList(); // Remove plugins with similar keys, and reschedule them for (var i = 0; i < scheduledJobs.Count(); i++) { var job = scheduledJobs[i]; _sched.UnscheduleJob(job.GetTrigger().Key); _sched.ScheduleJob(job.GetJob(), job.GetTrigger()); } } }

Next you need to create a plugins folder under the bin/Debug directory of the console application project. Then you need to copy the DLL from the class library project you made earlier into this directory.

You may copy that DLL under the plugins directory, and simultaneously observe on the console that the plugin will instantly start running.

Next you may remove that DLL from under the plugins folder and re-copy it there to see it reload seemlessly.

So, having this run in a Windows service and only deploying whatever is in the plugins directory will allow you to never have to bother with restarting or stopping the Windows service: just do an in-place deployment of the plugins and they will automatically be reloaded.

This would require well-thought-out logging, security and error handling, but with this solution at least one could achieve a singular solution for all the batch processing needs of an enterprise.

Here's the VS2012 full project for your perusal. (Remember again to restore all NuGet packages from the NuGet package manager.)

Good luck!

WebAPI convention based versioning with Accept-headers

So, you want to have different controllers for different versions of your API, well - so do I, so let's get started.

To begin with, WebAPI comes with a wonderful set of extension points, one of which we are going to use to achieve convention based accept header versioning.

What we want to achieve, is that our API receives an accept header, something like this:

Accept: application/xml;version=1

With our own custom implementation of IHttpControllerSelector, we'll intercept that header as WebAPI is going through its motions, and we'll pick the appropriate controller to execute based on a naming convention in the controller's name.

For example, with the above header a HTTP GET to /api/values would return V1ValuesController.

So, adding new versions just means making a new controller with the appropriate name, and things will just work.

Let's see the code.

    // Implement DefaultHttpControllerSelector, so we can override SelectController
    public class VersionControllerSelector : DefaultHttpControllerSelector
        private readonly HttpConfiguration _configuration;

        private Dictionary _apiControllerTypes;

        private Dictionary ApiControllerTypes
            get { return _apiControllerTypes ?? (_apiControllerTypes = GetControllerTypes()); }

        public VersionControllerSelector(HttpConfiguration configuration) : base(configuration)
            _configuration = configuration;

        public override HttpControllerDescriptor SelectController(HttpRequestMessage request)
            // Fall back to using the default implementation if no version is specified
            return GetVersionedController(request) ?? base.SelectController(request);

        private HttpControllerDescriptor GetVersionedController(HttpRequestMessage request)
            var controllerName = base.GetControllerName(request);

            var version = GetRequestVersion(request);

            // Given null, the default implementation will get called
            if (version == null)
                return null;

            var type = GetControllerTypeByVersion(version, controllerName);
            if (type == null)
                return null;

            return new HttpControllerDescriptor(_configuration, controllerName, type);

        private static string GetRequestVersion(HttpRequestMessage request)
            // Find an accept header with a version parameter
            var version = request.Headers.Accept.Select(i => i.Parameters.Single(s => s.Name == "version").Value).ToList();
            return !version.Any() ? null : version.First();

        private Type GetControllerTypeByVersion(string version, string controllerName)
            // Stick to a convention, where a class name begins with the version number, this could be changed
            var versionToFind = string.Format("V{0}", version.ToLower());
            var controllerNameToFind = string.Format("{0}{1}{2}", versionToFind, controllerName, ControllerSuffix);

            return ApiControllerTypes.Where(t => t.Key.ToLower().Contains(versionToFind.ToLower()) && t.Key.EndsWith(controllerNameToFind, StringComparison.OrdinalIgnoreCase)).Select(t => t.Value).FirstOrDefault();

        private static Dictionary GetControllerTypes()
            var assemblies = AppDomain.CurrentDomain.GetAssemblies();

            var types = assemblies.SelectMany(a => a.GetTypes().Where(t => !t.IsAbstract && t.Name.EndsWith(ControllerSuffix) && typeof(IHttpController).IsAssignableFrom(t)))
                .ToDictionary(t => t.FullName, t => t);

            return types;

The final thing you need to do is replace the default implementation of this class in Application_Start:



GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerSelector), new VersionControllerSelector(GlobalConfiguration.Configuration));



As for routes, just defining a route without the version numbers like you normally would is fine - it will basically just work. 

Many thanks to Andrew Malkov for this, which I used as a reference to achieve the above.

Full example downloadable here (open Nuget to restore packages)

In the example, just use a client like SoapUI and fire a normal GET request to /api/values, and then do the same again but with the accept header "application/xml;version=2" and you should see different return values based on version.

That's it, good luck :)

Chapter 1: What if I made an IT company - planning for growth?

Let's take a little tumble down the rabbit hole.

So I've got an idea, a mind boggling earth shattering idea, I make a company around that idea, it ends up being very successful - everyone's happy? No, not really.

It seems to me and in my experience that the Finnish way of management is set on the belief that growth is always in the amount of people you have sitting around the office. You had that really successful IP that made you a million and that was the signal to now have 100 people sitting around instead of the original 10 who made that first million.

The cost of having those people soars into the sky and there was no plan for how to manage that growth when it was there and now - because of the logistics of multi-team projects and lack of tooling in place to facilitate all that collaboration you have a dead fish that occasionally pumps out shitty software.

So what went wrong?

Well most companies, I think, do not plan their business for growth and I think it's absolutely necessary to do that. So - here's a few things you should think about before hiring more people or taking on new projects or both.

  • What projects do you have? To hire is to have work for them and a lot of it. People can do an amazing amount of things in 8 hours a day if given the right conditions. You have to commit to having these people - they won't give you any value if you can't provide them work.
  • Do you have the right conditions - can it be that the amount of people you currently have would just as well be able to produce what you have planned for the next year? Are they all working in the same room, do they have the best tools and is their productivity the highest? How often are your programmers in the zone, and if not, why?
  • Adding more people to a project will make collaboration more complicated - have you thought about how you're going to facilitate that collaboration? Is it going to be okay for everyone to be talking all the time about what needs to be done or do you have some IM-tooling in place for that? What about interrupting each other to ask questions and perhaps taking coders out of their zone? What about version control tooling - can coders share code and review work without too much hassle?
  • Is the project you want to hire for actually worth it? Does it fit the portfolio of your company - does it increase the competence of your people and your company? You do not want people doing a little bit of everything averagely, you want them doing their thing - efficiently and with gold nuggets of software coming out the other end.
  • Does your people want to take on this project? You really need to ask them because quality software requires people who care about and own their work.
  • If you take on the project, after all that, can you guarantee that you can deliver on that project on time with high quality and so that it solves the actual problem well. Have you made sure that your existing work force has time to show the new guy the ropes, and they have time to commit to the new project as well. You can't hire guys and dump a new project on them alone, you need to have a plan.
  • If you're adding more people to a project already late, it'll be later - and you'll end up with workforce you don't necessarily need.

Taking on a project - taking new recruits, growth seems to me like a much bigger deal than just saying yes or no.

The kind of developer I want to be

I got out of school a couple of years ago. I had worked some odd summer jobs at that point, but I got into work life almost instantly after that.

My education is in computer technology, so hardware stuff and embedded systems, but I did realize during my time in school that that line of stuff does not interest me. I'd say the annoyance/productivity ratio of that kind of work is just too damn high. 

At my first real work place, I didn't really know what to expect and how to handle myself. I would be given all kinds of work, and I would do it. I'm not the kind of person who takes ages to learn to use a new technology, and I can quickly become very efficient in it.

Lots of talking to my co-workers and hair pulling later, I started to get an idea of what kind of developer I want to be, and what kind of a future I want to build for myself.

I realized, that money is not the factor that keeps me going, in fact it is completely secondary to my work - a bonus. What matters to me far more is to work with like minded people, who aim to do things the right way, effectively and with efficiency. I cannot tolerate half-assedness, I hate when customers are not treated in the best way possible, and the only "reward" I value is getting knowledge and experience in the right things and learning the right way to do things.

When I say right things, I do not think it is worth my time to work with unknown outdated proprietery software by a company that has stopped supporting it ages ago. I want to work with the right tools, and get things done.

When I say learning the way to do things right, I mean not working in a wasteful way. I mean efficiency in everything you do, and rebelling against inefficiency. I also mean gathering enough information to make good decisions, and taking control of your work.

I do not believe in developers that know a little bit of everything, and thinking that that is enough.

I think you have to know exactly what you need to know, which is a little bit of everything, but you also have to specialize - strive to become the best at something. From a company's perspective, this is what should be nurtured, because quality software is developed by those kind of people. 

The best times for me are, when I'm given a software to design, and I lose sleep over designing it in a way that solves all the customer's problems. I want to provide a piece of software, that is elegant and shows craftsmanship, that delivers on solving the actual problem, and actually makes life easier for some. I want to design for the future, provide quality and value. I want to scrutinize over the code that I've done so that I can improve. I want to work in an ecosystem with tooling that promotes all that - especially quality. That's the kind of development I want to do.

If the place I work at is not all that and more, give me a chance, empower me, and I'll make it all happen myself.

“Anything worth doing, is worth doing right.”

 - Hunter S. Thompson