From Zero to Business Application in 15 Minutes Visual Studio LightSwitch is a new product in the Visual Studio family aimed at developers who want to quickly create data-centric business applications for the desktop and the cloud.LightSwitch is an extensible development environment and application framework that simplifies the development process because it lets you concentrate on the business logic and does a lot of the remaining work for you. LightSwitch is perfect for small business or departmental productivity applications that need to get done fast. In this article I will walk you through creating a business application from beginning to end using Visual Studio LightSwitch. A few years ago we had a lot of construction work done on our house to modernize the exterior. We updated all the siding, roof, windows, built a deck and did a bunch of landscaping. Our contractor would take tons of digital pictures for the before and after shots; so many that he would have mini SD cards lying all over his truck. He had a huge problem organizing all the pictures for all the construction projects he was managing. I told him I could write him an application to manage all the photos on each of his construction projects. At the time I used Windows Forms but this would have been a perfect small business application for Visual Studio LightSwitch. In this article I will quickly rebuild the application using LightSwitch. Let’s get started! Creating a LightSwitch Project When you open Visual Studio LightSwitch and go to the menu File ( New Project (or click “New Project…” on the start page), you will see that the environment is streamlined and the only decision you need to make up front is what programming language you want to use, Visual Basic or Visual C#. For this project I will use Visual Basic and name the project ContosoConstruction as shown in Figure 1. This sets up the necessary project folders and files on disk, populates the Solution Explorer project system and opens up the LightSwitch designer.  Figure 1. When you create a new LightSwitch project, the only decision you need to make up front is what programming language you want to use.Under the covers, LightSwitch projects are always logically three-tier applications and use n-tier best practices and patterns as well as familiar .NET technologies like Entity Framework, Silverlight and RIA services. Defining your Data The first step to building any LightSwitch application is to define the data tables, fields and relationships. After you create the project, you decide whether you want to start by creating a new table or if you want to connect to an existing data source, as shown in Figure 2. You can connect to databases like SQL Server or SQL Azure or any other database in which you have an Entity Framework provider installed. You can also connect to SharePoint or a custom RIA service. You can add more data sources later and even relate them together. This is a compelling feature of LightSwitch; you can federate multiple data stores, relate them together, and LightSwitch will handle selecting and updating the multiple data sources for you.  Figure 2. Once the project is created you need to define your data by creating new tables and/or attaching to an existing data source.For this project I will need to create a new database so I will choose “Create New Table”. This opens up the Entity (table) Designer which allows you to define the properties (fields) as well as relationships between entities. When you select the data type of a property you will see that there are the basic storage data types you would expect like string, decimal, integer, datetime, etc. However you’ll also notice that there are data types like Image, PhoneNumber and EmailAddress in the list. These are called custom business types and even though they are stored in the database using the basic storage types they come with additional validation, formatting and editors for free. You can also create business types of your own through the LightSwitch extensibility model. Figure 3 shows the designer with a Customer entity open. Notice that you only see one entity at a time in the designer with its direct relationships. To open another entity, click on the entity end of the relationship. You can also click on any table name in the Solution Explorer.  Figure 3. The Entity Designer is where you describe the tables, fields, business types and relationships as well as a variety of formatting and validation information.The Entity Designer is also where you write any validation rules or specify computed fields. Depending on the data type, the properties window will also display declarative validation rules that you can specify without writing any code. You can specify things like whether a field is required, its maximum length, if it should be unique, whether it is searchable, as well as numerical and date ranges and other formatting and rule enforcements. For this application I am going to need three entities; Customer, Project and Picture. Table 1, 2 and 3 describe the properties, data types and any non-default maximum lengths we need. For the Customer’s State property I want to create a choice list. A choice list lets you specify a fixed set of values that the user must select from. For this construction business in California I will limit the number of valid values to CA and bordering states, AZ, NV, OR. Another alternative to using a choice list here would be to add some custom validation that uses a regular expression to check valid state codes. I will show you how to add custom validation rules later, for now just enter the choices by clicking the “Choice List” link in the properties window and entering value and display name pairs. Summary properties are also specified here in the Entity Designer by selecting the entity itself (click the name in the blue title bar of the entity) and indicating the Summary Property in the appearance section of the properties window. Summary properties are used to describe the entity type. This determines what to display when a row of data is represented on a screen using the summary control. By default the first string property is automatically set as the summary property for you. This works nicely for the Project table but for Picture I will set the summary property to LastUpdated. For Customer, I will add a computed field for the summary property called FullName by clicking on the “Computed Property” button at the top of the designer. This sets the Is Computed property in the properties window for you and an “Edit Method” link appears. This method is where you return the value of the computed field. Computed fields are not stored in the underlying database, they are computed on the entity and only live in the data model. For FullName, I will return “LastName, FirstName”. Public Class Customer
Private Sub FullName_Compute( ByRef result As String) ' Set result to the desired field value result = Me.LastName + ", " + Me.FirstName End Sub End Class
I also need to set up relationships so that a Customer can have many Projects and a Project can have many Pictures. To set up the relationships, first select the Project entity and click the “Relationship…” button at the top of the designer to open the Add New Relationship dialog. Select Customer in the To column and specify the multiplicity and delete behavior as shown in Figure 4.  Figure 4. Setting up relationships between tables is easy, just specify the multiplicity and delete behavior you want.Repeat the same process for Picture by selecting the Picture entity and add a new many-to-one relationship to Project. Writing Custom Validation Rules I have simple data model in just a couple minutes but now I need to write some custom validation rules. You do this in the Entity Designer as well. In fact, you will spend the bulk of your time in the Entity Designer because this is where you write all of your business rules and most of the application code you write will be on your entities. If you select the dropdown arrow next to the “Write Code” button at the top of the designer you will see a plethora of methods for property validation, entity-level business rules, user access control, query, and data source methods. The first business rule I need to write will make sure that the Project StartDate is before the EndDate. Select the StartDate property on the Project entity, click the dropdown arrow next to the “Write Code” button, and select the StartDate_Validate method. Alternatively, you can select the “Custom Validation” link in the Validation section of the properties window. This creates the method stub for us. Here is where we will perform the validation rule check. Private Sub StartDate_Validate( results As EntityValidationResultsBuilder)
If Me.StartDate > Me.EndDate Then results.AddPropertyError( "Start date cannot be after the end date") End If End Sub
Next select the EndDate property and do the same thing to access the validation method for this property. Private Sub EndDate_Validate( results As EntityValidationResultsBuilder)
If Me.EndDate < Me.StartDate Then results.AddPropertyError( "End date cannot be before the start date") End If End Sub
Notice that I am specifying a rule error by calling AddPropertyError(). When a rule is in error, the user is not allowed to save the screen until the issue is resolved. You can also add warning and information messages by calling AddPropertyResult() and specifying the severity level. Warning and informational messages do not prevent the user from saving the screen. For instance, we could add a warning to the StartDate validation method if the StartDate is before the today’s date. Private Sub StartDate_Validate( results As EntityValidationResultsBuilder)
If Me.StartDate < Date.Today Then results.AddPropertyResult( "Start date is before today's date", ValidationSeverity.Warning) End If
If Me.StartDate > Me.EndDate Then results.AddPropertyError( "Start date cannot be after the end date") End If End Sub
Calling these AddProperty* methods causes the screen to display these messages in a summary control at the top of the screen as well as drawing an indicator on the control for the field. You can also specify general entity errors which aren’t related to specific fields by calling AddEntityError or AddEntityResult methods in your validation code. This will display errors only at the top of the screen. LightSwitch has a very robust validation framework that knows when to call these rules. For instance, these property rules will execute on the client first and if they pass they are executed again on the middle-tier. Additionally, LightSwitch guarantees that you are always working with the current set of data on the middle-tier so you can catch any changes other users have made to that data. This comes in handy when you are writing rules across collections of entities because you don’t have to worry about re-querying the data source and merging the changes from the client, LightSwitch handles this for you. There are a couple last bits of code I need to write for the Picture entity. I have a property called LastUpdated and I want to make sure that every time a Picture entity is created or updated that this value is updated to the current date and time. Select the LastUpdated property on the Picture entity, drop down the “Write Code” button and select the Picture_Created() method. Here is where you can set default values on your entities. Set the LastUpdated property to the current date and time. Public Class Picture
Private Sub Picture_Created() Me.LastUpdated = Date.Now() End Sub End Class
Go back to the entity designer and drop down the “Write Code” button again to access the Pictures_Updating() method. This method is on the ApplicationDataService class and runs on the server as the entity is being updated to the data source. Public Class ApplicationDataService
Private Sub Pictures_Updating(entity As Picture) entity.LastUpdated = Date.Now() End Sub End Class
Creating Screens Screens in LightSwitch are based on an extensible set of predefined templates that provide good starting points which can be customized later. Now that I have the data model designed and validation rules written, I am ready to create some screens. The better you describe your data model, the more LightSwitch can do for you when designing screens. As a matter of fact, you don’t need to create specific editing screens for an entity; LightSwitch can generate screens as needed based on your data model. I am going to need a handful of screens for this application. I want to allow the user to search for customers and projects, add new projects and new customers, as well as edit customer and project details. The project details screen will allow the user to add, edit and delete all the pictures in a project. First create the Project search screen. Right-click on the Screens node in the Solution Explorer and choose “Add Screen…” to open the Add New Screen dialog. Here is where you can select from a variety of layouts for your screens. These templates are just starting points, you have the ability to completely modify these if you want. You can also create your own screen templates through the LightSwitch extensibility model or download more from the community. Select the Search Data Screen template and for the Screen Data select Projects as shown in Figure 5.  Figure 5. You can choose from an extensible list of screen templates which provide good starting points for your screen layouts. The first screen you create by default becomes the first screen that opens when the application starts. You can change this behavior by opening the project properties and selecting the Navigation tab. I also want to allow the user to search for Customers directly if they need to so add another Search Screen and select Customers as the screen data. I also want to add a screen for adding customers. This time select the New Data Screen template and Customers for the Screen Data. Do this one more time for Projects; add a new screen, select New Data Screen and then choose Projects. Notice that you can also add child collections to these New Data screens. In the case of Customer you can also choose to add Projects and for Projects you could add Pictures. However, for this application I want to keep the New Data screens simple. Before I create the other screens I need, I want to run this application. Hit F5 to build and start the debugger. Notice at this point that you have a full-blown application shell with a screen navigation pane, a ribbon across the top with default commands and a tabbed area displaying the open screens. The application also has built in “dirty checking” right out of the box- meaning if you edit data on a screen and navigate away from it or try to close it, the application will prompt you. You can see this in action by opening the New Customer screen, filling out some data and then trying to close the screen or application as shown in Figure 6.  Figure 6. LightSwitch creates an application shell with a navigation menu pane, ribbon, a tabbed area displaying the open screens, plus a whole lot of functionality including dirty checking right out of the box.In addition to built-in features, LightSwitch applications follow N-tier architecture patterns, and incorporate best practices by default like data paging, async data loading, database concurrency checking, and well-known UI patterns to produce usable, scalable, and robust applications. All this comes for free without having to write the code yourself. I will first create a new customer to populate the development database with some data. Notice that when you click Save, LightSwitch generates an edit screen for you. I will override this behavior in a moment but it’s nice to see that you have a completely working application without having to specify every little thing. Next add a new project record. Notice that LightSwitch has created a control on this screen that allows you to choose the related customer on a project. LightSwitch knows how to create controls based on the relationships between your entities. Enter a couple customers and projects into the system and then go back to the Search Projects screen and click the Refresh button on the ribbon to reload the entire screen. Notice on the search screen you get paging, sorting, searching across all string fields, and exporting of the data to Excel all for free. You can also click on the summary control which looks like a hyperlink to open the edit screen for the Project. This screen is also automatically generated. Let me show you how you can override the default edit screens. Stop debugging, go back and add another screen. This time select the Details Screen and choose Project for the screen data. Notice that by default this will now be used as the default details screen. I also want to allow the user to manage Pictures on this screen so check the Project Pictures under the additional data to include. Hit F5 to run the application and now click on the link to a project in the Search Projects screen and notice that the screen now shows a grid of Pictures. Click the “Design Screen" button at the top-right of the application and make some adjustments to the layout as shown in Figure 7. In LightSwitch you can change the layout of screens while the application is running in debug mode. Here I made the data grid read-only and instead placed editing controls for the Picture entity to the right of the data grid. I also sized the picture editor so that it takes up most of the screen for easy viewing & editing.  Figure 7. When in debug mode, you can completely change the layout of a screen at runtime and easily see your changes take effect.When you are finished just click Save to persist the layout changes and go back to the running application. Add some pictures by clicking Add on the Pictures grid then hover over the image on the right and click the upload arrow to select a picture and upload it to the database. Notice that if you try to save the screen without specifying an image or if you make the project start date later than the end date, validation rule errors will display on the screen. One last screen I need to add is the Customer details screen. Add a new screen and this time select the Details Screen and choose Customer for the screen data, set it as the default edit screen and select Customer Projects as additional data to include. This will allow the user to add and edit multiple projects directly on the customer. However there is one behavior on this screen I want to override in the Screen Designer. The Screen Designer presents a hierarchical view of the controls on the screen based on the template you picked. The View is in the center of the designer. To the left is the View Model that shows the data collections and queries as well as any commands or other data items you add to the screen. When you write screen code you are writing code against this View Model. On the right side, the property window displays properties for the selected item in the designer as shown in Figure 8.  Figure 8. The Screen Designer presents a hierarchical view of the controls on the screen based on the template you picked. Any code you write here, you write against the View Model.I want to be able to open the Project Detail screen we created when the user clicks on the Edit… button on the Project grid. To change this behavior, expand the Command Bar under the Projects data grid, right-click on the Edit… button and select “Override Code”. This allows you to write code in the Execute and CanExecute methods for the button. However, I can only open this screen if the project record has been saved to the database. You return False from the CanExecute method to disable the button, otherwise return True to keep it enabled. Here I need to check to make sure a Project is selected as well as making sure the entity is not in an add state. You can get to entity state information by drilling into the Details property on any entity. Public Class CustomerDetail Private Sub ProjectsEditSelected_Execute() 'Open the Project details screen. Me.Application. ShowProjectDetail(Me.Projects. SelectedItem.Id) End Sub
Private Sub ProjectsEditSelected_CanExecute( ByRef result As Boolean) 'Make sure a project is selected and ' it is not a new record. result = (Me.Projects.SelectedItem IsNot Nothing AndAlso Me.Projects.SelectedItem. Details.EntityState <> EntityState.Added) End Sub End Class
Now when you run the application and open a Customer record you can edit, add, and delete the projects directly from this screen. If you click the Edit button on the grid it opens the Project Details screen we created earlier which allows you to edit the Pictures. As you can see you now have a fully working application that can manage pictures on construction projects in just a few minutes. Defining Queries There are a couple places where I could refine the application to make it better by defining queries. Queries are another important building block in LightSwitch applications. Queries allow you to set up sorts and filters as well as specify parameters to them all within the Query Designer. You can also drop to code if necessary and write LINQ statements directly. You can change queries on specific screens or you can create globally accessible queries. For this application, I want to add a query to sort the customers by name so that when the user creates a new project using the New Project screen and selects a customer, the list of choices are sorted by name. To add a query right-click on the table in the Solution Explorer that you want to base the query on, in my case Customers, and select “Add Query”. In the Query Designer name the query SortedCustomers and specify a sort on LastName, ascending then by FirstName ascending. Save the query and open the New Project screen. Click the “Add Data Item…” at the top of the screen designer and choose the SortedCustomers query. Then select the Customer control and in the properties window set the Choices from Auto to SortedCustomers. Now when the user selects a customer the list will be sorted. You can also base entire screens on queries. It would be nice to search all the pictures directly by customer regardless of the project. I will create a query with a parameter of Customer LastName and then use that as the basis of a new search screen. Add a new query called CustomerPictures based on the Pictures table, add a filter on Customer LastName and make it a parameter as shown in Figure 9.  Figure 9. The Query Designer allows you to specify sorts and filters on your entities. You can also drop to code if necessary and write LINQ statements directly by clicking the “Write Code” button.Create a new Search Data Screen and you will see CustomerPictures in the list of choices for the screen data. When you run the application and open the Search Customer Pictures screen enter a customer Last Name in the textbox at the top of the screen and hit enter or tab and the query will automatically execute and show the results. Of course, there are a lot more features you could add to this application like specifying user permissions to control access to adding, updating, deleting and even viewing entities as well as screens and queries. You could build your own custom controls, or change the theme or entire application shell by loading extensions. And there are many deployment options, even deploying to Azure. Conclusion To get started, head to http://msdn.com/lightswitch and watch training videos, read tutorials, download samples and interact with the team in our forums and blogs. We’d love to hear from you! Beth Massi |