Wednesday 23 December 2009

Coding a class so that a dependancy can be easily injected when the class is tested

This is one example of how Dependancy Injection can be used so a dependancy can be mocked whilst the class is tested

public interface IDependancy { }

public class SomeDependancy : IDependancy {}

public class MockDependancy : IDependancy {}

public class SomeClass
{
    private IDependancy dependancy = null;

    public SomeClass()
        : this(new SomeDependancy())
    {
        //  Do some stuff
    }

    // for testing only
    private SomeClass(IDependancy dependancy)
    {
        this.dependancy = dependancy;
    }
}

public class TestSomeClass
{
    public void Test()
    {
        Type t = Assembly.Load(assemblyFullName).GetType(typeName);

        ConstructorInfo ci = t.GetConstructor(
                BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(IDependancy) }, null);

        SomeClass c = (SomeClass)ci.Invoke(new object[] { new MockDependancy() });
           
        // test

    }
}


Catching the real Exception from a method invoke (through reflection)

Sometimes when invoking a method by reflection the method being invoked might throw an exception, but the reflection framework obscures this by wrapping the thrown exception as

   TargetInvocationException 

This is especially annoying if you have unit tests to excersise private methods of an assembly invoked from the test by reflection, you may be wanting to test a specific exception, here's a useful wrapper function to help out here:

        public void ExpectedExceptionMethodInvokeWrapper(object[] invokeParams, object instance, MethodInfo methodToInvoke)
        {
            try
            {
                methodToInvoke.Invoke(instance, invokeParams);

                // Fail: Expected Exception of T
            }
            catch (TargetInvocationException tie)
            {
                if (tie.InnerException is T)
                {
                    throw tie.InnerException;
                }
                else
                {
                    // Fail: Expected Exception of T
                }
            }
            catch
            {
                // Fail: Expected TargetInvocationException, with valid inner exception
            }
        }

Misc stream / string / serialization helpers

Some useful stream / string / serialization helpers

public string GetStringFromStream(Stream str)
{
    string s = null;

    using (StreamReader sr = new StreamReader(str))
    {
        s = sr.ReadToEnd();
    }

    return s;
}

public Stream GetStreamFromString(string s, out string charset)
{
    Stream str = null;
    charset = string.Empty;

    // Write the data to a new stream...
    using (StreamWriter sw = new StreamWriter(new MemoryStream()))
    {
        sw.Write(s);
        sw.Flush();
        sw.BaseStream.Seek(0, SeekOrigin.Begin);
        charset = sw.Encoding.HeaderName;
        str = sw.BaseStream;
    }
    return str;
}

public Stream GetStreamFromObject(object instance)
{
    Stream str = new MemoryStream();
    XmlSerializer xmlz = new XmlSerializer(instance.GetType());
    xmlz.Serialize(str, instance);

    return str;
}

public string SerializeInstance(object instance, Type t)
{
    MemoryStream ms = new System.IO.MemoryStream();
    XmlSerializer xmlz = new XmlSerializer(t);
    xmlz.Serialize(ms, instance);
    ms.Seek(0, SeekOrigin.Begin);

    using (StreamReader sr = new StreamReader(ms))
    {
        return sr.ReadToEnd();
    }
}

public static T DeserializeInstance(string xml)
{
    XmlSerializer xmlz = new XmlSerializer(typeof(T));
    return (T)xmlz.Deserialize(new XmlTextReader(new StringReader(xml)));
}

public static T DeserializeInstance(System.IO.Stream str)
{
    XmlSerializer xmlz = new XmlSerializer(typeof(T));
    return (T)xmlz.Deserialize(str);
}

Biztalk Catalog Explorer (Microsoft.Biztalk.ExplorerOM)

Ships as a dev tool with BTS and useful alternate to WMI, plenty of code example on the net.

Caching using static members

There is an interesting post that has proved useful covering the use of static lists in static class to cache.

   public static partial class Store
   {
        private static StringDictionary cacheCollection;

        // The static constructor is used to load the list, static
        // constructor is called only once
        // If the 'collection' is to be modified after load, 
        // then careful consideration is required around thread safety!
        static Store()
        {
            LoadCacheCollection();
        }

        private static void LoadCacheCollection() {
            
            cacheCollection.Add(...);
            .
            .
            return;
        }

   }

This method could be refactored such that the code required to manage the collection exists in a base assembly and the collection itself and anything specific exists in an assembly inheriting from the base.
Note: A static variable can be copied to an instance variable without extra memory being allocated (i.e. the pointer is moved, without a copy being made).

Monday 21 December 2009

Boiler plater WCF client

using (ServiceHost serviceHost = new ServiceHost(typeof(WcfServiceLibrary1.TestService)))
            {
                // Open the ServiceHost to start listening for messages.
                serviceHost.Open();
                // The service can now be accessed.
                Console.WriteLine("The service is ready.");
                Console.WriteLine("Press  to terminate service.");
                Console.ReadLine();

                // Close the ServiceHost.
                serviceHost.Close();
            }

DCS and XMLS - Serialization quick ref

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Web.Services;

namespace WcfServiceLibrary1
{
    // NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in App.config.
    [ServiceContract(Namespace="http://servicecontract"), XmlSerializerFormat(Style=OperationFormatStyle.Document)]
    public interface ITestService
    {
        [OperationContract]
        //[return: XmlElement(ElementName="MyType", Namespace="http://datacontract", Type= typeof(MyType))]
        MyServiceResponse GetDataUsingDataContract(MyServiceRequest composite);
    }


    /// 
    /// Control WSDL request wrapper
    /// 
    [MessageContract(WrapperNamespace = "http://datacontract")] //IsWrapped defaults to true
    public class MyServiceRequest
    {
        [MessageBodyMember()] 
        public CompositeType compostiteType { get; set; }
    }

    /// 
    /// Control wsdl response wrapper
    /// 
    [MessageContract(WrapperNamespace = "http://datacontract")] //IsWrapped defaults to true
    public class MyServiceResponse
    {
        [MessageBodyMember()]
        public CompositeType compostiteType { get; set; }
    }

    // Composite class for DCS and XMLS
    [DataContract, Serializable, XmlRoot(Namespace = "http://datacontract")] 
    public class CompositeType
    {
        [DataMember, XmlAttribute()]
        public bool BoolValue { get; set; }

        [DataMember, XmlAttribute]
        public string StringValue { get; set; }

        [DataMember, XmlElement]
        public string Description { get; set; }

        // ns required explicitly to ensure each array item has correct ns, but only required if the array item type has a different ns
        // to enclosing type
        [DataMember, XmlArray, XmlArrayItem(typeof(MyType), Namespace = "http://anotherdatacontract")]
        public List TypeList { get; set; }
    }

    /// 
    ///  Decorarated as a type rather than a root object (i.e. lives as a subtype not serialized as an instance directly)
    /// 
    [DataContract, Serializable, XmlType(Namespace = "http://anotherdatacontract")]
    public class MyType
    {
        [DataMember, XmlAttribute]
        public string StringValue { get;set; }
    }


/// Exposed as:
    public class TestService : ITestService
    {
        //[return: XmlElement("MyType", Namespace = "http://datacontract")]
        public MyServiceResponse GetDataUsingDataContract(MyServiceRequest request)
        {
            CompositeType composite = request.compostiteType;
            if (composite.BoolValue)
            {
                composite.StringValue += "Suffix";
                composite.TypeList[0].StringValue += " ... Hello";
                System.Diagnostics.Debug.WriteLine(HRG.Support.Serialisation.Serialise(composite));
            }
            MyServiceResponse resp = new MyServiceResponse();
            resp.compostiteType = composite;
            return resp;
        }
    }

}

Saturday 19 December 2009

vb.net nothing not the same as null

A colleague of ours (Paul) noticed this behaviour in vb recently:

Dim s as string = string.empty
If ( s = nothing ) then
   ' Do something
End if
The condition was met whether s was nothing or empty!

Paul also mentioned that changing the condition to:
If ( s is nothing ) then 
   ' Do something
End if
Which worked as expected - would pass for a null string and fail for an empty string.

We also discussed use of:
IsNullOrEmpty()

...which is a much more convenient method of checking for nothing and empty.

Another colleague Simon noted that he usually uses the (hangover from vb6)
Len()
...function which exhibits the same behaviour as is-null-or-empty!

A bit of digging with reflector and a look at the IL turned up some surprising facts (if the reflected code is to be trusted).

The statement
If ( s = nothing ) Then '(where s is a variable of type string)
End If 
...emits as:
VisualBasic.CompilerServices.Operators::CompareString() 
...Whereas the statement

If (s is nothing) Then
End If
...emits as: ceq – compare equal instruction

Already it’s clear that the “is nothing” statement is preferable in this context (and not just because it works as expected)!

Reflecting Compare-String shed some light on the behaviour (I looked at v8 of this assembly)

(Abridged)


if (Right == null)
{
   if (Left.Length == 0)
   {
     return 0;
   } 
   return 1;
}

Looking at the "len" function and is-null-or-empty confirmed that they do the same thing and should both be the same performance – though I would still use the latter as it’s clearer.


public static int Len(string Expression)
{
    if (Expression == null)
    {
       return 0;
    }
    return Expression.Length;
}

public static book IsNullOrEmpty(string value)
{
    if (value !=null)
    {
        return (value.Length== 0);
    }
    return true;
}