quickly build business apps - microsoft home page | devices and
Post on 12-Sep-2021
4 Views
Preview:
TRANSCRIPT
Quickly Build Business Apps
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 second 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 this paper we’ll walk through the development of a sample LightSwitch application and
experience a wide range of LightSwitch techniques and features as we present configuration examples,
illustrating screenshots, and code listings.
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
Building Our To-Do List ............................................................................................................................. 5
Creating the Application ............................................................................................................................... 6
Defining Data .............................................................................................................................................. 10
Defining Relationships ............................................................................................................................ 11
Building Choice Lists ................................................................................................................................ 12
Building Screens .......................................................................................................................................... 12
Test by Running ....................................................................................................................................... 13
What We’ve Got; What We Need ........................................................................................................... 15
Fit and Finish ............................................................................................................................................... 16
Computed Fields ..................................................................................................................................... 16
Security ................................................................................................................................................... 17
Permissions ......................................................................................................................................... 18
Roles and Users ................................................................................................................................... 18
Coding Security ................................................................................................................................... 19
Contemplating Code ................................................................................................................................... 20
Summing Up ................................................................................................................................................ 20
Appendix ..................................................................................................................................................... 22
Entity-Level Validation ............................................................................................................................ 22
Adding and Configuring Controls ........................................................................................................ 22
Advanced Security................................................................................................................................... 24
Field Access ......................................................................................................................................... 24
Screen Access ...................................................................................................................................... 24
Some Information on Advanced Coding ................................................................................................. 25
5
Introduction This is the second 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 this first paper, we provided an overview of the product and an analysis of the market need it meets.
In this paper we’ll walk through the development of a sample LightSwitch application. You’ll see a wide
range of LightSwitch techniques and features, including:
configuration examples
illustrating screenshots
short code listings
To demonstrate the core capabilities of LightSwitch, we’ll focus on facets of the application that almost
all business applications have:
master data (lookup tables)
business rules
data validation
permissions for screen and/or feature access
The sample application discussed in this paper implements office expense tracking in the context of
budget management. In subsequent papers in this continuing series, we’ll both enhance what we
implement here, and walk through additional applications, to showcase further LightSwitch capabilities
in data access and user interface (UI) design.
Building Our To-Do List LightSwitch is an ideal tool for building applications like the one we’ll look at here. As you see in this and
subsequent papers, designing the data model and screens, then connecting to external data sources is
incredibly easy in LightSwitch. This allows us to model our expense and budget category data and build
a user interface for entering and updating that data. We then add important validation rules with
minimal effort and give the application real rigor. In the next paper, we discuss how to connect to an
external vendor database and integrate its data into one of the screens discussed here.
LightSwitch accommodates either a methodical, linear mode of development or a more iterative
approach. Business applications are best developed using a combination of these approaches. We’ll
discuss layering new capabilities in an iterative fashion in subsequent papers, but for this first
application, we’ll look at the more linear approach. To build our application, here’s what we’d need to
do:
create the LightSwitch project
design our data entities
generate screens
customize screens
add business rules
6
add security logic and user interface
test the application
As logical as this plan may be, the reality is that in building an application like the one reviewed here, we
won’t get the data design absolutely perfect before moving on to screen design, and we probably won’t
get the screens perfect before we add the business rules. Each time we move ahead to a subsequent
step, we need to revisit and perfect the work we did in the preceding steps. So let’s consider the to-do
list as a general outline knowing that between each major step, we have some loopback back to
previous ones. Now let’s see how we would create our project.
Creating the Application We begin by starting Visual Studio LightSwitch, or any other non-Express edition of Visual Studio, that
has LightSwitch installed. The examples shown in this paper use the dedicated LightSwitch edition of
Visual Studio, whose Start Page and New Project dialog box are shown in Figure 1 and Figure 2.
Figure 1: The Visual Studio LightSwitch Start Page
7
Figure 2: The New Project dialog, with LightSwitch Application (Visual C#) project type selected and project name entered
A few things about Figure 2 bear mention.
First, the Installed Templates list at the left of the New Project dialog box offers LightSwitch as
the only project template option. In other Visual Studio editions, a longer list appears so make
certain to select LightSwitch from among those options.
Next, LightSwitch Application (Visual C#) has been chosen as the LightSwitch application type in
the main area of the dialog box, and “BudgetTracker” has been entered in the solution’s Name
field.
When you click OK, LightSwitch constructs a project and the LightSwitch application designer
window opens, as shown in Figure 3.
8
Figure 3: The LightSwitch designer in its initial “Start with data” mode
At first, the LightSwitch designer appears in a “Start with data” mode. Click the Create new table link to
launch immediately into data design. This opens the Data Designer, as shown in Figure 4.
9
Figure 4: The LightSwitch Data Designer with a new table opened
Let’s discuss some designer elements shown and numbered in Figure 4 so that we can understand
better how to build data entities. Notice the following:
1. LightSwitch has created a new table named Table1Item (1) and added a property named Id, of
type Integer (2).
2. The table name text (1) is selected for edit.
3. The Id property (2) is grayed-out and cannot be edited.
4. We add additional properties by entering their names directly in the <Add Property> area of the
property table (3).
5. In addition to in-place editing in the designer, we configure various objects in our data design by
editing their properties in the Properties window (4).
6. We add relationships (and the table properties that represent them) by clicking the
Relationship… button on the designer’s toolbar (5).
7. When we’re satisfied with the preliminary design for our data entity, we generate a screen for it
by clicking the Screen… button on the toolbar (6).
10
Defining Data Before going further, let’s clarify some vocabulary. The LightSwitch Data Designer User Interface (UI)
uses the terms “Table” and “Property” and so far, we have too. We are now going to use the terms
“Entity” and “Field,” respectively, to disambiguate LightSwitch data entities from the physical tables that
store them and the fields in those entities from the properties of objects that we edit in the Properties
window.
Figure 5 depicts initial configurations we make to our entity.
Figure 5: Data Designer with Expense entity and four fields defined
Notice what changes were made:
1. The entity’s name is set to “Expense.”
2. The required fields Description, ExpenseDate, BudgetYear, and Amount are added.
3. The data types for those fields are respectively set to String (the default), Date, Integer, and
Money.
We’re not done yet. An expense entity should also track a budget category and payment method, but
you don’t want those to be free-form fields. Instead, you want to select a value from a list. LightSwitch
supports two methods for handling this. In one, the list is populated from data in the database. That
11
data comes from an additional entity in the data model to which a relationship is set from the first
entity. The other method, suitable for short lists, allows us to enter the list of options – called a “choice
list” – directly into the data model. For this application, it would be most appropriate for budget
categories to be database-driven whereas payment methods form a small enough list that we could
enter those into the model directly.
Defining Relationships To create the BudgetCategory entity, we click the New Table button in the toolbar (highlighted in Figure
5), name the resulting entity, and add a string field to it called CategoryDescription. Next, we relate this
entity to our Expense entity by clicking the Relationship… button in the toolbar. That opens the Add
New Relationship dialog box, shown in Figure 6.
Figure 6: The Add New Relationship dialog, with the BudgetCategory-Expense relationship configured
Notice that Expense is selected as the To entity, that Multiplicity is set to One for BudgetCategory and
to Many for Expense. This reflects the fact that each expense has only one budget category but that
each budget category may apply to many expenses. This is also verbalized in the highlighted statements
at the bottom of the dialog box.
12
When we click OK, we see that an Expenses field has been added to the BudgetCategory entity. If we
open the Expense entity again, we see a corresponding change.
Building Choice Lists In our final step before moving on to screen design, we set up a choice list for payment method. To do
this, we start by adding a field to the Expense entity called PaymentMethod, of type String. Using the
numbered steps shown in Figure 7, we enter a “choice list” for that field.
Figure 7: Creating a choice list for the PaymentMethod field
We are now ready to create screens for our application.
Building Screens We looked at creating two entities, and at this point we’d probably like to create screens for each one.
For the Expense entity, we simply click the Screen… button on the toolbar. This opens the Add New
Screen dialog box. Making the selections highlighted in Figure 8 and clicking OK creates a fully
functional screen for the entity.
13
Figure 8: Creating a screen for the Expense entity
Repeating the process once more, but this time selecting BudgetCategory from the Screen Data drop-
down, generates a screen for the BudgetCategory entity.
Test by Running Our application is ready to run. Press the F5 key to open the Expense entity’s screen, as shown in Figure
9.
14
Figure 9: The Expense entity editable grid screen, with no data yet defined
Figure 9 shows what LightSwitch has produced for us:
A screen (1) that is automatically configured with the standard ribbon (2) that includes Save and
Refresh buttons.
A special Design Screen (3) button that appears only during development.
A menu, with links to each of our two screens (4).
A data grid with a blank row (5) into which we may begin to enter expense data.
From here we click the Editable Budget Categories Grid link in the menu, enter some data in that
screen, and click Save. Then we return to the Expense entity’s screen and start entering our main
expense data. Figure 10 shows how this might appear.
15
Figure 10: The Expense entity screen, with two expense records entered and payment method choice list displayed
What We’ve Got; What We Need LightSwitch is so powerful and natural that you may have a tendency to take what it does for granted.
But before we go on, let’s review what steps we’ve covered to get the application shown thus far. Let’s
also discuss what we didn’t get automatically, that we probably want to add.
LightSwitch created a fully functional application where we were only required to specify the following:
2 table names
5 field name/data type pairs
1 relationship
5 choice list data items
2 screens (which were created with 5 mouse clicks each)
We didn’t have to write code, expressly create a database, design any indices, specify a database
connection, or write any queries. Yet, we can still press F5 and an application opens that has a UI shell, is
multi-tier client/server in design, has a SQL Server database, and enforces referential integrity in that
database where necessary.
16
Fit and Finish If you need a functional application built very quickly, LightSwitch is invaluable. But it turns out that
adding advanced features to a LightSwitch application is not very complicated either. To illustrate this,
we look at how to add the following features to our application:
using a computed field to automatically determine budget year from expense date
creating security for users and roles, and adding code to ensure data entities enforce that
security
If you’re interested, you can read the appendix to this white paper for details about:
storing and displaying expense data, the id of the user who entered the data, and the date and
time the expense item was entered or updated
security code that limits edit access to specific fields and which shows or hides specific menu
items
Computed Fields Adding an automatic budget year calculation is pretty straightforward. The hardest part may just be
thinking through the calculation of what month is in what budget year, so let’s start there. We first
acknowledge that a budget year might not start on January 1st. And assuming it doesn’t, then the
budget year for an expense we are entering may be the current calendar year + 1. For example, if our
fiscal year starts on July 1, 2011 and we entered an expense for August 3, 2011, then the budget year
would actually be 2012. However, if we entered an expense for June of 2011, then the fiscal year would
match the calendar year, also coming out to 2011.
To code our business logic, we’d need to know on what month of the year our fiscal year started. For
simplicity, we could start by hard-coding that value to 7 (for July). Next, we’d need to determine if the
budget year should be set to the ExpenseDate field’s year or if it must be that year plus 1. And if the
fiscal year actually did start in January (that is, if the fiscal year were actually the same as the calendar
year), then we’d need to set the budget year to the ExpenseDate year, regardless of the month entered.
We would implement our business rule by changing the Expense entity’s BudgetYear field to be
computed, and would implement our logic in the field’s code. We follow these steps:
1. Double-click the Expenses entity node in Solution Explorer.
2. Select the BudgetYear field in the Data Designer grid.
3. In the Properties window, select the Is Computed option and then click the Edit Method link
that subsequently appeared.
4. Once in BudgetYear_Compute event code, change the stub so that it contained the code shown
in Listing 1.
17
Listing 1
partial void BudgetYear_Compute(ref int result) { int FYMonth = 7; int FYYear = ExpenseDate.Year; if ((FYMonth > 1) && (ExpenseDate.Month >= FYMonth)) { FYYear += 1; } result = FYYear; }
The code in Listing 1 accomplishes the following:
Hard-codes the first month of the fiscal year to 7 (July) and stores that the integer variable
FYMonth.
Stores the Year property value of ExpenseDate to the variable FYYear.
Increments FYYear by 1 if FYMonth is greater than 1 and the Month property value of
ExpenseDate is greater than or equal to FYMonth.
Sets the function’s result parameter to the value of FYYear.
That’s all there is to it. After entering the code in Listing 1 and running the application, we can enter
different dates into the “Expense Year” column of the editable grid to see that a corresponding value
automatically appears in the Budget Year column. The cells in the Budget Year column of the data grid
are no longer editable because LightSwitch automatically changed the control type from Text Box to
Label when we changed BudgetYear to be a computed field. Even if it didn’t, we could run the
application, click the Design Screen button on the ribbon, and change the Budget Year control type
ourselves.
Security Our fit-and-finish mission continues, and you might expect it to get more difficult. Changing a field to be
computed instead of manually entered is one thing, but what about building out a full login and access
control infrastructure? It turns out LightSwitch makes that easy too. Here are the basic steps:
1. Define individual permissions in the Access Control tab of the project properties in Visual Studio.
2. Define roles and users in your application, using screens for those tasks that are generated by
LightSwitch.
3. Write code that checks to see to which role the current user belongs, then grants or blocks
certain access to entities, screens, and fields accordingly.
Does this still seem difficult? It shouldn’t, because for step 3, oftentimes a single line of code is all you
need to write. Testing that code is easy as well since the Access Control tab allows you grant or deny
any given permission, with those settings effective when your application executes in Visual Studio.
For our application, we’d likely want to define permissions for entering/editing/viewing expenses, and
for entering/editing our budget category master data.
18
Permissions
Set up permissions by double-clicking the Properties node in Solution Explorer, then clicking the Access
Control tab, and entering some permissions data, as shown in Figure 11.
Figure 11: Creating permissions
By default, the Do not enable authentication option is selected and the permissions grid is disabled, so
we need to select the Use Forms authentication option (highlighted in Figure 11) before entering data
in the grid. The permission named SecurityAdministration (also highlighted) appears by default.
Roles and Users
To create roles and users, we now simply run the application. In the menu, we see a new group of
screens labeled Administration that contains Roles and Users child options. To define roles (named
groupings of specific combinations of the permissions defined in Figure 11), we click Roles, enter role
names and their associated permissions, and then save our changes. Next, we click Users to define
named users, their passwords, and the role or roles each belongs to.
While you can create roles and users while running your application in Visual Studio, you aren’t able to
log in as any of these users. Only when entering role and user data in a deployed application run
outside of Visual Studio, do created roles and users have any effect. You can still implement code to
19
enforce the permissions and use the Granted for debug options in the Access Control project property
sheet (highlighted in Figure 11) to test the code. Let’s explore the coding side of this now.
Coding Security
We begin by granting the ExpenseEntry and ExpenseReview permissions, shown in the last two rows in
the permissions grid in Figure 11. We then add a little code to the Expense entity definition, and the UI
for any screen that maintains that data would enforce those permissions automatically.
To enter the code, we first double-click the Expenses node in Solution Explorer. Next, in the data
designer’s toolbar, we click the drop-down arrow on the Write Code… button. On the drop-down list of
events, locate the Access Control Methods section and select the Expenses_CanRead option. A stub for
that event handler opens and we modify the stub to contain the code shown in Listing 2.
Listing 2
partial void Expenses_CanRead(ref bool result) { result = Application.User.HasPermission(Permissions.ExpenseReview); }
Notice only one simple line of code is required. The code merely sets the event handler’s return
parameter to reflect the bool (true or false) value for the ExpenseReview permission as returned by the
Application.User object’s HasPermission method. Listing 3 shows the code necessary for checking the
ExpenseEntry permission within the three relevant event handlers.
Listing 3
partial void Expenses_CanUpdate(ref bool result) { result = Application.User.HasPermission(Permissions.ExpenseEntry); } partial void Expenses_CanInsert(ref bool result) { result = Application.User.HasPermission(Permissions.ExpenseEntry); } partial void Expenses_CanDelete(ref bool result) { result = Application.User.HasPermission(Permissions.ExpenseEntry); }
Using the code in Listing 3 as a guide, we modify the BudgetCategory entity and create the
implementation code for the MasterData permission shown in Figure 111.
When we run the application, we see no difference in its behavior because we granted ourselves all
permissions. However, if we deselect the Granted for debug option for the ExpenseEntry or
ExpenseReview permissions in the Access Control tab of the project properties and then run the
1 Since everyone has CanRead permissions on the BudgetCategory entity, there’s no reason to code an event
handler for it, so you don’t need to implement code to replicate Listing 2
20
application again, we see that the Expense entity’s screen becomes read-only (the grid is populated but
non-editable, and the add, edit, and delete toolbar buttons are disabled), or is completely disabled.
With a little extra code, we could make the screen disappear entirely from the menu in cases where the
ExpenseReview permission is not granted. This code is discussed in the appendix to this white paper.
For the two entities we have defined thus far, our simple application is fully built out and stable. It has a
data model, a computed field, screens, and a security subsystem. We’ll add more entities and features
in the next paper in this series. Before we wrap up this paper though, let’s learn a little bit more about
what kind of code we can write in LightSwitch.
Contemplating Code We have seen that no code is strictly necessary in a LightSwitch application. When the desired polish on
an application does require some code, oftentimes very few lines are required.
Despite the flexible requirements around code, the opportunities to integrate code in a LightSwitch
application are numerous. This is a very unusual combination. In most development environments,
there is typically a correlation between degree of programmatic control that you can have and the
amount of code you must write. With LightSwitch, you can have a lot of code but you’re not obligated
to have much at all.
Using an event handler model, LightSwitch allows developers to integrate their own code in the
following contexts:
at the data entity and field level for data workflow (updates, validation, etc.)
at the data level, for computed fields
at the UI level, for UI workflow (screen activating, closing, etc.)
at the UI level, for user interaction (button clicks, data selections, etc.)
in standalone methods in screens (which can be called from code, or custom buttons)
for access control, of UI or data
In this paper, we discussed examples of many of the above, and we provide further detail in the
appendix. We’ll discuss methods and custom buttons in Part 4 of this white paper series.
Summing Up We provided an overview of the LightSwitch product in the first paper in this series. Look at what we
covered in this paper:
creating an expense application and its database
creating data entities, relationships between them, a choice list, a computed field for budget
year, and screens to interface with all of it
developing a full access control framework:
o creating specific permissions
21
o granting or revoking specific permissions for our debug sessions to test the permissions
code before deploying an application
In the remaining three papers in this series, we will discuss several of the techniques we merely touched
upon in this paper. Here’s what to expect in the following papers in this series:
In Part 3 we’ll look at data management in greater detail (including the creation of custom
queries and parameterization of those queries).
In Part 4 we’ll provide a more detailed look at designing and customizing screens and menus.
We’ll also discuss application deployment.
In Part 5, we’ll take a look at the world of LightSwitch extensions, including integrating third
party commercial extensions into your applications.
Hopefully this paper has helped you realize the power of the LightSwitch product and provided
motivation for digging deeper into its capabilities.
For more information:
Visual Studio LightSwitch Website: http://www.microsoft.com/lightswitch
Visual Studio LightSwitch Dev Center: http://msdn.microsoft.com/lightswitch
22
Appendix We provide this appendix to go into further detail on a few of the topics covered in this white paper.
Specifically, we look at:
entity-level validation
field- and screen-level access control
additional information about integrating conventional .NET code into your LightSwitch
applications.
Entity-Level Validation We added some nice polish to our application in this paper, but we could go further. For example, we
could add audit functionality to our expense data, in which we store the name of the user who last
updated a record and the date and time the user did so. This involve adding two fields to the Expense
entity, writing two lines of code, and modifying our screen to display the audit data. Here are the entity-
related steps (you can follow along if you wish):
1. Open the Expenses entity in the Data Designer.
2. Add a Date Time field called LastUpdatedDT.
3. Add a String field named LastUpdatedBy.
4. In the Properties window for each of the two new fields, clear the Display by Default and Is
Required options.
5. On the Data Designer toolbar, on the Write Code… button, click the drop-down arrow and select
Expenses_Validate from the drop-down list (seen in the General Methods section).
6. Modify the code stub as shown in Listing 4.
Listing 4
partial void Expenses_Validate(Expense entity, EntitySetValidationResultsBuilder results) { entity.LastUpdatedDT = DateTime.Now; entity.LastUpdatedBy = Application.User.Name; }
The code sets the value of the LastUpdatedDT field to the current date and time. It also sets the
LastUpdatedBy field to the current logged in user’s user name (the Application.User object makes this
simple).
Adding and Configuring Controls
In our example, we set each of the Display by Default property of each new field to false. This is a
sensible choice for an audit field, but to test that everything’s working, we need to manually update the
EditableExpensesGrid screen to display the data. Once again, LightSwitch keeps this from being
disruptive. Instead, we must complete a small, incremental task.
23
We start by double-clicking the EditableExpensesGrid node in Solution Explorer. The screen opens in its
designer and appears as shown in Figure 12.
Figure 12: The EditableExpensesGrid screen, in its designer
The new fields (highlighted) appear under the Expenses query on the left of the screen designer. There
are two ways we could add these fields to our data grid; let’s look at each one. In the query/members
bar on the left of the designer, we drag-and-drop the LastUpdatedDT field below the Payment Method
node in the control tree. While we could repeat this for the LastUpdatedBy field, we could also:
1. Click the Data Grid Row | Expense node in the control tree (it’s the 5th one from the top).
2. Click the drop-down arrow next to the Add node (the bottom-most node).
3. From the drop-down list, click the Last Updated By option.
This adds both fields to our Data Grid control, but they would be editable. So as last steps, we click the
drop-down arrow on the Last Updated DT node and change the control type from Date Time Picker to
Date Time Viewer, then change the Last Updated By control type from Text Box to Label.
Now we run the application, edit or add some expenses, then on the application’s ribbon, we click Save.
For each new or edited row, we see the current date and time appear in the Last Updated DT column.
We also see TestUser appear in the Last Updated By column.
24
Advanced Security
Field Access
Let’s look at a security coding technique to make specific fields read-only. As an example, imagine we
had a Budget entity, with the following fields:
BudgetYear (an Integer field)
BudgetCategory (based on a relationship to the BudgetCategory entity)
RequestedAmount (a Money field)
ApprovedAmount (a Money field)
To create BudgetRequest and BudgetApproval permissions along with this entity and make sure they
properly provide (or restrict) write access to the RequestedAmount and ApprovedAmount fields, we use
code in each field’s IsReadOnly event handler. To do so, we follow these steps:
1. Select the RequestedAmount field in the grid and then click the drop-down arrow on the Write
Code… button in the data designer’s toolbar.
2. Select RequestedAmount_IsReadOnly from the Property Methods section at the top of the
drop-down list.
3. Repeat the process for the ApprovedAmount field.
4. Finally, fill out the two new stubs as shown in Listing 5.
Listing 5
partial void RequestedAmount_IsReadOnly(ref bool result) { result = !Application.User.HasPermission(Permissions.BudgetRequest); } partial void ApprovedAmount_IsReadOnly(ref bool result) { result = !Application.User.HasPermission(Permissions.BudgetApproval); }
From here, we generate a screen for the Budget entity, run the application, and confirm that the UI
enforces all the implemented permissions properly.
Screen Access
If we experiment with our application for a while, we notice an anomaly. Even if the Granted for debug
options are deselected for both the ExpenseEntry and ExpenseReview permissions, we are still able to
open the EditableExpensesGrid screen. We won’t be able to edit or view any data once inside it, but the
non-functional screen can still be loaded. We clean this up, using the steps below:
1. Open the EditableExpensesGrid screen in its designer.
2. Click the drop-down arrow on the Write Code… button in the data designer’s toolbar.
3. In the Access Control Methods section, select the EditableExpensesGrid_CanRun option.
4. Modify the stub as shown in Listing 6.
25
Listing 6
partial void EditableExpensesGrid_CanRun(ref bool result) { result = User.HasPermission(Permissions.ExpenseEntry) || User.HasPermission(Permissions.ExpenseReview); }
The code simply checks to make sure that the current user has been granted the ExpenseEntry and/or
the ExpenseReview permission, and then sets the return parameter true or false accordingly. If this
event handler returns false, the option for the Editable Expense Grid screen does not appear on the
application’s menu.
As you can see, access control in LightSwitch can be quite specific and typically only a single line of code
in the right event handler is all that is required to implement such pinpointed security logic.
Some Information on Advanced Coding We looked in detail at LightSwitch’s event model and the coding opportunities it provides. If you’re
using LightSwitch in combination with Visual Studio 2010 Professional, Premium or Ultimate editions,
you can take coding a step further through the addition of full-fledged, conventional .NET code to your
applications.
That’s because LightSwitch applications are .NET applications, and so they allow for creating standalone
.NET classes that contain their own properties and methods. These classes can then be instantiated,
manipulated, and called from any of the event handling code already discussed in this paper.
The secret to adding conventional .NET code to a LightSwitch application lies in switching Solution
Explorer from Logical View to File View by using the View button on the Solution Explorer toolbar.
Once in file view, you see that a LightSwitch project is composed of three sub-projects (one each for the
client tier, server tier, and the common data layer code. You select any of these three sub-projects and
insert a class within it. Use either the Project/Add Class… option from the Visual Studio main menu, or
right-click the sub-project’s node in Solution Explorer and then select the Add/Class… context menu
option. Again, you must be using LightSwitch in combination with Visual Studio 2010 Professional,
Premium or Ultimate edition, for these options to be available.
Further opportunities for custom code exist, including creating your own WCF data service and
connecting to it from LightSwitch, or creating a custom control or other LightSwitch extension. We’ll
cover WCF data service creation in Part 3 of this white paper series and we’ll discuss LightSwitch
extensions in Part 5.
26
Figure 13 shows the menu option selection needed to switch to File View and Figure 14 depicts Solution
Explorer after File View is selected.
Figure 13: The Solution Explorer, in Logical View, with the File View option displayed
Figure 14: The Solution Explorer, in File View
Once in file view, you see that a LightSwitch project is composed of three sub-projects (one each for the
client tier, server tier, and the common data layer code. You select any of these three sub-projects and
insert a class within it. Use either the Project/Add Class… option from the Visual Studio main menu, or
right-click the sub-project’s node in Solution Explorer and then select the Add/Class… context menu
option. Again, you must be using LightSwitch in combination with Visual Studio 2010 Professional,
Premium or Ultimate edition, for these options to be available.
Further opportunities for custom code exist, including creating your own WCF data service and
connecting to it from LightSwitch, or creating a custom control or other LightSwitch extension. We’ll
cover WCF data service creation in Part 3 of this white paper series and we’ll discuss LightSwitch
extensions in Part 5.
top related