Archive for the ‘Silverlight’ category

Unit Testing in Silverlight

October 26th, 2009

Something I am a really big fan of is Unit Testing.  I was a big evangelist of unit testing at my last company.  The code my team wrote unit tests for was, on average, much better code than code that was written without unit testing.  Code-testing coverage via unit testing creates solid code.  It allows developers to thoroughly test their code in an automated fashion.  Unit tests give the developer confidence that they have introduced few or no regressions with new functionality added to old code.  All one needs to do is re-run the old unit tests to ensure everything still works.  Unit tests are a great form of documentation.  When a developer maintains code written by another they can inspect unit tests to see how the code is used, and can run these unit tests to ensure they aren’t breaking functionality they may not understand.  Ultimately unit tests act like a code specification.  In fact there is a style of coding called Test Driven Development (or its sexy new name, Behavior Drive Developer) that mandates that the tests be written first, and then the code is not considered complete until it satisfies the tests.  And even when unit testing is not take to that extreme, developing code that works well with unit tests usually ensures well-designed code from an object-oriented standpoint.  Code that is easily tested by a unit test is usually adequately decoupled and uses OO principles like inheritance, encapsulation and polymorphism in the right way.  Finally, writing code with unit tests can be faster.  Running tests can take less time than standing up an application and entering in the correct criteria to test the code in question.

At my current employer I have found myself working with a very mature (and very good) code-base that does not lend itself to unit testing.  It has probably been a year since I have written a unit test at work.  So when I started diving back into Silverlight I made it a goal to write our new framework to be as compatible with unit testing as possible.  This will help lesson the burden on our QA team, which has already written a lot of UI testing for our current ASP.Net web application.  We will also receive all the benefits mentioned above.

To start off I needed a unit testing framework.  NUnit is my old unit-testing friend and was my first thought.  However, NUnit and other unit testing frameworks don’t work in Silverlight-land, since Silverlight relies on a slightly different set of core .Net assemblies.  I did discover that there is a Silverlight version of NUnit and I considered it.  I also found the Silverlight Unit Testing Framework from Microsoft thanks to a post over on Scott Gu’s website.  The Silverlight Unit Testing Framework is based on the Microsoft library for normal .Net (which is also based on NUnit) but runs in Silverlight, in the browser.

Ultimately I chose the Microsoft library for a couple of important reasons.  First, there seems to be more acceptance and more example of the Microsoft library.  Second, the Silverlight Unit Testing Framework does one thing that is very unique compared to other unit testing frameworks: it runs the tests in the UI thread.  Jeff Wilcox, one of the authors of the framework, has an excellent post here about why Microsoft chose to do this, and it really makes sense.  Silverlight is a graphical library, and bugs will best be found if testing is written from a user-interaction standpoint.  Many things run on the UI thread, or are marshaled back and forth.  The Microsoft Silverlight Unit Testing Framework can work both as a unit testing framework and as a kind of integration testing framework.  The framework makes it very easy to test off the UI thread, and test asynchronously.  I found this excellent post on using the async features of the Silverlight Unit Testing Framework.  It really boils down to the testing environment being the same as the real run-time.  I have run across enough idiosyncrasies in the way Silverlight handles UI thread interaction to know that testing without it will miss a lot of bugs.

I have developed some “test” tests on business objects.  I also tested a thread manager I wrote using the built-in async functionality.  With the experience so far, I feel happy with the results.  My next step is to look at pluging in the unit tests into the automated build at work…

Silverlight Command Line Arguments.

April 17th, 2009

I have been developing a fairly rich Silverlight application for the last couple of months that is meant to ultimately replace some of our existing UI.  This project has evolved from prototype to framework authoring to actual wire-frame implementations.  I have had a chance now to step back and create some small charting components for one of our existing pages.  A change of pace can be refreshing, and this one allows me to stay in Silverlight land yet spend about a week writing some production code.

There are a number of charting components available, many of them free.  I am going to take this opportunity to write my own from scratch since I really only need some simple pie charts.  I want to keep it small and simple, and yet learn from the experience.

I have run into a new situation with these small components that I had not encountered with the large application.  I need to pass “command line arguments”.  Or rather, I need to embedd some data in the HTML page for the Silverlight to pick-up and render.  This data will be the charting data.  As it turns out this is dead simple.  In the Silverlight object tag I simply include the initParams parameter with my data, comma-delimited:

  <object type="application/x-silverlight" width="100%" height="100%">
    <param name="source" value="ClientBin/MyChartingApp.xap"/>
    <!-- Command Line Arguments -->
    <param name="initParams" value="datum1=1,datum2=2,etc" />
  </object>

Then I read that data in during the application’s Load event:

  private void Application_Startup(object sender, StartupEventArgs e)
  {
    foreach (var key in e.InitParams.Keys)
    {
      var datum = e.InitParams[key];
      //do something with the datum
    }
  }

Pretty simple!  Now I just need to write some ASP.Net code to render out the desired HMTL, and I am all set.  Oh, that and write the Silverlight component.

YouTube is stream March Madness… with Silverlight?

March 20th, 2009

It looks like YouTube is streaming March Madness not with Flash but with Silverlight. Huh.  Hopefully that will expand the Silverlight install base.

ASP.Net MVC, IE 8 (Yawn) Released

March 19th, 2009

The first tech news coming out of Mix this morning was the release of IE 8. While its nice that they are still trying to do nice things with IE, I currently have 3 browsers installed that I prefer over IE: Firefox, Safari and Chrome. Firefox is my everyday browser. Its much faster than IE, and its plug-in ecosystem is great.  All IE 8 does is make testing of our current release more difficult.  Now we have to support 3 versions of IE.  Such is progress.

There is something cool coming out of Mix today and that something is ASP.Net MVC.  I played around with ASP.Net MVC a couple of months ago and really, really liked it.  For creating a modern web site I don’t think it gets much better.  Think Rails done right on top of a managed, strongly typed, compiled language married to great tools.  Download page here.  Microsoft has been making a lot of great moves in the web development space recently with their adoption of jQuery, release of Silverlight 2 last year and upcoming release of Silverlight 3, and now ASP.Net MVC.

Some More New Features in Silverlight 3 Announced at #Mix09

March 18th, 2009

Scott Gu and Co. have announced a few more items that are, well, kick ass.

  • A new data tier technology that will allow developers to write data services, decorate those services with a client attribute, and your Silverlight project will automatically generate proxies for those data services.  This eliminates a lot of custom code I have written to do my WCF plumbing.
  • Silverlight on the desktop on Mac and Windows!  Its pretty obvious they are going after Adobe Air here.  This gives Windows developers and easy-in to Mac desktop development.
  • A Silverlight developer plugin for Eclipse on Windows and Mac.
  • Blend 3 can import from Photoshop.  It provides granular control over importing layers from the Photoshop document.  Very nice!
  • Blend 3, in general, looks like a huge improvement over Blend 2.

New Features in Silverlight 3

March 18th, 2009

Scott Guthrie is on stage right now in Las Vegas and here are a few things he has mentioned about Silverlight 3:

  • Utilization of the GPU on the client machine for graphics acceleration.
  • Merged Dictionaries (I had to write one of these myself).
  • Style inheritance.
  • On-demand type download – I wrote this from the ground up for the current app I am building.  Its nice to see it bundled in with SL3.
  • Gestures in Windows 7 – I don’t know if this will be available in Silverlight on all platforms…
  • Playboy is putting all of its archives into a Deep Zoom powered site.  Oh, and Rolling Stone is too.

Silverlight 3 Download Links Live

March 18th, 2009

The download links for Silverlight 3 are live on Microsoft.com

Microsoft® Silverlight™ 3 SDK Beta 1

Microsoft® Silverlight™ 3 Tools Beta 1 for Visual Studio 2008 SP1

Neither the Mix site nor the Silverlight site have any SL3 details as of 9:10 CST 3/18/09.  It looks like Microsoft may have put the links live before SL3 is officially announced.

I look forward to seeing the feature list for Silverlight 3.

EDIT: WordPress went nuts and put a bunch of weird formatting in which was occasionally showing up in Firefox.  I went into the HTML and ripped out all of the junk.

Cool Silverlight physics demos built by someone with way too much free time

March 17th, 2009

The title of the post really says it all.  Here is the link.

Silverlight: Framework vs API

March 11th, 2009

I have been developing a new Silverlight framework for the last two months.  Well, really just the last month since it took my about a month to actually ramp up to a point where I felt comfortable writing a Silverlight framework.  The reason I am writing a Silverlight framework in the first place is that we intend on using Silverlight to enhance some of the advanced features of our our existing web apps, and perhaps to develop a new web app.  Our stuff is written in ASP.Net, so it made sense to go with other .Net-based tech.

I decided that we needed to write  a framework around the time we first decided to start looking into Silverlight.  There are a lot of custom things we do in our existing ASP.Net framework, and some of that would need to be replicated for Silverlight.  When I started down this road I did not imagine I would have as much work to do as I have done.  I was actually counting on a lot of stuff in Silvelight to be extensible that is actually not extensible.  I am learning that Silverlight acts more like an API than a Framework.

Consider the Timeline class.  This is the class on which multiple animations classes are based.  Storyboard, DoubleAnimation and ColorAnimation are three common classes that derive from Timeline.  Since .Net (in general) is a framework and not an API (although it contains numerous APIs) I figured I would be able to derive from Timeline to create my own, custom animation classes.  This is a common task in normal .Net land.  Many core-framework classes are written to be extensible.  Boy was I stupid for thinking such a thing about Silverlight’s Timeline class!  As it turns out extending Timeline gets you nowhere.  The Timeline class, and the classes that derive from it in Silverlight, do not contain any actual animation logic.  They are really just command objects that describe some values about a particular type of animation, and the animation itself is run deep in the Silverlight runtime.

This really doesn’t do me any good for a couple of the tasks I would like to accomplish.  The recommendations online are either to use a timer or use a thread to drive a “game loop” to do custom animations.  Really?

So this morning I set out to write a custom animation framework.  I had been thinking of this for a while, so perhaps I should admit that I started the thought experiment of “How do I write a custom animation framework in Silverlight?” a couple of weeks ago.  Still, I wrote my first line of code this morning shortly after 9:00 AM CST.  At around 4:30 PM CST I had checked in an abstract classes similar in purpose to Timeline, except it actually drives the animation.  I had further derived an abstract child for animations that target object properties for animations (most cases), a class to extend said object that animates doubles (think DoubleAnimation), a concrete child that groups animations (think Storyboard), and a class that allows the programmer to write a custom logic that is fired for every frame render.  My core logic is based on the DispatchTimer class (in System.Windows.Threading), which I chose because it does the cross-thread invocation for me.

I am still missing some of the functionality that is represented in the Silverlight counterparts, and am missing several types of animations.  Additional animations should be easy to implement now that I have the base stuff written.  It should be really easy to replicate those classes found in the Silvelight version of .Net as most of those are really just numeric range animations.  I also need to implement some functionality like AutoReverse, and looping logic for my own Storyboard object (which is called GroupStory).  What does it do when all of its animations are complete?  Repeat?  And the framed animations are also a task to get to in the near future.

I did all this work, it is tested and checked in, in one day.  I wrote a framework to replace an API.  As much as I like Silverlight 2.0, I wish they have waited just a little longer to get some more of these “framework vs API” things resolved.  Animation is just one of the examples of where Microsoft should have been thinking about how all of us software engineer types in the real world would be extending their functionality.  But its a big example, especially considering their target audience.  I am not kidding myself here.  I prolly have bugs waiting for me in that code.  But I can leverage it to do so many interesting things now.  It may take me the rest of the week to really work through the other animations and fix bugs.  Maybe I will still be working on it next week.  But I am just one guy, and I can accomplish this much in such a short period of time?

I am also not kidding myself about the talent at MS.  IMO, .Net is Microsoft’s nicest product.  They have done a stellar job with it.  C# is my favorite language.  And really, Silverlight is a wonderful run-time.  I have no doubt that those developers and managers at MS responsible for it are hard working and talented people.  I just hope that the next version of Silverlight they produce is more like a framework that the current version.

Custom Visual States in Silverlight

March 9th, 2009

Visual States are the way Silverlight communicates basic state information about an object.  Is a button pressed?  Is a mouse over a button?  Is a button normal?  The available states for an object are indicated via decoration with the TemplateVisualStateAttribute (in System.Windows).  For example, the Button class in Silverlight looks like this:

[TemplateVisualState(Name="Unfocused", GroupName="FocusStates"),
TemplateVisualState(Name="MouseOver", GroupName="CommonStates"),
TemplateVisualState(Name="Normal", GroupName="CommonStates"),
TemplateVisualState(Name="Pressed", GroupName="CommonStates"),
TemplateVisualState(Name="Disabled", GroupName="CommonStates"),
TemplateVisualState(Name="Focused", GroupName="FocusStates")]
public class Button : ButtonBase
{
    // Methods
    public Button();
    internal override void ChangeVisualState(bool useTransitions);
    public override void OnApplyTemplate();
    protected override void OnClick();
    protected override AutomationPeer OnCreateAutomationPeer();
}

You might notice from this code that the various states also have group names.  If you look at the states it makes sense why we would want to group them.  States like Unfocused and Focused are related.  States like Mouse Over, Normal, Pressed, and Disabled are all related to how a button looks with various interactions.  Silverlight only allows one state from any group of an object to be active at once.  This also makes sense.  A button cannot be Focused and Unfocused, or Pressed and Normal, but a button can be both Pressed and Focused.  I like to think of each group like an enumeration, and the states of each group as the values that enumeration can hold.

When the button switches to a new state, it does so by calling VisualStateManager.GoToState(…).  Of course there needs to be some logic to fire this switch, and this is ultimately driven by built-in events like MouseEnter, MouseDown, etc.  To switch to Focused, the code might look like:

VisualStateManager.GoToState(this, "Focused", true);

To consume visual states one uses something called a VisualStateGroup class which contains a VisualState objects, one each corresponding to a visual state decorated on the class. This object is attached to the object’s template. Here is some sample XAML for the button class:

<ControlTemplate TargetType="Button"
                 xmlns:vsm="clr-namespace:System.Windows;assembly=System.Windows">
  <Grid >
    <vsm:VisualStateManager.VisualStateGroups>
      <vsm:VisualStateGroup x:Name="CommonStates">

        <vsm:VisualStateGroup.Transitions>

          <!--Take one half second to trasition to the MouseOver state.-->
          <vsm:VisualTransition To="MouseOver"
                              GeneratedDuration="0:0:0.5"/>
        </vsm:VisualStateGroup.Transitions>

        <vsm:VisualState x:Name="Normal" />

        <!--Change the SolidColorBrush, ButtonBrush, to red when the
            mouse is over the button.-->
        <vsm:VisualState x:Name="MouseOver">
          <Storyboard>
            <ColorAnimation Storyboard.TargetName="ButtonBrush"
                            Storyboard.TargetProperty="Color" To="Red" />
          </Storyboard>
        </vsm:VisualState>
      </vsm:VisualStateGroup>
    </vsm:VisualStateManager.VisualStateGroups>
    <Grid.Background>
      <SolidColorBrush x:Name="ButtonBrush" Color="Green"/>
    </Grid.Background>
  </Grid>

This markup generates a VisualStateGroup named to correspond to a group on the object. It contains visual states, each named to correspond to an existing state on the object.  The VisualStateGroup can also contain transition objects to control the transition to any given state.  The VisualState itself doesn’t do anything but start a Storyboard animation.  From that animation you target objects and properties as you would any other story board.  The pieces all just fall into place!

Many built-in object contain a number of visual states that you can utilize with control templates to change look and feel, but you can also create your own visual states on custom objects, and consume those states in your own custom code.  While this system is not as flexible as the event triggers built into WPF, it does allow for some interesting capabilities.