Silverlight Hack

Silverlight & related .NET technologies

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.

Silverlight 4 Business Intelligence Soft 

Contact: bartczernicki@gmail.com

View Bart Czernickis profile on LinkedIn

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.

Five Things that HTML5 Video Currently will not do, but Silverlight or Flash will

Abstract:  This article will cover 5 pieces of functionality that are not built-in currently into the HTML5 video specification that Silverlight and Flash can solve.  This article covers potential workarounds and how HTML5 will handle these limitations in the future.  Note a great deal of conent of this article comes from Nigel Parker's talk at MIX 2011 "Things You Need To Know To Start Using <video> and <audio> Today".

Note: this post is meant to be informational about HTML5 video compared to Silverlight/Flash. Even if you don't like Silverlight or Flash, I hope you learn something by reading sme of the current limiations of HTML5 video. For more info check out Robert Reinhardt's article (<Hype>Flash video is coming to iPad.</Hype><Reality>Yet another streaming solution will be available for H.264 to iOS.</Reality>) that covers the topic from another perspective.

Update 10/01/2011: Updated some information below, however the content in this article is still current.

1) Digital Rights Management (DRM) - Cannot protect video content over HTML5

The HTML5 does not and will not ever include Digital Rights Management.  One of the owners of the the HTML5 draft is quoted as saying: "If we provided DRM in the HTML5 draft, it would be hacked in 2 days".  Therefore, content that includes sports, Hollywood movies, tv shows etc. will never be provided over HTML5 video legally.  This can be confusing for some people, because you hear many people post blogs or tweets "Youtube is going full HTML5".  This is partly true.  User content on Youtube will be HTML5, but you will never see copyright music videos or movies on Youtube surfaced over HTML5 containers or codecs.  

Workaround: None (use Silverlight or Flash)

Probability of being included in future HTML5 draft: None

2) No Smooth Streaming or Adaptive Streaming

The HTML5 draft/spec does not include conventions for smooth streaming/adaptive streaming.  Silverlight with IIS 7.x Smooth Streaming extensions can provide this for you.  There do exist third-party solutions for HTML5 adaptive streaming.  For example, Apple's HTTP Live Streaming (HLS).  However, this is not part of the current HTML5 draft/spec.

There is work currently being done to take an adaptive streaming recommendation to the HTML5 council for approval.  The data visualization below (taken from w3.org ) shows this in better detail:

 

Workaround: Use Silverlight, Adobe Flash or Apple's native solutions

Probability of being included in future HTML5 draft: Very High
 
3) No Standard Video Codecs for HTML5
 
The HTML5 draft/spec does not include an explicit definition of what codec should be used for surfacing HTML5 videos.  This has been a contraversial decision that has led to developers of browsers to determine which codecs they allow to play on their browser.  The main contraversy surrounds the use of a proerietary codec (H.264), which both Apple and Microsoft support.  Conversely, the Mozilla, Opera and Google browsers have rallied around an open-source encoder called WebM and Ogg.  Neil Parker's slide from his MIX 2011 talk shows a great breakdown of the codec support in current browsers: 
 
 
Workaround: In the HTML5 markup, you can provide multiple different encoding sources and resolutions targeting mobile or desktop/laptop clients.  Furthermore, you can also fallback to Silverlight or Flash if the browser is not HTML5 compliant.  It is up to the developer to provide all these fallback scenarios.  This is equivelant to providing different CSS or JavaScript depending on browser support.
 
Probability of being included in future HTML5 draft: Very Low (the HTML5 spec would have to change their decision and prescribe a default codec for all HTML5 video tags)
 
4) Full Screen Support 
 
HTML5 currently does not support full screen video.  (Update 10/01/2011) For an example, check out a video from the Microsoft BUILD Conference.  While viewing the video in HTML5 format, you cannot view it in fullscreen (in Silverlight you can).  To me it is kind of a big deal especially when you are looking at source code on a partial screen.
This is not a technology problem or not possible to implement in browsers, however the current debate of full screen HTML5 video centers around what keyboard functions are available and what happens when you exit full screen mode.  The main reason for this is security:
 
"User agents should not provide a public API to cause videos to be shown full-screen. A script, combined with a carefully crafted video file, could trick the user into thinking a system-modal dialog had been shown, and prompt the user for a password. There is also the danger of "mere" annoyance, with pages launching full-screen videos when links are clicked or pages navigated. Instead, user-agent specific interface features may be provided to easily allow the user to obtain a full-screen playback mode." 
 
Note: Silverlight 4 and Adobe Flash 10.2 allow a user with dual monitors to play a video in full screen HD while the other monitor remains responsive to full user input.  It will be interesting how HTML5 browsers solve this, as this could be a potential security problem (since everything to manipulate in HTML5 is done via JavaScript libraries).  Example here of Silverlight 4 dual monitor pinning. 
 
Workaround: Use the VideoFullScreen.js provided by Martin Rauscher: here
 
Probability of being included in future HTML5 draft: High (HTML5 draft spec needs to explicitly define how browers interact with full screen.  For example, initially Silverlight 3 allowed full screen video but limited the keyboard functionality for the same security reasons as mentioned above).
 
5) No Standard Conventions/Look and Feel
 
One of the nice thing about plug-ins like Silverlight or Flash is that you essentially publish your video and let Microsoft or Adobe handle all the compatibility implementations across browsers or operating systems.  For HTML5 video tags it is up to the browsers to implement this themselves.  For example, Neil Parker had a great slide that showed an HTML5 video with a rounded corner border applied.  These are the results: 
 
 
 
This also includes the standard controls that are rendered with each video by different browsers.
 
Workaround: You can create a custom HTML5 video player control or use one of the third party ones.  Some are open source and some you can purchase.
 
Probability of being included in future HTML5 draft: Some of this already is.  It is up to the browser developers to fix their CSS and HTML5 video implementations (or use HTML polyfill patterns).  However, the HTML5 spec is not going to perscribe the very detailed looked of the progress bar of the video control (Note: in Silverlight and Flash you get a consistant look and feel across the browsers since Microsoft and Adobe control this; although you can create your own custom video players as well).
 
Summary 
 
In summary, the current HTML5 specification and implementations for video have some gaps.  It is important to note the current limitations of HTML5 video, especially with DRM.  A naive web developer wil be surprised to know that they can't just put a video tag with an encoded video and have it work as expected across all browsers just like Flash/Silverlight do.  There are some workarounds & solution available to provide Flash-like video.  However, the naive approach that HTML5 solves everything about video for you because its "new" or "better" will quickly get you in trouble.
 
Posted: Apr 16 2011, 13:05 by Bart Czernicki | Comments (10) RSS comment feed |
  • Currently 3.142857/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Filed under: HTML 5 | HTML5 | Silverlight
Tags:
Social Bookmarks: E-mail | Kick it! | DZone it! | del.icio.us

Maximizing your Silverlight LOB investment with Web Parts

Astract:  This article will show you how you can take advantage of the Silverlight architecture for easy deployment to web parts and easy client communication (intra web parts).  This article will amplify why Silverlight is still the technology of choice if you want to create modular functionality deployed as web parts into custom or SharePoint portals.

A few months ago Microsoft made the announcement that they are "repurposing" Silverlight from a general web technology in favor of HTML5.  They have backtracked a bit from this statement and have made statements like Silverlight has some "sweet spots" in line of business (LOB) applications.  Microsoft does a very poor job of defining these sweet spots and what they are.

Silverlight being a web browser plug-in offers some really nice deployment and integration capabilities; one of them being SharePoint and web parts.  This allows you to deploy Silverlight applications to existing custom portals, SharePoint 2003-2010 servers or other web part architectured sites with little/no additional code.  In my opinion this makes the Silverlight architecture very attrictive for intranet line of business applications.

Note: Additional details on this topic is provided in my new book "Silverlight 4 Business Intelligence", where I dedicate an entire chapter to Silverlight web parts. In the book you will see step by step instructions and code samples for the scenarios outlined below.

 

Silverlight as a Portable Web Part Module

Silverlight applications (XAP files) can be easily made into web part by simply surrounding the Silverlight application with a "web part wrapper".  This technique can be implemented via a ASP.NET Web Part interface, SharePoint 2003/2007 web part interface (deprecated) or the new SharePoint 2010 Silverlight Web Part.

Hosting Silverlight in web parts is as simple as "rendering" the XAP package inside the web part. 

Lets take a look an example of how to host an existing Silverlight application in a SharePoint 2010 portal using the new Silverlight web part.  SharePoint 2010 includes a new "Silverlight Web Part" which does exactly this.

SharePoint 2010 includes the "Silverlight Web Part" in the "Media and Content" section.

As long as the SharePoint 2010 server can access the URL location of the XAP file, you host the Silverlight application as a web part.  This means that SharePoint can host Silverlight content as a web part from a:

  • Remote Silverlight XAP file located on the internet
  • Document/SharePoint list URL location of the XAP file inside SharePoint
  • Another internet/intranet portal that is hosting the Silverlight application
SharePoint 2010 Silverlight Web Part requires just the Silverlight XAP file URL to render Silverlight content.
 
The SharePoint 2010 Silverlight Web Part also includes an additional parameter for initialization parameters passed into the Silverlight application before the content is rendered.  This is a nice feature; for example, if you want to let the Silverlight application know that it is being rendered in SharePoint to pull data from ShrePoint lists instead of portal services.
 
What if you want to create a Silverlight web part for SharePoint 2003/2007 or for an ASP.NET portal?  What if you want advanced features like web part communication configuration connections?  In those situations you will need to create a custom Silverlight web part wrapper or use an existing open source one.
 
Silverlight web parts are a VERY powerful feature that is often overlooked.  Imagine you have an existing ASP.NET MVC or ASP.NET web forms site that you want to host inside SharePoint.  This is not very easy without having already invested in a web part architecture.  However, with Silverlight hosting this content in SharePoint is trivial
 
Example of a full Silverlight dashboard hosted in SharePoint 2010 with NO CODE CHANGES (imagine doing this with another web technology if you didn't invest in web parts from the start; Silverlight's plug-in architecture pays dividends here)
 
 
 
Silverlight Web Part Communication 
 
Creating a single web part whether its an ASP.NET web part or Silverlight web part is fairly easy.  There is a lot of material out there to guide a developer through this.  However, web part communication gets very tricky in ASP.NET/SharePoint.  In these situations you will want an action on one web part to trigger a data refresh in the other web parts on that page.  This is where Silverlight really shines.
 
An example of three web parts, where an event on a single web part will update the content of the other two web parts on a page. 
 
In order to do this type of web part communication involves creating custom web parts with the provider and consumer interfaces explicitly defined.  Not only that, but traditional ASP.NET web parts post back and do not provide that "Ajax/web 2.0" feel.  Furthermore, when you have multiple layers of web parts (i.e. providers and consumers switching roles) then this gets very complicated with state management and the web part lifecycle.  Furthermore, interactivity (i.e. a slider moving and changing another web part contents in real-time) is not trivial as well.
 
Note: If you are not familiar with web part connections, look over the MSDN article that describes this.  As you can see the components involved: Web Part Manager, provider/consumer connections, web part interfaces, web part lifecycle all have to "play nice" with each other for this to work.
 
What advantages do Silverlight web parts provide:
  • Allows client-side, real-time communication between web parts without post backs
  • Allows communication between Silverlight and non-Silverlight web parts (using the Silverlight HTML bridge)
  • Simplifies the design/coding of the web parts by NOT having to implement web part interfaces, worrying about lifecycle management, which part is a provider consumer (you can of course do this if you want)
Silverlight web parts allow you to create very modular pieces of functionality inside Silverlight.  However, it also allows the SharePoint admin to expose the pieces of functionality that is interesting from the complete Silverlight application very easily in SharePoint with NO/LITTLE code changes.  Imagine if you have a great Silverlight application with MEF that composes the application in real-time.  You can leverage that composable and dynamic architecture into creating a modular SharePoint gallery that allows Silverlight web parts to communicate with each other based on what the portal admin or power user decide to place on the portal canvas.
 
How does Silverlight Web Part Communication Work? 
 
Silverlight web part communication has nothing to do with the web part framework provided in ASP.NET nor SharePoint!  It is actually natively provided with the Silverlight framework using the local communication APIs.   This means that if you have two Silverlight applications that utilize Silverlight messaging can be deployed a seperate web parts.  Furthermore, they can communicate between each other WITHOUT having to write additional web part framework code around providers/consumers/web part managers etc.
 
The primary mechanism for this is the LocalMessageSender and the LocalMessageReceiver classes.  For example, from the API documentation this all the code that is required to set up communication between two Silverlight applications:
 
// In the receiving application:
LocalMessageReceiver messageReceiver = new LocalMessageReceiver("receiver");
messageReceiver.MessageReceived += new EventHandler<MessageReceivedEventArgs>(receiver_MessageReceived);
try{messageReceiver.Listen();}
catch (ListenFailedException)
{MessageBox.Show("Cannot receive messages." + Environment.NewLine +"There is already a receiver with the name 'receiver'.","LocalMessageReceiver", MessageBoxButton.OK);}
// In the sending application:
LocalMessageSender messageSender = new LocalMessageSender("receiver");messageSender.SendCompleted += new  
EventHandler<SendCompletedEventArgs>(sender_SendCompleted);
 
 
In my book, I provide an example of two Silverlight web parts that can communicate between each other in SharePoint.
 
 
 
Note:  If you want Silverlight web parts to communicate with non-Silverlight web parts, this can be done easily using the HTML bridge.  For example, if a user clicked a Silverlight button this could trigger a post back and via the web part framework send the proper message via the agreed provider/consumer interface.  The part that is tricky is maintaining state between web parts and losing some of the client-side/non-flicker web part messaging.
 
 
Summary and Takeaways
 
This article hopefully showed you some of the advantages that Silverlight posseses when using web parts. Some of the key takeaways should be:
  • It is really easy to deploy a Silverlight application as a web part by simply "hosting it" in an ASP.NET web part.  This allows Silverlight applications to be deployed into custom ASP.NET portals or SharePoint 2003-2010 portals with no or minimal code changes.
  • SharePoint 2010 includes a new Silverlight Web Part that allows you to host local, remote or any Silverlight applications that are URL addressable.  Therefore, deploying a Silverlight application to SharePoint 2010 usually requires no additional code.
  • Web Part communication (which is not trivial to implement in advances scenarios) simply works without code changes inside Silverlight web parts using the local communication APIS.
  • Web Part communication within two Silverlight web parts happens on the client-side.  This provides real-time communication between two web parts without server postbacks nor page refreshes.  Silverlight web parts allow for many interactive scenarios that make UIs feel non-obsolete.
  • Advanced MEF scenarios can enable distributing Silverlight as seperate functional modules that can be deployed into portals dynamically.  This allows you to "break up" a larger Silverlight application into seperate Silverlight web parts that expose particular pieces of functionality.
If you want more details, excercises or code samples on this subject I dedicate an entire chapter to this topic in my book "Silverlight 4 Business Intelligence".
 
Posted: Jan 22 2011, 10:05 by Bart Czernicki | Comments (0) RSS comment feed |
  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Filed under: .net | Silverlight
Tags:
Social Bookmarks: E-mail | Kick it! | DZone it! | del.icio.us

Why a 64-bit runtime for Silverlight 5 Matters

Abstract:  This article discusses the upcoming 64-bit runtime of Silverlight 5.  You will see by example (SQL Server) how a 64-bit runtime can make a dramatic difference in the amount of functionality offered in an application.  These type of enhancements should flow into a 64-bit version of Silverlight 5.

Update 12/6/2010:  I know that the Silverlight 5 64-bit story is not fully understood yet.  This is not a "flashy or cool" feature, but has the potential to be very powerful much like the fact how Silverlight can distribute process work up to 8 logical CPUs.

Today (12/2/2010), Microsoft announced some future functionality and features of Silverlight 5.  A lof of features like media, data binding improvements (i.e. debugging) and 3D got a majority of the attention.  However, one of the most compelling features is that Silverlight 5 will include a 64-bit runtime.   I think a 64-bit Silverlight runtime has the potential to change amount of functionality that can be pushed down to the client.

A 64-bit architecture is More than just Access to More Memory

When most developers or architects are asked what is the difference between a 32-bit or a 64-bit version of an application; the answer is usually "the application can take advantage of more memory".  For the most part that is usually correct.  However, what is sometimes missed is that 64bit versions of applications increase the throughput or ceiling levels of pieces of functionality.  For example, if you have a 64bit version of PowerPivot (running on Office 2010 x64) you can put tens of millions of rows into memory on a client workstation.  This is a trivial example of an application that just leverages x64 architecture to address more memory.

64-bit SQL Server Features

Lets take a look at a more complex example with Microsoft SQL Server.  Microsoft SQL Server comes in two editions: 32-bit and 64-bit.  The current version(s) of Microsoft SQL Server put "frequently requested" data pages (indexes, tables etc.) into memory.  Therefore, a 64-bit version of SQL Server can allocate more of these data pages into memory and alleviate the I/O requests to a SAN or other persisted storage.  However, being able to "place more data into memory beyond 4 GB" is just part of the 64-bit story.

Any SQL Server code that is processed against data structures or algorithms essentially "runs in-memory" (even if the data pages need to be read from persisted storage).  A 64-bit architecture in SQL Server allows you the following features:

 

  • Index creation is faster, because there is more memory available to organize a clustered, non-clustered or the index data pages
  • 64-bit editions of SQL Server allow for more concurrent connections.  Connection pooling algorithms are optimized for the increased memory in 64-bit systems
  • T-SQL joins happen more quickly because heap, merge and other type of joins can happen in memory
  • Prevents "lock escalation".  Queries can hold locks on individual rows, pages instead of an entire table.  This improves concurrency in OLTP databases.
  • Heap joins (in-memory) are optimized for 64-bit architectures
  • Integration Services can take advantage of increased memory buffers
  • Analysis Services (with its OLAP based data structures) is more efficient with more memory
  • there is more....
The table below shows how additional memory in SQL Server can be leveraged to hold more lock resources in a heap table.
 
 
As you can see the ability to address more memory in 64-bit SQL Server provides an increased amount of functionality internally.  It is not just about "putting more stuff in memory".  A lot of the components of a 64-bit version of SQL Server work together with the increased addressable memory together to improve the overall performance of the server.  In a 32-bit version of SQL Server the individual components have caps, so the server does not run out of memory or steal memory from other areas.  In a 64-bit version these ceilings can be increased.
 
So what's the point?  This was not meant to be a SQL Server lesson on 64-bit memory.  However, I wanted to point out how a complex system like SQL Server that has many in-memory components has to juggle the available memory in a 32-bit environment; but not so much in a 64-bit environment.  The same concepts apply to Silverlight 5.  I think this opens up Silverlight 5 to some great potential applications.
 
64-bit Silverlight 5

As of now, we don't know how the 64-bit version of Silverlight 5 will perform or if there will be limitations on it (i.e. how much memory can a single process allocate).  However, the previous example of SQL Server should excite the developer community to be able to create more complex Silverlight functionality. A 64-bit Silverlight runtime should allow us to:
  • Use a 64-bit browser processes natively on a 64-bit OS :)
  • Cache a very large amount of data
  • Potentially improver the performance of the Silverlight control (load more elements into memory)
  • Create local "analysis cubes" similar to what Microsoft Office Excel PowerPivot does with x64 bit hardware
  • Increase the size of data structures for application functionality (i.e., connection pooling)
  • Ability for Silverlight to work together with other 64-bit applications together
 
64-bit Silverlight and Mobile Devices 
 
Also a lot of mobile devices like phones and tablets use RAM/ROM differently than a computer.  These devices use SD cards, SSDs or "true" RAM as RAM.  In the very near future we will have tablets or phones that come with 128 gig, 512 gig etc. that "share" RAM/ROM/HD space from a single form factor.  You can already see examples of this in Windows Vista/7 with ReadyBoost (where you can use an SD card as RAM).  I think this is where 64-bit Silverlight can make a HUGE difference especially on Windows Phone 7, Microsoft Media Set Top Boxes and Windows 7 CE Tablets (iPad competitors).  In the upcoming years the difference between persisted storage and RAM will be blurred on these devices as the speed of SD cards or SSD drives improves dramatically.

 
Silverlight 64-bit applications will be able to place "all reasonable data" in memory for real-time and offline access.  A great example is to have a statistical application for football that provides real-time business intelligence offline. (pro-football-reference.com web data running in offline Silverlight and used for in-game broadcasting for example)
 
 
 
If developers look at what can be done with a 64-bit architecture by looking at enterprise examples (i.e. SQL Server 64-bit), I think they will as excited as I am about the potential this can unlock.  Remember its more than just "putting more stuff in memory".
  
Posted: Dec 02 2010, 16:54 by Bart Czernicki | Comments (5) RSS comment feed |
  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Filed under: Silverlight | Silverlight 5
Tags:
Social Bookmarks: E-mail | Kick it! | DZone it! | del.icio.us

Creating a ASP.NET MVC HTML Helper for Silverlight

Abstract:  This article covers how to  create a custom ASP.NET MVC HTML Helper that will render the required HTML to host a Silverlight application (XAP file). Some knowledge of ASP.NET MVC is required.

Over the last few weeks I have started investing some time in learning ASP.NET MVC (specifically ASP.NET MVC 2).  This has nothing with the ongoing "Silverlight is dead" debate and I actually started a deep dive into the technology back in August 2010.  I think that ASP.NET MVC is very important for Silverlight developers to learn (more on this in another blog post), because of its obvious positioning in Microsoft's HTML5 tooling investments (more on that in MIX 2011).

Intro to HTML Helpers

HTML Helpers have the following qualities:

  • Usually implemented via extension methods
  • Usually implemented part of a static class
  • In .NET 4.0/C# 4.0 utilize optional parameters to minimize the initialization signature
  • Used inline with HTML in ASP.NET MVC Views to create dynamic content, while minimizing the code written and maintained
Basically an HTML helper is a extension method that takes some parameters and renders HTML.  In ASP.NET MVC you have complete control over the rendering of the HTML in your Views.  If you are an ASP.NET developer you can think of it as having the ability to dictate the exact HTML/Javascript that gets surfaced when you drag over any ASP.NET server control.  For example, if you drag over an ASP.NET button server control, ASP.NET handles how that control is rendered on the page.  Of course in ASP.NET you could override the rendering from the server, however it was a major pain.
 
HTML Helpers in ASP.NET MVC are there to minimize how much code you need to write.  For example, instead of having to write 100 lines of HTML every time there is an input form.  You could create an HTML Helper that does this for you.  This minimizes the code, improves maintenance of your code and abstracts that component into its own SRP (single responsibility principle) method.
 
ASP.NET MVC versions 1 through 3 include a ton of HTML Helpers.  These helpers include basic methods for rendering simple HTML like a text box to more complex helpers.  If you download the ASP.NET MVC 3 source code, you will see a lot of very complex HTML Helpers.  These HTML helpers can render complex HTML with interactive HTML.  For example, my companion site (http://www.silverlightbusinessintelligence.com) for my Silverlight business intelligence book utilizes the Twitter HTML helper that renders my tweets in a nice interactive HTML component with JavaScript that makes the appropriate web service requests.  Some of the advanced HTML helpers include: Facebook, Twitter, video etc.  The beauty of this is that in order to utilize this component I just had to reference it using one line of code.
 
 
Creating a Silverlight HTML Helper
 
In order to host a Silverlight application (XAP file) you need to create the following HTML at a minimum  (if you want error handling you will need additional JavaScript):

 
In order to create an ASP.NET MVC HTML Helper to host Silverlight we simply need to create a extension method that renders the HTML shown above.  When creating an HTML helper for an HTML component, you should analyze which parameters would be helpful to make the HTML more dynamic.  For example, for the Silverlight helper we could potentially have the following parameters:
  • URI location of the Silverlight XAP file
  • Silverlight minimum runtime version (minRuntimeVersion parameter)
  • Width and height dimensions of the Silverlight div tag
  • Silverlight application initialization parameters
  • Provide a dynamic name for the onError JavaScript method
In addition to the flexibility, the HTML Helper should provide a simple method signature.  For example, if I just want to provide the location of the Silverlight XAP file; why would I want to pass in all of these additional method parameters.  This is ideal for using the new .NET 4.0/C# 4.0 optional parameter syntax.
 
The rest of the HTML Helper is very simple; combining the method parameters with the static HTML div tag and rendering the content.  You are essentially building a .NET string that contains HTML content.   This can be done several ways (as shown below).  I used the string.Format method (because it uses StringBuilder for performance behind the scenes) and optionally for a cleaner "non-string" method you can use LINQ to XML to create the HTML string all in C#.
 
Creating the HTML using string.Format 

 
Creating the HTML using LINQ to XML

The final piece of the HTML Helper is to return an HTMLString object (which overrides some string method implementations).  The HTMLString object is used by most ASP.NET MVC helpers (considered a best practice).
 
Using the Silverlight HTML Helper
 
Using the Silverlight HTML Helper in an ASP.NET MVC View is incredibly simple.  Using the C# inline code in the view, all that needs to happen is to execute the HTML Helper method.  In the example below, I pass in the URI of the Silverlight XAP file and two optional height & width parameters.
 
If you are not familiar with C# optional parameters, notice the syntax below.  "objectContainerWidth: ...".  We can specify the optional parameter we want to pass into the method and the value.  If the HTML Helper had 20 parameters the syntax of this method would be very bloated.  However, optional parameters make the syntax very terse. 
 
 
 
Where and Why Would you want to do this?
 
There are a couple great uses of this Silverlight HTML Helper.  The first use is to simply host Silverlight applications in ASP.NET MVC.  If you create a "new Silverlight Project" and host it in a ASP.NET MVC project, you don't get a good hosting environment.  What actually happens is that you get an aspx page that is completely outside ASP.NET MVC views. The screen shot below shows the SilverlightApplication2TestPage.aspx page that is a classic ASP.NET page that does not go through the ASP.NET MVC runtime.  This is obviously not helpful if you want to host Silverlight in ASP.NET MVC.
 
 
Another great use of this Silverlight HTML Helper is to create dynamic web sites that include a lot of Silverlight content.  My companion site for my Silverlight BI books had a requirement of this.  I have over 60 Silverlight demos I needed to host on the web with different Silverlight versions.  If you navigate to http://silverlightbusinessintelligence.com/Demos you can see the Silverlight HTML helper in action.  
 
I wanted to keep the Views dynamic.  Therefore, using the Silverlight HTML Helper I can pull all of the values from a SQL Server table and dynamically create the views for each respective demo.  All those optional parameters for the Silverlight HTML helper come from the database.
 
Sample of some of my Silverlight HTML Helper Parameters stored in a database table 
 
 
Source Code
Attached is the cs file for the Silverlight HTML Helper.  Feel free to extend the HTML Helper as you wish.  I have omitted error checking and rendering the additional JavaScript files.  This could be added simply.   I did this on purpose, because right now ASP.NET MVC does not allow you to render JavaScript in the appropriate places.  You could create two separate HTML Helpers (one for the Silverlight XAP file and one for the JavaScript).  This would allow you to place the Silverlight JavaScript file with all your other js files on the web page.
 
Posted: Nov 16 2010, 08:52 by Bart Czernicki | Comments (0) RSS comment feed |
  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Filed under: ASP.NET MVC | Silverlight
Tags:
Social Bookmarks: E-mail | Kick it! | DZone it! | del.icio.us