Tag Archives: .net

Hello, Azure Scheduler

The Scheduler is one of the new kids on the block in Azure Land. With Scheduler you can set up triggers for some sort of event in your system. It is currently in preview. I took some time to get to know the basics of it, and I wrote up a three part series of articles. You can find the articles in my company’s blog:

Handling nullables efficiently

I earlier wrote about Handling null checks efficiently by using extension methods to make our code more terse, not cluttered by null check blocks. When we use nullables (Nullable<T>), we come across a similar construction in our code. We have to check if the nullable has a value before accessing the value. If we try to reference the value of a nullable, and it has no value, we get an InvalidOperationException. This is quite similar to getting an NullReferenceException if trying to access a reference which is null.

Let’s take the example code from my previous post, and add an enum for Nationality. Then, we add a Citizenship property with type Nullable<Nationality> to the Person class. Like so:

enum Nationality
{
    No,Se,Dk,Uk,Us
}
internal class Person
{
    public string Name { get; set; }
    public Address Address { get; set; }
    public Nationality? Citizenship { get; set; }
}

If we then create a Person object that has the Citizenship property not set, we get an exception if we try to dereference it:

var person = new Person {Name = "Jackie Chiles"};
Console.Write("Citizenship:");
Console.Write(person.Citizenship.Value);

Handling nullables efficiently

What we can do here, is that we can create an .IfHasValue and .DoIfHasValue extension methods that are analogous to the .IfNotNull and .DoIfNotNull extension methods in the previous blog post:

public static class FlowControlExtensions
{
    [DebuggerStepThrough]
    public static void DoIfHasValue<T>(this T? obj, 
        Action<T> action, bool doContinue = true) where T : struct
    {
        if (obj.HasValue)
        {
            action(obj.Value);
        }
        if (doContinue)
            return;
        ThrowInvalidOperationException<T, T>();
    }
    [DebuggerStepThrough]
    public static TResult IfHasValue<T, TResult>(this T? obj, 
        Func<T, TResult> func, bool doContinue = true, 
        TResult defaultValue = default(TResult)) where T : struct
    {
        if (obj.HasValue)
        {
            return func(obj.Value);
        }
        return doContinue ? defaultValue : 
            ThrowInvalidOperationException<T, TResult>();
    }
    [DebuggerStepThrough]
    private static TResult ThrowInvalidOperationException<T, TResult>()
    {
        throw new InvalidOperationException(string.Format(
            "Tried to access value of nullable of {0}, but it had no value",
                typeof(T).FullName));
    }
}

Now we can use this to prevent our code from throwing an exception, and return a default value instead:

 var person = new Person {Name = "Jackie Chiles" };
 Console.Write("Citizenship:");
 Console.Write(person.Citizenship.IfHasValue(c => c.ToString()));

If we wish to give it another default value, we can simply do this like so:

Console.Write(person.Citizenship
    .IfHasValue(c => c.ToString(), defaultValue: "(unknown)"));

You can find the code on GitHub

Handling null checks efficiently

At the QCon Conference in London in 2009, Sir C.A.R. Hoare apologized for inventing the null reference back in 1965 for the Algol W programming language. He called it his billion-dollar mistake.

Checking for null is one of the constructs that we use very often in our C# code. If we have a lot of them, they tend to clutter our code and make it harder to read and understand the business logic that our code implements. In this post I will use extension methods to make a bit more terse null checks to handle a few different code cases. It is by no means a novel idea, you can find various references on the web. Anyway, let’s give it a try.

Let’s consider this simple object model:

    +--------+    +-----------------+
    | Person |    | Address         |
    |--------|+-->|-----------------|
    | Name   |    | City            |
    +--------+    | PostalCode      |
                  | Street          |
                  | WriteToConsole()|
                  | ToString()      |
                  +-----------------+

We have a Person class which contains a reference to an Address class. When our program are trying to reference properies of the Address objects via the Person object, we have to consider that the reference to the Address object might be null. Here’s an example of what we would start out with:

var person = new Person {Name = "Cosmo Kramer"};
Console.WriteLine("Person: {0}", person.Name);
Console.WriteLine("Address:");
person.Address.WriteToConsole();

Of course, if person.Address is null, this will give us a NullReferenceExecption. So, one way to handle this, is to check for null before calling WriteToConsole, like so:

var person = new Person { Name = "Cosmo Kramer" };
Console.WriteLine("Person: {0}", person.Name);
Console.WriteLine("Address:");
if (person.Address != null)
{
    person.Address.WriteToConsole();
}

This is good, but if we have a lot of such null checks like these, our code will be quite cluttered. One simple solution would be to create an extension method that let us give a code to be called if the object called on is not null. Consider the following method:

public static class FlowControlExtensions
{
    public static void DoIfNotNull<T>(this T obj,
        Action<T> action) where T : class
    {
        if (obj != null)
        {
            action(obj);
        }
    }
}

If we use this new method, our code now looks like this:

var person = new Person { Name = "Cosmo Kramer" };
Console.WriteLine("Person: {0}", person.Name);
Console.WriteLine("Address:");
person.Address.DoIfNotNull(a => a.WriteToConsole());

Then we have a little more terse code. In this example, the execution will continue if the Address property of the person object is null. In some situations, nulls are not acceptable and we would like to throw an exception. For example:

var person = new Person { Name = "Cosmo Kramer" };
Console.WriteLine("Person: {0}", person.Name);
Console.WriteLine("Address:");
if (person.Address != null)
{
    person.Address.WriteToConsole();
}
else
{
    throw new NullReferenceException();
}

One of the annoying things about the standard .NET usage of the NullReferenceException is that it’s error message does not contain any hints about which object was null. Let’s take the opportunity to make it little better. Let’s change our DoIfNotNull method implementation:

public static class FlowControlExtensions
{
    [DebuggerStepThrough]
    public static void DoIfNotNull<T>(this T obj,
        Action<T> action, bool doContinue = true) where T : class
    {
        if (obj != null)
        {
            action(obj);
        }
        if (doContinue) return;
        throw new NullReferenceException(
            string.Format("Reference of type {0} was null.",
                typeof (T).FullName));
    }
}

We have added a default parameter to the method signature. This acts as a flag to set whether or not to continue the execution if null occurs, or throw an exception. Also, we take care to construct the error message so that it gives us the type of the reference being null, which would help us a bit investigating the error. Also note that I added the DebuggerStepThroughAttribute which means that the debugger will not step into this method, so that it will actually stop at the same code line as it would before we introduced our extension method. In the situation that we wish to throw an exception if the reference is null, the example now looks like so:

var person = new Person { Name = "Cosmo Kramer" };
Console.WriteLine("Person: {0}", person.Name);
Console.WriteLine("Address:");
person.Address.DoIfNotNull(a => a.WriteToConsole(), doContinue : false);

This code will now throw an exception with the message “Reference of type Address was null.”

So, now we have the possibility to run any code snippet that fits in an Action<T> if the reference is not null. Let’s try to handle the situation where we wish to evaluate an expression instead. Consider the following example:

var person = new Person { Name = "Cosmo Kramer" };
Console.WriteLine("Person: {0}", person.Name);
Console.WriteLine("Address:");
Console.WriteLine(person.Address.ToString());

The last line in this example will throw a NullReferenceException if the Address property is not set. Again, we will try to handle this situation using an extension method:

public static class FlowControlExtensions
{
    [DebuggerStepThrough]
    public static TResult IfNotNull<T,TResult>(this T obj, 
        Func<T, TResult> func) where T : class
    {
        if (obj != null)
        {
            return func(obj);
        }
        return default(TResult);
    }
}

Notice that if the object reference in fact is null, we return default(TResult) from the extension method. Now, we achieve to make our code run even though we have a null reference:

var person = new Person { Name = "Cosmo Kramer" };
Console.WriteLine("Person: {0}", person.Name);
Console.WriteLine("Address:");
Console.WriteLine(person.Address.IfNotNull(a => a.ToString()));

One improvement we might want to do here, is to make our little program make it explicit if the address is null. Right now, it will only print a blank line. Let’s make a small change to our extension method:

public static class FlowControlExtensions
{
    [DebuggerStepThrough]
    public static TResult IfNotNull<T,TResult>(this T obj,
        Func<T, TResult> func, 
        TResult defaultValue = default(TResult)) where T : class
    {
        if (obj != null)
        {
            return func(obj);
        }
        return defaultValue;
    }
}        

Here we introduced a named parameter which by default is default(TResult). If we wish, we can now override this to give the value returned by the extension method in case of null:

var person = new Person { Name = "Cosmo Kramer" };
Console.WriteLine("Person: {0}", person.Name);
Console.WriteLine("Address:");
Console.WriteLine(person.Address.IfNotNull(a => a.ToString(), defaultValue : "(unknown)"));

Before we call it a day, let’s handle one final scenario. Say that we actually want to sustain the default behavior in case of null, throw a NullReferenceException. This is trivial to do, but let’s take the opportunity to give a more helpful error message than the one we get by default. For this, we will put expression trees to work.

Instead of having our extension method take a Func<T,TResult> parameter, we will make it an Expression<Func<T,Result>>. What we achieve with this is to be able to traverese the expression tree to look for the property or method on the reference being null that we were trying to call. This will give us helpful hints about which object reference was actually null. Also, let’s introduce a parameter that enables us to say that we wish to throw an exception in case of an error. A simple implementation looks like this:

public static class FlowControlExtensions
{
    [DebuggerStepThrough]
    public static TResult IfNotNull<T,TResult>(this T obj, 
        Expression<Func<T, TResult>> func, 
        TResult defaultValue = default(TResult), 
        bool doContinue = true) where T : class
    {
        if (obj != null)
        {
            return func.Compile()(obj);
        }
        if (doContinue) return defaultValue;
        throw new NullReferenceException(
            string.Format("Reference of type {0} was null.",
                typeof (T).FullName));
    }
}

We can now use this method to throw an exception in case of null:

var person = new Person { Name = "Cosmo Kramer" };
Console.WriteLine("Person: {0}", person.Name);
Console.WriteLine("Address:");
Console.WriteLine(person.Address.IfNotNull(a => a.ToString(), doContinue: false));

If the Address property is null, it will throw a NullReferenceException with the message ‘Reference of type Address was null.’.

Handling null checks efficiently-2

Let’s try to see if we can improve the error message to give us a little more information. First, let’s introduce a private class which will traverse the expression tree to look for the method or property referenced:

public static class FlowControlExtensions
{
    private class MemberNameCollector : ExpressionVisitor
    {
        public string MemberName = "Unknown";
        private readonly string _parameterName;
        public MemberNameCollector(string parameterName)
        {
            _parameterName = parameterName;
        }
        protected override Expression VisitMethodCall(MethodCallExpression node)
        {
            if (node.Object != null 
                && node.Object.NodeType == ExpressionType.Parameter
                && _parameterName == node.Object.ToString())
            {
                MemberName = node.Method.Name + "(...)";
            }
            return base.VisitMethodCall(node);
        }
        protected override Expression VisitMember(MemberExpression node)
        {
            if (node.NodeType == ExpressionType.MemberAccess 
                && node.Expression.ToString() == _parameterName)
            {
                MemberName = node.Member.Name;
            }
            return base.VisitMember(node);
        }
    }
}

We can now use this class to alter the implementation of our IfNotNull extension method:

public static class FlowControlExtensions
{
    [DebuggerStepThrough]
    public static TResult IfNotNull<T,TResult>(this T obj,
        Expression<Func<T, TResult>> func, 
        TResult defaultValue = default(TResult), 
        bool doContinue = true) where T : class
    {
        if (obj != null)
        {
            return func.Compile()(obj);
        }
        if (doContinue) return defaultValue;
        var parameterName = func.Parameters.First().Name;
        var parameterType = typeof (T).FullName;
        var visitor = new MemberNameCollector(parameterName);
        visitor.Visit(func.Body);
        throw new NullReferenceException(
            string.Format("Tried to reference .{0} on parameter with name '{1}' of type {2}, but it was  null",
            visitor.MemberName, parameterName, parameterType));
    } 
}

We now get a little more information in our NullReferenceException message stating “Tried to reference .ToString(…) on parameter with name ‘a’ of type Address, but it was null”. A little more helpful…

Handling null checks efficiently-3

Summary

We have used extension methods to handle several null handling situations in a terse way. Here’s what we have covered:

person.Address.DoIfNotNull(a => a.WriteToConsole()); Runs a statement. Continue execution in case of null.
person.Address.DoIfNotNull(a => a.WriteToConsole(), doContinue : false); Runs a statement. Throws a NullReferenceException in case of null. Somewhat improved exception message compared to OOTB.
person.Address.IfNotNull(a => a.ToString()); Evaluates an expression. Returns default(T) in case of null.
person.Address.IfNotNull(a => a.ToString(), defaultValue : "(unknown)"); Evaluates an expression. Returns "(unknown)" in case of null.
person.Address.IfNotNull(a => a.ToString(), doContinue: false); Evaluates an expression. Throws a NullReferenceException in case of null. Improved exception message compared to OOTB.

If you want to try this out yourself, it is quite straightforward to copy and paste the code. You can also find the example code on GitHub.

Running chocolatey behind an authenticating firewall

I long grappled with a problem installing applications using chocolatey. Specifically, all installations that required downloading an MSI (or similar) file outside the .nupkg caused the following error message:

The remote server returned an error: (407) Proxy Authentication Required.

Yes, I am behind a firewall that requires authentication. I found several references to this error message on the chocolatey forums, but they all seemed to be fixed in the latest chocolatey version.

Through some googling I was able to track down the problem. Acutally, it is a problem with the .NET 3.5 runtime that causes the System.Net.WebClient to give up on an NTLM authentication challenge from proxies. Chocolatey uses Powershell, and indeed the System.Net.WebClient to download installation packages (all though not the package manifest itself, where it uses NuGet). As you my or may not know, Powershell uses the .NET 3.5 runtime per default.

Hence, the fix was to make Powershell use the .NET 4.0 runtime, where this bug is fixed. I figured out how to do this based on this entry on stackoverflow.

I then wrote this little Powershell snippet which changes Powershell on my machine to use .NET 4.0 instead of .NET 3.5:

if ([Environment]::Version.Major -lt 4) {
	$configFile = Join-Path $PSHOME -ChildPath '.powershell.exe.config'
	if (-not(Test-Path $configFile)) {
		@'
<?xml version="1.0"?>
<configuration>
  <startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0.30319" />
    <supportedRuntime version="v2.0.50727" />
  </startup>
</configuration>
'@ | Out-File -FilePath $configFile -Encoding UTF8
		"Created $configFile"
	}
	'Restart powershell in order to make it run in .NET 4'
}

Getting user information programmatically from Windows Identity Foundation

You can use the Windows Identity Foundation SDK to replace the authentication scheme of your ASP.NET web application. Most notably, this is useful for making your application claims-aware, which allows it to seamlessly play together with solutions like Active Directory Federation Services or the Windows Azure AppFabric Access Service. This is useful for a various number of SSO and federated authentication scenarios.

Basically, what you do is that you switch off the built-in authentication in ASP.NET like forms-based authentication, and let WIF act as a proxy in front of your application. WIF uses the authorization settings in web.config (/configuration/system.web/authorization and /configuration/location/system.web/authorization elements) and authenticates the user before the ASP.NET application receives the request. See WS-Federated Authentication Module Overview for details

So, when the application receives the request, the user is already authenticated, which is fine. However, there are times when the application needs to know who the user is, or getting access to the other claims that were provided from the identity service. Luckily, this is available on the HTTP context. Say, for instance, if you wish to find the email address of the logged-in user, you can do it like so:

protected void Page_Load(object sender, EventArgs e)
{
    var claimsIdentity = Context.User.Identity as IClaimsIdentity;
    foreach (var claim in claimsIdentity.Claims)
    {
        if (claim.ClaimType == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress")
        {
            var email = claim.Value;
        }
    }
}

If the user was authenticated using claims, Context.User.Identity will be an IClaimsIdentity which will contain a number of claims about the user. We can then iterate over these claims to find the one that we want.

The claim types are denoted using XML namespaces, which are a little bit cumbersome to work with. So, to make it easier to access, we iterate over the list of claims, and make all the claims available on a common object:

public static class IdentityExtension
{
    public static DynamicUser GetUserFromClaims(this HttpContext context)
    {
        var claimsIdentity = context.User.Identity as IClaimsIdentity;
        if (claimsIdentity == null) throw new FailedAuthenticationFaultException();
        return new DynamicUser(claimsIdentity.Claims);
    }
}
public class DynamicUser : DynamicObject
{
    private readonly ClaimCollection _claims;
    public DynamicUser(ClaimCollection claims)
    {
        _claims = claims;
        Id = ClaimsValue("nameidentifier")[0];
    }
    public string Id { get; private set; }
    public bool IsInRole(string role)
    {
        return ClaimsValue("role").Any(c => c.Equals(role, StringComparison.OrdinalIgnoreCase));
    }
    private string[] ClaimsValue(string claimSuffix)
    {
        return _claims.Where(c => c.ClaimType.EndsWith(claimSuffix)).Select(c => c.Value).ToArray();
    }
    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        var claimValue = ClaimsValue(binder.Name.ToLowerInvariant());
        if (claimValue.Length == 0)
        {
            return base.TryGetMember(binder, out result);
        }
        if (claimValue.Length == 1)
        {
            result = claimValue[0];
        }
        else
        {
            result = claimValue;
        }
        return true;
    }
}

Then, we can access the claim values using a prefix of the actual XML namespace of the claim type:

protected void Page_Load(object sender, EventArgs e)
{
    var user = Context.GetUserFromClaims();
    var id = user.Id;
    var username = user.Name; // "John Doe"
}

When hooking up the application to Windows Azure AppFabric Access Control Service (ACS), which claims that the application will receive depends on your rule group configuration. Here are some examples:

Claim type Shorthand Example value
http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier user.Id NHsTR1UXFI9xYk1xIRUNfucZ4/a5OWiILHlNyNEXozP=
http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name user.Name John Doe
http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress user.Emailaddress john.doe@hotmail.com

If you set up role claim rules in ACS, you can even get information about the user’s roles so that you can do authorization in the code:

protected void Page_Load(object sender, EventArgs e)
{
    var user = Context.GetUserFromClaims();
    var isAdmin = user.IsInRole("administrator"):
}

More on XML parsing using XmlSerializer

In my previous post, I talked about how we could use System.Xml.Serialization.XmlSerializer and System.Runtime.Serialization.DataContractSerializer to parse XML into an object tree. I pointed out that DataContractSerializer in my mind has some advantages in that types, properties, and members to use with the deserialization do not need to be public. On the downside, DataContractSerializer puts a quite limiting constraint on the XML format in that it cannot parse XML attributes. This is as far as I know, an absolute constraint that cannot easily be circumvented. Thus, regrettably, if we are not in control of the XML format, DataContractSerializer is sometimes useless.

In those situations, we can still use XmlSerializer. In order to achieve the same encapsulation with XmlSerializer, we have to adjust our model a bit. Here’s one suggestion on how to do this:

My approach to this is inspired by Josh Bloch‘s Builder pattern. The idea is changing the classes used for deserialization from being domain objects to being builder objects that build domain objects. This has another advantage in that our domain objects are not “polluted” with attributes and interfaces related to deserialization and are 100% plain old CLR objects (POCOs). So, lets first do a change our “deserialization” class (formerly ‘Country’) to a builder object, like so:

public class CountryBuilder
{
   [XmlElement(ElementName = "name")]
   public string Name;

   [XmlElement(ElementName = "iso-3166-alpha-2-code")]
   public string Code;

   public Country Build()
   {
      return new Country(Name, Code);
   }
}

Note here that our builder object has a Build() method which returns the domain object ‘Country’. This is the object that we will pass on to our clients. The Country class now represents our domain object:

public class Country
{
   private readonly string _name, _code;
            
   internal Country(string name, string code)
   {
      _name = name;
      _code = code;
   }

   public string Name { get { return _name; } }
   public string Code { get { return _code; } }
}

We have now restricted access to the creation of Country objects in that the constructor is internal, and it is also immutable (cannot change state once created) though making its fields readonly. It only exposes getters for its internal state. We can then do the same to our list of countries. The builder object for countries would look like this:

[XmlRoot("countries")]
public class Countries
{
   [XmlElement(ElementName="country")]
   public CountryBuilder[] countries;

   public IEnumerable<Country> Build()
   {
      return countries.Select<CountryBuilder , Country>(x => x.Build());
   }
}

The code for doing the serialization will then look like this:

string xml = ...;
XmlSerializer xmlSerializer = new XmlSerializer(typeof(CountriesBuilder));
var builder = xmlSerializer.Deserialize(new StringReader(inputXml)) as CountriesBuilder;
IEnumerable<Country> cs = builder.Build();

What we have achieved now is that we now can control the accessibility and encapsulation of our domain model. The builder objects are still public to anyone, but that really does not matter much in my mind. Thus, a relatively swift parsing of XML of various formats into a well designed object model.

Parsing XML using XmlSerializer or DataContractSerializer

If you want to parse XML in .NET, you have a lot of options to choose from. You can use XmlDocument to parse the XML into a DOM tree, you can use the XmlReader to write an efficient “pull” parser, or you can leverage some of the features provided with various serialization APIs.

Given the case where you have a fairly straightforward XML document (not too deep document tree, not too complex set of attributes and elements) that maps pretty well to your domain model, the serialization options is in my mind a good choice that requires little coding. Compared with this approach, using XmlDocument seems to be a bit of an overkill if you don’t need advanced traversal of the document, and writing a parser by hand using XmlReader seems to require quite a bit of coding.

So, given the following sample XML document, I will investigate the serialization options:

<countries>
   <country>
      <iso-3166-alpha-2-code>AF</iso-3166-alpha-2-code>
      <name>Afghanistan</name>
   </country>
   <country>
      <iso-3166-alpha-2-code>AX</iso-3166-alpha-2-code>
      <name>Åland Islands</name>
   </country>
   <country>
      <iso-3166-alpha-2-code>AL</iso-3166-alpha-2-code>
      <name>Albania</name>
   </country>
</countries>

Using System.Xml.XmlSerializer

The first option that came to mind, was to use the XmlSerializer object to deserialize the XML into C# (or VB for that matter) objects. It first requires that I annotate my object model in order to tell the serializer how to deserialize the XML:

[XmlRoot("countries")]
public class Countries
{
   [XmlElement(ElementName="country")]
   public Country[] countries;
}

public class Country
{
   [XmlElement(ElementName = "name")]
   public string Name;

   [XmlElement(ElementName = "iso-3166-alpha-2-code")]
   public string Code;
}

Then, I can use the serializer to deserialize the code:

string xml = ...;

XmlSerializer xmlSerializer = new XmlSerializer(typeof(Countries));
Countries c = xmlSerializer.Deserialize(new StringReader(xml)) as Countries;

Pretty sweet,  heh? Definitely. However, this has some drawbacks. If I want my Country class to be a well designed domain object that follows good OO design principles, I probably would like to encapsulate my data. Furthermore, I might want to restrict the creation of such objects from other parts of the code. In order for XmlSerializer to create my object, it requires that my types are public and that all properties or fields to set are public as well. What to do if I want to enforce my objects to be immutable once handed off to other parts of the code?

Using System.Runtime.Serialization.DataContractSerializer

Luckily, the serialization API that come with Windows Communication Framework has some neat features that fit like a glove. When defining my data model, it does not require that the types, neither the properties nor fields to set are public. Actually, I can restrict access to the type, its default constructor, and any of the properties or fields that I want to be deserialized! w00t!

So, this is what the Country class will looks like:

[DataContract(Name="country", Namespace="")]
internal class Country : IExtensibleDataObject
{
   private Country() { }

   [DataMember(Name="name")]
   public string Name { get; private set; }

   [DataMember(Name = "iso-3166-alpha-2-code")]
   public string Code { get; private set; }

   public ExtensionDataObject ExtensionData { get; set; }
}

The XML file contains a list of countries, and luckily, we have the CollectionDataContractAttribute to denote an element that is a list of elements. It supports generics, so that we can define our class as a strongly typed list:

[CollectionDataContract(Name="countries", Namespace="")]
internal class Countries : List<Country>, IExtensibleDataObject
{
   public ExtensionDataObject ExtensionData { get; set; }
}

And that’s it. Now we can deserialize:

string xml = ...;

DataContractSerializer ser = new DataContractSerializer(typeof(Countries));
using (StringReader stringReader = new StringReader(xml))
{
   using (XmlReader xmlReader = XmlReader.Create(stringReader))
   {
      Countries countries = (Countries)ser.ReadObject(xmlReader);
   }
}

Alternatively, our result could be typed as a list of countries:

IList<Country> countries = (IList<Country>)ser.ReadObject(xmlReader);

Note that there is a limitation in the latter method in that deserializing XML attributes is not supported. Thus, an XML document like the following would not work:

   <country iso-3166-alpha-2-code="AF">
      <name>Afghanistan</name>
   </country>
   <country iso-3166-alpha-2-code="AX">
      <name>Åland Islands</name>
   </country>
   <country iso-3166-alpha-2-code="AL">
      <name>Albania</name>
   </country>
</countries>

This will, however, work using the XmlSerializer.

Spring.NET: programatically add objects to the existing (XML) application context

My experience is that Spring.NET configuration files tend to grow very large. As far as I can figure, there are two principal problems that arise from this:

  1. The configuration files get difficult to read and maintain
  2. It gets easier to introduce errors in the configuration because of its size

In general, I am in favour of keeping configuration files as small as possible. I often work with web applications that can (quite) easily be redeployed to the production environment, hence I always ask the question “will this value ever change between environments or deployments” when considering introducing a new configuration part.

Now, the Spring XML configuration usually serves two main purposes; to wire together the application, and to provide values that should be possible to change between deployments of the application or for different environments. The first purpose, I would argue does not necessarily need to be in the XML configuration. Rather, if this is done in code, we get the benefit that the compiler will tell us right away if there are typos or missing references. If this wiring is in the XML configuration file, such errors will not surface until the application starts.

So, the question that I had, was how Spring context wiring could be combined in code and in XML. I found one way of doing it, but it is only applicable to singleton objects.

Say, for instance that we have an object “something” that we wish to have configured in XML:

  <object id="something" type="SpringTest.Something, SpringTest" singleton="false"/>

Then, we have a class that we want to initialize in code:

class Foo
{
    public Foo() { }
    private Something _s;
    Something S
    {
        set { _s = value; }
        get { return _s; }
    }
}

Now, we see that Foo has a dependency on Something; it needs an instance of Something to be injected. We can use the Spring context to do this after we have created the instance of Foo:

IApplicationContext context = ContextRegistry.GetContext();
Foo f = new Foo();
context.ConfigureObject(f, "fooPrototype");

But Spring does not yet know that the Foo instance needs to be injected Something. Hence, we need to tell Spring that by creating what I would call a “prototype” or “template” object configuration:

<object id="fooPrototype" type="ContextTestProject.Foo, ContextTestProject">
   <property name="S" ref="something"></property>
</object>

The final step is then to register our newly created object in the Spring context:

XmlApplicationContext xmlContext = context as XmlApplicationContext;
xmlContext.ObjectFactory.RegisterSingleton("foo", f);

After this, the Foo instance is available for the application in the Spring context.

Internet Explorer automation/Watin: catching navigation error codes

One question have troubled me for some time when automating Internet Explorer (actually, I am doing web testing with Watin): how to test for HTTP status codes. Finally, I figured out how to do this. The lies in an event that the InternetExplorer object raises when navigation is unsuccessful.

I ended up with writing a C# helper class:

using System.Net;
using WatiN.Core;
using SHDocVw;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Globalization;
namespace Test
{
    public class NavigationObserver
    {
        private HttpStatusCode _statusCode;
        public NavigationObserver(IE ie)
        {
            InternetExplorer internetExplorer = (InternetExplorer)ie.InternetExplorer;
            internetExplorer.NavigateError += new DWebBrowserEvents2_NavigateErrorEventHandler(IeNavigateError);
        }
        public void ShouldHave(HttpStatusCode expectedStatusCode)
        {
            if (!_statusCode.Equals(expectedStatusCode))
            {
                Assert.Fail(string.Format(CultureInfo.InvariantCulture, "Wrong status code. Expected {0}, but was {1}",
                    expectedStatusCode, _statusCode));
            }
        }
        private void IeNavigateError(object pDisp, ref object URL, ref object Frame, ref object StatusCode, ref bool Cancel)
        {
            _statusCode = (HttpStatusCode)StatusCode;
        }
    }
}

Note that I use Visual Studio test runner to run my web tests. Then, I can use this in my test:

using (IE ie = new IE())
{
    NavigationObserver observer = new NavigationObserver(ie);
    ie.GoTo("http://some.where.com");
    observer.ShouldHave(HttpStatusCode.NotFound);
}