Skip to content

Windows Phone 7 - What I’ve Learnt So Far

Windows Phone 7 Series - InicioI’ve been launching headlong into Windows Phone 7 development as can be seen from my previous post and I’ve come across some little tit bits I thought I’d post up here.

Jump Start Training

I can’t begin to say how helpful the jump start training courses have been.

So far I’ve done the introduction, building silverlight 1 & 2, and advanced applications 1 & 2. Some of the stuff I already knew from other blog posts (like the application lifecycle stuff) but I’ve learnt quite a few new things.

Windows Phone Developer Blog: Windows Phone 7 Jump Start Training

Getting Focus and Active Control

In old school WinForms there is a property of a form called ActiveControl which returns the control which is currently active. This property doesn’t exist in Silverlight. Instead you need to use the FocusManager static class and its GetFocusedElement static method.

object obj = FocusManager.GetFocusedElement();

if (obj != null && obj is TextBox)

{

TextBox txt = obj as TextBox;

txt.Text = "Has Focus";

}

Beta Tools Warning

In the current beta tools Control.Focus() does not correctly transfer focus to the control.

DataBinding and the ApplicationBar

I really like the way the application bar works to make a Windows Phone 7 application look, well, like a Windows Phone 7 application.

However as has been noted elsewhere the ApplicationBar is not a Silverlight control in the normal sense. This means that you cannot use data binding when setting it up, you can’t use Command’s to hook up events and various other little tit bits.

Here are two links to MSDN documentation about the ApplicationBar.

How to: Add an Application Bar to Your Application for Windows Phone

Application Bar Best Practices for Windows Phone

The fact the application bar does not appear on the Silverlight visual tree results in two other issues. Firstly, setting a x:Name property on your buttons and menu items does not work. The fields in your code will always be null. You have to use the ApplicationBar.Buttons and ApplicationBar.MenuItems arrays to get access to the buttons and menu items.

Secondly, if you set up your controls with data binding on the form then click on an application bar button the data binding for the control with the focus is not updated. These two issue are discussed on Laurent Bugnion’s blog here: Two small issues with Windows Phone 7 ApplicationBar buttons (and workaround).

Using the above code for determining the current focus control I came up with an elegant solution when you have more than one text box like so:

object focusObj = FocusManager.GetFocusedElement();
if (focusObj != null && focusObj is TextBox)
{
var binding = (focusObj as TextBox).GetBindingExpression(TextBox.TextProperty);
binding.UpdateSource();
}

So far I have only tested this with the TextBox.Text property. CheckBox’s don’t seem to have this issue. Other controls like list boxes might also need to be taken into account.

It should also be noted that in the final release an alternative solution would be to simply move the focus to another control, or to the page itself (IsTabStop must be set to true for the Focus() method to work on the page) to get the data binding to update.

Flickr (and OAuth) authentication

Finally a word on Flickr (and by extension OAuth) authentication.

The usual process for desktop app authentication for Flickr is that you request a temporary value from Flickr (called the ‘frob’), then redirect to the Flickr web site where the authentication is processed. Then when you return to the application you use that frob to get the authentication token.

At first I tried to use the WebBrowserTask to kick off the authentication process in much this manner. This works fine except for one thing. The only way to get back to your application is to repeatedly hit the back button to come all the way through the IE history to exit IE and return to your app. The authentication process is at possibly 4 pages (Yahoo login, Authentication warning, Authentication approval and Authentication Complete pages) and there is nothing to stop the user continuing to use the web browser after they have authenticated to continue browsing the internet, so this didn’t seem like a good way.

Then I tried using the WebBrowser control. This works, but I couldn’t find any way to tell if the user had finished authenticating.

I was OK with this, but wanted to improve the experience. I finally came across this post discussing OAuth (which follows the same kind of flow as Flickr) for Windows Phone 7: http://blog.markarteaga.com/OAuthWithSilverlightForWindowsPhone7.aspx.

To accomplish this you change your Flickr authentication to be web based, rather than desktop based. In this scenarios once the authentication is completed you get redirected to a callback URL you specify. You need to create a simple HTML page that can be redirected to that then calls window.external.Notify() method in javascript. The string value passed in to this page is then passed to the WebBrowser.ScriptNotify event where you can extract the frob from the URL, and complete the authentication.

I think this gives a much cleaner UI and I shall be implementing it in the near future.

Other useful Links

Me on Twitter: http://twitter.com/samjudson

The # wp7dev tag on Twitter: http://twitter.com/#search?q=%23wp7dev

Daily ‘twitter’ newspaper: http://paper.li/tag/wp7dev

Windows Phone 7 Developer Blog: http://windowsteamblog.com/Windows_Phone/b/wpdev/

Windows Phone 7 Developer site: http://developer.windowsphone.com/

Update: Tombstoned Apps may not be reactivated

I forgot to mention - if the user starts a new version of your application then any tombstoned version will be removed from the back stack. e.g. If they go Start Button –> Your App  –> Start Button –> Your App then pressing the back button will exite your application and take them to the Start screen, and pressing it again will do nothing – no second instance of your app will be reactivated.

This does mean however that if your app is loading, you can clear down any existing data that may be hanging around from tombstoned apps.

Tagged , ,

Flickr Uploader for Windows Phone 7

I’ve put together a basic photo uploader for the new Windows Phone 7. This was a good exercise for me as I had to a) make sure that the Flickr.Net library worked correctly in Windows Phone 7, and b) finally learn Silverlight, at least the basics anyway.

Well I had great fun, and I’m finally ready to share. You can download the files below.

Things I Learnt

There are a few things I learnt while doing this about the way to make great Windows Phone 7 apps, so I thought I would share.

Custom Navigation

One thing that was an interesting challenge was trying to make the authentication process work easily. Basically there are 3 pages to the app – the photo chooser, the authentication page, and the upload page.

If you have already authenticated then it skips the authentication page.

If you authenticate and then go to the upload page I didn’t want to back button to bring you back to the authenticate page again, I wanted to skip it. This is with the following code:

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
    if (!String.IsNullOrEmpty(SettingsHelper.AuthenticationToken) && NavigationContext.QueryString.Count == 0)
    {
        if (NavigationService.CanGoBack)
            NavigationService.GoBack();
    }

    base.OnNavigatedTo(e);
}

Basically if you have already stored the authentication token then continue to move back if you can. I added in a check on the querystring in case you ever wanted to ‘redo’ authentication (this hasn’t been implemented yet).

Download Files

Here are the source files and the XAP file to download:

Tagged ,

Flickr.Net for Silverlight/Windows Phone 7

Just a quick note to say I’ve released the first version of the Flickr.Net library to support Silverlight (3.0 and 4.0) and the new Windows Phone 7 SDK.

The release can be downloaded from flickrnet.codeplex.com - use the FlickrNetSilverlight.dll file in the binary download.

The new asynchronous methods added for silverlight (as all network traffic is async in silverlight) are also included in the existing Flickr.Net API for .Net 2.0+

Examples and documentation to come in the near future.

Let me know if you have any feedback.

Tagged , , , ,

Silverlight and Monotouch with Flickr.Net

The Flickr.Net library has been getting a bit of love recently.

Monotouch

Firstly, it got mentioned on the dotnetrocks podcast a week or so ago, a talk with Chris Hardy about Monotouch.

Postcast: http://www.dotnetrocks.com/default.aspx?showNum=568 - Flickr.Net is mentioned about 31minutes in. You can also view Chris’s talk at the NDC conference here: http://streaming.ndc2010.no/tcs/?id=815EADB7-066D-4516-A70F-31EEFDFB1DE2 - he does a demo using the Flickr.Net library in Monotouch at about the 40minutes mark.

Follow chris on twitter here: http://twitter.com/chrisntr

Silverlight

Recently I’ve been trying to work out how best to convert the Flickr.Net library over to Silverlight. Unfortunately it’s not as easy as it sounds, because most of the methods the library uses to talk to Flickr are only available in their asynchronous versions in Silverlight, which means the entire stack has to be converted to an asynchronous pattern.

Anyway, I’m almost there in terms of deciding on a method to use (maybe that is worth another post later) but in the mean time there is a post on the Silverlight Show web site about using Silverlight and Flickr which I’m using as my inspiration - the sooner the article is out of date the better :)

http://www.silverlightshow.net/items/Uploading-and-geo-tagging-photos-on-Flickr-using-Silverlight-4-s-HttpWebRequest.aspx

Tagged , , , ,

Missing drive when using Remote Desktop

Usually when you remote desktop to another machine you can turn on automatic mapping of your local drives to drives on the server - for example you local C: drive is available at \tsclient\c

However recently I have been experiencing a problem where I wasn’t seeing the C: drive, but only when I logged onto the remote server as a particular user. Other drives were avaialble but they where network drives I didn’t have permission to write files to this was a bit of a problem transferring files.

Luckily I found the solution in this Microsoft Knowledge Base article: http://support.microsoft.com/?kbid=940458

Turning on Smart Card detection fixed the problem. Hurray.

Tagged , , ,

Flickr Stats

Thought this might interest some people.

The Flickr Stats app on Flickr takes your archive of Flickr Stats (downloadable till the 1st June for Pro users) and generates some lovely graphs. http://www.flickr.com/services/apps/72157623630152423/

Well here is my graph:

http://flickr.vispillo.org/output/1273826937593.html

And what is one of the most popular search terms for finding my photos? Yes, guinea pigs. Great!

Tagged ,

Flickr.Net API Library 3.0 Release

I’ve just released a brand spanking new version of the Flickr.Net API library.

The big things to note are that this version has over 150 unit tests to make sure it is working correctly. It also covers 100% of the Flickr API methods (there is a unit test that ensures this).

I’ve also sent some considerable time running Microsoft Code Analysis against the library to try to ensure that it meets most of the Microsoft guidelines on library design. This has resulted in some quite wide ranging changes, most noticeably to many of the class names in the Library. Most of these changes could have been avoided but I felt that it was better to get the library in a consistent and easy to understand position going forward than try to maintain a large segment of code just for backward compatibility reasons.

The main reason for the change was actually to do with a little Flickr method called flickr.photos.getFavorites. Previously the library had used XML serialization and the serialization attributes to handle converting the returned XML from Flickr into .Net object. However there was a huge clash between the flickr.photos.getInfo method, which returned a root element of <photo> and sub elements containing different bits of information about that photo and the flickr.photos.getFavourites method which also returned a root element of <photo> and sub elements of <person> which were the people who had favourited that photo.

One solution to this was to add a PersonCollection property to the PhotoInfo class, but this I felt would just add to the already growing confusion in other areas, such as when returning a list of Photosets the Photoset.PhotoCollection property would always be null – this is because PhotosetsGetList does not return any photos, but the Photoset class is used in more than one place so had to handle all scenarios.

So instead I had to develop a method of overriding the XML deserialization. I chose to do this by a combination of a custom Interface (IFlickrParsable) and the use of generics to handle the processing of the responses.

Changes

So, now instead of PhotosetsGetList returning a Photosets class, it returns a PhotosetCollection class. This class is a generic collection which can be iterated over using foreach etc. It no longer has a PhotoCollection property. Instead the PhotosetsGetPhoto method now returns a PhotosetPhotoCollection which is a collection of Photo class instances as you would expect.

string ApiKey = "ABCDEFG";

string UserId = "";

Flickr f = new Flickr(ApiKey);

PhotosetCollection photosets = f.PhotosetsGetList(UserId);

foreach(Photoset photoset in photosets)

{

    PhotosetPhotoCollection photos = f.PhotosetsGetPhotos(photoset.PhotosetId);

    // Do something with all the photos here.

}

Likewise there are a large number of other changes – most noticeably that the Photos class is now called the PhotoCollection class.

Beta

Due to the large number of breaking changes I’ve labelled this version a beta until such time as I have had chance to actually use it myself. I’m already underway moving my Flickr screensaver over to this library, and its improved support for the Flickr methods has saved a huge number of method calls in that already, so I’m hopeful this is only a good move.

Download the latest version of the Flickr.Net API Library from here: http://flickrnet.codeplex.com/

You can also report bugs and ask questions over there too.

Peaceful Night

Last monday our Virgin Media connection went down. We lost our TV and
the internet (but phone was still working, somehow).

Now you might think - bloody disgusting, but I’m actually thankful.
Instead of sitting, face glued to a screen (TV or monitor) I put some
music on (Sign No More by Mumford and Sons for those interested) and
sat and read a book. Then I went to bed early and had a great nights
sleep.

I think I needed that.

Posted via email from Sam’s Random Junk!

Resistance is Futile

A picture says a thousand words…

New word: geotagginess

A new method pas been added to the Flickr API for specifying an ‘essence’ of a geotagged photo, such as ‘Indoors’ or ‘Outside’ (these are the only two currently supported values).

The funny bit however is that the documentation page contains the word ‘geotagginess’ which I think is a great word!

Flickr Services: Flickr API: flickr.photos.geo.setContext

Tagged ,

Space Cowboy

Space Cowboy
Space Cowboy, originally uploaded by Sam Judson.

The 6th photo on the 6th page of my Flickr photostream:

[via]

Regex Split bug in JScript?

I’ve been messing around with JavaScript quite a bit recently and I came across a ‘bug’ in the Microsoft implementation of the split() method.

Take the following example string (note the two tabs at the end):

var s = “Hello\tHow\tare\tyou\t\t”;

and then run the following to write it out to the screen:

document.writeln(s.split(”\t”));

Well that works as expected, and outputs “Hello,How,are,you,,”;

But if you replace the string in the split method with an inline Regex object it fails if run under a Microsoft implementation

document.writeln(s.split(/\t/));

This outputs the same as above in Firefox etc, but if run in JScript (i.e. Internet Explorer) you lose all empty elements and get the following: “Hello,How,are,you”. This is really weird, because if you use the string delimiter above it works just fine.

I have managed to find another blog post that tries to fix this problem, but doesn’t say why it happens.

http://blog.stevenlevithan.com/archives/cross-browser-split

To test this online, try going to W3Schools.com.

Tagged , ,

What makes StackOverflow different…

I was asked the question recently, what makes StackOverflow different from other developer forums. (Thanks http://twitter.com/redgum)

http://www.stackoverflow.com

I’ve only been using it for a few days now, and its still in private beta, although it is claimed to be (mostly) feature complete.

There are a few obvious things that mark it as different from your usual developer forum.

  1. No forums

It doesn’t have the concept of forums, instead uses tags to provide order to the chaos. This is good, in that everything gets at least some attention when it is posted, as well as the eventual problem of things being posted to the incorrect forum never appearing.

  1. No login

Eventually you will be able to ask questions and answer them without logging in. This does sound very strange, and as the web site is still in private beta it really isn’t being tested much yet, but it certainly could make life interesting.

  1. Voting

Questions, as well as answers can be voted up and down - you require a log in and the required reputation to do either of these things. Reputation is gained from answering questions, having questions and answers voted up, and by having answers marked as ‘correct’ by the question asker. The exact formula isn’t really known.

  1. Badges and Reputation

As you answer questions and generally interact you gain reputation, and various ‘badges’. This is in common with many game web sites (such as Kongregate) where completing certain objectives gives you a particular badge. Badges are given for things like ‘First Answer marked as Correct’.

So far this is producing a very fluid and engaging experience, but I don’t think it will truly get tested till it is open to a) Spam and b) Crap questions. Hopefully the reputation/voting system will encourage the better questions, while discouraging the worst.

Will StackOverflow end up any different from all the other developer forums? They have certainly set out on the right path. Whether this path enables them to end up better than the rest is something I think is still to be seen.

Tagged ,

Reasons Twitter is a better IM client…

I'm starting to like twitter. As with most (damn the phrase) web 2.0 major sites I have an account (I'm there on all the social networks, flickr, pownce, last.fm, friendfeed etc) but I found it quite hard work to get used to the format.

Then I started trying out http://www.posterous.com which takes anything I email them (like this), throws it on a blog and then updates twitter. That and a couple of people who've sent me actual tweets (ok, that still sounds silly) and the service just comes alive.

And the reasons I prefer it over normal IM - well mainly because of the whole "who's online" thing - I hate being pinged in IM by people at random times - if maybe I just logged on to check one thing in google, or I'm trying to write some code or play a game. So what do I do, well I shut down the IM client - or even worse make sure it doesn't start at startup. And from there on in it becomes pointless.

With Twitter there is no concept of being online - you just post anytime you want - and read others posts anytime you want. You can keep track of those sent to your ears, as well as what the world is saying (I think Search was the big thing missing, but now they've got that sorted too).

And if you close your twitter client (or heaven forbid twitter is down) then that's just a while for you to get more work done :)

Posted by email from Sam’s posterous

Big Bug in Flickr Screensaver

Hi

I’ve just been informed of a fairly large bug in the uninstaller for the latest Flickr Screensaver.

Basically if you uninstall it it will try and delete your Windows\System32 directory.

Obviously that is VERY BAD. I apologise. I’ve deleted the installer from the web site, but anyone who has the latest version of the screensaver should not uninstall it.

Sam