Scott Hanselman

NuGet Package of the Week #13 - Portable HttpClient makes portable libraries more useful

March 21, '13 Comments [16] Posted in NuGet | NuGetPOW | Win8 | Windows Client | WinPhone
Sponsored By

Reference Assemblies include .NET Portable AssembliesWhen you've got an idea for an app, it's likely that you've got the idea for that app in more than one place. By this I mean, you'll start with a phone app, then make a desktop app, then a web app. Or you'll make a game on one platform and then want it to work anywhere. In fact, with the rise of Xamarin, C# lets you put an app in every AppStore in the world with one language.

You likely already knew that you can target different versions of the .NET framework. You likely also know that there are small .NET Frameworks like Silverlight and the tiny .NET Micro Framework.

You can also target XBox and Windows Phone, OR better yet, target a profile called Portable Libraries that I've briefly mentioned before. Portable Libraries are a great idea that have some issues when you try to really use them. There's actually a great (if a little older) video with the inventors over at Channel 9. Note that Portable Libraries ship with Visual Studio 2012 and are a supported thing.

The idea is that you write a library that contains as much shared functionality as possible and then every application uses your now "portable" library. However, the subset of classes that are available are a subset. That means you can only use things that are available in the intersection of the targets you choose. Check this dialog:

Choose your target framework

And check out the Supported Features table at this MSDN article on Portable Libraries to find out what you can use where. Here's a graphical table I stole from Daniel.

PortableLIbraryChart

However, most folks that use Portable Libraries have ended up using them mostly for ViewModels - just simple classes without any real functionality. Almost as if we had a DLL full of structs. There are some great posts on how to make Portable Class Libraries work for you using architectural techniques like indirection and appropriate interfaces.

The number one complaint around code resuse and the number one voted item over at the Visual Studio UserVoice was "Add HttpClient support in Portable Class Libraries (including Windows Phone 8)." Why? Because the GETting of a remote resource via HTTP is such a fundamental thing that it'd be awesome to be able to bake that data access into a portable library and use it everywhere.

Now there is a Portable Http Client and you can get it via NuGet!

install-package Microsoft.net.http -pre

Here's an example of what the code looks like for a GET. Note that I'm using async and await also.

public static async Task<HttpResponseMessage> GetTheGoodStuff() 
{
var httpClient = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://hanselman.com/blog/");
var response = await httpClient.SendAsync(request);
return response;
}

.NET Portable Subset

If you were going to make a Twitter client (lame example, but bear with me) you could now put the JSON HTTP data access code in one library and share it across Windows Phone, Windows Store, WinForms, Console, whatever.

I'm hoping that the folks at MS and the folks at Mono will continue to work to make Portable Libraries a good option for Mono as well. I've been advocating (and pushing) to make something happen as well, as have the Portable Libraries folks. You'll find lots of working in the space around the web, so fear not, code reuse, either through Portable Libraries or via linked code files at compilation time is deeply possible. The game "Draw A Stickman Epic" achieved 95% code reuse by writing the game in C# with MonoGame!

.NET 4 or Windows Phone 7.5

If you want to use this HttpClient on .NET 4 or Windows Phone 7.5, note you might get a compile error if you use async and await.

Cannot await System.Threading.Task<HttpRequestMessage>

This is because .Net 4.0 and Windows Phone 7.5 did not support the async/await keywords. In order to fix this add a reference to the Microsoft.Bcl.Async nuget package, which adds the support for async and await in .NET 4 and WP7.5. Here's a post with more details on how this backport works.

Related Links

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. I am a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by ORCS Web

Updating my Windows Phone App to Windows Phone 8

December 8, '12 Comments [18] Posted in WinPhone
Sponsored By

Lost Phone Screen on Windows Phone 8Earlier this year I wrote a small Windows Phone 7 application in a day called Lost Phone Screen. It creates lock screens for you with your name and contact number on them to aid in finding your phone the old fashioned way when you lose it. No need for a GPS, just tell folks you have a small reward and give them a number to call. You can download it free now as folks will not pay 99 cents for anything except Angry Birds. But I'm not bitter. ;) Anyway, it works great on Windows Phone 7 and Windows Phone 7.5 (Mango.)

Recently I got a Nokia Lumia 920 with Windows Phone 8 and since there's a number of new APIs and features I could exploit - not the least of which being the ability to programmatically set the phone's Lock Screen without the user needing to do anything - I figured it was time to update it.

I encourage you to review the post From Concept to Code in 6 hours: Shipping my first Windows Phone App as a reminder of what the app did and the issues I had writing the Windows Phone 7.x version.

Here's what I had to think about updating the app for Windows Phone 8. Big thanks to my friend Justin Angel at Nokia for brainstorming on Skype with me and helping with the async code and resolution issues. His blog post on What's New in Windows Phone 8 was very useful, especially his little MultiRes helper class.

Updating The App

First, to be clear, the existing Windows Phone 7 app works great on Windows Phone 8 without ANY changes. It runs and behaves exactly on Windows Phone 8 as it did on Windows Phone 7. I wanted to update it in order to "light up" some the new features on the new OS.

Upgrading the Project to Windows Phone 8

Upgrading was easy, I opened the old project and was prompted to upgrade. I double-clicked on the WMAppManifest.xml and made sure to reassert some of the basic settings like icon sizes and tiles for my app, as well as confirming the capabilities that my app would need like photo access, etc.

I was sure to check the Supported Resolutions as I knew I'd need those later.

Windows Phone 8 supports three resolutions

Keeping two Branches vs. One Super Project

I went back and forth on this. It's an upgraded OS but 99% of the code will be shared. However, enough stuff has changed that I decided to make a branch in source control rather than make a single build. Honestly, there's likely no wrong answer here and you use what you're comfortable with. I could have to CSProj files if I liked, or just made a different Build Configuration (like Debug8 and Debug7, etc) but I understand my source control pretty well so I ended up with a phone70 and a phone80 branch and I switch between them. It's more likely that I'll be updating the phone80 branch then "back porting" new feature so for now this work fine, but know I can always make a single build if I want.

Ultimately though, I know that I need to make a build for Windows Phone 7.x and one for Windows Phone 8 but I can submit them each to the Store under the same name and the Store will do the right thing. If you've got Windows Phone 8 with a new resolution you'll get the right version as you can see in the screenshot below. I've submitted two XAP files.

Two versions of the same app in the Store, one for each phone

New Screen Resolutions

I updated my app a few weeks ago but my first good bug came in from a gent with a HTC Windows Phone device running at 1280x720, rather than 1280x768. He said my lockscreens were cropped! With Windows Phone 8 there's three resolutions, in fact as Justin points out:

The resolutions are: WVGA (480x800 pixels), also used in Windows Phone 7; WXGA (768x1280 pixels), essentially an HD version of WVGA; and the wildcard 720P (720x1280 pixels) that uses a different aspect ratio to WVGA and WXGA. You should be aware of these different resolutions, make sure to use relative <Grid /> positioning in laying out screens, and potentially different media assets for different resolutions.

It's less important that there's three resolutions but rather more interesting that 720p is a different aspect ratio! Turns out I was making a number of assumptions in my code, not the least of which being the screen resolution. I was assuming 15:9 as the aspect ratio like 800x480 and 1280x768, but 16:9 is 1280x720!

My initial reaction was, crap, now I have to actually think.

Turns out that it's easier than that. On all of my app's pages but one I was able to remove XAML code and hard coded margins and row definitions. I was actually being too specific and not letting the system lay itself out optimally.

I removed all my hard-coded margins and changed my Grids to use a RowDefinition of "*" which means "the rest of the space" like this:

<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
...
</Grid>

The first RowDefinition fills to the size of its content and the second just takes up the rest. This made all my pages look great on every resolution screen, and it was easy to test because I could just change the Emulator dropdown to select the various  resolutions:

Different Emulator Resolutions in a Dropdown

However, with these new resolutions, I did change my originally single SplashScreenImage.jpg to include one each for the three resolutions named SplashScreenImage.Screen-720p.jpg, SplashScreenImage.Screen-WVGA.jpg and SplashScreenImage.Screen-WXGA.jpg. You'll find that at least half your time doing mobile apps (regardless of Apple, Windows or Android) is getting the PNGs and artwork files correct).

Three new SplashScreens

I had (chose) to hard code some screen sizes in one place in the app. (I could have queried  Application.Current.Host.Content.ScaleFactor. Application.Current.Host.Content.ActualHeight and Application.Current.Host.Content.ActualWidth to be correct.) I have a VERY specific custom Image Cropping control that needed special handling for the 720p case, likely due to my lack of skill with XAML. I am told that only the most edgy of edge cases need to do this and often this is in the creation of pixel-perfect lock screens so you probably won't sweat it at all.

New Lock Screen API

Finally my app can update the Lock Screen without manual user intervention. This was my #1 request and everyone assumed it was my fault that the feature didn't exist. It's been added in Windows Phone 8.

If you app wants to change the Lock Screen it has to ask once and get permission. It has to be the "current lock screen provider." If it is, it requests access and then sets the lock screen.

if (!LockScreenManager.IsProvidedByCurrentApplication)
{
LockScreenRequestResult result = await LockScreenManager.RequestAccessAsync();
if (result == LockScreenRequestResult.Granted)
{
SetAsWallpaper(filename);
}
}
else
{
SetAsWallpaper(filename);
}

SetAsWallpaper is just a helper around LockScreen.SetImageUri().

private void SetAsWallpaper(string filename)
{
string realPath = "ms-appdata:///local/" + filename;
Debug.WriteLine(realPath);
//Debug.WriteLine(ApplicationData.Current.LocalFolder.Path);

LockScreen.SetImageUri(new Uri(realPath, UriKind.Absolute));
}

And that's it. Lovely and simple. BUT.

A Very Important Reminder when using Asynchronous APIs

In Windows 8 and Windows Phone 8 (since the Windows 8 magic dust is under Windows Phone 8) everything is all about asynchrony and non-blocking APIs. Before I'd just save the wallpaper and you'd wait and you had no choice. Now all the underlying APIs are asynchronous  (non-blocking) and we as developers have await/async keywords to make things simple, right?

Sure, but my second lovely bug that showed up was when folks mashed on the Save button many times. Because everything is non-blocking this would fire off many save requests and eventually they'd collide at the file system with an "Access Denied" or something equally useful.

I have this shared resource that I need to protect access to but I don't want to block the UI. Michael L Perry has a great solution for this that should probably be built into the Windows Phone SDK (unless it is and we've all missed it?) in his Awaitable Critical Section helper. This helper lets us use the familiar using{} block structure in situations where we are using async and await inside what would have been a lock(){} block.

As Michael points out, you CAN'T do this because you can't await in a lock.

lock (this)
{
FileHandle file = await FileHandle.OpenAsync();
await file.WriteAsync(value);
file.Close();
}

But with his helper you can do this:

using (var section = await _criticalSection.EnterAsync())
{
FileHandle file = await FileHandle.OpenAsync();
await file.WriteAsync(value);
file.Close();
}

And I did just that.

Analyze

When you're done, make sure you run the Windows Phone Application Analysis tools see how your application does. Does it use too much memory? Use up the battery? Does it startup in less than a second?

Windows Phone Application Analysis

This is fascinating stuff. Don't work so hard on your app and forget to profile it.

New Things to Remember when Submitting Your App and Submitting Two Versions

I fixed some bugs in the Windows Phone 7 version, changed that XAP's version number and submitted it as a small upgrade. Folks who have Windows Phone 7.x will get prompted to update their app. This version, as you'll recall, doesn't auto-update the lock screen because it can't.

I go into the Phone Marketplace and click Update App from the Dashboard. There's the Marketplace before my update, showing the 7.1 app:

Windows Phone 7 app

I click Update selected and upload the new Windows Phone 7.1 targeted XAP that I just built. After that's uploaded I change the dropdown and upload the Windows Phone 8 XAP. I make sure in both cases to upload a Release XAP and the "AnyCPU" version.

Windows Phone 8 app

I am keeping the Windows Phone 8 one a few versions ahead for my own sanity. It makes sense to me and it helps me remember what's "newest" even though it only matters that the new versions be higher than the previous versions.

Be sure to check all your text, your descriptions and icons to make sure they are correct.

Time Spend Coding vs. Time Spend Editing PNGs

Goodness, I swear I have spent more time messing with screenshots and PNGs than coding.

Here's the thing: Mobile app development is all about the Screenshots and Icons.

There's so many resolutions and assets and different scenarios where your application can be showcased that it's worth spending some time getting really good at PhotoShop or Paint.NET. I'm doing all my work in Paint.NET, in fact.

Because there's three resolutions you'll want to make note that you need three sets of screenshots! Fortunately there's a screenshot cool built into the Emulator and Windows Phone also supports in-device screenshots (finally) by pressing Power+Windows Key.

It may not be obvious from this picture of the marketplace submission but you need to click WXGA and 720p and upload separate screenshots for each one! Otherwise your potential users won't see your app looking exactly as it will on their device. Tedious, but crucial.

Three sets of screenshots for three resolutions

Truly, this became an asset management chore. I ended up with a folder fill of JPGs and PNGs and only kept my sanity with some reasonable file name conventions.

naming screenshots and splashscreens reasonably.

You will end up with at least 24 screenshots (3x8) plus three splash screens, several icon sizes and you'll also want to test on both the Dark and Light themes.

Conclusion

In the end, it will be seamless for your end users. Folks who have Windows Phone 8 will get their updates from your WP8-XAP and Windows Phone 7.x folks will get theirs from your WP7-built XAP. This whole thing took about 3 hours and most of that time was spent doing screenshots.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. I am a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by ORCS Web

"I can't even think about switching phones without these apps." Windows Phone 7, a Nokia Lumia 800 and the Essential Apps

February 28, '12 Comments [60] Posted in Tools | WinPhone
Sponsored By

Lots and lots of Windows Phone 7 AppsI'm still using my iPhone 4s mostly but a Nokia Lumia 800 showed up in the mail last week. I'm looking forward to the Nokia Lumia 900 as well. Turns out that Nokia was giving away new Lumias to folks that had written Windows Phone 7 applications in the month of January as a part of their "WPNewYear" promotion. Since I wrote Lost Phone Screen - The customizable Windows Phone 7 lock-screen I qualified for a free phone. Now I've got a Samsung Focus and a Lumia 800. This isn't a review of the Lumia 800 (I'll do that later) but I will say initially that this is a nice piece of hardware. It's got heft, it's got a crazy bright screen, good glass, 8 meg camera, glass lens, it's fast. It feels right. Better than the Focus. The Lumia 800 can stand up against the iPhone for most users. It's only major lacking is a front facing camera.

The thing that keeps me from switching over to some other phone always comes down to apps. Apps apps apps. Everyone's got that app or apps that they just "can't live without." The general belief is that Windows Phone doesn't have the essential apps with the big name services.

I took some time and listed out all the apps and social services that I use on my iPhone and found them for my Windows Phone 7. This is the "I can't switch even think about switching phones without these apps" list.

While l realize the irony of being on the "mobile apps update treadmill" and would prefer a world without apps, this is the world we have today so here are the apps to navigate it.

Basics

Get these obvious apps first. Facebook, YouTube, Acrobat, XBox Live Extras, and Vimeo. Also NetFlix if you have it.

The Essential Apps imageimage

Foursquare

There is a standard first-party Foursquare app on Windows Phone, but the BEST app for Foursquare is called 4th & Mayor. It's a gorgeous and meticulously well-designed application that is arguably the best example of an excellent Windows Phone 7 app there is today. If you are writing an app and are wondering how to do something in the UX, just refer to 4th & Mayor. It also takes excellent advantage of the WP7's Live Tile concept. I've pinned a "Check In Now" tile to my home screen which makes Foursquare check-ins just two clicks.

4th and Mayor

Twitter and Facebook

Windows Phone 7 People HubTwitter and Facebook sharing and contact management is built into Windows Phone 7's People Hub. You connect accounts together (this happens automatically) so if your friend Bob is on Facebook, Gmail, Outlook, Twitter and LinkedIn, rather than opening separate apps. Rather than app-focused it's people-focused. I use this for Family and Co-workers. It's nice to just see a Person and what's up with them.

You can see in the screenshot at the right that one person is automatically associated with four services and all their updates are under What's New. Same with pictures, I see their Facebook, etc, all in one place.

For power Twitter use though, I use an app. There's an official Twitter app which is fine for regular folks. For the more hardcore tweeters, I recommend Rowi. There's a free ad-supported one and a paid-for version. It has notifications, toast, tile updates, photo uploader and more. I've used the 2.0 beta (coming soon) and the future is bright as Rowi is actively developed.

Weather

The Weather Channel app is excellent, includes an updating animated Live Tile, radar maps, forecast and all the usual stuff - and more - you'd want from a Weather app.

971ff6f8-de15-483b-96a4-52f1a43a962d

Movies

There are two great movie apps and I move between them, but Flixster is pinned to the home screen. Flixster's LIve Tile is a current movie's poster, which is a nice touch. It supports fast app switching on Mango, has all the showtimes, favorite theatres, but most importantly Rotten Tomatoes movie scores. Fandango is also nice if you want to buy tickets, and they now support Pinning your ticket confirmation for easy access when you get to the theater. Also grab the IMDb application so you can argue a bout who That Guy is in the movie.

Flixster on Windows Phone 7

TripIt Travel with My Trips

TripIt is the greatest thing to happen to travel since Expedia. I blogged about it in my 10 Guerilla Airline Travel Tips for the Geek-Minded Person and I still recommend it today. On Windows Phone 7, use My Trips for access to all your travel, ticket, gate and flight status info on the go.

My Trips for TripIt on Windows Phone 7

News

I've just got room for a few good news apps in my life, so on Windows Phone I go with the same apps I have on my iPhone.

BBC News Mobile is an excellent 3rd part BBC news reader. Clean, fresh, looks good, supports Mango and has Live Tile support so I can get news headlines pushed to my home screen without launching the app. I also have NBC Nightly News because it includes the full show.

BBC News for Windows Phone

Engadget, well, is Engadget. It's tech news, gadgets and consumer electronics. Nice Live Tile with pictures pushed to it and fast, good-looking application.

Engadget for Windows Phone

I recommend AP Mobile with a caveat. It's a great looking app, one of the first with a Live Tile. It pushes a new daily photo to the tile, which is nice. It's got lots of great AP photography and has worked fine for months. However, in the last few weeks the photo quality has gone down the toilet. The photos are freakishly JPEGed and there's not a peep from AP about it. Something is clearly being proxied and double compressed ,  perhaps in an attempt to save bandwidth. I hope they fix it soon because it was/is a great app.

AP Mobile for Windows Phone

News Reader/RSS Reader/Google Reader

Pulse is a lovely aggregating reader that sits somewhere between regular RSS reader, magazine, and News App. Looks great on my Windows Phone as it did on my iPhone.

Pulse News Reader for Windows Phone

Wonder Reader synchronizes with my Google Reader account. It's got lots of cool features and uses of LiveTiles and allows you to pin feeds, categories, and favorite blogs. It's also got a nice collection of pre-loaded categories for jump starting. It's not Reeder for iPhone, but it is the best Google Reader client on Windows Phone. Even better, it has Instapaper support!

Wonder Reader google reader for Windows Phone

Instapaper

I am a heavy Instapaper user and recommend it highly. I've blogged about it in my Two Must-Have Tools for a More Readable Web. I pay Marco at Instapaper happily, and was thrilled when I found Stacks for Instapaper. If you are a hardcore Instapaper person, you'll agree that having Instapaper on your phone is required. This is a "first page app" for my iPhone and an "above the scroll" app for my Windows Phone.

Instapaper for Windows Phone

Nerd Social

What is a phone without Reddit? Baconit is a Reddit app for Windows Phone. It supports Live Tile pinning of subreddits and a clean UI.

Reddit for Windows Phone

Perhaps you prefer Hacker News? That's available now too with the Hacker News Reader.

Hacker News for Windows Phone

Music - Spotify and Vevo

Windows Phone 7 has deep integration with Zune and the Zune subscription music service (you pay $9 for all the music you can listen to...you're leasing music rather than buying) but I am a Spotify user. I've got Spotify on four other devices and my PC so I need it on my phone too. Finally, it's here. It plays music in the background and under the lock screen and it integrates with the existing Music Hub so it doesn't feel like a 3rd class citizen.

Spotify for Windows Phone

Vevo is like Hulu or YouTube for Music Videos. When I get tired of Spotify, sometimes I'll just let videos play with Vevo playlists. It also has a nice Live Tile. There is also Last.fm and IHeartRadio.

Vevo for Windows Phone

Photography - InstaCam and Pictures Lab

Pictures Lab is a nice effects and editing application (if not THE BEST editing app) for Windows Phone. All the functionality is there and cleanly integrated with the Photos Hub. Crop, Rotate, Effects, etc. It's a must-have if you are doing any photography on your phone.

Pictures Lab for Windows Phone

Say what you will about using a supercomputersmartphonewith8megapixels to take crappy Polaroid pictures but I'm a big Instagram fan. It is a fun social network and I use InstaCam on Windows Phone to explore it. Unfortunately it doesn't appear that Instagram (the company) is interested in fostering a 3rd party client application ecosystem because their API is effectively crippled with no upload support. Seems odd. It's also odd that you can visit a photo of mine on Instagram, but can't follow me from there OR see my  other photos!

Instagram for Windows Phone

Also consider Flickr if you use that service.

Cloud Storage - Dropbox and SkyDrive

I'm a paying Dropbox user and a big fan. There's a few Dropbox clients on Windows Phone but I use BoxFiles for DropBox and so far it's worked just fine. I can pin Dropbox folders to the start screen and email links to files in my Dropbox.

Dropbox for Windows Phone

I've got a few files on SkyDrive including some photos and OneNote files, so there's an official SkyDrive client as well. This app particularly shines when editing Word and Excel documents from the cloud on your phone.

SkyDrive for Windows Phone

Communication - Skype and GroupMe

Yes, Skype, baby. It's beta as of the time of this writng, so you can't search for it, you need to go get Skype for Windows Phone from this link or read their help page on Skype for Windows Phone. I'm less interested in the Video part, although that's cool, and more in the audio calls part. Whenever I'm overseas I always make Skype calls to my family from the hotel Wi-Fi. It's completely cut out international long-distance from my life, and I still get to talk on my same phone.

Skype for Windows Phone 7

GroupMe might not seem obvious or essential at first, but my team uses it all the time. It's a grouped IM service, except it will use the app OR SMS to communicate with the group. That means you can put together a group of family members and start a chat without paying for SMS costs, and everyone can talk to everyone at the time time across platforms. I create GroupMe Rooms for conferences that I attend so my friends/co-workers can have a private backchannel. It's fantastically useful, especially if you want to include non-smartphone-using Dad or Mom on the social.

GroupMe for Windows Phone

Amazon

Ya, they get their own category. I've got both the Amazon Mobile shopping app (a best-of-breed app on Windows Phone) and the Amazon Kindle app. Both apps are of exceedingly high quality. The Amazon Mobile app has UPC scanning as well as the ability to pin a scanning tile to you rhome screen so you can scan with one click.

Amazon Mobile for Windows Phone 7

The Kindle app is as you'd expect. It has a very nice theme but then turns into a clean reader when you are in the book with options for fonts and colors. Best part, it syncs you pages between all your Kindle devices.

Kindle for Windows Phone 7Amazon Kindle Reader on Windows Phone 7

As an honorary mention to the Amazon section, check out Craigslist Mobile. A very attractive and polished app (more than the CL website!) that lets you query and shop on Craigslist.

Craigslist Mobile for Windows Phone 7

Also  useful because my wife uses it is Groupon. I was impressed they had a native app.

Groupon for Windows Phone

Must Have Utilities

There are a couple of Utilities I've discovered for Windows Phone that GREATLY enhance the experience.  They are almost so useful that they should be built into the OS. (That's when I know a utility is work my time...when it just belongs.)

Ok, I'll cheat, the first one is mine. It's http://lostphonescreen.com/ and it's a customized Lockscreen for Windows Phone. I always think it's silly to get a fancy phone with a GPS to track it when it's lost. Why not just put your phone number on the wallpaper?

Customizable Lock Screen for Windows Phone

ConnectivityShortcuts gives you Live Tile links to stuff like Airplane mode, Wi-Fi and Bluetooth. Absolutely essential.

Wifi Shortcuts for Windows Phone

Wiztiles Pro is a little hard to understand but if you use the phone for more than a day you'll immediately want what it has to offer. It's essentially a shortcut creation kit. For example, I added custom shortcuts to my browser with a custom downloaded theme icon, added a directly link to Share Status. You can customize anything you like, even break large pictures up into tiles. You can customize the phone's tiles in ways you didn't think possible. It's really amazing.

Extreme Windows Phone Customization with Wiztiles ProExtreme Windows Phone Customization with Wiztiles Pro

Food

If you want Recipes, it's all about BigOven and AllRecipes. I use both regularly.

f87dbb70-e61a-4c6e-b672-d2cb52e7757738758da3-24f5-47b5-9daf-76035781b28a

Conclusion

If you've considered making an application of your own for the Windows Phone, here's a write-up on how I wrote my first app's first version in about 6 hours. I also have some podcasts you might be interested in:

Hope you enjoyed this list. I was pleasantly surprised how many apps that I already use were available. My wishes for the future are, 360Panorama from Occipital, Eye-Fi, Comixology (They already have a DC Comics viewer, so the hard work is done), Mint, and Hulu.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. I am a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by ORCS Web

From Concept to Code in 6 hours: Shipping my first Windows Phone App

January 30, '12 Comments [49] Posted in Open Source | WinPhone
Sponsored By

A screenshot of my new app Lost Phone Screen for Windows Phone 7Warning, this is long. I'll be frank with you, as I always am. I have an iPhone, a number of iPads and I like them fine. I have a Windows Phone that I use occasionally. I know C# but I do not know Objective-C.

TL;DR Version

I made my first Phone Application. I've spent about 6 hours on it. It's called Lost Phone Screen and it makes nice wallpaper. It's over at http://lostphonescreen.com. It's a simple customizable Windows Phone 7 Lockscreen. It was way easier and more fun to make than I expected. If I make a million bucks with this thing I'm GONE. You'll never see me again. :)

Introduction

I wanted to see how quickly I could make a useful Windows Phone 7 application. I'm not talking about just dragging a button onto a Hello World template and adding "press to fart." I'm talking about an MVP - Minimally Viable Product. It might not be the greatest app in the world, but it will provide value. At least to me.

Disclaimer: I don't work for the Windows Phone Team and don't really know anyone over there. I did this on my own with my personal details, personal account, as an "on the side moonlighting thing." While I work for Microsoft, I work in the Web department, not in Phones.

I honestly hadn't given the Windows Phone too much thought until the "Mango" release, when things got really interesting.

So, last week I sat down and decided to see how quickly I could come up with an app, write it, market it (make a website) and get it in the Windows Phone Marketplace. I had never done any of this stuff and my machine didn't even have any Phone development tools so I was starting from literally Step, ahem, Zero.

The Concept

I am consistently surprised at at how often someone shows me their fancy new phone - no matter what kind of phone they have - and they're using some lame default wallpaper. Folks rarely lock their phones (bad idea) and when they do, there's nothing on the lock screen wallpaper to help them get their phone back if it's ever lost.

"But Scott! I can enable this new fangled GPS and track my phone globally!"

Really? That's lovely and I'm sure ever se helpful when your phone is left in a basement pub, office building, subway or any other GPS-friendly locations. But that's not the point. Why make it hard? If your email or alternate phone number was on your lock screen - maybe even with a reward - chances are you'll get your phone back quickly and easily. Why do I say that? Because I've lost my phone twice before and had a dude call me to pick it up twice before.

I'll make an application that stamps your contact information on custom wallpaper for the Windows Phone 7. My requirements are:

  • Must create lock screen wallpapers that match the Phone's style.
    • The resulting wallpapers must look like a built-in feature
  • Must look actually designed. Correct fonts, alignment, layout.
    • No garish VB3-on-a-phone-green-background-purple-buttons for me.

Cool. I will call it LostPhoneScreen and I pay $8 for the domain. Then I get to work.

Step 0 - Get the Tools

First I go and download the Phone Development Tools. They are free to download, which is cool. To publish an app costs $99 a year though, but I don't have to pay until I decide to publish the app. I can publish up to 100 apps for that $99 and unlimited apps if I pay per app.

If I pay (which I did) I make an account at http://create.msdn.com and put in my bank account information  for when the checks come rolling in.

OK, the Windows Phone SDK is installed so I start looking around for best practices. A development environment is only as good as its community and I don't want to write a bunch of stuff myself if someone has already done the work for me.

Step 1 - Get the Essential Open Source Libraries

My app  has some requirements and some specific technical requirements. I pick these ones because I'm always irritated when apps don't do these things.

  • Must support Mango multi-tasking/quick-resuming
  • Must look nice and layout like a built-in app
  • Must notify (email?) me if a crash happens
  • Must work with light and dark theme
  • Must have a nice About Screen with release notes
  • Must have a nice website to promote that app

I started with these requirements and found these open source libraries and projects to support each requirement.These things are so important that the should have been included in the Phone SDK by default.

LittleWatson

You know when a Windows app crashes and a crash report is sent? That's done by a system called Dr. Watson. Andy Pennell made a small Error Reporting library for Windows Phone 7 called "Little Watson" that was then extended by Bjorn Kuiper and packaged into Bjorn's excellent Northern Light's WP7 Toolkit. His toolkit includes a bunch of little conveniences for serialization, logging and error handling.

It was extremely important to me as a first time app developer (and frankly, it's just important) to get notifications of crashes. I could setup a web service to catch them via HTTP but for the first version, I'll notify the user and email the call stack to me using Little Watson.

MetroGridHelper

Edit screen with transparant grid behind itI found out very quickly when doing resource on phone apps that coding is only maybe 30% of the work. The rest is design. Then layout, then more design. Even for a "trivial" app.

I'm not a designer, but I can follow the basic "Metro design guide for developers" and I see over and over that alignment is king. You know those apps where you look at them and know something's wrong? But you can't see what? Turns out it's usually font size, layout or alignment just poking at the back of your brain.

Jeff Wilcox create a useful debugging assistant that you can just drop into your application with NuGet that will make a set of red squares that are offset 12px from each other with in a page padding of 24px. As you start doing Windows Phone work you'll find that 12px is a magic number and everything looks "right" if it aligns on these boundaries.

I just need to

Install-Package MetroGridHelper

We'll also turn on the FrameRateCounter and only do these things if we are actively debugging.

// Show graphics profiling information while debugging.
if (System.Diagnostics.Debugger.IsAttached)
{
    // Display the current frame rate counters.
    Application.Current.Host.Settings.EnableFrameRateCounter = true;
 
    // Display the metro grid helper.
    MetroGridHelper.IsVisible = true;
...
}

This is so useful it should just be there by default. You'll hear me say that a lot.

SilverlightToolkit

The Silverlight Toolkit from Microsoft is up on CodePlex and also easily installed with NuGet.

Install-Package SilverlightToolkitWP

It include a pile of useful controls like DateTimePicker, LongListSelector, ProgressBar (the one I was interested in), Transitions (another that I wanted), and lots, lots more. These should be in the box. They are utterly essential.

TombstoneHelper

Tombstoning is what happens when you app gets navigated away from then navigated back to. It's how you make your app feel like it's been in the background the whole time the user was switching around, even though you were dead and then came back to life.

Install-Package WP7TombstoneHelper

There's a number of ways to save your apps state, but the I found the WP7 Tombstone Helper useful as it will automatically look at your controls and save their state away then put you right back when you're launched again. It isn't right for every scenario, but it was useful to me.

protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
{
this.SaveState(e);
}

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
this.RestoreState();
}

YourLastAboutDialog

If you're not careful, your About dialog can get more complex than your application. I don't want that, but I do like me a tidy About Dialog. I found YLAD - Your Last About Dialog to be the best option for me. It's a single DLL that gives you a generic but highly configurable about dialog. How configurable you ask?

Look how nice that is!

My lovely about box made with YLADMy lovely history box made with YLADMy lovely credits box made with YLAD

It's entirely managed by a single data.xml file that's totally self explanatory. I especially appreciate apps with clear listings of what's changed between versions. Not enough apps do that, probably because it's hard. But no more! Use YLAD.

Windows Phone Power Tools

Often you'll want to pull files off your emulator or actual phone directly. Since my app is going to serialize settings, make photos, and the like, I'll want to access the file system directly. The Windows Phone Power Tools were essential for accessing my application's Isolated Storage files. It was useful to simulate upgrades from one version to another and to debug serialization bugs.

Windows Phone Power Tools

Another one to watch is IsoStoreSpy that lets you preview files in the app itself.

PNGOut and PNGGauntlet

You will find yourself making a LOT of PNGs when you are doing mobile development. You'll almost always want to compress them before you ship. I squish the PNGs on my blog and often get compression improvements of 30% or more. I squished all the PNGs in my app to make the resulting XAP deployment file smaller, and the PNGs smaller on the phone itself.

I highly recommend PNGGauntlet with PNGOut. No quality is lost as PNG is a lossless image format. It's also worth pointing out that I lived in Paint.NET while making this application. It's an all around great app and the best way to work with all these PNGs.

Portable Library Tools

If you're going to want to create and use some assemblies between projects, the Portable Class Library project template for Visual Studio can make it a lot easier to share code.

Screenshots.cs

It's pretty hard to take a screenshot on a Windows Phone. On an iPhone there is a special button combination, but nothing like that exists on a Windows Phone. However, application developers have to take screenshots and submit screenshots all day long. Enter "screenshots.cs" from the crazy-useful Jeff Wilcox.

install-package ScreenShots.cs

When it's running (you don't want leave it running, just have it going when you need screenshots) it will take a screenshot programmatically every 2 seconds. If you leave it running it'll fill up your phone.  ;)

NotifyPropertyWeaver

When making ViewModels for Windows Phone, you'll always end up taking a nice clean class with some properties and end up littering the properties with code like:

string givenNames;
public string GivenNames
{
get { return givenNames; }
set
{
if (value != givenNames)
{
givenNames = value;
OnPropertyChanged("GivenNames");
OnPropertyChanged("FullName");
}
}
}
And this stresses me out. I don't want to see those OnPropertyChanged and watch my simple class full up with notification boilerplate that I don't need to see. Fortunately Simon Cropp agrees with me and created NotifyPropertyWeaver to add this code post-compilation via IL Weaving without the need for attributes, base classes or even a class reference! It's in NuGet:
install-package notifyPropertyWeaver

Or, even easier, from the Visual Studio Gallery. NotifyPropertyWeaver adds this MSBuild task automatically in your csproj:

<UsingTask TaskName="NotifyPropertyWeaverMsBuildTask.WeavingTask"
AssemblyFile="$(SolutionDir)Tools\NotifyPropertyWeaverMsBuildTask.dll" />
<Target Name="AfterCompile">
<NotifyPropertyWeaverMsBuildTask.WeavingTask/>
</Target>

I realize this whole idea is scary, but I can tell you that I added it and didn't think about INotifyPropertyChanged once in the development of my application. You just add properties and he'll take care of the OnPropertyChanged stuff. If you don't believe him (I didn't) then just open your DLL in Reflector and see for yourself.

My ViewModel class is super basic and I only had to implement INotifyPropertyChanged and the weaver did everything else automatically. Very cool and saved me a bunch of hassle. The details are up on the Google Code site for NotifyPropertyWeaver. I found it a very elegant solution to a potentially messy problem.

Coding4Fun Windows Phone Toolkit

No, the Windows Phone 7 Toolkit isn't enough. Clint and the guys over at Coding4Fun have created a toolkit of their own that adds even more awesomeness (that should have been baked into the thing from the start). Things like Color Pickers, Color Sliders, lots of different buttons and more.

Coding4Fun Windows Phone Toolkit

Drink in the awesome over at http://coding4fun.codeplex.com.

Windows Phone 7 Emulator Skin Switcher

OK, this one isn't essential but it's totally cool eye candy. Why not change your phone skin with the Windows Phone 7 Emulator Skin Switcher? Live a little. The default one that comes with the emulator is a little meh.

When you run it, be SURE to scroll to the right as there are LOTS to choose from.

WP7 Emulator Skin Switcher

It's a nice touch.

Lost Phone Screen inside a Nokia Lumia

There's a great list of other tools, libraries and tips over at Bil Simser's The Big Dummies Guide for Windows Phone Developer Resources. Bil helped me over Skype when I had dumb questions. I'm glad he called his guide the "Big Dummie's Guide" and not the Hanselman Guide because that'd make it too obvious that I was clueless when I called. Thanks, Bil!

All right. I've got the tools and I've got my idea. Now what?

Write The Application

I know C# as I'm an ASP.NET Web programmer, but I'm not a XAML guy. The last thing I wrote in XAML was BabySmash and let's just say it wasn't rocket science. I started by dragging stuff around on the visual designer, pulling in buttons, text boxes and stuff but the XAML source started getting really messy with absolute pixel values and stuff I didn't like looking at. I stared at it for a while and just decided to write the XAML manually via trial and error, convinced that the the simpler the XAML was that more likely my app was laid out correctly. This turned out to be pretty true. I made a home page and an edit page.

Visual Studio and LostPhoneScreen

I got the two pages laid out and focused on making sure everything line up on the 12's (remember the MetroGridHelper I mentioned above) and tried to "intuit" when things looked wrong. I also referred to the "Metro design guide for developers" a lot.

Adding Polish

One thing I couldn't get my head around was that the transition between the main screen and the edit screen seemed jarring. It was like "poof." Then I realized there was no animation. Windows Phone apps usually use short but subtle animations to move between screens. Not just any old animations, but ones that involve direction to indicate moving forward or backward.

I remembered the Windows Phone 7 Toolkit above had transitions, so I applied them. The XAML is scary, but I only had to copy/paste. I made a NavigationIn and a NavigationOut for both pages so that they flip cleanly between each other.

Nice Windows Phone Flip Animation

I changed the PhoneApplicationFrame in App.xaml.cs to a TransitionFrame and the rest was magic. It just worked. Nice.

private void InitializePhoneApplication()
{
if (phoneApplicationInitialized)
return;

//RootFrame = new PhoneApplicationFrame();
RootFrame = new TransitionFrame();

RootFrame.Navigated += CompleteInitializePhoneApplication;

// Handle navigation failures
RootFrame.NavigationFailed += RootFrame_NavigationFailed;

// Ensure we don't initialize again
phoneApplicationInitialized = true;
}

Once this was done, if I needed to add other animations, it would be trivial. This small change made the app feel more polished.

Resources (Yes, more PNGs)

I needed buttons for the ApplicationBar at the bottom but I'm not a designer. I talked to Jin Yang (a designer) to do the main icon:

This sad, tiny phone is lost and on the back of a milk carton. Won't you help him find a home?

ASIDE: If you don't understand this icon, it's because it's apparently not universal. In the US when a child was missing in the 80's and 90's they would put their picture on the back of a milk carton. The idea was that you'd be eating your cereal in the morning and you'd notice the picture and it would seep into you brain so you'd be on the alert for that child during the day. Maybe a "missing" flyer with this phone would be more culturally non-specific.

But I didn't need a full-blown expert for the standard black and white icons at the bottom. The Windows Phone SDK comes with 32 basic icons for things like download, save, stop, play, etc. Even better though are the icons at Templarian. These are hundreds of yummy icons for Windows Phone (and other phones) that are released under the Creative Commons license. The designers name is Austin Andrews and he's super talented. I mean, even when he's just drafting ideas he's awesome. If you use his icons, thank him and tell people. If you are a designer, why not join up and improve the pack for the community?

UPDATE: The 130 icons from WindowsWiki.info are also amazing and high quality. Another great place for icon inspiration is The Noun Project.

My app was so simple that I ended up only using just four of the icons that came with the SDK, but I'm going to exploit the Templarian Windows Phone Icon pack whenever I can in the future.

Interesting Gotchas (actually Got-mes)

The first time I submitted the app it was rejected within two days. Turns out that when you popup a Popup - like for my Save Button - the hardware Back button must dismiss the popup. They are really serious about this model that you move forward and the hardware Back button always moves "back."

I ended up having to close my popup like this:

protected override void OnBackKeyPress(CancelEventArgs e)
{
if (theHelpPopup != null && theHelpPopup.IsOpen == true)
{
theHelpPopup.IsOpen = false;
e.Cancel = true;
}
}

As I continue to explore Windows Phone Development I'm sure I'll find better (read: less hacky) ways to manage things like this. Frankly, I was surprised that the Popup class didn't handle this for me!

Test with Light Theme

Another important thing is to test your app with a light theme. I initially had colors with hard-coded opacity like "CC00000000" for a transparent black. However, when your theme is white-based, rather than black, things start look like crap when you hard code colors. Instead they recommend that you use StaticResources with names that will automatically look correct, regardless of theme:

<Grid Height="448" Width="480" x:Name="LayoutRoot" 
Background="{StaticResource PhoneBackgroundBrush}"
Opacity="0.8">
...

Here I'm using PhoneBackgroundBrush, which means my help Popup looks nice twice!

Lost Phone Screen with Two Themes

However, notice that the black text at the top is hard to read? More on that later. A feature to help with that will be in the next version, which should be out later this week!

Submit the Application

You log into http://create.msdn.com and go through a detailed but largely straightforward wizard. There's a long checklist but the one I spent the most time going over was the Application Artwork for Windows Phone section. You need two different icons for the phone, three different icons for the Marketplace and a panorama in case you are a Featured App. Remember earlier when I said it was less code and more PNGs? This is where the time was taken up; just making sure all the PNGs were perfect from a large source PNG.

After you submit, you wait. I waited 3 days, was rejected, fixed the Back Button issue and Submitted Again.

windowsphoenstep2

Now I've found a few more bugs and will submit an update this week. The cycle will continue.

Attention to Detail

There's so many little things from misspellings to missed pixels that you need to be on the lookout for. For example, I misspelled "wallpaper" in a screenshot - seriously - because I was working late into the night. Sloppy. And now I'll have to wait almost a week to fix it due to the way the Marketplace works. As a web programmer this will take getting used to as I'm used to "hit refresh, it's fixed" when squashing bugs for my users

Triple check everything, test and test again. Every small mistake means 3 days lost waiting for the marketplace to update. And those days can mean days of unhappy users.

Make the "Marketing" Website

Time to make myself a nice simple static website to promote my application. I could hire someone or try to make something myself, but I really just have some basic requirements.

  • The site should include screenshots
  • The site should be mostly static html but feel slightly dynamic (javascript?)
  • The site should work on a mobile device (even iPhones!) using responsive design.
  • The site should link to the Windows Phone Marketplace

I didn't want to spend much time on this, but I also didn't want to do my app a disservice with a crappy site. There are lots of mobile templates out there, but a few stand out as they are Windows Phone 7 Specific.

One is Wp7JekyllTemplates, which works nice if you are hosting your code and site on GitHub. The other is Wp7AppSite by Nick Harewood. I noticed that Wp7AppSite used the Skeleton Boilerplate, which I am a fan of. I used it on http://speakinghacks.com.  It looks great on mobile so I was sold.

It was stupid-easy to setup. I just pointed my domain my my host, setup index.html as the default document, resized the screenshots, modified the HTML and uploaded. Took about 10 minutes.

Pricing

I made it $0.99. I didn't want to make it free because I didn't want to make it free. It costs less than the foam on your latte and it will get nice updates for free. I find it funny that folks will research 99 cent apps for an hour while sipping a $5 latte. ;)

I buy lots of $1 apps because THEY ARE $1 APPS.

Find a Bug

Earlier I mentioned that some wallpapers make it so the text is hard to read depending on the theme. Tim Heuer reported this so I added a feature to invert the text color, as seen in the screenshot below:

Inverted Text in Lost Phone Screen

Notice how the A at the bottom in the Application Bar inverts depending on the color of the text. I am very happy with how that turned out.

Submit the Update

I also removed the progress bar as it was getting in the way of the screenshot process and fixed a data persistence bug where your settings don't always get saved depending on how you exit the application. This is due to my confusion about how task switching vs. application existing works in Mango. That's fixed and will be out as as a free update soon as they certify it.

I'll submit the 1.0.2 update this week that will include the smarter text coloring as seen in the screenshot above. Barring rejection, the Marketplace should notice you'll get the updates!

You can get Lost Phone Screen on the Windows Phone Marketplace and you can offer feedback and feature request on UserVoice. If you buy it, please review it on the marketplace from the About Screen.

UPDATE: Reviews

Bad Reviews hurt, even for a silly little application like mine. I've already released the 1.0.2 update with bug fixes that address many major issues folks have had with the app. Here's what you should do to keep on top of feedback and reviews:

I'll update this post with more info as I learn more. I haven't got download stats yet and I've only just released my first update.

Conclusion

I was pleasantly surprised how easy it was to get into Windows Phone 7 programming. I was also thrilled with the amount of great open source libraries, creative commons art and other resources that are available for the beginner. The marketplace process and website are still a little confusing and rough, and I don't like waiting days to find out how my app is doing, but I guess that's life with a marketplace.

Big thanks to Jin Yang for the Icon and Bil Simser for Skyping with me.

I'll keep updating my little app and trying to think of ideas for my Next App.

Enjoy!

Related Links

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. I am a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by ORCS Web

Hanselminutes Podcast 269 - Community vs. Evangelism vs. Marketing vs. Authenticity with Brandon Watson from Windows Phone

June 14, '11 Comments [3] Posted in Podcast | WinPhone
Sponsored By

Windows Phone 7 from HTCScott sits down with Brandon Watson, a Director on Windows Phone. He works with the Developer Community, but what does that really mean? What is Community vs. Evangelism vs. Marketing vs. Authenticity? Scott pushes on this point to better understand his own job at Microsoft

Download: MP3 Full Show

NOTE: If you want to download our complete archives as a feed - that's all 269 shows, please subscribe to the Complete MP3 Feed here.

Also, please do take a moment and review the show on iTunes.

Subscribe: Subscribe to Hanselminutes or Subscribe to my Podcast in iTunes or Zune

Do also remember the complete archives are always up and they have PDF Transcripts, a little known feature that show up a few weeks after each show.

Telerik is our sponsor for this show.

Building quality software is never easy. It requires skills and imagination. We cannot promise to improve your skills, but when it comes to User Interface and developer tools, we can provide the building blocks to take your application a step closer to your imagination. Explore the leading UI suites for ASP.NET AJAX,MVC,Silverlight, Windows Forms and WPF. Enjoy developer tools like .NET Reporting, ORM, Automated Testing Tools, Agile Project Management Tools, and Content Management Solution. And now you can increase your productivity with JustCode, Telerik’s new productivity tool for code analysis and refactoring. Visit www.telerik.com.

As I've said before this show comes to you with the audio expertise and stewardship of Carl Franklin. The name comes from Travis Illig, but the goal of the show is simple. Avoid wasting the listener's time. (and make the commute less boring)

Enjoy. Who knows what'll happen in the next show?

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. I am a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by ORCS Web
Page 1 of 3 in the WinPhone category Next Page

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.