LightSwitch hacking challenge: fix the NullReferenceException: sample

Yesterday I came across a rather interesting NullReferenceException, which occurred right after I set a local screen property to a particular value (non-null) then (in the very next line of code) retrieved that property to do some additional work.

Fixing it is easy ONCE you know what causes this odd behavior.  I can promise you that there’s not one single written resource available on the web about this, making it a very blogworthy subject.  Instead of going straight to the explanatory post though, I thought some readers would enjoy a riddle first (I certainly would), hence the hacking challenge.

To avoid confusion over the fact that I’m using a fancy user control or showing a modal dialog, I’ve uploaded a working code sample. You can download it, or just study the sources online.  In the sample, I’ve reduced the fancy control to an absolute minimum, to avoid any confusion (for example: that the NRE is caused by the fanciness of the control). I’ve also rewritten the original problem a bit to avoid confusion about the modal dialog or use of an entity.



I added an additional hint in the sample.  To see this hint, simple open the second screen (in the application/code).


Good luck, and keep rocking LS!

LightSwitch hacking challenge: fix the NullReferenceException

I’ve been posting so much about the awesome LightSwitch HTML client lately (have you seen the second season of Leading LightSwitch by the way?) that you might get the impression that I’m now an HTML-Hipster exclusively…

No way, and as a tribute to my love to the strongly typed world (also just because it’s really cool) I’m going to challenge your LightSwitch haxpert level with a coding riddle…

I have a normal LightSwitch screen, that has a local property (from Screen Designer > Add data item > Local property: UserRegistration(Entity) ) and a fancy custom user control.  From the screen’ Created method, I’m trying to bind an event handler to an event on this fancy custom user control that is supposed to instantiate the local UserRegistration property, then show a modal popup.  Nothing extraordinary, one would think when looking at the code:

This code actually throws a NullReferenceException at line 15 (much to my own initial surprise)…  I verified this by putting up a breakpoint, and indeed, ‘this.NewUserRegistration’ returns null even though we just assigned the return value of the AddNew method on line 14!!

Your mission, should you choose to accept it: explain why, and propose a fix.  The rules of the challenge are simple: the first one to post the correct answer wins, he/she doesn’t actually win anything (I’m completely broke after giving away $10.000 last month), and you are excluded from entering the competition if your name is Matt Evans, Huy Nguyen, … ( or if you share a whiteboard with any of these guys).

As always, should any member of your team be caught or killed, the Secretary will disavow all knowledge of your actions.

Keep rocking LS!

#LightSwitch and #Syncfusion: simply beautiful applications ($10.000 April raffle!)

With all the blog posts about the new LightSwitch HTML client, it’s easy to lose track of the continued investments in the Silverlight client and the server tier…

One minute summary

Today, this blog post will teach you what you can create by combining 30 minutes of your time with your existing LightSwitch skills, a little ASP.Net Web API creation, some Nuget-for-beginners and custom Silverlight controls to add a dashboard to a LightSwitch application.

Or, because a picture says a thousand words: today we’re going to create this (click-to-enlarge):

LightSwitch & syncfusion: deliver simply beautiful applications

Or, because a sample says more than a thousand pictures: <Download link coming soon> .

Ten minute summary


To follow this guide, you’ll need:

1. Creating reports on the server

Instead of dragging all records over the wire, we’re going to access the ApplicationServerContext directly on the server, aggregate and transform the data there, then send the summary back.

You’ll know why the latter approach is preferred once you pay for your own Azure bills. :p

Hit the “Toggle View” button in solution explorer so that the LightSwitch application is in File View.  Then, right-click on the server project > Add a folder > Name:”Controllers”.

Next, right-click that new folder and choose to Add New Item… > Web API Controller Class > Name:TopRegionsController.cs  (If you are unfamiliar with ASP.Net Web API, you can skim through this tutorial.)

Before actually implementing the controller, we’ll configure the server for these new controllers.  Right-click the project > Add New Item > Global Application Class:

using System;
using System.Web.Http;
using System.Web.Routing;

namespace LightSwitchApplication
    public class Global : System.Web.HttpApplication
        protected void Application_Start(object sender, EventArgs e)

               name: "ReportsApi",
               routeTemplate: "reports/{controller}"


Back to the controller, where we’ll implement the GET command:

using System;
using System.Linq;
using System.Web.Http;
using Microsoft.LightSwitch; //1.

namespace LightSwitchApplication
    public class TopRegionsController : ApiController
        // GET api/
        public object Get()
            using (ServerApplicationContext context = ServerApplicationContext.CreateContext()) //2.
                var query = context.DataWorkspace.NorthwindData
                    .Where(o => o.ShipRegion != null)
                        o => o.ShipRegion) //3.
                        g => new //4.
                            Label = g.Key,
                            Value = g.Count()
                        .Execute() //5.
                        .OrderByDescending(g => g.Value)
                return query;

Some code highlights:

  1. Don’t forget to add the using statement to bring the Microsoft.LightSwitch namespace into scope.
  2. This is the powerfull ServerApplicationContext.  An IDisposable  , type-safe object that represents your LightSwitch application on the middle tier.  You can access user information, the Dataworkspace, …
  3. Pro tip! This GroupBy method (only available after step 1.) is something you can’t do over OData.  The grouping itself is done directly in the data source, if your data source supports it.  SQL obviously does.  (In other words, calling this GroupBy method will cause your SQL query to contain a GROUP BY statement :-))
  4. We’re gathering the results in an anonymous type.  Bluntly put: why bother?
  5. Don’t forget to execute the query!

Et voila, the server is done.  One quick way to test if you have done everything correctly, is to press F5 to start debugging, then navigate your browser or fiddler to http://localhost:<assigned port number>/reports/TopRegions .

Image 037

2. Fetching the data from the client

Add an empty Screen to the LightSwitch (Silverlight: in or out-of-browser) application called “DashBoards”, using the “List and Details” screen template but leaving Screen Data blank.

From the Screen Designer, hit the “Write Code” button and choose “DashBoards_Activated”.  This will generate a method stub for you, where you can add some code to match the following outline snippet:

using Microsoft.LightSwitch.Presentation.Extensions;
using System.ComponentModel;
namespace LightSwitchApplication
    public partial class Dashboards : INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;

        public object TopRegions { get; set; }

        partial void Dashboards_Activated()
            //What comes here? :-s

As you can see, we’ve added a local property called “TopRegions”, of type object.  Because this can’t be done from the screen designer, we’ll have to notify when the property changes ourselves too.   The big question is what we should fill in as method body.  How do we find out what the server address is, perform the HTTP GET call asynchronously, and handle exceptions?

Luckily, when there’s a tough technical challenge, you can often hire “a developer in a box” (as I call it), or “Paul Van Bladel in a Nuget package” (as normal people would refer to it).

Open the package-manager console (if you don’t know what that is: View>Other Windows>Package Manager Console), make sure the LightSwitchApplication.Client project is selected as Default Project, then type:

Image 038

Pro tip!: after typing “inst” or “thelight”, you can press tab and have the rest of the command auto-completed.

This package will install some utility extension methods, which we can call from our method body (and effectively reduce this article from 14 pages to just 4):

        partial void Dashboards_Activated()
                (exception, result) =>
                    if (exception != null)
                        this.ShowMessageBox("There was an error while fetching the data.");

                        Microsoft.LightSwitch.Threading.Dispatchers.Main.BeginInvoke(() => //3.
                                TopRegions = result;
                                this.PropertyChanged(this, new PropertyChangedEventArgs("TopRegions"));  

Some code highlights:

  1. StartWebApiRequest is one of the methods added by the Nuget package, doing all the heavy lifting.  Thanks Paul!  We call the method and (by using the generic method signature) ask to cast the return value (a JSON list of anonymously typed stuff) to an array of MySyncfusionControls.DataViewModel (We’ll create this class in a second, by the way).  In a loosely typed language like JavaScript, or in an un-sandboxed environment like WPF, you could get away with not casting the return value (ie: casting it to object) but you’ll run into security problems trying to bind to it from the user controls later.  (Silverlight is very harsh on reflection-lovers, meaning safer for the end-user).
  2. This is the last part of the URI by which the server is exposing it’s endpoint, determined by the routing we set up in the Global.asax file, and the name of the controller.
  3. We’re currently on the logical thread.  This event will be handled on the UI thread.  Read about the incredible dual dispatcher objects in LightSwitch… O… wait…  //TODO: can someone blog about dual dispatcher objects?

 3. Creating the user control

To visualize the report to the user, you need some kick-ass controls.  LightSwitch Controls come in three flavors:

We’ll take the latter route: right-click on the solution > Add New Project > Silverlight 5 Class Library > Name:MySyncfusionControls

Replace the default class1 with:

    public class DataItemViewModel
        public string Label { get; set; }
        public double Value { get; set; }

This is the DTO we’ll use, duly note that the names of the two properties (“Label” and “Value”) match the one used in our anonymous type used to return the data from the server.

Goody, now for the actual control.  Add references to Syncfusion.Chart.Silverlight, then right-click the project > Add New Item > Silverlight User Control > Name:ColumnChartWrapper.  Replace the XAML with:

<UserControl x:Class="MySyncfusionControls.ColumnChartWrapper"
    d:DesignHeight="300" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot" Background="White">
        <syncfusion:Chart Margin="10" Name="Chart1" MinHeight="300" MaxHeight="450" MinWidth="600" MaxWidth="1000" Background="White">
            <syncfusion:ChartArea BorderThickness="0">
                    <TextBlock FontSize="20" Text="{Binding DisplayName}" />
                    <!-- 1. -->
                    <syncfusion:ChartAxis RangePadding="Normal" ValueType="String" Interval="1"/>
                    <syncfusion:ChartAxis RangePadding="Normal" IsAutoSetRange="True"/>
                <syncfusion:ChartSeries x:Name="series" 
                    DataSource="{Binding Value.TopRegions}" 

                    Type="Column" StrokeThickness="0"
                    EnableAnimation="True" AnimateOption="Rotate" AnimateOneByOne="True" AnimationDuration="00:00:10"
                    <!-- 2. -->
                        <syncfusion:ChartAdornmentInfo x:Name="Adornments_pot" Visible="True" SegmentLabelFormat="0.0"
                                                                   VerticalAlignment="Bottom" >
                                        <TextBlock  TextWrapping="Wrap" Text="{Binding}" FontSize="20" Foreground="White" HorizontalAlignment="Right" VerticalAlignment="Bottom">

Some XAML highlights:

  1. Bind to the DisplayName (which we’ll set in a minute)
  2. Well…
    • DataSource is set to Value.TopRegions.  The datacontext is the ContentItem that we’re about to drag on the screen designer.  This ContentItem has a property “Value”, which we’ll bind to the “Screen” in the screen designer.  This screen has a property called “TopRegions”, which we added in the code earlier.
    • BindingPathX and BindingPathsY are set to “Label” and “Value”, which are the names of the properties on or DTO that we created earlier.  This is where you would run into troubles if you didn’t cast the JSON result to a strongly typed object in a strongly typed language in a sandboxed environment.
    • Animations: you need lots of them and Syncfusion has some truly beautiful animations.  For demos, always include “EnableAnimation=”True” AnimateOption=”Rotate” AnimateOneByOne=”True” AnimationDuration=”00:00:10″”, you only get one shot at making a first impression so make sure there’s lots of shinies to catch your audience’s attention .  Pro tip! For production code, removing animations makes customers happier.

4. Finishing the screen

The heavy lifting is over…  So far, we’ve used ASP.Net Web Api and the LightSwitch ApplicationServerContext to gather and expose custom data reports, we’ve used C# code and a Nuget package to get that data to the client, and we created a custom Silverlight control based on one of the 7 billion (more or less) Syncfusion charting controls to visualize that data.

The glue to bind this all together: open the Dashboards screen in the screen designer, and in the middle area, select the main root (labeled “Columns Layout – Dashboard”) > Click on the Add link > New Custom Control. > Add Reference to the MySyncfusionControls library that we created, then > Select ColumnChartWrapper  > Data: Screen (ie: leave the default) > hit OK.

Image 024

Before finishing, select the user control in the screen designer, then in Properties Panel:

  • Set Display Name to “Top Regions”.  Remember the first of the XAML highlights? We’ll bind to this Display Name from the control. 🙂
  • Set Label Position to “None”
  • Set Horizontal Alignment to “Stretch”
  • Set Vertical Alignment to “Stretch”

Also, select the Save button in the screen command bar and in Properties Panel, set Is Visible to false.

Finally, press F5…


Image 026

By the way: the purple column seems to be falling, that’s because I intentionally took the screenshot in the middle of the  “Rotate” loading animation.  – Showoff…

Thirty minute summary

There is no thirty minute summary, so rinse, repeat, try out some other charting controls, …  I added two more custom controls in the sample <Download link coming soon>, (don’t forget the prerequisites) which you could already see in action at the top of this blog post!  

If you like what you saw, feel free to leave a comment and automatically enter the Syncfusion Raffle…

O yes…  “Almost forgot”… (wink, wink, nudge, nudge) <Smooth transition> 

The Syncfusion Raffle!

You might think that this blog post is a little biased towards Syncfusion.  I won’t deny that, but in fact, the opposite is also true: Syncfusion is biased towards my blog readers.  Even more so, they are giving away five Enterprise Syncfusion Essential Studio licences worth $1999 each!

Let that sink in a little…  Syncfusion is giving my blog readers TEN THOUSAND DOLLARS of licences!

To enter the raffle:

  1. Before May 1st 2013: send out a tweet containing the #LightSwitch and #Syncfusion hashtag, and a link to this blog post.  For example: “#LightSwitch and #Syncfusion: simply beautiful applications. ” or “Thousands of dollars worth of #Syncfusion licences thanks to this #LightSwitch blog” or …
  2. Grab the permalink, and post the link to your tweet as a comment to this blog post (make sure you use a valid email address to comment, I need to be able to contact you if you win!)

One entry per person, normal contest rules apply.  If you don’t have twitter, just post the message on your blog, facebook, … 

The winners will be announced on May 1st 2013.

Best of luck, and don’t forget:

Keep rocking LS!

PS: not fan of all those colors?  Don’t worry, the sample <download link coming soon> shows you how add a combo box so you can change your color schema at runtime from “boring grayscale” to “metro” to “acid tripping”… 🙂

Image 039

LightSwitch news RSS: bringing you news from around the world! (

So…. What’s up doc?

Not much.  Reading some blog posts by other LightSwitch community members…

Sweet! Google Reader?

Errr… Haven’t you heared? Google is dead.  (Google reader*)

The easiest way to keep up to date with the other LightSwitch community members is to wait until the end of the month, then read Beth Massi’s Community & Content Rollup.  Unfortunately, there’s two problems with that approach:

Don’t you have your own twitter bot to keep you up to date?

Well yes, to keep myself up to date on a daily bases (I like news as hot as it gets), I turned each interesting “source” into a tweet by my twitter bot using

Unfortunately, this bot had some weird hiccups lately so after an extremely exhausting week I decided to spend a Friday afternoon rethinking my news model…

Naice! Found something fancy?

Well, actually I did.  After signing up for over a dozen awesome, great or plain terrible services, I found a really fancy service and spent a couple of hours getting the result looking clean and crisp.  Unfortunately, after spending those hours I discovered that this particular service only refreshes once every 24 hours.  I ended up settling for Yahoo! pipes, some kind of workflowy editor that seems to have no other use than to combine RSS feeds.

Which in a way, is exactly what I need. 🙂  And the pipes themselves look kind of fancy.

Image 031

So half a blog post to talk about how you wasted your Friday to end up with an RSS feed instead of a twitter bot?


Half a blog post to talk about how I wasted my Friday to end up with an RSS feed in addition to a twitter bot.

That’s nice. Any downsides to this approach?

Well yes…. I got a bit lazy because Y!Pipes doesn’t have a copy&paste option, so now the bot that listens to the “LightSwitch news RSS feed”, doesn’t know the source of each item anymore.  Basically it  just tweets “#LightSwitch news: ….” now instead of tweeting “News by @AuthorTwitterHandle:  …”

Right… Well listen, thanks for blogging. We’ll give you a call…

Wait, there’s more!

  • RSS feeds are easy to plug into your favorite reader.  Or widget, like the new sidebar on my blog!
  • I can share the RSS feed now: .  And if I find any good bloggers (feel free to make suggestions too!) I can simply update the Y!Pipes schema and you get all the new content too!


And… Boring.  

Mostly boring.

So listen man, unless there’s some code goodies to be found in this post, I’ll be on my way.

Ok… Here you go 🙂

namespace RssDomain
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.ServiceModel.DomainServices.Server;
    using System.ServiceModel.Syndication;
    using System.Xml;

    public class LightSwitchNewsItem
        public string Id { get; set; }

        public string Subject { get; set; }

        public string Content { get; set; }

        public string FullArticle { get; set; }

        public DateTime PublishDate { get; set; }

    public class RssDomainService : DomainService

        private static IEnumerable<LightSwitchNewsItem> allItems;

        [Query(IsDefault = true)]
        public IEnumerable GetDefault()
            if (allItems == null)
                string url = @"";
                XmlReader reader = XmlReader.Create(url);
                SyndicationFeed feed = SyndicationFeed.Load(reader);

                allItems = feed.Items.Select(
                               item => new LightSwitchNewsItem
                                       Id = GetId(item),
                                       Subject = item.Title.Text,
                                       Content = item.Summary.Text,
                                       PublishDate = item.PublishDate.DateTime,
                                       FullArticle = GetLink(item)
                               .OrderByDescending(x => x.PublishDate);

            return allItems;


        static int i;

        static string GetId(SyndicationItem item)
            string id = null;
            if (!string.IsNullOrEmpty(item.Id))
                id = item.Id;
            else if ((id = GetLink(item)) == null)
                id = "Unknown  " + (++i).ToString("000");
            return id;


        static string GetLink(SyndicationItem item)
            var link = item.Links.FirstOrDefault();
            if (link != null)
                return link.Uri.ToString();
            return null;

My eyes! I’m not supposed to get ugly code in them!  What is that?

It’s the code you can copy&paste in a RIA domain service, then use it as an external data source in your LightSwitch projects.

Image 030

That is indeed pretty cool! 

Thanks!  But not as cool as Dissociative identity disorder.  But anyways, I’m off.  Cya man, and don’t forget:

Keep rocking LS!

You too!

LightSwitch: technology overview.

February ’13 will be a fun month full of LSL (“LightSwitch Lovin’ – highly addictive”), including a very short high-speed demo at MS Web Cafe, and an intensive evening workout co-hosted by community rock star Paul Van Bladel: “Simple on the outside, rich on the inside“. 

While prepping, I started drawing a bit to try and capture how LightSwitch manages to take a simple idea, and through a simple IDE allows you to create such an impressive ecosystem.

Here’s 3 of my drawings, feedback appreciated!!

A simple idea

A simple idea

In reality (server)

In reality (server)

In reality (client)

In reality (client)

PS: When you’re not counting cursive text, since it represents my random thoughts in between my traditional and formal writing style, this has got to be my shortest blog post ever…

Simple yes or no question: is Silverlight dead?

Looking at the search terms that people enter and happen to result in the outcome of them visiting my blog, I noticed quite some visitors come here hoping to get a simple yes or no answer to their question: “is Silverlight dead 2012”  (or deviations thereof, including “Silverlight vs HTML5” etc).

Although I normally don’t blog about this subject, I can understand the confusion, because I do have quite some posts that would match those keywords, like

With this post, based solely on my own opinion, I wanted to give those people the simple yes or no answer to their question, and here it is:

“Is Silverlight dead 2012?”

Yes, it is.



your target is Joe Blow playing FarmVille on his iPad while watching “[YourCountryHere] got talent”.

And there you have it.  My simple answer.

If you are interested in my reasoning behind that answer…

If your target is regular Joe…

I don’t mean this in any demeaning way.  The business to consumer market is huge, and when the iPhone was first released some people became millionaires by creating a $0.99 Fart-Machine-app for that market.

This market segment is so big that the consumerization of IT pretty much dictates what the next major coding language will be this decennium.  I read an interesting post by Shawn Wildermuth about the current state of Silverlight, stating that it was in fact Steve Jobs who is responsible for what is happening to Silverlight.  When Apple (traditionally more popular in the consumer world than in the business world) launched the iPhone & iPad, and decided that no plugins would work on these platforms, that basically killed Silverlight and Flash in the business to consumer market.

Personally, I also believe this is one of the causes why HTML5 is that much more impressive than it’s predecessor, because the death of browser plugins left a gap that needed to be addressed, causing all parties involved to jump on the HTML5 wagon in high pace.

So my advice if you are going to build an app for the business to consumer market, would be not to use Silverlight.  Some IDEs allow you to write code that runs natively on a broad range of mobile devices, HTML5 is platform independent, … or just take a pick and write a truly awesome native app for a specific platform (iOS, Win8, whatever).  Your market is huge, and by the time the technology you picked has peaked, you’ll have plenty of profit to pay for a rewrite anyways…

If your target is the business…

Then the answer becomes a bit more difficult.  There are pros and there are cons now.  Pros include the fact that in the business world, Windows is traditionally a lot more popular than other operating systems, so you’re not really cutting off a significant slice of your potential market if you would decide to actually use Silverlight.  Pros also include the fact that you might have years of experience building Silverlight apps and thus you’re simply better at it.  From the business’ point of view, this means less money for a more stable product.

Personally, I like the way LightSwitch, that primarily targets small to medium LOB applications, is heading here.  Main client is Silverlight, but there is in fact the ability to  quickly pump out a mobile companion app when cross-platform or going mobile becomes a true requirement, or even to write a custom website all-together.

Whenever I can, if the need arises for a small to medium LOB application, I’ll open up LightSwitch and write them the application that will last at least another 15 years as opposed to the 20 that HTML5 might last them (you don’t think HTML5 is the last stadium in IT evolution, do you?), for a tenth of the time it would take someone else the same application in another technology.

If your target is the enterprise…

If you’re lucky enough, like I am on my day job, to be involved in multi-million enterprise to enterprise applications, then the answer to the question become less difficult again.

HTML5, a logical competitor for Silverlight, might be better in quite a large number of ways.  However, the tooling and experience, isn’t better yet.   This will most likely change in a couple of years, but considering the available Silverlight libraries, both open source and built in-house, experience and tooling, still screams that making the swap today would be deadly to your enterprise organisation, unless there’s a specific requirement for another or multiple platforms for the entire application.

So in summary…

There you have your simple answer, or at least my vision about what the most simple answer to that question is.

Also, and this one comes out of personal frustrations & experiences:  if you read the intro to my LightSwitch Succinctly eBook,  you’ll know that I’m a firm believer of focusing on the end-users needs first.  Don’t read this blog post during office hours, especially not if you are looking for posts to back you up in a discussion with your boss or coworkers about the technology to use for the next project, if the real reason is that you are only looking for an opportunity to play around with another technology.  Feel free to play around during your own time, but when there’s real end-users involved, focus on their needs, and the amount of money they end up paying for what they get.  Let that be the dictating factor of your decisions…  /rant

I’d like to end this post with a saying I hear daily from one of my personal friends and work mates: The answer to any question in IT is, always was and always has been: “It depends”. – Quote Arne Wauters.



Executing an arbitrary method or long-running process on the LightSwitch server: 2. Grab the code.

In the business world that we try to model into bits and bytes, not everything is considered CRUD.  Although LightSwitch excels at creating CRUD-based applications or data services, the need to call an arbitrary method  or long-running process on the server couldn’t really be satisfied without hacks or workarounds…

Until now.

This sample explores the simple but (for unknown reasons) long-running business process of “inviting a friend to check out an application”.  The sample in itself has no other functionality than the ability to invite more users, who would not want to check this out?

Lesson of today: how to grab the code:

  1. Click this link
  2. Follow your intuition

And that’s all there is to it.

Finally, let’s finish off with a small recap of today’s blog post: click here to get the sample.


Keep rocking LS!


PS: I’m trolling, obviously, but I really wanted to publish a link to the code sample ASAP, just because I had it ready and working my way through all blog posts might take a while 😉