December 14, 2012

Binary Serialization

Some binary serialization links:
Version Tolerant Serialization
Format Your Way to Success with the .NET Framework Versions 1.1 and 2.0 - Used some of the classes here to develop the BinarySerializer class below
Advanced serialization tips
Custom Serialization
Here is a sample binary serialisation class
private class BinarySerializer
{
    internal interface IGenericFormatter
    {
        T Deserialize<T>(Stream serializationStream);
        void Serialize<T>(Stream serializationStream, T graph);
    }

    internal class GenericFormatter<F> : IGenericFormatter 
     where F : IFormatter, new()
    {
        IFormatter m_Formatter = new F();

        public T Deserialize<T>(Stream serializationStream)
        {
            return (T)m_Formatter.Deserialize(serializationStream);
        }
        public void Serialize<T>(Stream serializationStream, T graph)
        {
            m_Formatter.Serialize(serializationStream, graph);
        }
    }

    internal class GenericBinaryFormatter : 
     GenericFormatter<BinaryFormatter> { }

    public void SerializeToFile<Type>(Type obj, string filePath)
    {
        IGenericFormatter formatter = new GenericBinaryFormatter();
        using (Stream stream = new FileStream(
            filePath, FileMode.Create, FileAccess.ReadWrite))
        {
            formatter.Serialize(stream, obj);
            stream.Close();
        }
    }

    public Type DeserializeFromFile<Type>(string filePath)
    {
        Type res = default(Type);
        if (File.Exists(filePath))
        {
            IGenericFormatter formatter = new GenericBinaryFormatter();
            using (Stream stream = new FileStream(
                filePath, FileMode.Open, FileAccess.ReadWrite))
            {
                res = formatter.Deserialize<Type>(stream);
                stream.Close();
            }
        }
        return res;
    }

    public byte[] SerializeToByteArray<Type>(Type obj)
    {
        byte[] res = null;
        IGenericFormatter formatter = new GenericBinaryFormatter();
        using (MemoryStream stream = new MemoryStream())
        {
            formatter.Serialize(stream, obj);
            res = stream.ToArray();
            stream.Close();
        }
        return res;
    }

    public Type DeserializeFromByteArray<Type>(byte[] bytes)
    {
        Type res = default(Type);
        if ((bytes != null) && (bytes.Length > 0))
        {
            IGenericFormatter formatter = new GenericBinaryFormatter();
            using (MemoryStream stream = new MemoryStream(bytes))
            {
                res = formatter.Deserialize<Type>(stream);
                stream.Close();
            }
        }
        return res;
    }

    public Type Clone<Type>(Type obj)
    {
        byte[] bytes = SerializeToByteArray<Type>(obj);
        Type res = DeserializeFromByteArray<Type>(bytes);
        return res;
    }
}
Can be used with this code to test binary serialisation of something
private static Type SerializeDeserialize<Type>(Type src) 
    where Type
{
    BinarySerializer bs = new BinarySerializer();
    byte[] bytes = bs.SerializeToByteArray<Type>(src);
    // Use these lines to create binary serialization files, 
    //string filePath = Path.Combine(Path.GetTempPath(), "SerialisedObject.bin");
    //File.WriteAllBytes(filePath, bytes);
    Type ds = bs.DeserializeFromByteArray<Type>(bytes);
    return ds;
}

December 13, 2012

Codeplex library to compare .NET objects

Codeplex library to compare .NET objects can be found here
Here is a sample usage of the ObjectCompare class:
// An equality comparator for XXX. Uses a 3rd party ObjectComparer utility class.
// Objects are considered equal if all their public properties and fields are equal
// UNUSUALLY ReferenceEquals fails when the 2 references are equal
// We should not be comparing the same objects in these
// tests
static bool XXXsAreEqual(XXX ds1, XXX ds2, List<string> elementsToIgnore = null)
{
    // Check for null values
    if (ds1 == null)
    {
        return (ds2 == null);
    }
    else if (ds2 == null)
    {
        return false;
    }

    // Check for NOT reference equals
    if (object.ReferenceEquals(ds1, ds2))
        return false; // This should NOT happen in these unit tests, fail if it does!

    // compare run-time types.
    if (ds1.GetType() != ds2.GetType())
        return false;

    // Ensure all public non-static properties and fields are equal
    var objectComparator = new ObjectCompare();
    objectComparator.CompareStaticFields = false;
    objectComparator.CompareStaticProperties = false;
    objectComparator.ComparePrivateProperties = false;
    objectComparator.ComparePrivateFields = false;
    objectComparator.CompareFields = true;
    objectComparator.CompareChildren = true;
    objectComparator.CompareReadOnly = true;
    objectComparator.CompareProperties = true;
    objectComparator.Caching = true;
    objectComparator.AutoClearCache = true;
    objectComparator.IgnoreObjectTypes = false; // Already done this above
    objectComparator.MaxDifferences = 1;
    objectComparator.ElementsToIgnore = elementsToIgnore ?? 
                                                new List<string>();

    bool res = objectComparator.Compare(ds1, ds2);
    // If this method fails, check the cause here!
    List<string> causeOfFailure = objectComparator.Differences; 
    if (causeOfFailure.Count > 0)
    {
        Debug.Write("Equality failure caused by following properties/fields: ");
        string failedOn = string.Join(", ", causeOfFailure.ToArray());
        Debug.WriteLine(failedOn);
    }
    return res;
}
To convert this to an equals operator of some kind you would have to fix the reference equals part to return true when the 2 references are equal.

September 3, 2012

Where Visual Studio 2010 exported templates go

Had problems deleting my templates but eventually I found the solution
Templates are exported to here:
%userprofile%\Documents\Visual Studio 2010\My Exported Templates
Installed to here:
%userprofile%\Documents\Visual Studio 2010\Templates\ProjectTemplates\Visual C# - Project templates install to here
%userprofile%\Application Data\Microsoft\VisualStudio\10.0\ProjectTemplatesCache - Project templates go here as well
%userprofile%\Documents\Visual Studio 2010\Templates\ItemTemplates - Item templates, such as a class template install to here
%userprofile%\Application Data\Microsoft\VisualStudio\10.0\ItemTemplatesCache - Item templates, go here as well
To remove a template, close VS and THEN make sure the template is removed from both locations to remove the template permanently.
A better way to install a template is to use the Export Template Wizard to make the exported template an installable extension, this can be later uninstalled in the standard way.

August 28, 2012

Modifying Directory Access Rules

Here is the routine to do the work:
 
// Adds an ACL entry on the specified directory for the specified account.
public static void AddDirectorySecurity(
    string folderName, 
 string account, 
 FileSystemRights rights, 
 AccessControlType controlType)
{
    // Create a new DirectoryInfo object.
    DirectoryInfo dirInfo = new DirectoryInfo(folderName);

    // Get a DirectorySecurity object that represents the 
    // current security settings.
    DirectorySecurity dSecurity = dirInfo.GetAccessControl();

    // Add the FileSystemAccessRule to the security settings. 
    dSecurity.AddAccessRule(new FileSystemAccessRule(account,
                                                    rights,
                                                    controlType));

    // Set the new access settings.
    dirInfo.SetAccessControl(dSecurity);
}

Sample usage of the routine:
DirectoryInfo targetDir = GetDirectoryInfo();    
// eg Deny the current user write permission on a given directory       
AddDirectorySecurity(targetDir.FullName, Environment.UserName, 
    FileSystemRights.Write, AccessControlType.Deny);

There is a remove as well:
// Removes an ACL entry on the specified directory for the specified account.
public static void RemoveDirectorySecurity(string folderName, string account, FileSystemRights rights, AccessControlType controlType)
{
    // Create a new DirectoryInfo object.
    DirectoryInfo dInfo = new DirectoryInfo(folderName);

    // Get a DirectorySecurity object that represents the 
    // current security settings.
    DirectorySecurity dSecurity = dInfo.GetAccessControl();

    // Add the FileSystemAccessRule to the security settings. 
    dSecurity.RemoveAccessRule(new FileSystemAccessRule(account,
                                                    rights,
                                                    controlType));

    // Set the new access settings.
    dInfo.SetAccessControl(dSecurity);

}
These methods are useful when unit testing writing to a directory without the appropriate permission.

August 2, 2012

Generic Event Firer


Here is the common .NET pattern for firing some event
// Here is the event
public event EventHandler<ReminderEventArgs> ReminderOccured;
...
// And to fire it
EventHandler<ReminderEventArgs> reminderOccured = this.ReminderOccured;
if (reminderOccured != null)
{
    reminderOccured(this, new ReminderEventArgs { Reminder = reminder });
}

This is a common pattern so a helper class to tidy this up might be of some use:
public static class EventFirer
{
    public static void FireEvent<TEventArgs>(object firer, 
        EventHandler<TEventArgs> eventToFire, TEventArgs eventargs)
        where TEventArgs : EventArgs
    {
        EventHandler<TEventArgs> eventToFireReference = eventToFire;
        if (eventToFireReference != null)
        {
            eventToFireReference(firer, eventargs);
        }
    }

    public static void FireEvent(object firer, EventHandler eventToFire, 
        EventArgs eventargs)
    {
        EventHandler eventToFireReference = eventToFire;
        if (eventToFireReference != null)
        {
            eventToFireReference(firer, eventargs);
        }
    }
}
With this class firing the event becomes:
EventFirer.FireEvent<ReminderEventArgs>(this, 
    this.ReminderOccured, 
    new ReminderEventArgs { Reminder = reminder });

June 29, 2012

Windows Service Class

A WindowsService class to expose a windows service. This class also exposes some techniques such as
  1. Delegating events.
  2. Using Interlocked.CompareExchange to reduce the threads waiting in a timer delegate.
  3. The use of a System.Threading.Timer type timer.
  4. Implementing IDisposable
/// <summary>
/// WIP: Exposes a window service including an event 
/// that fires when the service status changes
/// </summary>
public class WindowsService : IDisposable
{
  ServiceController serviceController = null;
 
  /// <summary>
  /// Use this method to check that the named service exists 
  /// before creating a WindowsService object for it.
  /// </summary>
  /// <param name="serviceDisplayName">The user friendly name for the service</param>
  /// <param name="machineName">Machine upon which the service is created</param>
  /// <returns>true if a service by the given name and on the given machine exists</returns>
  public static bool CheckServiceExists(string serviceDisplayName, 
                                        string machineName = ".")
  {      
    ServiceController[] scs = ServiceController.GetServices(machineName);
    ServiceController scFound = scs.FirstOrDefault(
      (ServiceController sc) => sc.DisplayName == serviceDisplayName);
    return (scFound != null);
  }
 
  public WindowsService(string serviceDisplayName, string machineName = ".")
  {
    serviceController = new ServiceController(serviceDisplayName, machineName);
    timer = new Timer(new TimerCallback(TimerProc));
  }
 
  public WindowsService(ServiceController sc)
  {
    // Check sc, how?
    string str = sc.DisplayName;
    serviceController = sc;
    timer = new Timer(new TimerCallback(TimerProc));
  }
 
  private string Path
  {
    get
    {
      string path = "\\\\" + this.serviceController.MachineName +
        "\\root\\cimv2:Win32_Service.Name='" + 
        this.serviceController.ServiceName + "'";
      return path;
    }
  }
 
  public string MachineName
  {
    get { return this.serviceController.MachineName; }
  }
 
  public string ServiceName
  {
    get { return this.serviceController.ServiceName; }
  }
 
  public void Start()
  {
    this.serviceController.Start();
  }
 
  public void Stop()
  {
    this.serviceController.Stop();
  }
 
  object statusRefreshlock = new object();
 
  private ServiceControllerStatus GetStatus() // thread safe
  {
    ServiceControllerStatus scs;
    lock (this.statusRefreshlock)
    {
      this.serviceController.Refresh();
      scs = this.serviceController.Status;
    }
    return scs;
  }
 
  public ServiceControllerStatus Status // thread safe
  {
    get { return this.GetStatus(); }
  }
 
  public bool CanPauseAndContinue
  {
    get { return this.serviceController.CanPauseAndContinue; }
  }
 
  public bool CanShutdown
  {
    get { return this.serviceController.CanShutdown; }
  }
 
  public bool CanStop
  {
    get { return this.serviceController.CanStop; }
  }
 
  public string DisplayName
  {
    get { return this.serviceController.DisplayName; }
  }
 
  #region Extra properties
 
  public string Description
  {
    get
    {
      string res = "";
      ManagementPath mPath = new ManagementPath(this.Path);
      //construct the management object
      using (ManagementObject ManagementObj = new ManagementObject(mPath))
      {
        object obj = ManagementObj["Description"];
        if (obj != null)
        {
          res = obj.ToString();
        }
      }
      return res;
    }
  }
 
  public string FilePath
  {
    get
    {
      string res = "";
      ManagementPath mPath = new ManagementPath(this.Path);
      //construct the management object
      using (ManagementObject ManagementObj = new ManagementObject(mPath))
      {
        object obj = ManagementObj["PathName"];
        if (obj != null)
        {
          res = obj.ToString();
        }
      }
      return res;
    }
  }
 
 
  /// <summary>
  /// Gets or sets the start mode.
  /// </summary>
  public ServiceStartMode StartMode
  {
    get
    {
      ManagementPath mPath = new ManagementPath(this.Path);
      string mode = "";
      using (ManagementObject manager = new ManagementObject(mPath))
      {
        mode = manager["StartMode"].ToString();
      }
      ServiceStartMode res = ServiceStartMode.Disabled;
      Enum.TryParse<ServiceStartMode>(mode, out res);
      return res;
    }
    set
    {
      ManagementPath mPath = new ManagementPath("Win32_Service.Name='" + this.serviceController.ServiceName + "'");
      using (ManagementObject manager = new ManagementObject(mPath))
      {
        manager.InvokeMethod("ChangeStartMode"new object[] { value.ToString() });
      }
    }
  }
 
  #endregion Extra properties
 
  /// <summary>
  /// Send an event when the status of the windows service has changed, 
  /// Beware: this event will be invoked on a foreign thread!
  /// </summary>
  public event EventHandler<StatusChangedEventArgs> StatusChanged
  {
    add
    {
      serviceStatusChanged += value;
      ++count;
      if (count == 1) // Start listening as soon as someone registers for an event
        timer.StartPeriodic(updatePeriod);
    }
    remove
    {
      serviceStatusChanged -= value;
      --count;
      if (count == 0) // Stop listening as soon as there is no-one registered for events
        timer.Stop();
    }
  }
 
  #region ServiceStatusChanged Implementation
 
  // Normally implementation of add/remove are hidden 
  // but it is still possible to define them explicitly
  private EventHandler<StatusChangedEventArgs> serviceStatusChanged;
  int count = 0; // count the number of event handlers added
 
 
  public class StatusChangedEventArgs : EventArgs
  {
    public StatusChangedEventArgs(ServiceControllerStatus oldState, 
                                  ServiceControllerStatus newState)
    {
      OldStatus = oldState;
      NewStatus = newState;
    }
 
    public ServiceControllerStatus OldStatus
    {
      get;
      private set;
    }
 
    public ServiceControllerStatus NewStatus
    {
      get;
      private set;
    }
 
  }
 
  const int updatePeriod = 500; // update period in millseconds
 
  Timer timer = null;
  // prevStatus only ever accessed in the TimerProc method by one thread at a time
  ServiceControllerStatus prevStatus = ServiceControllerStatus.Stopped;
  int timerProcInUse = 0;
 
  // The Timer delegate to be invoked on a callback (from 
  // another thread)
  private void TimerProc(object obj)
  {
    // Only allow one thread to enter but dont block other threads 
    // they will simply exit, but this does not matter 
    // as only one update at a time is required.
    // This will stop them running into each other if the 
    // PC slows down or when debugging
    if (System.Threading.Interlocked.CompareExchange(
        ref timerProcInUse, 1, 0) == 0)
    {
      // Careful. TimeOut callback occurs on another thread
      // GetStatus() is thread safe
      ServiceControllerStatus newStatus = this.GetStatus(); 
      if (newStatus != this.prevStatus)
      {
        this.prevStatus = newStatus;
        if (this.serviceStatusChanged != null)
        {
          this.serviceStatusChanged(this, 
            new StatusChangedEventArgs(prevStatus, newStatus));
        }
      }
      // No longer in use
      timerProcInUse = 0;
    }
  }
 
  #endregion ServiceStatusChanged Implementation
 
  #region Dispose Implementation
 
  private void DisposeTimer()
  {
    if (this.timer != null)
    {
      this.timer.Dispose();
      this.timer = null;
    }
  }
 
  // Use C# destructor syntax for finalization code.
  ~WindowsService()
  {
    Debug.Assert(false"This object was not disposed of");
    Dispose(false);
  }
 
  private bool m_Disposed = false;
 
  //Implement IDisposable.
  public void Dispose()
  {
    Dispose(true);
    GC.SuppressFinalize(this);
  }
 
  protected virtual void Dispose(bool disposing)
  {
    if (m_Disposed)
      return;
 
    // leanup unmanaged resources in WindowsService
    DisposeTimer();
 
    m_Disposed = true;
  }
 
  #endregion Dispose Implementation
 
}
Uses the System.Threading.Timer extension methods

System.Threading.Timer extension methods

The methods of the System.Threading.Timer are not particularly intuitive. Wrote these set of extension methods to make them a bit easier to use:

public static class TimerExtensions
{
 
  /// <summary>
  /// Stop the timer. 
  /// </summary>
  /// <param name="timer"></param>
  public static void Stop(this System.Threading.Timer timer)
  {
    timer.Change(Timeout.Infinite, Timeout.Infinite);
  }
 
  /// <summary>
  /// Start the timer as a periodic timer.  
  /// </summary>
  /// <param name="timer">target timer</param>
  /// <param name="periodMs">Delay imbetween TimerCallback invokations.
  /// Period is expressed in milliseconds </param>
  public static void StartPeriodic(this System.Threading.Timer timer, int periodMs)
  {
      // Note that timer.Change(Timeout.Infinite, periodMs); does not work!
      timer.Change(periodMs, periodMs);
  }
  /// <summary>
  /// Start the timer as a once only timer. 
  /// </summary>
  /// <param name="timer">target timer</param>
  /// <param name="periodMs">Period before the single invokation of the TimerCallback, 
  /// expressed in milliseconds </param>
  public static void StartOneTime(this System.Threading.Timer timer, int periodMs)
  {
    timer.Change(periodMs, Timeout.Infinite);
  } 
then the timer can be created, started and stopped very simply:
Timer timer = new Timer(new TimerCallback(TimerProc));
...
timer.StartPeriodic(500);
...
timer.Stop();

Don't forget the timer delegate:
// The Timer delegate to be invoked on a callback (from 
// another thread)
private void TimerProc(object obj)
{
    // Careful! callback occurs on another thread
}

Don't forget to dispose of the timer:

private void DisposeTimer()
{
    if (this.timer != null)
    {
        this.timer.Dispose();
        this.timer = null;
    }
}

May 2, 2012

XmlSerializer Usage

C# Tutorial - XML Serialization

Watch out for derived classes, the Xml serializer will not know how to serialize them without being told about them.
For example, a base class is "MenuItemDefinition"
Derived classes are "StartExecutableMenuItem", "RestartExecutableMenuItem"
To serialize instances of the base class, create an XmlSerializer thus:
XmlSerializer serializer = new XmlSerializer(
  typeof(List<MenuItemDefinition>),   // Object type to serialize
  // Following list of types are derived class types that the 
  // XmlSerializer will need to know about to perform the serialization
  new Type[] { typeof(StartExecutableMenuItem), typeof(RestartExecutableMenuItem), });
so here is the full serialization:
private void MenuItemsSerialize()
{
    IEnumerable<MenuItemDefinition> menuItems = LoadMenuItemDefinitions();
    var li = new List<MenuItemDefinition>();
    li.AddRange(menuItems);

    XmlSerializer serializer = new XmlSerializer(
      typeof(List<MenuItemDefinition>), // Object type to serialize
      // List of types that are derived class types that the 
      // XmlSerializer will need to know about to perform the serialization
      new Type[] { 
        typeof(StartExecutableMenuItem), 
        typeof(RestartExecutableMenuItem), }
    );
    string path = Path.Combine(Path.GetTempPath(), "delme.xml");
    TextWriter textWriter = new StreamWriter(path);
    serializer.Serialize(textWriter, li);
    textWriter.Close();
}
Alternatively a bunch of XmlInclude attributes on the base class will do the job.

April 29, 2012

Page Breaks in HTML

Page break after description

Fixing page breaks just after a title when printing HTML.
Used an XSLT transform to break my document into sections each with a title. Trouble is when printing HTML, there is no way to know where the page break will be placed. In my case I ended up with page breaks just after a section title!. Fixed this by putting a <br style="page-break-after:always"/> at the end of each section. There are other types of page break in CSS but this fixed the problem and quickly. Some browsers do not accept all forms of page break; Firefox, for example.

April 24, 2012

Non-Virtual Interface Design Pattern

The Non-Virtual Interface Design Pattern is described here: http://www.blackwasp.co.uk/NVI.aspx

Basically the pattern promotes the use of non-virtual public base class methods that can be used by clients. A set of overridable behaviours are exposed (as protected or protected internal) that are invoked directly by exposed public methods in the base class. This way the base class behaviour can be overriden by deriving classes.

April 19, 2012

File Drag and Drop in WPF

Watch drag and drop to text boxes as they need special handling see Textbox Drag/Drop in WPF

Add to your control (or main window) declaration
AllowDrop="True" DragEnter="Window_DragEnter" Drop="Window_Drop"

In the code do something like this (this is a file drag/drop sample):
#region DragDrop

bool IsValidDropData(IDataObject draggedObj)
{
  bool res = false;
  IEnumerable<string> lst = draggedObj.GetData(DataFormats.FileDrop)
     as IEnumerable<string>;
  if (lst != null)
  { 
    // In this sample I am only taking the first file
 // the rest are ignored
    string first = lst.FirstOrDefault();
    if (!string.IsNullOrWhiteSpace(first))
    {
      FileInfo fi = new FileInfo(first);
      res = fi.Exists && HasValidFileExtension(fi);
    }
  }
  return res;
}

private bool HasValidFileExtension(FileInfo file)
{
  string[] validExtensions = new[] { ".xml" };

  bool res = false;
  res = (file != null) && validExtensions.Contains(file.Extension);
  return res;
}

private void Window_DragEnter(object sender, DragEventArgs e)
{
  if (IsValidDropData(e.Data))
  {
    e.Effects = DragDropEffects.Copy;
  }
  else
  {
    e.Effects = DragDropEffects.None;
  }
}

private void Window_Drop(object sender, DragEventArgs e)
{
  if (IsValidDropData(e.Data))
  {
    IEnumerable<string> files = e.Data.GetData(DataFormats.FileDrop)
        as IEnumerable<string>;
    string fileName = files.FirstOrDefault();
    if (!string.IsNullOrEmpty(fileName) && 
     File.Exists(fileName))
    {
       DoSomethingWith(fileName);
    }
  }
}

#endregion DragDrop

Embedded Resources

To embed a resource:
  1. Add it to the project
  2. Change the build action to "Embedded Resource"
The compiler adds the root namespace of the project to the name of the resource when it is included in the project. For example, if the root namespace of your project is MyNamespace, and the resource is XXX.xslt then the name of the resource when retrieving it is MyNamespace.XXX.xslt.

Further, if the resource is placed in a project folder, the name of the folder is added into the resource name. For example, if the embeded resource XXX.xslt, exampled above, is placed in a project folder "Resources" then the resource name when retrieving it is now MyNamespace.Resources.XXX.xslt.

To retrieve a resource thus embedded use the method GetManifestResourceStream on the assembly object. For example to retrieve the embedded resource MyNamespace.Resources.XXX.xslt from the executing assembly:
private string RetrieveEmbeddedStringResource(string resourceName)
{
  Assembly myAssembly = Assembly.GetExecutingAssembly();
  Stream fileStream = myAssembly.GetManifestResourceStream(resourceName);
  string text = "";
  if (fileStream != null)
  {
    using (StreamReader streamReader = new StreamReader(fileStream))
    {
      text = streamReader.ReadToEnd();
    }
  }
  return text;
}
and to call it:
string xslt = RetrieveEmbeddedStringResource(
    "ViewNUnitTestResults.Resources.NUnitTestResultsToHtml.xsl");
In this case the namespace is ViewNUnitTestResults, the resource is NUnitTestResultsToHtml.xsl which is stored under the project subdirectory Resources.
To retrieve a binary embedded resource:
private byte[] RetrieveByteArrayEmbeddedResource(string resourceName)
{
    byte[] bytes = new byte[0];
    Assembly myAssembly = Assembly.GetExecutingAssembly();
    bool resFound = myAssembly.GetManifestResourceNames().Contains(resourceName);
    if (!resFound)
        throw new ArgumentException("Could not find the embeded resource \'" +
            resourceName + "\'");
    using (Stream stream = myAssembly.GetManifestResourceStream(resourceName))
    {
        bytes = new byte[stream.Length];
        stream.Read(bytes, 0, (int)stream.Length);
    }
    return bytes;
}
and it is called like this
byte[] bytes = RetrieveByteArrayEmbeddedResource("XXXTests.Something.bin");

March 28, 2012

WPF/Silverlight MVVM

Quick Intro to MVVM A small introduction

Getting Started with the MVVM Pattern in Silverlight Applications

MVVM Light Toolkit
Download it here - There is a couple of videos here as well!

Chapter 5: Implementing the MVVM Pattern
Chapter 6: Advanced MVVM Scenarios - Most introductions only explain the topic in a basic way which does not occur in reality. Here, they show how to deal with the tricksey areas

Simplifying commands in MVVM and WPF - I like the adapted approach proffered by David N. in the comments

Using the BackgroundWorker in a Silverlight MVVM Application - Most of my apps have background worker threads or threading in some manner.

WPF MVVM Commands - new reduced-boilerplate recipe - Not so keen on this approach

March 26, 2012

Custom commands with standard menus

Define the command:
public static class CustomCommands
{
    private static RoutedCommand exitCommand;

    static CustomCommands()
    {
        exitCommand = new RoutedCommand("ExitApplication", typeof(CustomCommands));
    }

    public static RoutedCommand Exit
    {
        get
        {
            return (exitCommand);
        }
    }

}
Define the command in the window bindings:
<Window.CommandBindings>
        <CommandBinding
          Command="{x:Static local:CustomCommands.Exit}"
    Executed="Exit_Execute" 
          CanExecute="Exit_CanExecute" />
    </Window.CommandBindings>
Of course you'll have to define the namespace in the window/page class node:
<Window ...
xmlns:local="clr-namespace:MyNamespace"
... >
Alternatively, define the command in the window constructor:
InitializeComponent();
...
   CommandBindings.Add(
    new CommandBinding(
   CustomCommands.Exit, // this is the command object
   Exit_Execute,      // execute
   Exit_CanExecute));// can it execute?
Define the menu item that will call the command
<MenuItem Header="E_xit" Command="local:CustomCommands.Exit" />
Now define the event handlers that will execute the command
private void Exit_Execute(object sender, ExecutedRoutedEventArgs e)
{
    this.Close();
}

private void Exit_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
    e.CanExecute = CanExitApplication();
    e.Handled = true;
}

Using Application Commands

Define the command binding
<Window.CommandBindings>
<CommandBinding Command="ApplicationCommands.Close"
 Executed="CloseCommandHandler"
 CanExecute="Close_CanExecute"
 /> 
 ...
 </Window.CommandBindings> 
and then define the menu item:
<MenuItem Header="E_xit" Command="ApplicationCommands.Close" />
Again ensure that within the code behind window class that the event handlers are defined:
private void Close_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
    e.CanExecute = true;
    e.Handled = true;
}

private void Close_Execute(object sender, ExecutedRoutedEventArgs e)
{
    DoClose();
}
Beware of using commands with Context Menus. There is a 'gotcha' here. This is explained here: How to Solve Execution Problems of RoutedCommands in a WPF ContextMenu The simplest solution is to call 'Focus()' on the parent window.

March 6, 2012

Implementing ==, != Operators In Reference Types

For more on equality operators see the Equals Operator Pattern

Microsoft guideline: Guidelines for Overloading Equals() and Operator == (C# Programming Guide)

Find out about The ReferenceEquals() method - Standard class operator == does reference comparison, so it will end up returning false if the two arguments point to different references where both refences hold the same state. To define == operator for a reference type you must be careful to define it in terms of "RefenceEqual()" and "Equals()". If you use == within the definition you will likely get an infinite recursion. This blogs explains why. Value types do not have the same problem as "==" does not do a reference comparison, it compares the value types field by field for equality.

Following example shows how a reference object behaves when the '==' and '!=' operators are overriden and when they are not. The class 'With' has the operators overriden and the class 'Sans' has not.
class TestRefernceTypeEqualityOperator
{
  internal class With
  {
    public string Name { get; set; }
    public int UniqueId { get; set; }

    public override bool Equals(object obj)
    {
      if (obj == null)
        return false;

      if (object.ReferenceEquals(this, obj))
        return true;

      if (!(obj is With))
        return false;
      With selection2 = (With)obj;

      if ((this.UniqueId == selection2.UniqueId) &&
        (this.Name == selection2.Name))
        return true;

      return base.Equals(obj);
    }


    public static bool operator ==(With obj1, With obj2)
    {
      // IF obj1 1 is null
      //   so obj2 must be for equality
      // ELSE obj1 is not null,  
      //   compare it with obj2 using above Equals() operator
      if (ReferenceEquals(obj1, null))    
        return ReferenceEquals(obj2, null); 
      else                  
        return obj1.Equals(obj2);
    }

    public static bool operator !=(With obj1, With obj2)
    {
      return !(obj1 == obj2);
    }


    public override int GetHashCode()
    {
      string ensemble = this.UniqueId.ToString() + this.Name;
      return ensemble.GetHashCode();
    }

  }


  internal class Sans
  {
    public string Name { get; set; }
    public int UniqueId { get; set; }

    public override bool Equals(object obj)
    {
      if (obj == null)
        return false;

      if (object.ReferenceEquals(this, obj))
        return true;

      if (!(obj is Sans))
        return false;
      Sans selection2 = (Sans)obj;

      if ((this.UniqueId == selection2.UniqueId) &&
        (this.Name == selection2.Name))
        return true;

      return base.Equals(obj);
    }


    public override int GetHashCode()
    {
      string ensemble = this.UniqueId.ToString() + this.Name;
      return ensemble.GetHashCode();
    }


  }

  public void Test()
  {
    // Note that 'with' and 'with2' are different references 
    // with the same state
    With with = new With() { Name= "Smeg", UniqueId = 2739 };
    With with2 = new With() { Name = "Smeg", UniqueId = 2739 };
    With with3 = new With() { Name = "Smeg", UniqueId = 2740 };
    Trace.Assert(with.Equals(with2));
    Trace.Assert(with == with2);
    Trace.Assert(!(with != with2));
    Trace.Assert(!(with == null));
    Trace.Assert(!(null == with));

    Trace.Assert(!with.Equals(with3));
    Trace.Assert(with != with3);     
    Trace.Assert(!with2.Equals(with3));
    Trace.Assert(with2 != with3);

    // Note that 'sans' and 'sans2' are different references 
    // with the same state
    Sans sans = new Sans() { Name = "Smeg", UniqueId = 2739 };
    Sans sans2 = new Sans() { Name = "Smeg", UniqueId = 2739 };
    Sans sans3 = new Sans() { Name = "Smeg", UniqueId = 2740 };
    Trace.Assert(sans.Equals(sans2));
    Trace.Assert(!(sans == sans2));
    Trace.Assert(sans != sans2);
    Trace.Assert(!(sans == null));
    Trace.Assert(!(null == sans));

    Trace.Assert(!sans.Equals(sans3));
    Trace.Assert(sans != sans3);
    Trace.Assert(!sans2.Equals(sans3));
    Trace.Assert(sans2 != sans3);
  }
}
The 2 highlited lines show the difference. Without '==', '!=' operator the comparison is by reference so where 'with == with2' succeeds 'sans == sans2' fails even though the different references refer to objects with exactly the same state (and even though the 'Equals()' method does return true in this case).

March 1, 2012

Simple Generic ServiceLocator example

Find the root of all evil behind this pattern by Martin Fowler
What's the difference between the Dependency Injection and Service Locator patterns?

Here is a simple GenericServiceLocator class:
public class GenericServiceLocator
{
    #region Fast Thread Safe Singleton Implementation
        
    static GenericServiceLocator()
    {}

    private GenericServiceLocator()
    {}

    private static readonly GenericServiceLocator instance = 
        new GenericServiceLocator();

    public static GenericServiceLocator Instance
    {
        get
        {
            return instance;
        }
    }

    #endregion Fast Thread Safe Singleton Implementation

    Dictionary<object, object> interfaceToServiceMap = 
        new Dictionary<object, object>();

    public void AddService<IInterface>(IInterface svcImpl)            
    {
        Trace.Assert(typeof(IInterface).IsInterface);
        Trace.Assert(svcImpl != null);
        Trace.Assert(svcImpl is IInterface);
        Trace.Assert(!this.interfaceToServiceMap.
                               ContainsKey(typeof(IInterface)));
        this.interfaceToServiceMap[typeof(IInterface)] = svcImpl;
    }


    public IInterface GetService<IInterface>() 
    {
        Trace.Assert(typeof(IInterface).IsInterface);
        

        object obj = this.interfaceToServiceMap[typeof(IInterface)];
        return (IInterface)obj;
    }


    public bool HasService<IInterface>()
    {
        Trace.Assert(typeof(IInterface).IsInterface);

        return this.interfaceToServiceMap.
                                   ContainsKey(typeof(IInterface));
    }
}
Here is a simple tester for it:
class TestServiceLocator
{
    public interface IMyPieInterface
    {
        double GetPie();
    }

    public class PieMaker : IMyPieInterface
    {
        #region IMyPieInterface Members

        public double GetPie()
        {
            return Math.PI;
        }

        #endregion
    }

    public void Test()
    {
        GenericServiceLocator.Instance.
                          AddService<IMyPieInterface>(new PieMaker());
        Trace.Assert(GenericServiceLocator.Instance.
                          HasService<IMyPieInterface>());

        IMyPieInterface myPieMaker = GenericServiceLocator.Instance.
                          GetService<IMyPieInterface>();
        double pie = myPieMaker.GetPie();
        Trace.Assert(Math.Abs(Math.PI - pie) < 0.001);
    }
}

February 21, 2012

Asynchronous Programming with Async/Await

Easier Asynchronous Programming with the New Visual Studio Async

Every time an await is encountered, the currently executing method signs up the rest of the method as the thing to do when the current task is complete, and then immediately returns. Somehow each task will complete itself—either by being scheduled to run as an event on the current thread, or because it used an I/O completion thread or worker thread—and will then cause its continuation to “pick up where it left off” in executing the rest of the method.

Async Programming in Visual Studio 2010

The thing doing that work may be a background thread, an I/O completion thread, a graphic processing unit, or even the current thread. It doesn’t matter to the caller.

Await signifies two related things. First, it says that everything remaining in the method becomes the continuation for the method. A ‘continuation’ represents where the method will continue once the expression being awaited completes its work. Secondly, it tells the method to return.


Pause and Play with Await - How the Await and Async work underneath the covesr and how you can prepare for the m in .NET 4.0.

What is Binding?

Taken from the following article
What is "binding" and What makes it late? by Eric Lippert
Binding is the association of a syntactic element that names a method with a logical element of the program. So, speaking generally I would say that "binding" is any association of some fragment of syntax with some logical program element.

Basically by "early binding" we mean "the binding analysis is performed by the compiler and baked in to the generated program"; By "late binding" we mean "some aspect of the binding will be performed by the runtime" and therefore a binding failure will manifest as a runtime failure.

Early and late binding might better be called "static binding" and "dynamic binding"; static binding is binding performed using "static" facts known to the compiler, and dynamic binding is performed using facts "dynamically" known to the runtime.

February 17, 2012

WPF/Silverlight Data Binding

WPF Basic Data Binding FAQ - Better explanation than the one below.

WPF Data binding cheat sheet

Data Binding Overview - Basically, the target is the control and the source is the code property. Typically, each binding has these four components: a binding target object, a target property, a binding source, and a path to the value in the binding source to use. For example, if you want to bind the content of a TextBox to the Name property of an Employee object, your target object is the TextBox, the target property is the Text property, the value to use is Name, and the source object is the Employee object.

http://msdn.microsoft.com/en-gb/magazine/cc163299.aspx - Data Binding in WPF. Good introduction. Good short description of Xml data binding (though not 2 way I notice)

http://msdn.microsoft.com/en-us/magazine/cc700358.aspx - Customize Data Display with Data Binding and WPF. Some good stuff on hierarchical data templates and how to use them to fill a tree view using object data binding.

http://www.codeproject.com/Articles/26270/Understanding-WPF-via-ASP-NET - Nice article comparing WPF and ASP.NET data binding etc.

Also look at these related blogs
DisplayMemberpath
Data Templates

Bind "IsEnabled" of one control "cbXXX" to "IsChecked" property of another with name "cbYYY" in Xaml:
... Name="cbXXX" IsEnabled="{Binding ElementName=cbYYY, Path=IsChecked}" ...

February 16, 2012

DisplayMemberPath

DisplayMemberPath - Allows for simple binding on list type controls. Name or path on bound object that will be displayed for each item in the control.

See this article http://johnpapa.net/binding-to-silverlight-combobox-and-using-selectedvalue-selectedvaluepath-and-displaymemberpath - Nice ComboBox example that allows the user to chose some colors.

ObjectDataProvider

ObjectDataProvider - Wraps and creates an object that you can use as a binding source. Allows binding to objects that do not have a default constructor and that can be called Asynchronously.
http://www.thomasclaudiushuber.com/blog/2008/01/10/bind-to-methods-with-objectdataprovider/ - Nice simple example of using ObjectDataProvider

Data Templates

Taken from Top Ten UI Development Breakthroughs In Windows Presentation Foundation

You don't have to set the data template on a particular control. If you prefer, you can associate a data template with a particular type, indicating that WPF should use the specified template whenever it encounters that particular type as content.
eg
<Window.Resources> 
<DataTemplate DataType="{x:Type local:Person}"> <StackPanel Orientation="Horizontal"> <TextBlock FontWeight="Bold">Name:</TextBlock>
<TextBlock Text="{Binding Name}" Margin="2,0,10,0" /> <TextBlock FontWeight="Bold">
Date of birth:</TextBlock> <TextBlock Text="{Binding DateOfBirth}"Margin="2,0,10,0" /> </StackPanel> </DataTemplate> 
</Window.Resources>
Anything in the window that uses a Person object as its content will pick up this data template by default.

Example C++/CLI sealed properties and methods

This is to help remember the syntax of this stuff, it is too easy to forget
virtual void EnableStuff() sealed = IStuffEnabler::EnableStuff 
{
  stuffEnableImpl();  
}

virtual property bool IsStuffEnabled 
{
  bool get() sealed = IStuffEnabler::IsStuffEnabled::get
  {
 return stuffIsEnabledImpl();
  }
} 

Or split into source and header
Header file:
virtual void EnableStuff() sealed = IStuffEnabler::EnableStuff;
    
virtual property bool IsStuffEnabled 
{
  bool get() sealed = IStuffEnabler::IsStuffEnabled::get;
}      
and source file:
void StuffEnabler::EnableStuff() 
{
  stuffEnableImpl();  
}
    
bool StuffEnabler::IsStuffEnabled::get()  
{
    return stuffIsEnabledImpl();
}     

January 26, 2012

Lazy<T>

Added in version 4.0 of .Net, a lazy template. The templated paramater object is not created until its value is first accessed.
Here is a simple example:
public class Thingey
{
    public string Name { get; set; }
}
To test it:
internal void TestLazyTemplate()
{
    Lazy<Thingey> myThingey = new Lazy<Thingey>();
    bool isCreated = myThingey.IsValueCreated;
    Debug.Assert(isCreated == false); // Not created yet
    myThingey.Value.Name = "Sutum";   // Created when accessed
    isCreated = myThingey.IsValueCreated; 
    Debug.Assert(isCreated == true);
}