Tuesday, November 16, 2010

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!

Tuesday, November 16, 2010 10:53:00 PM (Eastern Standard Time, UTC-05:00)  #    Disclaimer  |  Comments [7]  |  Trackback
 Tuesday, September 21, 2010

If you’ve been searching the web for a good sample of how to drag and drop data from one DataGrid to another in Silverlight, you’ve probably found some great samples out there, showing “how easy” it can be by just surrounding your DataGrid with DataGridDragDropTarget tags.  In fact, if you do that, you can drag and drop data from one grid to the other.  The problem is that most of these demos are about the visual aspect of drag and drop.  But in the real world, there is more work to be done.  Most of the samples that I found did not deal with how to save the data once it was dropped in the other grid.  I’m using the MVVM pattern so basically what I need to do is, once the drop is complete, update my ViewModel.

The tricky part was figuring out what information was actually dropped on my target DataGrid.  It’s not at all obvious how to do that.  The Drop event uses DragEventArgs which has a Data property.  You’d think this would be the data from the other DataGrid, but you’d be wrong.  Data has a GetData() method but you need to provide it a parameter specifying the format of the Data.  Once you figure out how to do that, you’ll find that GetData() doesn’t actually give you the data!  It give you ItemDragEventArgs, which also has a Data property.  Is this Data the data you want?  Not exactly, but you are getting close.  This Data can be cast as a SelectionCollection – that is because a DataGrid supports multiple selections at the same time!  And each Selection in the collection is the data you actually want.  Is it me, or is that pretty confusing? 

I wouldn’t have gotten this far, but searching the web for a while, I stumbled across a post on StackOverflow that was helpful.  The response also references a blog post found here as well. 

Those samples I found were really helpful but it seemed like it could be made easier.  Starting with sample code from the blog post mentioned above, I created a very simple, reusable, Extension Method that uses Generics and does all of the heavy lifting for you!  This should make things pretty easy now.

Here is some of the sample code and a sample solution is attached here.   

First, here is the extension method that gets the underlying data that was dropped on the target:

public static IEnumerable<T> GetData<T>(this DragEventArgs args)
{
    IEnumerable<T> results = null;

    // Get the dropped data from the Data property and cast it to the first format. 
    ItemDragEventArgs dragEventArgs = args.Data.GetData(args.Data.GetFormats()[0]) as ItemDragEventArgs;

    if (dragEventArgs == null)
        return results;

    // Get the collection of items
    SelectionCollection selectionCollection = dragEventArgs.Data as SelectionCollection;
    if (selectionCollection != null)
    {
        // cast each item to what is expected
        results = selectionCollection.Select(selection => selection.Item).OfType<T>();
    }

    return results;
}

Here is the XAML for the two grids.  Note that in this sample (you can change this of course) I’m using AllowedSourceEffects.Copy so that the data remains in the first grid and is copied to the second.

<Toolkit:DataGridDragDropTarget AllowedSourceEffects="Copy"
                                Grid.Column="0" Grid.Row="0">
    <Controls:DataGrid x:Name="Data"
                        ItemsSource="{Binding Data}" 
                        AutoGenerateColumns="False">
        <Controls:DataGrid.Columns>
            <Controls:DataGridTextColumn Header="Id" Binding="{Binding Id}" />
            <Controls:DataGridTextColumn Header="First Name" Binding="{Binding FirstName}" />
            <Controls:DataGridTextColumn Header="Last Name" Binding="{Binding LastName}" />
        </Controls:DataGrid.Columns>
    </Controls:DataGrid>
</Toolkit:DataGridDragDropTarget>

<Toolkit:DataGridDragDropTarget AllowedSourceEffects="Copy"
                                Drop="DataGridDragDropTarget_Drop"
                                Grid.Column="1" Grid.Row="0">
    <Controls:DataGrid x:Name="MoreData"
                        ItemsSource="{Binding MoreData}" 
                        AutoGenerateColumns="False" 
                        AllowDrop="True">
        <Controls:DataGrid.Columns>
            <Controls:DataGridTextColumn Header="Id" Binding="{Binding Id}" />
            <Controls:DataGridTextColumn Header="First Name" Binding="{Binding FirstName}" />
            <Controls:DataGridTextColumn Header="Last Name" Binding="{Binding LastName}" />
        </Controls:DataGrid.Columns>
    </Controls:DataGrid>
</Toolkit:DataGridDragDropTarget>

Lastly, here is the code behind piece that handles the Drop event, get’s the data and passes it to my ViewModel.  Note here that I specify e.Handled = true.  Without that, the DragDropTarget would automatically copy the data again.

private void DataGridDragDropTarget_Drop(object sender, Microsoft.Windows.DragEventArgs e)
{
    //use the extension method to get the data from the DragEventArgs
    var data = e.GetData<Person>();

    foreach (var item in data)
    {
        _viewModel.AddToMoreData(item);
    }
    e.Handled = true;
}

Once again, here is a link to a complete sample project

Tuesday, September 21, 2010 11:18:14 PM (Eastern Standard Time, UTC-05:00)  #    Disclaimer  |  Comments [7]  |  Trackback
 Monday, August 23, 2010

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.

Monday, August 23, 2010 9:30:05 PM (Eastern Standard Time, UTC-05:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 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