get more from your data
TRANSCRIPT
Get More from Your Data
Visual Studio LightSwitch Technical White Paper
Author: Andrew Brust, Blue Badge Insights
Published: August, 2011
Applies to: Visual Studio LightSwitch 2011
Summary: This is the third in a series of white papers about Microsoft® Visual Studio® LightSwitch™
2011, Microsoft’s new streamlined development environment for designing data-centric business
applications. We’ll explore how to access external data sources, LightSwitch’s data capabilities, and
advanced data access and querying techniques.
2
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, e-
mail 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.
© 2011 Microsoft Corporation. All rights reserved.
Microsoft, Microsoft® LightSwitch® 2011, Microsoft® Excel, Microsoft® SQL Server®, Visual
FoxPro®, Visual Basic®, Microsoft® Windows® Azure™, are trademarks of the Microsoft group
of companies.
All other trademarks are property of their respective owners.
3
White Papers in this Series
1. What is LightSwitch?
2. Quickly Build Business Apps
3. Get More from Your Data
4. Wow Your End Users
5. Make Your Apps Do More with Less Work
4
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
5
Introduction This is the third in a series of white papers about Microsoft® Visual Studio® LightSwitch™ 2011,
Microsoft’s 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, we’ll explore:
how to access external data sources
LightSwitch’s data capabilities
more advanced data access and querying techniques
Also, in this paper’s 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 LightSwitch’s
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, we’ll look at acquiring external data in
LightSwitch, from SharePoint, from WCF RIA Services, and from external SQL Server databases.
Getting Data from SharePoint Although we have so far focused on working with SQL Server databases created by LightSwitch
specifically for applications, we have the option to connect to pre-existing and external data sources as
well. For example, LightSwitch can connect natively to SharePoint list data. Given the growing presence
of SharePoint in the enterprise and the common scenario of using SharePoint lists to store important
data, LightSwitch’s ability to connect to SharePoint is a real benefit for business application
development.
To explore this, let’s imagine that we have information on frequently used vendors stored in a
SharePoint list and that we want to integrate into the BudgetTracker application that we looked at in the
previous paper. What would be very nice, and is in fact quite easy, is to bring the vendor data into our
application as its own data entity, and create a relationship between it and the Expense entity.
6
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.
7
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.
That’s 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.
8
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.
9
Figure 5: EditableExpensesGrid screen with SharePoint-based vendor lookup data integrated
Linking to your own WCF RIA Service What happens if you have data that is not in SQL Server or SharePoint, and you need it in your
LightSwitch application? What if you have in-house systems that manage data that you want to
integrate into your LightSwitch application? What if the data that you want is in SQL Server, but you do
not have credentials to connect to it? Or what if the data wasn’t even stored in a conventional
database, but is instead managed by another application directly?
Access to corporate data is a huge, important requirement for lots of line-of-business applications, and
oftentimes, access to the most important data is neither open nor straightforward. Luckily, LightSwitch
provides a unique solution to this problem.
In most application development scenarios, the best way to interface with another application’s data is
in a loosely-coupled manner using services. In other words, developers responsible for the application
hosting the data can create services to expose it. LightSwitch supports such a scenario, provided the
developers of the source application build a WCF RIA Services interface to their data. If they do,
LightSwitch can connect right in, and yet the owners of the application retain control of their data rather
than ceding it.
WCF RIA Services can easily encapsulate data from a database. There’s tooling built right in to Visual
Studio Professional, Premium, and Ultimate to make exposing such data quite simple. But applications
that manage data in their own “Plain Old CLR Object” (POCO) classes can easily expose that data too,
and LightSwitch applications can consume such data as normal entities1. Developers who use
appropriate attributes in their source code can build RIA Services that give LightSwitch very specific
metadata. For LightSwitch, the result is entities that are perfectly configured as soon as they are
attached to.
1 Important note about building WCF RIA Services: You must have at least one method in the DomainService-
derived class with the Query(IsDefault = true) attribute applied for the service to be compatible with LightSwitch.
10
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. LightSwitch’s 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 you’re interested in more detail on how LightSwitch can work with RIA Services, see the “WCF RIA
Services Code” section of this paper’s appendix for additional information and sample code.
External SQL Server Data We have now learned about attaching to external data in SharePoint and WCF RIA Services and we have
also seen how to work with SQL Server data in databases created by LightSwitch. We have not
considered one remaining possibility, though: working with a SQL Server database created outside of
Visual Studio LightSwitch.
Before we even discuss the procedure for connecting to external SQL Server data, let’s just consider that
LightSwitch’s ability to connect to external SQL Server databases includes connectivity to cloud-based
SQL Azure databases as well, and that is a huge win for developers. Line of business applications are
excellent candidates for cloud deployment, as the developers behind these applications do not always
have the resources to provision on-site servers and even an application’s own internal SQL Server
database can be moved to SQL Azure at deployment time. LightSwitch’s approach to SQL Server
connectivity means developers can move from on-premise SQL Server to cloud-based SQL Azure, and
back again, with exactly the same skill set.
As you can see back in Figure 1, the Attach Data Source dialog box provides a Database option. If you
were to choose this and click Next, you would be prompted to select from a list of data sources or
compatible ADO.NET providers, SQL Server chief among them. In the Connection Properties dialog box,
as shown in Figure 6, you would just need to supply a server name, login credentials and the name of
the desired database, and click OK.
11
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.
Making Adjustments the LightSwitch Way Once your external database entities are available in LightSwitch, you might wish to consider the subject
of business types. LightSwitch supports special types – for example Phone, Email, and Money – that
map to string and numeric data types in the database. So inside the Data Designer, you might wish to
change the type of some string and numeric fields in your new entities to these business types. Your
LightSwitch application uses appropriate formatting and validation logic for these business types and the
structure of the underlying database is not altered.
We should point out a couple of technical notes. External tables need primary keys for their entities to
be editable. If foreign key constraints exist in the external database on any selected tables, LightSwitch
builds relationships between their corresponding entities. Entities based on external SQL Server tables
12
are not represented as tables in your application’s 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.
Real Queries for Real Apps Querying all rows from a table in an arbitrary sort order is fine for simple applications, but most business
applications require more precise querying. Many customers demand this and IT departments may not
permit deployment of applications that query tables’ entire contents. LightSwitch has developers
covered on this front as well.
Once data entities are created in LightSwitch, how do you query them precisely to work well in your
screens? In the previous paper in this series, we created an Expense entity and a BudgetCategory entity,
as well as an editable grid screen for each. The Expense entity had a relationship with the
BudgetCategory entity and therefore displayed values for it in its grid. It queries the BudgetCategory
entity to populate an AutoComplete control when in edit mode.
We considered how each of these two entities gets queried, but we looked at queries carried out in the
simplest manner possible. In our example, the entire contents of the underlying tables were retrieved
and presented in the physical order in which they were added to the tables. That was fine for an initial
discussion, but we need to get more sophisticated now.
Most business applications need to query data selectively, at least in certain contexts, filtered by some
reasonable criteria. In our BudgetTracker scenario, we certainly need to implement functionality that
would necessitate such selective querying. As a very simple example, our Expense entity’s editable grid
screen should display data only from the past year. LightSwitch can handle this rather gracefully. But
we need to understand how to create queries and manage parameters to make it all work.
Screen-Level Queries Let’s 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.
13
Figure 7: Examining the query in a screen
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.
14
Figure 8: Creating parameterized filter criteria in a query
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.
Figure 9 shows how we can define a parameter for our query.
15
Figure 9: Defining a query parameter
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 we’ve 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.
16
Figure 10: Creating a local property.
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.
2 The ExpenseDateStart parameter must be selected for this selection to be visible.
17
Figure 11: Binding a query parameter to a local property
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 screen’s 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 paper’s appendix for its
explanation and code.
If you select the local property and look at the Properties window, you’ll 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.
18
Entity-Level Queries It’s 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 you’d 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
19
We then design a screen around this query by following these steps:
1. Clicking the Add Screen button in the Query Designer’s 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 screen’s 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 paper’s 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 screen’s 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 we’ve 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.
20
With the basics of LightSwitch and the details of data design under our belts, we’re ready to go further
into the presentation layer. With that in mind, here’s what to expect in the following papers in this
series:
In paper #4 we’ll provide a more detailed look at designing and customizing screens and menus.
We’ll also discuss application deployment.
In paper #5, we’ll 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
21
Appendix
The parameterization of queries that we discussed in the body of this paper forms the design
underpinning of screens built with LightSwitch’s 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.
We’ll 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). We’ll 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.
22
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.
23
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 right-
hand 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
field’s 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 entity’s
summary property. Opening the BudgetCategory entity in its designer and clicking the BudgetCategory
entity name lets us view the entity’s properties. Figure 9 shows the Summary Property assignment in
the Properties window.
24
Figure 15: Setting an entity’s summary property
The summary property can be changed and the field used in the screen’s 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 doesn’t force you to keep those assignments. LightSwitch
saves you work but does not preempt you from doing work if you prefer to.
Detail Data: Generated Screens, Default Screens, and Modal Windows Knowing how to produce Editable Grid screens, and List and Details screens is helpful, but we still need
to get beyond displaying all of our data in lists and grids. Sometimes you need to display a single data
record, with each field’s value displayed in a separate control.
As an example, consider our vendor data SharePoint list. It contains the VendorName field that we need
to use as a lookup value in the EditableExpensesGrid screen, but it contains other useful data as well. It
includes a Boolean Preferred field and a numeric BalanceLimit field. Being able to view this detail data in
a screen linked to, but separate from, our EditableExpensesGrid screen is useful.
There are several ways to create such a separate screen. These include:
25
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.
Auto-Generated Details Screens Demonstrating the first technique is quite easy, and gives us a chance to see how in LightSwitch we can
use Customization Mode to edit the design of screens while they are running. Here are the steps
involved:
1. Execute the application, display the EditableExpensesGrid screen, and click the Design Screen
button on the ribbon.
2. Find the AutoComplete control bound to the VendorName field and click the drill-down triangle
next to it.
3. Select the Summary control within it, and set its Show as Link property to true. This is all shown
in Figure 16.
Figure 16: Setting our lookup field to Show as Link.
4. Click Save.
26
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 vendor’s data displays in a new screen, generated by LightSwitch on-the-fly.
There is no corresponding static screen in the project.
Creating Details Screens at Design Time Auto-creation of details screens is a neat feature in LightSwitch and developers don’t have to do
anything to get it. On the other hand, you might see fields displayed in a generated screen that you
wouldn’t want to be there (in our example, the CreatedBy and ModifiedBy fields). One way to remove
these is by clearing the Display by Default properties for those two fields. An even better way is to
create our own screen at design time.
To create a Details screen, we follow these steps:
1. Create a new screen for the SharePointVendor entity.
2. Use the Details screen template.
3. Select the Use as Default Details Screen option.
4. Click OK.
5. When the new screen displayed in its designer, we remove controls bound to the CreatedBy and
ModifiedBy fields from the tree.
6. Execute the application.
7. Click a SharePoint Vendor hyperlink as before, but this time see how the newly designed screen
opens instead of the dynamic one3.
Modal Windows Creating details screens at design time may provide a better experience than using LightSwitch’s
runtime-generated ones, but sometimes it’s 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 we’ll 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 query’s 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.
3 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.
27
Listing 1: Showing a modal window.
partial void ViewVendor_Execute() { this.OpenModalWindow("SharePointVendorModal"); }
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 LightSwitch’s screens also invoke screens that are
generated at run-time. In the next paper in this series, we’ll investigate how to make these standard
buttons open your own screens instead.
LightSwitch and SQL Server We’ve mentioned that LightSwitch creates SQL Server databases but we haven’t really discussed the
mechanics of how it does so. It’s nice that LightSwitch shields us from the complexity of explicitly
creating a SQL Server database during development and deploying it for test and production. But if
you’ve done much development work with databases, and especially with SQL Server, it’s useful to know
what LightSwitch is doing behind the scenes. Understanding these mechanics makes it much easier to
master the deployment process that we’ll discuss in the next paper in this series.
When it comes to LightSwitch and SQL Server, there are three things to remember:
1. LightSwitch uses SQL Server Express for development.
2. LightSwitch can use any edition of SQL Server (or Oracle and MySQL), including Express,
Standard, Enterprise, or SQL Azure for the deployed database.
3. If authentication is enabled for your application, then LightSwitch adds to your database a
number of tables, views, and stored procedures used by the ASP.NET membership service.
Let’s look at each of these points in a bit more detail.
On the development side, LightSwitch uses SQL Server® Express Edition®, in a special “user instance”
mode. This mode, first introduced with SQL Server 2005, allows a unique instance of SQL Server (as
opposed to a default or named static instance) to be created dynamically. This instance runs under the
identity of the current user, and operates without elevated permissions. Because the instance is
dynamic, a LightSwitch application’s development database has to be attached dynamically too.
28
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 it’s 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.
WCF RIA Services Code Attributes can be applied in WCF RIA Services code so that certain field properties in the connected
LightSwitch entity are configured automatically. The class definition in Listing 2 defines a class called
DivisionRecord with properties DivisionID and DivisionName. Connecting to it results in a LightSwitch
entity named identically to the class with fields named identically to the properties. The code contains
attribute settings to affect the following property settings on the LightSwitch side automatically:
the field DivisionID becomes the primary key field for the DivisionRecord entity
the Is Required property of the DivisionName field is set to true
its Maximum Length property is set to 50
its Display Name is set to The Division’s Name
its Description is set to Name of the Division
29
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.
Setting Screen-Level Query Parameter Values Listing 3 shows the event model code necessary to initialize the value of a screen’s local property. It
ensures that the screen-level query described in the “Screen-Level Queries” section of this paper
contains expense data that is at most 1 year old.
Listing 3: Setting our local property to the year-ago date, which value is passed into the query parameter
partial void EditableExpensesGrid_InitializeDataWorkspace(List<IDataService> saveChangesTo) { this.ExpenseDateStartProp = DateTime.Now.Subtract(new System.TimeSpan(365, 0, 0, 0, 0)); }
The code simply uses today’s date, subtracts 365 days from it to get the previous year’s 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 year’s 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.