Silverlight Hack

About Me

Welcome to Silverlighthack.com. This is a site where you can find many articles on Silverlight, Windows Phone 7 and .NET related technologies.

My name is Bart Czernicki. I have been working with computers since 1988 and have over 12 professional years in the IT field focusing on architecture, technology strategy and product management. I currently work as a Sr. Software Architect at a large software development company.

Below is the cover of my new book that shows how Silverlight's unique RIA features can be applied to create next-generation business intelligence (BI 2.0) applications.

Contact: bartczernicki@gmail.com

NONE of the comments or opinions expressed here should be considered ofmy past or current employer(s). The code provided is as-is without anyguarantees or warranties.

Silverlight clientaccesspolicy.xml files for the Enterprise (Part 1 of 2)

I decided to move this article up the chain in my backlog of articles as I have come across this scenario numerous times on the http://silverlight.net/ forums. This article will give some basic information that has been covered on numerous other sites and times and give some additional insight on how to handle cross-domain issues in enterprise Silverlight service deployments.

Note: This article is pretty long and doesn't really fit well into a blog format (which I find is very limited for effectivily presenting technical ideas on a larger scale). I am going to start moving some of my bigger articles into possible whitepaper format as well.

Contents of this article (Part 1 of 2):

Background Information about cross-domain service access in Silverlight

Deploying cross-domain policy files on Enterprise Servers

Examples of Enterprise cross-domain configurations

Problems with maintaining the clientaccesspolicy.xml file manually

HttpHandler solution for dynamic clientaccesspolicy.xml files for the Enterprise

Background Information about cross-domain service access in Silverlight

Silverlight 2 uses services as its primary source of retrieving data across domain boundaries. Once you enter the services and web application domain, you are exposing your content to malicious attacks. One way Silverlight prevents its applications from launching malicious attacks on other sites is through opt-in cross-domain access. This means the site has to say yes in order to receive and respond to requests from a particular domain. This opt-in feature is controlled by a clientaccesspolicy.xml file. If you have done any WCF programming with Silverlight, this should be familiar to you. If not, check the basic information on the MSDN site here.

The clientaccesspolicy.xml file is located where the service is being hosted. This is a very important point. Most Silverlight developers that are starting out make a mistake in that they think the clientacesspolicy.xml is deployed onto the server where the Silverlight application is hosted. This is not true and can cause many debugging headaches. The clientacesspolicy.xml NEEDS to be deployed on the server hosting the WCF service so that Silverlight can properly consume it.

Note: For simplicity reasons, I am not adding the crossdomain.xml file which is used by Flash. Silverlight also uses this file in case the clientaccesspolicy.xml doesn't exist. This is done for obvious reasons as Flash/Flex has a bigger install base and Silverlight is simply leveraging a possibly pre-existing cross-domain file.

Example of the format of the clientaccesspolicy.xml file that grants all domains access:

Example of the format of the clientaccesspolicy.xml file that grants access ONLY to contoso.com:

Note: Notice how the only change was to add the <domain uri="http://contoso.com"/>. This is more secure and other domains will be disallowed from making service calls.

Clientaccesspolicy.xml file that only grants service access from contoso.com (other requests are not fulfilled):

Deploying cross-domain policy files on Enterprise Servers

One of the key aspects of a clientaccesspolicy.xml file is that it needs to be accessed on the root of the website. In our example above, the request is http://mycontososervice.com/clientaccesspolicy.xml. In order to achieve this on IIS, we would simply place the clientaccesspolicy.xml file on the root of our website (default IIS: c:\inetpub\wwwroot folder). If you want to grant multiple domains access, an admin simply can modify the clientaccesspolicy.xml file.

As mentioned above, Flash has an equivalent cross-domain configuration file to Silverlight called the crossdomain.xml file. This file has a different format; however, it serves the same purpose as the Silverlight clientaccesspolicy.xml file. Let's take look at how some of the largest companies based on services use this file. You can try this yourself by using any browser.

Secure and unsecure (http vs. https protocols) also make the calls cross-domain.

As you can see, maintaining these files can get quite complex very quickly in more advanced scenarios. These files need to be accurate and improperly formatted xml config files can cause the validation of the configuration to be invalidated.

Problems with maintaining the clientaccesspolicy.xml file manually

Maintaing the clientaccesspolicy.xml file manually on a single or even a couple of servers is not a problem. However, maintaining complex properly validated clientaccesspolicy.xml files on multiple servers or domains can be quite challenging. One single fat finger and the file can invalidate all service calls. Improperly adding or not removing a domain can cause a serious security violation.

Scenarios where manually maintaining the clientaccesspolicy.xml file manually can be an issue:

You are maintaining 2 different RIAs and want to keep both XML files in sync (I know Silverlight can use Flash's file, but we want to prepare for mass Silverlight deployments)

The clientaccesspolicy.xml file is complex. You have over 10-15 domains, subdomains and protocols that all have to work.

The clientaccesspolicy.xml is dynamic

The solution you offer allows clients to access the site through specialized domain (i.e., client.mydomain.com, client2.mydomain.com)

Lots of changes occur to the file and you want to eliminate the "human factor".

The web service server is part of a web server farm or a cluster. The files need to be in sync almost instantaneously.

Client anonymity is important (i.e., You don't want to expose who is consuming your services)

Obviously some of these challenges can be mitigated with other security measures and designs. However, let's assume that in your scenario you have a properly working architecture/deployment and the clientaccesspolicy.xml file is becoming a maintenance nightmare. What can you do?

HttpHandler solution for dynamic clientaccesspolicy.xml files for the Enterprise

To overcome complex cross-domain scenarios by using some of the more advanced features of ASP.NET, we can mitigate some of the manual work that comes with creating cross-domain policy files. HttpHandlers are one way to solve some of the problems I listed above.

Httphandlers are a pretty powerful tool for ASP.NET applications that extend ISAPI extensions. There are many uses for Httphandlers and one of them is to map certain web requests to specific handler functionality. (I am not going to go over handlers in detail. If you need more information, try this link: http://www.15seconds.com/issue/020417.htm). We can create an HttpHandler that will see a request for a clientaccesspolicy.xml file. Instead of manually copying the file off of the root server, we can generate the file dynamically.

Change the getter for the IsResusable property the exception to simply "return true;" (This allows the Handler to be pooled.)

Delete the "throw new NotImplementedException();" inside the ProcessRequest method. We are going to replace this with code. We are going to use LINQ in order to build the clientaccesspolicy.xml file. We can just as easily use StringBuilder, XmlDocuments or other forms. (This is NOT meant for production. This is just illustrating a concept.)

Add a reference to the System.Core assembly. (This houses the LINQ methods.)

Add the following using statement: "using System.Xml.Linq;" .

Copy and paste the code below and insert it into the ProcessRequest method. The code below uses the Parse method from the XDocument class to load a string and transform it into an XDocument object.

Deploying managed HttpHandlers on IIS 7.0

This will go over deploying the HttpHandler solution we created above into IIS 7.0. I wanted to provide some basic instructions on deploying handlers as it can be tricky, making this article a complete resource. However, this article is not about deployment so I will cover only IIS 7.0. Why IIS 7.0 and not 6.0? Simply because I think that most advanced developers should be taking advantage of IIS 7.0 features and some of the new WCF 4.0 bits will only work in IIS 7.0. If you haven't converted to developing on either Vista or Windows 2008 now is a good time to do so.

This is one way we can deploy the HttpHandler on our server. I like this solution as it is a global way to add the handlers to the entire web server and it is simpler to follow. There are several different ways to do this. Another good solution would be to deploy the handlers with a Silverlight web project. This way the clientaccesspolicy.xml handler is only enabled when a Silverlight application is deployed.

Build the SilverlightCrossDomainHandler solution in release mode

Sign the assembly so that we can deploy it to the GAC

Install the assembly into the GAC by copying the assembly to the c:\windows\assembly\ folder

Edit the web server web.config and add our assembly type

Navigate to the C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG\ folder (v2 because that is the last version that has hooks into the core ASP.NET assemblies....NET 3.0 and 3.5 simply build on top of this)

Open the web.config file with Visual Studio

In the compliation element there is an assemblies element with several assemblies listed. We will add our custom assembly here.

Note: The PublicKeyToken could be different if you are doing this project on your own. Simply copy it and replace it with whatever your assembly has been signed with. You can check what your public key token is by right-clicking the assembly once it is in the GAC

Save the web.config file

Add the HttpHandler to the global web server

Open up IIS Manager

Double click on "Handler Mappings"

There will be several listed that are pre-installed when ASP.NET and IIS are set up by default. In order to add your own right-click and select "Add Managed Handler..." (this can take a few seconds)

A dialog box will appear

In the Request Path enter: clientaccesspolicy.xml (this will mean that ANY request to the clientaccesspolicy.xml file will be handled by our handler we choose)

Select the SilverlightCrossDomainHandler and whatever type you want (i.e. BasicClientaccesspolicyHandler) from the dropdown menu (if it is not located there, you probably messed up editing the web.config file)

Name the handler what you like (i.e. Clientaccesspolicyhandler)

Perform a restart on the web server or an iisreset or restart the application pool

Testing managed HttpHandlers (inside the browser)

To test our deployment simply point your browser to http://localhost/clientaccesspolicy.xml. Of course, you want to make sure that you actually do not have a clientaccesspolicy.xml file on the root of IIS. If you put the URL into the browser and click OK, you will simply get a blank page (as this is not an HTML/ASPX/RSS etc request that has a visual reponse). You can either use Fiddler or Web Development Helper. To test using the Web Development Helper (for those that use Fiddler, you know how to do this already):

Install the tool, if you haven't done so already. The tool is an add-in for Internet Explorer after you install it you have to close all your IE sessions.

Go to Tools -> Web Development Helper

A window shoul appear on the bottom

Check Enable Logging (this will let you monitor any requests made from the browser)

Double-click on the row and a dialog pops up with detailed information about the request

Click the Response Content Tab and notice that we have a well formed clientaccesspolicy.xml file

Note on the screen shot that Enable Logging is checked. We received a response from the request and the Response Contect is well formed for the clientaccesspolicy.xml and it is ready to serve us:

The fun doesn't stop here :) Since we deployed the handler to handle ANY request anywhere for clientaccesspolicy.xml (which you may or may not want to do). All requests for subdomains work fine as well and are handled by the very same handler we installed. In my test case I created a sub domain and profiled and it works fine:

TroubleShooting

If you do not have the proper IIS ASP.NET and Extensibility add-ons (ISAPI) turned on, you might receive this error: (Simply go back to Add/Remove programs and add the ASP.NET and Extensibility features for IIS). Furthermore, ensure that ASP.NET is properly registered on your site.

Summary

This article introduced you to some of the basics in managing a clientaccesspolicy.xml file for the Enterprise. We looked at other cross domain files how they are published in Enterprise scenarios and how some scenarios could warrant a more dyanmic configuration file. One way to solve the complexity of dynamic cross-domain configurations is to use HttpHandlers to create the configuration for us. In part 1 of the series we created a simple HttpHandler that returned a well formed file. In part 2 of the series, we will create a dynamic clientacesspolicy.xml file from a database store that will properly create the file in a more complex scenario.

PDC 2008 - Silverlight 2 Wrap-Up

PDC (Professional Developers Conference) 2008 is over and there was a lot of information released over the course of the 4 days. You probably have heard some of it if not all of it. I wanted to write a post to summarize the information pertaining to Silverlight either directly or not directly that was released last week. Over the course of the week, Silverlight developers were bombarded with information that was coming out and this post's goal is to help developers get a handle on all of the information. Here is the summary of what has been released during the week of the PDC 2008:

Silverlight Tools for Visual Studio 2008 SP1

Silverlight Control Toolkit

Expression Encoder SP1

PDC Silverlight Videos (directly related)

PDC Silverlight Videos (indirectly related)

Silverlight 2 for Mobile Devices

WCF REST Starter Kit

Silverlight and SEO

Silverlight Tools for Visual Studio 2008 SP1

Silverlight Tools for Visual Studio 2008 SP1 were released over 3 weeks ago. However, for those people who are detailed oriented, this release was labeled as RC1. I posted a question on this on the forum the day this was released. Apparently, this was NOT the final release of the tools. On 10/30/2008 Microsoft released a new build of the Silverlight Tools. I don't think anything has changed, but regardless, you will want to update your tools to this new build. The new build of the tools can be downloaded here: http://www.microsoft.com/downloads/details.aspx?FamilyId=c22d6a7b-546f-4407-8ef6-d60c8ee221ed&displaylang=en

Silverlight Control ToolKit

The Silverlight Contol Toolkit was announced at the PDC 2008. It has a bunch of great controls, themes and charting cababilities. The big news is that the toolkit is open sourced and it you can extend it or build your own controls. Not only is it a great way to enhance your current Silverlight applications, but it is also a great way to learn about Silverlight control development and architecture. Shawn Burke's team has also included a bunch of unit tests using the Silverlight Framework so you can learn how to implement some TDD with Silverlight. You can download the toolkit here: http://www.codeplex.com/Silverlight

Expression Encoder SP1

Expression Encoder SP1 has been released. I like the approach Microsoft took by adding service packs to both Blend and Encoder rather than forcing people to upgrade. Therefore, people who have invested in version 2 are getting their money's worth. SP1 of Encoder allows you to create custom Silverlight 2 video player skins. It also includes H.264/AAC support. The service pack is available here: http://www.microsoft.com/expression/try-it/default.aspx?filter=servicepacks (Note: Expression Encoder also has an Express version which will work after the trial expires allowing you to do some basic things.)

PDC 2008 Silverlight Related Videos Online

If you weren't at the PDC, Microsot published the videos from the 4 days to the web. You can watch the PDC 2008 Videos online here: https://sessions.microsoftpdc.com/timeline.aspx. Here are the videos that are either directly or indicrectly related to Silveright development and I have some notes on the ones I watched.

If you are an architect, development manager, etc., I highly recommend watching some of these videos and then getting your team together for a lunch or a meeting and watching this together. I find this spurs developers thinking together about the current and future technology earlier.

Lots of great Blend information. They have some good tips on Fonts towards the end. There is lots of great information about Blend 3. If you are a Silverlight/WPF developer, I would recommend checking this one out.

Seema has a lot of great tips on making your Silverlight applications run faster. If you're going to watch one video from all of the PDC, this one should be it. Lots of great debugging tips and tools are shown as well.

Silverlight cannot consume data directly from objects or databases located on servers (even if it is the same server Silverlight is hosted on). Silverlight is all about consuming data from services. These videos are an absolute MUST to watch if you are a Silverlight developer and consume data from services.

Great introduction on developing WCF services that are based on REST. Towards the end of the video there is a great example of consuming these services via a Silverlight client. Unless you are a REST expert, you will gain a lot of information from this video.

Excellent video that deals with ADO.NET Data Services development and the Entity Framework. This video shows some of the cool interceptors for security and enhancing services that exist in ADO.NET Data Services. If you are building a simple Silverlight client that needs, call batching, smart data and/or security concurrency management, ADO.NET Data Services provide a lot of great features here.

Silverlight 2 For Mobile Devices

Microsoft is porting Silverlight to mobile devices. This is a really welcome feature. Many users who have an iPhone know that Apple is currently "blocking" the availability of Flash to mobile devices. This is where Silverlight has a potential advantage and put a dent in the Flash market share by targeting mobile devices. Most of this information is coming from this video here from the PDC: http://channel9.msdn.com/pdc2008/PC10/

Here are some of the highlights from the PDC:

By 2010 statistics show that there will be about 4 billion mobile phones in the planet. There is a huge opportunity here! So how do you write applications that are rich to thousands of users? Silverlight :)

Silverlight 2 (That's right; the same Silverlight 2 on desktops) has been announced for the mobile space.

Plublic CTP will be available in 2009 (Q1). My guess is that they will release this at the same time as MIX 2009.

The really cool part is that the SL 2 on mobile requires NO CODE changes to work on a mobile device where Silverlight is installed!! That is really nice and very powerful and one code works on both the desktop and mobile devices.

The Baby Smash demo really drives this point home further. So not only can you share code between WPF and Silverlight 2, you can share code between WPF, Silverlight 2 and Silverlight 2 Mobile! That is impressive; three platforms with one codebase.

WCF REST Starter Kit

One of the ways that Silverlight can consume data is through RESTful services. WCF was part of the .NET 3.0 framework back in 2006. In 2006 REST services were just starting to get traction as many Web 2.0 companies used this design as a preferred method for their service APIs. WCF .NET 3.5 has added some features for REST services. However, there was still a lot of plumbing code in order to write proper RESTful services in .NET 3.5. The MySpace API is a great example of what can be done with WCF and REST on a very large implementation.

In order to make writing some of the WCF REST services easier, Microsoft released the WCF REST Starter Kit during the PDC.

The WCF Starter Kit makes building RESTful services a lot easier. It also shows the impressive architecture of WCF. It can be enhanced with using attributes and interceptors to build a REST architecture for services.

Silverlight and SEO

Several months ago Google announced that it can now crawl Flash-based applications. This is pretty important because now Flash-based content is searchable and this is critical to any revenue model that is based on high-page ranks on Google (sales, ads, etc). Silverlight currently cannot be crawled by Google (maybe in the future). However, there are couple things you can do right now to make sure your Silverlight application gets crawled by Google:

Ensure that the page hosting your Silverlight content has proper meta tags and place the SEO there.

You can also place a page for a "deprecated" client. Therefore, if you receive a hit from a user that doesn't have Silverlight, you can bring them to an HTML page rather than the full Silverlight client. This way when the Google robot tries to crawl your site, it will crawl it based on the HTML page.

This information is really important for developers that are jumping into RIA. Most architects are ready to jump right into the technologies and try to solve problems with RIA. However, things like SEO sometimes might fall through the cracks and might not be acceptable to a client. Check out this post for more information on Silverlight SEO Optimization: http://nerddawg.blogspot.com/2008/10/search-engine-optimization-for.html

Silverlight 2 for Mobile - Why you should start using a MVC pattern

Silverlight 2 for Mobiles was announced at the PDC. I wasn't there, but I read about it on Chris Hayuk's blog here. The real cool part of the announcement is what they announced that there will be no changes required to your code. So, this is not some Silverlight-type Compact Framework step child subset of .NET. To quote Chris exactly:

"YOU DO NOT HAVE TO DO ANYTHING

TO MAKE YOUR SILVERLIGHT APPLICATION TO MAKE IT WORK ON THE MOBILE,

NO RECOMPILING, NOTHING."

That is a pretty cool goal if Microsoft achieves this kind of transparency with the Silverlight 2 plug-in on mobile handhelds. However, to think that your 1280x1024 site with huge graphics and animations is going to automatically scale properly is ludacris. However, this is what software design/architecture patterns were made for.

You have problaby heard of the ASP.NET MVC Beta out there that has all the no postback and no viestate fluff etc. However, the MVC pattern at its core seperates the business logic from the UI. For example, in your web form you have a button and then you write a click handler to print "Hello". In ASP.NET this would be handled all in your codebehind cs file. With the MVC pattern changes this where the user click is handled by the controller and then sent to the model. I am not going to go over MVC in any kind of detail. However, the main thing to understand is that the UI code is seperated from the business logic properly and other UIs can simply be plugged in with a different View component. This lends itself very nicely to the Silverlight MVC pattern. Imagine writing an application in Silvrerlight 2 and simply swapping out the View for Silverlight 2 Mobile and the entire application just works. No code changes just that inside a regular browser you will load a normal View object and for Silverlight 2 Mobile you will use your Mobile View. This mobile view might be: simpler in scale, use a simpler/clearer theme, use less animations in order to fit nicely inside the smaller resolution screens. Depending on how your app is designed this might be all enclosed inside your XAML.

I had my "oh that makes sense now" moment with MVC several months ago, after seeing an example similar to this. Hopefully Silverlight developers can see that using a pattern like MVC (or MVP etc) is really powerful and not just some loosely thrown around "best practice". Furthermore, hopefully this example with Silverlight 2 Mobile helped. If Microsoft achieves its goal of being able to have one single runtime for the web and mobile; investing in the MVC pattern can potentially save you a ton of work in the future if you are thinking about targeting the mobile market.

I decided to compare Silverlight in a similar way to what Jason did when he compared ASP.NET MVC vs. Web Forms.

Here are the items he listed as ASP.NET MVC vs. Web Form:

PROs vs. ASP.NET Web Forms

No ViewState or "surprise crap"

This applies to Silverlight as well. Silverlight brings the "desktop" experience to the end user and there is no ViewState that is used in Silverlight.

Faster server-side& client-side

Silverlight is faster on the client/server side depending on how you look at it. Silverlight is compiled in a .NET subsystem of Silverlight. You have access to multithreading, LINQ, complex data structures, etc. The performance vs. an ASP.NET or AJAX/JavaScript application is it magnitudes times better because of the client execution and some of the items that normally are handled in a server BLL can be brought down to the client

Simplified model for multiple related views

Silverlight supports the complete seperation of the data and the UI. Taking this further by just creating seperate views for say another consumer of Silverlight is pretty powerful. You can apply the same MVC/MVP pattern inside Silverlight and attain this level of abstraction. Jason mentions an example of being able to create a seperate view for an iPhone and only the View component has to change. This applies to Silverlight as well for different things. For example, I have large sized Silverlight app I want to port to SharePoint. I can create a "Smaller View" for SharePoint so it fits nicer into the UI. Furthermore, Silverlight Mobile is being private tested now. I would assume that same very powerful level of abstraction applies as well to create a "Mobile view" for your Silverlight application.

Silverlight does NOT care if you are not running on IIS 6 or IIS 7 or Apache for that matter. This is one feature where Silverlight has an advantage over ASP.NET MVC.

Client Caching

In ASP.NET Web Forms or MVC, you are caching on the server. Silverlight allows you to cache on the client via Isolated Storage (which can be increased to hundreds of megs if necessary). This allows applications to perform ultra fast without bogging down the hosting server.

CONs vs. ASP.NET Web Forms

Difficult to convert existing code

Silverlight is a completely different programming platform than either ASP.NET WebForms or MVC. Not only will a lot of the code not convert, you also have to think about the client layer and in most cases a complete re-architecture is needed if you are replacing large modules inside your existing ASP.NET site.

NOT the best SEO out of the box

Google several months ago started spidering SWF files and adding them to the search engine. I think Silverlight is probably still a ways away here. What you can do for Silverlight SEO is the basic tricks to describe the meta data tags really well around the plug in.

Data access

Data access in Silverlight is limited to Web Services/WCF/ADO.NET Data Services. You cannot make direct calls via ADO.NET or stored procedures to a database.

Security

Silverlight runs on the client. A lot of your bits are then roaming in the wild on the internet. Furthermore, some of the data access techniques do not support full WS* standard security. Therefore, beyond certificate based transport security, you are either writing a lot of your own plumbing code or waiting for the next rev. The XAML code is pretty much insecure; not many applications have their Intellectual Property in their UI. In Silverlight, that can be very easily reverse engineered using Silverlight Spy for example. Silverlight, just by nature, is a little less secure than an ASP.NET MVC application. Obviously, you would want to encrypt/obfuscate your Silverlight assemblies before letting them off in the wild.

In conclusion, even though Silverlight and ASP.NET MVC are two completely different technologies, they share A LOT of the same pros and cons Jason pointed out vs. Web Forms. The only difference is that the hosting model for Silverlight is a lot simpler. Silverlight does have its nuances with data access and security that you have to worry about. Furthermore, you do get other benefits like client-side performance and client-caching.