Nico's digital footprint

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

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

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