In a previous post I wrote about some tips for creating WP7 apps which included using the CameraCaptureTask.  A reader responded, asking how to save the picture.  So I figured I’d write a more detailed response with some samples.

In this post I’ll show 3 easy sample:

  1. How to simply use the camera and display a photo.
  2. How to save an image to IsolatedStorage (and change the size of the photo too!)
  3. How to save an image to the phone’s media library.

All of these are pretty simple.  I’m sure once you get started you can easily modify this code to do more creative things. 

First, you’ll need to define a CameraCaptureTask.  You should always do so as a class level variable.   You should also wire up the Completed handler in the constructor  These steps are important for dealing with application tombstoning.  For more on this, please read this article.

private CameraCaptureTask _cameraCaptureTask;

public MainPage()
{
    InitializeComponent();

    _cameraCaptureTask = new CameraCaptureTask();
    _cameraCaptureTask.Completed += CameraCaptureTaskCompleted;

}

How to simply use the camera and display a photo:

You’ll need to kick off the camera task, I’m using a button.  
private void SimpleTest_Click(object sender, EventArgs e)
{
    try
    {
        _cameraCaptureTask.Show();
    }
    catch (InvalidOperationException ex)
    {
        // Catch the exception, but no handling is necessary.
    }

}
In my XAML, I’ve defined an Image named MainImage
<Image x:Name="MainImage" />

Now when the CameraCaptureTask is complete, just bind the results of the task to the Image as I’m doing here:

void CameraCaptureTaskCompleted(object sender, PhotoResult e)
{
    if (e.TaskResult == TaskResult.OK)
    {
        //simply use the picture.
        BitmapImage bitmapImage = new BitmapImage();
        bitmapImage.SetSource(e.ChosenPhoto);
        MainImage.Source = bitmapImage;
    }
}

Easy, right?

How to save an image to IsolatedStorage (and change the size of the photo too!)

In this case I want to save the image to IsolatedStorage.  In addition, the app I was creating didn’t need full size images.  So I figured, why waste space in the user’s IsolatedStorage?  So I use a WritableBitmap and change the size of the image.  You’ll notice that after I save the image, I read it back and bind the results to another image named SmallerImage.  That’s just to prove that saving it really worked!

void CameraCaptureTaskCompleted(object sender, PhotoResult e)
{
    if (e.TaskResult == TaskResult.OK)
    {
        //here I save the image to Isolated Storage.  Also I am changing the size of it to not waste space!
        WriteableBitmap writeableBitmap = new WriteableBitmap(200, 200);
        writeableBitmap.LoadJpeg(e.ChosenPhoto);

        string imageFolder = "Images";
        string imageFileName = "TestImage.jpg";
        using (var isoFile = IsolatedStorageFile.GetUserStoreForApplication())
        {

            if (!isoFile.DirectoryExists(imageFolder))
            {
                isoFile.CreateDirectory(imageFolder);
            }

            string filePath = Path.Combine(imageFolder, imageFileName);
         using (var stream = isoFile.CreateFile(filePath))
            {
                writeableBitmap.SaveJpeg(stream, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight, 0, 100);
            }
        }

        //now read the image back from storage to show it worked...
        BitmapImage imageFromStorage = new BitmapImage();

        using (var isoFile = IsolatedStorageFile.GetUserStoreForApplication())
        {
            string filePath = Path.Combine(imageFolder, imageFileName);
            using (var imageStream = isoFile.OpenFile(
                filePath, FileMode.Open, FileAccess.Read))
            {
                imageFromStorage.SetSource(imageStream);
            }
        }
        SmallerImage.Source = imageFromStorage;
    }
}

How to save an image to the phone’s media library.

This one is pretty easy too.  Just remember to add a reference to Microsoft.Xna.Framework or you can’t access the Media Library. Also, you’ll need this using statement:

using Microsoft.Xna.Framework.Media;
void CameraCaptureTaskForSavingToLibraryCompleted(object sender, PhotoResult e)
{
    byte[] imageBits = new byte[(int)e.ChosenPhoto.Length];
    e.ChosenPhoto.Read(imageBits, 0, imageBits.Length);
    e.ChosenPhoto.Seek(0, SeekOrigin.Begin);
    MediaLibrary library = new MediaLibrary();
    library.SavePicture("TestPhoto", imageBits);
}

Hopefully you’ll see that using this feature is pretty easy.

I recently started writing my first Windows Phone 7 Application.  I was shocked at how easy it was to get started although I’ll admit that has a lot to do with my existing knowledge of Silverlight.  If you don’t know Silverlight, now is a great time to learn it.  You can write apps for the web, desktop, and Windows Phone 7 too! 

As I wrote my application, I compiled a list of tips to share.  I spent a bunch of time tracking some of these down or figuring them out.  I hope this will be helpful to other people.  Plus, I’ll use this as a reference for myself when I create my next app!

Here you go.  The first two are pretty basic, but worth mentioning.

Tip:  Go For It!

The best advice is to install the tools and try it out for yourself.  If you create an application from one of the templates (you’ll get them after you install the tools for Visual Studio) you find that the templates themselves are a great learning tool.  Some include samples for styling, data binding, design time data binding, navigation, and more!  I recommend trying each of the templates out.

Tip: Install the Free Tools

This isn’t really a tip.  You can’t create apps without doing this!  Visit the App Hub to download the free tools.  You get all this for free: VS 2010 Express, the Windows Phone Emulator, Expression Blend for Windows Phone, and more!  Also, don’t forget to install Silverlight for Windows Phone Toolkit from the CodePlex site.  It includes some additional controls that are great like AutoCompleteBox, ContextMenu, GestureListener and more!  By the way, when you are at the App Hub, check out all the great learning resources.  By the way, you should keep in mind that Windows Phone 7 is a subset of Silverlight 3!  That means that most features of 3 are there but not all.  And Silverlight 4 features are obviously not included.

Tip: Using the Software Input Panel

The Software Input Panel (SIP) is the “on screen” keyboard that users use to key in data.  It’s pretty cool and has some great features.  First, you don’t need to turn it on.  If you include a TextBox in your app, when it gets focus the SIP will appear.  But there are many versions of the SIP and you can easily configure which one appears by setting the InputScope property of your TextBox.  You can get a full list of the options here.  If you want users to enter numbers, set InputScope to Digits.  For email address entry, try EmailNameOrAddress and the keyboard will include the @ sign.  Some choices are more subtle.  Choosing AddressCountryName may seem like the typical keyboard but the first letter typed will be capitalized, remaining character will be lower case.  There are many cool and smart features like that.  Also, options like Text or Chat will include word suggestions!  Here are some code samples and screen shots:

<TextBox InputScope="EmailNameOrAddress" Height="75" />
<TextBox InputScope="Text" Height="75" />

image     image

The first screenshot is the SIP when the EmailNameOrAddress version has focus.  In the second screen shot (TextBox InputScope set to Text), I typed a few letters and you can see the word suggestions!

Tip:  Orientation

If you want your application to support both portrait and landscape mode (when the user tilts the phone over), you need to set up each page’s SupportedOrientations property to do so as follows.  Set the default value in the Orientation property.

<phone:PhoneApplicationPage 
    x:Class="WindowsPhoneApplication1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    SupportedOrientations="PortraitOrLandscape"  Orientation="Portrait"

Tip: UI Design

First, you should check out the UI Design and Interaction Guide for tips on how to properly design and style the look and feel of your application.  Also, you should try to use the standard styles provided when you create an application.  Setting the style in this way will give your application a consistent look.  Here are a few samples:

<TextBlock x:Name="ApplicationTitle" Text="Demo" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="first page" Style="{StaticResource PhoneTextTitle1Style}"/>

Tip: Using Isolated Storage

For simple values, you can easily get in and out of IsolatedStorageSettings.ApplicationSettings (Dictionary). For more complex data, you can put it into IsolatedStorage.  Since there is no database available in Wp7, one common approach to saving data is to simple serialize your model and save it as a file.  To do so, make sure you mark all of your Model’s classes with the attribute DataContract and make sure the properties have the DataMember attribute.  Here’s a sample class called ListOfStuff as well as the methods I use to read/write it to/from IsolatedStorage:

[DataContract]
public class ListOfStuff : Observable
{
    [DataMember]
    public string Title
    {
        get { return _title; }
        set
        {
            if (_title != value)
            {
                _title = value;
                NotifyPropertyChanged("Title");
            }
        }
    }
    private string _title;

    [DataMember]
    public ObservableCollection<ListCategory> Categories
    {
        get { return _categories; }
        set
        {
            if (_categories != value)
            {
                _categories = value;
                NotifyPropertyChanged("Categories");
            }
        }
    }
    private ObservableCollection<ListCategory> _categories = new ObservableCollection<ListCategory>();
}
public static void SaveToFile(ListOfStuff listOfStuff)
{
    using (IsolatedStorageFile isolatedStorageFile =
    IsolatedStorageFile.GetUserStoreForApplication())
    {
        using (IsolatedStorageFileStream stream =
        new IsolatedStorageFileStream(string.Format("{0}.dat", listOfStuff.Title), FileMode.Create, isolatedStorageFile))
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(ListOfStuff));
            serializer.WriteObject(stream, listOfStuff);
        }
    }
}

public static ListOfStuff LoadFromFile(string listName)
{
    ListOfStuff listOfStuff = null;
    using (IsolatedStorageFile isf =
    IsolatedStorageFile.GetUserStoreForApplication())
    {
        using (IsolatedStorageFileStream stream = 
        new IsolatedStorageFileStream(string.Format("{0}.dat", listName), FileMode.OpenOrCreate, isf))
        {
            if (stream.Length > 0)
            {
                DataContractSerializer serializer = new DataContractSerializer(typeof(ListOfStuff));
                listOfStuff = serializer.ReadObject(stream) as ListOfStuff;
            }
        }
    }
    return listOfStuff;
}

Tip: Using the Phone’s Camera

Using the phone couldn’t be simpler, just use the CameraCaptureTask as follows:

**NOTE: As reader Andy Wilkinson pointed out in a comment to this post, I’m not following best practices here.  The way I declare my CameraCaptureTask could lead to problems with tombstoning.  He points out a nice article on MSDN that explains the proper use, please read it here.  Thanks, Andy, for the assistance!

**Another Note:  Another user asked about saving the results of the CameraCaptureTask.  So I’ve written another post that you may find useful.  Please check it out here.

private void Camera_Click(object sender, RoutedEventArgs e)
{
    CameraCaptureTask cameraCaptureTask = new CameraCaptureTask();
    cameraCaptureTask.Completed += cameraCaptureTask_Completed;
    cameraCaptureTask.Show();
}
After the picture is taken, you can access it later, as a Stream.  You can assign it to an Image, save it, or do whatever you want.
void cameraCaptureTask_Completed(object sender, PhotoResult e)
{
    var photoStream = e.ChosenPhoto;
}

Tip: Using Gestures

Of course, you want your application to react when users use common phone Gestures such as Flick, Pinch, Hold, etc.  Doing so is easy too!  The Silverlight Toolkit for Windows Phone (mentioned in second tip above) provides the GestureListener that you will need.  You can see how simple it is to wire up in the following example. In this case, I want the user to be able to hold their finger down on an image to go to “edit mode” where a description TextBox will appear.  In the NoteHold() method (not shown), you can imaging all I need to do is set the description TextBox to be visible.

<Image Source="{Binding Image}">
    <ToolkitControls:GestureService.GestureListener>
        <ToolkitControls:GestureListener Hold="NoteHold" />
    </< span>ToolkitControls:GestureService.GestureListener>
</< span>Image>

Now go start creating apps!

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 said this so many times, writing unit tests is easy if the code was written well in the first place.  And when I say “written well”, what I really mean is “written to be testable”.

So here is the situation:  I have a simple service that does some logging, most of the details are not important.  But in the LogDebug() method, the code checks the web.config file to see if the debug logging is enabled.  That too in itself is pretty simple stuff.  Typically it would look like this:

bool configDebugMode = bool.Parse(WebConfigurationManager.AppSettings["Logging.Debug"]);

EDIT: I should point out what I mean when I say below that testing this code isn’t very easy. Sure, testing it is easy if I only want to test one value from the web.config file, such as ‘true’. But in this situation, I want to test when the config file value is ‘true’, and also when it is ‘false’.

But testing that isn’t very easy at all.  You’d have to do some crazy stuff with multiple config files or something.  But if the code was written differently, it’s very easy to test.  The key is to wrap the call to WebConfigurationManager in another class that implements and interface, then use dependency injection.  And with the class designed like that, you can use a simple mock to make the testing simpler.  It’s really easy, here is how I’m doing it.

First I define an interface, I’m calling it IConfigurationManager: 

public interface IConfigurationManager
{
    string GetAppSetting(string key);
    ConnectionStringSettings GetConnectionString(string key);
}

The interface has two simple methods so I can use it to get AppSettings and ConnectionStrings.  Could be I’ll need to add some more methods later but I don’t need them yet.  Next I implement the interface in a concrete class that can get the values from the web.config.  This too is really simple.  I’m calling this class WebConfigConfigurationManager.  That may sound weird and redundant but it tells me that it is a ConfigurationManager that gets values from WebConfig.  If I need an implementation that pulls values from a db I could make another one called DbConfigurationManager.  Here is the code:

public class WebConfigConfigurationManager : IConfigurationManager
{
    public string GetAppSetting(string key)
    {
        return WebConfigurationManager.AppSettings[key];
    }

    public ConnectionStringSettings GetConnectionString(string key)
    {
        return WebConfigurationManager.ConnectionStrings[key];
    }
}

So far this is was pretty easy to write and you can see it isn’t too complicated so it should work pretty well.  But this doesn’t make it any more testable.  The key to making it testable is Dependency Injection.  My LoggingService will “depend on” this WebConfigConfigurationManager class.  But instead of just instantiating WebConfigConfigurationManager within LoggingService, I’ll inject it in.  By doing that, I’ll also be able to inject something different during unit tests.  Hang in there, I’ll show you how.  First, here is the injection part, it is much simpler than it sounds. I inject the dependency via the constructor, you’ll note I am injecting a few other dependencies too:

public LoggingService(IEnterpriseLoggingRepository loggingRepository,
                        ILoggingInformationAdapter loggingAdapter,
                        IConfigurationManager configurationManager)
{
    if (loggingRepository == null) { throw new ArgumentNullException("loggingRepository"); }
    _loggingRepository = loggingRepository;

    if (loggingAdapter == null) { throw new ArgumentNullException("loggingAdapter"); }
    _loggingAdapter = loggingAdapter;

    if (configurationManager == null) { throw new ArgumentNullException("configurationManager"); }
    _configurationManager = configurationManager;
}

If you were expecting something fancy, sorry to disappoint you. The Dependency Injection part is pretty simple too.  Here is the LogDebug() method too.  Please don’t worry about the details of _loggingAdapter.ToDomainModel().  That is something I need to turn the “message” into something that the LoggingRepository can work with. 

public void LogDebug(string message)
{
    try
    {
        //are we in debug mode?
        bool configDebugMode = bool.Parse(_configurationManager.GetAppSetting("Logging.Debug"));

        if (!configDebugMode)
            return;

        //convert the message into something the logging repo can use.
        LoggingData data = _loggingAdapter.ToDomainModel(message);

        //log it!
        _loggingRepository.LogDebug(UiSystem, data);
    }
    catch (Exception loggingException)
    {
        // if an exception occurred during logging, capture the message that was being logged in the first place
        throw new LoggingException(loggingException) { OriginalMessage = message };
    }
}

OK the code is written, so how does this make the testing easier?  Since the tough to test code is in a dependency, when I write the test, I can inject something different in.  In this case, I want to inject in a class that I can easily control and return either true or false for the Logging.Debug setting.  There are a bunch of ways to do this, I’ll use a mocking framework to help.  In this case I’m using MOQ.  Here’s most of the code from my NUnit TestFixture (I took out a bunch of extra tests for brevity.  An explanation follows.

[TestFixture]
public class LoggingServiceTests
{
private Mock<IEnterpriseLoggingRepository> _loggingRepository;
private Mock<ILoggingInformationAdapter> _adapter;
private Mock<IConfigurationManager> _configurationManager;
private LoggingService _loggingService;

[SetUp]
public void Setup()
{
    _loggingRepository = new Mock<IEnterpriseLoggingRepository>();
    _adapter = new Mock<ILoggingInformationAdapter>();
    _configurationManager = new Mock<IConfigurationManager>();
    _loggingService = new LoggingService(_loggingRepository.Object, _adapter.Object, _configurationManager.Object);

}

[Test]
public void LoggingDebugIsSkippedIfConfigSettingIsFalse()
{
    _configurationManager.Setup(cm => cm.GetAppSetting("Logging.Debug")).Returns("false");

    _loggingService.LogDebug("This is a test");

    _adapter.Verify(a => a.ToDomainModel(It.IsAny<string>()), Times.Never());
    _loggingRepository.Verify(lr => lr.LogDebug(It.IsAny<string>(), It.IsAny<LoggingData>()), Times.Never());
}

[Test]
public void LoggingDebugIsExecutedIfConfigSettingIsTrue()
{
    _configurationManager.Setup(cm => cm.GetAppSetting("Logging.Debug")).Returns("true");

    _loggingService.LogDebug("This is a test");

    _adapter.Verify(a => a.ToDomainModel(It.IsAny<string>()), Times.Exactly(1));
    _loggingRepository.Verify(lr => lr.LogDebug(It.IsAny<string>(), It.IsAny<LoggingData>()), Times.Exactly(1));
}

If you aren’t familiar with Mocking or MOQ, you may want to read up on the topic.  I’ll try to hit the highlights.  Check out the SetUp() method.  You can see that instead of using “real” classes, I instantiate a bunch of Mocks so I can control them easily.  In the last line of the method I “inject” the mocks into the LoggingService.  Next, let’s examine the method LoggingDebugIsSkippedIfConfigSettingIsFalse().  The first line of code pretty much says when the ConfigurationManager’s GetAppSetting() method is called with the argument “Logging.Debug”, just return false.  I really like the MOQ syntax, if you are used to Lambda expressions, the MOQ stuff reads pretty easily, I think.  The mock class won’t actually look at a config file or anything.  Remember, this is a mock so there is no implementation.  With code like this, you can actually step through with the debugger and see the mocks act as you told them too!  If you look back to the actual LogDebug() method you will see that if the Logging.Debug value is false the method simply ends.  So then the last two lines of code in the test verify that the adapter’s ToDomainModel() and the logging repository’s LogDebug() method are never called at all!  That’s all there is to it.  Plus the second unit test shown here does the opposite, it makes sure that all of the code is executed if Logging.Debug is set to true.

I can assure you it took me a lot longer to write this blog post than it did to code the IConfigurationManager, WebConfigConfigurationManager, and LoggingServiceTests.  I hope you find this code helpful.

Code snippets are a great time saver and they are pretty simple to create.  Any time you find yourself typing the same thing over and over again, you may want to consider creating your own code snippet to make life easier.

Here’s an example… I was recently working on a large refactor of some error handling code for a user interface.  Basically, I went from form to form, refactoring the way the error handling was implemented and then test it.  How did I test it?  By throwing exceptions in my code.  Doing so is pretty easy, just find the portion of code that needs to be tested and type “throw new Exception(“This is a test”);”  Plus, for good measure and safety I’d add this above it: “//TODO – Don’t forget remove this test code”

//TODO:  Don't forget to remove this test code:
throw new Exception("This is a test");

Sure, it is easy enough to type but it got old pretty quick and I decided to create a simple snippet.  Once I did, all I needed to type was “tne” (it stands for “Throw New Exception) and hit “tab” twice (hitting “Tab” twice tells Visual Studio to use the code snippet based on what you just typed).  Sounds cool huh?  Ok so here is how you create a simple code snippet…

Snippets are stored in XML files on your pc.  To create a new one, it is easiest to just start with an existing snippet and modify the xml to meet your needs.  Here is an example of the one I am using:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>Throw new Exception</Title>
      <Shortcut>tne</Shortcut>
      <Description>This will generate code to throw a new Exception</Description>
      <Author>Andy Schwam</Author>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
    </Header>
    <Snippet>
      <Code Language="csharp">
        <![CDATA[    //TODO: Remove this test code:
        throw new Exception("An Exception has been thrown"); $end$]]>
      </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

If you want to use your own snippet, just change the Title, Shortcut, Description and Author elements.  And of course, you need to put your snippet inside of the CDATA area of the the Code Element.

Next, you just need to save this file in a place where Visual Studio will pick it up.  To tell VS2008 where to look for it, go to Tools > Code Snippets Manager.  Make sure you select the correct language in the drop down, otherwise Visual Studio can’t connect your snippet to the language you meant it for.  You’ll also notice the existing folders for snippets.  That may give you an idea of where you should store your own snippets ;).

You can also write more complex snippets that allows you to use the snippet and then type in values that get used within the snippet.  For instance, I do a lot of work with Silverlight and for databinding my public variables must implement INotifyPropertyChanged.  Instead of manually typing a property that does so, plus a backing variable, I use a snippet with the shortcut “npc”.  In the sample below, you will see the words TYPE, PROPERTY and FIELD highlighted in Green.  Those are placeholders and when I utilize the code snippet, VS will prompt me to replace those values.  So if I want to create a public property and backing variable for a string FirstName, I just type the following:  “npc” TAB TAB “string” TAB “FirstName” TAB “_firstName” (but don’t type the quotes!).  It may seem weird at first but makes coding much easier.

private TYPE FIELD; 

image

Here is the XML for my “NotifyPropertyChanged” snippet:

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

<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>Notify Property Changed Property</Title>
      <Shortcut>npc</Shortcut>
      <Description>Code snippet for creating a property with a backing variable that calls NotifyPropertyChanged</Description>
      <Author>Andy Schwam</Author>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
    </Header>
    <Snippet>
      <Declarations>
        <Literal>
          <ID>type</ID>
          <ToolTip>The Type for the Property</ToolTip>
          <Default>TYPE</Default>
        </Literal>
    <Literal>
          <ID>fieldname</ID>
          <ToolTip>The Type for the field</ToolTip>
          <Default>FIELD</Default>
        </Literal>
    <Literal>
          <ID>propertyname</ID>
          <ToolTip>Parameter name</ToolTip>
          <Default>PROPERTY</Default>
        </Literal>
      </Declarations>
      <Code Language="csharp">
        <![CDATA[
    public $type$ $propertyname$ {
    get { return $fieldname$; } 
    set 
    { 
    if ($fieldname$ != value) 
    { $fieldname$ = value; 
    NotifyPropertyChanged("$propertyname$");
    }
    }
    }
    private $type$ $fieldname$; 
    $end$]]>
      </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

Unfortunately, there isn’t a Code Snippet Editor included in VS.  There is some kind of plug-in available for creating VB snippets but I’ve never used it.  I’m sure you can find it with your favorite search engine.  Still it is pretty easy to write these yourself.