Grid Application MVVM Template

Introduction

I was chatting with a buddy the other day about the C# Grid Application template that comes with Visual Studio 2012 for Windows Store applications.  I followed that up with trying to explain how to correctly set it up to use MVVM, data binding, and all of the cool features that Visual Studio provides.

After a few minutes we were both frustrated because the Grid Application template that comes with Visual Studio was very poorly done and doesn’t guide the developer to using the correct coding standards.

So, I took the default template and ripped out the bad parts.  Then I built it back up using a much better MVVM model.  I also set it up so each View Model has sample data.  This allows each page to use the Visual Studio designer to setup and manage data binding.  I also added an ExtendedSplash screen as part of the template to help avoid a common failure associated with certification.

Let’s Go Already!

Let’s get setup to walk through the template.  First, download and install the template file: Grid Application MVVM Template

Now open Visual Studio 2012 and create a new project. Select the Grid Application MVVM template and type in a project name and click OK.

NewProject

One the project is created, you’ll see the solution explorer should look something like this:

SolutionExplorer1

Background Information on MVVM

Let’s take a minute to talk about the parts of “MVVM”.   It stands for Model View View Model.  But it’s easier to read as: Model, View, View Model.

The Model is the code in DataModel. The Views are the various pages, in this case, GroupDetailPage, GroupedItemsPage, and ItemDetailPage.  Finally the ViewModel is the code in the ViewModel folder.

The Model is responsible for loading the data from the data source.  This can be a database, an XML file stored on a web service, or even Azure Mobile.

The View is responsible for displaying data to the user. Sometimes this maps 1:1 with the Model, but usually it does not.  Often the View needs data from various pieces of the Model.   This is what the View Model does.

The View Model is the glue that ties the View to the Model.  If you’ve worked with MVC, the View Model is essentially the Controller.  It is responsible for knowing what data the View needs and how to get it from the Model.  The View Model can also provide sample design time data that allows the developer to use the powerful Visual Studio 2012 designer.

The Data Model

The ExampleDataSource code is fairly simple because everyone needs to access data in different ways.  In this case, we have a LoadDataAsync call that is responsible for loading the data.  There is a 2.5 second delay to simulate a delay during loading.  This lets you get a better idea how the UI reacts while data is loading.  The we just load five groups of data into our list of groups.  Once this data is loaded, we can call the other methods to retrieve items.  Also notice that each of the Get methods are async. This ensures that even if we forgot to call the LoadDataAsync method, it will still be able to load the necessary data without blocking the UI.

The two primary data classes in this template are ExampleGroup and ExampleItem.  Both of these classes inherit from BindableBase.  This allows us to bind our View directly to one of these items.  I also was careful to name each property in a unique way. This makes it easier for developers to understand how each item is loaded, processed, data bound, and finally displayed.

The ExampleGroup contains two lists. One list contains all of the child items associated with the group and the other contains the top items.  The top items property is used later to display a smaller chunk of the total data set.

The ExampleItem contains a back reference to the group, as well as all of it’s necessary properties.

The View

Let’s dig into the GroupedItemsPage view.  There are a few pieces of Visual Studio magic that make the sample items show up.  The first is the in page setting of the DataContext:

DataContext1

This actually creates an instance of the view model class, but it also ensures the properties window knows the type of object this page is bound to.  Now when I go down to a bindable property I can click on the properties window and choose Create Data Binding:

CreateDataBinding1

This will pop up a dialog that lets you choose the property to bind to:

CreateDataBinding2

Notice that the data context references our view model object, and the path window shows all of the properties of our view model.  Now I can just select what I want to bind to, and Visual Studio does all of the work.

The View Model

The View Model is the glue that joins the Data Model and the View together.  In the example of the GroupedItemsPageViewModel, we expose the AllGroups property. This contains a read only observable collection of groups.  In the constructor, we put in code to allow us to populate the view model when we are viewing it in the Visual Studio designer.

Constructor1

This is a powerful tool that lets you see your page without the need to deploy and run the code. The BaseViewModel class is a wrapper that gives you two callbacks: PreRefresh and PostRefresh.  You can override these methods if you need to perform actions before or after the view model is refreshed.  In this case, we clear the collection of groups before we refresh.  Finally, it calls us back in RefreshInternalAsync.  This let’s us query our data source to get the data we need to populate our view model.  Now our GroupedItemsPage can call our ViewModel’s LoadAsync method, and this will trigger the view model to update and reload the data bound properties.

There is a generic version of BaseViewModel that allows you to specify a class that must be provided to the view model’s LoadAsync method call.  The GroupDetailPage and ItemDetailPage both use a version of this to provide data that can be used in the RefreshInternalAsync call to get necessary info from the Data Model classes.

Other Cool Stuff

One of the common problems when loading data is the amount of time it takes to do so.  The Windows Store recommends that you make an extended splash screen to perform long loading operations.  However, having one doesn’t hurt, even if your data load is quick.  So this template provides one for you.  You can see that we call our LoadDataAsync in the ExtendedSplash’s RestoreStateAsync method.  The customer experience will be the initial splash screen is displayed, there is a slight flicker as the extended splash is loaded, then the progress ring will start spinning while the data is loaded.  As far as Windows is concerned, your application is loaded and running, but the user gets a better experience as they aren’t staring as an empty main page.

Summary

I hope this template saves you a lot of time, as well as gives you a better start for designing a true MVVM model Windows Store application.  If you have comments or questions, don’t hesitate to ask!

Posted in Hobbies, Programming | Tagged , , , | 3 Comments

Learning to Program – Part 1

Introduction

Everyone learns in different ways.  And learning to program is one of those things that is unique to the individual.  I learned by reading books and researching online, then applying that in sample programs.  One of the first things you need to decide is the programming language you want to become proficient in.

There is a lot of debate in the software world about what language is best for each application, but I still feel that some languages are better for learning than others.  For example, C# is a great language because it is so forgiving and errors are much more clear and concise.  C++ is a powerful language, but it tends to have more obscure errors and allows a much lower level access to system resources.  With that said, the language is mostly irrelevant as most high level languages have similar constructs (loops, variables, functions) and once you learn one language, it is very easy to pick up other languages.

For this series, I’ll be using C# and what we refer to in the software world as pseudocode.  Pseudocode is basically a way to write the logic of the program in a way that is not language specific.

One final note before we get started.  At first, I won’t be digging into code, and this may feel frustrating.  However, I feel it’s important to understand the concepts before we try to make something actually run.

What is a program?

Let’s begin by answering the question of: “What is a program?”  A computer program as defined on Wikipedia is “a sequence of instructions written to perform a specified task with a computer.”  Simply put, it is an ordered list of things to do.  If I had to write a program for my son to make a peanut butter and jelly sandwich I may write a pseudocode program that looks something like this:

   1: breadOne = GetBread()

   2: breadTwo = GetBread()

   3:  

   4: jelly = GetJelly()

   5: peanutButter = GetPeanutButter()

   6: plate = GetPlate()

   7: knife = GetKnife()

   8:  

   9: while ( NotCovered(breadOne) )

  10:     Spread(jelly, breadOne, knife)

  11: while ( NotCovered(breadTwo) )

  12:     Spread(peanutButter, breadTwo, knife)

  13:  

  14: PutOn(plate, breadOne)

  15: PutOn(plate, breadTwo)

This is obviously a simple example designed to help you understand the basic concept of programming and reading pseudocode.  Lines 1 and 2 are two get our two slices of bread. Lines 4-7 give us all the other supplies we need.  Lines 9 and 10 are to spread jelly on the first slice of bread.  Lines 11 and 12 spread peanut butter on the other slice.  Finally 14 and 15 put those slices on the plate.  This could be far more complex, but I kept it simple to ensure you can follow the basic flow.

Now, back to the definition.  We have a sequence of instructions written to perform a specified task, but this is in a format that a human can read.  So the last part of the programming process is to compile this code into something a computer can read.  The compiler will take these instructions and turn them into a very low level machine code that isn’t readable by a human, but it is very efficient for the computer to process.

In short, that is all there is to programming! In the next part we’ll start talking about tools of the trade.  There are a multitude of tools out there and deciding what to use for any given task can be overwhelming.

If there is a particular topic you would like to see discussed, please don’t hesitate to ask and I’ll try to answer it in comments or as it’s own post if the response demands the space.

Posted in Uncategorized | Leave a comment

HAM Radio Musings

For the past month, I have been gearing myself up to get more involved in high-frequency (HF) work on the ham radio.  My Elecraft K3 was struggling with trying to tune and the RF output was weak, so I decided to send it in to the shop.  Sadly this journey would take almost 4 weeks to complete.  In the meantime, I went to one of the local field day activities, but the pacific northwest weather would put an early end to that endeavor.  As the skies opened and dumped buckets of water, I decided to throw in the towel and go home.

Another task I have given myself is to learn Morse Code (referred to as CW which stands for continuous wave.)  I have used the website LCWO.net and I highly recommend it to anyone who is looking to learn CW.  A few quick tips:

Take the time to adjust the tone to something that is comfortable. I find 650hz to be best for me.

  • Learn at a fast speed. 20WPM is what I recommend.
  • Start with a slow effective speed.  2WPM is what I recommend.
  • Do the lessons until you get 90% or better before moving on.
  • Do 2-3 sessions a day, which totals about 5-10 minutes.
  • Once you complete all 40 lessons, turn up the effective speed.  You want to get your effective speed up to 20 WPM as well.

I have been at this for a few weeks and I’m able to copy 25 characters/symbols/numbers.  I thought it would be impossible for me to learn given my hearing disability, but the key is a good set of headphones and blocking out all distractions.

Last night I was tuned around and was listening to a beacon out of California.  These are nice because they just repeat their callsign over at a fairly slow rate.  After a few passes, I was able to completely copy the callsign!  I’ve still got a long way to go before I’m hammering out a conversation over the air, but it really hasn’t been nearly as challenging as I thought it would be.

Posted in Hobbies | Tagged , , | Leave a comment

Hobby Check-in

Hey everyone… It’s been ages since I’ve posted. I haven’t had any real progress or changes related to the game table.  The system we have works great for our game and we have been using it for over 2 years!  So what have I been doing?

Work: I have moved over to the Kinect for Windows team at Microsoft.  This has been a fun challenge and I’ve already begun to devise ways I can use this to assist our game.

Ham Radio: Since my last check-in, I have upgraded my ham license to a general class. This allows me to use a greater range of frequencies.  Along with this I bought an Elecraft K3 and an HF9V antenna.  With this system, I have managed to talk all over the world with only 100 watts of power!

Gold Prospecting: We have taken up this hobby when time permits and hope to get more actively involved.  One thing I have noticed is that it seems like the gold prospecting resources on the net are weak and disorganized.

SCA: We have been less active in our SCA involvement, but this year we plan to perform two SCA related plays at events.

Las Vegas: Finally, we are going to Vegas this year.  It’s going to be a great trip as we’ve managed to coordinate with our friends, The Gills.  We’ll be staying at the same hotel, showing up at the same time, and hopefully winning big!

Posted in Uncategorized | 2 Comments

Touchscreen and Token Recognition Update

Last night I stumbled on an open source solution called reacTIVision.  It is a client/server setup that has sample C# client code. I just finished porting my token tool over to use this new solution and it is VERY promising.  I managed to prove that it can recognize a token, associate that token to an in game token from the MapTool program.  And finally, I’m able to send that info over the wire to MapTool to update the location of a token.

There are a few problems, but I have potential solutions. The problem with the projector washing out the markers might be fixed by using a nightvision style webcam that uses bright IR light to illuminate the bottom of the tokens with a massive amount of light that humans can’t see.  I haven’t tested this yet as I need to pick up some source of bright IR light, and a camera that is tuned to that wavelength.

The other cool part? This library is smart enough to detect “finger” sized points of light, meaning that it might be able to easily support a true “touch” system! I’ll update more later and if I get it working 100%, I’ll get some video to share!

Posted in Uncategorized | 2 Comments

New Blog Series – Life as a DM

I was pondering today about updating my blog to provide some insight into how my mind works as a DM.  I think the best place to start is at the beginning.  So, for today’s installment…

In the Beginning

I have many memories of playing D&D as a kid.  I remember my mom going through a religious phase and telling me that D&D made her uncomfortable.  She said it felt a lot like devil worshiping.  This, of course, didn’t stop me from playing.  I was probably only 10 or 12 years old (1986-1988), but I knew it was just a game where kids get to do what they do best, use their imagination.

So I read through my cousin’s books (red/blue/and green) and learned what I felt were the rules we were supposed to follow, then my cousin and I took turns making characters and running adventures for each other.  Thinking back, we were probably not following many rules, and none of our adventures really had a plot or purpose, but we did accomplish one important goal that every DM and player should strive for: Have Fun

I remember one of our games went like this: “You are at a town and they ask you to go save the princess from the cave. So you head out of town and you are walking down a path…  you keep going… a little more… then you see a clearing… like this (draws simple map on paper)… and goblins jump out and attack.”  As you can see, role playing and plot were far less important.  Heck, rules weren’t very important either.  We merely needed someone to provide the idea of a game, and we could play for hours!

Share your stories of your first D&D experience… Was it good? Bad? Were you the DM? A player?

Posted in Dungeons and Dragons | Leave a comment

The Game Table – A living thing

Well, we’ve been using the digital game table for a season and it has been wonderful.  As with all systems, the more you use it, the more ideas you get.  The Wiimote interface works, but sometimes it gets the IR pens get a little flaky.  Plus, it only allows one input at a time.  This doesn’t cause many problems, but sometimes we do see issues.

Talking with my wife and the other players, we considered using public libraries to produce a camera recognition application that can track markers on the table surface.  This allow us to toss markers on the table and they can be moved independently and at the same time. The camera will track these markers and tell Maptool to move the in game tokens.

Essentially this requires a custom app and a small change to the Maptool program to allow for a custom message that says what to do.  The long of the short, no more wiimote will be necessary.  Just 5 colored markers that sit on the table for the camera to track. Ahh.. progress.  I was able to get it working tonight.  Once I work out some small kinks, I’ll record a video and demo it.

Posted in Uncategorized | 5 Comments