Thursday, September 30, 2010

Windows Phone 7 Quick Tip #11 – Metro Part I - Colors

Before penning your first XAML angle bracket when building a Windows Phone 7 application you need to make an important decision.  Are you going to follow the built in color themes or are you going to create your own and ignore the selected theme.  Ignoring the selected theme is certainly an option and may be a good one depending on your situation.  The point is adopting the built in themes is pretty much an all or nothing decision.  The reason for this is simple, let’s say you think yellow would look good for the Foreground for your application, here’s an example:

image

As you are probably aware, the user can specify a light or dark background theme for their phone.  If they choose the white background, here is what you get:

image

Doesn’t look so great anymore does it?

So the primary point to this tip is if you are using the built in styles like this:image

If anywhere within your application you do something like this:

imageYou are probably doing it wrong and better really be careful and check your application running in both light and dark themes

-twb

Tuesday, September 28, 2010

Windows Phone 7 Quick Tip #10 – Metro: Learn it, Live it, Love it!

If you develop applications for Windows Phone 7, you really need to spend some time getting to know Metro.  Metro is the name of the design guidelines that define the look and feel behind Windows Phone 7.  You may not like Metro, you may _think_ to can do a better job, or you might actually be able to, however if you want to have the best chances to have widespread adoption of your application, your application needs to “feel” like it belongs on the device. 

If you are a developer, you may be “design-challenged” and if so you will learn to love Metro.  Even I can create users interfaces and experiences that don’t suck.  In the next few tips, I’m going to present Metro from a purely mechanical point of view and hopefully provide you with some tips and tricks you can immediately put into use.  Before next time your home work assignment is to download and review the  Windows Phone 7 UI Design and Interaction Guide from Charlie Kindel.

Happy Reading

-twb

Monday, September 27, 2010

Windows Phone 7 Quick Tip #9 – Updating the Geo Location of a UIElement on a Map Layer

If you are using the Silverlight Bing Map control for Windows Phone (or for the desktop for that matter) you have the ability to add a MapLayer where you can add you controls or images at specific latitudes and longitudes.  You can really get creative and do some awesome things with a MapLayer.

Prior to SWFL Code Comp this year if I added a UIElement and needed to move it, I removed it from the original MapLayer and then added it back in at the new Lat & Lon where it should be displayed.

if (_drawLayer.Children.Contains(_myImage))
    _drawLayer.Children.Remove(_myImage);

_drawLayer.AddChild(_myImage, position, PositionOrigin.Center);

Each time I did this I had to hold my nose ‘cause this had such a bad smell to it…there had to be a better way, but I was just too busy, lazy, no I guess actually too busy to do the required research and this sort-of worked and a lot of other stuff didn’t.

After my talk this last weekend, Christopher Bennage showed me the errors of my way and schooled me how to do this correctly.

After initially adding the UIElement to the MapLayer we can simply update the position with the following chunk of code.

_myImage.SetValue(MapLayer.PositionProperty, position);

Much cleaner eh?

-twb

Saturday, September 25, 2010

OuttaGas – Materials from SWFL Code Camp Presentation

On September 25, 2010, at South West Florida Code Camp I presented a talk on a tour of some “some-what” advanced Windows Phone 7 topics.

Enjoy!

-twb

Friday, September 24, 2010

Windows Phone 7 Quick Tip #8 – Making your Images “Theme-able”

When building your Windows Phone 7 application you should be aware of the concept of themes.  I’ve got another Quick Tip coming up on using themes, however if you use the built in themes and you have any “metro” style graphics, you’ll need to make sure they work with the both built in light and dark color themes.  If you create your graphics with a white foreground so that it contrasts the ‘dark’ background on the phone, when the white or ‘light’ background is selected by the user your images will disappear.  One potential solution here is to create two graphics (both white and black ones) and then swap them out based upon the selected background color.  I don’t think any of us really likes that idea.

With the help of Bill Reiss I came up with a custom control using an OpacityMask that will allow your metro type icons to work with both the light and dark backgrounds that can be selected by the user on their phone.

Here’s the source code, simply cut-and-paste it into your project.

using System;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows;

namespace WolfBytes
{
    public class ThemeableImage : Grid
    {
        Rectangle _rectangle;

        public ThemeableImage()
        {
            _rectangle = new Rectangle();

            var bgBrush = Application.Current.Resources["PhoneBackgroundBrush"]
                               as SolidColorBrush;

            if (bgBrush.Color == Color.FromArgb(0xFF, 0xFF, 0xFF, 0xFF))
                _rectangle.Fill = new SolidColorBrush(Colors.Black);
            else
                _rectangle.Fill = new SolidColorBrush(Colors.White);

            Children.Add(_rectangle);
        }

        public ImageSource Source
        {
            get
            {
                if (_rectangle.OpacityMask != null)
                    return (_rectangle.OpacityMask as ImageBrush).ImageSource;
                else
                    return null;
            }
            set
            {
                _rectangle.OpacityMask = new ImageBrush { ImageSource = value };
            }
        }
    }
}

Then for usage simply create either a black or white (or I guess for that matter any color image) transparent PNG.  That image will then be used to either show or hide the pixels of either the Black or White background (as specified with the “PhoneBackgroundBrush” resource) based upon their opacity of the pixels in the image.

Then in your XAML you can reference the control by adding the namespace with something like:

xmlns:wb="clr-namespace:WolfBytes"

With that in place you can add the new control to your page or control with:

<wb:ThemeableImage Source="/Images/Camera.png" x:Name="CameraButton" />

Being the Silverlight MVP, Bill suggest using OpacityMasks may have an effect on the performance of your page if you are doing any animations so you may want to look at adding a bitmap cache.

-twb

Wednesday, September 22, 2010

Windows Phone 7 Quick Tip #7 – Be Aware-of and Know the work around for a Data Binding bug in RTM tools

There is a bug in the final build of the development tools for Windows Phone 7 where if you have a two-way bound TextBox in focus, and you immediately click on an ApplicationBarIconButton, the property bound with that TextBox in focus won’t get updated before the ApplicationBarIconButton event handler.  Obviously if your handler does something like persist the values from the form, this could be a real problem.  If you use a <Button> Click event handler, you are fine, the property update will take place.

Here’s a simple work-around (that I received from the grape-vine, so if you were the original creator, please let me know so I can give credit where credit is due):

Create a static method on your application class:

        public static void BindCurrentTextBox()

    {

       var textBox = FocusManager.GetFocusedElement() as TextBox;
       if (textBox != null)
       {
          var binding = textBox.GetBindingExpression(TextBox.TextProperty);
          if(binding != null)
              binding.UpdateSource();
       }
    }

 

Then right before you do something from the ApplicationBarIconButton click event, call this static method.

Not pretty, but not all-that-bad of a work-around.

-twb

GPS Simulator for Windows Phone 7

UPDATE: 12/22/2010 - This project is now posted on codeplex http://wp7gps.codeplex.com/

You want to develop applications that use the GPS on your Windows Phone 7. You may not have a physical device. Or even if you do, sometimes it’s not very convenient to test out your GPS based software by walking around with your phone. To help out with this type of development I created a very simple and crude GPS Simulator to use in your WP7 apps. There are two components to the simulator, the first is a Silverlight desktop hack job application that can be used to construct your route and sample data points. The second is a class that you include in your WP7 app called FakeGps (hmmm wonder where I got that name from?). This class implements the interface IGeoPositionWatcher<T>. This is the same one that actual GPS handler System.Device.Location.GeoCoordinateWatcher implements. This means that your code that handles the events and manipulates the GPS will remain the same.

If your app uses one of those new fangled IOC containers that work on WP7, you can probably get creative and let it handle the instantiation of the GPS handler. Being old school, I’m not convinced that IOC’s really belong on a small phone app (my design pattern for mobile development is KISS) so I create an instance based upon if the debugger is attached, something like:

IGeoPositionWatcher<GeoCoordinate> _watcher;

if (System.Diagnostics.Debugger.IsAttached)
_watcher = new FakeGps();
else
_watcher = new GeoCoordinateWatcher();

Then just use the _watcher as you normally would.

To get going with the with Simulator, here’s a brief overview of what you need to know.

Prerequisites

  1. Silverlight 4 SDK
  2. Bing Maps Silverlight Control SDK

Usage

  1. Download the files from here.
  2. Start the solution file in WolfBytes.GpsSimulator
  3. Make sure the project WolfBytes.GpsSimulator.Web is set as your startup project and the page Data.html is set as the start page.
  4. Start the project, you should see a BingMap that looks similar to this.

image

  1. You can enter the Total Run Time for your route (based upon distance, this will determine your speed).
  2. You can update the Update Period, this is how often the PositionChanged event will fire into your application.
  3. Also you can enter the Pause Before Start. This the number of milliseconds between when the user starts the GPS and the GPS starts sending PositionChanged events.
  4. Finally the XML in the bottom right quarter of your screen will be used to plug your route into your Windows Phone 7 application. (use CTRL+C to copy it after selecting it, then just replace the sample XML in FakeGps with your custom route)
  5. To add route points simply click on the map. Where a push pin is displayed, a way point will be created.

To see how to use the Simulator in your Windows Phone 7 application, just look at the project WolfBytes.GpsClient in the attached solution.

I haven’t spent a ton of time testing this, but it works for my particular problem and rather than keeping it on a shelf until I can perfect it (which will probably never happen) here it is! Enjoy it for what it is…

-twb

Monday, September 20, 2010

Windows Phone 7 Quick Tip #6 – Use InputScope to give tour users a Better Experience

Typing on a virtual keyboard sucks.  Windows Phone 7 does as a good of a job as anything out there, however you can make this even better in your applications by using the InputScope property on your TextBox controls.  This basically allows you to present a context correct keyboard.  For example, if you are having the user enter an email address, you can use an InputScope of “EmailSmtpAddress”.  The one that makes typing long text on your device so-much-easier is “Text”.  The “Text” input scope does predictive text and word correction.  If you leave InputScope blank you won’t get this nice feature.

image

To use InputScope simply add the InputScope attribute to your XAML like:

<TextBox Text=”{Binding Words}”  InputScope=”Text” />

For an awesome post describing this in much greater detail check out James Ashely’s post here.

-twb

Saturday, September 18, 2010

Windows Phone 7 Quick Tip #5 – Dismissing Popups Controls

Generally it’s not a good idea to use Popups in your Windows Phone 7 application, however just as any rule of thumb, there are exceptions.

Here’s some XAML to add the Popup to your control or page:

<Grid x:Name="LayoutRoot"  >
       <Popup x:Name="MyPopup" Width="400" Margin="20"
                  VerticalAlignment="Top" >
                   <YOUR XAML HERE>

       </Popup>
</Grid>

To show the popup:

MyPopup.IsOpen = true;

Closing the Popup is as easy as setting the IsOpen property to false.

To provide a more seamless experience to your users you may want to wire in to the hardware back button to dismiss the popup control.  You need to do this manually however it’s relatively easy to do.  What we do is override the OnBackKeyPress method in your page and set the Cancel property to true on the CancelEventArgs instance passed to your override.

protected override void OnBackKeyPress(CancelEventArgs e)
{
    if (MyPopup.IsOpen)
    {
        MyPopup.IsOpen = false;
        e.Cancel = true;
    }

    base.OnBackKeyPress(e);
}

And it’s just that simple, now if your popup is visible and the user presses the back key on the Windows Phone 7 device, instead of navigating to the previous screen, the popup will be dismissed.

Thursday, September 16, 2010

Windows Phone 7 Quick Tip #4 – Choosers and OnNavigatedTo/Loaded Methods

Here’s a tidbit of knowledge I picked up while working with the Camera Chooser.  After your application comes back from taking a picture, you can get the picture or find out the user canceled with the following chunk of code:

_cameraCaptureTask.Completed += (sender, args) =>
{
      if (args.TaskResult == TaskResult.OK)
      {
           _image = new BitmapImage();
           _image.SetSource(args.ChosenPhoto);
           CameraButton.Source = _image;
           CameraButton.Stretch = System.Windows.Media.Stretch.Uniform;
        }
};

I ran into a problem where I was initializing the page in the OnNavigatedTo overload.

It turns out for this instance this was the wrong place to do this.  The reason being the cameraCaptureTask completed and then the OnNavigatedTo method was called.  I guess this makes sense if you think about it.  I put the initialization “stuff” in the Loaded event and everyone was happy.

So the point behind this quick tip is to make sure you are initializing your page in the proper sequence.  When coming back to your page, the OnNavigatedTo method is called, but the Loaded event isn’t fired.  In addition the chooser completion event is fired before the OnNavigatedTo method is called.

Of course the big and burning question you are asking yourself is how does tombstoning come into play after a chooser is displayed and dismissed.  Stay tuned for a future Windows Phone 7 Quick Tip on the Cliff Notes for Tombstoning.

-twb

Tuesday, September 14, 2010

Windows Phone 7 Quick Tip #3 – Use a NavDictionary to pass state between pages

I’ve fallen in love with the page navigation model in Windows Phone 7, it seems very natural.  One of the challenges with this is maintaining state between pages.  In the server side equivalent, IDs are used to lookup the state as each page is served up.  This works well on the server, but can be wasteful in a client application.  Another option is to use global variables to store state…nope.

Here’s my solution, it seems to work well, but I’d be interested in hearing other approaches.

Firstly - create a simple class to maintain state between pages, this class has two methods, an Add and a Get.  The Add will add the instance to a dictionary and return an ID that can be used to pass a reference between pages.  The Get will do a lookup based upon that ID and return the instance.  In my case I decided to always remove the item up on a Get.  Your approach might be different.  Using generics makes this even cleaner.

using System;
using System.Collections.Generic;

namespace MyWP7App
{
    public class NavDictionary
    {
        private static Dictionary<Guid, object> _dictionary = new Dictionary<Guid, object>();

        public static Guid Add(object o)
        {
            var id = Guid.NewGuid();
            _dictionary.Add(id, o);

            return id;
        }

        public static T Get<T>(Guid g) where T : class       
        {
            var item = _dictionary[g] as T;

            _dictionary.Remove(g);

            return item;
        }

    }
}

Then for the implementation:

To add an item:

var id = NavDictionary.Add(myObject);

NavigationService.Navigate(new Uri(string.Format("/MyPage.xaml?id={0}", id), UriKind.Relative));

And to get the item back out, simply call the Get method in the OnNavigatedTo event (or wherever it makes sense to for your application).

var myObject = NavDictionary.Get<MyType>
                 (new Guid(NavigationContext.QueryString["id"]));

Remember my Get implementation will yank the item out of the dictionary so it can only be called once, this works and make sense for my implementation.  You need to think how your application is implemented to take into account backwards navigation and tombstoning.

-twb

Saturday, September 11, 2010

Windows Phone 7 Quick Tip #2 – Missing StringFormat Attribute

One of my favorite features introduced into Silverlight 4.0 was the ability to use StringFormat with the following syntax:

<TextBlock Text=”{Binding Cost, StringFormat=\{0:c\} }” />

This allows for a pretty much flawless implementation of data binding.

Here’s a not-so-simple, yet not-so-difficult work around.  The idea is to use value converters.

Step 1: Create a value converter as described in Tim Heuer’s post:

http://timheuer.com/blog/archive/2008/07/30/format-data-in-silverlight-databinding-valueconverter.aspx

Step 2: Rather than adding your value converter to the local user control where it’s used, add it to the App.xaml file resources, this allows for easy inclusion into anywhere within your application.  Make sure you add the namespace for the converter at the top of your app.  Then simply create a resource with a key that describes the converter.

image

Step 3: Use your value converter in the controls XAML:

<TextBlock Text=”{Binding Cost, Converter={Static Resource CurrencyConverer}” />

Obviously this isn’t as clean or as flexible as using StringFormat, however it’s not all that bad of a solution.

-twb

Tuesday, September 7, 2010

Why Windows Phone 7 Will Fail *cough* *cough*

In an effort to bridge the gap in the Smart Phone wars, I’ve developed a little tool to help all of you iPhone and Android fan-boys that are just too busy to do your own research and form your own opinion on Windows Phone 7.  You know it will fail, so here’s a tool to generate reasons you can include in your blog posts and use to sound smart when talking to your friends.

Click here for my contribution.

-twb

Saturday, September 4, 2010

Windows Phone 7 Quick Tip #1 – Use App.Resources for your Application Title

On most screens within your Windows Phone 7 application you might need to display your application name.  This might be in a simple page or one that contains a Pivot or Panorama.

Standard Page

image

Pivot Page

image

Panorama Page

image

With the XAML that gets generated you can enter your application name for the respective page types as:

image

image 

image

Notice how the same text is entered for each title as a string literal?

A better solution is to use a string resource.  To create a string resource, add the following to your Application.Resources node within the App.xaml file.

image

Then everywhere you need to use your application name you can use the following syntax

image

-twb

Windows Phone 7 – Voice and Tone

While reviewing the UI Design and Interaction Guide for Windows Phone 7 (you have looked at this haven’t you?) this morning I came across something new.  From page 192 and 193:

Many users consider text displayed on computers to be another language
called computerese, a jargon-filled, soulless, completely impenetrable for-
eign language that torments them by hindering their ability to complete
tasks and asks nonsensical questions in dialog boxes.

Windows Phone 7 banishes computerese entirely and developers should
as well. The Windows Phone 7 voice and tone should be human, clear and
consistent.

Voice refers to the personality within the text. For example, the voice of
the writer would be their overall personality expressed by what they write.
Tone is the overall mood of the text such as happy or angry. The Windows
Phone 7 tone is friendly, lighthearted, and empathic.

One method to check if text has the proper voice and tone would be to
see if it sounds like a friend assisting another friend with something on the
phone. An example would be helping them understand an error mes-
sage that appears in the application. A developer shouldn’t offer a rigid,
uninformative response when trying to explain an issue such as, “Error
Code: 4B696C626F.” Many people could be confused or frustrated by that
message, as it provides no context or potential solution. However, some-
thing such as, “There is some info missing here. Please enter your name
in the text box to move to the next page,” is clear, friendly and provides a
helpful suggestion.

It is imperative to give users a meaningful response in a casual, com-
prehensible manner. Help them fix the problem in a way that they can
understand.

Consider the string, “Synchronize the phone device.” It sounds mechanical
and stilted. Instead, “Sync your phone,” sounds much more like what
someone would tell a friend to do.

Another example is, “Schedule a calendar event for tomorrow through
Outlook.” It is neither friendly nor representative of how a friend would
speak.  An alternative could be “Set up an appointment for tomorrow in
Outlook.”

Just like a lot of other stuff in Windows Phone 7.  It seems obvious and a good idea after you hear about it.

-twb

Wednesday, September 1, 2010

Where I was when Windows Phone 7 went RTM

Something tells me that today is going to be a fairly important day in the future of mobile computing.  This is a simple place holder post to mark where I was when Windows Phone 7 was “released to manufacturing”.

Today I’m working at our Hudson place working on SeaWolf; my first significant Windows Phone App I’ll be deploying on Marketplace; and cutting some videos for the Windows Phone 7.

After being involved with Window Phone for a while I have some thoughts on where I see this going.  If we look to the past, there are some analogies.

My two-cents:

Apple iPhone –> Apple ][: The original Apple ][ knocked everyone’s socks off but the Apple brand eventually became a niche marked as a result of being such a closed environment.  I think the “jump-the-shark” moment was the Apple Lisa.  Time will tell but it might also be the iPhone 4.  Apple set a very high bar and they only way to significantly raise the bar would be for a complete make-over.  From what I can see the iPhone 4 was an evolutionary product, not a revolutionary one.  The challenge Apple will have with a complete make-over is it will no longer be an iPhone and they will have to compete for market share, but now there’s competition.  Of course there will still be a ton of loyal followers, but it won’t just be the perception that the iPhone is the only “real” mobile phone.

Android –> VIC-20, Commodore 64: The earlier computer line filled a void for folks who couldn’t afford or didn’t want an apple.  However as time went on and technology/expectations advanced it was fairly clear that the Commodore 64 had some limiting factors that diminished its long term staying power.  After spending some significant time with the android devices, I’m seeing a lot of the same mistakes that Windows Mobile made over the past 4-5 years being repeated.  Android is not going away, but I think we’ve seen the peek of the popularity of the platform.

Windows Mobile 6.X: Not at all a bad operating system, designed and built in very different world from that which we currently live in.  When I show people my HTC HD2 and ask to compare it to their iPhone or Android phone, it’s really a shocking comparison.  The HD2 easily holds its own.  For a number of reasons I won’t get into here (and very few of them technical) the bottom line is that no-one wants Windows Mobile devices.

Of course that leaves the Blackberry users, a very loyal bunch, but I’m just not seeing much in the way of innovation coming from that camp.  Time will tell, however I think from a usage scenario standpoint, Windows Phone 7 will go a long ways to provide a very competitive offering to Blackberry users.

So my point is basically that it won’t be an easy ride, however the battle for a clear winner of the mobile space is far from over.  Windows Phone 7 is a real contender to establish a leadership position in the future.

Good luck and congratulations to everyone that helped get us to this point and I look forward to doing everything I can to help make Windows Phone 7 a success.

-twb