LightSwitch

Build Modern Business Productivity Apps with Visual Studio LightSwitch

Jan Van der Haegen
Beth Massi

Download the Code Sample

In this article we’ll take a look at some of the new features in Visual Studio LightSwitch that help you build modern, mobile, business productivity apps.

Visual Studio LightSwitch (just LightSwitch from here on for brevity) is designed to simplify and shorten the development of businesses apps. LightSwitch apps can consume a variety of data sources, provide business and authorization logic, and create clients that can run on a variety of devices—all without the need to write plumbing code.

LightSwitch can aggregate multiple data sources, and it exposes a set of open data services (the Open Data protocol, or OData) automatically to support custom clients and self-service business intelligence (BI) scenarios. LightSwitch also lets you write code to customize the apps as necessary, whether that’s the UI controls, business logic, data services or other components.

With the release of Visual Studio 2012 Update 2 in April, LightSwitch also has added the ability to quickly build touch-centric HTML5 clients that run well on modern mobile devices. LightSwitch HTML clients are built on standards-compliant HTML5 and JavaScript and provide modern, touch-first experiences on Windows RT, Windows Phone 8, iPhones and iPads with iOS 5 and 6, and Android 4.x devices.

Additionally, with the new SharePoint 2013 app model, LightSwitch is also bringing the simplicity and ease of building custom business apps into SharePoint and Office 365. Many enterprises today use SharePoint as a hub to enable better collaboration between people, content and processes. Although you can still choose to host your apps on your own or in Windows Azure, enabling SharePoint in your LightSwitch apps allows you to take advantage of the app lifecycle management, identity and access control capabilities within SharePoint—not to mention the business data and processes already running in SharePoint in your enterprise.

The LightSwitch HTML Client

In LightSwitch you always start with the data model, whether you’re modeling new data or connecting to existing data sources. Because in this article we’re focusing on new features, we’ve already created a simple data model and filled the database with some initial data. This way, you’re all set up and ready to start creating a client that you can use to make sure you sit in on the most interesting sessions when attending an exciting conference, such as Visual Studio Live! In case this is your first introduction to LightSwitch, make sure you don’t miss out on the wealth of data modeling, self-service BI, concurrency handling and multithreading goodness it has to offer by reading MSDN Magazine’s previous articles—such as “Shape Up Your Data with Visual Studio LightSwitch 2012” in the September 2012 issue (msdn.microsoft.com/magazine/jj618303)—or by checking out the LightSwitch Developer Center (msdn.com/lightswitch).

The HTML client provides an approach to building touch-first single-page apps that run on a broad range of mobile devices, often referred to as “companion apps” to signify that these apps play just one specific role in a larger architecture. Creating such a companion app to browse data on location—as we do in this article—is a great exercise to get started with the HTML client, but is in no way representative of the broad range of problems these apps can solve. These companion apps can help your business save time and money by allowing data not only to be consulted, but also modified and stored back (collecting a customer’s signature when a package is delivered, for example), and sometimes even making use of some device-specific capabilities such as geolocation (capturing the location where a soil sample is collected, for example).

Screen Templates and Navigation No matter what type of client you create, LightSwitch takes the same approach to defining screens using a set of predefined templates from which you can choose. To add a screen, simply right-click on the project in Solution Explorer and select the Add Screen option. This opens a dialog where you can select a screen template and some additional options such as the name of the screen and the data it will use. This screen then will be generated based on the chosen template and opened in the screen designer.

For the somewhat-experienced LightSwitch developer, this already feels familiar, because the design-time experience is almost exactly the same as when using LightSwitch to create screens in an out-of-browser Silverlight app, simplifying the already easy learning process. LightSwitch has stayed faithful to the app’s underlying Model-View-ViewModel (MVVM) architecture and the way the screen designer shows view models on the left-hand side and a representation of the corresponding views on the right.

One notable change is that setting up navigation from one screen to another (or binding any other action to events caused by the user tapping on elements in the screen) has really become a first-class citizen in the screen designer. This is an obvious improvement, not only because apps are so touch-focused, but also because the LightSwitch HTML client produces a single-page application (SPA). The Silverlight client had a Multiple Document Interface (MDI) shell that allowed many screens to be open at the same time; hence, in LightSwitch HTML apps, navigating between screens becomes incrementally more important.

For example, if you use the Browse Data template on the session entity to create the first screen in this app, a screen is generated that contains a list of sessions. (This list is selected in the screen designer, and then the Edit Item Tap Action link is clicked in the Properties window.) This opens up a dialog that’s highly adaptive in its suggestions: Because the user is browsing the sessions and has tapped on a single item, the dialog suggests the action of opening a screen where the user can view the details of the selected session. Because such a screen hasn’t been created yet, the dialog is suggesting that you go ahead and create that screen as well. This is shown in Figure 1.

Setting Up Actions for Touch Events Is Now a First-Class Citizen in the Screen Designer
Figure 1 Setting Up Actions for Touch Events Is Now a First-Class Citizen in the Screen Designer

After accepting, pressing F5 builds the app and starts a new debugging session in the default browser. The home screen opens and displays a simple list of sessions. When you tap on a session, the app smoothly navigates to the newly generated detail screen that displays the details of the particular session in a simple two-column layout, shown in Figure 2.

Adaptive Design Helps to Write a Single App for Multiple Form Factors
Figure 2 Adaptive Design Helps to Write a Single App for Multiple Form Factors

Although this screen looks simple, there’s a lot going on behind the scenes. This “simple list of sessions” is actually backed by a completely virtualized collection that loads more elements as the user scrolls down, to avoid unnecessarily transferring large amounts of data over a mobile connection. The two-column layout dynamically adapts to the available size, changing to a single-­column layout on smaller devices. This is a vital element in the strategy to write a single HTML app and run it on a variety of tablets and phones, each with its own form factor. The Visual Studio LightSwitch Team Blog post, “Designing for Multiple Form Factors” (bit.ly/18F320N) by Program Manager Heinrich Wendel, provides more detail about the vision behind this adaptive design, which normally requires a great deal of work from the developer, but which LightSwitch simply offers with little effort.

Other notable elements in the screen designer include the promoted usage of pop-ups and tabs, which each have their own command bar. One example of how these can make life easier for the end user is to add a filter on the sessions. To do this, you first select the Sessions query element in the view model (the left-hand side of the screen designer) and click Edit Query, which opens the query editor where you can quickly modify the query that’s used by adding some optional arguments. Next, hit the Add Data Item button to add a local Speaker property called FilterBySpeaker, set up data binding of this Speaker’s Id to the corresponding query argument, and repeat this process for the other entities: Room, Time Slot and Track.

To complete the screen, simply drag these four new view model properties onto a newly created pop-up in the view (the right-hand side of the screen designer). By default, LightSwitch will suggest to visualize each property as a Modal Picker control, which is just fine for this app. Finally, add a new button to the command bar and use the same dialog that appears when setting up the Edit Item Tap Action to open the newly created pop-up.

Hitting Save and refreshing the browser is all it takes to view the newly added filter in action (JavaScript doesn’t need recompilation, as do traditional Microsoft .NET Framework apps). The home screen opens, showing all sessions in a virtualized collection—and this time also showing a blue command bar with a single Filter button. When this button is clicked, a pop-up is displayed showing the four filter options (shown in Figure 3) on a couple different devices. As soon as you actually make a selection, the optional query arguments are automatically updated because of the data binding. This in turn automatically triggers a new HTTP GET operation to be sent to the back-end OData service, which filters the sessions by the correct arguments and returns the result.

The Added Filter in Action
Figure 3 The Added Filter in Action

In summary, the screen designer does an excellent job of making the correct abstractions so you can focus on setting up a professional HTML app with minimal effort. For example, this app includes a virtualized list that can be filtered, all of which has been set up without having to write a single line of code.

Note, however, that as a developer you shouldn’t get too hung up on that no-code philosophy.

Yes, it’s true that the screen designer focuses on abstracting the actual technology to increase developer velocity, and that like all rapid-application development (RAD) environments, this implies sacrificing some customizability. However, LightSwitch offers many scenarios in the screen designer, as well as a large number of extension points, so you can roll up your sleeves and override, alter or append to the HTML, JavaScript and CSS mix that forms an app.

As an example, you can add a new query to the app that returns only those sessions in the next Time Slot as a Data Item on the screen, and drag that query onto a new tab in the home screen. Again, you can keep the List control to show the sessions, but instead of having a one-line summary per session (the title), the screen designer is used to nest some row and column layouts and display some additional information about the session, which results in the first (on the left-hand side) layout in Figure 4.

Three Different Designs for the Home Screen
Figure 4 Three Different Designs for the Home Screen

Branding, Theming and Further Customization When it comes time to start mixing in custom code, it’s quick and easy to apply some global theming and branding. The logo, in fact, is nothing more than a .png file that you can replace from Windows Explorer, and the theme is nothing more than a standard JQuery Mobile theme. LightSwitch ships with a light (default) and a dark theme, both of which you can further modify using the online JQuery Mobile ThemeRoller. Changing both the logo and the theme results in the center layout in Figure 4.

Finally, you can further define the look of your app by using Render or PostRender methods. By selecting any LightSwitch control in the screen designer, a link in the Properties window labeled Edit PostRender Code becomes available. When you click this link, a JavaScript method stub is generated that will be executed at run time, directly after the LightSwitch JavaScript library has rendered the required HTML elements for the particular control. A possible use of this extension point is to alter the background of each row in the list, depending on the track that the session is a part of, by writing the following code in that method:

myapp.Home.NextSessionsTemplate_postRender =
  function (element, contentItem) {
  $(element).parent("li").css("background", 
    contentItem.value.Track.Color);
};

This code grabs the parent of the HTML element that LightSwitch added and sets the CSS background property to the color of the track of the current session (contentItem.value), resulting in the right-most layout in Figure 4.

Figure 4 reveals an obvious fault in design: If the track has a bright color associated with it, then because of the contrast between the content and the background, an item can become unreadable. To correct this, add two reusable CSS classes to the user-customization.css file and alter the code so that it appends one of these classes: 

myapp.Home.NextSessionsTemplate_postRender =
  function (element, contentItem) {
  $(element).parent("li").css("background",
    contentItem.value.Track.Color);
  $(element).addClass(
    (parseInt(contentItem.value.Track.Color.replace(
    "#", ""), 16) > 0xffffff / 2)
    ? 'darkForeground' : 'lightForeground'
  );
};

Customizing the rendering process by writing PostRender methods can be used for a variety of options, ranging from simple CSS tricks such as changing the background color to applying a reusable JQuery UI widget that hides all items in the list but one, turning the list into a dynamic banner or image carousel. Visible items are changed with a set timer, as described in the blog post (written by coauthor Jan Van der Haegen), “Create a JQuery slider for LightSwitch HTML pages” (bit.ly/WJwnPw).

After turning the list of upcoming sessions into a banner with a color-coded background, it’s easy to forget which track has which color. Besides altering standard LightSwitch controls using this PostRender option, you can also take complete control over the entire rendering of specific elements by indicating they’re custom controls in the screen designer and then writing your own code in the similarly generated JavaScript Render method. To add a legend of tracks and their color code, add a query on all tracks as a date item to the screen view model and display it as a Tile List (a built-in alternative collection control). In the template of each tile, render the color of each track as a simple square, using this JavaScript code:

myapp.Home.Color_render = function (element, contentItem) {
  $("<div style='background-color: "+ contentItem.value 
  +";'>&nbsp;</div>").appendTo($(element));
};

Besides various visual customizations, LightSwitch also offers numerous code extension points in the ViewModel and Model layers to help you tweak the control flow and business rules of your apps.

This app now has a first tab that features the upcoming sessions (in the form of a banner) and has a legend of colors per track, along with a second tab with an overview of all the sessions, including an easy-to-use filter. Because the home screen already shows all of the tracks, it’s a good idea to fill in the filter on the second tab when the user taps on one of the tracks in the first tab, then focus this tab to show only the sessions in the selected track.

This control flow can’t be set up directly from the screen designer, but it’s easily accomplished by selecting the Tile List of tracks and in the Properties Window binding the item tab to execute to a custom method. This generates a JavaScript method stub where you can write the following:

myapp.Home.BrowseByTrack_ItemTap_execute = function (screen) {
  screen.getTracks().then(function (tracks) {
    screen.FilterByTrack = tracks.selectedItem;
    screen.showTab("AllSessions");
  });
};

The app now has three different perspectives to slice the sessions: see the upcoming sessions in a banner; click on a track to see the list of sessions filtered by that track; or adjust track, time slot, speaker or room on that same filter manually.

One last perspective you can add is an overview of your favorite sessions. To accomplish this, add a simple entity called FavoriteSessions. Favorite sessions are those in which an entry in Favorite­Sessions exists with a particular name.

When the screen to view a particular session is opened, determine if such an entry exists by asynchronously executing a specialized FindFavoriteSessions query on the server and storing the existence of this result in a Boolean screen property called IsFavorite:

myapp.ViewSession.created = function (screen) {
  myapp.activeDataWorkspace
    .ApplicationData.FindFavoriteSessions(screen.Session.Id)
    .execute().then(
      function (result) {
        screen.IsFavorite = result.results.length != 0;
      }
    );
};

Then add two buttons to the tab’s command bar: Favorite and Unfavorite. Only one of these buttons can be active at the same time, so use the button’s CanExecute code extension point. The LightSwitch JavaScript library calls these methods at the appropriate times and makes sure the UI is updated accordingly. Although this behavior can be overridden for each screen from the Properties window, it does so by default by hiding buttons that can’t be executed at the moment, saving precious screen real estate on small devices:

myapp.ViewSession.Favorite_canExecute
  = function (screen) {
  return !screen.IsFavorite;
};
myapp.ViewSession.Unfavorite_canExecute
  = function (screen) {
  return screen.IsFavorite;
};

One amazing highlight about such simple code snippets is that the LightSwitch JavaScript library keeps track of when these Can­Execute methods should be reevaluated. Just like in Silverlight out-of-browser apps, you don’t need to take care of throwing events when a property changes. Just set a new value for the IsFavorite property from anywhere within the app and the LightSwitch runtime will automatically know to reevaluate these particular CanExecute methods and update the view (show or hide the buttons) as required.

All that’s left to do now is to write some code that creates a new FavoriteSession (or removes it) when the button is clicked:

myapp.ViewSession.Favorite_execute = function (screen) {
  var favored = myapp.activeDataWorkspace.ApplicationData.
    FavoriteSessions.addNew();
  favored.setSession(screen.Session);
  myapp.applyChanges().then(screen.IsFavorite = true);
};

After adding the list of FavoriteSessions to a new tab on the homepage, the app is ready for packaging and deployment.

It turns out that LightSwitch does a great job of keeping a balance between designing the app in a simple but powerful screen designer and the amount of customizability you need to sacrifice for this simplified and speedy development. It achieves this balance by introducing a large number of extension points where you can write custom code to alter, override or append the default design, control flow or behavior of the app.

Integrating with SharePoint 2013 and Office 365

SharePoint 2013 introduces a new cloud-based app model that allows you to create apps that extend the capabilities of a SharePoint Web site and supports a tiered architecture in which the app’s business logic, data and UI can be distributed. Users discover and download apps from the Office store or from their organization’s private app catalog and install them on their SharePoint sites. Because of this new distributed model, you can build LightSwitch apps that target SharePoint 2013 on-premises and on Office 365. You can deploy the LightSwitch Silverlight in-browser clients or the new mobile-based HTML clients into SharePoint.

Building upon the Visual Studio Live! example, you can take advantage of Office 365 services in order to allow conference staff to set up the conference schedule using a SharePoint calendar within the LightSwitch app. When a new session is approved and a time slot is chosen, this will add a new calendar entry. You can then imagine a series of possible workflows that may trigger additional actions that are common with SharePoint. Thus, LightSwitch apps allow you to create touch-enabled experiences that take advantage of business data and processes that are already running in SharePoint in your business.

Enabling SharePoint in LightSwitch Apps In the project properties you click the Enable SharePoint button and provide a local or remote SharePoint 2013 site you want to use for development. When you do this, you’re indicating to LightSwitch that the app should be deployed to SharePoint and can work with SharePoint assets. This adds the appropriate SharePoint references to your project.

LightSwitch will also handle authentication to SharePoint automatically for you via OAuth. You can configure Access Control Service (ACS), which is another server that brokers authentication between your app and SharePoint. Your app will have a “secret” known to SharePoint and can use it to authenticate via ACS, as is the case with Office 365. You can also choose a high-trust configuration if you have that set up on-premises, as shown in Figure 5.

Enabling SharePoint in a LightSwitch App
Figure 5 Enabling SharePoint in a LightSwitch App

To get started developing SharePoint apps quickly, you can sign up for a free trial of the Office 365 developer subscription at dev.office.com. MSDN subscribers can also sign up for a free year through their subscription benefits site.

SharePoint Lists as LightSwitch Entities Using the Data Designer, you can bring in SharePoint lists as entities into the LightSwitch data model. This allows you to manipulate list data directly through the LightSwitch data context. This means you can create screens directly against SharePoint list data that you already have set up, and LightSwitch will handle the authentication and data operations automatically. For example, in the Visual Studio Live! scenario, any of the data could be stored in SharePoint lists and the UI wouldn’t change.

When you bring SharePoint lists into the LightSwitch data model, it also allows you to access the list data via code in a streamlined way using the LightSwitch API. For example, in the Visual Studio Live! app, we wanted to write code to automatically add a SharePoint calendar entry when a new session is added. To do this, right-click on the Server node in the Solution Explorer and choose “Add data source,” then select SharePoint as the data source type. After indicating the SharePoint site address and selecting to automatically choose the user identity, the SharePoint lists are displayed.

The site being used already contains a calendar called ConferenceSchedule. When this is brought into the data model you can set up a virtual relationship to the session table data. Simply click the Relationship button at the top of the data designer and define a One-to-Zero-or-one relationship (see Figure 6).

Setting Up a Virtual Relationship Between Multiple Data Sources
Figure 6 Setting Up a Virtual Relationship Between Multiple Data Sources

Now you can create a new screen that allows staff to enter new sessions. You could include the ConferenceSchedule data directly on the screen, but in this case some server code will be written so it happens transparently in the background. When the session data is saved, use the save pipeline’s _Inserting and _Updated methods on the Session entity to add a new entry to the schedule from the server using Visual Basic .NET or C# code (see Figure 7 and Figure 8, respectively). There are many hooks on the server that allow you to control business logic and data processing this way.

Figure 7 Code to Add a New Entry to the SharePoint Calendar Using Visual Basic .NET

Private Sub Sessions_Updated(entity As Session)
  Me.UpdateCalendar(entity)
End Sub
Private Sub Sessions_Inserting(entity As Session)
  Me.UpdateCalendar(entity)
End Sub
Private Sub UpdateCalendar(entity As Session)
  If entity.Timeslot IsNot Nothing AndAlso
     entity.Room IsNot Nothing Then
      If entity.ConferenceSchedule Is Nothing Then
        entity.ConferenceSchedule = New ConferenceSchedule()
      End If
      entity.ConferenceSchedule.Title = entity.Title
      entity.ConferenceSchedule.Description = entity.Description
      entity.ConferenceSchedule.StartTime = entity.Timeslot.StartTime
      entity.ConferenceSchedule.EndTime = entity.Timeslot.EndTime
      entity.ConferenceSchedule.Location = entity.Room.Name
      Me.DataWorkspace.VSliveData.SaveChanges()
  End If
End Sub

Figure 8 Code to Add a New Entry to the SharePoint Calendar Using C#

private void Sessions_Updated(Session entity)
{
  this.UpdateCalendar(entity);
}
private void Sessions_Inserting(Session entity)
{
  this.UpdateCalendar(entity);
}
private void UpdateCalendar(Session entity)
{
  if (entity.Timeslot != null && entity.Room != null)
  {
    if (entity.ConferenceSchedule == null)
    {
      entity.ConferenceSchedule = new ConferenceSchedule();
    }
    entity.ConferenceSchedule.Title = entity.Title;
    entity.ConferenceSchedule.Description = entity.Description;
    entity.ConferenceSchedule.StartTime = entity.Timeslot.StartTime;
    entity.ConferenceSchedule.EndTime = entity.Timeslot.EndTime;
    entity.ConferenceSchedule.Location = entity.Room.Name;
    this.DataWorkspace.VSliveData.SaveChanges();
  }
}

When you debug the app (F5) you’ll first be asked if you trust it. Once you confirm that you do, you’ll see a SharePoint chrome control at the top that allows users to navigate up to the SharePoint site from the LightSwitch app. Add a new session, then click “Back to site” in the chrome to see the Conference Schedule. If you click on the Event item, you’ll see it was created by the LightSwitch app on behalf of the user. This shows that the SharePoint user credentials flow through the LightSwitch app automatically.

The SharePoint Project and Client-­Side Object Model Using lists as entities isn’t the only way to access SharePoint data. When you enable SharePoint in your LightSwitch apps, you have the full SharePoint Client-Side Object Model (CSOM) available to you, as well. You can manipulate not only lists this way but also access other SharePoint assets. For example, if you wanted to create a general app that you could sell in the SharePoint store, you might need to deploy and manipulate SharePoint lists in a more generic way.

When you enable SharePoint, a SharePoint project is added to your LightSwitch solution. If you flip to File View on the Solution Explorer, you’ll see it as shown in Figure 9. You can add a variety of SharePoint-specific items to your app this way that will get deployed when you package your app. Then you can use CSOM to manipulate these items in code. For example, you can add a custom list to your project and then interact with that list via CSOM. LightSwitch exposes a SharePoint object on the Application object that you can use to get at the host and app webs.

Adding Custom Lists and Other SharePoint Items via the Solution Explorer
Figure 9 Adding Custom Lists and Other SharePoint Items via the Solution Explorer

For example, we added a custom list to the VSLive.SharePoint project that’s used to write audit entries anytime a session is added, updated or deleted. We can tap into the save pipeline again and use the list via CSOM. First, import the Microsoft.SharePoint.Client namespace, and then you can write the code shown in Figure 10 (Visual Basic .NET) or Figure 11 (C#).

Figure 10 Manipulating a SharePoint List via CSOM in Visual Basic .NET

Private Sub Sessions_Inserted(entity As Session)
  Me.LogAuditEntry(entity, "inserted")
End Sub
Private Sub Sessions_Updated(entity As Session)
  Me.LogAuditEntry(entity, "updated")
End Sub
Private Sub Sessions_Deleted(entity As Session)
  Me.LogAuditEntry(entity, "deleted")
End Sub
Private Sub LogAuditEntry(  entity As Session, actionDescription As String)
  Using ctx = Me.Application.SharePoint.GetAppWebClientContext()
    Dim web As Web = ctx.Web
    Dim lists As ListCollection = web.Lists
    Dim auditLog As List = lists.GetByTitle("AuditList")
    Dim ci As New ListItemCreationInformation()
    Dim auditEntry As ListItem = auditLog.AddItem(ci)
    auditEntry("Title") = String.Format("Session {0} {1}",
    actionDescription,
    entity.Title)
    auditEntry("Name") = Me.Application.User.FullName
    auditEntry("Date") = DateTime.Now
    auditEntry.Update()
    ctx.ExecuteQuery()
  End Using
End Sub

Figure 11 Manipulating a SharePoint List via CSOM in C#

private void Sessions_Inserted(Session entity)
{
  this.LogAuditEntry(entity, "inserted");
}
private void Sessions_Updated(Session entity)
{
  this.LogAuditEntry(entity, "updated");
}
private void Sessions_Deleted(Session entity)
{
  this.LogAuditEntry(entity, "deleted");
}
private void LogAuditEntry(Session entity, string actionDescription)
{
  using (ClientContext ctx =
     this.Application.SharePoint.GetAppWebClientContext())
  {
    Web web = ctx.Web;
    ListCollection lists = web.Lists;
    List auditLog = lists.GetByTitle("AuditList");
    ListItemCreationInformation ci = new ListItemCreationInformation();
    ListItem auditEntry = auditLog.AddItem(ci);
    auditEntry["Title"] = string.Format("Session {0} {1}",
    actionDescription, 
    entity.Title);
    auditEntry["Name"] = this.Application.User.FullName;
    auditEntry["Date"] = DateTime.Now;
    auditEntry.Update();
    ctx.ExecuteQuery();
  }
}

For more information on using CSOM with LightSwitch, as well as other tips and tricks, see the SharePoint topics on the Visual Studio LightSwitch Team Blog at bit.ly/16JIWn6.

SharePoint Deployment Considerations LightSwitch apps are just Web apps, so you can host them on your own IIS Web servers or in a cloud such as Windows Azure. When you install a SharePoint app, a manifest is installed that has information on where your app runs. As part of the new SharePoint app model, any apps that contain server-side code—which all LightSwitch apps do—must run on a separate server outside of SharePoint. This isolation provides better stability to the SharePoint farm.

LightSwitch supports two types of SharePoint deployment: autohosted and provider-hosted. You need to consider these options when building your app because they might directly affect the architecture of your data.

With autohosted apps, the Web site and database are provisioned automatically into Windows Azure each time the app is installed. The data is provisioned into SQL Azure, and the middle tier is provisioned into a Windows Azure Web site. This means that each instance of your LightSwitch app that’s installed into SharePoint is isolated from all other instances on other SharePoint sites. This is a quick and easy type of deployment. However, if your app is uninstalled, then everything is deleted, even the data.

Provider-hosted apps give you the flexibility of hosting the Web app and database wherever you want. However, with this model, all SharePoint app instances share the same middle tier and data, so you’ll need to provide your own tenant isolation. LightSwitch provides row-level filtering mechanisms in the query pipeline to help build multi-tenant apps. You also need to manage availability—if your server goes down, all your SharePoint apps stop working.

You also need to specify how you want your app to authenticate. This is the “ACS versus high trust” choice you make when you start developing with SharePoint. If your SharePoint server or farm is using ACS, as is the case with Office 365, then all that’s required is a ClientID and secret that’s shared between your app and SharePoint.

You use the LightSwitch Publish Wizard to specify these settings and package your app. Depending on the type of hosting, it will either deploy your app service and database to a server you specify (or Windows Azure), as is the case with provider-hosting, or it will wrap everything into the SharePoint deployment package. You then take that package and install it onto your SharePoint site catalog. From there, users can add your app to their sites.

For more information on hosting LightSwitch apps in SharePoint, see the following Visual Studio LightSwitch Team Blog posts: “SharePoint Hosting and Authentication Options for LightSwitch” (bit.ly/10vEJez) and “Publishing LightSwitch apps for SharePoint to the Catalog” (bit.ly/11wSFqo).

Wrapping Up

As you can see, there are a ton of new features in the latest release of LightSwitch in Visual Studio 2012 Update 2. These features complement the desktop-based Silverlight client that’s been available since the first release—and still is today. However, with many employees bringing their own devices to the workplace, building a native client for every device and deploying each implementation to separate app stores is rarely feasible. LightSwitch HTML clients are built on standards-compliant HTML5 and JavaScript and provide modern, touch-first experiences for today’s mobile devices.

Additionally, enabling SharePoint in your LightSwitch apps allows you to take advantage of the business data, processes, app lifecycle management, identity and access-control capabilities within SharePoint that are already embedded into many enterprises today.


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 https://janvanderhaegen.com/.

Beth Massi is a senior program manager on the Visual Studio team at Microsoft and is a community champion for business application developers. She’s a frequent speaker at various software development events, and you can find her on a variety of developer sites including MSDN.com, Channel 9 and her blog, bethmassi.com. Follow her on Twitter at twitter.com/BethMassi.

Thanks to the following technical experts for reviewing this article: Brian Moore (Microsoft) and John Stallo (Microsoft)