Friday, August 13, 2010

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!
Friday, August 13, 2010 9:22:52 PM (Eastern Standard Time, UTC-05:00)  #    Disclaimer  |  Comments [5]  |  Trackback
 Wednesday, August 04, 2010

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.

Wednesday, August 04, 2010 9:05:17 PM (Eastern Standard Time, UTC-05:00)  #    Disclaimer  |  Comments [1]  |  Trackback
 Sunday, July 25, 2010

There seems to be a bug in Visual Studio 2010 when adding references to Silverlight projects.  You can add “regular” .Net references just fine using the add reference dialog.  However if you use the browse feature to find a reference in an “unusual” location, Visual Studio is supposed to record that location along with the reference in the .csproj file.  It includes the location via the HintPath property.

At my company, we use build machines and we don’t like to install a lot of software on them.  So in source control we have a folder (assets\lib) that includes all of the necessary .dll files that we need to build or projects.  When we add references to our project, like for a Silverlight control library, we add it from the assets\lib\Silverlight folder, even though that library is installed on my local machine.  Anyway, when I tried doing this in Visual Studio 2010 (I’m upgrading our existing 2008 solution), VS 2010 isn’t including the HintPath.  If you aren’t careful, you may not realize this is happening.  That’s because since the library is installed on my machine, the build works just fine, except it pulls the .dll from the wrong place.  If I were to try this build from my build server, it would fail though. 

Anyway, here is the workaround.  It’s a pain but it works…

  1. Add your references as you would normally do it via Visual Studio.
  2. Right click the project file in the Solution Explorer and choose Unload Project.
  3. Once the project is unloaded, right click again and chose edit.  This will open the file, and xml document, in Visual Studio.
  4. Find the incorrect reference in the file and edit it manually.  You’ll need to make it look something like this:
    <Reference Include="System.Windows.Controls, Version=2.0.5.0, Culture=neutral, 
    PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL
    " > <HintPath>..\..\..\Assets\lib\Silverlight\System.Windows.Controls.dll</HintPath> </Reference>
  5. Save the file and close it.
  6. Reload the project.

When you are done you can verify that it works.  Here’s how…

  1. In Visual Studio, choose Tools > Options.
  2. Find the Projects and Solutions section and select Build and Run.
  3. In the section “MsBuild Project build output verbosity”, select “Detailed”.
  4. Now build your project.  When you do so, you’ll see a lot of details of what goes on in the Output Window.  You’ll need to find the output that relates to the file that you specified, in my case it is System.Windows.Controls and the important output looks like this:

    Primary reference "System.Windows.Controls, Version=2.0.5.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35".
          Resolved file path is "C:\Projects\MC\BackOffice\UI\branches\2010Migration\Assets\lib\Silverlight\System.Windows.Controls.dll".
          Reference found at search path location "{HintPathFromItem}".

  5. You will note that it tells you specifically which path was used to resolve the reference!  And if you are so lazy that you don’t want to read the entire path used, you see that it says the reference was found at the search path location “{HintPathFromItem}”.  That means it used the path you specified.

I hope this helps!  Good luck and let’s hope they fix this bug soon.

Sunday, July 25, 2010 2:19:34 PM (Eastern Standard Time, UTC-05:00)  #    Disclaimer  |  Comments [5]  |  Trackback
 Thursday, July 08, 2010

We went to the beach for a long weekend as a family of three, we came home as a family of four!  Here are the details of our adventure.  Read it if you want or just look at the pictures!

On Thursday afternoon Rebecca went for her weekly checkup at the doctor.  Our baby was due in 3.5 weeks but they said she was doing great and had nothing to worry about.  We should go enjoy ourselves at the shore.  We were both really looking forward to the long weekend.  We had just found a new house, sold our house (although both closings are in September), and we have a baby on the way.  Plus our son Ben was really hitting his stride as a two year old, mastering the art of “No”.  So some time off was really in order.  We had a nice relaxing day on Friday, the weather was perfect and Ben was having a blast playing in the sand.

IMG_0014IMG_0023

Ben at the beach playground with cousins Hannah and Sam.  And Ben playing with Hannah (and Uncle Andy)

Part 1 – Controlled Panic:  Later that evening we were headed for a walk on the boardwalk with family.  Ben and I were a few minutes ahead of Rebecca.  When Rebecca didn’t follow us, we had to head back to see what was up.  We met up with Rebecca and she said “I think my water just broke”.  FYI, that didn’t happen when Ben was born so she wasn’t positive what was happening.  There was a lot of family at the house and lots of opinions and ideas.  “You should call the doctor”, “You should pack up and leave”, “Relax and go for a walk”, etc.  We called the doctor back home.  Keep in mind, we’re on the Jersey shore near Atlantic City, about 1.5 hrs from home.  The doctors advice was to head right to the hospital.  After water breaks anything could happen, and happen fast.  I thought, the last thing we want to have happen is to deliver a baby on the side of the AC Expressway.  Next, we had a nice family discussion/argument about which hospital to go to.  There were three to choose from.  My brother-in-law and sister-in-law took charge of that and called to figure out which is best.  That was a big help.  By this time it was about 8:30pm.  The next problem to deal with was how to get Ben to sleep.  Since it is the beginning of the summer, the house is a bit strange to him and he wanted me to sleep in the room with him.  I laid down for a while and every minute felt like an hour.  He finally fell asleep, we packed up and we were off to Atlanticare Regional Medical Center Mainland Campus. 

IMG_0796 On our walk before things got interesting.  Ben’s with cousin Sylvia (Sylvie) but Ben calls her “So-be”.  I think he is love with her.

One nice part of this whole crazy situation is that we had plenty of people to help with Ben.  If we were at home we would have had to find someone to come over and watch him for the night, plus we’d need people to help out all weekend long too.  Instead, we just drove off.  Well, first we spewed out a bunch of instructions about how to keep him happy while everyone nodded their heads saying “Sure, we’ve got it”.  Most of it didn’t matter, we knew he’d be in great hands if they followed our advice or not.

Part 2 – Hurry Up and Wait:  We got to the hospital and finally were in our room by around 11pm or so.  The staff now told Rebecca that since her water broke, she had to stay in bed.  Rebecca was seriously unhappy with that information.  When Ben was born she was told the best way to work through labor and keep things moving was to be up and around.  And she wasn’t that far along, so we’d likely not have a baby until the next day!  We both slept in the hospital but I’m sure that everyone knows you can’t really get much sleep in a hospital. 

Part 3 – Time to Rock and Roll:  Around 5:30 am they gave Rebecca a shot of Pitocin to move things along.  At 6:30 they injected some pain killers into her epidural and at 7:30 am on July 3rd Sarah Maya Schwam was born!  She weighed 5 lbs, 12 oz and was 19.25 inches long.  As a side note, I thought she looked shorter than that.  This week the pediatrician measured her at 18.5 inches.  I’m not sure what is up with that.  Being 3.5 weeks early, the staff was a little concerned and put the NIC unit on alert.  But after a check up, they decided that she was ok to stay with us and they’d keep an extra close eye on her.  That was a BIG relief to us.  10 fingers, 10 toes, and TONS of dark brown hair and cute as a button (whatever that means). 

IMG_0028 IMG_0808 IMG_0815 IMG_0821 IMG_0831 IMG_0850

Part 4 – Now What?:  OK, so we’ve got a healthy baby but we are pretty far from home with no “baby stuff”.  Well it turns out you don’t need too much stuff and in our neck of the woods (even down at the shore) there are always stores around.  My sister-in-law Dawn hit the drug store for some diapers and stuff, and a little boutique at the beach for a few outfits.  But you can’t leave the hospital without a car seat!  We planned to send the family out to Baby’s R Us to buy a new one when a few friends came to the rescue.  Neighbors Megan and Glen were on their way to the shore for July 4th when they saw my email baby announcement.  They offered to stop at our house and pick up the baby seat and other supplies and drop them at the hospital!  How cool is that?  We were all set!

IMG_0849 IMG_0840 IMG_0860

Our family including Aunt Dawn, Megan (who came to our rescue) and Sarah, and the four of us leaving the hospital via the required wheel chair.

Part 5 – Home At Last:  After 2 nights in the hospital (3 if you count the night before Sarah was born) everyone was released and we went back to the beach house.  It was Monday of a holiday weekend and we didn’t want to get stuck in any traffic coming home so we spent the night at the beach.  Of course, we didn’t have a bassinette there so we had to improvise with a drawer!   By noon on Tuesday we were finally back in our house!  It was great coming home and Benny was really happy.  I think the trip was toughest on him.

IMG_0865 IMG_0869 IMG_0883

Sarah with Rebecca’s dad, with my Mom, in her drawer (it looks safe and comfy, right?). 

What a crazy “vacation” this turned out to be!  It would have been a lot harder without our family that helped out so much with Benny.  He had a great time playing at the beach with his cousins.  I have no idea how we could have got through this without the family helping out.  Now Benny is totally in love with Sarah, like nothing I have ever seen before.  He just wants to kiss her and hug her and tickle her and just be around her ALL of the time.  “I want Sarah” is the new phrase heard around the house… over and over and over again.  We’re glad he likes her but it is making us a little crazy.  I’ve been told that this will wear off pretty soon and he’ll get used to having her around.  Having a sister certainly did not cure the “terrible two’s”.  This little guy really tries to run the show around here.  Lucky for us he’s still a sweet kid most of the time.

 |  | 
Thursday, July 08, 2010 8:17:14 PM (Eastern Standard Time, UTC-05:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Tuesday, May 25, 2010

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.

 |  |  |  |  | 
Tuesday, May 25, 2010 10:37:59 PM (Eastern Standard Time, UTC-05:00)  #    Disclaimer  |  Comments [5]  |  Trackback
 Sunday, May 02, 2010

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.

Sunday, May 02, 2010 3:36:46 PM (Eastern Standard Time, UTC-05:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Saturday, April 17, 2010

I’ve been working on continuous integration and automated builds/deployment lately.  I put together a MSBuild script that does a whole bunch of typical stuff including getting code from my repository, compiling, and running tests.  I also want to create a Tag in my Subversion repository so I know which code was deployed.  That wasn’t too hard to do either.  The tricky part was that I want my build to fail if I try to make a Tag that already exists!

I fumbled around with this for a while trying a wide variety of ideas.  In the end, it turned out to be pretty simple.  There may be better ways to accomplish this, but here is how I am doing it…

I’m using the SvnClient task (it’s part of the MSBuild.Community.Tasks download) and executing a command:  “ls $(SvnRepository)/tags/$(SvnTagName)”.  Of course, my MSBuild script already has the variables $(SvnRepository) which is the path to my repository and $(SvnTagName) which is the name of the Tag I hope to create.  You may have to tweak this stuff depending on the layout of your SVN repository.  The command “ls” will actually list the contents of my Tag.  Since I know my tag just has a few folders in it (it isn’t a recursive task), it isn’t too harmful if it succeeds.  If the Tag does not exist in my repository, the command actually fails.  Oddly, I actually want this task to fail!  Yes, in my case, I am hoping the task does not find the Tag with the specified name.  When the task is executed, it returns an ExitCode which is 0 for success or 1 for failure.  Next I just check the returned code and if it is successful I generate an error.  Sure this feels a bit odd.  I don’t love using this kind of logic, hoping for an error to occur. I’d much rather have some subversion command I could execute to see if the Tag exists but I couldn’t find anything like that.  Here is the actual xml from my Build file to check for the Tag:

<Target Name="CheckSvn">
  <Message Text="*** Checking to see if the tag already exists"/>
  <!-- this task will look up the tag supplied.  
    If it exists it will return a code of 0 
    Technically this is a success but for this instance, 
    it is a failure because we don't want to find it! -->
  <SvnClient Command="ls $(SvnRepository)/tags/$(SvnTagName)" 
             Username="xxx" password="xxx" ContinueOnError="true">
    <Output TaskParameter="ExitCode" PropertyName="CommandResult"/>
  </SvnClient>
  <Message Text="*** ExitCode = $(CommandResult)"/>
  <Error Condition="$(CommandResult)=='0'" Text="This Tag already exists!"/>
  <Message Text="*** Finished Checking to see if the tag already exists"/>
</Target>

Working with MSBuild is becoming a love/hate relationship for me.  I really love the power of what you can do to automate tasks.  But it can be a real pain to write, test, and debug these scripts.  I hope my sharing this code will make your life a little easier.

Saturday, April 17, 2010 1:49:50 PM (Eastern Standard Time, UTC-05:00)  #    Disclaimer  |  Comments [3]  |  Trackback
 Thursday, April 15, 2010

You’ve heard about LINQ to SQL, LINQ to Objects and LINQ to XML right?  Well how about LINQ to String?  Well technically there is no such thing.  But you use LINQ on a string!  You may not have realized this before but it works.  LINQ can be used to query IEnumerable<T> and a string is actually a collection of chars.  So yup, you can actually query the string itself.  Here are a few simple examples but you certainly do a lot more than this…

public void LinqToStringSample()
{
    string letters = "keuiwierqewefqwfwefcjlkjkl";

    //count all 'e'
    int count = letters.Count(l => l == 'e');

    //order
    var ordered = letters.OrderBy(l => l);
    
}
 | 
Thursday, April 15, 2010 8:53:45 PM (Eastern Standard Time, UTC-05:00)  #    Disclaimer  |  Comments [0]  |  Trackback

I recently gave an “Introduction To LINQ” presentation at the Microsoft event:  Data Access Firestarter.  That session was recorded and posted on MSDN’s Channel 9.  Here is the link so you can check it out.  If you want the content, you can get it from this post.  I’m really excited to be on Channel 9, it is such a great source of content!

I also gave the same talk at Philly.Net Code Camp this past Saturday.  That talk was also recorded and is available via Live Meeting replay.  I think it will be on Channel 9 too.  Both sessions went pretty well. 

I do feel the need to make a correction though!  In the presentation at Code Camp I answered a question incorrectly.  It was a subtle error, but one just the same.  The question was “Can you use LINQ to SQL against other databases?”.  I’m not really sure why I gave the wrong answer because I have been doing this stuff for a long time and I really do know the right answer.  My incorrect answer was that you can do LINQ to SQL as long as you have a provider to the other database.  This is completely wrong!  You can certainly do LINQ to a wide variety of data sources, including Oracle, but that isn’t “LINQ to SQL”.  LINQ to SQL is specifically an implementation of LINQ to a SQL Server Database.  I hope that makes sense.

Thursday, April 15, 2010 8:22:16 PM (Eastern Standard Time, UTC-05:00)  #    Disclaimer  |  Comments [0]  |  Trackback