Beantown .NET User Group Meeting on 9/2/2010 – Chris Bowen on Windows Phone 7

Hi All --

Beantown .NET is going to be meeting Thursday, 9/2/2010.  This month we have Chris Bowen presenting “Developing Applications for Windows Phone 7”. 

As always, our meeting is open to everyone so bring your friends and co-workers – better yet, bring your boss.  It is not required to RSVP for our meetings but if you know you’re coming, please RSVP by email (beantown@benday.com) by 3pm on the day of the meeting to help speed your way through building security and to give us an idea how much pizza to order.

Future meetings:

- October 7 – Shaun Avery, NHibernate
- November 4 – Andy Novick,  SQL Server Partitioning & Data Management
- December 2 – TBA

-Ben

When: Thursday, 9/2/10, 6p – 8p
Where:
Microsoft NERD
1 Memorial Drive
Cambridge, MA

Directions: http://microsoftcambridge.com/About/Directions/tabid/89/Default.aspx

Parking: Paid parking is available in 1 Memorial Drive. 

Title: Developing Applications for Windows Phone 7

Abstract:
Windows Phone 7 is dialed in for a holiday 2010 release and developers can answer the call now by leveraging Silverlight or XNA skills to create and extend applications or games to reach customers in new ways.  This demo-heavy session will give you the 411 on the Windows Phone 7 platform and on using the free Windows Phone 7 developer tools, Expression Blend 4, and Visual Studio 2010 to create Silverlight and XNA phone applications.

Bio:
Chris Bowen (http://blogs.msdn.com/cbowen) is a Developer Evangelist with Microsoft, covering the Northeastern US.  An architect and developer with over 17 years of experience, he joined Microsoft after holding senior positions at companies including Monster.com, VistaPrint, Staples, and IDX Systems, as well as consulting with others.  He is coauthor of "Essential Windows Communication Foundation" and "Professional Visual Studio 2005 Team System" and holds an M.S. in Computer Science and a B.S. in Management Information Systems, both from Worcester Polytechnic Institute.

An easier way to unit test INotifyPropertyChanged in Silverlight/WPF

If you’re coding your Silverlight or WPF app and you’re using the ViewModel Pattern, you’ve probably heard of the INotifyPropertyChanged interface.  INotifyPropertyChange is the glue that allows changes to values in your ViewModel classes to bubble up to your data-bound xaml user interfaces. 

When a change happens in a ViewModel property, the property raises INotifyPropertyChanged’s PropertyChanged event.  If this event doesn’t get thrown, then the user interface won’t know about the change and will continue to show the old value on the screen. 

It’s pretty important.  Sounds like it should be unit tested, huh?

The Problem: Well, I was writing some unit tests for INotifyPropertyChanged in one of my ViewModel classes over the weekend.  The way I was doing it was really cumbersome.

[TestMethod]
public void ViewModelField_NotifyPropertyChanged_NotifiesOnNewValue()
{
    string originalValue = "original value";

    var instance = new ViewModelField<string>(originalValue);

    Assert.IsInstanceOfType(instance, typeof(INotifyPropertyChanged));

    bool gotEvent = false;

    ((INotifyPropertyChanged)instance).PropertyChanged +=
        delegate(object sender, PropertyChangedEventArgs e)
    {
        gotEvent = true;
        Assert.AreEqual<string>("Value", e.PropertyName, "PropertyName was wrong.");
    };

    string newValue = "new value";
    instance.Value = newValue;

    Assert.AreEqual<string>(newValue, instance.Value, "Value didn't change.");

    Assert.IsTrue(gotEvent, "Didn't get the PropertyChanged event.");
}

In the code above, I’m using a delegate to subscribe to the PropertyChanged event and then setting the gotEvent variable to true if I get the event and then verifying that the PropertyName value on the event is what I expect.  So I set up the delegate and then modify the property.  When that’s done, I check that gotEvent is now set to true. 

It works but it’s kind of ugly.  If it’s ugly when I look at just one unit test method for INotifyPropertyChanged, image what it looks like when I have lots of test methods.  Yah.  Really ugly and there’s a lot of largely duplicated code.  It definitely violates the DRY Principle.

The Solution: I needed something clean and reusable so I created a tester utility class called NotifyPropertyChangedTester. 

NotifyPropertyChangedTester encapsulates all the logic of subscribing to INotifyPropertyChanged PropertyChanged event and hanging on to the events so that I can “Assert” on them. 

[TestMethod]
public void ViewModelField_NotifyPropertyChanged_NotifiesOnNewValue()
{           
    var viewModelInstance = new ViewModelField<string>("original value");

    var tester = new NotifyPropertyChangedTester(viewModelInstance);

    string newValue = "new value";

    // change the value
    viewModelInstance.Value = newValue;

    // check the property value
    Assert.AreEqual<string>(newValue, viewModelInstance.Value, "Value didn't change.");

    // check if INotifyPropertyChanged worked as expected
    Assert.AreEqual<int>(1, tester.Changes.Count, "Change count was wrong.");
    tester.AssertChange(0, "Value");           
}

The code above is that same unit test refactored to use the NotifyPropertyChangedTester class.  The delegate() logic is gone and NotifyPropertyChangedTester has a utility method called AssertChange() that contains the assertions for checking if the PropertyChanged event was right. 

My $0.02, I think this is a lot cleaner but it might not be obviously cleaner until you need to do a slightly more complex test that needs to check more than just one INotifyPropertyChanged event at a time like the code block below. 

[TestMethod]
public void MemberEditorViewModel_NotifyPropertyChanged_GetEventsWhenValuesChange()
{
    var viewModel = new MemberEditorViewModel(
        MockRepositoryInstance.Stub<IMemberService>());

    Assert.AreEqual<int>(0, viewModel.Id, "Id");
    Assert.AreEqual<string>(String.Empty, viewModel.FirstName, "FirstName");
    Assert.AreEqual<string>(String.Empty, viewModel.LastName, "LastName");
    Assert.AreEqual<string>(String.Empty, viewModel.EmailAddress, "EmailAddress");
    Assert.AreEqual<bool>(false, viewModel.ReceiveEmails, "ReceiveEmails");

    NotifyPropertyChangedTester tester = new NotifyPropertyChangedTester(viewModel);

    Assert.AreEqual<int>(0, tester.Changes.Count, "Changes count was wrong.");

    viewModel.Id = 1234;
    viewModel.FirstName = "fn";
    viewModel.LastName = "ln";
    viewModel.ReceiveEmails = true;
    viewModel.EmailAddress = "email";

    Assert.AreEqual<int>(5, tester.Changes.Count, "Changes count was wrong.");

    tester.AssertChange(0, "Id");
    tester.AssertChange(1, "FirstName");
    tester.AssertChange(2, "LastName");
    tester.AssertChange(3, "ReceiveEmails");
    tester.AssertChange(4, "EmailAddress");
}

The implementation for NotifyPropertyChangedTester is not too complex.  Here it is.

public class NotifyPropertyChangedTester
{
    public NotifyPropertyChangedTester(INotifyPropertyChanged viewModel)
    {
        if (viewModel == null)
        {
            throw new ArgumentNullException("viewModel", "Argument cannot be null.");
        }

        this.Changes = new List<string>();

        viewModel.PropertyChanged += new PropertyChangedEventHandler(viewModel_PropertyChanged);
    }

    void viewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        Changes.Add(e.PropertyName);
    }

    public List<string> Changes { get; private set; }

    public void AssertChange(int changeIndex, string expectedPropertyName)
    {
        Assert.IsNotNull(Changes, "Changes collection was null.");

        Assert.IsTrue(changeIndex < Changes.Count,
            "Changes collection contains '{0}' items and does not have an element at index '{1}'.",
            Changes.Count,
            changeIndex);

        Assert.AreEqual<string>(expectedPropertyName,
            Changes[changeIndex],
            "Change at index '{0}' is '{1}' and is not equal to '{2}'.",
            changeIndex,
            Changes[changeIndex],
            expectedPropertyName);
    }
}

Here’s the code.

-Ben

Silverlight Unit Tests: How to Stop Breaking on Assert Exceptions

There’s something a little peculiar about how unit tests work in Silverlight when the debugger is attached – when an Assert fails in one of your unit tests, the Visual Studio debugger breaks the execution and brings up the debugger dialog.

image

If you want to run a whole bunch of unit tests to see which ones are failing or you only care about the exceptions that your code throws, this feature can really cramp your style.  Thankfully, it’s pretty easy to edit the debugger settings to make these Assert exceptions go away.

Step #1: Go to the Debug menu in Visual Studio 2010, choose Exceptions…

image

Step #2: On the Exceptions dialog, click Add… 

image

Step #3: Register the exception types you want to tweek

image

From the Type menu, choose Common Language Runtime Exceptions.
In the Name textbox, type Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException.
Click OK.

Step #4: Repeat step #2 and #3 for Microsoft.VisualStudio.TestTools.UnitTesting.AssertInconclusiveException

Step #5: Uncheck Thrown and User-unhandled for the exceptions you just added.

image

Step #6: On the Exceptions dialog, click OK

image

Step #7: Enjoy your new streamlined exceptions.

image

-Ben

How to Permanently Banish Silverlight’s “Not Found” Error for WCF Service Calls

Have you seen this error message before?  “The remote server returned an error: NotFound.”  I think that this wins that the most infuriating exception in Silverlight.  I’ve personally wasted tens of hours trying to deal with this cryptic and utterly unhelpful message.  Over time, you come to understand that this is your Silverlight app’s way of telling you that there was an exception during a WCF Service call. 

Here’s the complete text of the exception:

System.ServiceModel.CommunicationException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound.
   at System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
   at System.Net.Browser.BrowserHttpWebRequest.<>c__DisplayClass5.<EndGetResponse>b__4(Object sendState)
   at System.Net.Browser.AsyncHelper.<>c__DisplayClass2.<BeginOnUI>b__0(Object sendState)
   --- End of inner exception stack trace ---
   at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
   at System.Net.Browser.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult result)
   --- End of inner exception stack trace ---
   at System.ServiceModel.AsyncResult.End[TAsyncResult](IAsyncResult result)
   at System.ServiceModel.Channels.ServiceChannel.EndCall(String action, Object[] outs, IAsyncResult result)
   at System.ServiceModel.ClientBase`1.ChannelBase`1.EndInvoke(String methodName, Object[] args, IAsyncResult result)
   at Benday.SilverlightFaults.TestService.TestServiceClient.TestServiceClientChannel.EndGetTime(IAsyncResult result)
   at Benday.SilverlightFaults.TestService.TestServiceClient.Benday.SilverlightFaults.TestService.TestService.EndGetTime(IAsyncResult result)
   at Benday.SilverlightFaults.TestService.TestServiceClient.OnEndGetTime(IAsyncResult result)
   at System.ServiceModel.ClientBase`1.OnAsyncCallCompleted(IAsyncResult result)

Doesn’t tell you much, does it?

Well, it turns out that you don’t have to just live with this.  I had a discussion with Ramesh Seshadri at Microsoft last week and he said that you can fix this with a little WCF server-side magic.  The magic is described in the Silverlight documentation in an entry called Creating and Handling Faults in Silverlight

Here’s the condensed version of the answer.  It all comes down to making your WCF service return a 200 HTTP Status code instead of the default of 400 or 500. 

I did up a little sample application.  In the screen below, if you click the Throw Server Exception button, it calls a WCF service and the service will throw an exception. 

image

What’s great about this is that it plays nicely with the  includeExceptionDetailInFaults property of <serviceDebug />.  If the value for includeExceptionDetailInFault is set to true, you’ll get a descriptive error message (shown above). 

image

If the value is set to false, you’ll get an error message that is more friendly than “Not Found” but still shields the details of the WCF server exception from the client as shown below.

image

Click here to download the source code.

-Ben

Article: Load Testing with Visual Studio 2010 (+ how to set up your Load Testing Rig)

I wrote a two part article for Visual Studio Magazine on Web Testing & Load Testing in Visual Studio 2010.  Here’s the second part.  This second part focuses on how to do Load Tests with a Load Testing Rig with an emphasis on how to actually install and configure your rig. 

(Here’s the link to the first part of the article.)

image

You can run load tests from a developer machine, but you usually can't generate enough traffic to really see how the application responds. In order to simulate a lot of users, you'll set up what is known as a Load Test Rig. A test rig is made up of a Test Controller machine and one or more Test Agent machines as shown in Figure 1. The controller manages and coordinates the agent machines and the agents generate load against the application. The test controller is also responsible for collecting performance monitor data from the servers under test and optionally from the test rig machines.

In case you were wondering what I mean by “Load Testing Rig”, here’s a quick diagram.

image

-Ben

 

-- Looking for help with Web Testing and Load Testing of your Silverlight, ASP.NET and WCF applications?  Want help configuring your test rig?  Think you might have performance problems in your app but you’re not sure how to pin them down?  Drop us a line: info@benday.com

Article: Web Performance Testing with Visual Studio 2010

I wrote an article for Visual Studio Magazine a while back on Web Performance Tests in Visual Studio 2010.  It’s part 1 of 2.  Enjoy.

image

In web performance tests, the addition of Loops and Conditions enables developers to write more complex and intelligent tests against their applications. For load tests, the addition of 64-bit agents and controllers allows you to more effectively use the available hardware resources to generate load. Additionally, changes to the licensing of the load test agents and controllers gives you greater flexibility, making it easier -- and potentially cheaper -- to configure your load test rigs.

Web tests allow you to simulate a user performing a set of operations – typically a defined use case – on your ASP.NET Web application, and validate the responses to see if the application is working as expected. Once you have your Web tests defined, you can knit them together to create a load test to see how well your application performs under stress.

It's always better to test your Web applications early to detect performance problems. In this article, I'll focus on authoring and debugging Web performance tests. In part 2, I'll explain how to set up and configure a Load Test Rig and use Web tests as the basic building blocks of your load tests.

-Ben

 

-- Looking for help with Web Testing and Load Testing of your ASP.NET and WCF applications?  Think you might have performance problems in your app but you’re not sure how to pin them down?  Drop us a line: info@benday.com

Silverlight 4 Databound CheckBoxList and RadioButtonList Controls

Last week I needed a CheckBoxList control and a RadioButtonList control for Silverlight 4.  I was surprised that they weren’t already part of the standard controls or the Silverlight Control Toolkit.

RadioButtonList
image

CheckboxList
image

Once I started to work on the controls, I realized that I didn’t know how to databind RadioButtons or databind Checkbox controls to a ViewModel in Silverlight.  The answer is to use the ItemsControl and the ItemsControl.ItemTemplate property. 

<ItemsControl x:Name="m_itemsControl" ItemsSource="{Binding}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <CheckBox Content="{Binding Text}" IsChecked="{Binding IsSelected, Mode=TwoWay}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

If you’re going to wrap the checkboxes and radiobuttons in to a reusable control, the databinding expressions need to point to a constant type.  My controls bind to an interface called ISelectableItem that implements INotifyPropertyChanged.

public interface ISelectableItem : INotifyPropertyChanged
{
    bool IsSelected { get; set; }
    string Text { get; set; }
    string Value { get; set; }       
}

This interface provides the Text to display in the list and also a boolean value to display whether the item is selected or not.  This allows me to bind the CheckboxList and RadioButtonList control to an instance of ObservableCollection<ISelectableItem> and then all the rest of the work is done automatically through the viewmodel binding expressions.

Click here to view a running sample.
Click here to download the source code.

-Ben

 

-- Looking for help with your Silverlight architecture?  Worried about getting it right the first time?  Questions about how to unit test your Silverlight application?  Drop us a line: info@benday.com

Bind a Silverlight 4 HyperlinkButton NavigateUri in a DataGrid to a DataSource value

The Problem: How to generate a NavigateUri for a HyperlinkButton in a DataGrid that contains an Id value using a data binding expression.
The Answer: Use StringFormat inside the NavigateUri binding.

It’s a pretty common thing to do in any kind of application – you’ve got a grid that’s filled with data and from that grid you need to display the detail for that record when a user clicks on the row.  In the image below, I’ve got a list of people and when you click on the “(view)” link, it takes you to the detail for that person.

image

image

A few days ago, I needed to implement this kind of functionality in Silverlight 4.  In my application, I’m using Silverlight Pages and Navigation Frames to move around throughout the application.  When I move to a new Page in the application, it usually is done via a HyperlinkButton control with the NavigateUri set to something like “/Views/About”

image

Using that Uri scheme, I’ve got a folder in my Silverlight project named Views and inside that folder, I’ve got a Silverlight Page named About.xaml.  Extending that uri naming scheme and making it look like a lot of the web an a lot of things that happen in ASP.NET MVC Framework, let’s say that I have a page called PersonDetail that allows the user to edit a specific Person record.  When I needed to navigate to a particular person, I wanted the Uri for that PersonDetail page to be something like “/Views/PersonDetail/6” where that last part of the uri – the ‘6’ – is the Id for the Person that I want to edit.

Since I was going to display these records in a DataGrid, I wanted to be able to use a data binding expression an a DataGridTemplateColumn that contains a HyperlinkButton and have the NavigateUri be generated automatically that would point to PersonDetail.  Sounds simple, right? Well, when I searched around on The Internet(s), it looked like it was going to be really hard.  Some posts suggested creating a custom version of the HyperlinkButton control, others suggested hooking in to the binding events on the DataGrid, and then there was also a suggestion that I write a value converter to plug in to the NavigatieUri binding expression.  It looked grim. 

Well, it looks like it’s gotten a lot easier in Silverlight 4. 

The answer: use StringFormat inside the NavigateUri binding.  (See the block of WPF Xaml below)

<sdk:DataGrid ItemsSource="{Binding Persons}" AutoGenerateColumns="False" >
    <sdk:DataGrid.Columns>
        <sdk:DataGridTemplateColumn CanUserReorder="True" CanUserResize="True" CanUserSort="True" Width="Auto">
            <sdk:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <HyperlinkButton Content="(view)" Tag="{Binding Id}"
                                 NavigateUri="{Binding Id, StringFormat='/PersonDetail/\{0\}'}"
                                 TargetName="ContentFrame" VerticalAlignment="Center"></HyperlinkButton>
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellTemplate>
        </sdk:DataGridTemplateColumn>
        <sdk:DataGridTextColumn CanUserReorder="True" CanUserResize="True" CanUserSort="True" Width="Auto" Header="Id" Binding="{Binding Id}"/>
        <sdk:DataGridTextColumn CanUserReorder="True" CanUserResize="True" CanUserSort="True" Width="Auto" Header="Last Name" Binding="{Binding LastName}"/>
        <sdk:DataGridTextColumn CanUserReorder="True" CanUserResize="True" CanUserSort="True" Width="Auto" Header="First Name" Binding="{Binding FirstName}"/>
    </sdk:DataGrid.Columns>
</sdk:DataGrid>

Click here to view a running sample application
Click here to download the source code for this example.

-Ben

-- Looking for help with your Silverlight architecture?  Worried about getting it right the first time?  Questions about how to unit test your Silverlight application?  Drop us a line: info@benday.com

Error 2103 “Unhandled Error in Silverlight Application”

Seen this error before? 

image

Line: 54
Error: Unhandled Error in Silverlight Application
Code: 2103   
Category: InitializeError      
Message: Invalid or malformed application: Check manifest 

At first I was terrified that there was some kind of mysterious corruption in my Visual Studio 2010 Silverlight 4 bits.  After some searching on The Internets, I found the answer at http://forums.silverlight.net/forums/p/170656/384800.aspx#384800.  On March 25, 1010 at 4:15pm, sladapter said that this error "usually happens when you changed the namespace of your app [and] then did not change the Startup Object in the project property." 

I did just do a big refactoring and renamed a lot of stuff – including renaming the Silverlight project – so I figured that this was the problem.  Unfortunately, I didn’t immediately know what he meant. 

The answer, open the Solution (sln) that has your Silverlight 4 project.  Go to the Silverlight project (not the *.Web project), right-click the project and choose Properties.  When the Project Properties page comes up, click the Silverlight tab and you should see the screen below.

image

When I went to the Silverlight tab for my project, I found that the Startup object was indeed set to the old name and namespace for App.xaml. 

Now, open the Startup object dropdown.

image

The old value isn’t even available in the list anymore.  Choose the right value from the Startup object dropdown list, Save the project, and now your Silverlight application should run.

-Ben

Visual Studio 2010 Web Testing Article at Visual Studio Magazine

FYI, part 1 of my Visual Studio Load Testing & Web Testing article is up on the Visual Studio Magazine site.

image

-Ben

«September»
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789