Thursday, March 14, 2013

Getting started using Silverlight 4 in an ASP.NET MVC 3 application and accessing data with JSON

ASP.NET MVC is such a great platform for web applications because it makes it so easy to tackle many different integration challenges. You need to add a Silverlight application to your web site and send it some JSON data to work with? No sweat. Stumped on where to start? Well, you are in the right place. Let's make it happen.
In honor of Mix 11 kicking off tomorrow, we will imagine that we are tasked with the need to build a web application that renders a list of MIX 11 sessions and allows the video of each session to be viewed in a browser (of course we don't really need to build such a solution because the live.visitmix.com site already provides that content for us...but, for the sake of being hypothetical). What a perfect reason to use Silverlight in a MVC 3 web application! We will work through rendering a Silverlight application in an MVC 3 view and populate it with a list of MIX 11 session names delivered in JSON from our MVC application. We will not be addressing how to render video in Silverlight in this post though, so if you want to take the Silverlight portion further you may want to check out www.iwantmysilverlight.com (is anyone actually rockin' that domain name?).
As always, we begin with a blank ASP.NET MVC 3 Web Application project (named Website) using an Empty project template and target the Razor view engine. Once the solution is created with the MVC project we will add a new Silverlight Application project to the solution.
New Project
To start this post I didn't have the Silverlight Developer Tools installed on my workstation running Visual Studio 2010 (Service Pack 1), so I encountered the following dialog upon clicking OK from the add project dialog:
No Silverlight Developer Tools installed
Clicking on the link in this dialog opened up a browser and downloaded the installer. After running the installer, restarting Visual Studio 2010, and attempting to add the new Silverlight Application project a second time I found success. The Silverlight Application project prompts you with an options dialog:
Silverlight Application options
I unchecked the options for "Add a test page that references the application" and "Enable Silverlight debugging (disables javascript debugging)" and clicked OK. Once the Silverlight Application project was added my solution tree looked like so:
Solution Explorer
With the projects in place we are ready to start adding some code. First up, we need to add a controller and a view that will render a page with our Silverlight application on it. Lets add a good old HomeController with a Index action method. Our HomeController.cs file will contain:
using System.Web.Mvc;
namespace Website.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }
}
Our Views/Home/Index.cshtml file will contain:
@{
    ViewBag.Title = "Index";
}
<h1>Our Silverlight application demo</h1>
If we do a quick F5 to check out our page we are presented with the following dialog:
Page debugging
I clicked No...nothing broke or melted. The page showed up with our h1 tag screaming at us in huge bold font. Now lets see about getting our Silverlight in that view. The SilverlightApplication project comes pre-loaded with a MainPage.xaml file. If we open that file in Visual Studio 2010 it will give us a split window with a Design view at the top and a XAML view at the bottom. From here we can use the Toolbox window to add some UX stuff. If you don't have this displayed because you build rad ASP.NET MVC web applications without that crazy design view stuff or you recently read Scott Hanselman's blog post on how to Simplify your Visual Studio 2010 Toolbar and Free Your Mind and turned off everything under the sun then you can get it back by hitting Ctrl+Alt+X or navigating to View -> Toolbox from the main menu.
The default content for the MainPage.xaml file looks like:
<UserControl x:Class="SilverlightApplication.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot" Background="White">

    </Grid>
</UserControl>
We will drag and drop a TextBlock and set the Text attribute to "Session Videos". This will add the following XAML tag to the <Grid> tag:
<TextBlock Height="23" HorizontalAlignment="Left" Margin="12,12,0,0" 
    Name="textBlock1" Text="Session Videos" VerticalAlignment="Top" />
Our MainPage.xaml file will end up looking like so:
<UserControl x:Class="SilverlightApplication.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot" Background="White">
        <TextBlock Height="23" HorizontalAlignment="Left" Margin="12,12,0,0" 
            Name="textBlock1" Text="Session Videos" VerticalAlignment="Top" />
    </Grid>
</UserControl>
We can preview this by right clicking on the SilverlightApplication project in the Solution Explorer and selecting "View in Browser" (or hitting Ctrl+Shift+W). With our browser open we can see our Silverlight running, displaying the "Session Videos" text. If we right click on the window content we get the "Silverlight" context menu:
Silverlight right click
Now lets get this puppy running in our view. Guess what! By adding the SilverlightApplication to our solution after we added the ASP.NET MVC 3 Web Application we were presented with the "Host the Silverlight application in a new or existing Web site in the solution" option pre-checked and our project named Website pre-selected in the drop down. Since we left that option checked and the Website project selected, when we did a build of our Website application (the F5 we did earlier to preview it) the SilverlightApplication.xap file was created and deployed to a ClientBin directory in our MVC project.
Solution Tree 2
We can add an <object> tag to our Index.cshtml view file to render our Silverlight application within the view. The code for our view file will be:
@{
    ViewBag.Title = "Index";
}
<h1>Our Silverlight application demo</h1>
<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="400" height="300">
    <param name="source" value="ClientBin/SilverlightApplication.xap"/>
    <param name="background" value="red" />
    <param name="minRuntimeVersion" value="4.0.60129.0" />
    <param name="autoUpgrade" value="true" />
    <a href="http://www.microsoft.com/getsilverlight/get-started/install/" style="text-decoration:none">
    <img src="http://go.microsoft.com/fwlink/?LinkId=161376" 
        alt="Get Microsoft Silverlight" style="border-style:none"/>
    </a>
</object>
If we do another F5 we will see our page with our Silverlight application included.
Silverlight application in page
So we have some Silverlight running in an ASP.NET MVC 3 web application. Coolio! Now lets see what we can do to populate some data in that Silverlight. We will create a new action method in our HomeController.cs file named SessionVideoList that will return a JsonResult that will contain a list of session names we can use in our Silverlight application. We can create a List<string> of some session names and return it as a Json object. Our updated controller code:
using System.Collections.Generic;
using System.Web.Mvc;
namespace Website.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public JsonResult SessionVideoList()
        {
            var sessionVideos = new List<string> { "Keynote", "Silverlight Boot Camp", 
                "Fun with ASP.NET MVC 3 and MEF", "ASP.NET MVC 3 @:The Time is Now" };
            return Json(sessionVideos, JsonRequestBehavior.AllowGet);
        }
    }
}
We also need to add a route to our route table to be able to call this action method. An update to our Global.asax.cs file will look like so:
using System.Web.Mvc;
using System.Web.Routing;
namespace Website
{
    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "SessionVideoList",
                "SessionVideoList",
                new { controller = "Home", action = "SessionVideoList" }
            );

            routes.MapRoute(
                "Default",
                "{controller}/{action}/{id}",
                new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }
    }
}
Our MVC application is set up to provide data for our Silverlight application to consume. Our final step involves adding the code to our Silverlight application to hit our MVC route and process the data returned. To keep it simple, we will modify our MainPage.xaml file to enlarge the TextBlock element so that it fills the Silverlight application and use that to render our list of session names. We can add a Width attribute and change the existing Height attribute on our <TextBlock> tag:
<TextBlock Height="276" HorizontalAlignment="Left" Margin="12,12,0,0" 
    Name="textBlock1" Text="Session Videos" VerticalAlignment="Top" Width="376" />
This will ensure that the rendering of our TextBlock will be big enough to display a handful of lines of text. From here we need to open up our MainPage.xaml.cs file and add some code to call our MVC action url and process the response stream content. In the constructor for MainPage we will add an instantiation of a Uri object, a WebClient object, and do an async read of the Uri object with the WebClient object. We will also add a private method named openReadCompleted that we will add to the WebClient.OpenReadCompleted event handler. This method will handle processing the JSON data from the response stream and populating our TextBlock element. We are going to use System.Json to process the JSON data which requires us to add a reference to the .NET assembly in our SilverlightApplication project.
Add reference
Lets take a look at the code in the file as a whole and then we will go over the parts.
using System;
using System.Json;
using System.Net;
namespace SilverlightApplication
{
    public partial class MainPage
    {
        public MainPage()
        {
            InitializeComponent();
            var serviceUri = new Uri("/SessionVideoList", UriKind.Relative);
            var webClient = new WebClient();
            webClient.OpenReadCompleted += openReadCompleted;
            webClient.OpenReadAsync(serviceUri);
        }

        private void openReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if (e.Error != null) return;
            var sessions = (JsonArray)JsonValue.Load(e.Result);
            foreach (string sessionName in sessions)
            {
                this.textBlock1.Text += string.Format("{0}{1}", Environment.NewLine, sessionName);
            }
        }
    }
}
In the MainPage constructor we instantiate a new Uri object. We pass in a relative uri string that represents the route to our action method. We need to include the UriKind argument (value of UriKind.Relative) in this constructor in order for our Silverlight application to correctly resolve the path when rendered in our MVC application. Then we instantiate our WebClient, add the event handler, and do our asynchronous read.
public MainPage()
{
    InitializeComponent();
    var serviceUri = new Uri("/SessionVideoList", UriKind.Relative);
    var webClient = new WebClient();
    webClient.OpenReadCompleted += openReadCompleted;
    webClient.OpenReadAsync(serviceUri);
}
In our openReadCompleted method we do a simple check for errors and return without taking any action if we encounter an error. From there we use the JsonValue.Load method to deserialize the response stream data that is stored in the OpenReadCompletedEventArgs.Result property and cast it to a JsonArray object. This is based on knowing the structure of the JSON objects we are dealing with...there are other JSON object types that can be used here. More info can be found on MSDN. Finally, we iterate through the JsonArray object and add the session name to a new line in our TextBlock element.
private void openReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
    if (e.Error != null) return;
    var sessions = (JsonArray)JsonValue.Load(e.Result);
    foreach (string sessionName in sessions)
    {
        this.textBlock1.Text += string.Format("{0}{1}", Environment.NewLine, sessionName);
    }
}
If we go back to our MVC project and do an F5 we will see our Silverlight application rendered in our page and populated with the JSON data from our SessionVideoList action method.
Final page view
And voilĂ , we have a starting point for an integration between ASP.NET MVC 3 and a Silverlight 4 application. The rest is easy right? Simply build a robust Silverlight application solution and update the MVC application to return more complex JSON data. Knock that out in a day or two? I think I'll spend the next day or two sitting at home watching the Mix 11 session online and toss some sadfaces out as I watch all the Twitter chatter from all of those out in Vegas having fun instead. Oh, and answer reader comments of course!

No comments: