Case-insensitive regular expression matching in ADFS claim rules

Today I needed to create a claim rule in ADFS to send certain claims to users depending on their email address. The idea was to prevent people in certain email domains from getting claims they weren’t supposed to have.

I created a claim rule that ran regular expressions against the user’s email address and it worked fine in test, but in production, users were getting claims they weren’t supposed to have! I soon realised the reason: the casing of email addresses in our AD differs drastically. Some are in the form joe.bloggs@contoso.com, while others were john.smith@Contoso.Com. We pretty much found every type of casing possible.

It turns our that by default, regular expression matching in ADFS claims rules is case-sensitive, but it’s easy to switch the matching to case-insensitive using the information in the following Microsoft article:

Microsoft Article – Understanding Claim Rule Language in ADFS

Adding (?i) to the start of the regular expression forces case-insensitive matching, as in Microsoft’s example:

c:[type == "http://contoso.com/email", Value =~ "(?i)bob"] => issue (claim = c);

With this in place, everything worked as expected.

Installing two build agents on TeamCity

Other than jogging my memory in the future when I need to do the same thing again, this post adds no value other than to direct people to Marcos Placona’s great blog post on how to run two build agents on the same TeamCity instance. Unfortunately this doesn’t work out of the box so there is some tweaking involved, as you’ll see.

So, without further ado, over to you Marcos…

http://www.placona.co.uk/1327/technology/new-teamcity-agents-the-right-way/

Help! My Windows desktop is upside down!

Occasionally when I hit a bunch of keys while trying to find those elusive Windows/Visual Studio short-cuts I end up managing to spin the desktop on my PC so that it is either upside down or rotated by 90 degrees. I’m sure this is a useful feature if you want to fix your monitor to a wall or ceiling, but for most users it’s just an annoyance that is hard to get out of if you happen to do it by mistake… unless you’re good at Googling while in the handstand position.

So, if you’re reading this with your head tilted to one side, or indeed in an upside down position, the keys you need to press to get your desktop the right way up again are:

CTRL + ALT + Up Arrow

Using the other arrow keys will rotate your desktop back to less readable configurations.

NHibernate and log4net

Here’s a quick trick for people using NHibernate and log4net within their .NET applications. (…and if you’re not using NHibernate or log4net, you should seriously think about it!)

Add the following to your log4net configuration to find out what’s going on inside NHibernate:

  <logger name="NHibernate">
    <level value="DEBUG" />
  </logger>
  <logger name="NHibernate.SQL">
    <level value="DEBUG" />
  </logger>

As those kind folks at NHibernate have already set up the loggers behind the scenes, everything just works. The SQL logger is especially useful as it’ll show you explicitly which SQL statements are being generated by NHibernate. You can adjust the levels of NHibernate logging independently of your normal application logging, which is useful as the NHibernate logs tend to be pretty verbose.

The full configuration will look something like this:

<log4net>
  <appender name="TraceAppender" type="log4net.Appender.TraceAppender" >
    <layout type="log4net.Layout.PatternLayout">
      <param name="ConversionPattern" value="%d %-5p- %m%n" />
    </layout>
  </appender>
  <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
    <file value="Application.log"/>
    <appendToFile value="true"/>
    <rollingStyle value="Date"/>
    <datePattern value="yyyy-MM-dd'.log'"/>
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"/>
    </layout>
  </appender>
  <root>
    <level value="DEBUG"/>
    <appender-ref ref="TraceAppender"/>
    <appender-ref ref="RollingFileAppender"/>
  </root>
  <logger name="NHibernate">
    <level value="ERROR" />
  </logger>
  <logger name="NHibernate.SQL">
    <level value="ERROR" />
  </logger>
</log4net>

Taking databases offline in SQL Server 2012

Whenever I try and use the Take Offline feature in SQL Server 2012 via SQL Server Management Studio, the progress window hangs, and no matter how long I wait, nothing seems to happens.

I found an alternative way to do this today, which solves the problem nicely. Simply run the following T-SQL:

ALTER DATABASE {DatabaseName} SET OFFLINE WITH ROLLBACK IMMEDIATE

…and the database goes offline, ready for other operations such as database restores to be performed.

Changing the default naming convention for foriegn keys when using Fluent NHibernate

By default, NHibernate will assume that foreign keys should be named using the convention ReferencedTableName_id (e.g. Person_id). I personally don’t like this conversion and would prefer ReferencedTableNameId (e.g. PersonId).

Fortunately, this is pretty easy to achieve by extending the ForeignKeyConvention class in Fluent NHibernate:

using System;
using FluentNHibernate;
using FluentNHibernate.Conventions;

namespace NHibernate.Helpers.Conventions
{
    public class CustomForeignKeyConvention : ForeignKeyConvention
    {
        protected override string GetKeyName(Member property, System.Type type)
        {
            if (property != null)
            {
                return property.Name + "Id";
            }

            if (type != null)
            {
                return type.Name + "Id";
            }

            // If both are null, we throw an exception:
            throw new ArgumentNullException("property", "The property and type parameters cannot both be null");
        }
    }
}

This needs to be wired into your SessionFactory creation code as follows:

sessionFactory = Fluently.Configure()
    .Database(DatabaseConfiguration)
    .Mappings(x => x.FluentMappings.AddFromAssembly(MappingsAssembly))
    .Mappings(x => x.FluentMappings.Conventions.Add(new CustomForeignKeyConvention()))
    .ExposeConfiguration(x => new SchemaUpdate(x).Execute(false, true))
    .BuildSessionFactory();

Note that the example above will also update the database schema.

Once you’ve done that, all foreign keys will use the desired naming convention.

Testing Windows Services with dependency injection

Last year I wrote a post on Testing Windows Services. I pointed out that recompiling and installing your Windows Service following each change is a really inefficient way to develop and test a service. Instead, I suggest that you can run and debug your service in Visual Studio simply by wrapping the service up in a test console application.

I said that I would revisit the post for services using dependency injection, so here goes. Note that the code in this article follows on directly from the code in the previous article, so you’ll need to read the previous article in order for this to make sense!

First, a quick discussion as to how you could add dependency injection to a Windows Service:

I believe the easiest way to use dependency injection in a .NET Windows Service application is to use the dependency injection engine to inject required services into the ServiceBase.Run() method in the Program class for the service:

using System.ServiceProcess;

namespace MyService
{
    public static class Program
    {
        public static void Main()
        {
            var servicesToRun = new[] { (ServiceBase)Injector.Instance.Resolve() };
            ServiceBase.Run(servicesToRun);
        }
    }
}

In order to do this, you simply need to create an empty interface for your service, which the service implements:

namespace MyService
{
    public interface IService
    {
        // No implementation
    }
}
using System.IO;
using System.ServiceProcess;

namespace MyService
{
    public partial class Service : ServiceBase, IService
    {
        public Service()
        {
            InitializeComponent();
        }

        // Service implementation...
    }
}

My original article gave an example of a service which creates and deletes a file when it starts and stops. To complete the example, let’s extract the file interaction code out as a dependency. Here’s the interface:

namespace MyService
{
    public interface IFileCreator
    {
        void Create();
        void Delete();
    }
}

…and here’s the implementation:

using System.IO;

namespace MyService
{
    public class FileCreator : IFileCreator
    {
        public void Create()
        {
            using (var stream = new FileStream("Running", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                using (var writer = new StreamWriter(stream))
                {
                    writer.WriteLine("Running");
                    writer.Flush();
                }
            }
        }

        public void Delete()
        {
            var fileInfo = new FileInfo("Running");
            if (fileInfo.Exists)
            {
                fileInfo.Delete();
            }
        }
    }
}

The injector class for the service would then look something like this:

using Castle.MicroKernel.Registration;
using Castle.Windsor;
using Castle.Windsor.Installer;

namespace MyService
{
    public static class Injector
    {
        private static readonly object InstanceLock = new object();

        private static IWindsorContainer instance;

        public static IWindsorContainer Instance
        {
            get
            {
                lock (InstanceLock)
                {
                    return instance ?? (instance = GetInjector());
                }
            }
        }

        private static IWindsorContainer GetInjector()
        {
            var container = new WindsorContainer();

            container.Install(FromAssembly.This());

            RegisterInjector(container);
            RegisterService(container);
            RegisterFileCreator(container);

            return container;
        }

        private static void RegisterInjector(WindsorContainer container)
        {
            container.Register(
                Component.For()
                .Instance(container));
        }

        private static void RegisterService(WindsorContainer container)
        {
            container.Register(
                Component.For()
                    .ImplementedBy(typeof(Service)));
        }

        private static void RegisterFileCreator(WindsorContainer container)
        {
            container.Register(
                Component.For()
                    .ImplementedBy(typeof(FileCreator)));
        }
    }
}

Note that I’ve wired up both the service (using IService) and my new FileCreator class.

The ServiceWrapper class would be exactly as in the previous example. The only change to the wrapper console application would be to change the Program, as follows:

using System;
using MyService;

namespace MyServiceWrapper
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var serviceWrapper = new ServiceWrapper();

            // Wire up service dependencies here:
            serviceWrapper.FileCreator = Injector.Instance.Resolve();

            try
            {
                serviceWrapper.TestStart();
                Console.ReadLine();
                serviceWrapper.TestStop();
            }
            catch (Exception exception)
            {
                Console.WriteLine("Error: " + exception.Message);
                Console.ReadLine();
            }
        }
    }
}

Unfortunately, in this class I’ve had to wire up all the dependencies in the ServiceWrapper manually as I haven’t found a way to do this automatically. However, this one small pain point is a significant improvement compared to compiling and installing your service each time you make a change!

Removing duplicates with LINQ in C#

Here are a couple of tricks to remove duplication using LINQ.

Firstly, for simple lists:

var numbersWithDuplicates = new[] { "One", "Two", "Two", "Three", "Four" };
var numbers = numbersWithDuplicates.GroupBy(x => x).Select(group => group.First());

…and secondly for more complex objects:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

…you can de-duplicate using any property you like:

var peopleWithDuplicates = new[]
{
    new Person { Id = 2, Name = "Alice", Age = 29 },
    new Person { Id = 1, Name = "Bob", Age = 30 },
    new Person { Id = 3, Name = "Claire", Age = 31 },
    new Person { Id = 4, Name = "Bob", Age = 50 },
};
var people = peopleWithDuplicates.GroupBy(x => x.Name).Select(group => group.First());

Prevent malicious image uploads

If you allow users to upload images to your site, you may be opening up your site to malicious use. This is because particularly cunning hackers can hide commands to do just about anything in the data that makes up the image.

For a great example of an infected image file, see the following page:

http://www.eicar.org/86-0-Intended-use.html

Note that you’ll need to disable your anti-virus if you want to create this file on your computer.

If you allow users to upload this file, it will produce some interesting results!

To prevent the vulnerability (at least when using C#) you simply need to try and load the image data into an Image object. This will throw an exception if the image contains anything nasty. Here is an example:

var image = Image.FromStream(imageDataStream);
using (var memoryStream = new MemoryStream())
{
    image.Save(memoryStream, ImageFormat.Png);
}

Note that you’ll need to load the uploaded data into a stream (imageDataStream in the example above) to get this to work.

Using the Return key with Back and Next buttons on web-sites

When it boils down to it, most sites on the web are just gloried data crunchers. Users enter information, which the system churns up and splits out again at some point in the future, potentially to a different user.

If a site requires a lot of information, it is common to see multistage wizards, with each stage asking for a small portion of the information. Each stage usually has a Back button and a Next button. Convention and common sense dictate that the Back button should be on the left, and the Next button on the right as in the following example:

Type something here:
… and here:

NB: The onclick events return false to prevent the page from actually submitting.

This all seems to works fantastically, and even uses tabindex to ensure that the user tabs onto the Next button before the Back button… until someone comes along that prefers to use the Return key to submit the form, instead of using the mouse or tabbing to the Next button. In this case, the Return key will call the first submit button it can find, which in this case is the Back button. This is not the expected behaviour! Put the cursor in one of the input fields and click Return to see this in action.

One solution to correct this would be to use floats and/or JavaScript to try and reverse the order the buttons are displayed in while still having the Next button placed highest in the HTML to ensure that it would respond to the Return key. However, if a user disables CSS and/or JavaScript this solution will fail. A simpler option is to create a hidden submit button as the first element within the form, which performs the desired Return key operation. The order of any other (visible) buttons on the form is then irrelevant.

The following form demonstrates this:

Type something here:
… and here:

Again, put the cursor in one of the input fields and click Return to see this in action. The only downside to this is that the user will see another submit button if they disable CSS, but in most cases I think it is still the best solution.