The ultimate hack for Silverlight in Blend

I recently needed to write some design-time support for a Silverlight framework.  I needed to discover a solution’s assemblies while running in Blend, and then pass those assemblies downstream for further processing.  In WPF, using the full .NET framework, that’s easy: just call AppDomain.CurrrentDomain.GetAssemblies() and then filter them based on the Location property.  In Silverlight, however, a couple of problems showed up that seemed to make this task impossible.

First, the Assembly.Location property is marked ‘Security Critical’ in Silverlight 3.  This means that if you access the property, an exception will be thrown.

Second, Silverlight 3’s AppDomain class does not have a GetAssemblies method!

It turns out that both of these problems are easy to overcome.  The key thing to know is that when Silverlight code is running in Blend, it’s actually executing against the regular .NET Framework (the same one that WPF uses).  You can access ‘Security Critical’ members and no errors occur.  That takes care of the Assembly.Location issue.  Even though the Silverlight code you write, that is intended to run in Blend, can only access the Silverlight API, you can still access the full .NET framework’s API via reflection.  This allows you to work around the second issue.  For example:

var assemblies = typeof(AppDomain)
   .Invoke(AppDomain.CurrentDomain, null);

Remember, this hack only works when your Silverlight code is running in Blend! This will not work when running under normal circumstances, since Silverlight apps normally only have access to the Silverlight subset of the .NET Framework.

Happy coding!

6 Responses to The ultimate hack for Silverlight in Blend

  1. […] The ultimate hack for Silverlight in Blend (Josh Smith) […]

  2. […] more: Josh Smith on WPF Possibly related posts: (automatically generated)Fixing Visual Studio 2010 and Blend Preview for […]

  3. […] The ultimate hack for Silverlight in Blend […]

  4. […] The ultimate hack for Silverlight in Blend (Josh Smith) […]

  5. radixal says:

    information is very interesting, thanks for sharing

  6. Hello, I came across this blog article while searching for help with Microsoft Silverlight. I have recently switched internet browser from Safari to Microsoft Internet Explorer 5. Just recently I seem to have a problem with loading websites that use Microsoft Silverlight. Everytime I go on a website that requires Microsoft Silverlight, my browser crashes and I get a “npctrl.dll” error. I can’t seem to find out how to fix the problem. Any aid getting Microsoft Silverlight to function is greatly appreciated! Thanks

%d bloggers like this: