Wednesday, December 16, 2009

System.Drawing.Bitmap to fancy WPF BitmapSource

One of the big transitions that WPF (Windows Presentation Foundation) made away from the old GDI+ Windows Forms was the complete change to DirectX image formats.

Fortunately, Microsoft provide a nice little Interop method for this. Unfortunately, it's not that useful by itself.

The following .NET 3.5 extension methods convert either a System.Drawing.Image or System.Drawing.Bitmap to a System.Windows.Media.Imaging.BitmapSource.

/// 
    /// Contains extension methods for images.
    /// 
    public static class ImageExtensions
    {
        /// 
        /// Converts a  into a .
        /// 
        /// The source image./// A  containing the same image.
        public static BitmapSource ToBitmapSource(this System.Drawing.Image source)
        {
            System.Drawing.Bitmap bitmap = source as System.Drawing.Bitmap;
            if (bitmap != null) return bitmap.ToBitmapSource();

            bitmap = new System.Drawing.Bitmap(source);
            try
            {
                return bitmap.ToBitmapSource();
            }
            finally
            {
                bitmap.Dispose();
            }
        }

        /// 
        /// Converts a  into a .
        /// 
        /// The source bitmap./// 
        /// Uses GDI to do the conversion. Hence the call to the marshalled DeleteObject.
        /// 
        /// A  containing the same image.
        public static BitmapSource ToBitmapSource(this System.Drawing.Bitmap source)
        {
            var hBitmap = source.GetHbitmap();

            try
            {
                return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                    hBitmap,
                    IntPtr.Zero,
                    Int32Rect.Empty,
                    BitmapSizeOptions.FromEmptyOptions());
            }
            catch (Win32Exception)
            {
                return null;
            }
            finally
            {
                NativeMethods.DeleteObject(hBitmap);
            }
        }
    }

Enjoy!

Code Snippet - Event Declaration

So I found myself needing to write a bunch of events and their calling method OnEvent. And I thought, well this is a bit ridiculous, surely there is a handy code snippet I could write that would automate the entire process.

And so...

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>Public Event Declaration</Title>
      <Description>Snippet for automatic public Event and private OnEvent declaration.</Description>
      <Shortcut>eventpri</Shortcut>
      <Author>Alastair Pitts</Author>
    </Header>
    <Snippet>
      <Declarations>
        <Literal>
          <ID>EventArg</ID>
          <ToolTip>Replace with the event args.</ToolTip>
          <Default>EventArgs</Default>
        </Literal>
        <Literal>
          <ID>EventName</ID>
          <ToolTip>Replace with name of event.</ToolTip>
          <Default>MyEvent</Default>
        </Literal>
      </Declarations>
      <Code Language="CSharp">
        <![CDATA[
        public event EventHandler<$EventArg$> $EventName$;
        
        private void On$EventName$(object sender, $EventArg$ e)
        {
            var temp = $EventName$;
            if (temp != null)
                temp(sender, e);
        }
        ]]>
      </Code>
    </Snippet>
  </CodeSnippet>
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>Protected Event Declaration</Title>
      <Description>Snippet for automatic public Event and protected OnEvent declaration.</Description>
      <Shortcut>eventpro</Shortcut>
      <Author>Alastair Pitts</Author>
    </Header>
    <Snippet>
      <Declarations>
        <Literal>
          <ID>EventArg</ID>
          <ToolTip>Replace with the event args.</ToolTip>
          <Default>EventArgs</Default>
        </Literal>
        <Literal>
          <ID>EventName</ID>
          <ToolTip>Replace with name of event.</ToolTip>
          <Default>MyEvent</Default>
        </Literal>
      </Declarations>
      <Code Language="CSharp">
        <![CDATA[
        public event EventHandler<$EventArg$> $EventName$;
        
        protected virtual void On$EventName$(object sender, $EventArg$ e)
        {
            var temp = $EventName$;
            if (temp != null)
                temp(sender, e);
        }
        ]]>
      </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

By typing the intellisense shortcut eventpri, you get the event with a private OnEvent method. This is suitable for sealed classes. The generated signature will look like this:
public event EventHandler<MyEventArgs> MyEvent;

private void OnMyEvent(object sender, MyEventArgse)
{
    var temp = MyEvent;
    if (temp != null)
        temp(sender, e);
}

If your creating a class that maybe inherited from, then the eventpro will be suitable as the OnEvent method can be overridden and acted upon. The generated signature will look like this:
public event EventHandler<MyEventArgs> MyEvent;

protected virtual void OnMyEvent(object sender, MyEventArgse)
{
    var temp = MyEvent;
    if (temp != null)
        temp(sender, e);
}

I hope this snippet is useful and allows developers to shave the required seconds off development time :)


The snippet file can be downloaded from the following link: Event.snippet
To install, copy to "C:\Users\[Username]\Documents\Visual Studio 2008\Code Snippets\Visual C#\My Code Snippets"

Tuesday, December 15, 2009

Any start is a good thing

The idea for this blog is meant to show some useful pieces of .NET code, not specifically LINQ related, more just good pieces of code.

The first (or second) real post will contain some useful code snippets that generate event signatures. This will come in the next couple of days, but until then...

Caio!