Trying to learn Windows Phone development at the same time as trying to understand how to implement the MVVM pattern is a bit challenging. So my focus is on the following objectives of MVVM:

  • View has a single ViewModel.
  • View binds to the ViewModel’s Notifiable properties and Observable collections for data.
  • View binds its behaviors to ViewModel’s ICommand implementations.
  • View subscribes to ViewModel messages for navigation.
  • ViewModel is unaware of view.
  • ViewModel is responsible for state persistance.

I looked at a number of canned solutions for MVVM such as “MvvmLight”, “Prism” and others.  I’m in no position to judge which is best for me until I can actually grasp what it is they do.  And to do that I need to try to work out solutions to these objective myself, with a little help-by-example.

So to start, the following is my implementation of “commanding”.  The objective is to use a control’s behaviors rather than events and to implement these behaviors in the view model rather than the code-behind. There are a number of reasons to do this, least of which is testing your logic without the need for a view.

The following is the CommandHandler class.  It implements the ICommand interface needed by a controls Command property (or an Interaction’s Trigger).

    public class CommandHandler : ICommand
    {
        private Action<object> execAction;
        private Func<object, bool> canExecFunc;

        public CommandHandler(Action<object> execAction)
        {
            this.execAction = execAction;
        }

        public CommandHandler(Action<object> execAction, Func<object, bool> canExecFunc)
        {
            this.execAction = execAction;
            this.canExecFunc = canExecFunc;
        }

        public bool CanExecute(object parameter)
        {
            if (canExecFunc != null)
                return canExecFunc.Invoke(parameter);
            else
                return true;
        }

        public event System.EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            if (execAction != null)
                execAction.Invoke(parameter);
        }

        public void OnCanExecuteChanged()
        {
            if (CanExecuteChanged != null)
            {
                foreach (var v in CanExecuteChanged.GetInvocationList())
                {
                    try
                    {
                        v.DynamicInvoke(this, new EventArgs());
                    }
                    catch { }
                }
            }
        }
    }

To use this class the view model needs to provide the following implementation:

        private CommandHandler someButtonCommand;
        public ICommand SomeButtonCommand
        {
            get
            {
                if (someButtonCommand == null)
                    someButtonCommand = new CommandHandler(new Action<object>((object parm) =>
                    {
                        // execute actions for this command...

                    }), new Func<object,bool>((object parm)=>
                    {
                        // optionally provide feeback to the control
                        // as to the state of this command.
                        return true;
                    }));

                return someButtonCommand;
            }
        }

In this example the command handler implements both the execute action and the optional canExecute function.  In the XAML the binding looks like this:

        <Button Content="Do It" Command="{Binding SomeButtonCommand, Mode=OneWay}" />

By binding the control’s Command property to the ICommand  property of the view model you delegate command execution to the view model.  In addition, the button control automatically subscribes to the CanExecuteChanged event of the handler making is very simple to disable the control when ever the view model decides that the command is not appropriate.  This can be accomplished when the control invokes the CanExecute delegate or when the view model proactively invokes the OnCanExecuteChanged method of the handler. In either case, the CanExecute  will return either true or false indicating the state of the command and ultimately the enabled state of the bound control.

For controls that don’t have the Command property you can still bind their behaviors by using Interaction Triggers.  The following is an example of how to bind the SelectionChanged event of a ListBox to the view model using the same implementation approach as before.

         <ListBox Name="listBox1" >
             <i:Interaction.Triggers>
                <i:EventTrigger EventName="SelectionChanged">
                    <i:InvokeCommandAction Command="{Binding ItemSelectedCmd, Mode=OneWay}"/>
                </i:EventTrigger>
             </i:Interaction.Triggers>
         </ListBox>
 

Get your free Lumia 900 while they last.

I got my $99 Lumia 900 Windows phone on Monday.  While playing around with all of the settings and pre-installed apps everything appeared to be working great.  Of course the whole time I was doing this I was at home… on WiFi.   So I finally got around to trying the hot spot feature or what WP7 calls “Internet Sharing”.  Suddenly things weren’t going so well.  Trying to share my Internet connection resulted in persistent error popups telling me that my cellular data connection was down.  Same thing happened when I tried to browse or email while on cellular.  Hmmm.. Wifi working great, phone and text working great, just no Internet through the so called “blazing fast 4G” connection.

After three hours on the phone with various AT&T support representatives the end result was, “take the phone back to where you bought it and get another one.”  Okay, I guess that can happened. This wouldn’t be the first time I bought something that was broke out of the box.  Then about an hour later I came across this:

Nokia Offers Lumia 900 Exchange, Credits as Problem Surfaces

Yup, this is what happened to me.  I have the “data  problem”.  So bottom line, I just got a free phone in exchange for a little patience. And the best part is that you can too,  even if you haven’t purchased one yet.  All you have to do is order one before April 21 and you will get the $100 credit as well.  So anyone can get one of these great phones for free.  Truly an awesome and timely gesture from Nokia.  Nothing like coming clean right away, no “antennae gate” here!

Bottom line,  especially if you are a Windows developer, this is a great phone with a liberating user interface and awesome inter-app integrations that make learning how to use this phone as easy as getting one for free!

Here is the link from the Nokia blog explaining the issue and their offer…

Apr 012012
 

Happy birthday to me I have an iPad 3!

After a couple of years with the old iPad I was ready to throw it against a wall.  After 3 or 4 IOS updates and dozens of app updates my old iPad just couldn’t keep up.  So for my birthday I decided to upgrade.

My first impression was, wow, just like my old iPad the day I first got it— fast! But of course that’s pretty much were the comparison ends.   So far I’m majorly impressed with performance and battery life.  Altough I haven’t done a full charge yet I can tell that the life is going to be about the same as before, at least a full day’s worth of use.

The high-res display is excellent.  I think I notice that more with text than anything  else so far.  Everything is just clearer and more distinct.  I’ve been spending  most of today in my Kindle app because it’s just so much more enjoyable than before.

This time I picked up a keyboard cover as well.  I’m writing this using the keyboard and I love it!  Don’t know why I waited so long.

I did discover the camera app and was making movies ealier today of the dogs.  Excellent resolution/frame rate for an iPad, not bad at all.  Stills were great too.

More later….

 

Recently I worked on an application for streaming image data from a Windows PC to an iPad.  The image data consisted for a series of bitmapped images (in PNG format).  Essentially I was transmitting a window’s UI from my PC to my iPad and as the window updated on the PC I wanted to send just those updated areas to my iPad.  So in the end, the composite image on the iPad would mirror the window on my PC in real-time. To make this usable I needed to be able to maintain a data rate of several frames per second.

The first challenge I faced was figuring out the best way to drive the display processing on the iPad.  I needed a way to quickly update the iPad UI as new image data arrived.  I initially thought I would have to write a custom UIView and override the DrawRect method.  I actually started down this path but got stuck on how to force the iPad to update the screen on demand as data arrived.  There were some methods to support this such as SetNeedsDisplayInRect however they weren’t reliable.
After some trial and error I abandoned the custom UIView approach and went back to a previously rejected idea of just using the UIImageView class.  Originally I thought this view was only good for displaying static image data (and/or animations).  The UIImageView class has an Image property that you set to your desired image and when the view does its drawing it displays your image.  What I didn’t know was that anytime you set this property the UIImageView will automatically update the screen immediately… which was exactly what I needed.
 

Although the .NET TcpClient class provides timeout settings for sending and receiving data there is no timeout for the actual connection process itself. This can be frustrating because the method call to Connect can hang forever if the target host is not reachable or just not responding.

Below is a simple solution to handling this issue by using the asynchronous BeginConnect method within a standard synchronous process.  By passing a null as the callback method you can handle the completion event in-line by waiting on the async result.

TcpClient client = new TcpClient ();
IAsyncResult result = client.BeginConnect (addresses[0], serverPortNumber, null, null);

// wait 10 seconds for the connection to complete

if (!result.AsyncWaitHandle.WaitOne (10000, true))
{

    Console.WriteLine (&quot;Connection timed out.&quot;);
    //.....throw an exception, exit or return ...

}
else
{
    client.EndConnect (result);
    Console.WriteLine (&quot;Connected successfully.&quot;);
}

//.....You now have a connection... proceed to send/recv...
© 2012 blog@johnthom.com Suffusion theme by Sayontan Sinha