Windows Phone 7 Beta with Windows Live Messenger Connect

Windows Phone 7 Beta with Windows Live Messenger Connect

Recent Microsoft announced a major update to their Live platform. There are a number of updates that are currently in Beta including Messenger and Live Writer but what interests me is the new development platform, Messenger Connect. Go to the Windows Live developer portal for all the details. For anyone who has worked with any of the Live Id apis in the past it was difficult to get all the information you wanted. It appears that Messenger Connect is a great rationalisation of these apis and with libraries to support both rich and web client access, getting started should be easy.

Unfortunately, and for those getting into the Windows Phone space you’ll get used to this, there is no library available for accessing the Messenger Connect apis. Of course, the team has done a great job of making all the data available via REST  but honestly, that’s like trying to write a Windows Phone app in XAML when you have the power of Blend…. not something you want to have to do.

I figured it couldn’t be that hard to take the existing library for Silverlight, decompile it thanks to Reflector, update it to work for Windows Phone and we should be good to go. No so, after quite a painful day yesterday I have got a working library that’s able to authenticate and access contacts and activities (haven’t tested the other functionality yet). Unfortunately this meant not only reverse engineering the Microsoft.Live.dll but also the odata sdk library for Windows Phone (as they haven’t made the source available). Anyhow, enough complaining about the lack of source code publishing by Microsoft (please, please, please Microsoft, stop closed-sourcing these sdk libraries – all it does is frustrate us!).

So the SDK library is relatively easy to use:

– Start by adding a reference to the Microsoft.Live and System.Data.Services.Client (the one in the attached zip file, not the odata sdk version).

– Next, you’ll need a WebBrowser control on the page that you’re going to do the authentication on – this is used to display the Messenger Connect sign in prompt. The SDK library for Silverlight uses a ChildWindow but this isn’t available for Windows Phone so I’ve hacked around this for the moment. I’m sure there’s a better solution for this so feel free to modify it

– Add a button and some code to authenticate the user:

const string ClientId = "***Your-Client-ID***";
const string ClientSecret = "***Your-Secret-Key***";

LiveDataContext dataContext = new LiveDataContext();
AppInformation appInfo;

private void SignInButton_Click(object sender, RoutedEventArgs e)
{
    SignInButton.IsEnabled = false;

    try
    {
        appInfo = new AppInformation(ClientId, ClientSecret);
        appInfo.RequestedOffers.Add(new Offer()
        {
            Name = "WL_Contacts",
            Action="View"
        });
        appInfo.RequestedOffers.Add(new Offer()
        {
            Name = "WL_Activities",
            Action = "View"
        });
        appInfo.RequestedOffers.Add(new Offer()
        {
            Name = "WL_Photos",
            Action = "View"
        });
                
        this.dataContext.SignInAsync(this.SignInBrowser, appInfo, null);
    }
    catch (Exception ex)
    {
        ShowErrorDialog("Failed to sign in to Windows Live: {0}", ex.Message);
        SignInButton.IsEnabled = true;
    }
}

private void SignInCompleted(object sender, SignInCompletedEventArgs e)
{
    if (!e.Succeeded)
    {
        string authError = (e.AuthInfo.Error == null) ? string.Empty : e.AuthInfo.Error.Message;
        ShowErrorDialog("Failed to sign in to Windows Live! {0}", authError);
        SignInButton.IsEnabled = true;
    }
    else
    {
        MessageBox.Show("Welcome To Windows Live!", "Windows Live", MessageBoxButton.OK);
        this.Contacts.Visibility = System.Windows.Visibility.Visible;
    }
}

private static void ShowErrorDialog(string errMsg, params string[] paras)
{
    MessageBox.Show(string.Format(errMsg, paras), "Windows Live", MessageBoxButton.OK);
}

Essentially the process goes like this:

– the user clicks the SignInButton

– the WebBrowser control is displayed and navigates to the Messenger Connect sign in page

– the user signs in and grants appropriate privileges

– after sign in the WebBrowser is automatically hidden and the SignInCompleted event is raised

In action:

image

In the code to sign in you will have noticed that there are three Offers that have been requested. These correlate to the scopes of information that the user is going to grant this application. In this case View privileges to Contacts, Photos and Activities. To retrieve these sets of information we can kick of an odata service call.

private void FetchContactsButton_Click(object sender, System.Windows.RoutedEventArgs e)
{
    var qry= dataContext.ContactsQuery;
    qry.BeginExecute(Response, qry);
}
void Response(IAsyncResult result)
{
    var qry = result.AsyncState as DataServiceQuery<Contact>;
    var contacts = qry.EndExecute(result);
    this.Dispatcher.BeginInvoke(() =>
    {
        this.InformationList.Items.Clear();
        foreach (Contact c in contacts)
        {
            this.InformationList.Items.Add(c.ToString());
        }
    });
}

private void FetchActivitiesButton_Click(object sender, RoutedEventArgs e)
{
    var qry = dataContext.MyActivitiesQuery;
    qry.BeginExecute(ActivitiesResponse, qry);
}

void ActivitiesResponse(IAsyncResult result)
{
    var qry = result.AsyncState as DataServiceQuery<Activity>;
    var contacts = qry.EndExecute(result);
    this.Dispatcher.BeginInvoke(() =>
    {
        this.InformationList.Items.Clear();
        foreach (Activity c in contacts)
        {
            this.InformationList.Items.Add(c.ToString());
        }
    });
}

This code illustrates retrieving the list of contacts and activities for the currently signed in user.

Hopefully this will help you build a Windows Phone application that takes advantage of the new Messenger Connect apis. Oh, before I forget, to get the sample to work you’ll need to sign up for access to the Messenger Connect apis, then register your application (use the Windows Application option). Include the ClientId and ClientSecret at the top of the MainPage.xaml.cs (first code sample above).

Messenger Connect Sample: Download Sample

Update: It’s important that you read the licensing agreements that accompany the use of the apis. Angus posted on Messenger Connect saying the following:

    1. Public APIs: Our “Public APIs” are available to all developers and third parties to access in a self-service manner. Appropriate use is governed by our Terms of Use and Terms of Service, and is monitored for abuse reported by customers. Third parties can sign-up for access through our application management tool at http://manage.dev.live.com.

How’s my Windows Phone 7 application being used? Getting started with the Microsoft Silverlight Analytics Framework for Windows Phone development

How’s my Windows Phone 7 application being used? Getting started with the Microsoft Silverlight Analytics Framework for Windows Phone development

Microsoft has just released an update to the Silverlight Analytics Framework which now includes support for Windows Phone development. This gives you a standard approach to include usage tracking within your Silverlight application that is somewhat independent of the tracking site/service you use. I say somewhat as each service requires a custom behavior to be created in order for it to be used with the framework. Luckily the major tracking services already have behaviors available for Silverlight 3 and 4.

To get started tracking usage within your Windows Phone application get the updated version of the Microsoft Silverlight Analytics Frameworkand run through the installer.

image

We’ll cover using the Console output and Google Analytics to track usage but you can use the behavior that corresponds to the tracking service you use (at the time of writing this only includes Webtrends, Google Analytics and the generic Service Oriented Analytics).

In this case we’re going to create a new Windows Phone application but there is no reason why you can’t add the event tracking to an existing application (just skip the first step of creating a new application).

image

Next, add the following references to your application:

ComponentModel
Composition.Initialization
Google.WebAnalytics (only required if you want to use Google Analytics to track events)
Microsoft.WebAnalytics
Microsoft.WebAnalytics.Behaviors
Microsoft.WebAnalytics.Navigation
System.Windows.Interactivity

image

Due to some of the limitations of the Silverlight implementation on Windows Phone there is an additional step that is required in order for the MSAF to work properly. Add a new class called AnaltyicsApplicationService to your project can update the code to look like the following:

using System.ComponentModel.Composition.Hosting;
using System.Windows;

public class AnalyticsAppplicationService : IApplicationService
{
    public void StartService(ApplicationServiceContext context)
    {
        CompositionHost.Initialize(new AssemblyCatalog(
            Application.Current.GetType().Assembly),
            new AssemblyCatalog(typeof(Microsoft.WebAnalytics.AnalyticsEvent).Assembly),
            new AssemblyCatalog(typeof(Microsoft.WebAnalytics.Behaviors.TrackAction).Assembly));
    }

    public void StopService() { }
}

Next, update your App.xaml to look like the following. If you are adding MSAF to an existing application the important part in this code snippet is the creation of the two additional ApplicationLifetimeObjects, AnalyticsApplicationService and WebAnalyticsService.

<Application 
    x_Class="MSAFSampleForWP7.App"
           
    
    
    
    
    >

    <!--Application Resources-->
    <Application.Resources>
    </Application.Resources>

    <Application.ApplicationLifetimeObjects>
        <local:AnalyticsAppplicationService/>
        <mwa:WebAnalyticsService/>
        <shell:PhoneApplicationService 
            Launching="Application_Launching" Closing="Application_Closing" 
            Activated="Application_Activated" Deactivated="Application_Deactivated"/>
    </Application.ApplicationLifetimeObjects>

</Application>

We’re going to add some behaviors to the pages of the application so let’s jump across to Expression Blend. You can easily do this by right-clicking on the Windows Phone application project and clicking the Open in Expression Blend link

image

Make sure that you rebuild the application within Blend so that the various windows are all up to date. In the Assets window, under Behaviors > Analytics, you’ll see that there are a number of different behaviors that you can drag onto your application to track events.

image

Start by dragging both the ConsoleAnalytics and GoogleAnalytics behaviors on the LayoutRoot node in the Objects and Timeline window. In this example we’re also going to track a button click event, so you’ll have to add a button to the page. Then you can drag the TrackAction behavior onto the button. This should give you the following tree in the Objects and Timeline window.

image

There are some additional properties you will need to set on the GoogleAnalytics behavior. Whilst the Category isn’t required, it’s a good idea to set it so that you can easily filter the event data by category. I’d suggest at least making the Category application specific.

image

The Web Property ID is required and needs to correspond to the ID of your Google Analytics account. When you log into Google Analytics, you can find this ID on the first page, along side the list of profiles.

image

You also need to configure properties on the TrackAction behavior. In this case the behavior is responding to the Click event of the button. We’re also going to specify both a Category and Value that will be passed through to Google Analytics (don’t include any user information that can be identified unless you’re going to be using SSL!)

image

And that’s all there is to it. Run your application up and you will see a basic page where you can go ahead and click the button. The Google Analytics event tracking will record application start up and the button click event.

image

Now you might be wondering how you’re going to view the console output. Well there are two ways: Firstly, assuming the debugger is attached you can view the console output in the Output window in Visual Studio. Alternatively, if you’re running the application on the emulator you can enable the console output window. This is done by setting the HKEY_LOCAL_MACHINESOFTWAREMicrosoftXDEEnableConsole registry key to 1 – you’ll most likely have to create this entry as it isn’t there by default.

image

With this registry key set, if you restart the emulator, you should see a command prompt window appear that lists the console output from the emulator.

image

Ok, now the last thing to do is to go back to Google Analytics and check that the events are coming through. Be warned that there can be a substantial delay between raising the events and them appearing in the Google Analytics window. To find the event tracking you have to drill into the Content > Event Tracking node on the left side of the page.

image

That’s all there is to getting started with the MSAF for Windows Phone.

________________________________________________________________________________________

Issues: At the moment the current installer doesn’t work as described above. There are a couple of issues, one relating to the binaries that are installed and the other relating to the Google Analytics implementation for WP7. The installer is also missing half the source files for the WP7 sample project

1 & 3) The first and third issues can be resolve by downloading the actual source for the MSAF. This includes all the source code for the sample project and will allow you to recompile the MSAF. Download the source from the Source Code tab of the MSAF codeplex site

2) The second issue relates to the way the code detects whether to use ssl or not for downloading the Google Analytics event tracking image. Essentially this code attempts to detect whether the uri for the current document uses ssl or not. Clearly for a WP7 app this isn’t going to work. The work around for this is to decompile the GoogleAnalytics assembly (not sure why this isn’t checked into codeplex), modify the code and recompile the source. The following link contains the Google Analytics assembly along with the working test project.

MSAF with Fixed Google Analytics Download

Windows Phone 7 beta: Debugging Tombstoned XNA Games with Visual Studio

Windows Phone 7 beta: Debugging Tombstoned XNA Games with Visual Studio

In my previous posts on Windows Phone 7 I’ve been focussing on Silverlight. You can of course build applications and games using XNA – not being that familiar with XNA it’s going to take a lot of encouragement for me to invest serious time into learning another framework but if I was building games I think it’s a technology that is worth knowing since you can build games for Windows, XBox and now Windows Phone.

One of the things that you may notice when you build and deploy your XNA game to the emulator is that it doesn’t appear in the applications list. That’s because it is installed as a game, not an application. As such it appears in the Games hub, rather than in the applications list. If you use one of the hacked emulator builds you can see this hub and use it to relaunch your application without the debugger attached if you feel like it.

Ok, so onto the topic of this post. The last couple of posts have been about how you accommodate for the Windows Phone application lifecycle model, specifically the fact that your application may (and in the case of the current emulator, will) get terminated when it goes into the background. In these posts we used the Launching, Activated and Deactivated events on the Application (wired up in the App.xaml) and we relaunched Visual Studio when necessary in order to resume the debugging experience. This is essentially the same process for XNA with some minor differences.

Firstly, there is no App.xaml file, so you have to manually wire up these events. Also, by default there is no project reference to Microsoft.Phone.dll, so you’ll have to add that too. Then in the Game1.cs file (or in my case the MyGame.cs file, since I renamed the game from Game1 to MyGame) you need to attach the necessary event handlers. Note that I’ve wrapped the event wiring and the event handlers themselves with a check for the WINDOWS_PHONE conditional compilation symbol. Remember that you can target multiple platforms with the same XNA game – each target has a different compilation symbol: WINDOWS, XBOX, and now WINDOWS_PHONE.

public MyGame()
        {
            graphics = new GraphicsDeviceManager(this);

            //Set the Windows Phone screen resolution
            graphics.PreferredBackBufferWidth = 480;
            graphics.PreferredBackBufferHeight = 800;
            graphics.IsFullScreen = true;

#if WINDOWS_PHONE
            Microsoft.Phone.Shell.PhoneApplicationService.Current.Launching += new EventHandler<Microsoft.Phone.Shell.LaunchingEventArgs>(Current_Launching);
            Microsoft.Phone.Shell.PhoneApplicationService.Current.Deactivated += new EventHandler<Microsoft.Phone.Shell.DeactivatedEventArgs>(Current_Deactivated);
            Microsoft.Phone.Shell.PhoneApplicationService.Current.Activated += new EventHandler<Microsoft.Phone.Shell.ActivatedEventArgs>(Current_Activated);
#endif
            Content.RootDirectory = "Content";

            // Frame rate is 30 fps by default for Windows Phone.
            TargetElapsedTime = TimeSpan.FromSeconds(1/30.0);
        }

#if WINDOWS_PHONE
        void Current_Launching(object sender, Microsoft.Phone.Shell.LaunchingEventArgs e)
        {

        }

        void Current_Activated(object sender, Microsoft.Phone.Shell.ActivatedEventArgs e)
        {

        }

        void Current_Deactivated(object sender, Microsoft.Phone.Shell.DeactivatedEventArgs e)
        {

        }
#endif

 

Now, the second thing that you’ll have to do is to change the build configuration to prevent Visual Studio deploying your game every time. If you don’t do this the sequence goes like this:

Run Game > Press Start  (Game terminates in background) > Press Back (blank screen displayed) > Press F5/Run in Visual Studio (this builds, deploys and attempts to run game) > Game runs as if it wasn’t tombstoned (ie Launching event raised instead of Activated)

To get the Activated event to fire you need to adjust the build configuration so that it doesn’t deploy the game every time you press F5/Run. Right-click on the solution in Solution Explorer and select Configuration Manager. Uncheck the box in the Deploy column.

image

You can still deploy your XNA game to the device, you just need to right-click on the project and select Deploy (remember to do this each time you make changes to your XNA game to make sure you are debugging the latest version).

Run Game > Press Start  (Game terminates in background) > Press Back (blank screen displayed) > Press F5/Run in Visual Studio (runs game) > Game runs as if it were tombstoned (ie Activated event raised)

Windows Phone 7 beta: Application Crashes With No Exception In Visual Studio

Windows Phone 7 beta: Application Crashes With No Exception In Visual Studio

Here’s a simple scenario: You have some code that gets invoked during application startup (for example creating instances of your view model, loading data from isolated storage etc). Whilst developing this code you place breakpoints in this code. When you run your application in the debugger the breakpoints get hit, you step through the code and it all works as expected. However, when you press F5 to continue, the application just terminates and Visual Studio stops debugging…. you’re left thinking what the?

What I suspect your seeing is the implementation of one of the Windows Phone 7 requirements around launching. If you read the Windows Phone 7 Application Certification Requirements you will see that 5.2.1 talks about launch time.

5.2.1 Launch Time
a. The application must render the first screen within 5 seconds after launch.
To meet this requirement, Microsoft recommends that the application provides a splash screen image in a file called SplashScreenImage.jpg in the root of the XAP package.
b. Within 20 seconds after launch, the application must be responsive to user input.

If you either allow your application to launch without breakpoints, or you quickly step through your breakpoints you should see that your application loads without any issues. If you stop the application on a breakpoint for a good 30 seconds, your likely to see your application terminated. This also applies to when you return to your application after it has been Tombstoned (ie Deactivated and then terminated in the background) – in this case you need to make sure you restart your application from Visual Studio quickly otherwise it will be terminated completely and you’ll have to restart your debugging again.

Windows Phone 7 beta: Launcher and Chooser Tasks Cludge

Windows Phone 7 beta: Launcher and Chooser Tasks Cludge

Firstly I have to apologise to any readers who experienced issues viewing my blog over the last 72 hours. This was a result of my awesome (not!) hosting provider webhost4life. Anyhow hopefully the issues have been resolved and life can continue.

In my previous post (Windows Phone 7 beta- Who Killed My Application) I talked about what happens when your application goes into the background. Specifically that in the current bits your application will be terminated. Now in actual fact the Windows Phone developer contract doesn’t state this, it only says that your application may be terminated any time between when your application receives a Deactivated event and when it receives an Activated event. In the case where it is terminated (which is always the case in the current dev bits) when the user presses the Back button your application will be relaunched and the Activated event raised (not the Launching event).

Here’s another scenario where you may be wondering what’s going on with Visual Studio. In your application you want to use the CameraCaptureTask to take a photo. You create an instance of the CameraCaptureTask, add an event handler for the Completed event (note that this is different from the April CTP where you overrode a method on the base class) and then call the Show method. For example the following code launches the CameraCaptureTask and then sets the photo as the source of an Image control.

using System;
using System.Windows;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;

namespace WindowsPhoneTasks
{
    public partial class MainPage : PhoneApplicationPage
    {
        CameraCaptureTask cameraTask = new CameraCaptureTask();
     
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            cameraTask.Completed += new EventHandler<PhotoResult>(cameraTask_Completed);
        }

        void cameraTask_Completed(object sender, PhotoResult e)
        {
            var source = new BitmapImage();
            source.SetSource(e.ChosenPhoto);

            this.PhotoImage.Source = source;
        }

        private void TakeAPhotoButton_Click(object sender, RoutedEventArgs e)
        {
            cameraTask.Show();
        }
    }
}

When you run this you will notice something weird. The following screenshot sequence illustrates this. Initially the emulator is at the Start screen (1). You run the application from Visual Studio and then you click the Take Photo button (2). This launches the camera capture dialog (3) and you’ll notice that your application has been terminated – this dialog is a bit buggy at the moment so you may need to click around the screen in order to find the button to take a picture; it’s in the top right corner! When you click “accept” you will see a blank screen(4). If you recall from my previous post, this is what happened when the user clicked the Back button to return to your application. You’re seeing a blanks screen because your application isn’t there any more. Press F5 or Run your application from Visual Studio and the Completed event will be fired, displaying the photo in the Image (5).

 

image[4]

Here’s the cludge (as if having to restart Visual Studio wasn’t enough of a cludge): In order for the Completed event to work the instance of the CameraCaptureTask has to be an instance variable where the event handler is wired up in the constructor of the page. As you can imagine there is some additional logic that gets performed as part of the add event handler operation (using Reflector):

 

public event EventHandler<TTaskEventArgs> Completed
{
    add
    {
        if ((this._completed == null) || (Array.IndexOf<Delegate>(this._completed.GetInvocationList(), value) == -1))
        {
            this._completed = (EventHandler<TTaskEventArgs>) Delegate.Combine(this._completed, value);
            InvokeReturningEventArgs args = null;
            if (ChooserListener.IsChooserCompletePending(this._genericChooser, value, out args))
            {
                this.OnInvokeReturned(args.returnBuffer, value);
            }
        }
    }
    remove
    {
        this._completed = (EventHandler<TTaskEventArgs>) Delegate.Remove(this._completed, value);
    }
}

Windows Phone 7 beta: Who Killed My Application

Windows Phone 7 beta: Who Killed My Application

If you hadn’t already noticed Microsoft have released the first beta of the Windows Phone 7 developer tools. There are some significant, breaking, changes from the previous release from April. These have been quite well documented in this migration post however there are some gotchas that aren’t pointed out. The first of these is what happens when your application goes into the background.

As most of you will be aware Microsoft has been avoiding the question as to what the behaviour is when your application goes into the background (eg the Start is displayed and/or another application loaded). This is in part because they don’t want developers to develop according to the current Windows Phone implementation. Rather they want developer to develop against a contract which states that “should your application go into the background, it should assume that it will be terminated at any point in the future by the operating system”. What this means in practice is that Windows Phone has the option of leaving your application in memory, effectively running in the background, or terminating it immediately or at a later stage.

Let’s take a look at what happened in the April CTP – in this case when your application went into the background there was a Paused event raised on the Application which you could intercept and persist any information about the current state of your application. However, your application wasn’t actually terminated when the user presses the Start button (on the emulator that is).

Now, let’s look at the behaviour in the beta of the tools. Now, when you run your application, then click on the Start button you will notice that your application is terminated (this is evident because you will notice Visual Studio is no longer attached to the running process). However, when you click the Back button, your application should reappear, right? Wrong! Well, at least, without you doing anything that will be the case. What you actually see when you press the Back button is a blank screen. At this point if you run your application from Visual Studio 2010 it will start as if the user had pressed the Back button.

Take the following scenario:

1) Application loads and displays page 1
2) User navigates to page 2
3) User clicks Start (application is terminated)
4) User clicks Back (application is not running)
>> Press F5 or Run in Visual Studio
5) Application loads and returns to page 2.

Note that when the application loads for the second time, page 1 is never loaded. However, if the user presses the Back button again page 1 will again be displayed.

You should also be aware of the events that get raised within your application (these are exposed by the PhoneApplicationService and are wired up by default in App.xaml to methods in the App.xaml.cs file)

Launching – This event is raised when the application is launched from the Start screen. This event is not raised when the application is reloaded when the Back button is pressed.

Activated – This event is raised when the application is returned to by clicking the Back button. This event is not raised when the application is launched from the Start screen

Deactivated – This event is raised when the application is sent into the background. This might be due to the user clicking the Start button, or launching a task. You should save both persistent (between application sessions) and transient (for the current application session) at this point. You should assume that your application may get terminated at will by the operating system. You will not get another opportunity when this happens to persist information.

Closing – This event is raised when the application is closed by the user pressing the Back button when at the home/first page of the application.

I can’t reiterate this enough: When you get the Deactivated event, make sure you save both the persistent and transient state of your application. This should also include information about the visual state of the current page (eg what text the user may have entered, perhaps even which control has focus). When the user clicks the Back button, they will want to see the same page that was there when they pressed the Start button, irrespective of whether the application was terminated and relaunched, or not.