WCF Ria Services vs Entity Framework

This is a quick tip for anyone using WCF RIA Services with Entity Framework.  The WCF RIA Services team has fixed what I consider a fairly annoying ‘bug’ with Entity Framework.  In Entity Framework the EntityCollection class does not implement INotifyCollectionChanged, however the client side EntityCollection class that RIA uses is part of the RIA framework and they have fixed this issue.  They have explicitly implemented the interface however so you will need to cast the EntityCollection to a INotifyCollectionChanged before you see the CollectionChanged event.

RIA Services XMLMetaDataProvider and Dynamic Assemblies

If you are using the XMLMetaDataProvider and have a dynamic assembly reference your service might fail with the following error:

           The invoked member is not supported in a dynamic assembly

There are two fixes for this problem, one is to use the full attribute names.  So ‘DisplayAttribute’ instead of just ‘Display’.  Second option is to fix the code in MetadataSet.cs.  The problem is with the TryGetType method around line 421.  You should be able to find the code below, the GetExportedTypes needs to be changed to GetTypes. 

   1: // TODO : the metadata file might need a way to specify the set
   2: // of source assemblies to load from - for now search all loaded assemblies
   3: foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
   4: {
   5:     foreach (Type t in assembly.GetTypes())
   6:     {
   7:         if (t.Name == typeName || t.FullName == typeName)
   8:         {
   9:             typeMap[typeName] = t;
  10:             return t;
  11:         }
  12:     }
  13: }


Thanks to Manfred Lange for the tip on the error message.

WCF RIA Services XMLMetaDataProvider Problem

The current RIA Services project I’m working on has been using the XMLMetaDataProvider due to the fact that our model and DomainService are in different projects.  This rules out defining your metadata in a partial class for each entity.   As the project got bigger we noticed that randomly our metadata was not being created at build time.  Turns out there is a race condition with loading the XML file and the requests for metadata.  Here is the new XmlMetadataProvider.cs file where we now load the dataset in the constructor, not the first time it is requested.  After all that, I think we’ll try using Nikhil Kothari’s fluent API style, I like the look of it over the mass amount of XML.

   1: internal class XmlMetadataProvider : TypeDescriptionProvider
   2:     {
   3:         private Type domainServiceType;
   4:         private MetadataSet metadataSet;
   6:         /// <summary>
   7:         /// Constructor that accepts a metadata context to use when generating custom type descriptors
   8:         /// </summary>
   9:         /// <param name="existingProvider">The parent TDP instance</param>
  10:         /// <param name="domainServiceType">The DomainService Type exposing the entity Types this provider will be registered for</param>
  11:         public XmlMetadataProvider(TypeDescriptionProvider existingProvider, Type domainServiceType)
  12:             : base(existingProvider)
  13:         {
  14:             this.domainServiceType = domainServiceType;
  15:             LoadMetadataSet();
  16:         }
  18:         public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)
  19:         {
  20:             return new XmlMetadataTypeDescriptor(this.MetadataSet, objectType, base.GetTypeDescriptor(objectType, instance));
  21:         }
  23:         private MetadataSet MetadataSet
  24:         {
  25:             get
  26:             {
  27:                 if (metadataSet == null)
  28:                 {
  29:                     LoadMetadataSet();
  30:                 }
  31:                 return metadataSet;
  32:             }
  33:         }
  35:         private void LoadMetadataSet()
  36:         {
  37:             metadataSet = new MetadataSet();
  39:             // load all the metadata files found
  40:             IEnumerable<string> metadataFiles = domainServiceType.Assembly.GetManifestResourceNames().Where(p => p.EndsWith(".metadata.xml", StringComparison.OrdinalIgnoreCase));
  41:             foreach (string metadataFile in metadataFiles)
  42:             {
  43:                 Stream stream = domainServiceType.Assembly.GetManifestResourceStream(metadataFile);
  44:                 StreamReader streamReader = new StreamReader(stream);
  45:                 String metadata = streamReader.ReadToEnd();
  47:                 try
  48:                 {
  49:                     metadataSet.Load(metadata);
  50:                 }
  51:                 catch (Exception e)
  52:                 {
  53:                     string msg = string.Format(CultureInfo.CurrentCulture, Resource.MetadataLoadError, metadataFile) + " : " + e.Message;
  54:                     throw new InvalidOperationException(msg, e);
  55:                 }
  57:             }
  58:         }
  59:     }
  60: }

Enter the Stargate Destiny, courtesy of Silverlight, DeepZoom, Photosynth.

This may result in a “geekasm” – you’ve been warned.



How’d they do it?

MGM Stargate Case Study

Silverlight 3.0 and Why Flash Still (unfortunately) Won

Last week Silverlight 3.0 was released.  In Toronto, ObjectSharp put on a very cool launch event, with lots of great demos and compelling reasons to start using Silverlight immediately.  I was impressed, but I’m a Microsoft fan-boy (fan-boi?), so that doesn’t count.  It was certainly fitting that ObjectSharp propose using Silverlight for some parts of our new website www.woodbineentertainment.com, seeing as they won the bid to build the new site.  I saw the potential; as did a few others on the team.  However, some executives did not see the benefit.  I respect their opinion, somewhat because I have to – they can fire me after all, and mostly because they have business sense on their side.

The company is very much on the cutting edge of technology in a few respects, but very conservative in the way we choose technology.  For instance, our new site will be built on Microsoft Office SharePoint Server 2007.  I’d wager there are less than a hundred publically facing websites on the internet that use MOSS (probably due to complexity and cost), yet we chose to use it because of the potential in further developing it in future iterations.

Silverlight on the other hand is a different story.  Recent reports peg Silverlight penetration at around 25-30% of all browsers.  Whether or not this is accurate, who knows.  It’s the only data available.  Flash penetration is at 96%.  Now, in my opinion 25% growth in 2 years on Silverlight’s part is impressive.  Flash has been around for nearly 2 decades.  There is definitely a correlation to be made in there somewhere.

At this point, I was sold on using Silverlight.  The exec’s still weren’t.  Seeing as Silverlight is a browser plug-in, it must be installed in some way, shape, or form.  At 25%, that means our customer demographic would have around 10% penetration.  That is terrible.  Getting them to install a plug-in to view site content is a tough sell.  The executives didn’t want to scare away customers by making them install the plug-in.  SharePoint doesn’t need a browser plug-in.

And here in lies the Catch-22

To expand our marketed audience, we build on Silverlight to give them more content that is better authored to their needs.  In doing so, we lose customers because they need to install the plug-in.  There is no metric at this point in time to help us extrapolate the difference.  There is a reasonable risk involved with using such cutting-edge technology.  We will use it when browser penetration is high enough, yet browser penetration won’t grow if sites like ours don’t use Silverlight.

Ah Well

I’m a technology risk taker.  I live on the bleeding edge.  I run Exchange 2010 beta, on Server 2008 virtualized on Hyper-V, with IIS7 running this site, browsed by IE8 on Windows 7 RC, and authored in Office 2007 (2010 if Microsoft would give me the flippin bits!).  The company, not so much.  Risk is good – as long as you can mitigate it properly.  I can manage my risk, as it’s not the end of the world is something here crashes.  I don’t lose an audience.  If the company can’t market to it’s customers because the tools in use are too new, it will lose audience.  Period.  And that means lost revenue.

Maybe we can convince the exec’s in Phase II.

Join ObjectSharp for Silverlight on the Silver Screen – July 9 – Scotiabank Theatre Toronto

Silverlight 3 will soon be released.  And to properly celebrate the excitement of its release, ObjectSharp is teaming up with Microsoft to present an action-packed first look at the UX3 platform, live from the Scotiabank Theatre in Toronto. 

As one of the first companies to be featured on Microsoft’s Silverlight gallery, our consultants will share with you their deep knowledge of the next generation of tools.  Whether you are a designer, developer, or purely a marketing geek, you will not want to miss this blockbuster event.  You will see feature-rich demonstrations of Silverlight, Expression Blend, SketchFlow, and  Windows 7 touch technology.  You will also see how these tools can be used to dazzle your customers and gain attention for your brand.







For Developers and Designers:

  • See in-depth demonstrations of Silverlight 3, Expression Blend, and Windows 7 touch technology.
  • Learn how to quickly design user interactions with Microsoft SketchFlow
  • Take Designer/Developer work flow to the next level with Visual Studio Team System
  • Learn how to cut off your bosses head off and paste it on other people’s bodies with Expression Studio


For CTOs and Marketing Managers

  • Understand the benefits of creating line-of-business applications with Silverlight and .NET RIA Services
  • Learn how to integrate Rich Media and Advertising with the Microsoft Platform
  • See Touch technology and natural user interfaces bring kiosk applications to life with Windows 7 and WPF

Technologies You Will See:

  • Silverlight 3 featuring WPF & XAML
  • Expression Blend 3 featuring SketchFlow
  • Windows 7 featuring Touch
  • Microsoft Office SharePoint System 2007 (MOSS) for external facing web sites
  • Visual Studio 2010 Team System

Register Online   |   Watch the Movie Trailer

Data Bondage in WPF presentation at Toronto Code Camp

My final presentation in my April World Speaking tour was at the Toronto Code Camp this afternoon. As always, the code camp was a huge success. The efforts of many people went into making it so, but the organization was top notch.

As part of the lead-up to my presentation, Joey de Villa made good on a promise to wear Microsoft branded assless chaps. And he even regaled the crowd with his version of Hit Me With Your Best Shot, a choice completely in character with the theme of the presentation.

As for the presentation, it went very well. Something like 70-80 people where there and I was pleased by the questions that were asked. I have always preferred an interactive audience because it means that they are probably listening. :)

As I promised at the end of the presentation, here are links to the slides and demos. Any questions are most welcome.

Slides: here

Demos: Download

Update: For those who want a more complete story surrounding the title of the presentation and the assless chaps references, check out Joey's blog post here.

Dropping Cookies in IE7

I was asked an unusual question yesterday about cookies, Silverlight and WCF. The scenario was that a Silverlight application was being used in a consumer-facing situation. The application itself communicates with the server using WCF. The service which is the target of the communication uses ASP.NET Authentication to authenticate the user. It’s an implementation detail (but critical to this post) that the method of storing the authentication token is a cookie called .ASPXAUTH.

In a normal (that is, working) scenario with Silverlight, the credentials are sent to the server and an .ASPXAUTH cookie is returned. The browser strips off the cookie and stores it. On any subsequent requests, Silverlight creates a request and sends it the the server through the browser’s networking API. The browser is responsible for determining which, if any, cookies should be send with the request and adding them to the outgoing header. In other words, the Silverlight application has no specific knowledge of or interaction with the .ASPXAUTH cookie.

As you would expect, this mechanism works the vast majority of the time. If it didn’t, I think it would have been a significant story long before now. But my questioner was running into a situation where the Silverlight application was unable to communicate with the server even after authentication was performed. What’s worse, this behavior was only happening on IE7. When Silverlight was run through Firefox, it worked exactly as it was supposed to.

The diagnostic step in a situation like this is to use Fiddler (or whatever your favorite TCP trace application is) to view the raw messages. And what was seen is that although the authentication response had the .ASPXAUTH cookie in it, any requests sent back to the server after authentication did not. Given when I’ve already explained about the processing of cookies with Silverlight requests, this eliminates the Silverlight application as the most likely culprit. But it also makes one scratch your head, as we can be pretty certain it’s not a widespread failure of IE7 to process cookies.

The answer likes in a strange bug in IE7. It turns out that if a domain name has a underscore in it, IE7 doesn’t persist the cookies. Let me repeat that, because it’s such a bizarre sounding problem. In IE7, if the domain name has an underscore (‘_’) in it, then any cookies returned from the domain will not be persisted. Which also means that subsequent requests will be ‘cookie-free’.

I’m guessing that most domain names don’t have an underscore, which is why this bug didn’t get widespread notice. In this particular case, the domain was one used for development, which would keep the problem from being a production issue. But I have no reason to believe that the bug would be restricted to a local problem. Deploy a ‘underscored’ domain name to the public internet and no authentication, shopping carts or other state information can be saved.

Fortunately, the solution was a simple one. If the domain name in the endpoint configuration is replaced with the raw IP address, IE7 is more than happy to save the cookie. I wouldn’t be surprise if an entry in your local hosts file would have the same effect. And the final solution would be to have your domain administrator create a DNS Alias entry…one that doesn’t have an underscore, of course.

Code Contracts in .NET Demo Code

This is the demonstration code used during my Code Contracts in .NET presentation for TVBUG.

What’s New in Silverlight 3 at the Toronto Silverlight User Group

This past Thursday, I had the opportunity to present on Silverlight 3 to the Toronto Silverlight User Group. It was my first time presenting to the group and I was impressed by the number of attendees (I would say 30-40) who managed to hang around on the Thursday evening before a long weekend.

As promised, I have posted the slides and the source code to the following links:

Slides: Here

Source Code: Here

If you have any questions, please feel free to drop me a comment or an email message.