August 16, 2008

Enums

See this blog entry for information and example on the use of DescriptionAttribute with Enums

This example uses an ComboBox to store the enumeration values as strings Preparing the Combobox
foreach (XXXEnum entry in Enum.GetValues(typeof(XXXEnum)))
    comboBox.Items.Add(entry);
OR
cbLoggingLevel.Items.AddRange(Enum.GetValues(typeof(XXXEnum)));

// Making an initial selection
comboBox.SelectedIndex = comboBox.Items.Count - 1; // Select the last one
OR
comboBox.SelectedIndex = 0; // Select the first
Converting to and from a string
//To convert an enum to a string use:
MyComboBox.SelectedItem = m_Object.XXXEnum .ToString();

//The reverse process is a little more complicated
XXXEnum gc = (XXXEnum ) Enum.Parse(typeof(XXXEnum ),
                        MyComboBox.SelectedItem.ToString(), true);
There is a better way to parse the enum from a string that I found here.:
public static class StringExtender
{
  public static TEnum ParseToEnum<TEnum>(this string name)
    where TEnum : struct
  {
    if (false == typeof(TEnum).IsEnum)
      throw new NotSupportedException(typeof(TEnum).Name + " must be an Enum");

    string trimmed = name.Trim();
    
    if (false == Enum.IsDefined(typeof(TEnum), trimmed))
      throw new ArgumentException(string.Format(
         "\'{0}\' is not defined in type of enum {1}", trimmed, typeof(TEnum).Name));

    return (TEnum)Enum.Parse(typeof(TEnum), trimmed);
  }
}
alternatively use the TryParse method.
public class EnumTester
{
  public enum DescriptionsEnum
  {
    None,
    AddOn,
    SnapOn,
    Adjacent,
    Fixed,
  };

  public void ParseEnumFromStringTest()
  {
    DescriptionsEnum test = DescriptionsEnum.None;
    test = StringExtender.ParseToEnum<DescriptionsEnum>("Adjacent");
    Debug.Assert(test == DescriptionsEnum.Adjacent);
    test = "Fixed".ParseToEnum<DescriptionsEnum>();
    Debug.Assert(test == DescriptionsEnum.Fixed);
    test = "   SnapOn  ".ParseToEnum<DescriptionsEnum>();
    Debug.Assert(test == DescriptionsEnum.SnapOn);
    //test = "      snapon    ".ParseToEnum<DescriptionsEnum>(); // FAILS!
    //Debug.Assert(test == DescriptionsEnum.SnapOn);

    bool success = Enum.TryParse<DescriptionsEnum>("Adjacent", out test);
    Debug.Assert(test == DescriptionsEnum.Adjacent);
    success = Enum.TryParse<DescriptionsEnum>("fixed", true, out test);
    Debug.Assert(test == DescriptionsEnum.Fixed);
    success = Enum.TryParse<DescriptionsEnum>("  fixed     ", true, out test);
    // Line below succeeds. - TryParse is more robust so use it instead!
    Debug.Assert(test == DescriptionsEnum.Fixed); 
  }
}

Iterating through enumerated types:
foreach (XXXEnum entry in Enum.GetValues(typeof(XXXEnum)))
{
    Debug.WriteLine(entry.ToString() + "=" + ((int)entry).ToString());                
}
See Flags Based Enumerated Types

Color

To create a color with a given RGB value use
Color color = Color.FromRGB(0xf1, 0xee, 0x45);
//otherwise
Color.Red, ...

Random Number Generator

Random class in .Net is part of System namespace
//Declare an object
Random randomNumberGenerator = new Random();
random.NextDouble() //to get the next random number between 0.0 and 1.0;
random.Next() // to get the next random positive integer number
// to get the next random integer, x where  'upper' <= x  < 'lower'
random.Next(lower, upper) 
Byte[] b = new Byte[10];
random.NextBytes(b); to set an array of bytes

//To set a seed for the random number generator
int seed = 137;
System.Random randomNumberGenerator = new System.Random(seed);

August 10, 2008

Ownerdraw ListView

Msdn: On Msdn Find this article with Google TODO: Add our code here

Standard Delegates And Events

Standard event handler, no delegate definition necessary.
public event EventHandler xxxChanged;
Standard delegate handler, no delegate definition necessary.
using System;
//public delegate void Action()
Action xxxDelegate = new Action(xxxMethod);

public delegate TResult Func()
//Use it with anonymous methods:
Func methodCall = delegate() { return xxx.MethodReturningABool(); };
//There are other Func overloads, eg:
//public delegate TResult Func()
Func convert = delegate(int s)
         { return i.ToString() }; 

OR
// definition: public delegate void MethodInvoker()
using  System.Windows.Forms;
...
MethodInvoker xxxDelegate = new MethodInvoker(xxxMethod);

Loading Objects Using Reflection

This helper class loads a bunch of objects from assemblies found in the specified search path. The objects must support an interface of the given type eg usage. List<ISomeInterface> plugIns = PluginHelper.LoadPlugins <ISomeInterface>(@".\");
class PluginHelper
{

  // Loading a bunch of objects dynamically using reflection
  // In this case the type parameter specifies an interface for
  // an object with a public default constructor
  public static IList<INTERFACE> LoadPlugins<INTERFACE>(
         string searchPath)
  //where INTERFACE :  // (only reference types)
  {
    List<INTERFACE> objList = new List<INTERFACE>();

    string[] files = Directory.GetFiles(searchPath, "*.dll");
    foreach (string file in files)
    {
      try
      {
        Assembly assembly = Assembly.LoadFrom(file);
        foreach (Type type in assembly.GetTypes())
        {
          if (!type.IsClass || type.IsNotPublic) continue;
          Type[] interfaces = type.GetInterfaces();
          if (((IList<Type>)interfaces).Contains(typeof(INTERFACE)))
          {
            try
            {

              // Find the default constructor
              ConstructorInfo conInfo = type.GetConstructor(new Type[0]);
              bool hasPublicDefaultConstructor = ((conInfo != null) &&
                  ((conInfo.Attributes | MethodAttributes.Public) > 0));
              if (hasPublicDefaultConstructor)
              {
                object obj = Activator.CreateInstance(type);
                INTERFACE instance = (INTERFACE)obj;
                Debug.Assert(instance != null);
                objList.Add(instance);
              }
              else
              {
                Trace.WriteLine("LoadPlugins<INTERFACE>() - Can not create the type \'" +
                    type.ToString() + "\' in assembly \'" + file +
                    "\' as it does not have a public default constructor");
              }
            }
            catch (Exception ex)
            {
              Trace.WriteLine("Exception occurred creating an instance of \'" +
                  type.ToString() + "\' from assembly \'" + file + "\'");
            }

          }

        }
      }
      catch (Exception ex)
      {
        Trace.WriteLine("Exception occurred trying to load from assembly \'" +
            file + "\'");
      }
    }
    return objList;
  }

}

Xml Serialisation/Deserialisation

A simple helper class
using System.Xml.Serialization;

...
public static class XmlSerializationHelper
{

    // Serialize the given type (only reference types) to an Xml string
    // Catches any exceptions
    // Eg:
    // string xmlString = SerializationHelper.SerializeToXml<MyClass>(myClass);      
    public static string TrySerializeToXml<T>(this T targetObj, params Type[] extraTypes)
        where T : class // (only reference types)
    {
        string res = string.Empty;
        try
        {
            StringBuilder builder = new StringBuilder();
            XmlSerializer xmlSerializer = new XmlSerializer(typeof (T), extraTypes);
            xmlSerializer.Serialize(new StringWriter(builder), targetObj);
            res = builder.ToString();
        }
        catch (Exception ex)
        {
            Trace.WriteLine("SerializationHelper.SerializeToXml<T>: " +
                            "Exception occurred during deserialization " + ex.ToString());
            Debug.Assert(false, "Exception occurred during serialization " +
                                ex.ToString());
        }
        return res;
    }


    // Deserialize the given type (only reference types) from an Xml string
    // Eg:
    // MyClass myObj = SerializationHelper.DeserializeFromXml<MyClass>
    //(xmlString);
    public static T TryDeserializeFromXml<T>(this string xml, params Type[] extraTypes)
        where T : class // (only reference types)
    {
        T obj = null;
        try
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof (T), extraTypes);
            obj = (T) xmlSerializer.Deserialize(new StringReader(xml));
        }
        catch (Exception ex)
        {
            Trace.WriteLine("SerializationHelper.DeserializeFromXml<T>: " +
                            "Exception occurred during deserialization " + ex.ToString());
            Debug.Assert(false, "Exception occurred during deserialization " +
                                ex.ToString());
        }
        return obj;
    }


    // Serialize the given type (only reference types) to an Xml filePath
    public static void TrySerializeToXmlFile<T>(this T targetObj, 
        string filePath, params Type[] extraTypes)
        where T : class // (only reference types)
    {
        try
        {
            using (TextWriter tw = new StreamWriter(filePath))
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof (T), extraTypes);
                xmlSerializer.Serialize(tw, targetObj);
                tw.Close();
            }
        }
        catch (Exception ex)
        {
            Trace.WriteLine("SerializationHelper.SerializeToXml<T>: " +
                            "Exception occurred during deserialization " + ex.ToString());
            Debug.Assert(false, "Exception occurred during serialization " +
                                ex.ToString());
        }
    }


    // Deserialize the given type (only reference types) from an Xml filePath
    public static T TryDeserializeFromXmlFile<T>(FileInfo file, params Type[] extraTypes)
        where T : class // (only reference types)
    {
        T obj = null;
        try
        {
            using (Stream fs = new FileStream(file.FullName, FileMode.Open))
            {
              // Use an XmlReader as according to the MSDN documentation it
              // "automatically detects and uses the encoding specified by 
              // the XML document."
              using (XmlReader xmlReader = new XmlTextReader(fs))
              {
                 XmlSerializer serializer = new XmlSerializer(typeof (T), extraTypes);
                 obj = (T) serializer.Deserialize(xmlReader);
              }
            }  
            //using (TextReader tr = new StreamReader(file.FullName))
            //{
            //    XmlSerializer serializer = new XmlSerializer(typeof (T), extraTypes);
            //    obj = (T) serializer.Deserialize(tr);
            //    tr.Close();
            //}
        }
        catch (Exception ex)
        {
            Trace.WriteLine("SerializationHelper.TryDeserializeFromXmlFile<T>: " +
                            "Exception occurred during deserialization " + ex.ToString());
            Debug.Assert(false, "Exception occurred during deserialization " +
                                ex.ToString());
        }
        return obj;
    }


}

Using this XmlSerialiser/Deserialiser sample
class XmlSerialiserDeserialiserTester
{
  public void TestTaskSerialisation()
  {
    string testPath = Path.Combine(Path.GetTempPath(), "TestSerializer.xml");

    TaskManager tm = new TaskManager();
    tm.Add(new Task { When = Task.WhenEnum.Fortnight, Displayable = true, 
        Description = "Buy water proofing spray" });
    string serialised = tm.TrySerializeToXml<taskmanager>(); // Serialize
    Debug.WriteLine(serialised);

    TaskManager dtm = serialised.TryDeserializeFromXml<taskmanager>(); // Deserialize
    Debug.Assert(tm.Count == dtm.Count);
    Debug.Assert(tm[0].Description.Equals(dtm[0].Description, 
                                          StringComparison.InvariantCultureIgnoreCase));
  }
}

public class TaskManager : List<Task>
{
}

public class Task
{
 public enum WhenEnum
 {
  Fortnight = 1,
  Month = 2,
  Year = 3,
 }
 public WhenEnum When { get; set; }
 public bool Displayable { get; set; }
 public string Description { get; set; }
}