Shake Detection on Windows Phone 7

Back in Sept 2009 I did a few presentations for FITC Mobile 2009 and in the sample code I included a modified version of the Sensor API available on Codeplex.  The modified version of the API included some code that leveraged the accelerometer on some devices to detect when a device was shaken.  This code base was for Windows Phone 6.x and used .NET Compact Framework 3.5.  Essentially all you would have to do is wire up a ShakeDetected event and whenever the API detects a shake you would be notified via an event.

private IGSensor m_sensor;

public Form1()
{
    InitializeComponent();

    m_sensor = GSensorFactory.CreateGSensor();
    m_sensor.ShakeDetected += m_sensor_ShakeDetected;
  
}

void m_sensor_ShakeDetected(object sender, EventArgs e)
{
    //Invoke into the main thread since we are coming form a background thream
    this.Invoke(new EventHandler(delegate(object s, EventArgs ea)
    {
        //Code once shake is detected
        MessageBox.Show("Shake Detected");
    }));

}

Couple of things I didn’t like about this code.

  1. There is a thread running in the background doing a calculation of the X,Y,Z values and determining whether a shake has occurred.  This will drain the battery.
  2. It’s not a standard API and does not work on all devices because either the device does not have the hardware or the PInvokes are specific for only one OEM such as HTC.

To try it out for your self download the sample code for shake detection here. (Find it under Release Presentation Code\New Windows Mobile 6.5\Demo1\ShakeDetection).

Shake Detection On Windows Phone 7

Since the development environment for Windows Phone 7 is completely different now and uses Silverlight, the ‘shake detection’ code essentially is useless but that doesn’t mean the code can’t be ported over.

The good thing is Windows Phone 7 introduces standard hardware and standard APIs for sensors which should alleviate some developer pains from previous Windows Phone versions.  All Windows Phone 7 devices from OEMs will include an accelerometer so no more worrying about code not working.  Before I get into how to detect shake, see here for an overview of the accelerometer on Windows Phone 7.

To get shake detection working on Windows Phone 7, I had to wrap the AccelerometerSensor class within a wrapper class called AccelerometerSensorWithShakeDetection.  Using the new class is pretty straight forward and basically have to create an instance of the class and wire up the ShakeDetected event handler.

AccelerometerSensorWithShakeDetection m_shakeSensor;

public MainPage()
{
    InitializeComponent();

    m_shakeSensor = new AccelerometerSensorWithShakeDetection();
}

private void btnStart_Click(object sender, RoutedEventArgs e)
{
    m_shakeSensor.ShakeDetected += m_shakeSensor_ShakeDetected;
}

private void button2_Click(object sender, RoutedEventArgs e)
{
    m_shakeSensor.ShakeDetected -= m_shakeSensor_ShakeDetected;
}

void m_shakeSensor_ShakeDetected(object sender, EventArgs e)
{
    lblShakeStatus.Text = string.Format("Shake Detected @ {0}",
                  DateTime.Now.ToString("hh:mm:ss")); }

AccelerometerSensorWithShakeDetection implementation is different from the previous version because we now have a standard API.  Internally we wire up the AccelerometerSensor.ReadingChanged event when a user wires up the ShakeDetected event and call the AccelerometerSensor.Start and AccelerometerSensor.Stop when the AccelerometerSensorWithShakeDetection.Start/Stop methods are called.

public event EventHandler ShakeDetected
{
    add
    {
        m_ShakeDetectedHandler += value;
        m_sensor.ReadingChanged += Default_ReadingChanged;
    }
    remove
    {
        m_ShakeDetectedHandler -= value;
        m_sensor.ReadingChanged -= Default_ReadingChanged;
    }
}
        
public void Start()
{

    if (m_sensor != null)
        m_sensor.Start();
}

public void Stop()
{
    if (m_sensor != null)
        m_sensor.Stop();
}

When the reading change event occurs, we run our shake detection logic to see if the user has shaken the device.

private void Default_ReadingChanged(object sender, AccelerometerReadingAsyncEventArgs e)
{
    //Code for checking shake detection
    if (e.Value.State == SensorState.Ready)
    {
        AccelerometerReading reading = e.Value.Value;
        DateTimeOffset timeStamp = e.Value.Timestamp;
        try
        {
            if (!shaking && this.CheckForShake(m_lastReading, reading, 
                       shakeThreshold) && shakeCount >= 5) { //We are shaking shaking = true; shakeCount = 0; OnShakeDetected(); } else if (this.CheckForShake(m_lastReading, reading, shakeThreshold)) { shakeCount++; } else if (!this.CheckForShake(m_lastReading, reading, 0.2)) { shakeCount = 0; shaking = false; } m_lastReading = reading; } catch { /* ignore errors */ } } } private void OnShakeDetected() { if (this.m_ShakeDetectedHandler != null) this.m_ShakeDetectedHandler(this, EventArgs.Empty); } private bool CheckForShake(AccelerometerReading last,
                            AccelerometerReading current, double threshold) { double deltaX = Math.Abs((double)(last.X - current.X)); double deltaY = Math.Abs((double)(last.Y - current.Y)); double deltaZ = Math.Abs((double)(last.Z - current.Z)); return (deltaX > threshold && deltaY > threshold) || (deltaX > threshold && deltaZ > threshold) || (deltaY > threshold && deltaZ > threshold); }

When a shake is detected, the ShakeDetected handler is called to notify the listeners.

So porting code from previous Windows Phone versions to Windows Phone 7 is definitely possible because we are still using Managed code.  Some advantages to the new code are

  1. Standard APIs are used for the Accelerometer
  2. No threads running in the background to detect shake.  Instead an event based mechanism is used which will preserve the user experience and preserve the battery life.

One thing to note, to code compiles and runs on the emulator, but because I don’t have a real Windows Phone 7 device, I cannot test the code.  The version for .NET CF 3.5 works and the shake detection logic is essentially the same for Windows Phone 7 so I’m assuming it will work.  But if anyone in the product group wants to test on a real device (or send me a real device 🙂 please do and let me know if it works.

Once I get a real device, I’ll test and update this post.  In the meantime, download the shake detection source code here to take a peak.

OAuth with Silverlight for Windows Phone 7

In my last post I wrote about the Silverlight WebBrowser control on Windows Phone 7 and how to communicate with a web page hosted inside the control and your Windows Phone 7 app.  The example in that post was pretty trivial, so why not try something like OAuth and Twitter.

For more background on how OAuth and Twitter work check the Authentication Overview on dev.twitter.com.

In short here is the process (overly simplified) to authenticate a twitter user

  1. Register your app with Twitter and get a key
  2. Within app, get an request token
  3. With the WebBrowser control, navigate to Authentication URL
  4. Wait till the user authenticates.
  5. Get an access token
  6. Make secure calls

After becoming familiar with OAuth, first thing I decided to do was find an OAuth library for Silverlight.  The one I found most useful and easily portable to Windows Phone 7 was sample code in the book Professional Twitter Development by Daniel Crenna.  Unfortunately, this did  not compile without a few changes on WP7.  Here is a quick summary of the changes I made

  1. Change all HttpWebRequests to be async since sync requests are not supported
  2. Added callback param to all methods to get responses back to the UI
  3. Created and OAuthEventArgs class
  4. Modified support to POST web requests
  5. Added helper methods to ParseQueryString and HexEscape characters
  6. Added a TwitterOAuth class to contain all tokens, Urls and various other items.

Next thing I had to do was wire up the code to enable the user to authenticate via OAuth with Twitter.  Basically all you have to do is get a “request token” then navigate to the “authentication Url” for the user to enter their credentials.  Here is the code

OAuth.GetRequestToken(m_twitterOAuth.RequestTokenUrl,
    m_twitterOAuth.ConsumerKey,
    m_twitterOAuth.ConsumerSecret,
    new EventHandler<OAuthEventArgs>((o, args) =>
    {

        if (args.IsError)
            this.Dispatcher.BeginInvoke(() => MessageBox.Show(args.ErrorMessage));
        else
        {
            //extract the items
            Dictionary<string, string> results = 
                              Helpers.ParseQueryString(args.Response); foreach (var item in results) { if (item.Key.Equals("oauth_token")) m_twitterOAuth.Token = item.Value; else if (item.Key.Equals("oauth_token_secret")) m_twitterOAuth.TokenSecret = item.Value; } //Wait till the browser loads while (!m_browserLoaded) Thread.Sleep(100); //once loaded invoke the browser to go to twitter auth page this.Dispatcher.BeginInvoke(() => { webBrowser1.Navigate(new Uri(m_twitterOAuth.AuthenticationUrl)); }); } }));

When asking for a request token, you can specify a callback url that twitter will navigate to when the user successfully authenticates.  Next step is to create an HTML page that will invoke a method within our WP7 application.  The HTML Page is as follows and is very straight forward.

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>TwitterCallback</title>
     <script type="text/javascript">
         function InvokeApp(input) {
             window.external.Notify(window.location.href);
         }

    </script>
</head>
<body onload="InvokeApp()">
</body>
</html>

The method inside our WP7 app will parse the url which contains details on the authentication then goes out and gets the access token to make secure calls

void webBrowser1_ScriptNotify(object sender, NotifyEventArgs e)
{
    //we are back from authentication so extract the verifier
    try
    {
        Uri uri = new Uri(e.Value);
        //parse the query string
        Dictionary<string, string> results = Helpers.ParseQueryString(uri.Query);    

        foreach(var item in results)
        {
            if (item.Key.Equals("oauth_verifier"))
                m_twitterOAuth.Verifier = item.Value;
        }

        //hide the web browser control
        this.Dispatcher.BeginInvoke(() =>
        {
            textBlock1.Text = "Contacting twitter to get access to your twitter 
account. Please be patient :)"
; textBlock1.Visibility = System.Windows.Visibility.Visible; webBrowser1.Visibility = System.Windows.Visibility.Collapsed; }); //now that we have the verifier get the access token OAuth.GetAccessToken(m_twitterOAuth.AccessTokenUrl, m_twitterOAuth.ConsumerKey, m_twitterOAuth.ConsumerSecret, m_twitterOAuth.Token, m_twitterOAuth.TokenSecret, new EventHandler<OAuthEventArgs>((obj, args) => { //handler when the get access token call returns if (args.IsError) this.Dispatcher.BeginInvoke(() =>
                               MessageBox.Show(args.ErrorMessage)); else { //extract the items results = Helpers.ParseQueryString(args.Response); foreach (var item in results) { if (item.Key.Equals("oauth_token")) m_twitterOAuth.Token = item.Value; else if (item.Key.Equals("oauth_token_secret")) m_twitterOAuth.TokenSecret = item.Value; else if (item.Key.Equals("user_id")) m_twitterOAuth.UserId = item.Value; else if (item.Key.Equals("screen_name")) m_twitterOAuth.ScreenName = item.Value; } //update the label this.Dispatcher.BeginInvoke(() => { MessageBox.Show(textBlock1.Text,
                                   "Authorized for Twitter", MessageBoxButton.OK); btnSignOut.Visibility = btnPostTweet.Visibility =
                                     txtTweet.Visibility = Visibility.Visible; textBlock1.Visibility = Visibility.Collapsed; }); //save the settings SaveTwitterOAuth(); } })); } catch (Exception ex) { this.Dispatcher.BeginInvoke(() => MessageBox.Show(ex.Message)); } }

Now that we are authenticated we can make a ‘Tweet’ from with our application as follows

private void btnPostTweet_Click(object sender, RoutedEventArgs e)
{
    if (txtTweet.Text.Length > 140)
    {
        MessageBox.Show("Message is greater than 140.  Cannot post");
    }
    else
    {
        OAuth.GetProtectedResource(
            string.Format(m_twitterOAuth.StatusUpdateUrl, 
                  HttpUtility.UrlEncode(txtTweet.Text)), "POST", m_twitterOAuth.ConsumerKey, m_twitterOAuth.ConsumerSecret, m_twitterOAuth.Token, m_twitterOAuth.TokenSecret, new EventHandler<OAuthEventArgs>((obj, args) => { //the post is back so parse the response //handler when the get access token call returns if (args.IsError) this.Dispatcher.BeginInvoke(() =>
                             MessageBox.Show(args.ErrorMessage)); else { this.Dispatcher.BeginInvoke(() => { MessageBox.Show(args.Response,"Tweet Posted",
                                           MessageBoxButton.OK); txtTweet.Text = string.Empty; }); UpdateUsernameLabel(); } })); } }

Here is a screen shot of a test tweet

image One of the advantages of using OAuth with Twitter is you get your ‘application name’ in the ‘via’ section instead of it saying ‘posted from web’.  Also, since Basic Authentication is no longer supported by Twitter, your only option is either OAuth or XAuth.  Considering with XAuth you have to email twitter and convince them to give you access to that, OAuth is the easier way to go.

Here are some screen shots of the Windows Phone 7 client.

wp7oauthtwitter

 

You can download the source code here.  I have no plans on building a Twitter client for Windows Phone 7 as I have a feeling someone out there is probably building one 🙂

Any feedback let me know via here or via Twitter.

NOTES: The app will not compile until you remove the #error to add your registered app key.  Also, make sure you change the timezone and set the correct time on the emulator or else the OAuth signature generation will not work.

Windows Phone 7 Webcast with Microsoft Canada

Yesterday I had a chance to do a webcast with Microsoft Canada on the developer experience for Windows Phone 7 and getting developers ramped up.  If you missed it you can get it on demand here : In the Know With Windows Phone 7 

There were a few demos that I went through during the webcast which are

  1. FirstApp – typical hello world type app
  2. AppNavigation – navigating and using the back button
  3. InputScope – setting different input scope/SIP types
  4. Launchers and Choosers – examples of using it
  5. Multimedia – playing a wmv file
  6. Notifications – sending toast and tile notifications

These are very introductory demos and no error checking has been built in so make sure you add that.  You can download the source here

If you have any feedback or comments on the webcast feel free to contact me at mark [at] redbitdev [dot] com.

Silverlight WebBrowser Control and Windows Phone 7

Silverlight for Windows Phone 7 contains a WebBrowser control and there is nothing to impressive about that other than you have the ability to load a web page within your Silverlight application. But there is a hidden gem, the ability for two way communication with the webpage within your Silverlight app. There is a mini browser sample available on the Windows Phone Development section on MSDN which basically places a web browser control with a textBox and button so you can navigate to a URL. If you know the basics of using the control skip to the Hidden Gem section below.

The Basics

Using the WebBrowser control is nothing too exciting or complicated.  Just drag it from your ToolBox within Visual Studio Express for Windows Phone and drop it on your page in the designer.  Visual Studio will automatically add a reference to Microsoft.Phone.Controls.Webbrowser and Microsoft.Phone.Controls.WebbrowserInterop.

image

Then doing a quick call to WebBrowser.Navigate() on the button click event and your done.  Again nothing too exciting or complicated but can be useful in some situations within your app.

The Hidden Gem

The hidden gem I learned during Mike Harsh’s MIX10 session.  I was really excited about it because it solved a few problems I had on previous versions. This gem comes in the form of the WebBrowser.IsScriptEnabled property.    Basically this property will allow the loaded page within the webBrowser control invoke the ScriptNotify Event handler within your Silverlight app.  But that’s not all, using the WebBrowser.InvokeScript allows the Silverlight for Windows Phone app invoke a Javascript function on the web page loaded within the webBrowser control.  Basically you have two way communication which could be valuable in some situations.  Here’s how it works.

First step is making sure the IsScriptEnabled property is set to true.  This allows the communication to work between the two layers.  Default value is false.

image

In the sample code, I created a textBox to type in the URL to browse to and a button to call WebBrowser.Navigate().  I also created an extra textBox and button to invoke a javascript function within the loaded web page.  You will also have to wire up the WebBrowser.ScriptNotify event.  I did this via Xaml but can also be done in code as follows:

webBrowser1.ScriptNotify+=new EventHandler<NotifyEventArgs>(webBrowser1_ScriptNotify);

and the handler is just a messagebox to show the data received

private void webBrowser1_ScriptNotify(object sender, NotifyEventArgs e)
{
    MessageBox.Show(
string.Format("New value received from web browser control (\"{0}\")", e.Value)); }

To invoke a script in the web browser control use the InvokeScript method passing in the Javascript method  to invoke and the string to send as follows:

webBrowser1.InvokeScript("DataReceivedFromPhoneApp", textBox1.Text);

The page is very basic and looks like this.

image

The other side of this sample is a web page to load.  Again I kept it basic but here is the web page rendered

image and the source

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <
html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta name="mobileoptimized" content="480" /> <title>SamplePage1</title> <script type="text/javascript"> function DataReceivedFromPhoneApp(input) { textReceived.innerHTML = input; return true; } function SendDataToPhoneApp() { window.external.Notify(textToSend.value); } </script> </head> <body> <div> Enter your text: <input name="textToSend" type="text" value="send to app" /> </div> <div> <input type="button" value="Send to Phone" onClick="SendDataToPhoneApp()"/> <br /> <br /> </div> <div>Value received from phone app:</div> <div id="textReceived" style="font-size: x-large; font-weight: bold; color:
#800000;
border: thin solid #000000"></div> </body> </html>

When you run the app an navigate to the page (I hosted it on my local IIS on my dev machine) it will render up the web page.  Clicking the button inside the web browser control produces the following.

image

And clicking the button within the Silverlight app modifies the html via javascript producing the following

image

Conclusion

There you have it two way communication between your Silverlight for Windows Phone 7 app and a web page within the WebBrowser control.

Pre-Windows Phone 7 using .NET Compact Framework this was possible but again with a lot of extra effort.  As far as I know, you would need to create an ActiveX control, register it on the device and somehow communicate with the web browser and the .NET CF app using some form of Inter-Process Communication (IPC).  Not fun or easy!

Explore some more and download the sample code here

Windows Phone 7 CTP Refresh and InputScope

If you haven’t heard the Windows Phone 7 CTP April Refresh has been released.  Prepping for my Toronto CodeCamp Session tomorrow I found an issue with setting an InputScope to TextBox.  I am basically doing the same demo Mike Harsh did at MIX10 where all InputScopeNameValues were used to populate a ListBox and then dynamically change the InputScope on a TextBox.

Pre April CTP you could use the following code

textBox1.InputScope = new System.Windows.Input.InputScope() { Names = new InputScopeName() { NameValue = InputScopeNameValue.AddressCity} };

with the April CTP for Windows Phone 7 this breaks now and gives an error of  “Property or indexer ‘Names’ cannot be assigned to — it is read only”

Don’t know if it’s a bug or not but there is an alternative as follows.

textBox1.InputScope = new System.Windows.Input.InputScope() ;
textBox1.InputScope.Names.Clear();
InputScopeName isn = new InputScopeName() { NameValue = InputScopeNameValue.AddressCity };
textBox1.InputScope.Names.Add(isn);

Peter Foot also mentioned that you can use XAML to make this happen:

<TextBox Height="32" HorizontalAlignment="Left" Margin="324,70,0,0"
Name="textBox1" Text="TextBox" VerticalAlignment="Top" Width="137" InputScope="Text" />

and then dynamically set it with the following:

((InputScopeName)textBox1.InputScope.Names[0]).NameValue = val;

This is expected with CTPs, just wish it didn’t happen the day before a presentation!

Can Windows Phone 7 Multitask?

[UPDATE – April 12, 2010: the test below is a bug in the Windows Phone 7 CTP Emulator as I expected.  Expect the Pause/Resume/Suspend functionality to be fixed in future emulators and to work on a real device.  Don’t rely on your threads running in the background in future versions and offload background processing to a server and use Push Notifications to update/notify device.]

There has been a lot of talk about how Microsoft is behind the ball on Windows Phone 7 since it can’t multitask since Apple announced iPhone 4.0 OS will now include multitasking.

What’s my take on this?  Well, Windows Phone 7 is based on Windows Embedded CE.  Without going into too much details on Windows CE, it is basically a real-time operating system and is not a trimmed down version of their desktop Windows OS.  Windows CE is it’s own full fledged real-time operating system and yes it can do multitasking. 

In all the years I’ve been developing Windows Phone and Windows CE software for customers, I have seen lots of applications that just go out and kill the battery, launch X number of threads or do things that are just not too smart and really kills the end user experience on the device. Think about it, when an app kills the battery in 1hr, the end user will usually say “this phone sucks” and returns it. In reality it’s not the phones fault, it’s the crappy app! This has always been a problem that has plagued Pocket PC/Windows Mobile/Windows Phone 5.x – 6.x for some time.  Windows Phone 7 is about the end user and making sure their experience with the phone is top notch.  This post on Windows Phone 7 and “Focus” by Charlie Kindel talks a bit more about the end user experience.

Back to the question, Can Windows Phone 7 Multitask?  Of course it can, it’s just not fully exposed to third party developers.  Things like the Zune player will continue to run in the background even if it’s not the foreground app.  What the Windows Phone 7 team has done is scale back some of the power a third party developer has so the end user experience is not compromised. 

So as a third party developer what’s available to us?  Peter Torr gave a session at MIX10 called Building Windows Phone Applications with Silverlight (Part II) and shows this diagram of application state when jumping to another application.

 

image

So your application has four states:

  1. Running – Here your application is started by the user and will run
  2. Paused – User decided to switch over to another application or answered a phone call (remember the device is a phone too :).  Here you should save your application state in case you go into “Suspended” state
  3. Suspended – Here you could assume your application is being killed by the OS.  That’s ok as long as you saved your state when you are paused.
  4. Resume – The user has started your app again and you want to resume where they left off since you saved state when paused

Because there is a suspended state, it doesn’t mean your app will always get suspended.  Your app will only get suspended if they OS feels that it is running low on resources.  (Remember, the phone doesn’t run a quad core processor with 8GB of ram :)  Once the OS is running low on resources it will start Suspending (or killing) apps most likely starting with the one that has not been in the foreground for the longest time.  To me it sounds very similar to WM_HIBERNATE and old school Windows Phone and Windows CE developers will know all about this.

So, being a curious developer, I tested the “Paused” state above but because the Windows Phone 7 Dev tools are CTP I can’t come to a definite conclusion.  Basically I created a simple app that continues counting on a background thread and updates the UI

image

Without hitting the “Back” button (because that will close my app), I clicked on the “Start” button and started the EnergizeIT Mobile app and logged in to get to the main screen.  I then clicked on the “Start” button again, opened the Start Menu and opened the WPMultitask1 sample app and my counter was incremented to 1724 from 1676.  In fact, I’ve been running it in the background for about 1,700s while I was writing this post.

image

Because I am using a CTP, maybe the “Pause” state does not work yet.  Couldn’t really test the “Suspended” state because all the Windows Phone 7 emulator has is Internet Explorer so most likely can’t use up all resources on the device.

In the end, Windows Phone 7 can do multitasking but is just limited to third party developers.  My test above shows a Thread in an app will continue to run while not being the foreground app.  Since iPhone OS 4.0 was just announced and now will support multitasking, my guess is the Windows Phone 7 team may consider opening up multitasking a bit more to third party developers.  Maybe during marketplace submission there will be a check box that says “My application requires access to run in the background” and the testing process will be more rigorous (yes I’m over simplifying it). The OS has the power to do multitasking, it’s just a matter of doing it right and preserving the end user experience.

Here is the code to run the threads:

/// <summary> /// thread to update the counter /// </summary> private Thread m_counterThread; /// <summary> /// Waithandle to tell the thread to stop /// </summary> private ManualResetEvent m_waitHandle = new ManualResetEvent(false); /// <summary> /// The current count to display /// </summary> private int m_count = 0; public MainPage() { InitializeComponent(); SupportedOrientations = SupportedPageOrientation.Portrait |
SupportedPageOrientation.Landscape; //enable disable the buttons btnStop.IsEnabled = false; } private void btnStart_Click(object sender, RoutedEventArgs e) { if (m_counterThread == null) { m_waitHandle.Reset(); WaitHandle[] handles = new List<WaitHandle> {m_waitHandle}.ToArray(); m_counterThread = new Thread(() => { //Main counter thread int index = WaitHandle.WaitTimeout; while (index == WaitHandle.WaitTimeout) { //incrememnt the counter m_count++; //update the counter label this.Dispatcher.BeginInvoke(new Action(() => { //Update the lable counter.Text = m_count.ToString(); })); //Wait for the stop handle index = WaitHandle.WaitAny(handles, 950); } }); //Start the thread m_counterThread.Start(); } //enable disable the buttons btnStart.IsEnabled = false; btnStop.IsEnabled = true; } private void btnStop_Click(object sender, RoutedEventArgs e) { if (m_counterThread != null) { //tell the main thread loop to stop m_waitHandle.Set(); //wait here till the thread stops m_counterThread.Join(); m_counterThread = null; //enable disable the buttons btnStart.IsEnabled = true; btnStop.IsEnabled = false; } }

And here is the partial Xaml for the page (ContentGrid)

<Grid x:Name="ContentGrid" Grid.Row="1">
    <TextBlock x:Name="counter" Text="[Counter Text]" 
               Style="{StaticResource PhoneTextPageTitle2Style}" 
               Margin="0,119,0,414" 
               TextAlignment="Center" />
    <Button x:Name="btnStart" 
            Content="Start Thread" 
            Click="btnStart_Click" 
            Margin="70,334,76,205" />
    <Button x:Name="btnStop" 
            Content="Stop Thread" 
            Click="btnStop_Click"
            Margin="70,453,76,90" />
</Grid>

EnergizeIT: From the Client to the Cloud – The Mobile App

I few months ago RedBit was asked by Microsoft to help them create a Windows Phone 6.5 demo application for EnergizeIT: From the Client to the Cloud tour across Canada. 


The purpose of the mobile software was to allow a fictitious insurance company to AppLogo_Splash_VGA_thumb[7] collect car accident information from a consumer. The consumer would be able to fill in basic information about the accident, take pictures of the incident, get the GPS location including address of the accident and submit this to a backend system where the data can be collected and acted upon.  The goal was to show EnergizeIT attendees how to leverage the Microsoft based platform and tools such as Silverlight, .NET 4.0, Azure and Visual Studio 2010.  The mobile software used .NET Compact Framework 3.5 but I’ll have a future post on porting it to Windows Phone 7.


RedBit’s role was to get the data from the Windows Phone to the backend database.  Our goal was also to make the mobile app look a little nicer than traditional Windows Mobil apps. What we created is a mobile client to have the consumer enter accident information and also created a WCF service to allow consumers to submit the data for the insurance company to act on. 


image image image


For location support we created a WCF service to reverse geocode a location to provide a readable address and an image of the location via Bing Maps API.


image image







The user would also be able to see their insurance card and the autos that are insured cars under their policy.


image image


We also included a feature called On The Road that allowed you to search for various services around you. 


imageBy the way, you can download Find My Bru from Windows Phone Marketplace now.


Overall, I think we were able to deliver a pretty good looking functional app on Windows Phone 6.5 (with a lot of effort for the UI).  Thanks to Christian Beauclair and the rest of the Canadian DPE team for giving us the opportunity to build this app for Windows Phone. 


Unfortunately, I won’t be publishing the source to this app but will be following up on blog posts showing some code snippets that I think will be useful to the developer community. 


I’ll also be following up in another blog post on porting this mobile application to Windows Phone 7 and what code we were able to re-use and most importantly, how easy it is to make a good looking app on Windows Phone 7.



If you want more info on the app please feel free to contact us at info[@]redbitdev[dot]com

TechDays Canada 2009 Sample Source Code

In our recent session at TechDays Canada 2009 (Taking Your Application on the Road with Windows Mobile® Software) I promised to make some links and the source code available so here it is

See my post on FITC Mobile 2009 for more links.

Here is the .NET sample source code for Windows Mobile for the demos shown.

If you have questions just ping me via my blog or twitter.

FITC Mobile 2009 – Wrap Up

A few weeks ago I did a three presentations and one workshop at FITC Mobile 2009. Unfortunately I did not get to stick around to talk to attendees or go to the second day because I had to fly out to Vancouver for a TechDays session the next day.

I did promise a link to the demo code and various other links to help attendees get up to speed on developing for Windows Mobile so here they are.

  1. Windows Mobile Consumer Solution Accelerator
  2. MSDN UI Framework
  3. Gestures API Managed Wrapper
  4. Windows Mobile Blog
  5. Windows Mobile Developer Site
  6. Porting the Amplitude application to Windows Mobile

Sample Source Code Includes:

And here is a link to the FITC Mobile 2009 Windows Mobile sample source code.

If you have questions just ping me via my blog or twitter.  Also, if you are looking at implementing a mobile solution and don’t know where to start, contact me and I’m sure RedBit can help out!

Glass Effect On Windows Mobile using Compact Framework

There has been a lot of talk about how the Windows Mobile user interface is just not up to par with mobile devices such as the iPhone.  As developers we cannot change the Windows Mobile user interface but we do have the opportunity to differentiate our applications from the competition or to just add a little “eye candy” to improve our applications user experience. 


So how do we get this done on Windows Mobile?


Well not being a graphics expert I decided to search the web. First thing I did is figure out how to implement a ‘glass effect’ using Paint.Net and found this post on how to make ‘glass buttons’.  Now that I had the knowledge on how to create a glass button using a graphics program I could try and implement in code.


Before I did that I searched for any existing code on the desktop.  I found an article on Code Project which uses GDI+ on the desktop to create a glass button and works great.  Using the knowledge form Alex Feinman’s article on Using GDI+ on Windows Mobile I was able to port the desktop code to Windows Mobile.


The glass button sample accompanying this post just draws on the main form and uses a panel for the bounds of the ‘button’ and checkboxes to set different states for the button.


In the interest of time, I did not implement a full glass button control and I’ll leave it up to you to implement a control possibly using the gradient button for Windows Mobile available on MSDN as a starting point.  Now that you have the knowledge (and code) on how to paint a ‘glass effect’ on Windows Mobile this should be straight forward.


The code results in the following:



Glass Button with Enabled State
GlassButton1 


Glass Button With Hovered State (or Focused)
GlassButton2 



Glass Button with MouseDown State
GlassButton3 


Although this will add some eye candy to your Windows Mobile application, there are a few caveats:



  1. The glass button sample code doesn’t really create a button control but just draws and blits to the screen
  2. GDI+ is only support on Windows Mobile 5+ with touch screens which means this code will not work on SmartPhone (or non-touch screens 🙂 )
  3. GDI+ on Windows Mobile is too slow IMO but caching the bitmaps should help.

So there you have it, glass effect on Windows Mobile.  I’ll be following up with some more posts on some techniques I’ve used in the past to give Windows Mobile applications a nice UI instead of the standard ‘grey controls’.