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 :)

Explicit Interface Implementation in C#

If a class implements two interfaces that contain a member with the same signature, then implementing that member on the class will cause both interfaces to use that member as their implementation.

class Sample : ISample, ISample2
{
    //Both ISample and ISample2 will call this method.
    public int Add(int a, int b)
    {
        return a + b;
    }
}

interface ISample
{
    int Add(int a, int b);
}

interface ISample2
{
    int Add(int a, int b);
}

If the two interface members do not perform the same function, however, this can lead to an incorrect implementation of one or both of the interfaces.

Explicit Interface Implementation

Explicit Interface Implementation

It is possible to implement an interface member explicitly – creating a class member that is only called through the interface, and is specific to that interface. This is accomplished by naming the class member with the name of the interface and a period.

class Sample : ISample, ISample2
{
    public int Add(int a, int b)
    {
        return a + b;
    }

    int ISample2.Add(int a, int b)
    {
        return a + b + 10;
    }
}

The class member ISample2.Add only available via ISample2 interface, not available through class instance.

var sample = new Sample();
var result = sample.Add(10, 20);
Console.WriteLine(result);  //Will return 30

ISample2 sample2 = new Sample();
var result2 = sample2.Add(10, 20);
Console.WriteLine(result2);  //Will return 40

Explicit implementation is also used to resolve cases where two interfaces each declare different members of the same name such as a property and a method.

Points of interest.

  • Solves the diamond problem – The “diamond problem” (sometimes referred to as the “deadly diamond of death”[6]) is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If there is a method in A that B and/or C has overridden, and D does not override it, then which version of the method does D inherit: that of B, or that of C?
  • Improves design – always promotes “Program to interface not implementation” design technique
  • Explicit Interface Implementations are not overridable and cannot be made virtual.
  • Avoid implementing interface members explicitly without having a strong reason to do so. – Understanding explicit implementation requires an advanced level of expertise. For example, many developers do not know that an explicitly implemented member is publicly callable even though its signature is private. Because of this, explicitly implemented members do not appear in the list of publicly visible members. Explicitly implementing a member can also cause unnecessary boxing of value types.
  • Cleaner code / Refactoring is safer – There will be a compiler error if the an interface method is removed in case of explicit interface implementation, however if you implement the method implicitly you can end up with unused ‘orphaned’ public methods.

Do we require Explicit Interface Implementation always? / Should we enforce it as best practice? – Not always, for me it is complicated and confusing. If you found a library from nuget and will check which all interfaces available in it or will you check available public methods in it? Again it is subjective, as MSDN recommends – Avoid implementing interface members explicitly without having a strong reason to do so. If you are developing a framework, I will not recommend explicit interface implementation.

Happy Coding :)

CreateObject equivalent for C#

In current project, I had to use some 3rd party APIs, which is exposed via COM Interop. I found some VB.Net code to consume, but I couldn’t find in C# implementation for the same. Here is the code snippet which is equivalent VB.Net CreateObject method.

var txt = "HelloWorld";
var type = Type.GetTypeFromProgID("vbscript.regexp");
dynamic vbScriptRegEx = Activator.CreateInstance(type);
vbScriptRegEx.Pattern = "l";
Console.WriteLine(vbScriptRegEx.Replace(txt, "##"));

You may get some other errors, if your platform / platform target is different from the COM object compiled platform.

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 :)