Force .NET application to run in 32bit process

Due to lack of 64 bit version of few COM libararies, we faced a situation to run our AnyCPU application into 32 bit. You can do this either by setting the Platform target or by using the corflags command.

  1. Using Platform target feature. – This is the simple solution, you can change the Platform target settings from Project Properties > Build tab.

    Platform Target settings from Project Properties

    Platform Target settings from Project Properties

    This will cause the compiler to set the 32Bit flag in the CLR header of the corresponding assembly. Every time we run this application no matter on what type of OS it will execute as a 32bit process. But this solution although simple and straight forward was not a viable solution for us since – as mentioned above – we want to have one and only one version of our product. Thus all components of our package have to be compiled with Platform Target set to Any CPU.

    From VS 2011 onwards there is new compiler flag available “Prefer 32-bit”, which will help a .NET application compiled to x86 will fail to run on an ARM Windows system, but an “Any CPU 32-bit preferred” application will run successfully. Also, the “Prefer 32-bit” checkbox is only enabled for .NET 4.5+ executable projects.

  2. Using corflags command – Similar to the above solution, here as well we are setting the CLR header to 32 bit using a tool called corflags – You can find more details about this tool here. To set the 32Bit flag, open the Developer Command prompt, navigate to the directory where your assembly is and use this command.
    CorFlags.exe Sample.exe /32Bit+
    

    You can use this solution as part of the build, so that you can switch to x64 in future, developer don’t need to worry about any platforms.

Happy Programming :)

How extension method works in .Net

What is extension method

Here is the Wikipedia definition – In object-oriented computer programming, an extension method is a method added to an object after the original object was compiled. The modified object is often a class, a prototype or a type. Extension methods are permitted by some object-oriented programming languages. There is no syntactic difference between calling an extension method and calling a method declared in the type definition.

Extension method introduced in .Net Framework 3.0. The implementation is little different in C# and VB.Net. In C# extension method implemented as static methods in static classes, with the first argument being of extended class and preceded by “this” keyword. And in VB.Net extension method are recognized by the presence of the “extension” keyword or attribute. The most common extension methods are the LINQ standard query operators that add query functionality to the existing System.Collections.IEnumerable and System.Collections.Generic.IEnumerable types. To use the standard query operators, first bring them into scope with a using System.Linq directive. Then any type that implements IEnumerable appears to have instance methods such as GroupBy, OrderBy, Average, and so on. You can see these additional methods in IntelliSense statement completion when you type “dot” after an instance of an IEnumerable type such as List or Array.

Here is a simple extension methods, which reverses a string.

class Program
{
    private static void Main(string[] args)
    {
        string name = "dotnetthoughts";
        Console.WriteLine(name.Reverse());
    }
}

static class Extensions
{
    public static string Reverse(this string name)
    {
        var result = string.Empty;
        var chars = name.ToCharArray();
        for (int i = chars.Length - 1; i >= 0; i--)
        {
            result += chars[i];
        }

        return result;
    }
}

If you look into the code, by default string doesn’t have a method like Reverse. And you can find a static class Extensions, which has a Reverse() static method, with the first argument being of extended class and preceded by “this” keyword, it an a extension method for string class. Because of this, compiler will compile the source without any problem.

How it works.

If you look into the IL code generated using IL Disassembler, you can find a type like Extensions which is decorated with ExtensionAttribute, this is the same attribute you need to create an extension method in VB.Net. In C#, if you use this modifier for the first parameter of extension method, compiler will automatically emit ExtensionAttribute for the methods.

Extension Attribute in IL Code

Extension Attribute in IL Code

And in the consuming code, it is like invoking a static method.

IL Main - Invoking static method

IL Main – Invoking static method

General guidelines to implement Extension Methods

  • An extension method will never be called if it has the same signature as a method defined in the type.
  • Extension methods are brought into scope at the namespace level.

Happy Coding

Serializing .NET dictionary

Recently I had to implement XML Serialization in one of my class, it was deriving from base class, which has a dictionary property and XML Serialization was failing due to that. And here is the code snippet which will help you to serialize a .Net dictionary. It is implemented using IXmlSerializable interface

Here is the Unit Tests (It was TDD implementation :))

[TestClass]
    public class SampleTests
    {
        [TestMethod]
        public void TestSampleCanBeSerialized()
        {
            var sample = new Sample();
            sample.Colors = new Dictionary<int, string>();
            sample.Colors.Add(1, "Red");
            sample.Colors.Add(2, "Blue");
            Serialize(sample);
        }

        [TestMethod]
        public void TestSampleIsProperlySerialized()
        {
            var sample = new Sample();
            sample.Colors = new Dictionary<int, string>();
            sample.Colors.Add(1, "Red");
            sample.Colors.Add(2, "Blue");
            var result = Serialize(sample);            
            Assert.IsNotNull(result);
            var newsample = DeSerialize(result);

            Assert.IsNotNull(newsample,"Sample not created");
            Assert.IsNotNull(newsample.Colors,"Couldn't create colors");

            Assert.AreEqual(2, newsample.Colors.Count);
        }

        private static string Serialize(Sample sample)
        {
            using (var stringWriter = new StringWriter())
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(Sample));
                xmlSerializer.Serialize(stringWriter, sample);
                return stringWriter.ToString();
            }
        }

        private static Sample DeSerialize(string text)
        {
            using (var stringReader = new StringReader(text))
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(Sample));
                return xmlSerializer.Deserialize(stringReader) as Sample;
            }
        }

    }
}

Here is the actual implementation.

public class Sample : IXmlSerializable
{
    public Dictionary<int, string> Colors { get; set; }

    public XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(XmlReader reader)
    {
        var xmlDocument = new XmlDocument();
        xmlDocument.Load(reader);
        var colors = xmlDocument.SelectNodes("//Color");
        Colors = new Dictionary<int, string>();
        foreach (XmlNode color in colors)
        {
            Colors.Add(int.Parse(color.Attributes["Key"].Value.ToString()), color.Attributes["Value"].Value.ToString());
        }
    }

    public void WriteXml(XmlWriter writer)
    {
        writer.WriteStartElement("Sample");
        writer.WriteStartElement("Colors");
        foreach (var color in Colors)
        {
            writer.WriteStartElement("Color");
            writer.WriteAttributeString("Key", color.Key.ToString());
            writer.WriteAttributeString("Value", color.Value);
            writer.WriteEndElement();
        }
        writer.WriteEndElement();
        writer.WriteEndElement();
    }
}

Happy Programming :)

Create Custom Configuration Sections in .Net

This post is about creating custom configuration sections in .Net. If you search for this topic in internet, you will find lot of code snippets and blog posts(Here is the MSDN link). Unlike that, this post is about a nice tool, .NET Configuration Code Generator which will help you to generate code for you to create custom configuration section. It is a free, open source tool licensed under Apache License 2.0 (Apache).

.NET Configuration Code Generator

.NET Configuration Code Generator

You can download it from codeplex – http://nconfiggen.codeplex.com/

And once you generate the custom configuration code, you can access it using ConfigurationManager class.

var person = (PersonSection)ConfigurationManager.GetSection("person");
Console.WriteLine(person.FirstName);
Console.WriteLine(person.LastName);

And you need to modify the app.config file to identify the Person section like this. In this ConsoleApplication10.PersonSection is class and ConsoleApplication10 is the assembly, in which class exists. (This is a template I got from the tool)

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="person" type="ConsoleApplication10.PersonSection, ConsoleApplication10"/>
  </configSections>
  <person first-name="Ryan" last-name="James">
    <intelligence>
      <rank value="10" />
      <rating value="Excellent" />
    </intelligence>
    <height value="6.0" tall="true" />
  </person>
</configuration>

And if you want to keep your configuration file out of the app.config / web.config, you can do something like this.

<configuration>
  <configSections>
    <section name="person" type="ConsoleApplication10.PersonSection, ConsoleApplication10"/>
  </configSections>
  <person configSource="Person.config" />
</configuration>

And your Person.config file will look like this.

<?xml version="1.0" encoding="utf-8" ?>
<person first-name="Ryan" last-name="James">
  <intelligence>
    <rank value="10" />
    <rating value="Excellent" />
  </intelligence>
  <height value="6.0" tall="true" />
</person>

Happy Programming :)