Leading LightSwitch

Hello, Mobile

Jan Van der Haegen

Microsoft recently released a second update to Visual Studio 2012, containing a significant enhancement to the LightSwitch experience. In this article, I’ll walk you through one of the most important features that the team has been working on: the ability to create clients in HTML5 that are tailored to the size and UX concept of mobile devices.

The application used as an example, JungleTrek, aids a group of Cambodian researchers in taking quick notes of their sightings and samples as they trek through the jungle; these notes are then processed once they get back. Creating companion applications that will be used to aid with specific tasks both in and outside of the office, taking advantage of the mobility and some other device specific capabilities of these next-generation tablet devices, is one of the primary scenarios that this LightSwitch update targets.

Getting Started: Setting Up the Project and Creating Some Models

To get started, download and install the update. Then, open Visual Studio 2012 and create a new LightSwitch application. There are now two possible LightSwitch projects that you can choose from (not counting those added by the extension toolkit): LightSwitch application or LightSwitch HTML application, both available in C# or Visual Basic .NET.

Adding a new project
Figure 1 Adding a new project

Select the HTML Application in your .NET language of choice, give the project a name and get ready to create a LightSwitch project that leverages C#/VB.NET, JavaScript, JQuery and JQuery Mobile to create rich mobile applications.

The Cambodian researchers will need about three entities to store the data of their sightings, the details and the exact species this sighting is about.

Creating some entities
Figure 2 Creating some entities

These are created using the Entity Designer and you’ll quickly notice that its development experience hasn’t changed since last year, apart from the addition of a couple of productivity improvements (Forward, Back and Related Items buttons) and an added Perspective at the bottom. This Perspective is needed because LightSwitch allows you to write custom code that gets executed when you work with these entities, but before you do, Visual Studio needs to know if this code will run client (JavaScript) or server (.NET) side. In previous versions this didn’t matter because the runtime of the desktop applications were .NET, so code could just be shared as is.

To write some custom initialization logic for the Sighting entity, switch the Perspective to the mobile application and select “Created Event” from the ‘Write Code’ dropdown. A method stub appears that looks like this:

/// <reference path="../GeneratedArtifacts/viewModel.js" />
myapp.Sighting.created = function (entity) {
  // Write code here.
  entity.CreatedOn = new Date();

The first line (the comment that starts with three forward slashes) is a Visual Studio IDE hint to help with IntelliSense. Just add the middle line to instantiate the CreatedOn property to a new Date.

Now that the model tier is ready, we can dive into the new HTML goodies.

Some Simple Screens

The design time experience for the HTML clients is surprisingly like the productivity boost you felt when using LightSwitch to create Silverlight applications. Start by right-clicking on the application, select Add New Screen and a dialog will appear where you can select a template to start the screen creation.

It’s a good practice to create a Home screen recent sightings near the current user, or other personalized data, but this is beyond the scope of this introduction. Instead, we start by creating a “Browse Data” Home screen with no Screen Data attached.

Creating the Home screen
Figure 3 Creating the Home screen

Before adding content to the Home screen, add a second screen and this time select the Add/Edit Details Screen template to create a screen to register new sightings, as in Figure 4.

Creating a New Details screen
Figure 4 Creating a New Details screen

The only thing left to do before we can test the application is to add a button to the Home screen that will navigate the user to the second screen.

Go back to the Home screen, select the Command Bar from the screen designer and click to “Add Button”. From the wizard that appears, you can choose to write custom code or select from one of the many available actions. Which actions are available depend upon your type of screen and the data on the screen. Select the method that will take you to the Register New Sighting screen and leave the default parameter: “passing a new Sighting as an argument”.

Setting up navigation
Figure 5 Setting up navigation

That’s all there is to it! Hit F5 to start debugging and your application will launch, showing a rather empty Home screen. At the bottom there’s a command bar with one command, “Register New Sighting”, and when you click it a modal popup will appear where you can edit the new Sighting. Notice how the “Created On” property is already filled in; which proves that navigating caused a new Sighting entity to be created, causing the JavaScript code that we added earlier to execute correctly.

The register new Sighting popup
Figure 6 The register new Sighting popup

Extending the Screens

In the Screen designer, drag and drop elements to alter their order or group them differently, and use the available drop-down menus to select a different control. When you are done, press Save and refresh the browser. Figure 7 shows a 30 second makeover, including changing the screen from an Edit Dialog to an Edit Screen. By default, all screens to modify data will be created as modal dialogs. If this is not to your liking, select the root control in the Screen Designer control tree, then in Properties Window there’s a checkbox to indicate if the screen should be treated as a screen or as a modal popup.

Changing the screen’s appearance
Figure 7 Changing the screen’s appearance

Before running the application again to see these changes, let’s do one more small modification. Each time the user browses to this screen to register notes of a new sighting, ask the browser the current geographical location and store this as well.

Select the Notes control in the Screen Designer, and then in Properties Window click the Edit Post Render code link. A method stub will be generated for you, where you can use the JavaScript geolocation API to asynchronously request the current’s user’s location from the browser.

/// <reference path="../GeneratedArtifacts/viewModel.js" />
myapp.RegisterNewSighting.Notes_postRender = 
  function (element, contentItem) {
  var screen = contentItem.screen;
  if (!screen.Sighting.LocationLatitude) {
var sighting;
function getLocation(entity) {
  sighting = entity;
  if (navigator.geolocation) {
  } else {
this.successPosition = function (position) {
  sighting.LocationLatitude = position.coords.latitude;
  sighting.LocationLongitude = position.coords.longitude;
this.errorPosition = function () {

Copy and paste the snippet above over the generated method stub, and press F5 to build and launch with debugging. Using the button at the bottom of the Home screen, you can navigate to the Register New Sighting screen, and your JavaScript code will request your location to your browser, which in turn asks the user for permission first.

Asking for the current user’s location
Figure 8 Asking for the current user’s location

Pushing the Limits?

The time has come to add the final screens: allow the user to add details about the new sighting, and a fourth screen to select the particular animal species.

From the Screen Designer, add a new button to the Command Bar of the “Register new Sighting” screen. One of the navigation suggestions already in the wizard is to navigate to a screen to Add or Edit SightingDetails. LightSwitch makes this suggestion simply because you have a list of SightingDetails on the screen. Because it also detects there’s no Edit Screen for the SightingDetail entity, it is also suggesting to create a New Screen for this.  

Context-aware options in the Add Button wizard
Figure 9 Context-aware options in the Add Button wizard

When you click OK, the edit screen for the SightingDetails entity will be generated, and is pretty much done. In summary: add a new button, LightSwitch inferred the rest. I doubt a developer’s life can get any easier.

However, some developers incorrectly assume that the more you gain development speed due to auto-generation of code or screens, the more you lose freedom to do anything outside of the generated path. Let’s put this theory to the test and see how hard it is to deviate from the standard screen flow in the final screen, which will be a screen where the scientists can select the sighted animal’s species.

Because this screen lists out the animal species, it’s an obvious choice to add a new screen to the application using the Browse Data screen template on the AnimalSpecies entity.

If the user taps on one of the animal species from the list, this animal should then be selected for a particular sighting’s detail line, so add such a detail line on the current screen by clicking on the Add Data Item button, and selecting a local property of the SightingDetail type, named CurrentSightingDetail. When you select that newly added property, make sure the Is Parameter checkbox is checked.

Select the List from the screen designer, and select to execute a new method:

/// <reference path="../GeneratedArtifacts/viewModel.js" />
myapp.BrowseAnimalSpecies.AnimalSpecies_ItemTap_execute = 
  function (screen) {
  screen.CurrentSightingDetail.AnimalSpecies = screen.AnimalSpecies.selectedItem;

This code consists of two lines: one that adds the currently selected AnimalSpecies to the current SightingDetail, and one that commits these changes to the current changeset and navigates back one screen. You can read about the details of the commitChanges method on the LightSwitch’s team blog..

Your screen should now look like Figure 10.

Screen to select an animal species (part 1)
Figure 10 Screen to select an animal species (part 1)

To set up navigation from the third screen (the one that was automatically generated for us) to this screen, add a new button on the previous screen and from the dialog that appears, select to navigate to this screen when that button is clicked. If you set up everything correctly, the wizard should ask about a SightingDetail parameter too.

The CurrentSightingDetail parameter is asked when setting up navigation to this screen.
Figure 11 The CurrentSightingDetail parameter is asked when setting up navigation to this screen

Right now, the scientists have to scroll through a list of hundreds of animal species, making it anything but a user-friendly experience. To fix this we’re going to add the ability to filter all animal species, before we apply the finishing touches to the application.

From the left-hand side of the screen designer, select the AnimalSpecies collection and click the Edit Query link to open the Query designer.

Add a new, optional parameter and set up a filter so that the animal species get filtered by category.

Filtering the animal species by category
Figure 12 Filtering the animal species by category

Hit the Back button to navigate back to the Screen Designer, and you should see that the AnimalSpecies collection now has a query parameter. If you create a new popup and drag this parameter onto the screen, LightSwitch will automatically add a new local property (a string called “AnimalCategory”) and set up the binding to keep this local property in sync with the actual query parameter.

Now all we need to do is add some kind of trigger that will open the popup. Add a new button to the command bar, and from the wizard select the OpenDialog option. Your screen should look like Figure 13.

Screen to select an animal species (part 2)
Figure 13 Screen to select an animal species (part 2)

Press F5 to pick the fruits of your labor.

List of animal species with a popup to filter by category
Figure 14 List of animal species with a popup to filter by category


After further tidying up, using only standard options in the screen designer, we have created a professional and responsive HTML client that can run on any mobile device. In a next article, we’ll follow up with some advanced control and general layout CSS modifications that you can do.

The application has a home screen (which admittedly is rather empty right now), where the scientists can click to register a new sighting. Using a few lines of JavaScript, this will automatically fetch the scientists’ current location, and the scientist can then use the touch-friendly UI to select the animals they saw, and add additional notes.

The user experience in the finished application
Figure 15: The user experience in the finished application

Again, the LightSwitch team succeeded in taking out the tedium of the application’s development, hiding common tasks behind a simple IDE, allowing the developers to focus only on the challenging bits without ever really running into limits caused by this type of speedy development.

If you want to learn more about the new HTML client, download the update, start playing yourself, and pay a visit to the HTML client development center or further tutorials.

Jan Van der Haegen is a green geek who turns coffee into software. He’s a loving husband, .NET addict, LightSwitch lover, blogger, independent consultant and columnist for MSDN magazine online. He secretly dreams of becoming a professional goat herder one day. You can find his coding experiments at http://janvanderhaegen.com/.

Thanks to the following technical experts for reviewing this article: Beth Massi, Heinrich Wendel and Joe Binder.