Nico's digital footprint

I grew up in the nineties, that makes me awesome by default

Grid column behavior–Xamarin XAML vs MS XAML

by Nico

There’s a small detail difference in how rows and columns in a Grid behave in Xamarin Forms vs Microsoft XAML. A small difference but with quite a big impact. Look at the following XAML snippet (Microsoft XAML)

Code Snippet
  1. <Grid Background="Red">
  2.     <Grid.RowDefinitions>
  3.         <RowDefinition Height="50" />
  4.         <RowDefinition Height="*" />
  5.     </Grid.RowDefinitions>
  6.  
  7.     <Grid Grid.Row="1" Background="Blue">
  8.         <Grid.RowDefinitions>
  9.             <RowDefinition Height="Auto" />
  10.             <RowDefinition Height="300" />
  11.         </Grid.RowDefinitions>
  12.     </Grid>
  13. </Grid>

At runtime this looks like:

Exactly what we as seasoned XAML developers would expect.

Converted to Xamarin Forms XAML this turns into:

Code Snippet
  1. <Grid BackgroundColor="Red">
  2.   <Grid.RowDefinitions>
  3.     <RowDefinition Height="50" />
  4.     <RowDefinition Height="*" />
  5.   </Grid.RowDefinitions>
  6.   
  7.   <Grid Grid.Row="1" BackgroundColor="Blue">
  8.     <Grid.RowDefinitions>
  9.       <RowDefinition Height="Auto" />
  10.       <RowDefinition Height="300" />
  11.     </Grid.RowDefinitions>
  12.   </Grid>
  13. </Grid>

Only difference is the property name to set the background color. However, if we look at this at runtime we see a completely different story.

It looks like the inner Grid isn’t rendered at all. But let’s try to add a Label to the inner Grid.

Code Snippet
  1. <Grid BackgroundColor="Red">
  2.   <Grid.RowDefinitions>
  3.     <RowDefinition Height="50" />
  4.     <RowDefinition Height="*" />
  5.   </Grid.RowDefinitions>
  6.   
  7.   <Grid Grid.Row="1" BackgroundColor="Blue">
  8.     <Grid.RowDefinitions>
  9.       <RowDefinition Height="Auto" />
  10.       <RowDefinition Height="300" />
  11.     </Grid.RowDefinitions>
  12.     <Label Text="Hello Xamarin!" />
  13.   </Grid>
  14. </Grid>

So what exactly is going on here? The inner Grid (the blue one) doesn’t specify any columns, that means that by default there’s only one column available. In Microsoft XAML the width of that default column is set to “*” so it takes up all available space. In Xamarin Forms that width is set to “Auto” so it only takes up the space it needs. A subtle difference with a big impact.

To fix this, add a column with “*” as width

Code Snippet
  1. <Grid BackgroundColor="Red">
  2.   <Grid.RowDefinitions>
  3.     <RowDefinition Height="50" />
  4.     <RowDefinition Height="*" />
  5.   </Grid.RowDefinitions>
  6.   <Grid.ColumnDefinitions>
  7.     <ColumnDefinition Width="*" />
  8.   </Grid.ColumnDefinitions>
  9.   
  10.   <Grid Grid.Row="1" BackgroundColor="Blue">
  11.     <Grid.RowDefinitions>
  12.       <RowDefinition Height="Auto" />
  13.       <RowDefinition Height="300" />
  14.     </Grid.RowDefinitions>
  15.  
  16.   </Grid>
  17. </Grid>

result:

Conclusion

In this post I’ve shown a difference in implementation between Xamarin Forms XAML and Microsoft XAML and how to fix it.

Note that this sample is based on Xamarin Forms 1.2. Xamarin has stated that they will change the implementation in Forms 1.3 to reflect the Microsoft implementation.


Tags:

XAML | WinRT | WP8 | WPF | Xamarin

A practical guide to MVVM (Light)–Part 2

by Nico

A practical guide to MVVM (Light) – Part 1

In part 1 I’ve shown you how to setup a new Windows Phone project with MVVM Light, how to hookup everything and we’ve seen what databinding is and how it works. In this part we’re going to build on that same project, delving a bit deeper into MVVM in a practical way.

Intro

In part 2 we’ll have a look at how to navigate from a list page, like the one we’ve created in part 1, to a detail page. We’ll need to inform the viewmodel on what item was clicked so that it can fetch more detailed information from the datastore. We’ll also have a look at value converters, a feature not really MVVM related but one that’s really important so I’m including it here anyway.

Navigation

There are a few ways to get navigation done in a Windows Phone app. You can use a NavigationService class for example. A class that can get injected via SimpleIoc and that has a .Navigate function, the Cimbalino Toolkit has one build-in for example. One other way to do navigation without delving into code-behind code in the view is by using Behaviors and Actions in XAML. Don’t worry, you don’t need to remember the exact syntax as long as you have Blend.

Open up the MainPage.xaml of our Part 1 project in Blend and have a look at the Assets Tab. (Quick tip: if you want to open a certain page in Blend, right-click it in Visual Studio and select “Open in Blend”, this also works for opening a page from Blend in Visual Studio).

In the Behaviors section you’ll find a bunch of Actions and Behaviors. An interesting one here is the NavigateToPageAction, drag and drop that one onto the ListBox. You’ll notice that the Action has attached itself to the ListBox if you have a look at the Objects & Timeline pane.

Before we can navigate we need to create a new page, add a page called DetailPage.xaml to the View folder of the project. Creating the page can be done from either Blend or Visual Studio. After creating the DetailPage, go back to MainPage in Blend and select the NavigateToPageAction that’s attached to the Listbox in the Objects & Timeline pane. Go to the properties.

You’ll see here that the action contains a trigger. There we can select what event from the Listbox will trigger the action, set this to SelectionChanged. In the dropdown for TargetPage you should see MainPage and DetailPage (and any other pages you might have created), set it to DetailPage and run the app. Click on an item and you’ll see that the app navigates to the detailpage. This is what the action looks like in XAML.

Code Snippet
  1. <ListBox ItemTemplate="{StaticResource PersonTemplate}" ItemsSource="{Binding Persons}">
  2.     <i:Interaction.Triggers>
  3.         <i:EventTrigger EventName="SelectionChanged">
  4.             <ec:NavigateToPageAction TargetPage="/View/DetailPage.xaml" />
  5.         </i:EventTrigger>
  6.     </i:Interaction.Triggers>
  7. </ListBox>

Loading detailed data for clicked item

When we select an item we navigate to a detail page. It would be nice to effectively show all the details. When using a ListBox this is pretty easy. We can just define a property on the viewmodel and bind the ListBox’s SelectedItem property to the property on the viewmodel. The property could look something like this

Code Snippet
  1. public Person SelectedPerson
  2. {
  3.     get { return _selectedPerson; }
  4.     set
  5.     {
  6.         if (_selectedPerson == value) return;
  7.         _selectedPerson = value;
  8.         RaisePropertyChanged(() => SelectedPerson);
  9.         LoadDetails();
  10.     }
  11. }

The binding on the ListBox would look like this

Code Snippet
  1. <ListBox ItemTemplate="{StaticResource PersonTemplate}
  2.          ItemsSource="{Binding Persons}"
  3.          SelectedItem="{Binding SelectedPerson,
  4.                                 Mode=TwoWay}">

Notice that we have to specify that this is a two-way binding. If we don’t, the property will not get updated from the view. Databinding by default is OneWay, from the viewmodel to the view.

While this is a valid way of working, it has some issues.

  • LongListSelector doesn’t support binding to SelectedItem (I described workarounds for this here and here)
  • The DetailPage needs to have MainViewModel as datacontext, which is possible and allowed but often this means that a viewmodel turns into a superclass that handles the datacontext for every view.

On to the next possibility we go!

EventToCommand

The way of passing the selecteditem from the view to the viewmodel and to the next viewmodel I’m about to describe takes a bit more setup than the previous part. However, while it is a bit more work, it’s my preferred way of working. To me this feels like the “MVVM way” but use whatever feels most comfortable for you.

Go into Blend and delete the NavigateToPageAction that is still attached to the ListBox. Go back to the Assets pane, to the list of Behaviors. You’ll find that in the list is an EventToCommand behavior. This allows us to hook up events fired by controls in the view to trigger certain actions on the viewmodel. Drag & drop the EventToCommand onto the ListBox.

Before specifying the target command for the behavior, we’ll have to add one to the viewmodel first. Windows Phone has an interface called ICommand that we can use for binding. MVVM Light comes with two implementations of ICommand called RelayCommand and RelayCommand<T>. We’re going to use the generic version RelayCommand<T> because this way we can get the event arguments into our viewmodel.

Code Snippet
  1. private RelayCommand<SelectionChangedEventArgs> _selectionChangedCommand;
  2.  
  3. public RelayCommand<SelectionChangedEventArgs> SelectionChangedCommand
  4. {
  5.     get
  6.     {
  7.         return _selectionChangedCommand ??
  8.                (_selectionChangedCommand = new RelayCommand<SelectionChangedEventArgs>(OnSelectionChanged));
  9.     }
  10. }

When using the generic version of RelayCommand we specify the type of T as the type of eventargs we’re expecting. Note that this can also be a string that’s passed in as commandparameter for example when binding to a button’s command property.

SIDENOTE – the ?? operator: If you’ve never seen the ?? operator before, it checks if whatever’s on its leftside is not null, if it is it executes whatever’s on its rightside. In this case the rightside will only get executed the very first time the command is called, that’s when the private field is instantiated.

the parameter passed into the RelayCommand<T> constructor is the action that we’ll be executing when the command is called.

Code Snippet
  1. private void OnSelectionChanged(SelectionChangedEventArgs args)
  2. {
  3.     throw new System.NotImplementedException();
  4. }

We’ll complete this in a minute, just leave it like this to make the application compile.

Bind the EventToCommand Command property to the RelayCommand either through Blend or in XAML. Make sure to check the PassEventArgsToCommand checkbox when going via Blend. This is what the XAML should look like.

Code Snippet
  1. <ListBox ItemTemplate="{StaticResource PersonTemplate}"
  2.     ItemsSource="{Binding Persons}">
  3.     <i:Interaction.Triggers>
  4.         <i:EventTrigger EventName="SelectionChanged">
  5.             <Command:EventToCommand PassEventArgsToCommand="True" Command="{Binding SelectionChangedCommand, Mode=OneWay}"/>
  6.         </i:EventTrigger>
  7.     </i:Interaction.Triggers>
  8. </ListBox>

No more SelectedItem binding. If we place a breakpoint in the OnSelectionChanged method and check the parameter you should see the selected item in there.

So far, we’re using the controls their events, using a behavior to pass the eventhandler to a command on our ViewModel. No code behind required, clean MVVM setup. The next step is to navigate to another page and pass the selected item to another viewmodel. Let’s start by navigating.

Navigating via the ViewModel

I’ve mentioned before that navigating from within the viewmodel can be done by using a NavigationService. It’s time to do just that. A NavigationService is not included in Windows Phone so we’ll either need to write one or use an existing one. I’m going to do the latter and use an existing one.

Use either NuGet or the Package manager console to add the Cimbalino Windows Phone toolkit to the project

Install-Package Cimbalino.Phone.Toolkit

Now it’s time to revisit the ViewModelLocator. Remember SimpleIoc? We used the ViewModelLocator to register services and use constructor injection to inject those services into our viewmodels. First add a using statement to the ViewModelLocator

Code Snippet
  1. using Cimbalino.Phone.Toolkit.Services;

Next, register the NavigationService in SimpleIoc. (line 14)

Code Snippet
  1. public ViewModelLocator()
  2. {
  3.     ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
  4.  
  5.     if (ViewModelBase.IsInDesignModeStatic)
  6.     {
  7.         // Create design time view services and models
  8.         SimpleIoc.Default.Register<IDataService, DesignDataService>();
  9.     }
  10.     else
  11.     {
  12.         // Create run time view services and models
  13.         SimpleIoc.Default.Register<IDataService, DataService>();
  14.         SimpleIoc.Default.Register<INavigationService, NavigationService>();
  15.     }
  16.  
  17.     SimpleIoc.Default.Register<MainViewModel>();
  18. }

Back to the MainViewModel, we add a new parameter to its constructor.

Code Snippet
  1. private INavigationService _navigationService;
  2. public MainViewModel(IDataService dataService, INavigationService navigationService)
  3. {
  4.      _navigationService = navigationService;

Using the NavigationService is pretty easy.

Code Snippet
  1. private void OnSelectionChanged(SelectionChangedEventArgs args)
  2. {
  3.     _navigationService.NavigateTo("/View/DetailPage.xaml");
  4. }

Do be careful with the path to the page, it’s a string so no intellisense. If the page is in a folder make sure to start with “/”. Run the app, click an item. The app should navigate to the DetailPage, just like we had before. Time to add the PersonViewModel. Add a class named PersonViewModel and make it inherit ViewModelBase, that’s enough for now.

Every new viewmodel in an MVVM Light application needs to be added to the ViewModelLocator. We need to register the viewmodel in SimpleIoc and create a property to allow databinding. First register the viewmodel in the ViewModelLocator’s constructor

Code Snippet
  1. SimpleIoc.Default.Register<PersonViewModel>();

Next is the property

Code Snippet
  1. public PersonViewModel Person
  2. {
  3.     get
  4.     {
  5.         return ServiceLocator.Current.GetInstance<PersonViewModel>();
  6.     }
  7. }

Now we can set the DetailPage’s datacontext to the PersonViewModel by adding this to the opening tag of the page.

Code Snippet
  1. DataContext="{Binding Person,
  2.                       Source={StaticResource Locator}}"

For your reference, here’s the complete tag

Code Snippet
  1. <phone:PhoneApplicationPage x:Class="MvvmDemo.View.DetailPage"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  5. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  6. xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
  7. xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
  8. DataContext="{Binding Person,
  9.                       Source={StaticResource Locator}}"
  10. FontFamily="{StaticResource PhoneFontFamilyNormal}"
  11. FontSize="{StaticResource PhoneFontSizeNormal}"
  12. Foreground="{StaticResource PhoneForegroundBrush}"
  13. Orientation="Portrait"
  14. SupportedOrientations="Portrait"
  15. shell:SystemTray.IsVisible="True"
  16. mc:Ignorable="d">

Messaging

Now that we have two viewmodels, we need to setup a form of communication between them. Luckily for us, MVVM Light has something in place for this called the Messenger. The Messenger is a class that receives and delivers messages. One viewmodel subscribes for a certain message, the other viewmodel sends a message and the messenger makes sure it gets delivered nicely. The messenger can take any type and send it as a message, we could for example send an entire person, or the ID of a person and send it as an integer. But in a bigger app this could get complicated, imagine if 5 viewmodels start listening for integers but one is expecting the id of a product, another one expects the id of a person while a third one expects a result of some sorts. It would be a lot of work to get the subscribe / unsubscribe just right. That’s why I advice you to make it a habit to encapsulate the data in a special message class. Like for example to send our selected person over to the PersonViewModel.

Code Snippet
  1. public class PersonSelectedMessage : MessageBase
  2. {
  3.     public Person SelectedPerson { get; set; }
  4.     public PersonSelectedMessage(Person selectedPerson)
  5.     {
  6.         SelectedPerson = selectedPerson;
  7.     }
  8. }

As you can see, this is a really simple class with only one purpose: encapsulate a Person instance. The MessageBase baseclass is an MVVM Light class that contains some info about the sender and the target but I use this mainly to make the classes easier to recognize as MVVM Light messages. I also place all those message classes in a Messages folder in my project.

Let’s subscribe to this type of message from the PersonViewModel. First add a Person property to the PersonViewModel that we can bind to.

Code Snippet
  1. private Person _selectedPerson;
  2.  
  3. public Person SelectedPerson
  4. {
  5.     get { return _selectedPerson; }
  6.     set
  7.     {
  8.         if (_selectedPerson == value) return;
  9.  
  10.         _selectedPerson = value;
  11.         RaisePropertyChanged(() => SelectedPerson);
  12.     }
  13. }

Then add this in the PersonViewModel constructor.

Code Snippet
  1. public PersonViewModel()
  2. {
  3.     Messenger.Default.Register<PersonSelectedMessage>(this, msg =>
  4.     {
  5.         SelectedPerson = msg.SelectedPerson;
  6.     });
  7. }

This registers our current instance of PersonViewModel to receive messages of the PersonSelectedMessage type. We will send this message from the MainViewModel in the OnSelectionChanged method that fires when selecting a person in the ListBox.

Code Snippet
  1. private void OnSelectionChanged(SelectionChangedEventArgs args)
  2. {
  3.     _navigationService.NavigateTo("/View/DetailPage.xaml");
  4.     Messenger.Default.Send(new PersonSelectedMessage(args.AddedItems[0] as Person));
  5. }

If you set a breakpoint in the action that fires when a message arrives and try to select a person the first time it will probably fail. This is because the message departs before the PersonViewModel has had a chance to initialize and register for the message, it will be sent but it will never arrive. If you hit the back key back to the MainPage and select another person it will arrive because the PersonViewModel instance already exists and is listening to the message. The quickest (and easiest) way to fix this is to make sure that PersonViewModel is initialized when the app launches. We can use an overload of SimpleIoc’s register method for this.

In the ViewModelLocator, add true as a parameter to the registration

Code Snippet
  1. SimpleIoc.Default.Register<PersonViewModel>(true);

This will initialize the class at the moment of registration and it will register itself as a subscriber for the PersonSelectedMessage. After binding the page title to SelectedPerson.Name and running the app this is the result:

If this was a real application you would use the action of the messenger to fetch the detailed information of the selected item. DataBinding takes care of displaying the data on screen.

Conclusion

In this second part of my practical guide to MVVM Light I’ve discusses the way I usually work to select an item from a list, navigate to a detail page and fetch / show detailed information.

Some more MVVM related articles:

Some more in depth IOC/DI articles:

Feel free to ping me on Twitter (@NicoVermeir) should you have any questions.

The code for this second part can be found on OneDrive.


Tags:

.Net | Binding | MVVM Light | Metro | Silverlight | WP7 | WP8 | WPF | WinRT | Windows 8 | XAML

WP8 as bluetooth Start button

by Nico

If you’ve ever used applications like the Office Remote that seem to take over your computer you’ll know that it can provide quite the “magic” experience. As with all magic technologies this one is quite simple as well. All we need is a computer with Bluetooth that runs a small app with a Bluetooth listener and a Windows Phone app that connects to that listener app via Bluetooth. For this demo app I’m going to make the Windows Phone app act like the Start button on a Windows machine.

Simulating the Windows key

The listener application is a small WPF app that has only one button. That button will act like the Start button. To interact with the operating system and simulate a keyboard press we’ll need to import user32.dll and hook into its keybd_event. We’ll want to send ctrl + esc to Windows (acts the same as the Windows key)

Code Snippet
  1. //source: http://www.codeproject.com/Questions/46731/Open-Start-Menu
  2. private static void ShowStartMenu()
  3. {
  4.     // key down event:
  5.     const byte keyControl = 0x11;
  6.     const byte keyEscape = 0x1B;
  7.     keybd_event(keyControl, 0, 0, UIntPtr.Zero);
  8.     keybd_event(keyEscape, 0, 0, UIntPtr.Zero);
  9.  
  10.     // key up event:
  11.     const uint keyeventfKeyup = 0x02;
  12.     keybd_event(keyControl, 0, keyeventfKeyup, UIntPtr.Zero);
  13.     keybd_event(keyEscape, 0, keyeventfKeyup, UIntPtr.Zero);
  14. }
  15.  
  16. [DllImport("user32.dll")]
  17. static extern void keybd_event(byte bVk, byte bScan, uint dwFlags,
  18.    UIntPtr dwExtraInfo);

In the event handler of the button we call ShowStartMenu() and behold: a wild software Windows key appears!

Building the Bluetooth listener

Adding Bluetooth support to a .NET application isn’t the easiest thing to do. Luckily for us there are libraries out there that take out the hassle. For this project I used Peter Foot’s 32feet.NET library available through NuGet

Install-Package 32feet.NET

A small note on this package as found on the 32feet.NET product page

“Bluetooth support requires a device with the Microsoft or Widcomm Bluetooth stack”

Luckily for me, my device uses the Microsoft BT stack, so I’m good to go. Now on to the code, we’ll need to start a BT listener and once connected read data from a networkstream. If we receive a certain message we’ll execute the ShowStartMenu() method.

First some fields

Code Snippet
  1. private BluetoothListener _listener;
  2.  
  3. //unique service identifier
  4. private readonly Guid _service = new Guid("{7A51FDC2-FDDF-4c9b-AFFC-98BCD91BF93B}");
  5. private bool _connected;

BluetoothListener is a class we get from 32feet.NET. The GUID is a reference to the service this app is providing, our Windows Phone app will need the same GUID to be able to connect to this service. And the third field is a boolean to keep track of having a connected client or not.

Code Snippet
  1. private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
  2. {
  3.     BluetoothRadio br = BluetoothRadio.PrimaryRadio;
  4.  
  5.     if (br == null)
  6.     {
  7.         MessageBox.Show("No supported Bluetooth radio/stack found.");
  8.     }
  9.     else if (br.Mode != RadioMode.Discoverable)
  10.     {
  11.         MessageBoxResult rslt = MessageBox.Show("Make BluetoothRadio Discoverable?",
  12.             "Bluetooth Remote Listener", MessageBoxButton.YesNo);
  13.  
  14.         if (rslt == MessageBoxResult.Yes)
  15.         {
  16.             br.Mode = RadioMode.Discoverable;
  17.         }
  18.     }
  19.  
  20.     _listener = new BluetoothListener(_service);
  21.     _listener.Start();
  22.  
  23.     System.Threading.Thread t = new System.Threading.Thread(ListenLoop);
  24.     t.Start();
  25. }

In the OnLoaded event from the MainWindow we’ll first check if there’s a BT radio found that works on the MS or Widcomm stack. If that’s found, and made discoverable, we’ll start the listener with the service GUID specified in the field. Once the listener is started we fire up a second thread that will contain a loop to connect a client and read data from the stream.

Code Snippet
  1. private void ListenLoop()
  2. {
  3.     byte[] buffer = new byte[1024];
  4.  
  5.     while (true)
  6.     {
  7.         BluetoothClient bc;
  8.         Stream ns;
  9.  
  10.         try
  11.         {
  12.             bc = _listener.AcceptBluetoothClient();
  13.             ns = bc.GetStream();
  14.             _connected = true;
  15.         }
  16.         catch
  17.         {
  18.             break;
  19.         }
  20.  
  21.         //keep connection open
  22.         while (_connected)
  23.         {
  24.             try
  25.             {
  26.                 int received = ns.Read(buffer, 0, buffer.Length);
  27.  
  28.                 if (received > 0)
  29.                 {
  30.                     string data = Encoding.UTF8.GetString(buffer);
  31.  
  32.                     string command = data.Substring(0, data.IndexOf("\0", StringComparison.Ordinal));
  33.  
  34.                     if (command == "Start")
  35.                     {
  36.                         ShowStartMenu();
  37.                     }
  38.                 }
  39.                 else
  40.                 {
  41.                     //connection lost
  42.                     _connected = false;
  43.                 }
  44.             }
  45.             catch
  46.             {
  47.                 _connected = false;
  48.                 break;
  49.             }
  50.         }
  51.  
  52.         try
  53.         {
  54.             bc.Close();
  55.         }
  56.         catch
  57.         {
  58.         }
  59.     }
  60. }

This is the code for the loop that runs in the second thread. First we declare a buffer of 1KB, more than enough for this sample. Next we start an infinite loop, in that loop we declare a BluetoothClient and a Stream. Once a client connects through the AcceptBluetoothClient method we fetch a stream and set the connected flag to true. As long as we’re connected we read data from the stream into the buffer, once we receive actual data we’ll decode it from a byte array (the buffer) into a string (the original message). In this sample the message will be 5 bytes but the buffer can hold 1024 bytes. It will fill up the remaining bytes with “\0” so we’ll need to chop that of with a Substring. If the received string is “Start” we’ll flip to the Start screen. If we read from the stream but the number of received bytes is zero, we’ve lost the connection to the client.

Fire up the WPF app, make sure the button flips you to the Start screen and let’s get started on the WP8 app!

Windows Phone Client

The Windows Phone app consists of two pages. The MainPage is for selecting a Bluetooth peer to connect to and the ConnectedPage has the same button as the WPF application. The app uses MVVM Light, everything happens in the MainViewModel. Both the MainPage and ConnectedPage use MainViewModel as their datacontext. For navigation I’ve added the always helpful Cimbalino NuGet package and registered their NavigationService in SimpleIoc through the ViewModelLocator

Code Snippet
  1. public ViewModelLocator()
  2. {
  3.     ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
  4.  
  5.     if (ViewModelBase.IsInDesignModeStatic)
  6.     {
  7.         // Create design time view services and models
  8.     }
  9.     else
  10.     {
  11.         // Create run time view services and models
  12.         SimpleIoc.Default.Register<INavigationService, NavigationService>();
  13.     }
  14.  
  15.     SimpleIoc.Default.Register<MainViewModel>();
  16. }

In the MainViewModel I have declared three properties

Code Snippet
  1. private ObservableCollection<PeerInformation> _peers;
  2. private PeerInformation _selectedPeer;
  3. private ICommand _goToStartCommand;
  4.  
  5. public ICommand GoToStartCommand
  6. {
  7.     get { return _goToStartCommand ?? (_goToStartCommand = new RelayCommand(SendCommand)); }
  8. }
  9.  
  10. public ObservableCollection<PeerInformation> Peers
  11. {
  12.     get { return _peers; }
  13.     set
  14.     {
  15.         if (_peers == value) return;
  16.  
  17.         _peers = value;
  18.         RaisePropertyChanged(() => Peers);
  19.     }
  20. }
  21.  
  22. public PeerInformation SelectedPeer
  23. {
  24.     get { return _selectedPeer; }
  25.     set
  26.     {
  27.         if (_selectedPeer == value) return;
  28.  
  29.         _selectedPeer = value;
  30.         RaisePropertyChanged(() => SelectedPeer);
  31.  
  32.         ConnectToDevice();
  33.     }
  34. }

The PeerInformation class is something we get from the Windows Phone Bluetooth API. We have an observablecollection that will hold all peers that are known for your Windows Phone device, we also have a property for the selected peer and a command that will fire a message into the NetworkStream.

We’ll also need some fields

Code Snippet
  1. private StreamSocket _socket;
  2. private DataWriter _dataWriter;
  3.  
  4. private readonly INavigationService _navigationService;

The socket will hold the connection between the phone app and the WPF app. The DataWriter can write data into the stream. The NavigationService is the one from the Cimbalino toolkit.

Here’s the constructor for the MainViewModel

Code Snippet
  1. public MainViewModel(INavigationService navigationService)
  2. {
  3.     if (IsInDesignModeStatic) return;
  4.  
  5.     _navigationService = navigationService;
  6.  
  7.     if (Microsoft.Devices.Environment.DeviceType == Microsoft.Devices.DeviceType.Emulator)
  8.     {
  9.         MessageBox.Show("Bluetooth not available in the emulator");
  10.     }
  11.     else
  12.     {
  13.         RefreshPairedDevicesList();
  14.     }
  15. }

The NavigationService is injected via SimpleIoc. First we check if the current device is the Windows Phone emulator, the emulator doesn’t support Bluetooth so we need an actual device to test this on.

The RefreshPairedDevicesList looks like this (all using the Windows Phone Bluetooth APIs)

Code Snippet
  1. private async void RefreshPairedDevicesList()
  2. {
  3.     try
  4.     {
  5.         // Search for all paired devices
  6.         PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
  7.         var peers = await PeerFinder.FindAllPeersAsync();
  8.  
  9.         Peers = new ObservableCollection<PeerInformation>(peers);
  10.     }
  11.     catch (Exception ex)
  12.     {
  13.         if ((uint)ex.HResult == 0x8007048F)
  14.         {
  15.             if (MessageBox.Show("Bluetooth is off, enable it?",
  16.                 "Bluetooth Off", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
  17.             {
  18.                 ConnectionSettingsTask connectionSettingsTask = new ConnectionSettingsTask
  19.                 {
  20.                     ConnectionSettingsType = ConnectionSettingsType.Bluetooth
  21.                 };
  22.                 connectionSettingsTask.Show();
  23.                 RefreshPairedDevicesList();
  24.             }
  25.         }
  26.         else
  27.         {
  28.             MessageBox.Show(ex.Message);
  29.         }
  30.     }
  31. }

First we’ll look for all paired devices for our phone, those get pushed into the observablecollection. If that fails with result 0x8007048F that means that Bluetooth is disabled on the device, in that case we use the ConnectionSettingsTask to redirect the user to the Bluetooth settings page in WP8.

After the list of peers is build, the user will be able to select one (I’ll discuss the pages in a minute). When a peer is selected we open up the Bluetooth connection

Code Snippet
  1. private async void ConnectToDevice()
  2. {
  3.     if (_socket != null)
  4.     {
  5.         // Disposing the socket with close it and release all resources associated with the socket
  6.         _socket.Dispose();
  7.     }
  8.  
  9.     try
  10.     {
  11.         _socket = new StreamSocket();
  12.  
  13.         //connect to the service with specified GUID
  14.         await _socket.ConnectAsync(SelectedPeer.HostName, "{7A51FDC2-FDDF-4c9b-AFFC-98BCD91BF93B}");
  15.  
  16.         // Connection was successful
  17.         _dataWriter = new DataWriter(_socket.OutputStream);
  18.         _navigationService.NavigateTo("/ConnectedPage.xaml");
  19.     }
  20.     catch (Exception ex)
  21.     {
  22.         MessageBox.Show(ex.Message);
  23.  
  24.         _socket.Dispose();
  25.         _socket = null;
  26.     }
  27. }

The ConnectAsync method takes in the hostname of the peer and the same GUID we used in the WPF application to start the service. Once the connection is made we take the OutputStream and use it to initialize the DataWriter and we navigate to the ConnectedPage.

Let’s have a quick look at the MainPage xaml.

Code Snippet
  1. <phone:LongListSelector ItemsSource="{Binding Peers}">
  2.     <phone:LongListSelector.ItemTemplate>
  3.         <DataTemplate>
  4.             <TextBlock Margin="12, 0, 0, 12"
  5.                        Style="{StaticResource PhoneTextTitle2Style}"
  6.                        Text="{Binding DisplayName}" />
  7.         </DataTemplate>
  8.     </phone:LongListSelector.ItemTemplate>
  9.     <i:Interaction.Behaviors>
  10.         <behaviors:SelectedItemBehavior SelectedItem="{Binding SelectedPeer, Mode=TwoWay}" />
  11.     </i:Interaction.Behaviors>
  12.  
  13. </phone:LongListSelector>

The MainPage consists of a LongListSelector with an ItemsSource bound to the observableCollection on the MainViewModel. as a DataContext we show the displaynames of all available peers.

NOTE: LongListSelector does not support SelectedItem binding. I’ve added a behavior to this project that gives us just that. For more information on the behavior see my blogpost from a while ago.

The ConnectedPage only has a button with a command bound to the GoToStartCommand on MainViewModel. Once that command is fired we send a string “Start” on to the stream.

Code Snippet
  1. private async void SendCommand()
  2. {
  3.     _dataWriter.WriteString("Start");
  4.     await _dataWriter.StoreAsync();
  5.     await _dataWriter.FlushAsync();
  6. }

And that’s it! The message gets written into the DataWriter, stored in the stream and the stream gets flushed. In the WPF app the string gets read into the buffer as a byte array, gets converted back into a string and the Start screen appears!

Wrap-up

In this post I’ve discussed how to connect your Windows Phone device to another bluetooth enabled device and use a service running there.

Happy coding!


Tags:

.Net | Devices | Bluetooth | MVVM Light | WP8 | WPF | XAML | Windows programming

Branching XAML Styler

by Nico

Some time ago I blogged about having recompiled the great XAML Styler plugin so it would install into Visual Studio 2013. The recompiled plugin suddenly became an unexpected success and it got me thinking that this plugin should really continue to exist, even if the original author isn’t supporting it anymore (not sure of this but it has been quite some time since he pushed anything to Codeplex).

After waiting around a bit I’ve decided to download the original source code, get it up and running in Visual Studio 2013 and push it to both Github and the Visual Studio gallery. So I’m happy to announce that the code can be found at Github and the VS2013 version of the plugin can be found at the Visual Studio Gallery

The future?

The version that is now on the gallery is the exact same version that I’ve compiled back in November. It’s the plugin that the original author created but recompiled with the VS2013 SDK. I did create a new VS Package project to be able to have it on the gallery side by side with the original plugin.

As for the future of the project, I’m currently going through the source code, getting to know the application and the code that makes it tick. Afterwards I’m planning on having a look at the logged issues on the original Codeplex site and tackle those.

Issues

Should you run into any issues while using the forked plugin please log an issue on the Github page.

Contributions

So you want to contribute? Great! Fork the Github version and go wild! Create a Pull request when you’re ready and if everything checks out I’ll happily merge your changes into the main branch and give props to every contribution you make.

Let’s keep this plugin alive and make it even better together!


Tags:

.Net | Community | Patterns | Silverlight | WP7 | WP8 | WPF | WinRT | Windows 8 | XAML | github | OSS

Xaml Styler for Visual Studio 2013

by Nico

Xaml Styler is a free Visual Studio 2012 extension available from the gallery. I’ve been using this extension for quite some time now and I’m really happy with how it styles my XAML code. Unfortunately the extension isn’t compatible with Visual Studio 2013.

Luckily for us, the extension is on Codeplex. I’ve downloaded the code, referenced the new Visual Studio SDK and recompiled it. It seems to be working fine with Visual Studio 2013 now.

I’ve uploaded the binaries to my Skydrive folder so that everyone can enjoy the extension in Visual Studio 2013 until the original author of the plug-in creates official Visual Studio 2013 support.

Be aware, this version isn’t thoroughly tested by anyone! I’ve compiled it, installed it and I’m currently using it. I haven’t ran into any problems yet but that doesn’t mean that it won’t have any problems. These binaries are supplied as-is.

Download from Skydrive

Gallery link

Original Codeplex page


Tags:

.Net | WP7 | WP8 | WPF | WinRT | Windows 8 | XAML

WP8, Leap Motion and a glue called Sockets

by Nico

I’m one of the lucky few who got their hands on a Leap Motion developer device (check out the video above if you’ve never heard of the Leap Motion). It’s a pretty cool device that gives you motion tracking not unlike Kinect but limited to finger and hand movement instead of complete body tracking.

I had the device and needed something to play with and what’s cooler then combining a cool gadget with an awesome smartphone? So I decided to build a small proof-of-concept that would capture finger movement in a WPF application and translate that movement to a moving ellipse in a Windows Phone application.

The Leap Motion’s documentation got me to a moving ellipse in a WPF application pretty fast thanks to the samples and documentation found on their developer portal. It took me a bit more time to get the position of the ellipse send to the phone, I wanted to use Sockets for this (SignalR would be way easier but I didn’t want an extra service running, now I have peer to peer communication).

Here’s how I did it

WPF and the Leap Motion

First, the WPF project. This project will be the socket server and the app that captures the Leap Motion’s output. The application only has one page with this as XAML

Code Snippet
  1. <Window x:Class="LeapWpPoc.MainWindow"
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.         Title="MainWindow"
  5.         Width="525"
  6.         Height="350">
  7.     <Canvas x:Name="TheCanvas">
  8.         <Ellipse x:Name="TheEllipse"
  9.                  Canvas.Left="211"
  10.                  Canvas.Top="118"
  11.                  Width="70"
  12.                  Height="70"
  13.                  Fill="#FFFF0C00"
  14.                  Stroke="Black" />
  15.         <TextBlock x:Name="TextBlockStatus"
  16.                    Canvas.Left="10"
  17.                    Canvas.Top="10"
  18.                    Foreground="Red"
  19.                    Text="Not connected"
  20.                    TextWrapping="Wrap" />
  21.     </Canvas>
  22. </Window>

Let’s have a look at how to interact with the Leap Motion first.

First thing you need when working with the Leap Motion (apart from the actual device that is) is a reference to LeapCSharp.NET4.0.dll however, you’ll also need Leap.dll and LeapCSharp.dll. Now I find this a bit dirty and I sincerely hope that the Leap Motion team will find a way to fix this but those two libraries aren’t referencable in our project but they need to be present in the application’s directory or it won’t work. What I did is add them as an existing item to the project, set their build action to Content and Copy if newer, at least this way they will always get copied into the build directory of the application.

Next, you’ll needs a class that inherits from Listener (Listener is part of the Leap Motion SDK). Listener is a base class that provides a bunch of virtual methods like OnExit, OnDisconnect, OnConnect and OnFrame. Feel free to override those to add some logging or logic but I’m only using the OnFrame method here. Here’s my Listener class

Code Snippet
  1. class PocListener : Listener
  2. {
  3.     public event EventHandler<FrameDetectedEventArgs> FrameDetected;
  4.  
  5.     public override void OnFrame (Controller controller)
  6.     {
  7.         // Get the most recent frame and report some basic information
  8.         Frame frame = controller.Frame ();
  9.  
  10.         if (FrameDetected != null)
  11.         {
  12.             FrameDetected(this, new FrameDetectedEventArgs(frame));
  13.         }
  14.     }
  15. }

The OnFrame method fires constantly, passing all the movement information, if any, in a frame. If my listener implementation detects a frame the FrameDetected event will fire, passing in the detected frame as an eventarg, FrameDetectedEventArgs is a very basic class that only passes the frame data to whoever is listening to the event.

Code Snippet
  1. public class FrameDetectedEventArgs : EventArgs
  2. {
  3.     public Frame Frame { get; set; }
  4.  
  5.     public FrameDetectedEventArgs(Frame frame)
  6.     {
  7.         Frame = frame;
  8.     }
  9. }

Notice that the OnFrame method needs a Controller as parameter? Controller is the class from the Leap Motion API that talks to the device. I create a new instance of Controller and my Listener in the MainWindow constructor.

Code Snippet
  1. private Frame _previousFrame;
  2. private Frame _currenFrame;
  3. private readonly PocListener _listener;
  4. private readonly Controller _controller;
  5. private readonly SocketFactory _socketFactory;
  6.  
  7. public MainWindow()
  8. {
  9.     InitializeComponent();
  10.  
  11.     _listener = new PocListener();
  12.     _controller = new Controller();
  13.  
  14.     // Have the sample listener receive events from the controller
  15.     _controller.AddListener(_listener);
  16.  
  17.     _listener.FrameDetected += ListenerOnFrameDetected;
  18. }

This is the constructor and some private fields, I need to keep track of both the current frame and the previous one to detect if there’s any change in the position of the hand or fingers. I also have an instance of PocListener (my own Listener class) and of Controller, both get instantiated in the constructor.Next I need to register my Listener in the Controller, that’s done on line 14 and then finally I attach an event handler to the FrameDetected event.

The event handler of the FrameDetected event will be responsible of checking if hands and fingers are detected.

Code Snippet
  1. private void ListenerOnFrameDetected(object sender, FrameDetectedEventArgs frameDetectedEventArgs)
  2. {
  3.     _currenFrame = frameDetectedEventArgs.Frame;
  4.  
  5.     if (!_currenFrame.Hands.Empty)
  6.     {
  7.         // Get the first hand
  8.         Hand hand = _currenFrame.Hands[0];
  9.  
  10.         // Check if the hand has any fingers
  11.         FingerList fingers = hand.Fingers;
  12.         if (!fingers.Empty)
  13.         {
  14.             if (_previousFrame == null) _previousFrame = _currenFrame;
  15.             //check if the current frame is different from the last frame
  16.             if (_currenFrame != _previousFrame)
  17.             {
  18.                 //we only need one finger so we'll take the first one that's detected
  19.                 Finger finger = fingers[0];
  20.  
  21.                 float x = _previousFrame.Fingers[0].TipPosition.x - finger.TipPosition.x;
  22.                 float y = _previousFrame.Fingers[0].TipPosition.y - finger.TipPosition.y;
  23.  
  24.                 //update the sphere's position
  25.                 Dispatcher.BeginInvoke((Action)(() =>
  26.                                                 {
  27.                                                     Canvas.SetTop(TheEllipse, Canvas.GetTop(TheEllipse) + y);
  28.                                                     Canvas.SetLeft(TheEllipse, Canvas.GetLeft(TheEllipse) - x);
  29.                                                 }));
  30.  
  31.                 //set this frame as the previous one and get ready to receive a new frame
  32.                 _previousFrame = _currenFrame;
  33.             }
  34.         }
  35.     }
  36. }

First we check if the previous frame has the same information as the current frame, if it does there’s no need to update the ellipse’s position.

If a hand and fingers are detected I select the first detected finger, because that’s currently the only one I’m interested in. Since all the Leap Motion actions are happening on a separate thread I need to invoke the UI thread to update the ellipse’s position, that’s what’s happening on line 25. The position of a UIElement in a Canvas in XAML is set through attached properties (Canvas.Left=”177” for example) to set these in code we use Canvas.SetLeft. To determine the new location of the ellipse I take the X and Y positions of the first finger in the previous frame and substract the X and Y of the first finger in the current frame. The new Y value gets added to the Canvas.Top of the ellipse and the new X value gets subtracted  from the Canvas.Left value. Last but not least I set the previousframe to the currentframe.

That’s all the code you need to get an ellipse moving in a canvas with the Leap Motion. So part 1 is a great success. Now onto the bigger challenge, getting a similar ellipse to move in a Windows Phone project.

Windows Phone and sockets

Implementing sockets to make devices talk to each other over the wire can be challenging but it’s also very rewarding and just plain fun once it works. I haven’t worked with sockets before so I had a real blast trying to figure this out and I went through the roof once that ellipse started moving on the Windows Phone emulator Glimlach. Before we dive into the sockets, let’s have a quick look at the MainPage.

Code Snippet
  1. <Canvas x:Name="TheCanvas">
  2.     <Ellipse x:Name="TheEllipse"
  3.              Canvas.Left="302"
  4.              Canvas.Top="186"
  5.              Width="70"
  6.              Height="70"
  7.              Fill="#FFFF0C00"
  8.              Stroke="Black" />
  9.     <TextBlock x:Name="TextBlockStatus"
  10.                Canvas.Left="10"
  11.                Canvas.Top="10"
  12.                Foreground="Red"
  13.                Text="Not connected"
  14.                TextWrapping="Wrap" />
  15. </Canvas>

Exactly the same controls as in the WPF project, nothing spectacular here. Let’s have a look at the code behind the MainPage.

Code Snippet
  1. public partial class MainPage
  2. {
  3.     private SocketClient _client;
  4.     const int Port = 8000;
  5.     private const string IpAddress = "10.16.79.70";
  6.  
  7.     // Constructor
  8.     public MainPage()
  9.     {
  10.         InitializeComponent();
  11.         _client = new SocketClient();
  12.  
  13.         _client.OnConnected += (sender, args) => Dispatcher.BeginInvoke(() =>
  14.             {
  15.                 TextBlockStatus.Text = "Connected";
  16.                 TextBlockStatus.Foreground = new SolidColorBrush(Colors.Green);
  17.             });
  18.         _client.OnMessageReceived += (sender, args) => Dispatcher.BeginInvoke(() => MoveBall(args.Response));
  19.         _client.Connect(IpAddress, Port);
  20.  
  21.         _client.Receive();
  22.     }
  23.  
  24.     private void MoveBall(string response)
  25.     {
  26.         response = response.Replace(',', '.');
  27.         var coordinates = response.Split(';');
  28.  
  29.         float y = float.Parse(coordinates[0]);
  30.         float x = float.Parse(coordinates[1]);
  31.  
  32.         Canvas.SetTop(TheEllipse, y);
  33.         Canvas.SetLeft(TheEllipse, x);
  34.     }
  35. }

First some fields, don’t worry about the SocketClient class, we’ll get to that in a minute. Some constants holding the IP address and the port of the server (don’t forget to change this IP address to the address of your own pc!)

In the constructor we instantiate the SocketClient instance and handle its two events. The OnConnected event is going to change the text of the TextBlock to “Connected” and the OnMessageReceived event handler will move the ellipse.

The MoveBall() method will do the actual moving. The message that we will receive will be a string that has the Y and X of the ellipse in the WPF application seperated by a semicolon. The problem I had here was that instead of a dot to separate the decimals .NET had changed it into a comma (which is the default decimal sign in Belgium) so I need to change that back. I then split up the string using the semicolon as split character, parse the values into a float and set the ellipse to its new position. Let’s get serious and dive into the socket stuff now.

Sockets provide us with TCP and UDP communication, next to a whole bunch of other features. This app will use a TCP connection between WPF and a Windows Phone application. Since we’re currently looking at the Windows Phone app, let’s continue there. I’ve added a class called SocketClient that takes care of connection a socket, sending and receiving messages. Let’s start with the fields and constructor.

Code Snippet
  1. // Cached Socket object that will be used by each call for the lifetime of this class
  2. Socket _socket;
  3.  
  4. // Signaling object used to notify when an asynchronous operation is completed
  5. static ManualResetEvent _clientDone;
  6.  
  7. // Define a timeout in milliseconds for each asynchronous call. If a response is not received within this
  8. // timeout period, the call is aborted.
  9. const int TimeoutMilliseconds = 5000;
  10.  
  11. // The maximum size of the data buffer to use with the asynchronous socket methods
  12. const int MaxBufferSize = 2048;
  13.  
  14. public event EventHandler<MessageReceivedEventArgs> OnMessageReceived;
  15. public event EventHandler OnConnected;
  16.  
  17. public SocketClient()
  18. {
  19.     _clientDone = new ManualResetEvent(false);
  20. }

First field is the actual socket that we’ll be using, second one is a reset event that we can use to make a thread block while waiting for an event to fire. The timeout is the max amount of time that the reset event will block a thread. The buffersize is the size of the buffer for socket messages. The two events are fired when the app receives a socket message or when a socket connects.

The most important function of the SocketClient class that I’m building here is to connect two sockets.

Code Snippet
  1. public string Connect(string hostName, int portNumber)
  2. {
  3.     string result = string.Empty;
  4.  
  5.     // Create DnsEndPoint. The hostName and port are passed in to this method.
  6.     DnsEndPoint hostEntry = new DnsEndPoint(hostName, portNumber);
  7.  
  8.     // Create a stream-based, TCP socket using the InterNetwork Address Family.
  9.     _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  10.  
  11.     // Create a SocketAsyncEventArgs object to be used in the connection request
  12.     SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs {RemoteEndPoint = hostEntry};
  13.  
  14.     socketEventArg.Completed += (sender, args) =>
  15.                                         {
  16.                                             // Retrieve the result of this request
  17.                                             result = args.SocketError.ToString();
  18.  
  19.                                             // Signal that the request is complete, unblocking the UI thread
  20.                                             _clientDone.Set();
  21.  
  22.                                             if (OnConnected == null) return;
  23.  
  24.                                             OnConnected(this, new EventArgs());
  25.                                         };
  26.  
  27.     // Sets the state of the event to nonsignaled, causing threads to block
  28.     _clientDone.Reset();
  29.  
  30.     // Make an asynchronous Connect request over the socket
  31.     _socket.ConnectAsync(socketEventArg);
  32.     
  33.     // Block the UI thread for a maximum of TIMEOUT_MILLISECONDS milliseconds.
  34.     // If no response comes back within this time then proceed
  35.     _clientDone.WaitOne(TimeoutMilliseconds);
  36.  
  37.     return result;
  38. }

The connect method takes in two parameters, the hostname (or IP address) and the portnumber of the socket we want to connect to. Based on these two parameters we create a DnsEndPoint that will be passed to the server socket as being the remote endpoint so that the server socket knows where to send his messages. Next we instantiate the Socket, stating that it’s using an internal IPv4 network, a stream socket and the TCP protocol. Now that we have a socket and an endpoint we’ll need some eventargs, those args will be passed onto the server. Once the connection succeeds (or fails) the Completed event on the SocketAsyncEventArgs will fire, in that event handler we’ll trigger the OnConnected event. With that in place we call the Reset() method on the ManualResetEvent to set the event to nonsignaled, call the ConnectAsync() method on the Socket and pass in the eventargs and finally blocking the thread for a certain time to allow the socket time to connect.

So now that our client can connect to a socket, let’s build something to send messages to the connected socket. From the Windows Phone 8 version it looks like this

Code Snippet
  1. public void Send(string data)
  2. {
  3.     data = data + "<EOF>";
  4.  
  5.     if (_socket != null)
  6.     {
  7.         SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs
  8.             {
  9.                 RemoteEndPoint = _socket.RemoteEndPoint,
  10.                 UserToken = null
  11.             };
  12.  
  13.         socketEventArg.Completed += (sender, args) =>
  14.                                         {
  15.                                             _clientDone.Set();
  16.                                         };
  17.  
  18.         // Add the data to be sent into the buffer
  19.         byte[] payload = Encoding.UTF8.GetBytes(data);
  20.         socketEventArg.SetBuffer(payload, 0, payload.Length);
  21.  
  22.         // Sets the state of the event to nonsignaled, causing threads to block
  23.         _clientDone.Reset();
  24.  
  25.         // Make an asynchronous Send request over the socket
  26.         _socket.SendAsync(socketEventArg);
  27.  
  28.         // Block the UI thread for a maximum of TIMEOUT_MILLISECONDS milliseconds.
  29.         // If no response comes back within this time then proceed
  30.         _clientDone.WaitOne(TimeoutMilliseconds);
  31.     }
  32. }

We get in the message as a parameter, at the end of the message I add “<EOF>” just to make sure that I only get the part that I need at the server side and that the message has been delivered in full. If at this point the socket is null then it isn’t connected yet. If it isn’t we once again instantiate SocketAsyncEventArgs. The data gets serialized into a byte array and set as a buffer in the eventargs. Set the ManualResetEvent to nonsignaled, start sending the message over the socket async and block the thread.

And last but not least there’s the code to receive messages on the socket.

Code Snippet
  1. public void Receive()
  2. {
  3.     if (_socket != null)
  4.     {
  5.         SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs
  6.             {
  7.                 RemoteEndPoint = _socket.RemoteEndPoint
  8.             };
  9.  
  10.         // Setup the buffer to receive the data
  11.         socketEventArg.SetBuffer(new Byte[MaxBufferSize], 0, MaxBufferSize);
  12.  
  13.         socketEventArg.Completed += (sender, args) =>
  14.             {
  15.                 if (args.SocketError == SocketError.Success)
  16.                 {
  17.                     // Retrieve the data from the buffer
  18.                     string response = Encoding.UTF8.GetString(args.Buffer, args.Offset, args.BytesTransferred);
  19.                     response = response.Trim('\0');
  20.  
  21.                     if (response.Contains("<EOF>"))
  22.                     {
  23.                         response = response.Substring(0, response.IndexOf("<EOF>"));
  24.                         if (OnMessageReceived != null)
  25.                             OnMessageReceived(this, new MessageReceivedEventArgs(response));
  26.                     }
  27.  
  28.                     Receive();
  29.                 }
  30.  
  31.                 _clientDone.Set();
  32.             };
  33.  
  34.         // Sets the state of the event to nonsignaled, causing threads to block
  35.         _clientDone.Reset();
  36.  
  37.         // Make an asynchronous Receive request over the socket
  38.         _socket.ReceiveAsync(socketEventArg);
  39.  
  40.         // Block the UI thread for a maximum of TIMEOUT_MILLISECONDS milliseconds.
  41.         // If no response comes back within this time then proceed
  42.         _clientDone.WaitOne(TimeoutMilliseconds);
  43.     }
  44. }

So the same story with the null check on the socket and creating of the SocketEventArgs. Once the Completed event fires we’ll check if the receive was successful  and if the received message contains “<EOF>”, if it does we take everything before <EOF> and pass it in the MessageReceivedEventArgs that go with the MessageReceived event.

Code Snippet
  1. public class MessageReceivedEventArgs : EventArgs
  2. {
  3.     public string Response { get; set; }
  4.  
  5.     public MessageReceivedEventArgs(string response)
  6.     {
  7.         Response = response;
  8.     }
  9. }

Once everthing is handled we call the Receive method again so it’s ready to start receiving the next message.

And that’s basically all the logic for a socket connection on the Windows Phone side of things. The only thing left to do in the app is change the MainPage’s constructor to initialize the SocketClient and add some fields.

Code Snippet
  1. private SocketClient _client;
  2. const int Port = 8000;
  3. private const string IpAddress = "10.16.79.70";
  4.  
  5. // Constructor
  6. public MainPage()
  7. {
  8.     InitializeComponent();
  9.     _client = new SocketClient();
  10.  
  11.     _client.OnConnected += (sender, args) => Dispatcher.BeginInvoke(() =>
  12.         {
  13.             TextBlockStatus.Text = "Connected";
  14.             TextBlockStatus.Foreground = new SolidColorBrush(Colors.Green);
  15.         });
  16.     _client.OnMessageReceived += (sender, args) => Dispatcher.BeginInvoke(() => MoveBall(args.Response));
  17.     _client.Connect(IpAddress, Port);
  18.  
  19.     _client.Receive();
  20. }

The constructor instantiates the SocketClient, attaches an handler to the OnConnected event to update the textbox with the connection status and handle the OnMessageReceived event to update the position of the ellipse. Don’t forget to update the IP address to the one from your own pc!

Back to WPF!

Now that our Windows Phone app is ready, it’s time to implement the socket server. As mentioned before, the WPF app that gets input from the Leap Motion will serve as socket server.

I’ve added a class to the WPF project called SocketFactory, it serves the same function as the SocketClient class in the Windows Phone project but from a server point of view. The way to build and use a socket in full blown .net 4.5 differs a bit from how we did it in Windows Phone. First we’ll need a state class, this contains a socket, the buffersize, a byte array to function as the buffer and a stringbuilder to recompose the message.

Code Snippet
  1. // State object for reading client data asynchronously
  2. public class StateObject
  3. {
  4.     // Client  socket.
  5.     public Socket WorkSocket = null;
  6.     // Size of receive buffer.
  7.     public const int BufferSize = 1024;
  8.     // Receive buffer.
  9.     public byte[] Buffer = new byte[BufferSize];
  10.     // Received data string.
  11.     public StringBuilder Sb = new StringBuilder();
  12. }

Next, we’ll need some fields in the SocketFactory class

Code Snippet
  1. // Thread signal.
  2. public static ManualResetEvent AllDone = new ManualResetEvent(false);
  3. private StateObject _state;
  4. public event EventHandler OnConnected;

And here’s the function to receive a connection request

Code Snippet
  1. public void Start()
  2. {
  3.     IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
  4.     IPAddress ipAddress = ipHostInfo.AddressList[3];
  5.     IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 8000);
  6.  
  7.     Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  8.  
  9.     // Bind the socket to the local endpoint and listen for incoming connections.
  10.     try
  11.     {
  12.         listener.Bind(localEndPoint);
  13.         listener.Listen(100);
  14.  
  15.         while (true)
  16.         {
  17.             // Set the event to nonsignaled state.
  18.             AllDone.Reset();
  19.  
  20.             // Start an asynchronous socket to listen for connections.
  21.             Console.WriteLine("Waiting for a connection...");
  22.             listener.BeginAccept(AcceptCallback, listener);
  23.  
  24.             // Wait until a connection is made before continuing.
  25.             AllDone.WaitOne();
  26.  
  27.             if (OnConnected == null) return;
  28.  
  29.             OnConnected(this, new EventArgs());
  30.         }
  31.  
  32.     }
  33.     catch (Exception e)
  34.     {
  35.         Console.WriteLine(e.ToString());
  36.     }
  37. }

We declare a socket called listener, pass it the same parameters as we did for Windows Phone, stating that it’s local network, streaming and using the TCP protocol. We need to bind this socket to an IPEndPoint, to create an IPEndPoint we need an IPAddress and a port. Lines 3 and 4 are used to getting the computer’s IP address from its hostname. Once we have that we can bind the socket to the endpoint. Make sure that the port you set here is the same port you try to connect to in the Windows Phone app. Once the socket connects the callback fires, in the callback we start receiving data from the connected client.

Code Snippet
  1. public void AcceptCallback(IAsyncResult ar)
  2. {
  3.     // Signal the main thread to continue.
  4.     AllDone.Set();
  5.  
  6.     // Get the socket that handles the client request.
  7.     Socket listener = (Socket)ar.AsyncState;
  8.     Socket handler = listener.EndAccept(ar);
  9.  
  10.     // Create the state object.
  11.     _state = new StateObject { WorkSocket = handler };
  12.  
  13.     handler.BeginReceive(_state.Buffer, 0, StateObject.BufferSize, 0, ReadCallback, _state);
  14. }

Once data is received, the ReadCallback fires

Code Snippet
  1. public void ReadCallback(IAsyncResult ar)
  2. {
  3.     StateObject state = (StateObject)ar.AsyncState;
  4.     Socket handler = state.WorkSocket;
  5.  
  6.     int bytesRead = handler.EndReceive(ar);
  7.  
  8.     if (bytesRead > 0)
  9.     {
  10.         // There  might be more data, so store the data received so far.
  11.         state.Sb.Append(Encoding.ASCII.GetString(
  12.             state.Buffer, 0, bytesRead));
  13.  
  14.         // Check for end-of-file tag. If it is not there, read
  15.         // more data.
  16.         string content = state.Sb.ToString();
  17.         if (content.IndexOf("<EOF>") > -1)
  18.         {
  19.             Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
  20.                 content.Length, content);
  21.         }
  22.         else
  23.         {
  24.             // Not all data received. Get more.
  25.             handler.BeginReceive(state.Buffer, 0, StateObject.BufferSize, 0, ReadCallback, state);
  26.         }
  27.     }
  28. }

We can get the stateobject and socket from the IAsyncResult and we start reading until we encounter “<EOF>”, once everything is received we write it out in the output window. Now in this example the server won’t actually be receiving any messages, I’ve just put in this method in case you want to enhance it or have some use for the code.

What is important in this sample is the Send method, this will send a message over the connected socket to the client.

Code Snippet
  1. public void Send(string data)
  2. {
  3.     Send(_state.WorkSocket, data);
  4. }
  5.  
  6. private void Send(Socket handler, string data)
  7. {
  8.     data = data + "<EOF>";
  9.     // Convert the string data to byte data using ASCII encoding.
  10.     byte[] byteData = Encoding.ASCII.GetBytes(data);
  11.  
  12.     // Begin sending the data to the remote device.
  13.     handler.BeginSend(byteData, 0, byteData.Length, 0, SendCallback, handler);
  14. }

I’ve split up the Send into two methods, the public one just receives the message we want to send and passes it trough to the private one, also passing in the socket to use. This way the application itself doesn’t need to worry about selecting a socket, let the socketFactory deal with that. The Send method adds the end of file part to the message, serializes it into a byte array and sends it over the socket. Once the send is complete, the callback will fire.

Code Snippet
  1. private void SendCallback(IAsyncResult ar)
  2. {
  3.     try
  4.     {
  5.         // Retrieve the socket from the state object.
  6.         Socket handler = (Socket)ar.AsyncState;
  7.  
  8.         handler.EndSend(ar);
  9.     }
  10.     catch (Exception e)
  11.     {
  12.         Console.WriteLine(e.ToString());
  13.     }
  14. }

I’m not really doing anything in the callback, but this would be the perfect place to check for successful delivery and maybe notifying the UI thread to show a confirmation or something similar.

Now that our socket infrastructure is in place and we have a client updating a UI based on the received messages, it’s time to finish this sample by letting the server send the coordinates of the ellipse. In the MainWindow add a field for the socket factory. (line 5 is the extra field)

Code Snippet
  1. private Frame _previousFrame;
  2. private Frame _currenFrame;
  3. private readonly PocListener _listener;
  4. private readonly Controller _controller;
  5. private readonly SocketFactory _socketFactory;

With the new field in place, replace (or update) the constructor to this

Code Snippet
  1. public MainWindow()
  2. {
  3.     InitializeComponent();
  4.  
  5.     _socketFactory = new SocketFactory();
  6.     _socketFactory.OnConnected += (sender, args) => Dispatcher.BeginInvoke((Action) (() =>
  7.         {
  8.             TextBlockStatus.Text = "Connected";
  9.             TextBlockStatus.Foreground = new SolidColorBrush(Colors.Green);
  10.         }));
  11.  
  12.     Task.Run(() => _socketFactory.Start());
  13.  
  14.     _listener = new PocListener();
  15.     _controller = new Controller();
  16.  
  17.     // Have the sample listener receive events from the controller
  18.     _controller.AddListener(_listener);
  19.  
  20.     _listener.FrameDetected += ListenerOnFrameDetected;
  21.  
  22.     Timer timer = new Timer(200);
  23.     timer.Elapsed += (sender, args) => Dispatcher.BeginInvoke((Action)(() =>
  24.         _socketFactory.Send(string.Format("{0};{1}", Canvas.GetTop(TheEllipse), Canvas.GetLeft(TheEllipse)))));
  25.  
  26.     timer.Start();
  27. }

We instantiate the SocketFactory, attach an handler for the OnConnected event to update the UI. The SocketFactory’s Start method is queued on the thread pool to run async, this way the UI thread will remain responsive. The Leap Motion get’s initialized and we start a timer. This timer will make sure that every 200 milliseconds the coordinates of the ellipse are send over the socket to the client. The sending of the message needs to be done on the UI thread because we need the ellipse’s coordinates, and that ellipse lives on the UI thread.

Now, why use a timer? In the first version of this sample a message was send every time the ellipse moved, this resulted in really really really poor performance, messages were being send faster than they arrived causing all kinds of weird behavior. Sending it every 200 milliseconds makes it move quite well.

Everything is in place now, so run it and move the ellipse around with the Leap Motion!

Conclusion

In this post I’ve explained my adventure of connecting the Leap Motion to a Windows Phone application by using sockets. While not the easiest thing to set up or use, sockets are a really powerful way of communicating between applications no matter what platform they’re on (as long as that platform supports sockets).

The Leap Motion is a great device. It’s small, light, has a very small footprint on your system and is just plain fun to mess around with. I could’ve used anything for a socket example but making something move on screen, on two devices at the same time by just moving your hand has something magically. The Leap Motion is definitely on my list of awesome gadgets.

The code for this post can be found on my Skydrive


Tags:

NUI | LeapMotion | .Net | Devices | WP8 | WPF

Comic Organizer Part III: MainViewModel and Facade pattern

by Nico

Last time we did some Xaml work to setup the metro style that will be used throughout the application, now it’s time to dive into some C# code. In this part we’ll start adding some properties to the MainViewModel that can be used for databinding and we’ll talk a bit about the Façade pattern, the first of the design patterns that we’ll try to implement.

 

ViewModel

To show data in the views of an MVVM application we need some bindable properties. Those properties are called bindable because they can be bound to a control on the view, for example a string property can be bound to a textbox so that the value of the string is shown as the textbox.Text property. Or the other way around, or both ways. Creating those properties works in the same way you’d create a property in any class but they can’t be auto properties, you need to create them the old-fashioned way. For the moment I need two properties, a string that will contain the text that a user typed into the searchbox and a list that will contain the searchresults.

Code Snippet
  1. private string searchString;
  2. public string SearchString
  3. {
  4.     get { return searchString; }
  5.     set
  6.     {
  7.         searchString = value;
  8.         RaisePropertyChanged(SearchStringPropertyName);
  9.     }
  10. }
  11.  
  12. private Response searchResult;
  13. public Response SearchResult
  14. {
  15.     get { return searchResult; }
  16.     set
  17.     {
  18.         searchResult = value;
  19.         RaisePropertyChanged(SearchResultPropertyName);
  20.     }
  21. }

“Wait, I thought you said one of them would be a list?”
Yes I did
“But I see no list”
Deceiving looks can be my young Padawan.

“Response” is a class I build that contains the list I previously mentioned, it’s in a separate class so that later on I can use the MVVM Light messenger to pass it around, the messenger won’t pass around a list so this is a work-around, more about that when we get to that.

 

Domain Project

The response classed is declared in a separate project, I’ve added a C# class library to the solution and called it “ComicOrganizer.Domain”. It will contain all the classes I’ll be needing, for now it just contains the Response class

The Response class looks like this:

Code Snippet
  1. public class Response
  2. {
  3.     public int NumberOfPageResults { get; set; }
  4.     public int StatusCode { get; set; }
  5.     public string Error { get; set; }
  6.     public IList<SearchResult> Results { get; set; }
  7.     public int Limit { get; set; }
  8.     public int Offset { get; set; }
  9.     public int NumberOfTotalResults { get; set; }
  10. }

So it has a few more properties than just a list, but we’ll need them later. These can be auto properties because we won’t be binding them to a control in the view.

The application will be using a normal List<T> but I’ve declared it here as an IList<T> so that, if we in the future build our own list, based on IList<T> we won’t need to adapt our class. Working with interfaces instead of implementations is also a best practice and helps utilising the Open/Close principle.

The IList expects members of type “SearchResult”, which is also one of my homecooked classes. A small background before we dive into that one. The purpose here is to accept a searchstring by the user, send the string to the Comicvine api, which returns the result as a JSON object (more about that later). We deserialize the JSON object in objects that our application can understand and pass it to the ViewModel. A JSON result returned by ComicVine looks like the Response class above, it states how many pages it contains (20 items per page), it has a StatusCode which is 0 if everything went peachy, if it hasn’t it sends the error. It has an array with 20 results, a total results and an Offset. With the offset we can ask the API for results 0-20 or 20-40 and so on.

The results themselves look like the SearchResult class I’ve build:

Code Snippet
  1. public class SearchResult : IResource
  2. {
  3.     public Publisher PublishedBy { get; set; }
  4.     public Image Images { get; set; }
  5.     public string Name { get; set; }
  6.     public string ApiDetailUrl { get; set; }
  7. }

As you can see this class implements the IResource interface, which is just an empty interface, the use will become clear later on. Also the Image type used here isn’t the .net Image type, it’s again a custom class, just like Publisher.

Code Snippet
  1. public class Image : IResource
  2. {
  3.     public string IconUrl { get; set; }
  4.     public string MediumUrl { get; set; }
  5.     public string TinyUrl { get; set; }
  6.     public string SmallUrl { get; set; }
  7.     public string ThumbUrl { get; set; }
  8.     public string ScreenUrl { get; set; }
  9.     public string SuperUrl { get; set; }
  10. }
  11.  
  12. public class Publisher : IResource
  13.     {
  14.     public string LocationCity { get; set; }
  15.     public string LocationState { get; set; }
  16.     public string LocationAddress { get; set; }
  17. }

And that’s all the classes we need for now. The returned JSON contains a whole lot more information but we won’t be using that, so we filter it out.

 

Facade Pattern

The Façade Pattern according to dofactory.com:

Provide a unified interface to a set of interfaces in a subsystem. Façade defines a higher-level interface that makes the subsystem easier to use.

The façade pattern creates some sort of API on top of an API, there are many reasons to do so. In our case it’s because the Comicvine API is very big and we only need a portion of it, also the Comicvine API returns JSON results, we need .net objects. So we create a wrapper around it, this wrapper is called the Façade pattern.

I’m going to start with just one method in the façade pattern, we will expand it as this series moves along. For starters I created an interface called IApi, the interface has one method called SearchVolume. This will search the Comicvine database for all comic series (called Volumes by Comicvine) that contain the searchstring the user entered. The interface looks like this:

Code Snippet
  1. public interface IApi
  2. {
  3.     void SearchVolume(string searchString);
  4. }

It accepts the searchstring but doesn’t return any value because getting the info will happen asynchronously and we will return the result by using the MVVM Light Messenger.

Now, why would I want to use an interface for my façade pattern? Let’s say that in a few months I run against another comicsite that offers an api that I want to include in my application. I can just build a second façade that again implements the interface but talks to the new API. I don’t have to adjust any logic in my view or viewmodel because it uses all the same methods and returns the same types, pretty cool huh?

Okay, let’s implement the interface in a class called ComicVineApi

Code Snippet
  1. public class ComicVineApi : IApi
  2. {
  3.     public void SearchVolume(string searchString)
  4.     {
  5.         string completeUrl = ComicVineConstants.Url + "search/" + ComicVineConstants.Key + "&query=" + searchString + "&resources=volume" + "&field_list=" + ComicVineConstants.VolumeFields + ComicVineConstants.Format;
  6.  
  7.         Download(completeUrl);
  8.     }
  9.  
  10.     private void Download(string url)
  11.     {
  12.         WebClient client = new WebClient();
  13.         client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(ClientDownloadDetailStringCompleted);
  14.         client.DownloadStringAsync(new Uri(url));
  15.     }
  16.  
  17.     private void ClientDownloadDetailStringCompleted(object sender, DownloadStringCompletedEventArgs e)
  18.     {
  19.         if (e.Error == null && !e.Cancelled)
  20.         {
  21.             JsonSerializer jsonrep = new JsonSerializer();
  22.  
  23.             string json = e.Result;
  24.             Response response = new Response();
  25.  
  26.             response = jsonrep.ConvertJson(json);
  27.  
  28.             Messenger.Default.Send<Response>(response);
  29.         }
  30.         else
  31.         {
  32.             MessageBox.Show(e.Error.Message);
  33.         }
  34.     }
  35. }

So what happens here? In the SearchVolume method we build the url that contains the Comicvine API request. a complete url looks like this:

http://api.comicvine.com/search/?api_key=1234f&query=hulk&resources=volume&field_list=api_detail_url,count_of_issues,description,
image,name,start_year,site_detail_url&format=json

I removed my API key from the URL for obvious reasons, if you want to test this link out you can request your own API key at http://www.comicvine.com it’s completely free.

The ComicVineConstants is a class where I put most of my so called magic strings, strings hard coded in the application.

Code Snippet
  1. public class ComicVineConstants
  2. {
  3.     public const string VolumeFields = "api_detail_url,count_of_issues,description,image,name,start_year,site_detail_url";
  4.     public const string Key = "?api_key=1234";
  5.     public const string Url = "http://api.comicvine.com/";
  6.     public const string Format = "&format=json";
  7. }

Again, the API key is removed from this code for obvious reasons.

So once the url is build it’s passed into the download method which will start an asynchronous download by using a WebClient instance. After that the application continues to run while the JSON results are downloaded on the background, once the download is complete the DownloadStringCompletedEventHandler will fire. The eventhandler deserialises the JSON into .net objects by using JSON.net, which is available on NuGet, and sends it on it’s way.

The Messenger class is part of the Galasoft.MvvmLight.Messaging assembly. In the eventhandler we say that we want to send an object of type “Response” on the instance called “Default” of the Messenger class. Now every class that has registered to messages of type “Response” will receive the message and can act accordingly. The Messenger class helps the separation of concerns here by allowing us to send the result to any instance of any class available, without it we would have to do the download logic in the ViewModel and that just feels plain wrong.

I will end this part here. In part IV we will start building some UI, do some databinding and register our MainViewModel to the Messenger class. And we will finally start receiving some data from the Comicvine API so we can see our façade pattern in action, until then: Live long and prosper!


Tags:

.Net | WPF | Patterns | MVVM Light

Comic Organizer Part I: MVVM Light

by Nico

All right, let’s grab a beer and get this show on the road shall we?

First topic I want to discuss is MVVM, Model-View-ViewModel. A big mistake people tend to make is to call MVVM a framework, in reality MVVM is a design pattern, a best practice guide to build a structured loosely coupled application. MVVM works great in WPF, Silverlight and Windows Phone 7 development. Windows 8 Metro apps will also be great to use MVVM in.

So let’s walk through the different parts of the pattern, I know there are thousands of articles about this subject on the net but bear with me, things will get interesting.

Let’s start off with a small diagram

All right, keep this in mind and let’s start discussing the different parts.

The View

First subject is the view, the view in our WPF application will consist out of XAML files, these files describe the user interface and all the controls on them. This includes buttons, checkboxes, radiobuttons, listboxes, etc. The only thing that the view is aware off is what viewmodel it is binded too and what controls are bound to what property on the viewmodel. There is no business logic in the view and although there is a code-behind file, the rule is to keep it as clean as possible. The viewmodel and control bindings happen in the XAML code, each XAML control has a property that can be bound to a viewmodel property. An example of binding a button:

Code Snippet
  1. <Button x:Name="SearchButton" Content="Search" Margin="0,50,0,0" Command="{Binding SearchCommand, Mode=OneWay}"/>

When the button is clicked the Binding command goes searching in the viewmodel for a command called SearchCommand and executes it.

The ViewModel

The viewmodel contains all the data that needs to be shown on the view. These data are contained in properties that are bound to the controls on the view. Apart from data that is shown on the view, the viewmodel can also contain a bunch of commands that can be bound to events, most often used for a button click. The advantage of seperating form and form logic is that it’s very easy to bind a new view to an existing viewmodel, it’s just a matter of adding controls on the form and binding them to the right properties. The command used in the example of the view is defined like this:

Code Snippet
  1. public RelayCommand SearchCommand { get; private set; }

RelayCommand is a class from MVVM Light that implements the System.Windows.Input.ICommand interface.

The ICommand interface is what you need to implement if you’re not using an MVVM implementation by a third party. The interface looks like this:

Code Snippet
  1. public interface ICommand
  2.     {
  3.         bool CanExecute(object parameter);
  4.         void Execute(object parameter);
  5.         event EventHandler CanExecuteChanged;
  6.     }

The relaycommand now needs to know what method to execute when it’s called. This is usually done in an InitiateCommands method like this:

Code Snippet
  1. private void InstantiateCommands()
  2.         {
  3.             SearchCommand = new RelayCommand(LoadList);
  4.         }

This will call a method called LoadList when the button is clicked. You can, off course, use anonymous methods like this:

Code Snippet
  1. private void InstantiateCommands()
  2. {
  3.     SearchCommand = new RelayCommand(()=>
  4.                                             {
  5.                                                 //...
  6.                                             });
  7. }

for those not familiar with anonymous methods, when the button is clicked all instructions between the brackets are executed. I’ll show more examples of databinding as I get further into this serie.

The Model

The model is often a separate object and contains the business logic. Classes that process the information that the viewmodel uses to pass to the view or that is passed to the viewmodel from the view.

MVVM Light

So what is this MVVM Light thing all about? MVVM Light is an open-source MVVM implementation created by Laurent Bugnion and can be downloaded from Codeplex. MVVM Light can be installed from Codeplex or from NuGet. When you install it from Codeplex you get new project types for WP7, WPF and SilverLight. Laurent recently added a preview version for Windows 8 Metro apps. Now what sets MVVM Light apart from its competitors? For me personally, the ease of use. MVVM Light just makes sense, it’s easy to use, Laurent has some nice documentation and some videos from events where he talked about his toolkit. The toolkit also contains a great messaging system that allows an application to send messages between all classes and projects within an application, a great tool that helps you create nice loosely coupled applications. Recently a very basic IoC container was added to the toolkit, which really shows the dedication and hard work that Laurent puts in his product. The container allows the viewmodels to accept instances from classes without tight coupling them, more about that when we get to it in future posts.

I really hope this first post made some sense, it’s the first time that I’m writing a series of blogposts while learing about the subject myself. If I made any errors or you’ve got some questions, feel free to drop me a message on Twitter, mail or leave a comment.

See you soon in Part 2!


Tags:

.Net | WPF | Windows programming

Starting new blogseries

by Nico

My comic application for Windows Phone 7, called ComicDB, has been published for a good month now and as I’m working on version 2 I got an idea to build a Windows desktop application. The application will allow users to maintain a library of comic series and to keep track of owned and read issues, something I’m struggling with myself. I decided to make a blogseries about my progress, I started working on it today so I’ll try to get the first post online in a few days.

Some details:

  • WPF application
  • Metro style
  • MVVM Light
  • trying to use the SOLID principles

I’m currently learning SOLID principles and design patterns, so some refactoring might occur but I think it’ll be fun for you to follow my learning progress and it’ll be fun for me to build now and to look back to in a few years


Tags:

.Net | WPF | Windows programming

  Log in

About the author

Hi,

My name is Nico, I’m an MVP Windows Platform Development living in Belgium.
I’m currently employed as a .NET consultant at RealDolmen, one of Belgium’s leading IT single source providers.

I'm also founding member and board member of the Belgian Metro App Developer Network, a user group focussed on Windows 8 and Windows Phone development. If you're in Belgium feel free to drop by if we're doing an event. http://www.madn.be

Since June 2012 I'm a proud member of Microsoft's Extended Experts Team Belgium. And in February 2013 I became a member of DZone's Most Valuable Bloggers family.

In 2013 I became a book author and wrote "Windows 8 app projects, XAML & C# edition".

In 2014 I received the MVP award for the very first time.

I hope to get feedback from my readers either through comments, mail (nico_vermeir@hotmail.com), twitter, facebook, …

 

mvp

 

mvp

 

 

MeetLogo

 

MVBLogo

mybook

 

Month List