Tag Archives: mango

Retrieving Contact Information In WP7.1 (Async/Sync Goodness)

Over the last few days I’ve come up with another application that I’d love to make, and a small part of it involves retrieving contact details. As part of the Mango update, one of the new APIs provided by Microsoft is the contacts API, falling under the Microsoft.Phone.UserData namespace.

This is awesome, except that because the contact search method is only provided asynchronously, I was having a massive headache trying to write code that would return a random contact, wrapped in a DataObject, synchronously. In effect, I wanted something like this:

[sourcecode language="c-sharp"]
public Person GetRandomPerson(string s)
{
Person myPerson = new Person();
Person contacts = new Contacts();
contacts.SearchCompleted += new EventHandler<ContactsSearchEventArgs>(contacts_SearchCompleted);
contacts.SearchAsync(String.Empty, FilterKind.None, "All Contacts");

return Person; //I’m not sure how this will ever work…
}

void contacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
{
//convert a Contact object to Person object here
}
[/sourcecode]

After going around in circles with async and AsyncCallback and EAP and APM and a trillion google posts, it boiled down to a few things:

1) Passing the Person / DataObject through to the contact search callback as the third state/object parameter. – eg:

contacts.SearchAsync(String.Empty, FilterKind.None, myPerson);

2) using AutoResetEvent to control the thread execution, in order to prevent the GetRandomPerson() method from returning until we were sure the Contact Search had finished its thing – so creating an AutoResetEvent object, then calling are.WaitOne() after calling contacts.SearchAsync(), and in the callback, calling are.Set().

3) most importantly – calling all the code in a background thread. The UI thread doesn’t like being asked to .WaitOne() and just dies, so I used ThreadPool.QueueUserWorkItem(). Of course, this means that my code now goes Async -> Sync -> Async (which is still async.)

My final code looked like this:

[sourcecode language="c-sharp"]
private void Button_Click(object sender, RoutedEventArgs e)
{
//this should be done asynchronously – "request" a person

List<Person> people = new List<Person>();
PersonService ps = new PersonService();
ThreadPool.QueueUserWorkItem(func =>
{
for (int i = 0; i < 10; i++)
{
people.Add(ps.GetRandomPerson()); //you need to call this on a separate thread or it will lock the ui thread.
}
Dispatcher.BeginInvoke(() => { Status.Text = "done"; }); //your button click method is now also asynchronous
});
}

/*** Helper class ***/

public class PersonService
{
AutoResetEvent sync = new AutoResetEvent(false);

public Person GetRandomPerson()
{
Person person = new Person();
Contacts contacts = new Contacts();
contacts.SearchCompleted += new EventHandler<ContactsSearchEventArgs>(contacts_SearchCompleted);
contacts.SearchAsync(String.Empty, FilterKind.None, person);
sync.WaitOne();
return person;
}

void contacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
{
Contact[] allContacts = e.Results.ToArray();
Contact randomContact = allContacts[new Random().Next(allContacts.Length)];
Person person = (Person)e.State;
person.Name = randomContact.DisplayName;

sync.Set();
}
}
[/sourcecode]

Note that the Windows Phone emulator comes loaded with some test contacts, but I’m not entirely sure they come with contact images so that’s something you may need to double check if you’re planning on using. If anyone’s got a better way of solving the same issue, let me know!

WP7 Mango Rolling Out

Although since I’ve been on the developer beta for a while, it doesn’t really feel all that different – it’s nice to have the official bits though, and I’m sure everyone who’s going from NoDo to Mango is going to be super excited!

On the WP7 front, Noborizaka has been updated but there was a slight hiccup with the publishing so it should be rolling out worldwide soon-ish…watch this space!

WP7: Upgrading Your App From 7.0 to Mango (FAS / Tombstoning)

While upgrading an existing Windows Phone 7.0 application to Mango and all its multitasking and performance improvement glory is a pretty easy task (simply go to the Project properties and change the target from Windows Phone 7.0 to Windows Phone 7.1), there are a few things you need to watch out for when upgrading that you might have to fix manually.

One of the bugs I came across in Noborizaka was that when my application was first launched, everything would operate as normal – but whereas in the old Windows 7.0 version if my application got tombstoned and reactivated everything would work fine, in Mango, after my app was rehydrated, the databinding for my listboxes etc. didn’t seem to be valid any more so new items wouldn’t appear on the main page until I reset the application fully.

It turns out the reason for this is that as part of Mango and Fast Application Switching (FAS), the OS automatically stores your application’s entire state while it’s in the “multitasking backstack”. So therefore, you need to check the .IsApplicationInstancePreserved proeprty in the Application_Activated of your App.xaml.cs, and if it’s true, you should not restore your state from IsolatedStorage. Example:

[sourcecode language="c-sharp"]
//Windows Phone 7.0
private void Application_Activated(object sender, ActivatedEventArgs e)
{
RestoreStateFromTombstone();
}

//Windows Phone 7.1/7.5/Mango
private void Application_Activated(object sender, ActivatedEventArgs e)
{
if (!e.IsApplicationInstancePreserved)
{
RestoreStateFromTombstone();
}
}
[/sourcecode]

Everything else should work as normal – good luck to all the devs out there making Mango apps! (p.s. if you’d like to read more on the Execution Model of WP7, and what the lifecycle of an application looks like, you can take a look at the MSDN documentation here.)

WP7: Updating Live Tiles Locally In Mango

As you’ll no doubt be aware if you’ve been looking at any of the information around Mango released over the past few months, there’s a large number of additional APIs available in the upcoming update release to Windows Phone 7. One of the ones I’m very excited for is the ability to update the live tile for your application locally! This means that for Noborizaka, I no longer have to host an Azure service to generate an image when I can simply do so from the phone itself.

Updating Live Tiles programmatically is extremely simple, too. The basic steps are:

  • Get the main Application Tile. Every app you create has this tile, and this is the tile users see when they pin your application to the Start screen. You can do so like this:

    [sourcecode language="c-sharp"]
    ShellTile defaultTile = ShellTile.ActiveTiles.First();
    [/sourcecode]

  • Update the application tile, providing a StandardTileData object. Once you have a reference to the main application tile, you can call the Update() method, providing a StandardTileData object which can contain a BackgroundImage, Title, Count (as well as some other properties for the back of the tile, which is also new to Mango).

    [sourcecode language="c-sharp"]
    defaultTile.Update(new StandardTileData { BackgroundImage = new Uri("isostore:" + sTilePath, UriKind.Absolute), Title = "Noborizaka" });
    [/sourcecode]

  • Note that instead of pointing to a BackgroundImage with a Uri to an online image, I’m pointing to an image that I’ve stored in local isolated storage – I’ve set up my app so that when it’s exiting or being deactivated, it quickly generates the tile image and saves it to isolated storage before the live tile is updated, and it all seems to work quite well. Note that the tile image needs to be stored in a folder ‘\Shared\ShellContent’ for it to be available for tile updates.

    If you’d like to read more on live tile updating (such as updating the back of the live tile and secondary tiles), check out this MSDN Article. You can also check out how to generate live tile images without using the visual tree here (ie, elements that aren’t being rendered directly onto your application).

Noborizaka is not dead…

Just sleeping :( I do also know that it is still mistakenly listed under the Games category on the Marketplace, but as it’s published through my work’s MSDN account, there’s a little bit (not much) of bureaucracy to get it republished…

At the very minimum you can expect a version for Mango with the performance/multi-tasking improvements. Watch this space! (And thanks for all your support so far)

WP7 Mango Beta Is Delicious

I’ve been running the Developer Beta 2 preview on my WP7 for a few days now, and I can safely say that it is a massive step forward for Microsoft. There’s a ton of stuff out there on the internet, but just some of the features that I absolutely love:

Quick Calendar Entry
WP7 boasts one of the best mobile calendar apps out there (infinitely better than the crappy Calendar app on the iPad, for which I have a complaints list as long as my arm for), and they made it even better, adding support for multiple synced calendars (Windows Live / Exchange only for now…) and creating calendar entries even faster! Now when you tap on a timeslot in the day view, you can start entering the title immediately, and it defaults to an hour block. It’s fast, good looking, and easy.

Messaging Threads
Conversing via txt to MSN to txt to Facebook is amazing, and is really one of the killer features in WP7, as far as I’m concerned. A nice little touch is the automatic emoticons that come up now, even for text messages!

Battery Saver
They’re not kidding when they say it saves battery. WP7 now gives you a rough time-based battery life estimate in terms of hours (which is useful enough on its own), but also now has a battery saver mode which you can enable manually, or set to turn on when your phone is running out of juice. It pumped the life of my phone from 5 hours to roughly 10 – which is awesome if you know you need to receive an important call, but you’re running low on power.

Chinese Keyboard Drawing Input
Now this is pretty awesome. I don’t know if anyone’s detailed exactly how it works, but it seems accurate enough – you just draw your chinese characters straight onto the phone (of which I know very few, but enough to play around with this).

It’s definitely worth the rather long update process to get your phone to run the Mango Beta – you won’t regret it!

The Great Wall of WP7 Apps

So, apparently at MIX ’11, Microsoft covered three walls with every single app in the Markeetplace to date. While the one Apple had at the WWDC conference in 2009 does sound awesomer, it’s still pretty awesome that they did so. You can find some high resolution shots here and here, courtesy of Long Zheng.

And obviously, the first thing I wanted to do was to look for my app, and I think I found it. What do you think?

Sidenote: I am super, super excited for the Mango update. Pretty much every complaint or issue I’d have with the SDK is going to go away – direct access to camera/sensors (for much improved barcode scanning apps), local live tile updating (so that I don’t have to keep my Azure web service whose sole purpose in life is to update Noborizaka live tiles), sockets support (so that I can get a Skype app), access to Contacts library (for Whatsapp), Live Agents (for alarm/reminders) – now if only they can release Mango in a timely and non-disastrous fashion, we might have a winner here…