13 people following this project (follow)

Project Description
Some sample code demonstrating how various GUI architectural patterns can be implementing in WPF.

These patterns include:
  • Autonomous View
  • Passive View
  • Supervising Controller
  • MVVM/ViewModel/Presentation Model

In case you are wondering, Model-View-Presenter is covered in the list. Supervising Controller and Passive View are two flavors of MVP.

Be sure to check out http://caliburn.codeplex.com for an excellent WPF/Silverlight framework.

 Christopher Bennage News Feed 
Friday, April 27, 2012  |  From Christopher Bennage

It’s common for a single web page to include data from many sources. Consider this screen shot from Project Silk. There are four separate items displayed.





The primary concern of the page is displaying a list of vehicles. However it also displays some statistics and a set of reminders. I labeled the stats and reminders as orthogonal because they are (in a sense) independent of the primary concern. Finally, there is the ambient data of the currently logged in user. I call this data ambient because we expect it to be present on all the pages in the application.



It’s a common practice in MVC-style applications to map a single controller action to a view. That is, it is the responsibility of a single action to produce everything that is needed to render a particular web page.



The difficulty with this approach is that other pages often need to render the same orthogonal data. Let’s examine the code for the action invoked by \vehicle\list.



public ActionResult List()
{
    AddCountryListToViewBag();

    var vehicles = Using<GetVehicleListForUser>()
        .Execute(CurrentUserId);

    var imminentReminders = Using<GetImminentRemindersForUser>()
        .Execute(CurrentUserId, DateTime.UtcNow);

    var statistics = Using<GetFleetSummaryStatistics>()
        .Execute(CurrentUserId);

    var model = new DashboardViewModel
                    {
                        User = CurrentUser,
                        VehicleListViewModel = new VehicleListViewModel(vehicles),
                        ImminentReminders = imminentReminders,
                        FleetSummaryStatistics = statistics
                    };

    return View(model);
}


Disregarding how you might feel about the Using<T> method to invoke commands and other such details, I want you to focus on the fact that the controller is composing a model. We generate a number of smaller viewmodels and then compose them into an instance of DashboardViewModel. The class DashboardViewModel only exists to tie together the four, otherwise independent data.





Project Silk had separate actions just to serve up JSON:



public JsonResult JsonList()
    {
        var list = Using<GetVehicleListForUser>()
            .Execute(CurrentUserId)
            .Select(x => ToJsonVehicleViewModel(x))
            .ToList();

        return Json(list);
    }


You’ll notice that both JsonList and List use the same GetVehicleListForUser command for retrieving their data. JsonList also projected the data to a slightly different viewmodel.


Reducing the Code



While reevaluating this code for Project Liike, we decided to employ content negotiation. That is, we wanted a single endpoint, such as \vehicle\list, to return different representations of the data based upon a requested format. If the browser requested JSON, then \vehicle\list should return a list of the vehicles in JSON. If the browser requested markup, then the same endpoint should return HTML.



First, we needed to eliminate the differences between the JSON viewmodel and the HTML viewmodel. Without going deep into details, this wasn’t hard to do. In fact, it revealed that we had some presentation logic in the view that should not have been there. The real problem was that I wanted the action to look more like this:



public ActionResult List()
{
    var vehicles = Using<GetVehicleListForUser>()
        .Execute(CurrentUserId);

    return new ContentTypeAwareResult(vehicles);
}


Only, the view still needed the additional data of statistics and reminders. How should the view get it?



We decided to use RenderAction. RenderAction allows a view to invoke another action and render the results into the current view.



We needed to break out the other concerns into their own actions. For the sake of example, we’ll assume they are both on the VehicleController and named Reminders and Statistics. Each of these action would be responsible for getting a focused set of data. Then in the (imaginary) view for List we could invoke the actions like so:



// List.cshtml 
<ul>
@foreach (var vehicle in Model)
{
    <li>@vehicle.Name</li>
}
</ul>

<section role="reminders">
@{ Html.RenderAction( "Reminders", "Vehicle") }
</section>

<section role="statistics">
@{ Html.RenderAction( "Statistics", "Vehicle") }
</section>




The value of using RenderAction is that we where able to create very simple actions on our controllers. We were also able to reuse the actions for rendering both markup and JSON.



A secondary benefit is the separation of concerns. For example, because we moved the responsibility of composition from the controller into the view, a designer could now revise the view for the \vehicle\list without needing to touch the code. They could remove any of the orthogonal concerns or even add new ones without introducing any breaking changes.


The Downside



There are a few caveats with this approach.



First, don’t confuse RenderAction with RenderPartial. RenderAction is for invoking a completely independent action, with its own view and model. RenderPartial is simply for renders a view based on a model passed to it (generally derived from the main viewmodel).



Secondly, avoid using RenderAction to render a form. It’s likely won’t work the way you’d expect.This means that any form rendering will need to occur in your primary view.



Thirdly, using RenderAction breaks the model-view-controller pattern. What I mean is that, in MVC, it’s assumed that the view does nothing more than render a model. Controllers invoke a view, and not vice versa. Using RenderAction breaks this rule. Personally, I have no problem breaking the rule when it results in code that is more simple and more easily maintained. Isn’t that the whole point of best practices anyway?

Tuesday, February 07, 2012  |  From Christopher Bennage

Acknowledgment: This is meant to be the Windows equivalent of Anders Janmyr’s excellent post on the subject of finding stuff with Git. Essentially, I’m translating some of Anders’ examples to Powershell and providing explanations for things that many Windows devs might not be familiar with.



This is the third in a series of posts providing a set of recipes for locating sundry and diverse thingies in a Git repository.


Determining when a file was added, deleted, modified, or renamed



You can include the –diff-filter argument with git log to find commits that include specific operations. For example:



git log –diff-filter=D # delete
git log –diff-filter=A # add
git log –diff-filter=M # modified
git log –diff-filter=R # rename


There are additional flags as well. Check the documentation. By default, git log just returns the commit id, author, date, and message. When using these filters I like to include –summary so that the list of operations in the commit are included as well.



N.B. If you run a git log command and your prompt turns into a : simply press q to exit.



I don’t think that you would ever want to return all of the operations of a specific type in the log however. Instead, you will probably want to find out when a specific file was operated on.



Let’s say that something was deleted and you need to find out when and by whom. You can pass a path to git log, though you’ll need to preced it with and a space to disambiguate it from other arguments. Armed with this and following Ander’s post you would expect to be able to do this:



git log –diff-filter=D –summary – /path/to/deleted/file


And if you aren’t using Powershell this works as expected. I tested it with Git Bash (included with msysgit) and good ol’ cmd as well. Both work as expected.



However, when you attempt this in Powershell, git complains that the path is an ambiguous arugment. I was able to, um, “work around” it by creating an empty placeholder file at the location. Fortunately, Jay Hill heard my anguish on Twitter and dug up this post from Ethan Brown. In a nutshell, Powershell strips out the . You can force it to be recognized by wrapping the argument in double qoutes:



git log –diff-filter=D –summary "–" /path/to/deleted/file


That works!



I’m guessing that Powershell considers to be an empty arugment and therefore something to be ignored. I also assume that when the file actually exists at the path that git is smart enough to recognize the argument as a path. (Indeed, the official documentations says that “paths may need to be prefixed”).



While we’re here, I also want to point out that you can use wild cards in the path. Perhaps you don’t know the exact path to the file, but you know that it was named monkey.js:



git log –diff-filter=D –summary – **/monkey.js


Happy hunting!

Wednesday, February 01, 2012  |  From Christopher Bennage

Acknowledgment: This is meant to be the Windows equivalent of Anders Janmyr’s excellent post on the subject of finding stuff with Git. Essentially, I’m translating some of Anders’ examples to Powershell and providing explanations for things that many Windows devs might not be familiar with.



This is the second in a series of posts providing a set of recipes for locating sundry and diverse thingies in a Git repository.


Finding content in files



Let’s say that there are hidden monkeys inside your files and you need to find. You can search the content of files in a Git repositor by using git grep. (For all you Windows devs, grep is a kind of magical pony from Unixland whose special talent is finding things.)



# find all files whose content contains the string ‘monkey’
PS:\> git grep monkey


There several arguments you can pass to grep to modify the behavior. These special arguments make the pony do different tricks.



# return the line number where the match was found
PS:\> git grep -n monkey

# return just the file names
PS:\> git grep -l monkey

# count the number of matches in each file
PS:\> git grep -c monkey


You can pass an arbitrary number of references after the pattern you’re trying to match. By reference I mean something that’s commit-ish. That is, it can be the id (or SHA) of a commit, the name of a branch, a tag, or one of the special identifier like HEAD.



# search the master branch, and two commits by id, 
# and also the commit two before the HEAD
PS:\> git grep monkey master d0fb0d 032086 HEAD~2


The SHA is the 40-digit id of a commit. We only need enough of the SHA for Git to uniquely identify the commit. Six or eight characters is generally enough.



Here’s an example using the RavenDB repo.



PS:\> git grep -n monkey master f45c08bb8 HEAD~2

master:Raven.Tests/Storage/CreateIndexes.cs:83:         db.PutIndex("monkey", new IndexDefinition { Map = unimportantIndexMap });
master:Raven.Tests/Storage/CreateIndexes.cs:90:         Assert.Equal("monkey", indexNames[1]);
f45c08bb8:Raven.Tests/Storage/CreateIndexes.cs:82:          db.PutIndex("monkey", new IndexDefinition { Map = unimportantIndexMap });
f45c08bb8:Raven.Tests/Storage/CreateIndexes.cs:89:          Assert.Equal("monkey", indexNames[1]);
HEAD~2:Raven.Tests/Storage/CreateIndexes.cs:83:         db.PutIndex("monkey", new IndexDefinition { Map = unimportantIndexMap });
HEAD~2:Raven.Tests/Storage/CreateIndexes.cs:90:         Assert.Equal("monkey", indexNames[1]);


Notice that each line begins with the name of the commit where the match was found. In the example above where we asked for the line numbers, the results were in the pattern:



[commit ref]:[file path]:[line no]:[matching content]


N.B. I had one repository that did not work with git grep. It was because my ‘text’ files were encoded UTF-16 and git interpretted them as binary. I converted them to UTF-8 and the world became a happy place.


References


Sunday, January 29, 2012  |  From Christopher Bennage

Acknowledgment: This is meant to be the Windows equivalent of Anders Janmyr’s excellent post on the subject of finding stuff with Git. Essentially, I’m translating some of Anders’ examples to Powershell and providing explanations for things that many Windows devs might not be familiar with.



This is the first in a series of posts providing a set of recipes for locating sundry and diverse thingies in a Git repository.


Finding files by name



Let’s say that you want locate all the files in a git repository that contain ‘monkey’ in the file name. (Finding monkeys is a very common task.)



# find all files whose name matches ‘monkey’
PS:\> git ls-files | Select-String monkey


This pipes the output of git ls-files into the Powershell cmdlet Select-String which filters the output line-by-line. To better understand what this means, run just git ls-files.



Of course, you can also pass a regular expression toSelect-String (that is, if you hate yourself.)


References




[Next, searching for files with specific content.](/blog/2012/02/01/finding-stuff-in-your-git-repo-2/)
–>

Monday, January 09, 2012  |  From Christopher Bennage

My interest in making software well is an accident. What I’m really interested in is living life well. Chasing that chimerical beast of software “best practices” is merely a happy side-effect.



To that end, there’s an ancient maxim: ‘know thyself’. Despite over three decades of living with myself, I am often surprised by what I do. Surprised, and many times embarassed.



For example, last week I complained on twitter about what I had perceived as selfish and inconsiderate behavior of some of my fellow employees. It was quickly pointed out to me that I was wrong; that I was completely misinterpreting my observations.



Once I realized my mistake, my immediate thought was “Oh, I don’t want people to think that I’m a jerk. I wish I hadn’t said that”. Shortly afterwards though, I realized that I had been more concerned about what other people thought and not my real problem. The real problem was that I was a jerk. I had judged people I did not know with only scant evidence. This reminded me of another ancient maxim: “judge not, that ye be not judged”.



Now, here is the surpising conclusion. I’m glad that I stated my faulty opinion out loud, despite that it embarassed me, because it revealed my fault and I had to correct it. I had to confront my own prejudice and fix it. If I had kept the venom to myself, I would have gone on nursing my prejudice.



My take away: it doesn’t matter what people think about me, it matters what I am. It is better for me to surface my flaws and fix them, than it is for me to hide them and decay.

Tuesday, November 01, 2011  |  From Christopher Bennage

Working with people is a lot like working with code. New relationships are green fields. Over time they become brown fields and (just like code) they require maintenance. I’m sure that everyone reading this can identify some legacy relationships that they would describe as well complicated. Just like some legacy code.






I mean a lot with the word ‘relationship’. I have in mind everything from co-workers to friends to significant others. All of these variations require maintenance and I think we should deliberately structure our relationships so that maintenance is easier.


Interaction Smells





So what is the social equivalent of a switch\case statement?



We talk about code smells in software development as suggestive indicators that something is wrong. When it comes to relationships, I’ll call them interaction smells. I would consider these common emotional responses to be smells:



  • avoidance
  • irritation
  • suspicion


Personally, I have been guilty of avoiding someone because I thought I would irritate them and I didn’t want the hassle. This was in a work environment and it a negative effect on the overall efficacy of the group. My impulse to avoid was a smell and it led to a problem that needed to be addressed.


Amicability Debt



Bad code gets worse over time. We call this technical debt. Relationships that have soured do not get better by themselves. Little fractures grow over time. If we don’t address them when we smell them, the stink only gets worse. In addition, the stinky relationship can be begin affecting other parts of design, uh I mean, other social interactions (e.g., the team you are working with).


Refactoring the Relationship



Relationships are more difficult to work with than code for one primary reason:



You cannot revert back to a previous state if your changes fail.



Nevertheless, we often need to make changes. Refactoring code doesn’t change the exposed functionality, we just make internal changes to improve it. If you are beginning to have problems with your boss, that doesn’t necessarily mean it’s time to quit (that would be changing the function) rather you might just need some relational refactoring.



But what do I mean by refactoring a relationship? Well, there’s a lot to be said and you can find a good deal of practical advice on dealing with conflict over on “Doc” List’s blog.



In brief though, I mean this:



Be honest and humble. “Hey, Joe, I feel like you’ve been a bit on edge with me. Did I do something to frustrate you? I’d like to clear the air.” Then talk it over. Again, refer to Doc’s blog for lots of details.



One final qualification, since you cannot revert what you say and do, you must be deliberate and thoughtful about your refactoring.



This was originally posted this in August 2009, but I needed a reminder myself so…

Thursday, October 27, 2011  |  From Christopher Bennage

I’ve alluded before that I did a large chunk of my development in some form of ECMAScript for the first ten years of my professional life. Now, JavaScript is cool again for the first time. Everyone wants to learn it.



So, like me, you probably already kinda maybe knew JavaScript. But times have changed and now it’s a serious language. How do you get up to speed? Here’s what I did.


Read Some Books


Eloquent JavaScript



This is probably the best book to start with if you are really rusty (which also includes plain ol’ new as well). Personally, I found the book a bit tedious and I didn’t quite finish.



Did I mention that it’s free?


JavaScript: The Good Parts



An essential read for modern JavaScript development. It’s short and terse and easy to read. Douglas Crockford is highly regarded, though he can get occasionally harsh some mellow. He’s the supreme overlord author of JSlint, a nifty tool that’s useful for detecting the not so good parts in your own JavaScript. The information in this book is foundational and I recommend reading it soon.


JavaScript Patterns



This book is awesome. Seriously. Someone should give Stoyan a trophy. It deals with higher level patterns in your JavaScript applications. Be sure to read it after you become comfortable with core language concepts.


High Performance JavaScript



I haven’t actually read this one yet, but it’s on my list. I have however heard Nicholas C. Zakas speak and from that I suspect that the content will be excellent.


Staying in Touch



I’ve found it a little difficult to stay abreast of what’s having in the JavaSCript community.


JavaScript Weekly



The weekly podcast and its associated newsletter have been excellent. Highly recommended.


On the Interwebz



Start with Elijah Manor. Aside from just being a good guy, Elijah is a perpetual fountain of information. So, you’ll want to follow him on Twitter. Caveat: Following Elijah is drinking from a firehouse.



I also recommend:




I’m sure there are many other resources. Please add additional ones in the comments.


Some Thoughts



Here’s a few thoughts about learning JavaScript. Take them or leave them, but these are my current opinions.


Prototypes, not classes



JavaScript is not a classical language (that’s fancy talk for ‘class based’ language). Sometimes it looks classical, and may even taste a little classical, but really it’s not. Don’t try to force it. I think you’ll be happier and you’ll write happy little functions if you embrace it’s prototypical nature. If you don’t understand the difference, that’s okay. You will after reading the books I listed above.


Don’t confuse the language and the environment



We mostly know JavaScript through browser development. As such, we’ve generally confused the inside evil of the DOM with JavaScript itself. Or at least we did before jQuery rescued us.



However the browser isn’t the only environment. For the troglodytes amongst us, you can use Node.js and write JavaScript on the server.


Leverage the natural strengths



Each of these concepts deserves a post (or more) on their own, so I won’t go into details.



K.I.S.S.



Don’t mix trying to learn JavaScript with trying to learn a framework or library. My initial attempt to learn Ruby was thwarted by Rails. I know that some folks will disagree with me on this point. Here are my reasons:



  • It’s likely that you’ll encounter many new concepts just learning the language.
  • Sometimes it’s difficult to discern between a language feature and a framework feature.
  • Many frameworks embody an opinions that can (unintentionally) mislead you about the language (e.g., many frameworks attempt to make JavaScript classy).


Now, having said that, I do recommend exploring the vast diversity of frameworks and libraries out there after you’ve become comfortable with JavaScript.


Some Resource




What else can you add?

Wednesday, October 19, 2011  |  From Christopher Bennage

Take this post cum granlis salis. I’m trying to figure this stuff out and I’m thinking out loud.


Background



Whenever a browser makes a request, it includes a string identifying itself to the server. We commonly refer to this as the user agent string. This string identifies the browser and the platform and the version and a great deal more such nonsense.





This sounds great in theory. We should be able to use this data to optimize what’s being sent to the (mobile) browser. However, there’s been something of a sordid history for user agent strings. In retrospect, we’ve realized that user agent sniffing is a tool that has often hurt more than it has helped.



We’ve learned to favor feature detection over browser detection (or device detection). Take a look at modernizr and haz.io for more on the that front. The success of feature detection has also resulted in a shift from server logic to client logic. We detect features on the client but we detect user agent strings on the server, before we send anything to the client.



How does all this play into the mobile web? One of the key mobile features we are interested in is screen size. Luckily for us, the W3C has blessed us with media queries. In a nutshell, media queries allow you to conditionally apply CSS based properties of the display device. This has given rise to something known as Responsive Web Design. Responsive Web Design is about having a single set of markup whose layout can respond to the device’s display capabilities. Unfortunately, there are a few rough edges with this approach.


Moving Backwards…



In the mobile world, client-side feature detection has a few drawbacks. It requires extra code to be sent to the browsers and it takes additional processing on the client. It’s also likely that you’ll end up sending more than is really needed (or that you’ll need to make additional requests).



One solution to this conundrum is to use the open source “database” called WURLF. You can query WURL with a user agent string and it will return a set of capabilities. I think of it as feature detection on the server. Though admittedly it’s a bit misleading to call it that.



This means your server can ask questions like “Does this client support HTML5? If no, what do they support?” before the first response is even sent.



WURLF has commercial support and a C# API. For ASP.NET developers, 51Degrees has an open source project called Foundation that is built on top of WURL. It uses an HttpModule to automatically query WURL and populate the Request.Browser. Setting up WURLF without Foundation takes a little bit more work, but not too much. Both are available on Nuget: WURL and 51Degrees.


What should you do?



I don’t think that there is a cut and dry answer at the moment. What you do depends heavily on your target audience. If you are targeting the North American market there’s a good chance you’ll be okay with a single set of markup, going with a responsive mobile-first design. In other words, there would be no need for something like WURLF.



However, you might need a very broad reach or you might be targeting a market heavy in feature phones or something else that’s very different from North America. In those cases, it is good to understand your options.

Monday, October 17, 2011  |  From Christopher Bennage

I’ve recently discovered that I favor blocks over playsets. I’m talking about toys, and of course the canonical example of blocks is Legos. You can build nearly anything with them. They are useful, versatile, and inviting.



Now, the term ‘playset’ warrants a bit more explanation. I don’t mean the large outdoor sets with swings and sandboxes and spring-loaded ponies. No, I’m a child of the 80s and I loved me some Star Wars playsets.





So my definition of ‘playset’ is colored by my childhood. I think think of ‘playset’ as a themed toy representing an environment. Like the Hoth playset pictured here. If you want to pretend you are the Imperials raining destruction upon a ragtag Rebel Alliance, the Hoth Imperial Attack playset can’t be beat.



The problem is that’s all you can do with it. I mean, you can’t use the Hoth playset to stage an epic Cybertronian showdown between Optimus and Megatron. (Well you can, but you’ll have admit it’s just a bit awkward.)



Let’s get back to the blocks. Those puppies can be used to reconstruct a carbonite freezing chamber as well as hosting a dramatic cliff-side battle between Snake Eyes and Storm Shadow. Better yet, you can construct worlds of your own invention instead of merely mirroring those of others.



In reality, it’s not so cut and dry. (Nothing is, is it?) No, in reality, there’s a spectrum. In reality, there is Lego® Star Wars®. The line between blocks and playsets is blurred.


Software



I believe these categories apply to software as well, though we call them libraries and frameworks. Rob Conery asked a question about this on Google+ recently. Derick Bailey provides a definition attributed to Chris Eppstein:



“Frameworks call your code, you call library code.”



I began thinking about this from a different angle. I think that frameworks impose an opinion. Ruby on Rails has a strong opinion about how to create web apps. I think that make it a framework. Or at least, closer to the framework end of the spectrum than to the library end.





Now, to be clear, I am not saying that opinionated software or that frameworks are bad. In fact, they can be brilliant. I think Rail’s strong opinion has been a significant contribution to its success. What’s important to understand though is the limitations. When you are using a framework, the boundaries are harder to cross. The results can be strained and unnatural. The problem for me begins when our fanboy favor for a framework leads us to force its use it where it doesn’t fit.


Fun



Playing with both blocks and playsets is fun. So let’s stretch the analogy even further. What does that mean to software development? My takeaway is this:


Monday, October 10, 2011  |  From Christopher Bennage

The last few weeks I’ve been trying get a finger on the pulse of mobile web development. I wanted to identify the thought leaders, understand the big questions, and (perhaps mostly importantly) begin cataloging the practical considerations for building mobile experiences today.



Here’s where I’m at so far…





What is ‘the mobile web’?




The definition of mobile web is quickly evolving. Devices are varied and the distinctions are blurring. If you think it’s as simple as iOS, Android, and Windows then you’ll be surprised. (I do genuinely love my WP7). Personally, I think the distinction between mobile and desktop is fading more and more everyday. When I say mobile web I am talking about HTML-based applications and not applications that are built natively for their respective platforms. Of course, there is debate over native apps versus web apps: when is one appropriate over the over? etc, etc. This is a question when intend to address in Project Liike.


Who to follow?



I’ve been following a mishmash of people, and I must confess that my process of qualifying them has been some haphazard.
I’m compiling a list on twitter. A number of folks on this list are signatories of future friend.ly.



Other sources I’ve been paying attention to are:



  • A List Apart – “For people who make websites.”
  • Smashing Magainze – Lots of articles on design, web, and of course mobile.
  • Cloud Four – Many recent and thorough posts exploring some of the big questions in mobile.
  • Yiibu – They have a lot of interesting ideas, and they’ve done some impressive work for Nokia.


I’ve also been reading through Programming the Mobile Web by Maximiliano Firtman. The first few chapters are pretty scary for someone like myself who did not understand how diverse and scattered the mobile world is. (It’s also funny to see how much has changed since the book was published in 2010.)



Anything you’d recommend?


The state of things



Caveat: This is just Christopher’s brain dump. Consider it merely food for thought.



  • There are many compeling reasons for developing mobile web apps. Not to the complete exclusion of native apps, but maybe?
  • You need to understand your target market and the devices that it uses. Don’t make assumptions. You might be surprised.
  • The space is changing, standards are evolving, solutions are being formulated. However, if you need to you need build an app today, there is still plently of pragmatic advice.


One more thought: don’t jump to conclusions. You might read about something cool like Responsive Web Design, but such cool and innovative techniques can be deceptive. Research and testing is your friend.

Wednesday, October 05, 2011  |  From Christopher Bennage

I’m two weeks shy of six months at Microsoft. When I arrived here I was immediately thrown into the fray on Project Silk. The primary developer on the project was heading into paternity leave. Fortunately, I had read JavaScript: The Good Parts on my flight out to Redmond. (I had no idea that I’d be diving deep into JavaScript.)



After Silk, I um, got to work on some other cool stuff that propelled me even deeper in the HTML5/JavaScript world.



After hours, I started playing with NodeJS. Specifically, spiking out some play-by-post dorky goodness inspired by the efforts of my buddy Drew Miller using Express, Mongo, and Expresso.



I’ve really enjoyed jumping back deep into JavaScript. This is a return for me in many ways. Back in the late 90s I was doing classic ASP development and I had settled on JScript over VBScript. (I had even begun writing an ORM in JScript, though I had no idea what an ORM was or just how deep the water can get. I just knew that I was tired of writing the same thing over and over.) I was also spending a lot of time with Flash and ActionScript back then. In fact, the Flash community was were I first encountered the MVC pattern. It was also the place where I first began learning about object-oriented programming.



Working at Microsoft has been a wonderful experience so far and I’m especially fond of my team here at p&p. It is a different perspective being on the inside. I’m excited about the opportunities to produce quality guidance. I’m also glad to help encourage trends here that I believe are helpful both to the company and the community.



As a bonus, these first six months here in Redmond have been beautiful weather.



My next project is exploring the mobile web. This is a crazy, active, and vibrant area at the moment. There’s a lot for me to learn. Fortunately, we value transparency here in p&p and I intend to post frequently about my projects.

Monday, August 08, 2011  |  From Christopher Bennage

I’m lazy. I remember reading somewhere that that was a desirable trait to have in a developer. I’m not sure where though, and honestly it’s just too much effort to bingle it. This laziness came to the forefront recently as I was playing with Node.



In my last post, I showed you how to spin up a quick web app using Node. As I was playing with this app, I found that I had to restart Node every time I made a change to the source. This meant I had to switch to the console, stop the process, start the process and THEN refresh my page to see the effect of my change. Too much work I say.






So I wondered if Node had something built-in for monitoring changes to the file. I didn’t see anything useful from node.exe –help and researching it on the Web is just so tedious, so I decided to write my own solution.


Looking for Some Change



In .NET, there is a class System.IO.FileSystemWatcher. With an instance of this class you can monitor the files in a directory for changes. I set it up like this:



var watcher = new FileSystemWatcher(); 
watcher.Path = @"C:\node.js\stuff"; 
watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName; 
watcher.Filter = "*.js"; 

watcher.Changed += Changed; 
watcher.Created += Changed; 
watcher.Deleted += Changed; 
watcher.Renamed += Renamed; 

// Begin watching 
watcher.EnableRaisingEvents = true;


The NotifyFilter property allows you to specify the sort of changes you are interested in. You can check out the full list here. You’ll also notice that I used the Filter property to narrow it down just to js files.



Next, there are a number of events to wire to respond to changes. I reused the same handler as much as I could because I always want to do the same thing: restart Node. It’s also not entirely obvious how these events relate to NotifyFilter, but I didn’t dig too deep into that. (I’m lazy remember.)



It’s also important to set EnableRaisingEvents. If you don’t, then the (guess what) no event are raised.


Kill, Kill, Kill



Now whenever a significant change occurs, it’ll be time to restart Node. For this I used System.Diagnostics.Process. This is a bit of a tricky classs, with a number of not-so-obvious knobs to turn.



First, I’ll need to get a reference to the Node process. I noticed in Task Manager that the process name was “node”. So I used Process.GetProcessesByName("node").



This returns an array of processes, and so I did this:



var matches = Process.GetProcessesByName("node");  

matches.ToList().ForEach(match => {  
    Console.WriteLine("attempting to close node.js [" + match.Id + "]");  
    match.Kill();  
    match.WaitForExit(300); // it shouldn’t take this long, we’re just being cautious  
    Console.WriteLine("successfully closed");  
});


Admittedly, this is hitting it with a hammer. It’s okay, because this is just a quick and dirty helper tool for me and not a production application.



After killing the process, I’ll want to start another one. Now, I don’t care for another console window to pop up each time I restart, instead I’d like to simply redirect the input and output to my little helper app. This can be a little tricky, and I had to do some experimentation to find the right combination in order keep things from hanging. If you find it misbehaving, I recommend searching StackOverflow. I found several useful questions there. One of the keys that came up more than once was capturing and closing the stream for the standard input.



var start = new ProcessStartInfo();  
start.FileName = @"C:\node.js\node.exe";  
// start the process directly, as opposed to going thu the shell  
start.UseShellExecute = false; 
// we don’t want a new window  
start.CreateNoWindow = true; 
start.RedirectStandardOutput = true;  
start.RedirectStandardInput = true;  
start.Arguments = Path.Combine(@"C:\node.js\stuff", @"server.js");  

var node = new Process();  
node.EnableRaisingEvents = true;  
node.OutputDataReceived += OutputHandler;  
node.StartInfo = start;  
node.Start();  

// refresh the metadata stored in the instance of Process   
node.Refresh();
Console.WriteLine(node.ProcessName);  
Console.WriteLine("[" + node.Id + "] node.exe started");  

// close the input, we won’t use it  
var input = node.StandardInput;  
input.Close();  

// and now for the output  
node.BeginOutputReadLine();  


First we create an object that contains the configuration for starting an instance of Node. Notice that we are passing in the server.js file as an argument.



Also note that after starting the process, I call Refresh. I need to do this so that I’ll have the correct info to write out to the console. This data is not captured automatically.



Finally, I handled the redirection of the input and output.



The complete code for the app is available at https://gist.github.com/1108727.


Epilogue



This is very much a hack and I am not an expert on the proper usage of these classes. Please feel free to offer improvements.

Monday, August 08, 2011  |  From Christopher Bennage

I’m lazy. I remember reading somewhere that that was a desirable trait to have in a developer. I’m not sure where though, and honestly it’s just too much effort to bingle it. This laziness came to the forefront recently as I was playing with Node.

In my last post, I showed you how to spin up a quick web app using Node. As I was playing with this app, I found that I had to restart Node every time I made a change to the source. This meant I had to switch to the console, stop the process, start the process and THEN refresh my page to see the effect of my change. Too much work I say.

So I wondered if Node had something built-in for monitoring changes to the file. I didn’t see anything useful from node.exe –help and researching it on the Web is just so tedious, so I decided to write my own solution.

Looking for Some Change

In .NET, there is a class System.IO.FileSystemWatcher. With an instance of this class you can monitor the files in a directory for changes. I set it up like this:

var watcher = new FileSystemWatcher();
watcher.Path = @"C:\node.js\stuff";
watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName;
watcher.Filter = "*.js";

watcher.Changed += Changed;
watcher.Created += Changed;
watcher.Deleted += Changed;
watcher.Renamed += Renamed;

// Begin watching
watcher.EnableRaisingEvents = true;

The NotifyFilter property allows you to specify the sort of changes you are interested in. You can check out the full list here. You’ll also notice that I used the Filter property to narrow it down just to js files.

Next, there are a number of events to wire to respond to changes. I reused the same handler as much as I could because I always want to do the same thing: restart Node. It’s also not entirely obvious how these events relate to NotifyFilter, but I didn’t dig too deep into that. (I’m lazy remember.)

It’s also important to set EnableRaisingEvents. If you don’t, then the (guess what) no event are raised.

Kill, Kill, Kill

Now whenever a significant change occurs, it’ll be time to restart Node. For this I used System.Diagnostics.Process. This is a bit of a tricky classs, with a number of not-so-obvious knobs to turn.

First, I’ll need to get a reference to the Node process. I noticed in Task Manager that the process name was “node”. So I used

Process.GetProcessesByName("node")


This returns an array of processes, and so I did this:



var matches = Process.GetProcessesByName("node");

matches.ToList().ForEach(match => {
Console.WriteLine("attempting to close node.js [" + match.Id + "]");
match.Kill();
match.WaitForExit(300); // it shouldn’t take this long, we’re just being cautious
Console.WriteLine("successfully closed");

Admittedly, this is hitting it with a hammer. It’s okay, because this is just a quick and dirty helper tool for me and not a production application.

After killing the process, I’ll want to start another one. Now, I don’t care for another console window to pop up each time I restart, instead I’d like to simply redirect the input and output to my little helper app. This can be a little tricky, and I had to do some experimentation to find the right combination in order keep things from hanging. If you find it misbehaving, I recommend searching StackOverflow. I found several useful questions there. One of the keys that came up more than once was capturing and closing the stream for the standard input.



var start = new ProcessStartInfo();
start.FileName = @"C:\node.js\node.exe";
start.UseShellExecute = false; // the starts the process directly, as opposed to going thu the shell
start.CreateNoWindow = true; // we don’t want a new window
start.RedirectStandardOutput = true;
start.RedirectStandardInput = true;
start.Arguments = Path.Combine(@"C:\node.js\stuff", @"server.js");

var node = new Process();
node.EnableRaisingEvents = true;
node.OutputDataReceived += OutputHandler;
node.StartInfo = start;
node.Start();

node.Refresh(); // refreshing the metadata stored in the instance of Process
Console.WriteLine(node.ProcessName);
Console.WriteLine("[" + node.Id + "] node.exe started");

// close the input, we won't use it
var input = node.StandardInput;
input.Close();

// and now for the output
node.BeginOutputReadLine();


First we create an object that contains the configuration for starting an instance of Node. Notice that we are passing in the server.js file as an argument.



Also note that after starting the process, I call Refresh. I need to do this so that I’ll have the correct info to write out to the console. This data is not captured automatically.



Finally, I handled the redirection of the input and output.



The complete code for the app is available at https://gist.github.com/1108727.


Epilogue



This is very much a hack and I am not an expert on the proper usage of these classes. Please feel free to offer improvements.

Wednesday, July 27, 2011  |  From Christopher Bennage

What is Node?

The simplest answer, albeit a simplistic answer, is that Node (or Node.js) is JavaScript on the server. Actually, it’s a more than just that, but you can read about the more in other places. This is a good enough answer for us n00bs.

Unless you’ve been living in in cave, you might have noticed that JavaScript is all the rage now. It’s the new assembly language of the Web. (It’s even for the enterprise.) With Node, you can now take that webby clienty goodness to your server applications.

The reason I’m brining all this up is because there’s now a version of Node.js for Windows. It’s currently the unstable release only, but it’s a sign of coolness to come. Furthermore, Microsoft has partnered with Joyent and Rackspace to make it happen. You can read about it here and here. The ultimate goal (according to the posts) is for Node.js to run on both Windows and Azure.

Now, I want to be clear too, since I have been newly assimilated, Node is not a Microsoft product..

Tutorial

I want to show you how easy it is to try out Node.

First, download the exe. I grabbed v0.5.2.

Next, run it. Yeah, it’s that easy. It used to be way harder.

You’ll be presented with a prompt and you can start writing JavaScript in paradigm-shifting REPL.

node-repl

Now, let’s say you want to create a web server. We’ll begin by yanking the ‘hello world’ snippet from nodejs.org.

var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');


I saved this snippet into a file named server.js. Then from a PowerShell prompt, I ran



 .node.exe .\server.js


node server



Next, I hit http://localhost:8124 with a browser and I got exactly what you’d expect.



hello



Now you know enough to be dangerous. Winking smile



Of course, you have to restart Node when you make changes to the file (use Ctrl + C). I’ll show you how I got around that in another post.



Have fun!

Wednesday, April 06, 2011  |  From Christopher Bennage

Chapter XXXVI

My time with Blue Spire has officially ended. I have accepted a position with Microsoft on the Patterns & Practices team. My start date is April 18th.

Even though I’ve been professionally restless for a while, leaving Blue Spire turned out to be rather emotional for me. Untangling myself from a business I spent almost five years building up depressed me. Nevertheless, it’s done and Blue Spire lives on. Keep an eye on Rob’s blog for details about the company and his future plans.

Why?

Several friends have asked me why I would make this choice. Why would I leave running my own business? Why would I go to Microsoft of all places? Why would I uproot my family from a city we love, from dear and close friends, and move so far a way?

I needed a reboot. I wasn’t achieving the personal professional goals I had set for myself and I needed to reevaluate. I wanted a job and a city that would expose me to lots of different influences and perspectives.

So why Microsoft? There were several really exciting positions out there and it was hard to choose. In the end, the Microsoft position had the best balance for what I wanted in my next professional role. I’m genuinely excited about joining P&P. I asked around and I heard nothing but good things about the P&P team. Even from folks who are critical of Microsoft in general. In addition,the values and culture of the team align with my own. They have a vision I can buy into.

Still, at the end of the day, my wife and I made the choice to have the experience. We want to spend some time living on the West Coast. I want to see what it’s like to work for a giant like Microsoft. We wanted to live near a major city, and mountains, and ocean. Of course, I had other goals as well; certain financial criteria I needed to meet, opportunities to learn and grow, chances to exercise my pedagogical nature, and so on. They all flowed together. In the end though, I want my life to be punctuated, full of chapters, experiences, and stories.

I’m excited.

Monday, January 31, 2011  |  From Christopher Bennage

On March 31, 1998, around 10am, my then-manager Alex and I left the office we shared together and headed over to Electronics Boutique. Alex and I were both developers working for the IT department of an up and coming software company called PC DOCS. In those days, we didn’t have a corporate firewall. My desktop was a node on the internet. In fact, I was running a web server on it. A bunch of us would stay late after work, barricaded in other peoples’ cubicles, all phones on speaker, playing WarCraft II and Quake. Those were halcyon days. I was just about to turn 23. I was just about to get married.

Alex and I had headed to EB because it was Release Day for StarCraft. I don’t think that I had ever been so excited about a video game. Well, maybe once but that’s another story…

A few months ago, StarCraft 2 was released. While there wasn’t as personal ceremony this time, I still purchased it on Release Day.

This time around I decided to really learn how to play the game. In case you are unaware, StarCraft is huge. There are televised tournaments, professional players, and so on. In many ways, it’s analogous to chess. As I began to learn more about it, I found that there are certain tenets of gameplay and, as I mused on these, I found that they extend to life in general (though I’ll limit them here to a professional context).

The First Lesson

ss107-hiresIn the game, there are a dizziness amount of options. Your opponent can overwhelm you with astounding ease if you are unprepared for their particular tactic. So you might be inclined to try and prepare for all contingencies. But guess what? You can’t. You will end up spending all of your resources ‘preparing’. You think that this aligns with your overarching goal, but in reality it is a distraction.

Professionally, we are given a goal: build software that will do X. As developers we typically and immediately begin thinking about all the ‘what ifs’. Usually because we’ve been burned by them in the past. X is still in sight, but there is a long road to get to there, because we have to deal with Y and Z and so many other things. We have to be prepared.

The truth is that you cannot be prepared for everything. It is actually a waste of energy and a distraction from your real goal. In the game of StarCraft, if you try to prepare for everything, you will lose. Instead, you must choose your battles.

The Second Lesson

How do you know which battles to choose? Surely a battle is coming. There are always problems in every project. You can’t simply be unprepared. That’s suicide.

In StarCraft, the answer is scouting. That is, you gather intelligence about what the enemy is doing. Once you know, then you can prepare properly and efficiently.

Recently, I was asked about some performance concerns at the start of a project. Now, I have been seriously burned by performance issues. In fact, one of the worst software disasters I was a part of was a performance issue. Nevertheless, the concerns raised with granular and premature. As Donald Knuth said “premature optimization is the root of all evil”. Now, I am most emphatically not saying to avoid optimization. What I am saying is to scout, gathering intelligence and responding accordingly.

A Summary

I’ll sum up these two thoughts:

  • Don’t waste time on things you don’t need.
  • Find out what you need through active analysis.

None of this is new. In fact, you see pretty much the same things preached all over. I hear it in XP, I hear it in Agile, I hear it in StarCraft.

Epilogue

I’m reminded of a passage from G. K. Chesterton’s Manalive (chapter 3):

"Well," said the girl solidly, "what is there to wake up to?"

"There must be!" cried Inglewood, turning round in a singular excitement—"there must be something to wake up to! All we do is preparations—your cleanliness, and my healthiness, and Warner's scientific appliances. We're always preparing for something—something that never comes off. I ventilate the house, and you sweep the house; but what is going to HAPPEN in the house?"

Friday, January 21, 2011  |  From Christopher Bennage

I’ve been working on the Silverlight client for the RavenDB. In Raven, you can write a Linq query in the Silverlight client that will ultimately be executed against a Raven server somewhere. The execution of the query is asynchronous and we want that to be explicit in the api. It should be obvious to the  developer that its execution is an asynchronous operation. By that I mean, we don’t want the api to give the consuming developer a nasty surprise. Ayende wrote about this issue a few months ago.

To demonstrate how easy it is to make a mistake, you could very easily write this code:

using (var session = documentStore.OpenAsyncSession())
{
var companies = session.Query<Company>()
.Where(x => x.Name == "Blue Spire")
.ToList();
}


The problem here is that the execution of the query is going to be asynchronous and we need to provide a mechanism for a callback after the results have been returned from the server. We have added ToListAynsc() which will initiate the request and provide a Task for handling the continuation. That’s great, but now the problem is that calling ToList() doesn’t make any sense. We’d like to prevent a developer from calling ToList(), preferably at compile time.



Unfortunately, the technique that Ayende used in his post won’t work for us. At least, not without some tweaking. Why not?



Well, if we examine the session above. we’ll see the Query method returns an IRavenQueryable<T>. This interface inherits from the built-in interfaces necessary for supporting Linq; which ultimately is IQueryable. Now the nature of Linq is to have a series of chained method calls. After the first link in the Linq, we no longer have an IRavenQueryable<T>, instead we have an IQueryable<T>. This is because all of the Linq methods are extensions methods living on Queryable. (Well, at least the ones we’d be using in this discussion so far. There are other implementations such as the ones on Enumerable.)



Once a link in the chain returns an IQueryable<T> then any method defined on Queryable is valid for compilation, even though it might not make sense. What we’d like to do is override these Linq methods so that we always return an IRavenQueryable<T> and thus explicitly control what is available to developer.



It turns out that this is easy to do, but (like all things in implementing Linq) rather tedious.



We have to provide our own implementation of every extension method for IQueryable. In most cases, the new implementation is just a matter of casting back to our desired type:



public static IRavenQueryable<T> Where<T>(this IRavenQueryable<T> source, Expression<Func<T, bool>> prediate)
{
return (IRavenQueryable<T>)Queryable.Where(source, prediate);
}


Now that we can always return an IRavenQueryable<T> we can use the Obsolete attribute to disable the Linq operations that don’t make sense for our context.



[Obsolete("You cannot execute a query synchronously from the Silverlight client. Instead, use ToListAsync().", true)]
public static IList<T> ToList<T>(this IRavenQueryable<T> source)
{
throw new NotSupportedException();
}


This also means that we are able to make ToListAsync specific to IRavenQueryable<T> (the only place where it makes sense).



public static Task<IList<T>> ToListAsync<T>(this IRavenQueryable<T> source)
{
// if you really want to see the implementation, check out the source on github
}

Monday, January 17, 2011  |  From Christopher Bennage

First a confession, and I know I’ll invoke shame for this one: I have done Very Little Testing with Silverlight. I won’t bore you with reasons or excuses, but I wasn’t up on the state of unit testing in Silverlight until very recently. (In fact, I might  still be missing some chunks.)

The Problem

Last week, I started writing some tests for Raven DB. I won’t call them ‘unit’ tests because they were really ‘integration’ tests. Specifically, I wanted to test the budding Silverlight client for Raven. This mean that my tests had to make calls to the Raven server, wait for the result, then assert something.

Large portions of the Silverlight client are cross-compiled and I wanted to do the same with the relevant tests. On the .NET side, a demonstrative test looks like this:

[Fact]
public void Can_insert_async_and_get_sync()
{
using (var server = GetNewServer(port, path))
{
var documentStore = new DocumentStore { Url = "http://localhost:" + port };
documentStore.Initialize();

var entity = new Company { Name = "Async Company" };
using (var session = documentStore.OpenAsyncSession())
{
session.Store(entity);
session.SaveChangesAsync().Wait();
}

using (var session = documentStore.OpenSession())
{
var company = session.Load<Company>(entity.Id); // the SL client won’t have sync methods!

Assert.Equal("Async Company", company.Name);
}
}
}


The client is making use of Task from System.Threading.Tasks, and in case you didn’t know, this namespace has been ported to Silverlight as part of the CTP for the new C# 5 async syntax.The idea here is to make the async code read synchronously.



Using XunitLight, I was able to cross compile a similar test and run it with the Silverlight Unit Test Framework. Only, it didn’t work.



It doesn’t work because the test is running on the UI thread, and the call to Wait() blocks the execution on the current thread while the Task returned from SaveChangesAsync() executes. This task is making use of WebRequest and deep in the bowels of Silverlight some calls are being marshaled back onto the UI thread. Only that thread is being blocked by Wait(), so nothing happens.


The Standard Solution



The Silverlight Unit Test Framework has some infrastructure for handling this sort of problem. Jeff Wilcox, who built the framework, talks about asynchronous test support in this post. Using the standard approach, I ended up with this test:



[Asynchronous]
[TestMethod]
public void Can_insert_async_and_load_async()
{
var documentStore = new DocumentStore { Url = "http://localhost:" + port };
documentStore.Initialize();

var entity = new Company { Name = "Async Company #1" };
using (var session_for_storing = documentStore.OpenAsyncSession())
{
session_for_storing.Store(entity);
var result = session_for_storing.SaveChangesAsync();
EnqueueConditional(() => result.IsCompleted || result.IsFaulted);
}

EnqueueCallback(() =>
{
using (var session_for_loading = documentStore.OpenAsyncSession())
{
var task = session_for_loading.LoadAsync<Company>(entity.Id);
EnqueueConditional(() => task.IsCompleted || task.IsFaulted);
EnqueueCallback(() =>
{
Assert.Equal(entity.Name, task.Result.Name);
EnqueueTestComplete();
});
}
});
}


The Asynchronous attribute tells the framework to use a queuing mechanism to execute the test. Then in your test, you must carefully arrange the code with various enqueue methods. This was actually one of the simpler tests, a couple of them had even more nesting of EnqueueCallback. It was functional, but my heart hurt.



I should also note that the code you see here is a mix of several things. From the Silverlight Unit Test Framework itself we have [Asynchronous] and the enqueue methods. (These methods are provided on a base class SilverlightTest). In addition, [TestMethod] is part of the Visual Studio Team Test (VSTT). In my .NET example above, I was using [Fact] from XUnit. The Silverlight Unit Test Framework includes a default provider for VSTT. Finally, the Assert.Equal call is from XUnit (well, from XunitLight).


The Alternative Solution



Writing the tests like this was killing me. So I lifted the syntax used in Caliburn for coroutines and I was able to convert the test to this:



[Asynchronous]
[TestMethod]
public IEnumerable<Task> Can_insert_async_and_load_async()
{
var documentStore = new DocumentStore { Url = "http://localhost:" + port };
documentStore.Initialize();

var entity = new Company {Name = "Async Company #1"};
using (var session_for_storing = documentStore.OpenAsyncSession(dbname))
{
session_for_storing.Store(entity);
yield return session_for_storing.SaveChangesAsync();
}

using (var session_for_loading = documentStore.OpenAsyncSession(dbname))
{
var task = session_for_loading.LoadAsync<Company>(entity.Id);
yield return task;

Assert.Equal(entity.Name, task.Result.Name);
}
}

How This Works



I’m leveraging the fact that all of the asynchronous work is performed with Task. In Caliburn, we use IResult for the same purpose. You’ll note that my test returns an IEnumerable of Task. I took the default implementation of the provider for VSTT, and I found the bit where the test was actually invoked and I changed it to this (note that methodInfo contains the test method):



public virtual void Invoke(object instance)
{
var type = typeof (IEnumerable<>).MakeGenericType(new[] {typeof(Task)});
if(type.IsAssignableFrom(methodInfo.ReturnType))
{
var executor = instance.GetType().GetMethod("ExecuteTest");
executor.Invoke(instance, new[] {methodInfo});
} else
{
methodInfo.Invoke(instance, None); // this is the original implementation
}
}


I check to see if my test method returns an IEnumerable<T> and if it does, I then look for a method named ExecuteTest on my test class and I invoke that passing in my actual test method as a parameter.



public void ExecuteTest(MethodInfo test)
{
var tasks = (IEnumerable<Task>)test.Invoke(this, new object[] { });
IEnumerator<Task> enumerator = tasks.GetEnumerator();
ExecuteTestStep(enumerator);
}


Yes, this code is far from bullet proof. It should check to make sure our test class contains an ExecuteTest method (among other things).



Finally, ExecuteTestStep takes each of the Task instances that are yielded and calls the various enqueue methods from SilverlightTest.



private void ExecuteTestStep(IEnumerator<Task> enumerator)
{
bool moveNextSucceeded = false;
try
{
moveNextSucceeded = enumerator.MoveNext();
}
catch (Exception ex)
{
EnqueueTestComplete();
return;
}

if (moveNextSucceeded)
{
try
{
Task next = enumerator.Current;
EnqueueConditional(() => next.IsCompleted || next.IsFaulted);
EnqueueCallback(() => ExecuteTestStep(enumerator));
}
catch (Exception ex)
{
EnqueueTestComplete();
return;
}
}
else EnqueueTestComplete();
}


If you are familiar with the source from Caliburn Micro, you’ll notice that this is very similar to the logic for executing IResult instances.



The complete source, along with a few examples tests, is available on github.



I’ll likely improve it during the next couple of weeks. For example, there’s no real needs for the attributes when the method returns IEnumerable<Task>.



Feedback is welcome.

Tuesday, November 09, 2010  |  From Christopher Bennage

kinectI didn’t intend to purchase a Kinect for some time. However, there I was, walking reluctantly through Stuffmart, picking up a few random items for my home office. My four year old son, Ranen, had accompanied me. I was digging through various audio connectors when Ranen stopped and said “Daddy! It’s that game!” He was referring to Kinectimals.

I was stunned. He was standing in front of a shelf full of Kinects. I had been under the impression they were sold out nearly everywhere. I stood there, staring destiny in the face. The purchase was inevitable, so I embraced it.

The Setup

There was very little to setting up the device. I don’t have the newer Xbox, so the Kinect just plugged into the wifi port on the back. Once the device was detected, an application called Kinect Hub was installed. It’s like a minimal version of the main Xbox menus built specifically to utilize Kinect’s features.

There was also a built-in tutorial that both explained how Kinect works and did some initial calibration. It lasted 5 to 10 minutes at most.

I moved our coffee table out of the way, giving us about 12 square fee to work with. That was all the space we needed.

Kinect Adventures

Kinect Adventures is the game that comes with the device. It consists of 5 mini-games and reminded me a lot of the initial offering for Wii. The game takes longer than most games to start up. There is a period of calibration for the device as the game starts. After letting it run through this the first three or four times we started the game, I began to skip the calibration with no noticeable impact.

Ranen and I were able to join in a start playing immediately. Picking up the game for him was much easier than it had been using controllers. (His favorite Xbox game is Lego Star Wars, but he still fumbles with the controls every now and then.)

My  8 year old and 2 year old showed up about this time. We discovered that you can simply swap places with an active player to jump in. So two of us would play, while the rest sat on the sofa (which happened to be just out of range).

The facial recognition struggled somewhat with us switching places. I also wonder if poor lighting affected it as well. There is very little light on our faces when we are facing the TV.

I was impressed with Kinect’s ability to keep track of active players with my children constantly running around. It would temporarily lose a player if someone walked in front of the device (and thus completely occluding a player). However, it would pick them back up almost immediately.

It also struggled just a bit with Ranen’s size. Remember, he’s four. Every now and then, it interpreted him as squatting when he was really standing. It didn’t really affect the gameplay, but it bothered him. My two year old didn’t really play, but the Kinect would occasionally get confused when he would wander into the play area.

The game itself was a hit with the kids and I had a lot of fun as well. I’m sure the game will get old after the novelty wears off, but it is definitely a fun entry title.

Demo Games

Saturday night we had a few friends over sans children. In addition to Kinect Adventures, we played through some of the included demos. The dance game was a hoot and it is definitely on the “to buy” list. We also had fun with the racing game, but I don’t anticipate it having enough variety for the long term. I was impressed how friends who don’t play video games at all were able to pick it up and navigate the games.

The fitness game demo was short, but very impressive. That’s on the “to buy” list as well.

Voice

The voice recognition works, but isn’t really that useful. You can navigate Kinect Hub, but that’s about it. Funny enough, it doesn’t recognize my daughter. That really frustrated her.

Interface

The default interface is a little clunky. This is a UI design issue though and not a problem with the hardware. For example, the dance game has a great navigation interface for Kinect.

I’m hoping this will improve in future updates.

Summary

Overall, I was impressed with Kinect’s ability to cope with the chaos of active kids. It really delivers on what it promised with respect to “you being the controller”.  The games I tried felt natural, were lots of fun, and contained many creative surprising uses of the hardware.

I do think Kinect is best suited to family and party games, but there’s an increasing amount of that in my life.

Recommendation: purchase.

Friday, October 22, 2010  |  From Christopher Bennage

The latest release of IronRuby (1.1.1) includes Visual Studio integration!

From the release notes:

The integration includes

  • Ruby colorizer and syntax checker
  • interactive loop window
  • directory based project
  • templates for common Ruby applications (including Ruby on Rails 3, Sinatra, Gems and Silverlight based browser scripting app)

Yes, you read that correctly, there is even an out of the box Sinatra project!

IronRuby in VS

 Christopher Bennage News Feed 

Last edited Jun 10 2009 at 9:21 PM by bennage, version 5