I love working with other developers, whether it be formal “paired programming” or just one person helping the other with a problem.  I love it so much because I always learn something new.  Sometimes what I learn is some major, powerful technique for doing something complicated but usually it is not.  Usually it is one of those simple, cool, helpful tidbits.  You probably know what I mean.  You sit with a coworker and without any fanfare they type some keystroke and you say, “Whoa, I didn’t know you could do that… how did you do that?”  Here’s an example of something I do that I’ve noticed many developers aren’t aware of. It’s nothing fancy, but I find it helpful.

Like many developers, I like to surround my code in collapsible regions.  I don’t get too carried away with this technique, but I usually have a region for Public Properties, another for Public Methods, maybe one for Class Level variables.  Stuff like that.  Anyway, most people label the top of the region but I’ve found that many developers don’t know you can label the bottom.  That extra label on the bottom is really helpful when you are scrolled down far.  Without the label, you find an #endregion and you don’t know what region it is the end of.  This is especially tricky when working with nested tags.  How do you do it?  Just type the label :).

#endregion with label:
#region Public Methods
// put stuff here...
#endregion Public Methods

I think the reason people don’t do this more is that (I’m pretty sure) you could NOT do this with some earlier version of Visual Studio.  Those of us that have worked with VS for a long time just got used to doing #endregions without the label.  Back then I used to put a comment at the end of my region like this, but it isn’t necessary anymore:

#region Public Methods
// put stuff here...
#endregion //Public Methods

But at some point, maybe VS2008, we were allowed to just put the label at the end. 

But wait, there’s more…

Recently I had the idea to update the code snippet for “Surround with Region”.  You can use this built in Visual Studio snippet by highlighting some code and hitting “Ctrl + s”, then select #region from the dropdown.  When you do, your code is automatically surrounded by the #region and #endregion, plus you’ll be prompted for the text for the label.  I tweaked it so it puts the label at the beginning and the end. 

  • You can find your snippets by going to the Code Snippets Manager (Tools > Code Snippets Manager, or Ctrl + k, Ctrl + b).
  • Then select Visual C# (or VB I guess, I don’t use it :) )
  • When you click on the folder or the name of the snippet, the path is shown in the window.  See the screen shot below…
  • In my case, and I think it is pretty standard, I open the snippet in Notepad at the following path: C:\Program Files\Microsoft Visual Studio 10.0\VC#\Snippets\1033\Visual C#\pp_region.snippet
  • Then change the snippet and use the XML listed below.
  • The only thing I changed was the 24th line.  After “#endregion” I put in the $name$ variable.  The variable was already used in the snippet on line 22 so it was easy. 
  • Note: If you can’t save this snippet with notepad, make sure Visual Studio is closed and run notepad “as administrator”.
Snippet XML:

<?xml version="1.0" encoding="utf-8" ?>

<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">

    <CodeSnippet Format="1.0.0">

        <Header>

            <Title>#region</Title>

            <Shortcut>#region</Shortcut>

            <Description>Code snippet for #region</Description>

            <Author>Microsoft Corporation</Author>

            <SnippetTypes>

                <SnippetType>Expansion</SnippetType>

                <SnippetType>SurroundsWith</SnippetType>

            </SnippetTypes>

        </Header>

        <Snippet>

            <Declarations>

                <Literal>

                    <ID>name</ID>

                    <ToolTip>Region name</ToolTip>

                    <Default>MyRegion</Default>

                </Literal>

            </Declarations>

            <Code Language="csharp"><![CDATA[#region $name$

        $selected$ $end$

    #endregion $name$]]>

            </Code>

        </Snippet>

    </CodeSnippet>

</CodeSnippets>

Code Snippets Manager:

image

Code Snippets are really cool and easy to use.  For more information, please see this post.

I’ve seen a few posts describing how to use a Uri as a source for a BitmapImage, and then the BitmapImage as the source for the WriteableBitmap.  But that didn’t work so well until I figured out the trick.  Here goes…

First, here is the code that I THOUGHT would work, but did not.

Uri uri = new Uri("http://somedomain.com/someimage.png");
BitmapImage bitmapImage = new BitmapImage(uri);
WriteableBitmap writeableBitmap = new WriteableBitmap(bitmapImage);

When you run that, you’ll most likely get an exception (I did) because the BitmapImage is not set when it is used for the WriteableBitmap.  My hypothesis was that the BitmapImage doesn’t render itself until it is needed.  I started looking through the properties of the BitmapImage, luckily there aren’t too many, when I came across the CreateOptions property – that sounded interesting!  It is an Enum with 3 values: DelayCreation, IgnoreImageCache, and None.  Guess which one is set as the default?  DelayCreation!  Here was my next pass at the code:

Uri uri = new Uri("http://somedomain.com/someimage.png");
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.CreateOptions = BitmapCreateOptions.None;
bitmapImage.UriSource = uri;
WriteableBitmap writeableBitmap = new WriteableBitmap(bitmapImage);

That’s it, pretty simple and it works.  But I took it one step further just in case.  I’m not positive this is necessary but I like to play it safe.  When inspecting the properties of the BitmapImage, I saw there is an ImageOpened event. I was thinking that some images may load slowly and I wasn’t sure if that happens asynchronously or not.  Would my application wait around for them to finish loading?  I don’t really know but it sure sounds like the ImageOpened event would be a way to make sure my images were loaded.  Here is my final take:

public void SomeMethod()
{
    Uri uri = new Uri("http://somedomain.com/someimage.png");
    BitmapImage bitmapImage = new BitmapImage();
    bitmapImage.CreateOptions = BitmapCreateOptions.None;
    bitmapImage.ImageOpened += ImageOpened;
    bitmapImage.UriSource = uri;
}

void ImageOpened(object sender, RoutedEventArgs e)
{
    BitmapImage bm = (BitmapImage)sender;

    WriteableBitmap wbm = new WriteableBitmap(bm);

    //now I can use wbm for whatever I need...
}

Good luck with your WriteableBitmaps!

I’m a big fan of the MVVM Pattern for Silverlight development, so naturally I was excited about Silverlight 4 having support for Commanding.  I recently upgraded my current project to Silverlight 4 and I found that binding my buttons to my View Model commands was pretty easy.  However, it wasn’t long before I needed to create a custom control and I wasn’t sure how the Command Binding would work.  I searched the web for some samples but found none so I was on my own.  It wasn’t too hard to figure out the solution, here is how I did it.

The setup… For the sake of this demo, I’ll need a resuable control that combines 2 buttons:  Save and Cancel.  I’ll call it a SaveCancel control :).  The control is simple enough.  Thanks to Silverlight 4, buttons already support the command binding – all you have to do is bind the command in your View Model to the Command property of the button (and optionally the CommandParameter property).  If you aren’t familiar with the basics of commanding, I suggest you check out this blog post by John Papa.  Anyway, when it is time to use the SaveCancel control on another page/control, it becomes pretty clear that you can’t access the individual button’s properties to bind to them!  The individual buttons are not publicly available since they are “child” controls of the SaveCancel control.  The solution:  The Command and CommandParameter properties of each button are just DependencyProperties so all you have to do is create matching properties on the new control that “wrap” the internal properties.

Here’s how it’s done…

First, the XAML of the SaveCancel control is pretty straightforward:

<UserControl x:Class="CustomControlWithCommanding.SaveCancel"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" >
    
    <StackPanel x:Name="LayoutRoot" Orientation="Horizontal" >
        <Button x:Name="Save" Width="50" Height="25" Content="Save" Margin="0,0,5,0" />
        <Button x:Name="Cancel" Width="50" Height="25" Content="Cancel" />
    </StackPanel>
</UserControl>

Next the Code Behind of the SaveCancel control.  Here is where all of the wiring is done for each button’s commands. There are a few parts.  First is the DependencyProperty for the Save button’s command.  Like any dependency property, you need a public property with a Get/Set that sets the value of the Dependency Property as well as a DependencyProperty:

public ICommand SaveCommand
{
    get { return (ICommand)GetValue(SaveCommandProperty); }
    set { SetValue(SaveCommandProperty, value); }

}
public static readonly DependencyProperty SaveCommandProperty =
    DependencyProperty.Register("SaveCommand", typeof(ICommand), typeof(SaveCancel), 
                                new PropertyMetadata(null, OnSaveCommandChanged));

Note that in the PropertyMetaData argument for the SaveCommandProperty we are passing in a callback reference (OnSaveCommandChanged).  We’ll use that method to set the value of the new DependencyProperty to the actual Save button.  Here is the code:

private static void OnSaveCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    SaveCancel sc = (SaveCancel)d;
    sc.Save.Command = (ICommand)e.NewValue;
}

To be complete, we’ll do some similar work to make sure that we can wire up the CommandParameter to the Save button as well, even though we don’t really need it to make the button work for this sample.  

public object SaveCommandParameter
{
    get { return GetValue(SaveCommandParameterProperty); }
    set { SetValue(SaveCommandParameterProperty, value); }

}

public static readonly DependencyProperty SaveCommandParameterProperty =
    DependencyProperty.Register("SaveCommandParameter", typeof(object), typeof(SaveCancel), 
        new PropertyMetadata(null, OnSaveCommandParameterChanged));

private static void OnSaveCommandParameterChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    SaveCancel sc = (SaveCancel)d;
    sc.Save.CommandParameter = e.NewValue;
}

To use the new SaveCancel control in another Silverlight control, all I need is some code like the sample below.  It works perfectly with no events wired up and no code behind on the page where it is used!

<CustomControlWithCommanding:SaveCancel SaveCommand="{Binding SaveCommand}" 
                                        CancelCommand="{Binding CancelCommand}" />

Of course, my ViewModel must have the commands (SaveCommand and CancelCommand) to support this as well.  But that is just normal ViewModel commanding.  Again, if you aren’t familiar with that, check out John Papa’s blog post.

Complete Source Code:

To see the complete sample solution, download it here.