Skip to main content

Xaml Meets ASP.NET MVC – Create databound visualizations with Xaml + ASP.NET MVC using XamlAsyncController

For some time, I was thinking about leveraging the power of Xaml to create databound images/visualizations in web applications, and did a quick POC implementation of the same. Here is the demonstration. We’ll start from the final output, and see how quickly you can render a Xaml control as an image from your ASP.NET MVC Controller – after binding that to your ViewData or view model.

[+] Related Code: Go get it, from codeplex

Generating data bound images using Xaml

The gist of this article is how you can create dynamic or data bound images from Xaml user control. When I mention dynamic or data bound image - what I mean is, taking a snapshot of your Xaml user controls that are bound to the view data or view model. So that, your images will be generated based on the view data/model.

How to do this? The related source code (find the link above) contains a XamlAsyncController implementation, to make the whole task easier in ASP.NET MVC.

Let us go through an example - If you see, there are two images in the below web page – and in this case, both images are generated from Xaml files.

image

The Views\Home\Index.aspx view that generates the above page is as below.

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Home Page
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h2><%: ViewData["Message"] %></h2>
    <image src="/Home/ShowMessage" />
    <h2>A simple dashboard</h2>
     <image src="/Dashboard/Chart" />

</asp:Content>

How to render a Xaml from the Controller?

Now, let us see how you can use XamlAsyncController to implement Xaml image rendering in your own ASP.NET application.

If you see the aspx code above, you may note that the first image is generated by the action ShowMessage in Home Controller, and the second image is generated from the Chart action in Dashboard controller. To render a Xaml Usercontrol as an image, basically you need to do two things.

1 – Inherit your Controller from XamlAsyncController, and add an Async action for serving the image

You need to create a reference from your ASP.NET MVC to the MvcXamlController.Lib (included in the download below).

For example, let us see how the ShowMessage action is implemented for serving the image. If you look at the HomeController, you can see that the HomeController is inherited from XamlAsyncController, a custom abstract controller I implemented, inheriting from AsyncController, that’s already there in ASP.NET MVC 2 (Read about using Asynchronous Controller if you are not familiar with Asynchronous controllers). You just call StartRendering() method in your ShowMessageAsync, and return XamlView() in your ShowMessageCompleted.

    [HandleError]
    public class HomeController : XamlAsyncController
    {
        public void ShowMessageAsync() 
        {
            ViewData["Message"] = "Welcome from Xaml in MVC";
            StartRendering();
        }

        public ActionResult ShowMessageCompleted()
        {
            return XamlView();
        }
    } 
   

2 – Add your Xaml file to the path /Visualizations/{Controller}/{Action}.xaml

Once you have your controller’s action to serve an image as above, the next step is to add a Xaml file. Before that, you should  It should be in the path /Visualizations/{Controller}/{Action}.xaml (This is synonymous to adding a View in the path /Views/{Controller}/{Action}.aspx

SideNote: This is going to be a bit tricky. First thing is, you need to add references to WindowsBase, PresentationUI, PresentationCore dlls to your ASP.NET MVC project, which is already done in the demo project. Then you need to manually copy a xaml file from some where else to the required path, as Visual Studio ‘Add New Item’ dialog box won’t display xaml files when you try to add a new item inside your ASP.NET MVC Project.

See how I’m placing the ShowMessage.xaml, under the Visualizations\Home folder.

image

And you are done. XamlAsyncController is smart enough to fetch the xaml file from the location /Visualizations/{Controller}/{Action}.xaml by convention, and render it as an image. And of course, in your Xaml, you can bind to the ViewData. Let us have a look into our ShowMessage.xaml

<UserControl x:Class="MvcXamlController.Demo.Visualizations.Home.ShowMessage"
        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"
        Margin="1" Padding="2" Width="300" Height="60"
        mc:Ignorable="d">
    <Grid>
        <Border BorderBrush="Gray" BorderThickness="2"  
                Background="WhiteSmoke" CornerRadius="5" Padding="4">
            <StackPanel>
            <TextBlock Text="I am a WPF control rendered as image"/>
            <TextBlock Text="{Binding Message}"/>
            </StackPanel>
        </Border>
    </Grid>
</UserControl>
And you can find that we are binding to the Message element we pumped into the ViewData, from the controller. This is generating the first image in the rendered html file.

Another Example – A Simple Chart Image

Now, let us see how to create a simple chart in Xaml, based on your viewmodel data?.

Let us add a new Controller to our ASP.NET MVC App, DashboardController.cs. And we have an async action, named Chart. See that we are using an overload of StartRendering to pass some dummy view model data.

public class DashboardController : XamlAsyncController
    {
        
        public void ChartAsync()
        {
            var items=new List<Item>()
            {
                new Item{Name="Windows7", Region="US", SalesNo=100 },
                new Item{Name="Office2010", Region="US", SalesNo=70 },
                new Item{Name="Sharepoint", Region="US", SalesNo=20 },
            };
           
            StartRendering(viewModel:items);
        }

        public ActionResult ChartCompleted()
        {
            return XamlView();   
        }

     }

And yes, we have our Chart.xaml in the location /Visualizations/Dashboard/Chart.xaml – and here is how it looks like.

    <UserControl x:Class="MvcXamlController.Demo.Visualizations.Dashboard.Chart"
        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"
        Width="400"
        Height="200"
        mc:Ignorable="d">
    
 
    <Grid Background="WhiteSmoke">
        
        <ItemsControl ItemsSource="{Binding .}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                <StackPanel HorizontalAlignment="Left">
                    <TextBlock Text="{Binding Name}" 
                               HorizontalAlignment="Left" Height="24" />
                    <Rectangle HorizontalAlignment="Left" 
                               Width="{Binding SalesNo}" Height="10" Fill="Red"/>
                </StackPanel>
            </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </Grid>
</UserControl>

More Thoughts And Going Forward

We havn’t yet explored the actual implementation of my XamlAsyncController, and that is for another post. If you are so curios, you can definitely have a look at the source related code.

And remember, this is an experimental implementation, with few hacks here and there. There are various cases that needs to be addressed – for example, the rendering will not be proper for elements that has some loading animation etc. Also, I havn’t yet run this outside the ASP.NET Development server, and hasn’t really done any performance analysis.  How ever, I think this is a good start towards exploring how we can leverage Xaml in web applications.

[Note: Read Part II about this]

Laurent Bugnion also blogged about some of his thoughts about rendering Xaml from server side, how ever I still need to have a look into his code.

Also, Keep in touch :) follow me in twitter or subscribe to this blog.

Interested in ASP.NET MVC? Read my articles about creating a custom view engine for ASP.NET MVC or using Duck Typed View Models in ASP.NET MVC

Popular posts from this blog

Top 7 Coding Standards & Guideline Documents For C#/.NET Developers

Some time back, I collated a list of 7 Must Read, Free EBooks for .NET Developers, and a lot of people found it useful. So, I thought about putting together a list of Coding Standard guidelines/checklists for .NET /C# developers as well.As you may already know, it is easy to come up with a document - the key is in implementing these standards in your organization, through methods like internal trainings, Peer Reviews, Check in policies, Automated code review tools etc. You can have a look at FxCop and/or StyleCop for automating the review process to some extent, and can customize the rules based on your requirements.Anyway, here is a list of some good Coding Standard Documents. They are useful not just from a review perspective - going through these documents can definitely help you and me to iron out few hidden glitches we might have in the programming portion of our brain. So, here we go, the listing is not in any specific order.1 – IDesign C# Coding StandardsIDesign C# coding stand…

Hack Raspberry Pi – How To Build Apps In C#, WinForms and ASP.NET Using Mono In Pi

Recently I was doing a bit of R&D related to finding a viable, low cost platform for client nodes. Obviously, I came across Raspberry Pi, and found the same extremely interesting. Now, the missing piece of the puzzle was how to get going using C# and .NET in the Pi. C# is a great language, and there are a lot of C# developers out there in the wild who are interested in the Pi.In this article, I’ll just document my findings so far, and will explain how develop using C# leveraging Mono in a Raspberry Pi. Also, we’ll see how to write few minimal Windows Forms & ASP.NET applications in the Pie as well.Step 1: What is Raspberry Pi?Raspberry Pi is an ARM/Linux box for just ~ $30. It was introduced with a vision to teach basic computer science in schools. How ever, it got a lot of attention from hackers all around the world, as it is an awesome low cost platform to hack and experiment cool ideas as Pi is almost a full fledged computer.  More About R-Pi From Wikipedia.The Raspberry Pi

5 Awesome Learning Resources For Programmers (To help you and your kids to grow the geek neurons)

Happy New Year, this is my first post in 2012. I’ll be sharing few awesome learning resources I’ve bookmarked, and will be pointing out some specific computer/programming related courses I've found interesting from these resources.Also, thought about saving this blog post for my kids as well - instead of investing in these Child education schemes (though they are too small as of today, 2 years and 60 days respectively ). Anyway, personally my new year resolution is to see as much videos from this course collections (assuming I can find some free time in between my regular job && changing my babies diapers).1 – Khan AcademyAs I mentioned some time back, you and your kids are missing some thing huge if you havn’t heard about Khan Academy.  It is an awesome learning resource, especially if you want to re-visit your basics in Math, Science etc.With a library of over 2,600 videos covering everything from arithmetic to physics, finance, and history and 268 practice exercises, th…