Aaronontheweb

Hacking .NET and Startups

6 Really Useful Windows Phone 7 Articles

I’m in the midst of working on a line of related Windows Phone 7 MVVM Light applications which are all built on the upcoming release of Quick and Dirty Feed Parser, which includes Silverlight and Windows Phone 7 support.

I found the following articles to be really useful in the course of trying to smooth out some performance problems, implement local caching, and are just generally good links to have around if you’re trying to do any serious WP7 development:

  1. Performance of Windows Phone 7 Applications – if you’re wondering why your UI seems sluggish, then you need to read this article. It explains how to use built-in tools to enable basic performance monitoring and has a great list of fixes for common performance problems.
  2. Using Isolated Storage on Windows Phone 7 – provides a great learn-by-example overview of how you can use IsolatedStorage in Windows Phone 7 to perform simple reads, writes, and serialization operations.
  3. How to Access Packaged XML Files in Silverlight – if you ever find yourself struggling to figure out how to access XML files that you package with your Silverlight or Windows Phone 7 application, the techniques illustrated in this article should provide some illumination. It’s not as easy or intuitive as it is in ASP.NET or WPF development, but it works nonetheless.
  4. Rapid Repository 2.0 – If you’re looking for a great local db to use in Windows Phone 7, Rapid Repository might be right for you. It’s simple and easy to use, but it’s mandatory Guid-only-key policy was a deal-breaker for me. Still, compared to some of the other engines I tried, it’s one of the more well-designed local database implementations I’ve used.
  5. Passing Parameters With Behaviors In MVVM Light for Windows Phone – Great article which explains how to use commanding in MVVM Light. I use EventToCommand everywhere in my MVVM Light applications, so this was a helpful resource for me – the code sample in particular.
  6. Add/RemoveRange Methods for ObservableCollection in Silverlight - This article solved a major UI performance problem for me; the technique of supressing property notification changes for bulk modifications to lists resulted in a pretty drastic performance improvement. I'll be doing a follow-up post on this myself.

Let me know in the comments if there are any great Windows Phone 7 links that you’ve used recently that are worth sharing!

If you enjoyed this post, make sure you subscribe to my RSS feed!



MVVM Light Toolkit Pitfalls on Windows Phone 7 and How to Avoid Them

mvvm-light I’ve been leaning heavily on Laurent Bugnion’s MVVM Light Toolkit framework in the course of learning Windows Phone 71 development for my work as a developer evangelist at Microsoft. It’s a fantastic framework and it does an excellent job of enabling SOC in Windows Phone 7 application development.

However, during some of my experimentation with the framework I’ve run into some initially puzzling development pitfalls that I wanted to share and demystify.

These pitfalls might also apply to vanilla Silverlight and WPF in general, but my experience has been with Windows Phone 7 development so I’ll qualify these pitfalls accordingly:

Pitfall #1 – DispatcherHelper is NOT initialized by default

The DispatcherHelper is useful for scenarios like this one from my Twitter search MVVM demo on WP7 where you have to marshal UI updates across threads:

//ListBox on MainPage.xaml is bound to this collection of Tweet objects
public ObservableCollection Results { get; private set; }

//Callback method when RestSharp returns an RSS feed worth of tweets relevant to our keyword
public void GetResults(RestResponse results)
{
    var returnResults = SearchResultConverterHelper.ConvertRssFeed(results.Data);
    DispatcherHelper.CheckBeginInvokeOnUI(() =>
    {
        Results.Clear();
        foreach (var item in returnResults)
        {
            Results.Add(item);
        } 
    });            
}

If you try to use this code as-is in your application you’ll receive a NullReferenceException stemming from the DispatcherHelper itself. This is because the default MVVM Light Toolkit project templates don’t call DispactherHelper.Initialize() anywhere; so the fix to this is pretty easy – just add this line of code inside your App.xaml.cs constructor:

public App()
{
    // Global handler for uncaught exceptions. 
    // Note that exceptions thrown by ApplicationBarItem.Click will not get caught here.
    UnhandledException += Application_UnhandledException;

    // Standard Silverlight initialization
    InitializeComponent();

    //Readies the DispatcherHelper for usage throughout application
    DispatcherHelper.Initialize();

    // Phone-specific initialization
    InitializePhoneApplication();
}

This will ensure that any calls you make to the DispatcherHelper

Pitfall #2 – EventToCommand namespaces are not included by default

EventToCommand is awesome. Take a moment to look at the documentation on it and bask in its elegant simplicity. Here’s an example below from my Twitter demo again:

<TextBox Height="71" Name="txtBoxSearch" Text="" Width="370" />
<Button Content="Go!" Height="71" Name="btnSearch" Width="Auto">
<Interactivity:Interaction.Triggers>
    <Interactivity:EventTrigger EventName="Click" x:Name="btnSearchClickedEventTrigger">
        <Command:EventToCommand Command="{Binding ExecuteSearch}" 
                                CommandParameter="{Binding Text, ElementName=txtBoxSearch}"/>                                
    </Interactivity:EventTrigger>
</Interactivity:Interaction.Triggers>
</Button>

However, there is one minor pitfall which is that in order for this code to compile you need to make sure that both of these namespaces are included in your XAML file:

xmlns:Command="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WP7"
xmlns:Interactivity="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

This isn’t really a pitfall so much as it is a snag that can slow you down when you’re trying to hammer out code.

Pitfall #3 – Messenger.Register/Send may not occur in the order you expect

Here are two pieces of code I have in a new Windows Phone 7 application I’m building – the first is in my MainViewModel class and the other is in the MainPage.xaml.cs code-behind:

MainViewModel.cs

//From the constructor of my MainViewModel class
DetermineAccountStatus = new RelayCommand(() => 
    {
        if (Accounts.Count == 0)
            Messenger.Default.Send(MessagingConstants.NoTwitterAccountsAuthorized, MessagingConstants.AccountsStatus);
        else
            Messenger.Default.Send(MessagingConstants.AtLeastOneTwitterAccountAuthorized, MessagingConstants.AccountsStatus);
    });
DetermineAccountStatus.Execute(new object());

MainPage.xaml.cs

public MainPage()
{
    InitializeComponent();

    //Receive messages from the view model notifying us if we need to show our "no accounts added" message or not
    Messenger.Default.Register(this, MessagingConstants.AccountsStatus, s =>
    {
        if (s == MessagingConstants.NoTwitterAccountsAuthorized)
            this.txtBlockMissingAccounts.Visibility = System.Windows.Visibility.Visible;
        else
            this.txtBlockMissingAccounts.Visibility = System.Windows.Visibility.Collapsed;
    });                  
}

So what’s the problem here? The problem is that because the XAML parser instantiates the MainViewModel first because the ViewModelLocator is included in the App.xaml resource dictionary, which is hit first by the XAML parser before the MainPage.xaml file is!

<!--Application Resources-->
<Application.Resources>
    <vm:ViewModelLocator x:Key="Locator"
                            d:IsDataSource="True" />       
</Application.Resources>

Therefore the message is sent before the MainPage class ever has a chance to register to receive it.

This is a design mistake and it’s easy to make: don’t send any messages during object instantiation. Instead, let the View invoke the ViewModel after it’s loaded, like so:

public MainPage()
{
    InitializeComponent();

    //Receive messages from the view model notifying us if we need to show our "no accounts added" message or not
    Messenger.Default.Register(this, MessagingConstants.AccountsStatus, s =>
    {
        if (s == MessagingConstants.NoTwitterAccountsAuthorized)
            this.txtBlockMissingAccounts.Visibility = System.Windows.Visibility.Visible;
        else
            this.txtBlockMissingAccounts.Visibility = System.Windows.Visibility.Collapsed;
    });

    Loaded += new System.Windows.RoutedEventHandler(MainPage_Loaded); 
}

        
void MainPage_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
    //Tell the ViewModel to call us back regarding whether or not we have any accounts to list in our listbox
    ViewModel.ViewModelLocator.MainStatic.DetermineAccountStatus.Execute(new object());
}

The MVVM Light Toolkit is a great framework and it’s a pleasure to work with once you start to understand some the nuances of Silverlight / Windows Phone 7 development. If you have any questions please feel free to leave a comment on this post!


1If you're interested in developing for Windows Phone 7, you can download all of the development tools for free from http://developer.windowsphone.com/

If you enjoyed this post, make sure you subscribe to my RSS feed!



MVVM Light Toolkit Example on Windows Phone 7: Twitter Search

I wrote this example in conjunction with the lightning talk I gave at SHDH #40 on MVVM for Noobs, and I thought that developers who are new to developing in Silverlight or for Windows Phone 7 might benefit from it.

One of the major issues I had in moving from ASP.NET MVC to MVVM in Windows Phone 7 was learning how to let go and let Silverlight do a lot of the heavy lifting for me, particularly in the area of data binding and managing the life cycles of your business objects.

Please take a look at the attached source – I’ll be writing up a follow-up post with some specific learnings in the near future.

mvvm wp7 twitter search.zip (471.88 kb)

If you enjoyed this post, make sure you subscribe to my RSS feed!



SuperHappyDevHouse Lightning Talk: MVVM for Noobs

I'm at Microsoft's Silicon Valley Campus this weekend where we're hosting SuperHappyDevHouse #40 - I'm going to be giving a lightning talk on MVVM for Noobs in the next hour or so and I wanted to post my presentation online as I think some of you might find it to be of some use. My presentation is largely focused on the MVVM Light Toolkit for Windows Phone 7, and I really struggled to grasp MVVM when I first started developing for WP7 largely because of some long-held views I brought over from ASP.NET MVC and tried to force upon Silverlight and MVVM.

This presentation should help shed some light on how to get some of the necessary plumbing up and running.

If you enjoyed this post, make sure you subscribe to my RSS feed!



10 Harder-to-find-than-they-should-be Answers for Silverlight Beginners

August 4, 2010 19:57 by Aaronontheweb in Silverlight // Tags: , , , // Comments (0)

I’ve been teaching myself WPF / Silverlight as part of my next big project at StannardLabs: a line of trivia games for WinMo7 / Android / iOS phones. It’s mostly an exercise for learning how each of those platforms work, how they differ, and some of the application marketing differences on each platform.

In the process of learning Silverlight 4, the most recent version of Silverlight for which few guides or books exist, I’ve built a list of the top ten answers I wish were easier to find when I started learning Silverlight.

I was unable to quickly find answers on these subjects perhaps because I was using the wrong lexicon or perhaps these are things that professional Silverlight / WPF developers consider to be too “obvious” to be worthy of inclusion in any of their books or blog entries.

Well to make it easier for all of you, I went ahead and researched all of these.

Here’s my list:

  1. How do I actually navigate to different Silverlight content within an application?

    Answer: Thinking about Silverlight from a web-based approach at the moment, what you're really asking is "how can I create separate pages within a Silverlight application?" Fortunately, that metaphor matches up identically to what Silverlight uses: the Navigation framework and Silverlight Pages.1

    The easiest solution I've found using these tools is to create a masterpage (Main.xaml or something like that) which has a Silverlight Frame element sitting in the middle of it, and you swap out your interchangable pages within that frame.

    How Frames and Navigation Work in Silverlight

  2. How can I create a hyperlink to a webpage from within a Silverlight application?

    Answer: Using the same Silverlight Navigation framework I highlighted in my answer to question one you can create hyperlinks in Silverlight to external content which will open in a web browser. Here's a code sample from MSDN which will show you how it's done:

    <HyperlinkButton NavigateUri="http://www.microsoft.com"
        Content="Go to Microsoft" TargetName="_new" />
  3. How do I open a modal dialog window within a Silverlight application?

    Answer: First, understand that Silverlight is not Windows Forms or WPF, which both implement modal dialog behavior familiar to anybody who has worked with the Win32 API in the past. Silverlight is a cross-platform technology, therefore the behaviors you're used to courtesy of the Win32 API and its .NET progeny won't be available on every environment in which your Silverlight application executes therefore the standard modal dialog tools you're used to in WPF can't be used in Silverlight.

    That being said, it's easy to implement a modal dialog user interface element in Silverlight. Here's a couple of resources which explain how to do this:

  4. How can I span different font styles to small portions of inline text within a TextBlock element?

    Answer: Essentially, what you're asking for is the XAML / WPF equivalent of a <span> tag from HTML so you can selectively apply styles within a TextBlock element.

    Fortunately, an equivalent exists - it's called the Run element, which can be used anywhere inside the text content of a TextBlock element. Here are some great examples of the Run element being used in Silverlight, one of which I'm going to include below:

    <TextBlock> 
            <Run Background="Red"> 
                Republican 
            </Run> 
            <Run Background="Blue"> 
                Democrat 
            </Run> 
    </TextBlock>
  5. What’s the best way to implement session-specific storage for a Silverlight application?

    Answer: This question isn't as tricky as it seems - if you're an ASP.NET developer like me, you approach the concept of session and state differently than desktop programmers given that we work with HTTP, a stateless protocol.

    So here's the good news: Silverlight handles states just like a desktop application! So you can stash your session data in a handful of public properties on your application class for lightweight scenarios, create a static session class for middleweight scenarios, or use isolated storage for heavier scenarios - check out this thread from the official Silverlight forums if you want more information.

  6. Are there any compelling reasons to use an RIA-service instead of a vanilla WCF service in Silverlight applications?

    Answer: If you've ever read Microsoft .NET: Architecting Applications for the Enterprise (which you should read for the discussion of design tools and patterns even if you aren't an enterprise developer, which I am not) then you'll know that the answer to every design question like this one is always "it depends." This post by Shawn Wildermuth does a better job than I ever could laying out the factors that might lead you to pick one data service implementation for Silverlight over another, but I'll sum it up for you in order to answer this question:

    If your goal is to get a Silverlight application up and running as quickly as possible, then you should use RIA services as you won't need to write as much code compared to the alternatives nor will you need to worry about WCF cross-domain policy files, change tracking, and so forth.

  7. On the contrary, why might you choose a WCF service over an RIA-service for a Silverlight application?

    Answer: I made the decision to go with a vanilla WCF service over an RIA service because, from everything that I've read on the matter, WCF is a better choice for situations where you need to support additional clients besides Silverlight (iOS and Android clients in my case.) Additionally, if you have an existing WCF service already in place, you'll want to use that instead of rewriting everything to use RIA services.

  8. Can RIA-services be easily reused among non-Silverlight applications?

    Answer: the answer appears to be "no," but given that I'm still new to Silverlight myself I could be wrong. If you need to support additional clients, especially ones not on the .NET framework, then I recommend using WCF instead.

  9. How can I dynamically add XAML elements to my application at run-time?

    Answer: there are hundreds of different ways to add new XAML elements to your Silverlight application at run-time. My personal favorite is this example which shows you how to use LINQ to create additional data-driven elements in a Silverlight application. If you're looking for a simple guide on how to add new XAML elements programmatically, then I'll refer you to "Dynamic Manipulation of Silverlight Controls" which sums it up nicely.

  10. What’s the best way to implement form validation in a Silverlight application?

    Answer: where there is data, there shall be validation. Silverlight ships with its own validation framework, much the same way that ASP.NET ships with a validation framework. This step-by-step guide on forms validation in Silverlight 3 is the best example on how to get started that I've found.

And that does it - as always, I'm eager to hear back from the community regarding better answers to these questions, or perhaps more interestingly: better questions I did not ask!


1The Navigation elements uses a pathing formula similar to ASP.NET routing if you're familiar with ASP.NET MVC.

If you enjoyed this post, make sure you subscribe to my RSS feed!



Search

About

My name is Aaron, I'm an entrepreneur and a .NET developer who develops web, cloud, and mobile applications.

I left Microsoft recently to start my own company, MarkedUp - we provide analytics for desktop developers, focusing initially on Windows 8 developers.

You can find me on Twitter or on Github!

Recent Comments

Comment RSS

Sign in