Archive for the ‘Silverlight’ category

COM: Everytime I think I am out, it pulls me back in. (Silverlight + DLR)

May 24th, 2010

Silverlight 4 introduces some nice functionality on top of the Out Of Browser (OOB) capabilities introduced in Silverlight 3.  The application can now be granted a higher level of trust which allows it to operate outside the Silverlight sandbox file system, and to interact with COM.  To test the capabilities of this new functionality I immediately tried to take it file system access far beyond the sandbox; I wanted to enumerate all of the drives on the client machine.  I quickly ran into a wall.  Silverlight does not expose access to drives through its IO libraries.  Why?  I read several answers to this question, none of which satisfied me, especially given the fact that the app can simply access these drives through COM!

Luckily .Net 4.0 / Silverlight 4.0 / C# 4.0 comes with the Dynamic Language Runtime (DLR).  I had previous used the new dynamic pseudo-type that ties into the DLR to call Iron Python.  I figured I would see if I could use this same technique to call into COM. Back in ancient times (circa 1990s) I called into COM all the time from VB and ASP. I knew the libraries were all there to do what I needed to do.

I was not surprised to find I wasn’t the first person down this path, and quickly encountered multiple articles and postings about working with the file system via COM this exact way.  With the knowledge that it was possible I plowed forward.

To access COM from Silverlight one uses the AutomationFactory to instantiate a COM library.  I wanted to use the good ol’ Scripting.FileSystemObject.  In my test case I had a Silverlight app running locally OOB with elevated privileges.  This Silverlight app has a single list box which will display the drive letters once I can get access.  Via COM, the code looks like this:

dynamic fs = AutomationFactory.CreateObject("Scripting.FileSystemObject");

foreach (dynamic drive in fs.Drives)
{
  filesListBox.Items.Add(drive.DriveLetter);
}

Its really that simple. The dynamic keyword and COM do all the heavy lifting. The most work I had to do was lookup the object model to use in the FSO, as no intellisense is available. The runtime does late binding onto these properties via the DLR. This did a nice end-route around the missing Silverlight IO libraries and provided me with a nice list of drives.

Silverlight, REST, and Unhandled Exception

March 19th, 2010

As part of the final push to finish up our brand-new, Silverlight 3, MVVM application I have been writing a lot of logging and instrumentation code.  Any new platform is a risk, and while we believe we have taken a solid approach using MVVM and the unit testing it allows, we still don’t really know how this thing will perform in the field.  With this in mind, I am trying to be rather liberal in the logging.

In Silverlight, one can write code to handle any unhandled exception in the application.  This type of functionality exists in Winforms, WPF and ASP.Net, so I wasn’t terrible surprised to find it available.  This is incredibly convenient.  I can attack areas likely to cause exceptions such as web service calls with specific logging and exception handling code, and catch everything else with a few lines of general-purpose logging.

As soon as I implemented this catch all I immediately started getting log messages stating:

No XAML was found at the location ”.

at System.Windows.Navigation.PageResourceContentLoader.EndLoad(IAsyncResult asyncResult)

at System.Windows.Navigation.NavigationService.ContentLoader_BeginLoad_Callback(IAsyncResult result)

at System.Windows.Navigation.PageResourceContentLoader.BeginLoad_OnUIThread(AsyncCallback userCallback, PageResourceContentLoaderAsyncResult result)

at System.Windows.Navigation.PageResourceContentLoader.<>c__DisplayClass4.<BeginLoad>b__0(Object args)

Well, that was really helpful.  And after some Google searches I soon realized that I wasn’t going to find a solution on the web.  Well, I guess this is why I actually get paid to program.  After some testing I discovered that the only time I saw this error (and it was just logging, it never bubbled up to the UI) it was when leaving the Silverlight app for another page in our web application.

Our app takes advantage of Silverlight’s Frame + Page navigation handling, which can map one URI to another.  In practice this is basically REST.  When the frame “hears” a new URI entered it converts the URI  to an internal, component-based URI with the location of the Silverlight page to display.  These mappings are configured during our bootstrap process which rides on top of Prism.

As it turns out, when the user (me) clicks on a link to leave the Silverlight app, the frame “hears” a new URI.  The browser is navigating, and the frame tries to handle it.  But it doesn’t have a mapping for the URI, which is curiously an empty string no matter where outside the Silverlight app one is navigating.  The frame barf, and produces the above exception.  But no one sees it because the app is closed within a split second of all this happening.

After poking and prodding with various ways of squashing this, I finally figured out that in the Navigating event of the Frame I can just set e.Cancel = true, which tells the frame to not navigate.  My conditional logic simply checks to see if the URI is empty.  The browser continues on with its business, and the Silverlight app ignores the navigation from that point on.

Hopefully this entry helps someone else doing REST in Silverlight.

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.