August 2011

Volume 26 Number 08

Visual Studio LightSwitch - Build Business Applications with Visual Studio LightSwitch

By Robert Green | August 2011

Consider the tale of two overworked individuals. Antonio is a senior developer in the IT department of a large bank with hundreds of branch offices. Dalia is the manager at one of these branches. She wants to do a better job of tracking computer assets. Who has what computer and how long have they had it? When was each printer and fax machine purchased and serviced? How much does the branch spend on peripherals and supplies each month?

Dalia e-mails Antonio and asks him to create an asset-tracking application. Antonio agrees this is needed and could save the bank significant sums of money, but he’s already fully committed to other projects and has no time to help Dalia. He knows that Dalia is going to build the application herself in Excel or another end-user application, and this worries him because she’s likely going to build a single-tier, self-contained application that won’t scale. But what can he do?

Fast forward six months. Dalia is a hero. She built her app and it has cut her branch’s computer spending by 25 percent while also increasing productivity due to more efficient use of resources. Bank management decides that all of the branch offices should adopt this system and that the data should be centralized. Antonio is told to make this happen by the end of the month, and it’s now his nightmare to convert this application into something that resembles what he would have built if he had had the time. Good luck, Antonio!

Introducing Visual Studio LightSwitch

Visual Studio LightSwitch is designed to address this all-too-common scenario. LightSwitch is a new product in the Visual Studio family aimed at developers of all skill levels who want to quickly create data-centric business applications for the desktop, Web and cloud. LightSwitch simplifies the development process because it does most of the development work for you. You don’t need to write code to interact with databases and you don’t need to manually lay out screens. You can concentrate on the business logic.

LightSwitch applications are based on Silverlight. They use proven n-tier architecture patterns based on Model-View-ViewModel (MVVM), as well as familiar Microsoft .NET Framework technologies such as the Entity Framework and WCF RIA Services. LightSwitch applications can be deployed as desktop (out-of-browser) or browser-based applications. Desktop applications can leverage local hardware resources and work with applications such as Microsoft Word and Excel. Both desktop and browser-based LightSwitch applications can be hosted on IIS and Azure.

The primary audience for LightSwitch is end-user developers such as Dalia. They’re information workers, IT professionals, business analysts and so on who do some development as part of their job. They aren’t professional developers, and they want a smooth on-ramp to development, built-in plumbing that handles common application requirements, and simple and flexible deployment options. In short, they want to quickly build well-architected, data-centric applications that can be easily deployed and scaled.

Existing Visual Studio developers will often find LightSwitch an attractive addition to their toolset. LightSwitch installs on top of Visual Studio 2010 Professional and above. Visual Studio developers can build LightSwitch applications from scratch or they can open a LightSwitch application in Visual Studio and extend it. If Dalia had used LightSwitch to build her application, Antonio could open it and enhance it. Or Antonio could build the application in LightSwitch in potentially dramatically less time than if he started from scratch.

In this article, I’ll review a LightSwitch application used by the construction company arm of the ubiquitous Contoso Corp. The company wants to manage customers and their projects. You can download the sample application I’ll be discussing here: code.msdn.microsoft.com/Contoso-Construction-9f944948.

Entities

The first step in building a LightSwitch application, after choosing whether you want to code in Visual Basic or Visual C#, is to define your data. You can create new tables or attach to external data sources. If you create tables from scratch, they’re added to the application database, which is a SQL Server Express database. Note that when it’s time to deploy the application, you can choose any edition of SQL Server to host the data. To work with external data, you can connect to an external database such as SQL Server or SQL Azure or any database for which you have an Entity Framework provider. You can also connect to SharePoint lists or WCF RIA Services.

The sample application contains a Customer entity (table), as shown in Figure 1.

The Customer Entity
(click to zoom)

Figure 1 The Customer Entity

For each entity property, you can define not only the data type, but also whether the property is required, unique, searchable and displayed on screens by default. You can also specify alternate display labels and maximum lengths. For numeric and date properties, you can specify minimum and maximum values.

Rather than leave certain properties as strings or their default types, you can use built-in data types, also referred to as custom business types. The phone and fax properties in the Customer entity use the Phone Number data type, and the Email property uses the Email Address data type. The built-in data types provide validation and will generate user-friendly runtime errors. There’s no need for you to write code to validate that a phone number or e-mail address is valid. In addition, the Phone Number data type includes built-in formatting, as shown in Figure 2.

The Built-In Phone Number Data Type Provides Validation and Formatting

Figure 2 The Built-In Phone Number Data Type Provides Validation and Formatting

There are also Date, Image and Money data types that all come with built-in editors, formatting and validation.

After adding properties to an entity, you should review the entity’s Summary property, which describes the entity. It also becomes a hyperlink on search screens.

The screen displays all customers in a grid. Notice the Full Name column contains hyperlinks. When the user clicks a full name, LightSwitch displays the detail screen for that customer. As the LightSwitch developer, you don’t need to write any code to make this happen. Figure 3 shows the Search Customers screen.

An Entity’s Summary Property Is a Hyperlink in Search Screens

Figure 3 An Entity’s Summary Property Is a Hyperlink in Search Screens

By default, LightSwitch uses the first string property as the entity’s Summary property. If there are no strings, it will use the first non-string property. In the sample application, customers are people and the first string in the Customer entity is LastName. Rather than use that as the Summary property, the Customer entity has a FullName property. This is a computed property. To make a property computed, you check Is Computed in the Properties window or click a button at the top of the designer, click Edit Method, and then write the following code to compute the value of the property (I’ll be using Visual Basic):

Private Sub FullName_Compute(ByRef result As String)
  result = Me.LastName + ", " + Me.FirstName
End Sub

To make FullName the Summary property, simply select the Customer entity and set the Summary property to FullName.

Computed properties aren’t stored in a database. They’re computed at run time as properties of an entity. You can use computed properties for simple concatenations of names and addresses and also for calculated values such as year-to-date revenue or total value of outstanding invoices.

To create a relationship between entities, click the Relationship button in the Data Designer. In the Add New Relationship dialog box, select the two entities, the type of relationship and the delete behavior. The Customer entity has one-to-many relationships defined with the Project and Appointment entities. Therefore, Customer has a Projects property and an Appointments property. These two properties are collections.

You can not only create relationships between entities in a single data source, but also between entities in multiple data sources. LightSwitch will handle retrieving all of the data, presenting it to users and saving changes. The ability to create federated relationships is a unique and compelling feature of LightSwitch.

Custom Validation Rules

In addition to using the validations provided by the built-in business types, you can add custom business logic code, both at the screen and entity level. Screen validation code runs only on the client and validates screen properties and data. Entity property validation code runs on the client first and then on the middle tier. Users get immediate feedback and can correct errors before sending data to the middle tier. The validation logic also runs on the middle tier to handle situations where data is changed by other users. This is a best practice in n-tier design.

To write validation code for an entity property, you can select the property in the Entity Designer and then select the appropriate method from the Write Code button drop-down list: Address1_Validate, for example (shown in Figure 4).

Figure 4 The Address1_Validate Method

Private Sub Address1_Validate(results As EntityValidationResultsBuilder)
  'Warn the user if the Address is empty
  If Me.Address1 = "" Then
    results.AddPropertyResult(
      "Address should not be empty. " & 
      "Construction project cannot begin unless an address is supplied.", 
      ValidationSeverity.Warning)
  End If
End Sub

EntityValidationResultsBuilder is a container for validation results. It can contain validation information, warnings and errors. Validation information and warnings present information to the user but don’t prevent the user from saving data. If the collection contains any validation errors, the user can’t save the data.

In the sample application, the user is warned if the address is empty. The user can still save the data. However, the code to validate the ZIP code (shown in Figure 5) isn’t as forgiving.

Figure 5 The ZIP_Validate Method

Private Sub ZIP_Validate(results As EntityValidationResultsBuilder)
  If Me.ZIP <> "" Then
    'Enter the dash if not supplied and is 9 digits long
    If Me.ZIP.Length = 9 Then
      Me.ZIP = Me.ZIP.Substring(0, 5) + "-" + Me.ZIP.Substring(5)
    End If
    'Make sure valid zip code (5 or 5+4 format)
    If Not System.Text.RegularExpressions.Regex.IsMatch(
      Me.ZIP, "^\d{5}$|^\d{5}-\d{4}$") Then
      results.AddPropertyError(
        "Please enter a valid US ZIP code. (ex. 98052 or 98052-1234)")
    End If
  End If
End Sub

If the ZIP code isn’t in the proper format, the code adds a validation error. This will prevent the user from saving the invalid data. Figure 6 shows the results of leaving the address empty and entering an invalid ZIP code. The empty address generates a warning and the invalid ZIP code generates an error.

The Empty Address Generates a Warning While the Invalid ZIP Code Generates an Error

Figure 6 The Empty Address Generates a Warning While the Invalid ZIP Code Generates an Error

Screens

After you define your entities, the next step in building a LightSwitch application is to design screens. LightSwitch includes the following predefined screen templates:

  • Details Screen This displays a single entity and can include related data in a grid.
  • Editable Grid Screen This enables the editing of one or more items in a grid.
  • List and Details Screen This displays a collection of items in a list. Selecting an item in the list displays the details for that item.
  • New Data Screen This is a screen for creating a new item. The screen can also provide a grid to enable the ability to add related data at the same time.
  • Search Data Screen This displays data returned from a query. Each item includes a link to display the entity’s details screen.

These templates provide a good starting point for your screen layouts. To create a screen, you can right-click the solution or the Screens node in the Solution Explorer and select “Add Screen.” You can also click the Screen button in the Data Designer. When you create a screen, you select the type of screen and the primary screen data. You can select an entity or a query based on an entity. You can then specify related data you want to appear on the screen.

When you open a Silverlight screen in Visual Studio, you see a design canvas and XAML. When you open a screen in LightSwitch, you see the Screen Designer, as shown in Figure 7.

The Screen Designer Shows a Hierarchical View of the Controls on a Screen

Figure 7 The Screen Designer Shows a Hierarchical View of the Controls on a Screen

On the left is the screen members list. This contains the items that are available on the screen. It includes the data items in each entity included in the screen. It also contains methods such as Close, Refresh and Save. On the right is the screen content tree. This is a hierarchical view of the controls on the screen and the data to which they’re bound. You can add data items to the screen as needed. You can rearrange the screen controls as well as modify the screen layout. For example, you may want the customers list on the left and orders on the right rather than customers on top and orders below. You can also set various properties of controls, such as label text, whether a label appears, horizontal and vertical alignment, height and width.

After you create at least one screen, you can press F5 and run the application. The first screen you create is the application’s default screen. You can change this on the Navigation tab of the Application Designer. LightSwitch applications automatically include an application shell, a navigation menu, a ribbon, a tabbed area for screens and data binding, as shown in Figure 8.

LightSwitch Applications Automatically Include an Application Shell, Menu and Ribbon

Figure 8 LightSwitch Applications Automatically Include an Application Shell, Menu and Ribbon

The application also has built-in dirty checking and concurrency handling. LightSwitch handles all the plumbing of a typical data-centric application for you so you don’t need to write any of that code.

The LightSwitch screen templates provide specific functionality. For example, a search screen contains a grid to display items and a button to export those items to Excel. You can add additional items as needed. The SearchCustomers screen (shown in Figure 8) has two additional buttons: an Add Customer button in the ribbon and an Add button in the grid’s header.

To add a button to the ribbon, you can right-click Screen Command Bar in the Screen Designer and select Add Button. Or you can expand the Screen Command Bar and select New Button from the Add button’s drop-down list, as shown in Figure 9. To add a button to the grid, use the Command Bar contained in the grid.

The Screen Command Bar Contains the Buttons in the Application’s Ribbon

Figure 9 The Screen Command Bar Contains the Buttons in the Application’s Ribbon

When you add a button, LightSwitch prompts you for the name of the method that runs when the user clicks the button. You can right-click the button and select Edit Execute Code, and then write the code that executes. Both Add buttons on the SearchCustomers screen call the gridAddAndEditNew_Execute method, which calls the ShowCreateNewCustomer method. This is a LightSwitch built-in method that displays the CreateNewCustomer screen, as shown here:

Private Sub gridAddAndEditNew_Execute()
  Me.Application.ShowCreateNewCustomer()
End Sub

Just like entities, screens have a number of events you can handle, as shown in Figure 10.

Access Screen Event Handlers via the Write Code Button

Figure 10 Access Screen Event Handlers via the Write Code Button

The Run event occurs when a request is made to display a screen. The Run event handler includes a handled argument. If you set this to true, you can prevent the screen from continuing. The InitializeDataWorkspace event occurs just before the screen data is retrieved. This is a good place for screen initialization code. The other events are self-explanatory. You might think that events such as Run or Saving are good places to put code that checks whether the user can perform actions such as open the screen or save the data. However, you should put that code in the appropriate Access Control methods, such as CanRun at the screen level or CanUpdate at the entity level. Access control is a big feature of LightSwitch applications that I’ll discuss later.

LightSwitch development is designed to be highly iterative. Developers can edit screens at run time while running in Debug Mode by clicking the Design Screen button in the ribbon. This switches to the screen’s Customization Mode, as shown in Figure 11.

Users Can Edit Screens at Run Time and View Their Changes Immediately
(click to zoom)

Figure 11 Users Can Edit Screens at Run Time and View Their Changes Immediately

Users can rearrange controls and set properties, click Save and see their changes immediately.

Knowing that a LightSwitch application is a Silverlight application, you may be wondering, “Where is the XAML?” A primary goal of LightSwitch is to make it much easier to build applications. It therefore does not expose XAML at design time. Rather, LightSwitch generates XAML at run time based on the screen design. This makes it dramatically easier for users to build applications. If you’re an experienced Silverlight developer, you might be thinking that this also limits your ability to build the screens you’d like.

While this may be true if you’re only using Visual Studio LightSwitch, you have much more flexibility if you have LightSwitch on top of Visual Studio 2010 Professional or above. You can create your own Silverlight user controls and add them to LightSwitch screens, as well as use controls that aren’t included in LightSwitch. You can create composite controls or even entire screens that include custom logic, plus you can easily bind these user controls to screen entities.

Another way to add functionality to a LightSwitch application is to use an extension. There are six types of LightSwitch extensions: controls, screen templates, business types, shells (application look and feel), themes (colors and brushes for a shell) and custom data sources. You’ll need Visual Studio 2010 Professional or above and the Visual Studio 2010 SDK to create a LightSwitch extension, but anyone can use them in their LightSwitch project, no matter what edition they have installed.

Extensions are distributed via VSIX packages. If you want to make an extension broadly available, you can upload it to the Visual Studio Gallery. It will then appear in the Extension Manager within LightSwitch. After installing an extension, you can enable it on the Extensions tab of the Application Designer. The Contoso Construction sample application uses a Bing map control extension to show the location of customers, as shown in Figure 12.

You Can Use LightSwitch Extensions, Such as the Bing Map Control Extension, to Provide Additional Functionality in Your Applications

Figure 12 You Can Use LightSwitch Extensions, Such as the Bing Map Control Extension, to Provide Additional Functionality in Your Applications

Queries

All screens are based on queries. The query for a Detail screen returns one row. The query for a List and Details screen returns one parent row and all of the related child rows. The query for a Search or Editable Grid screen will return all rows by default. Note that queries that return a number of rows don’t literally return all of the rows at once. The queries support paging by default. To configure the paging, select the query in either the Screen or Query Designer and change the paging-related properties.

You can filter the data returned by a screen query that returns a collection of entities. To do this, click Edit Query in the Screen Designer. In the Query Designer, you can then add Where and Sort clauses. You can also add parameters to queries.

Screen queries are specific to a particular screen. Although it’s quick and easy to modify a screen’s query, a better practice is to create a reusable query. For example, you may want customers sorted by company name on the customer search screen. However, customers may also appear in a modal window picker on the screen where you create new appointments and in an autocomplete text box on the screen that displays customers and their projects. Rather than add the same Sort to three queries on three different screens, you can create one query and use it on the three screens.

To create a query, you can right-click on an entity in the Solution Designer and select Add Query. You can name the query and then add filtering, sorting and parameters. The CurrentAppointments query, shown in Figure 13, returns all appointments, sorted by start time, where the start time is now or later.

You Can Filter the Results of a Query and Specify the Sort Order

Figure 13 You Can Filter the Results of a Query and Specify the Sort Order

Once you’ve created a query, you can use it as the basis for screens. You can also use it as the basis for additional queries. For example, in the sample application, the CurrentAppointmentsByEmployee query starts with the CurrentAppointments query and then filters the results to return only the appointments for a particular employee.

Access Control

Access control gives you the ability to control what actions users can take in an application. LightSwitch uses the standard ASP.NET membership and role providers to enable both Windows and Forms authentication. You can authorize users to perform actions by creating permissions, assigning them to users and then checking in code whether the user has a particular permission.

By default, all users can perform all actions in a LightSwitch application. To change this, open the Application Designer and select the Access Control tab, as shown in Figure 14. Then select either Windows or Forms authentication. The built-in SecurityAdministration permission controls whether a user can see the security administration screens at run time. You use those screens to assign permissions to users and add users if necessary. You can create additional permissions if desired. During development, you can turn off permissions by unchecking Granted for debug. This enables you to test the application using various combinations of permissions.

Specify Windows or Forms Authentication and Then Specify Additional Permissions

Figure 14 Specify Windows or Forms Authentication and Then Specify Additional Permissions

You can check for permissions in code at the entity, screen and query levels. Entities provide CanDelete, CanInsert, CanRead and CanUpdate methods, which all run on the server. You can access these from the Write Code button drop-down list in the Data Designer. You can check for the appropriate permission and return false if the user isn’t permitted to take the associated action. For example, in the sample application, only administrators can modify employee data. The following code ensures this:

Private Sub Employees_CanDelete(ByRef result As Boolean)
  result = Me.Application.User.HasPermission(
    Permissions.SecurityAdministration)
End Sub
Private Sub Employees_CanInsert(ByRef result As Boolean)
  result = Me.Application.User.HasPermission(
    Permissions.SecurityAdministration)
End Sub
Private Sub Employees_CanUpdate(ByRef result As Boolean)
  result = Me.Application.User.HasPermission(
    Permissions.SecurityAdministration)
End Sub

Screens provide a CanRun method, which runs on the client. You can use this method to not open a screen if the user can’t view or modify the screen’s data. The following code ensures that only administrators can open the ManageEmployees screen:

Private Sub ManageEmployees_CanRun(ByRef result As Boolean)
  result = Me.User.HasPermission(Permissions.SecurityAdministration)
End Sub

During the deployment process, you’ll specify the user name and password of the administrator. At run time, the administrator creates roles and assigns users to them. The administrator then assigns permissions to roles.

Deployment

LightSwitch provides three models for deploying applications: two-tier desktop application, three-tier desktop application and three-tier Web application.

A two-tier desktop application runs entirely on the end user’s computer as an out-of-browser Silverlight application. The UI and all the application’s middle-tier components run locally. The application connects to the database directly in typical client-server fashion. 
This avoids the need for a Web server. The application has access to local resources, including COM or local files. COM support provides the ability to control applications such as Word or Excel. Note that desktop applications require Windows.

A three-tier desktop application runs as an out-of-browser Silverlight application hosted on IIS or Azure. The UI runs on the end user’s computer, while the middle-tier components run on the host server.

A three-tier Web application runs as an in-browser Silverlight application hosted on IIS or Azure. The UI is browser-based and the middle-tier components run on the host server. Web applications don’t have access to COM or local resources, but they do provide the most reach across Mac and Windows OSes and multiple browsers.

To deploy an application, you first publish it. To publish the application, click the Publish button on the Application Type tab in the Application Designer, as shown in Figure 15.

Specify Whether the Application Is a Two-Tier Desktop Application, Three-Tier Desktop  Application or Three-Tier Web Application

Figure 15 Specify Whether the Application Is a Two-Tier Desktop Application, Three-Tier Desktop  Application or Three-Tier Web Application

The LightSwitch Publish Application Wizard will then walk you through the publishing process.

If you publish the application as a two-tier desktop application, you’ll create a ClickOnce package. You’ll create a SQL Server database that contains any local tables you created, as well as system tables. You can also specify where this database resides. If the application is used by a single person, you may locate the database on that user’s computer and use SQL Server Express. If the application will be used by more than one person, you’ll likely store the database on a network computer running SQL Server.

If you publish the application as a three-tier desktop or Web application hosted on IIS, you can publish directly to IIS if the server is running the Microsoft Web Deployment Tool service. Otherwise, you can create an MSDeploy package and manually import it into IIS. If you publish the application to Azure, the wizard will prompt you for your account subscription ID, the service and storage accounts you’ll use, and an SSL certificate to use. For more information on deployment and publishing to Azure, see the deployment section of the LightSwitch Developer Center on MSDN (bit.ly/jiYov5).

The Simplest Way

Wrapping up, the primary audience for LightSwitch is end-user developers. These are people building applications to support business functions. They aren’t professional developers. They’re IT pros, information workers and others who do some development as part of their job. They often have a need to build applications that manage “things,” such as department computer assets or car fleets. They may need an application to manage an event, such as a quarterly open house.

LightSwitch provides these users with a smooth on-ramp to development. It automatically builds the “plumbing” to perform common application tasks, such as working with data, generating screens, exporting data to Excel and more. It also provides a simple and flexible deployment model.

LightSwitch is the simplest way to build data applications for the desktop and the cloud. The Dalias of the world can build the applications they need and then turn them over to the Antonios of the world to be extended and deployed. For more information on how to build applications with LightSwitch, visit the LightSwitch Developer Center on MSDN (msdn.com/lightswitch).


Robert Green is a technical evangelist in the Developer Platform and Evangelism group at Microsoft. This is his second stint at Microsoft. From 2005 to 2010, he was a senior consultant with MCW Technologies, focused on developer training. He authored and coauthored a number of Visual Studio and .NET courses for AppDev (appdev.com). Prior to that, in his first stint at Microsoft, he was in Developer Tools marketing and then community lead on the Visual Basic team.

Thanks to the following technical expert for reviewing this article: Beth Massi