Nico's digital footprint

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

Techdays Belgium 2012

by Nico

So Techdays is right around the corner and I’ll be attending for the third time.I’ll be attending all kinds of sessions going from Windows 8 development to the complete deep dive track on web to my favorite subject, Windows Phone 7 development. I’m also excited about the Scott “The Gu” Guthrie doing the opening keynote and doing a session the second day. Also presenting this year is Laurent Bugnion, the father of the awesome MVVM Light framework.

Here’s the list of sessions I’ll be attending, this list is subject to change depending on if I change my mind the last minute, as I’m known to do sometimes Glimlach.

Tuesday February 14th

  • Opening keynote with Scott Guthrie
  • Welcome to the Metro Application Platform
  • Windows Phone Fast App Switching, Tombstoning and Multitasking
  • The Future of C# and Visual Basic
  • Devices + Cloud: Using Azure on iOS, Android, Windows Phone, …

Wednesday February 15th

  • ScottGu unplugged
  • Take a ride on the Metro
  • The zen of async: Best practices for best performance
  • MVVM Applied: From Silverlight to Windows Phone to Windows 8
  • MVVM & WCF RIA Services: an architectural story
  • Building a data intensive application

Thursday February 16th

This is a deep dive day, I’ll be following the web track that focuses on what’s new in ASP.net 4.5 and Visual Studio 11

 


Tags:

.Net | Presenting | WP7 | Windows programming | XAML | XNA | Web development | MVVM Light | Devices

BlockAddiction: My WP7 XNA game

by Nico

On 8 January my very first game was published to the Windows Phone marketplace. It’s a very simple game called BlockAddiction, the purpose is to keep stacking the blocks on top of each other while they keep speeding up. Now, 19 days later I’ve reached over 250 downloads with this. It may not seem like a lot but I’m pretty pleased with the result Glimlach

Right now, I’m working on version 2.0 and it will include a new game mode and some changes:

  • Time Attack mode: stack as many blocks as possible within 60 seconds without dying (player has 3 lives)
  • About page
  • Maybe some ads but only on the menus, I want the game experience to remain the same and completely ad-free

Time Attack mode is almost complete, just have to develop the difference between time up and game over. Then I need to find out how to add an about page to an XNA game, but more about that later.

For those who want to try out the current version of BlockAddiction, search for it on the marketplace or click here!


Tags:

.Net | WP7 | XNA

Overview of WP7 devices

by Nico

I’ve created an overview of all currently known Windows Phone devices. I’ll try to keep this as up-to-date as possible but don’t shoot me if it takes some time to add new devices to the list Glimlach.

Every device is linked to a site with all specifications. You can find the page by clicking the link on the right or by clicking here.

For those that are too lazy to check the page, I’ll paste the list here:

Name Release Date CPU speed Memory Display Notes
Acer Allegro November 2011 1 GHz 8GB 3.6" LCD No flash
Dell Venue Pro November 2010 1 GHz 8GB/16GB 4.1" AMOLED Portrait keyboard
Fujitsu Toshiba IS12T September 2011 1 GHz 32GB 3.7" LCD 13.2MP camera and waterproof
HTC Pro 7 January 2011 1 GHz 8GB/16GB 3.6" LCD  
HTC Surround November 2010 1 GHz 16GB 3.8" LCD slide out speaker
HTC Trophy October 2010 1 GHz 8GB/16GB 3.8" SLCD  
HTC Mozart October 2010 1 GHz 8GB/16GB 3.7" SLCD Xenon flash
HTC HD7 October 2010 1 GHz 8GB/16GB 4.3" SLCD  
HTC Titan October 2011 1.5GHz 16GB 4.7" SLCD  
HTC Titan II March 2012 1.5GHz 16GB 4.7" SLCD 16MP camera, 4G LTE
HTC Radar October 2011 1 GHz 8GB 3.8" SLCD  
LG Optimus 7 October 2010 1 GHz 16GB 3.8" LCD DLNA support
LG Quantum October 2010 1 GHz 16GB 3.5" LCD  
Nokia Lumia 710 November 2011 1.4 GHz 8GB 3.7" LCD  
Nokia Lumia 800 November 2011 1.4 GHz 16GB 3.7" ClearBlack AMOLED N9 design
Nokia Lumia 900 March 2012 1.4 GHz 16GB 4.3" ClearBlack AMOLED 4G LTE
Samsung Focus November 2010 1 GHz 8GB 4" Super AMOLED microSD support
Samsung Focus S November 2011 1.4 GHz 16GB 4.3" Super AMOLED  
Samsung Omnia 7 October 2010 1 GHz 8GB/16GB 4" Super AMOLED  
Samsung Omnia W November 2011 1.4 GHz 8GB 3.7" Super AMOLED  
ZTE Tania December 2011 1 GHz 4GB 4.3" LCD  

Tags:

Devices | WP7

Nokia Lumia 800 launch party

by Nico

Last friday Nokia Belgium officially showed the Lumia 800 to the crowd in Belgium. 1300 people signed up for the event, 100 received an invitation. I was one of the lucky few that was there.

The party started at 6PM in the Event Lounge in Brussels. The lounge was nicely decorated with balloons, banners and promo girls from Nokia. Microsoft had some xbox360 systems available with Kinect for some fun and entertainment (Fruit Ninja Kinect is a blast!). Immediately at the entrance there was a possibility to try the Lumia 800 in all its different colors. After about an hour of fun and networking it was time to start the presentations.

The first speaker was Jurgen Thysmans, Communications Manager at Nokia Belgium. He told the audience that the Lumia 800 will be available on the 1st of February for about 499 euros. The Lumia 710 will be available on the 1st of March exclusively at Proximus, a Belgian provider. No price was given for the 710.

After Jurgen a reviewer from ZDnet took over, he wrote a review on the Lumia 800 and had some negative points about the device. Afterwards it became clear that he wrote a review based on a prototype with pre-release hard and software. Where I come from we call that a Preview but hey, what’s in a word… His mock-up of the Microkia logo was pretty funny but that’s about all I remember about his talk.

Closing the presentation was Jeroen Van Hees, he’s a Portfolio Manager at Microsoft Belgium. He gave us a live demo on his personal Lumia 800 device, whooing a lot of the guests with the snappyness of WP7 and the awesome design of the Lumia. The reactions were amazing, both in the room and on Twitter (hashtag #lumiabxl).

After the presentation, a young lady from Nokia did some challenges like Ben the pc guy did on CES. She challenged the attendees to put their non-WP7 smartphone against the Lumia, if they could beat her they’d receive a Nokia Play 360 wireless speaker. She smoked them all. Off course, the challenges were made to compliment the features of WP7, like taking pictures from the lockscreen, posting messages on Twitter, Facebook and LinkedIn at the same time.

After the presentations it was time for food and drinks, did some more networking, met some really cool guys. It was a very fun and entertaining evening, and I got a Nokia Play 360 because I smoked the girl with the Lumia using my own Lumia 800 Glimlach

Thank you Microsoft and Nokia for an awesome event and see you hopefully at the Lumia 900 launch event!

For all the pictures, check out my SkyDrive.
All pictures are taken with my Lumia 800.


Tags:

WP7

FollowMyFeed app submission: the result

by Nico

Yesterday, a few days after I submitted my app that was generated by FollowMyFeed (see previous blog post) I got the result. The app passed certification and is now available on the marketplace. Hooray!

But there’s one thing that’s kind off weird. The marketplace certification rules clearly say that every app should launch and be ready to use in under 5 seconds. The generated app takes 7-8 seconds on my Omnia 7. I can think of two reasons why the app still passed certification.

  • The test team only used second generation devices and they boot up the apps faster
  • They don’t care since FollowMyFeed is a Microsoft product and it would be bad for them if they shot down apps generated by their own software.

Anyhow, now you can have an app to read my blog and follow my Twitter feed. Get the app here


Tags:

.Net | WP7 | XAML

FollowMyFeed: generate WP7 apps without any coding

by Nico

Some time ago MIcrosoft launched a website called FollowMyFeed. The site is a service that allows anyone with an RSS feed to generate an application for Windows Phone 7 in mere minutes, without any coding. Sounds like fun, so I decided to test the service with the RSS from this blog.

These are the features, copied from the site:

  • Multiple RSS feeds
  • Logo, Tile, Background, Pivotbackground custom
  • Offline content
  • Comments (online)
  • Share to social networks (online)

Before you get started you do need to prepare some graphics like a splash screen, background and icons. For this purpose Microsoft put some templates on FollowMyFeed in both Photoshop and Paint.Net format. The templates are in a zip file and contain all the graphics needed to build an app. All graphics accept all the different icon sizes that are needed, luckily there’s an app for that. Someone build an app that takes an image, you select a square that you want used as icons, click save and the app will save the icon in all the necessary sizes. WP IconMaker can be found here (codeplex).

Generating a new application is as easy as following a small wizard, selecting the correct graphics and colors, setting the RSS feed and you’re done. I did encounter 1 issue, when I uploaded the splash screen it didn’t work. A splash screen can be maximum 480x800 pixels, the resolution of all WP7 devices, my splash screen was exactly that size but didn’t work. I’ve resized it to 479x799 and it worked flawlessly. Besides this small bug I didn’t encounter any problems, I’ve downloaded the .XAP file, installed it onto the emulator to take some screenshots and submitted it to the marketplace, once I got the result of my submission, I’ll let you know.

I made some screenshots of the entire process, those can be found here


Tags:

.Net | WP7 | XAML

Binding a dynamic Pivot in Windows Phone 7

by Nico

I’m currently working on a Windows Phone 7 application that needs a dynamic Pivot. For every item in a list there should be a pivot item. Besides that, every dynamic pivot item should have a listbox that is bound to another list. I found very little information on these topics so I decided to write it down myself.

Both the header binding and the listbox binding are done from the same class. The class is called DemoClass and contains a string Name that will be bound to the header of the pivot item and a list of strings called Result that will be bound to the pivot item’s body. Here’s the code for the class:

Code Snippet
  1. using System.Collections.ObjectModel;
  2.  
  3. namespace BindingDynamicPivotDemo
  4. {
  5.     public class DemoClass
  6.     {
  7.         public string Name { get; set; }
  8.         public ObservableCollection<string> Result { get; set; }
  9.  
  10.         public DemoClass()
  11.         {
  12.             Result = new ObservableCollection<string>();
  13.         }
  14.     }
  15. }

I used ObservableCollection here instead of List because ObservableCollection already implements INotifyPropertyChanged and takes care of notifying all it’s subscribers when it changes. It’s perfectly possible to use a IList<string> instead of the ObservableCollection but then the DemoClass needs to implement INotifyPropertyChanged. In the constructor of the class the collection gets initialized.

Next thing I needed was a viewmodel to bind to my xaml page. The viewmodel declares a collection of DemoClass instances and fills those instances with dummy data.

Code Snippet
  1. using System;
  2. using System.Collections.ObjectModel;
  3.  
  4. namespace BindingDynamicPivotDemo
  5. {
  6.     public class MainViewModel
  7.     {
  8.         public ObservableCollection<DemoClass> PivotItems { get; set; }
  9.         
  10.         public MainViewModel()
  11.         {
  12.             PivotItems = new ObservableCollection<DemoClass>();
  13.  
  14.             //load pivot headers
  15.             LoadData();
  16.  
  17.             //load random dummy data for the pivot body
  18.             FillLists();
  19.         }
  20.  
  21.         public void LoadData()
  22.         {
  23.             //pivot headers
  24.             for (int i = 1; i <= 10; i++)
  25.             {
  26.                 DemoClass newClass = new DemoClass {Name = "pivotItem " + i};
  27.  
  28.                 PivotItems.Add(newClass);
  29.             }
  30.         }
  31.  
  32.         public void FillLists()
  33.         {
  34.             Random rnd = new Random();
  35.  
  36.             //fill each list with dummy data, this will be shown in the pivot body
  37.             foreach (DemoClass pivotItem in PivotItems)
  38.             {
  39.                 pivotItem.Result.Clear();
  40.  
  41.                 for (int j = 0; j < 10; j++)
  42.                 {
  43.                     pivotItem.Result.Add("item " + rnd.Next(0, 1000));
  44.                 }
  45.             }
  46.         }
  47.     }
  48. }

I am again using an ObservableCollection for the same reason as I did in the DemoClass. LoadData() creates 10 instances of DemoClass and adds them to the PivotItems collection. FillLists() will fill the Result collection of every DemoClass instance with random dummy data.

Next step is to let the view know where it needs to look for its data. This can be done from xaml or from code behind. MVVM Light takes the xaml approach while the default Visual Studio projects do it from code behind, since this is a default project I followed the code behind approach. This is how my MainPage.xaml.cs looks liks.

Code Snippet
  1. using System.Windows;
  2. using Microsoft.Phone.Controls;
  3.  
  4. namespace BindingDynamicPivotDemo
  5. {
  6.     public partial class MainPage : PhoneApplicationPage
  7.     {
  8.         // Constructor
  9.         public MainPage()
  10.         {
  11.             InitializeComponent();
  12.  
  13.             // Set the data context of the listbox control to the sample data
  14.             DataContext = App.ViewModel;
  15.         }
  16.  
  17.         private void Button_Click(object sender, RoutedEventArgs e)
  18.         {
  19.             App.ViewModel.FillLists();
  20.         }
  21.     }
  22. }

Instantiation of the ViewModel occurs in App.xaml.cs and is auto-generated code. The Button_Click method is an event handler for a button, obviously. It will call a method on the ViewModel that regenerates new random dummy data for the pivot body. This shows how an ObservableCollection gives a powerful auto-updating binding while keeping the DemoClass nice and clean.

Now let’s take a look at the xaml and specifically at the bindings. This is the MainPage.xaml.

Code Snippet
  1. <Grid x:Name="LayoutRoot" Background="Transparent">
  2.         <!--Pivot Control-->
  3.         <controls:Pivot x:Name="PivotPlatform" Margin="0,0,8,77" Title="BindingDynamicPivotDemo" ItemsSource="{Binding PivotItems}" >
  4.             <controls:Pivot.HeaderTemplate>
  5.                 <DataTemplate>
  6.                     <TextBlock Text="{Binding Name}"/>
  7.                 </DataTemplate>
  8.             </controls:Pivot.HeaderTemplate>
  9.             <controls:Pivot.ItemTemplate>
  10.                 <DataTemplate>
  11.                     <ListBox ItemsSource="{Binding Result}">
  12.                         <ListBox.ItemTemplate>
  13.                             <DataTemplate>
  14.                                 <TextBlock TextWrapping="Wrap" Text="{Binding}" />
  15.                             </DataTemplate>
  16.                         </ListBox.ItemTemplate>
  17.                     </ListBox>
  18.                 </DataTemplate>
  19.             </controls:Pivot.ItemTemplate>
  20.         </controls:Pivot>
  21.         <Button Content="Randomize" HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="0,0,0,4" Click="Button_Click"/>
  22.     </Grid>

I only pasted the layoutRoot grid here because all the xml namespaces are the default ones from a WP7 project. So for starters I’ve bound the Pivot’s ItemsSource to the PivotItems collection. Then I declare two templates, the header template is the title of the pivot item, by binding it to name it will use the Name property from the DemoClass. Since the Pivot’s ItemsSource is bound to PivotItems, the textblock in the header template is now bound to PivotItems.Name. The itemtemplate is what makes up the pivot’s body, it contains a listbox that is bound to PivotItems.Result. Underneath the pivot is a button that triggers the event handler in MainPage.xaml.cs.

When this is executed you’ll see an automatically generated pivot bound to dummy data, every time the button is clicked new data will be generated and shown in the pivot immediately thanks to the ObservableCollection.

screen

The source of this project can be found here.

Conclusion

In this small article I explained how you can databind a pivot so that it’s items are automatically generated and bound to other properties. It’s not hard to do but it took me some time to figure out so I hope I’ve helped someone by writing down my findings.


Tags:

.Net | WP7 | XAML | Binding | Silverlight

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 II: Going metro

by Nico

In part 1 I talked about MVVM and MVVM Light, I hope you learned something from it. Now it’s time to move on to the next part, we’re going to start building a WPF application.

First things first, here are the tools I’m going to use:

The WPF toolkit is a set of controls that extend the default WPF controls, it’s build by Microsoft and updated a few times a year.

If the MVVM Light toolkit is installed you should see new project types when creating a new project in Visual Studio. I’m going to create a new WPF 4 project.

Now that the project is created, take a look at the solution explorer, there you will find the MVVM parts nicely ordered in separate folders. If you want you can take them and put every part in a separate project, I won’t be doing that for my application since it’s pretty small.

 

Now that we got our project, let’s metronize it. For this we need to open the solution in Expression Blend. The best way to work on XAML based projects is to open the solution in both Visual Studio and Expression Blend, changes made in one will automatically be reflected in the other.

Metro isn’t a style that is out of the box available for WPF. While searching for a way to imitate the Metro windows like Microsoft uses it in Zune I stumbled upon the blog of Steven Hook. He had the idea of using the Wingdings font for the upper right buttons. Sounds weird? Let me show you how it works.

In Expression Blend I’ve set the WindowsStyle property to “None” and ResizeMode to “ResizeWithGrip”, the generated XAML looks like this

Code Snippet
  1. <Window x:Class="ComicOrganizer.MainWindow"
  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.         mc:Ignorable="d"
  7.         Title="Comic Organizer"
  8.         DataContext="{Binding Main, Source={StaticResource Locator}}" WindowStyle="None" ResizeMode="CanResizeWithGrip" AllowsTransparency="True">

This gives a clean white window without borders that can be resized by using the grip in the lower right corner. Next step is adding the controls for closing, maximizing and minimizing the window. This is the XAML responsible for those buttons

Code Snippet
  1. <Grid
  2.     x:Name="HeaderGrid"
  3.     Height="50"
  4.     VerticalAlignment="Top" Grid.ColumnSpan="2">
  5.     <Grid
  6.         x:Name="DragableArea"
  7.         Background="White"
  8.         MouseDown="DragableGridMouseDown"/>
  9.     <StackPanel
  10.         Orientation="Horizontal"
  11.         Margin="0,5,5,0"
  12.         HorizontalAlignment="Right"
  13.         VerticalAlignment="Top"
  14.         Background="White">
  15.         <TextBlock
  16.             x:Name="ChangeViewButton"
  17.             Text="2"
  18.             FontFamily="Webdings"
  19.             Foreground="Gray"
  20.             Margin="0"
  21.             VerticalAlignment="Top"
  22.             HorizontalAlignment="Right"
  23.             MouseLeftButtonUp="ChangeViewButtonMouseLeftButtonUp" />
  24.         <TextBlock
  25.             x:Name="MinimizeButton"
  26.             Text="0"
  27.             FontFamily="Webdings"
  28.             Foreground="Gray"
  29.             Margin="5,0,0,0"
  30.             HorizontalAlignment="Right"
  31.             VerticalAlignment="Top"
  32.             MouseLeftButtonUp="MinimizeButtonMouseLeftButtonUp" />
  33.         <TextBlock
  34.             x:Name="MaximizeButton"
  35.             Text="1"
  36.             FontFamily="Webdings"
  37.             Foreground="Gray"
  38.             Margin="5,0,0,0"
  39.             HorizontalAlignment="Right"
  40.             VerticalAlignment="Top"
  41.             MouseLeftButtonUp="MaximizeButtonMouseLeftButtonUp" />
  42.         <TextBlock
  43.             x:Name="CloseButton"
  44.             Text="r"
  45.             FontFamily="Webdings"
  46.             Foreground="Gray"
  47.             Margin="5,0,0,0"
  48.             HorizontalAlignment="Right"
  49.             VerticalAlignment="Top"
  50.             MouseLeftButtonUp="CloseButtonMouseLeftButtonUp" />
  51.     </StackPanel>
  52. </Grid>

The “DragableArea” grid will allow the application to be dragged around the screen by the user, just like any app does. The Stackpanel takes care of the 4 buttons in the upper right corner.

Now we need to implement the logic for these buttons, the buttons are actually textblocks but will behave like buttons. The blog that I got this idea from said that the logic of the buttons is the responsibility of the view, so even in an MVVM application it could be placed in the code behind file of the view. I tend to agree with this logic so I’m going to place it in the code behind as well, although it’s perfectly possible to put it in the ViewModel.

The complete code behind file looks like this:

Code Snippet
  1. using System.Windows;
  2. using System.Windows.Input;
  3. using ComicOrganizer.ViewModel;
  4.  
  5. namespace ComicOrganizer
  6. {
  7.     /// <summary>
  8.     /// Interaction logic for MainWindow.xaml
  9.     /// </summary>
  10.     public partial class MainWindow : Window
  11.     {
  12.         /// <summary>
  13.         /// Initializes a new instance of the MainWindow class.
  14.         /// Metro style logic is done here because it's the responsibility of the View
  15.         /// idea found on http://stevenhook.blogspot.com/2011/01/wpf-borderless-window-controls.html
  16.         /// </summary>
  17.         public MainWindow()
  18.         {
  19.             InitializeComponent();
  20.             Closing += (s, e) => ViewModelLocator.Cleanup();
  21.         }
  22.  
  23.         private void CloseButtonMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
  24.         {
  25.             Close();
  26.         }
  27.  
  28.         private void MaximizeButtonMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
  29.         {
  30.             WindowState = WindowState.Maximized;
  31.         }
  32.  
  33.         private void ChangeViewButtonMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
  34.         {
  35.             WindowState = WindowState.Normal;
  36.         }
  37.  
  38.         private void MinimizeButtonMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
  39.         {
  40.             WindowState = WindowState.Minimized;
  41.         }
  42.  
  43.         private void DragableGridMouseDown(object sender, MouseButtonEventArgs e)
  44.         {
  45.             if (e.ChangedButton == MouseButton.Left)
  46.                 DragMove();
  47.         }
  48.     }
  49. }

 

These little methods speak for themselves, if you have any questions about them feel free to leave a comment or contact me via mail, twitter, …

That was it for this second part, we now have a running WPF application in Metro style using some easy tricks. I believe that Microsoft will give a real Metro style out to the community, when they do I’ll probably convert this app to use the real style.

In part III we’ll start receiving data and maybe some databinding as well, who knows? Glimlach

Stay tuned for part III in a couple of weeks!


Tags:

.Net | Windows programming

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

  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