Summary: This is the third in a series of white papers about Microsoft Visual Studio LightSwitch 2011, Microsofts new streamlined development environment for designing data-centric business applications. Well explore how to access external data sources, LightSwitchs data capabilities, and advanced data access and querying techniques.
Copyright
The information contained in this document represents the current view of Microsoft Corporation on the issues discussed as of the date of publication. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information presented after the date of publication. This white paper is for informational purposes only. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED, OR STATUTORY, AS TO THE INFORMATION IN THIS DOCUMENT. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in, or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation. Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property. Unless otherwise noted, the example companies, organizations, products, domain names, email addresses, logos, people, places, and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, place, or event is intended or should be inferred.
Microsoft, Microsoft LightSwitch 2011, Microsoft Excel, Microsoft SQL Server, Visual FoxPro, Visual Basic, Microsoft Windows Azure, are trademarks of the Microsoft group of companies.
Contents
Introduction .................................................................................................................................................. 5 Getting Data from SharePoint ...................................................................................................................... 5 Linking to your own WCF RIA Service ........................................................................................................... 9 External SQL Server Data ............................................................................................................................ 10 Making Adjustments the LightSwitch Way ............................................................................................. 11 Real Queries for Real Apps.......................................................................................................................... 12 Screen-Level Queries .............................................................................................................................. 12 Entity-Level Queries ................................................................................................................................ 18 Conclusion ................................................................................................................................................... 19 Master-Detail Screens ................................................................................................................................. 21 Summary Properties ............................................................................................................................... 23 Detail Data: Generated Screens, Default Screens, and Modal Windows ................................................... 24 Auto-Generated Details Screens ............................................................................................................. 25 Creating Details Screens at Design Time................................................................................................. 26 Modal Windows ...................................................................................................................................... 26 LightSwitch and SQL Server ........................................................................................................................ 27 Sample Code ............................................................................................................................................... 28 WCF RIA Services Code ........................................................................................................................... 28 Setting Screen-Level Query Parameter Values ....................................................................................... 29
Introduction
This is the third in a series of white papers about Microsoft Visual Studio LightSwitch 2011, Microsofts new streamlined development environment for designing data-centric business applications. In the first paper, we provided an overview of the product and an analysis of the market need it meets. In paper #2, we provided and discussed the steps involved in the development of a sample LightSwitch application. In this paper, well explore: how to access external data sources LightSwitchs data capabilities more advanced data access and querying techniques
Also, in this papers appendix, we provide details about: creating Master-Detail screens, and how they utilize queries and parameters creating Detail Data screens or screen elements that expose and take advantage of LightSwitchs underlying data capabilities how LightSwitch works with SQL Server in development and after deployment
In general, this paper gives you a greater understanding of how LightSwitch works with data and not just the mechanical steps required to make it do so. To begin, well look at acquiring external data in LightSwitch, from SharePoint, from WCF RIA Services, and from external SQL Server databases.
To connect to a SharePoint list, LightSwitch requires that it be present on a server running SharePoint 2010, with WCF RIA Services installed. As long as the prerequisites are met, connecting to the data is easy. The steps to bring SharePoint data into LightSwitch are as follows: 1. Start by right-clicking the Data Sources node in Solution Explorer and selecting Add Data Source from the context menu. The Attach Data Source Wizard opens, as shown in Figure 1.
Figure 1: The Attach Data Source Wizard, with SharePoint selected as the data source
2. Next, select SharePoint as the data source and click Next. 3. Type the URL and credentials for the SharePoint site containing the desired list (but not a link to the list itself) and click Next. The wizard displays a tree view of all lists on the site.
4. Select the list(s) you want and a name for the data source, as shown in Figure 2.
Figure 2: Attaching a LightSwitch application to a SharePoint list
5. Click Finish.The new data source and entities are added to our application. This is easily observed in Solution Explorer as shown in Figure 3.
Figure 3: The Solution Explorer window reflects the addition of our SharePoint data source and lists
In the example shown in Figure 2 and Figure 3, the UserInformationLists list was selected by default. Thats reasonable given that user-created lists in SharePoint have relationships with UserInformationLists to properly reflect the identities of the users who created and modified each list item. You see the relationship in the Data Designer, which opens automatically after you have connected to the list. This is shown in Figure 4. 7
Figure 4: A SharePoint list-based entity and its relationship to the UserInformationLists entity.
We could now easily integrate this data with the data native to our application. We simply open the Expense entity in the Data Designer and add a relationship between it and the SharePointVendor entity. When we do this, we see two fields added to the Expense entity: one for the SharePointVendor entity one named SharePointVendor_Id (a byproduct of how LightSwitch handles external SharePoint data)
With all this done, we simply add a control to the EditableExpensesGrid screen that is bound to the SharePointVendor field, and we have a drop-down list of vendors. This is shown in Figure 5.
Important note about building WCF RIA Services: You must have at least one method in the DomainServicederived class with the Query(IsDefault = true) attribute applied for the service to be compatible with LightSwitch.
If LightSwitch only allowed its applications to work directly against SQL Server and SharePoint data, IT departments in many companies might object to its use. Sometimes direct access to corporate database tables is not permitted. At other times, data might be kept in an unconventional database that LightSwitch might not connect to directly. LightSwitchs ability to connect to WCF RIA Services ensures that the custodians of the desired data (be they IT employees or other developer teams) can safeguard their data properly and still grant LightSwitch applications the permission to read it or modify it. If youre interested in more detail on how LightSwitch can work with RIA Services, see the WCF RIA Services Code section of this papers appendix for additional information and sample code.
10
Figure 6: The Connection Properties dialog box, for an external SQL Server database
Back in the wizard, you are presented with the tree view of tables and/or views for which you would like LightSwitch to create entities. After you made these choices and clicked Finish, the entities would be added to your project under their own data source. You could then treat them as you would entities created natively in LightSwitch.
are not represented as tables in your applications own database. (This is discussed in more detail in the LightSwitch and SQL Server section in the appendix to this document.) Creating a database from inside LightSwitch is straightforward. But as in other cases, LightSwitch lets you employ more advanced options if you want to. Using external SQL Server databases in LightSwitch lets you or a database administrator design your database in a very precise way, with LightSwitch still able to use it. Different developers have different preferences on this matter, and LightSwitch accommodates each of them.
Screen-Level Queries
Lets start with queries. We have actually been using them all along. Every time we have built a screen on an entity, a query against that entity was added to that screen. The presence of queries in screens is actually exposed quite plainly by the screen designer. Figure 7 shows the EditableExpensesGrid screen from the previous paper in this series, in design mode, with the query against the Expense entity highlighted.
12
Notice the highlighted paging-related properties toward the lower-right hand corner of Figure 7. Paging assures that even if the query were designed to query an entire table, that only a certain maximum number of records (45 in this case) would be fetched and displayed at a time. Paging is enabled by default and helps assure that LightSwitch applications do not burden corporate database servers with heavy, resource-intensive queries. The Edit Query link (toward the upper-left hand corner of the screen designer) is our clue that there is a true query being executed against the entity and that we can modify it. If you click that link, the screen designer enters its query design mode, where you can supply filter and sort criteria. If you like, your criteria can be based on parameters, so the bottom section of the designer allows you to create parameters and then use them in the query. Figure 8 shows how we might change our query to select only expenses made on or after a certain date, and create a parameter to store that date.
13
As is shown in Figure 8, clicking the Add Filter link adds a row where a conditional statement can be entered. Notice the following: The Where criterion is selected (the other choice is Where Not). ExpenseDate is the field used for filtering. The >= operator indicates that ExpenseDate should be equal to or greater than a certain date. The Parameter option (which persists as an @ sign) is the source of the filter value. (The other choices are literal, property, and global.) Lastly, we select Add New to create the parameter.
14
The numbered steps in Figure 9 depict: 1. Where we enter the name (ExpenseDateStart) and type (Date) of the parameter. 2. How the entered name affects the parameter operand in the filtering expression. 3. Where to click the Back to EditableExpenseGrid link once weve finished. After our query is parameterized, we need to have a place at the screen-level where that value for the parameter could be stored (and eventually passed to the query parameter itself). Figure 10 depicts, also in numbered steps, how to create a local property for this purpose.
15
Our steps thus far would create a parameter in the query called ExpenseDateStart and a property in the screen, called ExpenseDateStartProp. Figure 11 shows both of these highlighted, on the left side of the screen designer. It also shows the setting in the Properties window necessary to bind the query parameter to the local property2.
16
Once the Parameter Binding property is set, a connecting arrow appears on the left of the screen designer linking the query parameter to its source local property. The connecting arrow is not depicted in Figure 5. Our final step is to write a line of code for the screens InitializeDataWorkspace event to set the value of the local property to the year-ago date. This ensures that the screen displayed only data from the past year. See the Setting Screen-Level Query Parameter Values section of this papers appendix for its explanation and code. If you select the local property and look at the Properties window, youll see an Is Parameter option is present. When selected (which is not the case in our example above), the local property becomes a screen parameter and is accessible by other screens. This allows selections to be made in one screen which can drive the property value (and by extension, the query parameter value) in the second screen. This works nicely in situations where there is a one-to-many relationship between data entities, but where those entities are maintained in separate screens. It allows an entity to be selected in one screen, and then launch a second screen, through a button click or other user interface (UI) action in a mode where the child data is displayed.
17
Entity-Level Queries
Its important to know that as convenient as screen-level queries are, it is typically more sensible to build the queries inside entities themselves. Entity-level queries can also have filter and sort criteria, and be parameterized. They can then potentially be used in multiple screens, with the query editing work being done just once. There are two ways to create an entity-level query: In Solution Explorer, right-click the entity on which youd like the query built, and choose Add Query from the context menu. Or Alternately, if the source entity is open in the Data Designer, click the Query button in its toolbar.
Either action opens the Query Designer, which looks and works just like the screen designer in query design mode. As an example, we create a query identical to the one we just created in our EditableExpensesGrid screen, naming it something logical like ExpensesInLastYear. Figure 12 depicts the design for such a query and also highlights how that query appears in Solution Explorer (after it is saved), indented under its parent entity.
Figure 12: Designing an entity-level query
18
We then design a screen around this query by following these steps: 1. Clicking the Add Screen button in the Query Designers toolbar to create an editable grid screen based upon this query (rather than on the underlying Expense entity directly). 2. Add the code to the new screens InitializeDataWorkspace event handler set a local property value that is passed to the query parameter. (The code appears in Listing 3 in the Setting Screen-Level Query Parameter Values section of this papers appendix.) If you performed these steps, you see that the new screen behaves identically to the original EditableExpensesGrid screen. The potential re-use of entity-level queries is reason enough to use them, but there are other benefits as well. When you base a screen on the entity-level query, several things happen automatically: The screens own query is filtered and sorted identically to the entity-level query from which the screen was generated. A local property is added to the screen. The query parameter is bound to the local property.
The automatic property generation and binding of the parameter to the property means that the manual work shown in Figure 10 and Figure 11 for a screen-level query is not necessary when you use an entity-level query. This underscores a point weve been making all along: with a little planning, LightSwitch lets you create powerful applications with minimal effort and code.
Conclusion
In this paper, we looked look at a number of LightSwitch data features: linking to external data in SharePoint connecting to custom WCF RIA Services linking to external SQL Server databases entity- and screen-level queries and parameters
With that coverage, you are able to understand a few related concepts very quickly. So in the appendix that follows this section, we also discuss: master-detail data creation of detail data screens and modal windows how LightSwitch and SQL Server work together
Again and again, we see how LightSwitch is logical and consistent yet flexible and extensible. We discovered how LightSwitch handles external data and we got a better understanding of queries, and the mechanics of query design.
19
With the basics of LightSwitch and the details of data design under our belts, were ready to go further into the presentation layer. With that in mind, heres what to expect in the following papers in this series: In paper #4 well provide a more detailed look at designing and customizing screens and menus. Well also discuss application deployment. In paper #5, well take a look at the world of LightSwitch extensions, and integrating third party commercial extensions into your applications.
For more information: Visual Studio LightSwitch Website: http://www.microsoft.com/lightswitch Visual Studio LightSwitch Dev Center: http://msdn.microsoft.com/lightswitch
20
Appendix
The parameterization of queries that we discussed in the body of this paper forms the design underpinning of screens built with LightSwitchs List and Details screen template. As it turns out, the mapping of local properties to query parameters underlies screens built with the Details screen template. And a discussion of Details screens allows us to introduce the important LightSwitch concept of summary properties. Well discuss all of that in this appendix. And for those readers who are curious to know, we also provide details of how LightSwitch works with SQL Server (including Express Edition for development and all SQL Server editions for deployed applications). Well also provide and annotate the sample code mentioned, but not detailed, in the body of the paper.
Master-Detail Screens
The screen building discussed in this paper and the previous one has focused exclusively on the Editable Grid screen template. This screen template format works fine as a general-purpose view-and-edit UI, but it has its limits. For example, showing master and detail data on the same screen calls for a different approach. The built-in List and Details screen template works well for such hierarchical data presentations. In our BudgetTracker application scenario, we could use this screen template to display budget categories in a list and all expenses for the selected category in an adjacent grid. As different budget categories were selected in the list, the population of the grid changes to reflect it. We could follow these steps to add such a screen: 1. Click the Screen button on the Data Designer toolbar (or right-click the Screens node in Solution Explorer) and select Add Screen from the context menu. The Add New Screen dialog opens. 2. Select List and Details Screen from the template list on the left. 3. Select BudgetCategories from the Screen Data drop-down list on the right. Two options appear immediately below it: one for the BudgetCategory data (which goes in the list) one for the child Expense data (which goes in the grid) Select both options. 4. Assign a useful name for the screen, like ExpensesByCategory. The dialog box appears as shown in Figure 13.
21
Figure 13: Configuring a List and Details screen for Expense and BudgetCategory data
5. Click OK to run the application and then click the menu link for our new screen. It appears as shown in Figure 14.
22
Figure 14: List and Details screen showing expense data for the selected Telecommunications budget category
Users click any budget category in the left-hand list and see all expenses for that category in the righthand grid. The selected category description is repeated in a read-only text box above the grid. Users type the first few letters of a category name into the search box in the left-hand list to narrow the list of categories, or even whittle it down to one specific category if the search string were specific enough. The sort order of the left-hand list is changed by clicking the drop-down arrow just below the search fields magnifying glass icon. By default, the categories are listed by ID, but by changing the Sort by: selection in the drop-down list, users sort them by description instead.
Summary Properties
A question arises: how did the screen generator know to use CategoryDescription as the sole field in the in the left-hand list? The answer is that this field is configured to be the BudgetCategory entitys summary property. Opening the BudgetCategory entity in its designer and clicking the BudgetCategory entity name lets us view the entitys properties. Figure 9 shows the Summary Property assignment in the Properties window.
23
The summary property can be changed and the field used in the screens List control can be a property other than the summary property. Remember, LightSwitch assigns default values based on very reasonable inferences about your data, but doesnt force you to keep those assignments. LightSwitch saves you work but does not preempt you from doing work if you prefer to.
24
Letting LightSwitch create one for us at run-time simply by configuring the AutoComplete control bound to the VendorName field to display the vendor name as a link. Generating a screen at design time in LightSwitch using the Details screen template. Creating a Modal Window control group (in the EditableExpensesGrid screen) that displays SharePointVendor data and adding a button to display it.
4. Click Save. 25
5. In the application, we click the SharePoint Vendor drop-down for any row in the grid and see that each vendor displays as a link. 6. Click any of those links. The corresponding vendors data displays in a new screen, generated by LightSwitch on-the-fly. There is no corresponding static screen in the project.
Modal Windows
Creating details screens at design time may provide a better experience than using LightSwitchs runtime-generated ones, but sometimes its nice to have such data displayed in a pop-up window, rather than a full-fledged screen. This process is a bit verbose to describe, so well do so at a high level. Here are the steps required: 1. In the EditableExpensesGrid screen, add a screen-level query against SharePointData.SharePointVendors_SingleOrDefault. 2. Bind the querys Id parameter to Expenses.SelectedItem.SharePointVendor.Id. 3. Add a new controls group to the screen that is bound to this query, name it SharePointVendorModal, and set its type to Modal Window. 4. Remove any fields from the group which you do not want displayed. 5. Add a new button to the toolbar and set its Execute code to be similar to the code in Listing 1.
The new screen automatically contains a parameterized query, and a local property whose Is Parameter option is selected. As discussed in the Screen-Level Queries section of this paper, this makes the screen itself parameterized and allows the linkage from the EditableExpensesGrid screen to work.
26
The code displays the SharePointVendor record in a modal window. The data is read-only, unlike in the last two examples, but this is still a great way to display detail data on-demand without using any real estate in the main screen. If screen real estate was not an issue and we wanted to display the SharePointVendor data on the EditableExpensesScreen screen itself, we simply change the Modal Window container to another layout type (for example, Rows Layout) and the data is added to the main screen. No other modifications are necessary and can we even make the change in the Customization Mode (shown in Figure 16) while the application is executing. Such flexibility is a key value proposition of LightSwitch. The standard edit and add toolbar buttons on LightSwitchs screens also invoke screens that are generated at run-time. In the next paper in this series, well investigate how to make these standard buttons open your own screens instead.
27
Accordingly, the database exists as a standalone file named ApplicationDatabase.mdf in the /bin/data folder under the main project folder. The development database contains: a table for each entity in the ApplicationData data source ASP.NET membership tables (if authentication is enabled) a RolePermissions table (which contains the association data between the roles and permissions defined for your application).
If all of entities are based on external data and authentication is not enabled, then none of the above is necessary and LightSwitch does not create a SQL Express application database. Things change a bit once an application is deployed. First, the deployed database is statically attached to a named or default instance of SQL Server (even if its Express) or SQL Azure. Second, the database is named identically to the application (in the application we have been discussing, the database name is BudgetTracker). If all your entities are based on external tables and authentication is not enabled, then no database is deployed at all, as no database was created for development and the application uses external data sources exclusively. Assuming a database is deployed, the tables in it are the same as those in the development database. No entity data is copied to the deployed database, and the ASP.NET membership and RolePermissions tables, if they exist, do not have their data copied over either. This is to allow the production database to have its own authentication and authorization data that is not polluted by the corresponding data created during development.
Sample Code
In this last section we look at sample code that further illustrates two topics discussed in this white paper: using attributes in WCF RIA Services code and setting the parameter value for a screen-level query.
28
Listing 2: Use of attributes in a RIA Services POCO class to pre-configure certain LightSwitch entity field properties
public class DivisionRecord { [Key] public int DivisionID { get; set; } [Required(), StringLength(50), Display(Description="Name of the Division", ShortName="The Division's Name")] public string DivisionName { get; set; } }
The attributes shown in Listing 2 require using (or Imports in VB .NET) the System.ComponentModel.DataAnnotations namespace in the source code.
The code simply uses todays date, subtracts 365 days from it to get the previous years date, and then assigns that result to be the value of the local property created in Figure 10. Since the property is bound to the query parameter, the query is then automatically configured to return data where the ExpenseDate field is equal to or greater than the previous years date. To test this, you would: 1. Run the application. 2. Create a record with an expense date greater than 1 year old. 3. Click the Refresh button on the ribbon. The record you just entered should disappear, proving that the entity-level query filter works.
29