in a Windows Phone application, sometimes you might have a long operation , and you do not want to freeze the User Interface (i.e. block the UI thread).

One way to avoid blocking the UI is to use a background worker thread to run the Operation asynchronously and tell it what method to call when it completes processing.

The pseudocode for it…

Start with declaring a background worker.
Tell it what do when finished.

Tell it what method to invoke (which is the long task).
Pass in the argument if any (as an object), so you can have a simple string or a custom object that holds a set of params.

Here is the code for it:

            BackgroundWorker bw = new BackgroundWorker();
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(DoneWork); 
            bw.DoWork += new DoWorkEventHandler(DoWork); 
            bw.RunWorkerAsync(arg1);

Note: This concept is applicable to Silverlight in general, and if you are using .NET 4.0 (and not only the Phone), you can use a generic Tuple object for the argument and then type-cast your argument to whatever you passed in.

The signatures for DoWork and DoneWork have to be of the required delegate type, for e.g.:

private void DoWork(object sender, DoWorkEventArgs e)

private void DoneWork(object sender, RunWorkerCompletedEventArgs e)

e.Argument will give you the argument arg1, which you had passed in.

You can store objects you want to send back to the caller as e.Result.

Use this technique to show a progress bar or a wait state in the UI.

Remember, UI operations like updating a list or it’s bindings while done from either delegate need a context switch and are not directly possible because the UI thread is different from the one we might be running on.

This is a pain to code but unavoidable, and to do this, wrap your calls with an anonymous method and call it like this:

            Deployment.Current.Dispatcher.BeginInvoke(
             () => {
                     ... 
                     this.listBox.ItemsSource = items;
                     this.PageTitle.Text = text;             
                   }

Hope that helps…

While developing Win Phone apps, there are a few options for having a timer. Here are 2 possibilities which provide precision vs. blocking/overhead:

1. Dispatch timer
This is basically a timer that runs on the UI thread and so is precise but can block the UI for any refreshes and activity when it executes, so be careful how/when you use it.

It can be declared and created as:

System.Windows.Threading.DispatcherTimer _predictionTimer = new System.Windows.Threading.DispatcherTimer();

It is set up as: (Do this in the Page loaded event, for the Page)

_predictionTimer.Interval = new TimeSpan(0, 0, TIMER_INTERVAL_SECONDS);
_predictionTimer.Tick += new EventHandler(PredictionTimerEvent);
_predictionTimer.Start();

Note: If you type in the += after the second statement, hitting Tab twice will also generate a callback stub in code (like the one below) for you.

The method to call for the timer event is written as:

void PredictionTimerEvent(object sender, EventArgs e)
{
   …do something…}

2. IDisposible timer

This timer is not very precise, but runs on its own thread and not the UI thread  and so does not block the UI. It does need to switch contexts to do anything with the UI/display. So, you need to get a handle to the UI thread to do anything with the display. I use the MVVM Light Messenger and subscribe to a message that I then send in the timer so I don’t need to do any switching myself.

It is declared as:

        IDisposable _timer;

It is created as: (Do this in the Page loaded event)

if (_timer== null)

{

        IScheduler scheduler = Scheduler.Dispatcher;

    _timer = scheduler.Schedule

                              (new Action<Action<TimeSpan>>TimerInterrupt), 
                    TimeSpan.FromSeconds(TIMER_INTERVAL_SECONDS));

}

The timer event handler is written as:

        void TimerInterrupt(Action<TimeSpan> action)         {             …do something…             action(TimeSpan.FromSeconds(TIMER_INTERVAL_SECONDS));         }

To kill the timer (while navigating away, for e.g.)

_timer.Dispose();  //kill timer

Both of the above essentially do the same thing, but there are different reasons to use either.
Hope that helps.

As part of developing for WP7, I came across a few issues that I’d like to share with you, and maybe help you avoid some pitfalls I faced…

1. WebClient requests are cached by emulator
If you use the WebClient class to download information from the web, be aware that the web requests are cached by the emulator (and the actual phone?) and this can be quite confusing, especially for real-time data from the web. There is no straight-forward workaround, and the only way for me to get this working was to tag on a GUID in my query string. Something like:

downloadUrl = url + “&guid=” + Guid.NewGuid()

This, of course is a hack which might work with most websites because they only pick out params they care about and ignore the rest. Watch out for some strict sites that check for a fixed number of params and I have nothing around that at the moment.

2. Fiddler with WP7

As part of troubleshooting my first problem, I tried to use Fiddler which will not track WP7 web requests out of the box, but can be made to do so with the following steps:

  1. Start Fiddler (ensure you have the latest version).
  2. Click Tools > Fiddler Options.
  3. Open the Connections tab and tick the Allow remote computers to connect box. Click OK.
  4. In the QuickExec box (shown in red) under the session list, type prefs set fiddler.network.proxy.registrationhostname [HostName] where HostName is the name of your desktop computer.

image

   5. Close and restart Fiddler and the Windows Phone 7 Emulator.

Now you should  be able to track requests from the Emulator in Fiddler.

I referred to Eric’s blog post and the Phone 7 blog for this issue.

3. Application Icon and Splash Screen don’t show up in app
I replaced my ApplicationIcon.png and SplashScreenImage.jpg but was scratching my head when they did not show up at run-time. A little looking into showed that when I replaced the original files, I lost their Properties and these files need to marked as Content Resources, like this:

image

4. WP7 toolkit installation problems

I had a few headaches getting the toolkit to install, and it kept failing for some reason and I think they were related to not having VS Express (or whatever the free version is).
I don’t remember what I did exactly, but there are people who have workarounds and a few retries worked for me, for installing the XMA framework for example.

If you’re having an installation problem, look for the toolkit iso and shut down and even reboot and try again. If not, ask in the WP7 forum at create.msdn.com and hopefully you will get some help.

5. Consider the LongListSelector control for nested lists

I had a situation whereby I had a kind-of master-detail view shown together where the master items are shown with their details items next to them, for eg.

Master 1
      detail 1.1
      detail 1.2

Master 2
     detail 2.1

Master 3
    detail 3.1
    detail 3.2
    detail 3.3
    detail 3.4

I started with nested Listboxes but then realized that the ItemsControl is also a possibility since I did not need Listbox behavior like selection of items, etc.
Think of ItemsControl as the insides of a ListBox.

But then scrolling became an issue because I wanted all items to be visible at once and not need to scroll the detail list for item 3 for example.

Fyi, you can make the ItemsControl scrollable by adding a View Template, like so:

<ItemsControl x:Name="myItems">
 <ItemsControl.Template>
  <ControlTemplate TargetType="ItemsControl">
    <StackPanel>
      <ScrollViewer VerticalScrollBarVisibility="Auto" Margin="0,0,0,0">
	<ItemsPresenter />
      </ScrollViewer>
    </StackPanel>
  </ControlTemplate>
 </ItemsControl.Template>
</ItemsControl>
There are many nice posts about ItemsControl which you can look at to tweak and use them well.
Unfortunately, they couldn’t work easily for me, since I needed to autosize the nested details so that either 1 or 4 items could be shown without scrolling.
I say easily because I am sure sure some WPF gurus can do almost anything with ListBoxes, but not me.
I am now working to adapt the LongListSelector control from the toolkit. It was mainly made for virtualizing the View and the data to give you a fast scrolling and grouped list.
The Contacts list on the phone is a good example of it.
So, if you want to use nested lists and want the children to autosize, etc., look at the LongListSelector sample in the toolkit.
This mini-series by WindowsPhoneGeek helped me understand it better.

6. Re-entrancy problems are possible with MVVM Light
I am using the MVVM Light framework which is quite handy for locating ViewModels, but you also need to be careful about manipulating collections while in a loop.
This is more an issue of bad implementation than the framework itself, but iterating over static ViewModel is enticing and a common mistake and should be done with caution.
If you change any item in the List will throw an Exception. I forget now exactly, but I think I was getting a NullReferenceException.
So, my advice while manipulating a ViewModel List, is to create a new List and iterate over the static ViewModel List and copy it’s contents and then set the ViewModel list to your new local List.
Hope these points saved some of your time…

Since everyone (including me) and their mother is now dabbling in WP7 development, I thought I’d write about some of it and share my experiences with the community.

Before getting into dev details, let’s start with the setup and getting off the ground.

The page to access the wormhole is at: http://create.msdn.com.
It has a link to download the (free) tools you’ll need.

image

Please go ahead and install the various components required; I’ll wait.
The pieces include the VS extensions which installs the various phone app templates, the WP7 emulator that lets you run and test apps without a real phone in hand, etc.

We are now ready to write our first app.
Note that we are going to explore Silverlight apps and not XNA apps. These run on a managed Silverlight layer on the phone, as opposed to an XNA platform that conceptually treats the device like a console where you can manipulate each pixel.

Open VS and select New Project –> Silverlight for Windows Phone – Windows Phone Application (the first item), as shown below.

image

Give it a name and location and you will be faced with the Mainpage.xaml

image

If you just want to run the project and hit F5, you will get a compile error stating that “Zune software is not installed. Install the latest version of Zune software.”

image

This happens because the output is set to a device, and you can change it to go to the Emulator by changing the dropdown selection next to the Play button to Windows Phone Emulator.

image

Hitting F5 now, loads the Emulator and shows the app in it.

To end debugging, the instinctual way is to close the Emulator. But I like to keep the Emulator running in order to save time in further debugging sessions.
Hit the Back <- button at the bottom of the Emulator or go to VS and hit Stop to exit from Play mode.

So, now you have a very basic Phone app running in Visual Studio. That’s all for now. More to come in future posts…