Tải bản đầy đủ

1207 pro visual studio lightswitch 2011 development

BOOKS FOR PROFESSIONALS BY PROFESSIONALS ®

Leung
Duran

RELATED

Pro Visual Studio LightSwitch 2011
Development
Pro Visual Studio LightSwitch 2011 Development helps you build advanced business applications with Microsoft’s powerful development tool. It shows you how to go
beyond the basics, yet still retain the elegance and convenience offered by Visual Studio
LightSwitch 2011. Authors Tim Leung and Yann Duran—both awarded Microsoft 2011
Community Contributor Awards for their LightSwitch expertise—detail everything you
need to know to take the next step using Microsoft Visual Studio LightSwitch 2011.
With Pro Visual Studio LightSwitch 2011 Development, you’ll learn how to design
complex screens, query data using LINQ and other syntax structures, secure your
application, and more. This book shows you how to:
• Design tables and relationships to store your data
• Specify advanced query expressions using LINQ
• Master the intricacies of complex user interface design
• Write custom .NET code to enhance LightSwitch

• Handle events in code and debug applications
• Reuse your code across projects by writing extensions
• Secure your applications by using access control techniques
• Improve performance and aggregate data using RIA Services
If you’ve already mastered the basics of LightSwitch and are looking to do more, turn
to Pro Visual Studio LightSwitch 2011 Development and find all that you need to take
the next step. This book gives you the knowledge and skills you need to build, enhance
and deploy advanced business applications using Visual Studio LightSwitch 2011.
US $49.99
Shelve in
.NEt
User level:
Intermediate

SOURCE CODE ONLINE

www.apress.com

www.it-ebooks.info


For your convenience Apress has placed some of the front
matter material after the index. Please use the Bookmarks
and Contents at a Glance links to access them.

www.it-ebooks.info


Contents at a Glance
 About the Authors................................................................................................ xxi
 About the Technical Reviewers .......................................................................... xxii
 Acknowledgments ............................................................................................. xxiii
 Foreword ........................................................................................................... xxiv
 Introduction ........................................................................................................ xxv
 Part 1: Introducing Office 365 to LightSwitch Concepts.........................................1
 Chapter 1: Forms Over Data and Beyond ................................................................3
 Chapter 2: Working in Visual Studio .....................................................................23
 Part 2: Working With Data ....................................................................................51
 Chapter 3: Working with Data...............................................................................53
 Chapter 4: Accessing Data from Code ..................................................................89


 Chapter 5: Validating Data ..................................................................................123
 Chapter 6: Querying Data....................................................................................147
 Part 3: Interacting With Data ..............................................................................197
 Chapter 7: Creating and Using RIA Services .......................................................199
 Chapter 8: Creating and Using Screens ..............................................................225
 Chapter 9: Creating and Using Custom Controls................................................337
 Chapter 10: Creating and Using Extensions........................................................365
 Part 4: Getting Data Out ......................................................................................473
 Chapter 11: Creating and Displaying Reports.....................................................475

iii

www.it-ebooks.info


 Chapter 12: Creating and Sending Emails ..........................................................525
 Part 5: Securing Your Application ......................................................................549
 Chapter 13: Authenticating Your Users ..............................................................551
 Chapter 14: Authorization...................................................................................565
 Chapter 15: Auditing What Your Users Do ..........................................................595
 Part 6: Deployment .............................................................................................613
 Chapter 16: Deploying Your Application .............................................................615
 Chapter 17: When Things Don’t Go Quite Right...................................................663
 Appendix A: Culture Names ................................................................................679
 Appendix B: LINQ Query Operators .....................................................................687
 Index ...................................................................................................................689

iv

www.it-ebooks.info


Introduction
We’ve designed this book to show you how to write professional applications using Microsoft
LightSwitch.
As software developers, we understand how difficult it is to develop software in real life. End
users expect their applications to be reliable, functional, and polished. They’ll also have preferences in
terms of how they want their application to look and feel.
To help you meet these real-life expectations, we’ve focused this book on many of the typical
scenarios that customers or clients will ask of you. For example, we’ll show you how to perform various
tasks that are not natively supported. These include creating reports, sending email, and working with
data in nonstandard ways.
To make life easy for you, LightSwitch hides away much of what it does. This is great when
you’re a beginner. But if you need to create some advanced applications or if you just happen to be
curious, this can soon become a hindrance. To help you as much as possible, we’ve tried to focus on the
following:


Describing what LightSwitch does beneath the surface



Showing you where and how to write code in LightSwitch
If you come from the following background, you’ll be sure to get the most out of this book:



You have some programming experience, either with .NET or some other
programming language environment.



You have a basic understanding of database concepts such as tables, columns,
and data types.



You’ve installed LightSwitch and have spent some time familiarizing yourself with
the development environment.

However, don’t worry if you don’t meet the exact profile that we’ve just described. We’ll now
guide you through a few of the basics to get you started.

Understanding the Basics
Although we’ve targeted this book at those with some development experience, don’t worry if you’re
only just starting out. The book explains everything that you need to know.
But if you want to ground yourself a bit more in the basics, we recommend that you visit the
LightSwitch Developer Center at the following URL:
http://msdn.microsoft.com/en-us/lightswitch/ff796201

xxv

www.it-ebooks.info


 INTRODUCTION

Through the developer center, you’ll find the latest news on LightSwitch as well as links to the
MSDN help and forums. You’ll also find links to a series of how to videos that we highly recommend. The
star behind these videos is Beth Massi, and she has kindly spoken to us about her role as the LightSwitch
community manager.

A Word from the LightSwitch Community Manager
My name is Beth Massi and I’m currently the community manager for the Visual Studio LightSwitch Team at
Microsoft. My professional programming career started in the 1990s using Clipper and FoxPro to build information
systems for the health-care industry. I remember back then, just out of college, how these rapid application
development (RAD) languages and tools made it so much easier to build database applications for businesses,
especially over the alternatives at the time. I also remember how helpful the community was for newbies like me.
There was always a feeling of “no question is a stupid question” on the forums, and almost everyone was excited
and welcoming to me. Because of my passion for these RAD tools and the closeness of that community, I built
many valuable relationships that took my career to the next level. I started to give back by writing and building free
application frameworks and then eventually speaking at user groups and conferences. As the years flew by, I
moved to VB.NET and Visual Studio and brought the same passion for the developer community with me, which
helped me get my first Solutions Architect MVP award in 2005.
After being an MVP for a few years, Microsoft approached me to help them with the Visual Basic
developer community. I couldn’t pass up the opportunity to be a part of the community as an official Microsoft
employee. I produced hundreds of articles and videos and delivered presentations all over the world. I’ve met
many types of developers doing many interesting things and have helped people troubleshoot many interesting
problems. Microsoft has given me the ability to reach the entire world, and I will always appreciate that.
Even before the first beta of Visual Studio LightSwitch was available, internally I was begging to be part of the
LightSwitch team. I wanted to use the successes I had with the Visual Basic community to help kick-start a new
community on one of the most RAD development environments I had seen come from Microsoft in a very long
time—especially one that focused on building business applications. I felt the nostalgia of the old dBase
community I started from and wanted to foster a similar vibe. So when the first beta for Visual Studio LightSwitch
was released at the end of 2010, I had the opportunity to become the community manager for the team and I
jumped on it.
First order of business was to create a slew of training content and erect a web site on MSDN called the
LightSwitch Developer Center (http://msdn.com/LightSwitch). This is your one-stop-shop for videos, articles,
samples, starter kits, and much more to get you productive quickly. The site continues to grow as we build more
content every week. If you are new to LightSwitch, I encourage you to visit the learning center Getting Started
section (http://bit.ly/LearnLightSwitch) as well as the How Do I videos
(http://bit.ly/LightSwitchVideos). From the LightSwitch Developer Center, you can easily get to our forums
(http://bit.ly/LightSwitchForums), where we have an active community helping answer questions with
LightSwitch team members. You can also see the latest blogs on the home page from our LightSwitch bloggers,
including the LightSwitch Team (http://blogs.msdn.com/LightSwitch) and myself (www.BethMassi.com).
Finally, I encourage you to join the conversation on Twitter (@VSLightSwitch) as well as our Facebook page
(facebook.com/VSLightSwitch) and let us know what you think!

xxvi

www.it-ebooks.info


 INTRODUCTION

I am confident that the LightSwitch community will continue to grow and that I will see newbies
become MVPs just as I did so many years ago. I couldn’t be happier to help nurture the community in the
goodness that is Visual Studio LightSwitch. Enjoy!

Where to Download LightSwitch
To get started, you’ll need to download and install LightSwitch. You can download a free 90-day trial by
following the link at the developer center. On the download page, you’ll have a choice of downloading a
web installer (3.7MB) or the full LightSwitch CD in ISO format (577MB). The web installer detects the
components that are installed on your machine and installs only the additional components that are
needed.
The full ISO download is ideal if you want to install LightSwitch on multiple machines, or if you
suspect that you’ll need to reinstall LightSwitch at some point in the future.
If Visual Studio 2010 is already installed on your computer, LightSwitch integrates itself into
your existing Visual Studio 2010 installation. If not, LightSwitch installs itself as a stand-alone product.
When you’re ready to purchase LightSwitch, you can do so by clicking Help ä Register Visual
Studio 2011 from within LightSwitch. This opens a dialog box displaying a button that takes you to the
Microsoft Store, enabling you to purchase LightSwitch. You’ll receive a product key at the end of the
process.

You can then convert your trial version into the full version by entering your product key.

xxvii

www.it-ebooks.info


 INTRODUCTION

System Requirements
To create applications by using LightSwitch, your development computer needs to meet the following
specifications.
The operating system requirements are as follows:


Windows 7 (x86 and x64)



Windows Vista (x86 and x64) with Service Pack 2—all editions except Starter
Edition



Windows XP (x86) with Service Pack 3—all editions except Starter Edition



Windows Server 2008 R2 (x64)—all editions



Windows Server 2008 (x86 and x64) with Service Pack 2—all editions



Windows Server 2003 R2 (x86 and x64)—all editions



Windows Server 2003 (x86 and x64) with Service Pack 2 (Users will need to install
MSXML 6, if it is not already present.)
The hardware requirements are as follows:



Computer with a 1.6GHz or faster processor



1024MB RAM (1.5GB if running in a virtual machine)



3GB of available hard-disk space



5400RPM hard drive



DirectX 9–capable video card running at 1024×768 or higher-resolution display

How This Book Is Structured
The book is divided into six main parts:


Part 1: LightSwitch Concepts



Part 2: Working with Data



Part 3: Interacting with Data



Part 4: Getting Data Out



Part 5: Securing Your Application



Part 6: Deployment

In the first part, we describe the architecture behind LightSwitch and explain the parts that
make up a LightSwitch application.
Part 2 focuses on data. We show you how to design tables, write queries, access data via code,
and how to validate your data.

xxviii

www.it-ebooks.info


 INTRODUCTION

Part 3 shows you how to use RIA Services to perform more-sophisticated tasks using data. It
also introduces the screen designer and explains that you’re not just limited to the controls that
LightSwitch provides. The custom controls chapter shows you how to go beyond the controls that are
natively provided. We also show you how to reuse code by creating extensions.
In part 4, we show you how to create reports and how to send emails.
Part 5 explains how to restrict what your users can or can’t do in your application. We also show
you how to audit the activity that takes place in your application.
Part 6 shows you how to deploy your application. It also includes a troubleshooting section that
shows you what to do when things go wrong.

Conventions
The following sections describe conventions used throughout this book.

Examples
To give this book a bit of real-life feel, we’ve based many of our examples on a fictional company. This
company specializes in selling healthy organic snacks through the Web.
The snacks are delivered by mail, and the business model works by means of subscription.
There are three types of subscription (bronze, silver, gold), and these are priced on a monthly basis. Each
subscription type entitles you to a number of free snacks per month, and higher-level subscriptions
entitle you to receive more food packages and a greater variety of food.
The company has embraced LightSwitch and has started using it throughout all parts of the
business.
The office workers use an application called OfficeCentral. This application supports the
activities that take place in the office and includes features such as the following:


Timesheet



Expenses



Project codes



Holiday request tracking



Purchase order tracking



Invoice tracking



Asset tracking



Accident report book



Staff home contact details

The staff responsible for shipping the deliveries works from a warehouse and uses an
application called ShipperCentral. This application enables workers to view and amend orders, delivery
details, and customer details.
The management uses an application called AdminCentral. This application supports the
managerial side of the business and allows managers to keep an eye on churn rates, subscription

xxix

www.it-ebooks.info


 INTRODUCTION

cancellations, and revenues. One of the business objectives is to encourage bronze customers to
upgrade to silver or gold packages, and the application helps management meet this objective. It
contains features for generating mailshots to lapsed subscribers and for generating a targeted email
marketing campaign.
As you might appreciate, LightSwitch is a perfect tool for handling most of these scenarios. In
fact, the preceding ideas might also give you some inspiration as to how you could incorporate
LightSwitch in your own organization.
In many of the examples, we’ve used tables such as Employee, Customer, and Orders. We’ve
chosen these types of tables because such data structures are fairly self-explanatory. For example, each
customer is associated with one or more orders, and the typical data that you’d store for a customer
would include first name, surname, and address details.

Code
C# and VB.NET are the languages that are supported by LightSwitch. Throughout this book, you’ll find
code samples in both languages.
LightSwitch tries to remove much of the complexity that goes with writing an application. In the
LightSwitch designer (in the screen and query designers, for example), you’ll find a Write Code button
that allows you to handle various LightSwitch events. When you click this button, LightSwitch opens the
code editor window and allows you to start writing code.
Because LightSwitch tries to make this as simple as possible, the location of the file that you’re
working on isn’t always obvious. To clarify the code that we’re describing, we’ve added a file location at
the start of most code listings. Listing 1 shows a typical code listing.
Listing 1. Hello World Example
VB:
File: ShipperCentral\Server\UserCode\ApplicationData.vb
'REM VB Code appears here
C#:
File: ShipperCentral\Server\UserCode\ApplicationData.cs
//REM C# Code appears here
For both the VB and C# examples, the File heading specifies the file name and path. In this
example, ShipperCentral refers to the project name. This would relate to the name of your LightSwitch
project. The name Server refers to a subfolder called Server. This folder contains the contents of the
Server project. You’ll find out what this project does in Chapter 2, and learn more about the other
projects that you’ll find, such as Client and Common. Finally, UserCode is a subfolder, and
ApplicationData.vb/ApplicationData.cs refers to the name of the VB or C# file inside the folder.

xxx

www.it-ebooks.info


 INTRODUCTION

Terminology
If you’re a database professional, you’ll be familiar with the terms table, row, and column. SharePoint
developers work with lists and list items. The LightSwitch IDE refers to tables for SQL data sources, and
lists for SharePoint data sources. But when you’re working in code, LightSwitch refers to both of these
objects as entity sets.
There are several ways that you can express the same thing in LightSwitch. In most cases, we’ve
tried to use the names that are exposed by the LightSwitch API. However, the context of a sentence
sometimes makes it confusing to adhere to a single naming convention. For example, LightSwitch uses
the word property to refer to the fields that are added to a table (a customer surname property, for
example). When you’re working in code, it’s often hard to distinguish between a user-defined property
and a property that’s generated by LightSwitch. It can also become confusing once you begin talking
about properties of properties.
Therefore, we’ve occasionally used these terms interchangeably. To avoid any confusion, Table
1 provides a translation of words that are used to refer to the same thing.
Table 1. Translation of Terms Used to Describe Data
LightSwitch
Entity set
Entity type
Entity object
Property

SQL Server
Table
Column data type
Row
Field

SharePoint
List
Field type
List item
Field

Tips/Notes/Cautions
Throughout this book, we’ve included various tips and notes to help you along your way. If there’s
anything important that might cause damage, we’ve added the details into a caution section to help you.

Comments and Errata
Although we’ve tried hard to be accurate, mistakes do sometimes happen, particularly with a book of
this size. If you have any feedback or want to report any bugs, please visit the official page for this book
on the Apress web site:
http://www.apress.com/microsoft/net-framework/9781430240082
This page will also show you any errata, mistakes that have been discovered after publication.

xxxi

www.it-ebooks.info


PART 1




LightSwitch Concepts

www.it-ebooks.info


CHAPTER 1

Forms Over Data and Beyond
If you’ve ever gone skydiving, you’ll recognize that using Microsoft Visual Studio LightSwitch is much
like a skydiving experience.
As you jump from the airplane at 10,000 feet, you’d see a magnificent view of countryside, cities, and
towns linked together by roads, railways, and other pieces of infrastructure. A high-level view of
LightSwitch is rather like that. It consists of several large pieces that are all interconnected and
synchronized together.
Of course, jumping from an airplane can be scary and so too can using LightSwitch, particularly if
you start to push toward the technical limitations of the product. Although this book doesn't provide a
cure for vertigo, we hope that the contents will at least alleviate any fears of LightSwitch that you may
have and help you get the most out of your development experience.
As we descend from that 10,000-foot view, we can see some more ways in which LightSwitch is like
skydiving. Writing LightSwitch applications can be very fast. It can also be a lot of fun because you don't
have to worry about writing the boring, repetitive boilerplate code you seem to have to write in other
applications.
When we finally hit the ground (we hope, as lightly as a feather), you can look back on the
experience and appreciate the thrill of what has just happened. We hope that with the help of this book,
your journey into the advanced LightSwitch development adventure will be just as exciting.

Who Is LightSwitch For?
According to Microsoft, LightSwitch provides the “easiest way to build data centric applications for the
desktop or cloud.” This focus on ease of use means that LightSwitch is often labeled as a tool for
nondevelopers. But according to the architects behind the product, LightSwitch was never designed as a
tool for nondevelopers. It was designed for an audience that Microsoft calls “breadth professional
developers.” This group describes practical people with wide technical skills who look to technology to
solve specific problems.
Since LightSwitch’s release, it’s attracted a wide audience of people from many different
backgrounds and varying abilities.
During the early beta-1 days, LightSwitch was initially thought of as a natural successor to Access,
kind of “Access.NET,” or even a “Microsoft Access for the web” as it were. Grouping LightSwitch and
Access together was a natural association for many developers, because both products are data-centric
rapid application development (RAD) tools. Because of these similarities, many Access developers are
converting to LightSwitch. Many developers with experience in FoxPro and Excel/VBA are also using
LightSwitch for the same reason.
Meanwhile, information technology (IT) departments and decision makers have found that
LightSwitch provides the perfect tool for power users, and they have encouraged this group of users to
turn to LightSwitch. Power users are highly intelligent individuals who’ve not selected IT as their chosen

3
www.it-ebooks.info


CHAPTER 1  FORMS OVER DATA AND BEYOND

career path but are experts in some other business domain. However, they’ve found themselves
developing applications to help perform their main job function.
Because these individuals haven’t been trained to program computers, they might cobble together
an application (perhaps using Access and Excel) to solve a specific business problem. But if the
individual leaves or if the application needs to scale, it becomes notoriously hard for IT departments to
support such solutions. LightSwitch applications are easier for IT departments to maintain because they
can leverage their existing .NET and SQL Server skills. Because LightSwitch uses a three-tier architecture
and actively guides the developer toward writing code in the right place, it’s more difficult to write
applications badly in the first place.
Farther up the scale, LightSwitch attracts many professional developers who have come from .NET,
ASP.NET, and Silverlight backgrounds. These professional developers realize how much time
LightSwitch can save them, so they have embraced the product. They understand how useful
LightSwitch can be for developing forms over data applications and how easy it is to write web-based
applications with it.
We’ve therefore seen that LightSwitch attracts a wide audience, but all of these groups share one
thing in common. They see LightSwitch as a serious tool for solving business problems and understand
how powerful it can be.
The rest of this chapter shows you how LightSwitch stands out from the crowd and discusses some
of the key technologies that have gone into the product. We’ll start by giving you a high level overview
and then cover the following topics:


The model centric architecture of LightSwitch.



The data, logic, and presentation tiers.



How the Model-View-ViewModel pattern applies to LightSwitch.



How a LightSwitch application actually works.

The 10,000-Foot View
LightSwitch applications conform to a traditional three-tier architecture, containing presentation,
application (business logic), and data tiers. This has many advantages and benefits. In addition to being
modular (a good practice), the three-tier design provides a scalability that was sorely missing from
Access applications and enables tiers to be replaced or modified without affecting others. To give an
example, Microsoft may choose to replace the current Silverlight client with an HTML/JavaScript client
or some other emerging technology in a future version. The three-tier architecture makes this possible
without the whole application needing to be rewritten. In fact, active members of the LightSwitch
community have already written several articles about creating HTML frontends to LightSwitch.
At the presentation level, the client is a Silverlight 4.0 application, running either inside a browser or
as an OOB (out-of-browser) desktop application. The client connects to middle tier logic using WCF-RIA
(Windows Communication Foundation–Rich Internet Applications) services. The middle tier itself also
consists of a set of WCF-RIA domain services running under ASP.NET 4.0.
If you’re unfamiliar with RIA services, this technology was introduced in 2009 and is used to marshal
data between a database and the LightSwitch application. Specifically, RIA services coordinate the
application logic between the middle and presentation tiers. The biggest benefit it provides is that it
significantly simplifies the development of n-tier solutions in a RIA web environment such as Silverlight.
At the data tier level, Microsoft SQL Server is the database of choice. You can also attach to other
data sources, including SQL Azure, SharePoint 2010, and custom adapters written using RIA domain
services. Connections to SharePoint technically take place using an OData (Open Data Protocol)
endpoint exposed by the SharePoint API (Application Programming Interface).

4
www.it-ebooks.info


CHAPTER 1  FORMS OVER DATA AND BEYOND

LightSwitch utilizes the power of the Microsoft ADO.NET Entity Framework 4.0. This is an ORM
(Object Relational Mapping) system, which was first introduced in .NET 3.5. One of the key benefits of
using an ORM is that it abstracts away the schema of the database from the conceptual view that is
visible in code. It eliminates the problem of what is commonly known as the object relational impedance
mismatch that is often experienced in database-oriented applications. In simple terms, an ORM allows
you to refactor database tables without affecting the view of the data in code.
To query data from LightSwitch, you can use LINQ (Language INtegrated Query). This was also
introduced in .NET 3.5 along with Entity Framework V1. LINQ provides a set of common query
operators, the biggest advantage being that you can use the same syntax for querying various different
data sources. For example, you can just use LINQ rather than having to learn the individual, and very
different, syntaxes of query technologies like T-SQL, XPath, LDAP, and the various other query languages
that would otherwise be necessary to query different types of data. If you’re using LINQ for the first time,
a tool called LinqPad (www.linqpad.net/) provides a greatly simplified and easy-to-use learning
environment.
Architecturally, LightSwitch is based on a model-centric architecture. Applications are authored in
terms of building blocks such as entities, screens, and data services that are animated by the LightSwitch
runtime (using Silverlight and .NET technology stacks). Having these building blocks means that the
LightSwitch business logic doesn’t have a specific technology dependency. LightSwitch incorporates all
of these proven .NET technologies along with best practices for their use. Any application you create
using LightSwitch will therefore also be based on this solid foundation.

Figure 1-1. LightSwitch components
Figure 1-1 shows the three tiers that make up a LightSwitch application and identifies the main
components that belong to each tier. We’ll now explain each tier in more detail.

5
www.it-ebooks.info


CHAPTER 1  FORMS OVER DATA AND BEYOND

WHY THE NAME LIGHTSWITCH?
LightSwitch is certainly an unusual name, so where did it come from?
During the writing of this book, we spoke to a product manager at Microsoft who was involved in the
naming of LightSwitch. Unfortunately, Microsoft’s public relations department has prevented us from
disclosing any details about product naming. The process that they use is secretive.
During the early life of a Microsoft product, internal code names are used for identification. In the case of
LightSwitch, the code name was Kitty Hawk. These code names often relate to towns and places and in
the case of LightSwitch, Kitty Hawk most likely refers to a town in North Carolina. At some point afterward,
the actual name is determined through a formalized process, which might include a focus group.
Because we can’t publish any details about the naming of the product, we’ll share some of the rumors that
exist instead. LightSwitch uses Silverlight, which might explain the light part of the name. It’s also been
noted that the first characters of each word in both product names are swapped around (i.e., LightSwitch
vs. Silverlight).
Interestingly, we spoke to a very senior member of the LightSwitch team who didn't know the history
behind the name. In his opinion, however, this was something that was better left unknown. He believes
that the product naming might be based on something quite mundane; if we don’t know the story, we can
allow our imagination to supply a better one.

Model-Centric Architecture
LightSwitch is based on a model-centric architecture. What exactly do we mean by this and why is it
important?
When you’re writing a LightSwitch application, imagine that you’re a bricklayer rather than a
programmer. The raw materials at your disposal include entity, query, screen, and control building
blocks. To build an application, you simply put these building blocks together in the appropriate way.
The important analogy here is that building blocks are the main construct used for building
applications, not code. Figure 1-2 shows the building blocks that are defined by LightSwitch.

6
www.it-ebooks.info


CHAPTER 1  FORMS OVER DATA AND BEYOND

Figure 1-2. LightSwitch building blocks
When you create a new project, LightSwitch creates a new empty model (which we’ll refer to as the
LSML model). This model takes the form of an XML file called ApplicationData.lsml. When you create a
new screen in your application, LightSwitch adds the XML markup that represents a screen building
block into your ApplicationData.lsml file. The same thing happens when you add data sources, tables,
and queries. At the end of the design process, your application is expressed entirely in XML.
On its own, XML isn’t capable of doing very much—after all, it’s just data. Something needs to turn
these data into a functioning application, and this role is carried out by the LightSwitch runtime.
The LightSwitch runtime comes into action when a user actually runs your application. It reads the
model and performs many other functions such as loading the application, authorizing access, and
retrieving data. The LightSwitch runtime consists of the many technologies that were mentioned earlier,
such as Silverlight, WCF, Entity Framework, and the DLLs that belong in the Microsoft.LightSwitch
namespace. The runtime runs on both the client and logic tiers.
The beauty of this architecture is that it abstracts the definition of your application away from the
actual implementation. Hypothetically speaking, some other runtime could be written and used instead.
This new runtime might target different devices or operating systems. The benefit of the architecture is
that it doesn’t impose any solid dependency on any specific technology. The model-driven design
therefore makes LightSwitch more extensible and more future proof.

The Data Tier
As mentioned earlier, LightSwitch provides first-class support for reading and writing to SQL Server, SQL
Azure, and SharePoint 2010 data sources. You can very easily create screens to display data, and you can
even display data from multiple data sources on a single screen.

7
www.it-ebooks.info


CHAPTER 1  FORMS OVER DATA AND BEYOND

LightSwitch also depends on a special SQL Server database called the intrinsic or ApplicationData
database. Any users and tables that you create in LightSwitch are added to this database.
When you run or debug a LightSwitch application at design time, LightSwitch hosts your intrinsic
database using a local instance of Microsoft SQL Server Express. At design time, a local instance of SQL
Server Express must be used and other editions of SQL Server are not supported. In production,
however, this restriction doesn’t apply, and the intrinsic database can be hosted using any version of
Microsoft SQL Server 2005 or above, as well as Microsoft SQL Azure.
When you run an application at design time, an intrinsic database is created and any data you enter
are persisted between debug iterations.
However, you should treat these data as temporary because any major changes made to your data
schema can force the intrinsic database to be deleted and re-created. (LightSwitch will warn you before
it does this to prevent data loss.) Another important point is that any data entered during design time
won’t be retained when you deploy your application.
For security, LightSwitch uses the ASP.NET SQL membership provider, and if you take a peek inside
the intrinsic database, you’ll see the tables that are used. Examples include the dbo.aspnet_Membership,
dbo.aspnet_Roles, and dbo.aspnet_Users tables.
At design time, the intrinsic database is created, re-created, and updated dynamically by
LightSwitch using the table definitions you’ve specified in the designer. Specifically, it generates the
intrinsic database schema using the modeled EntityContainer building block.

The Logic Tier
The logic tier can also be known as the middle tier, business layer, or business logic layer. Its main task is
data access and processing.
For each data source you add to your application, LightSwitch creates a corresponding data service
in the logic tier. A data service encapsulates the data access operations on a data source and is exposed
as a public service endpoint at the logic tier boundary. The Silverlight client uses this data service to
carry out data access that is needed for a given data source.
Data services expose entity sets, which contain operations for retrieving, updating, and saving data.
An entity set is a container for items of the same entity, and all data access is carried out through an
entity set.
By default, each entity set contains all and single queries, which return all records and single
records by primary key. The queries you create yourself are also exposed as an entity set operation.
Figure 1-3 illustrates the relation between data services, entity sets, and operations.

8
www.it-ebooks.info


CHAPTER 1  FORMS OVER DATA AND BEYOND

Figure 1-3. Data service, entity sets, and operations
When a query is executed, it passes through the query pipeline. The query pipeline exposes various
points in the lifecycle of a query that you as a developer can intercept and inject with custom code.
During the preprocessing phase, for example, you can tailor the results of a query by appending
additional query operators using LINQ.
Each entity set also includes a single built-in operation called SaveChanges. When working with a
LightSwitch application, the client maintains a set of all the added, updated, and deleted records in an
object called a change set. When the user clicks the save button on a screen, the change set is passed to
the logic tier and the SaveChanges operation is called. At this point, the processing enters the save
pipeline and, just as with the query pipeline, the save pipeline can be intercepted with custom code.
Figure 1-4 shows the phases in the save and query pipelines and highlights some of the points where you
can write your own code.

9
www.it-ebooks.info


CHAPTER 1  FORMS OVER DATA AND BEYOND

Figure 1-4. The Save Pipeline and Query Pipeline
When updates are applied at the database, LightSwitch uses optimistic concurrency and doesn’t
apply any locks to the database. If concurrency violations are encountered, it alerts the user and displays
a dialog with the proposed, current, and server values. The SaveChanges operation also takes place inside
a transaction, and all data changes are committed atomically. Either all changes are saved successfully
or no changes will be saved at all.

 Note Unlike Microsoft Access and other DBMSs (database management systems), if you create a query in
LightSwitch, you cannot modify the columns that are returned in the query. This behavior is explained by the way
data access must occur through entity sets that are fixed in their structure.

10
www.it-ebooks.info


CHAPTER 1  FORMS OVER DATA AND BEYOND

Data Providers
When LightSwitch creates a data service, it configures the data service to work with a data provider that
corresponds with the data storage service that’s used (e.g., the database). The data provider offers a set
of libraries that enables the logic tier to communicate with the storage service. Table 1-1 shows the data
providers that LightSwitch uses.
Table 1-1. Data Providers Used by Data Storage Service Type

Data Storage Service

Data Provider

Microsoft SQL Server

SqlClient for the Entity Framework

Microsoft SQL Azure

SqlClient for the Entity Framework

Microsoft SharePoint

OData client

Custom RIA services

Requires a WCF-RIA domain service

Although LightSwitch uses the Entity Framework to connect to the SQL Server, you don’t need to
understand how this works, nor do you need to learn how to use the Entity Framework API. When you’re
writing code, LightSwitch produces entity classes that allow you to get to your data easily and naturally.
For instance, you can use the following code to retrieve a customer surname:
ApplicationData.Customer.Surname. LightSwitch makes it really simple and intuitive for you to work with
data.

The Presentation Tier
The presentation tier controls what the user sees and does. It’s responsible for showing data to the user,
allowing data entry to happen, and all other tasks that relate to human interaction. Importantly, it also
performs operations such as data validation and it keeps track of data changes and interacts with the
data services in the logic tier.
The activities of the LightSwitch client can be summarized into the following three categories:


User interface (UI),



Client business logic,



Data service access.

Everything that happens on the client is encapsulated inside the LightSwitch shell. From a top level,
the hosting, shell UI, and theming services are the parts that make up the shell, and this is shown in
Figure 1-5. We’ll now describe the parts that make up the client in more detail.

11
www.it-ebooks.info


CHAPTER 1  FORMS OVER DATA AND BEYOND

Figure 1-5. The LightSwitch shell

Screens
A screen represents a piece of user interface that is used to view or enter data, just like a form in an
Access application. Multiple screens can be opened in a LightSwitch application, but there can only be
one single active screen at any time.
Each screen contains a data workspace that is used for fetching and managing data. The data
workspace manages the state of the data in a change set, and this is submitted to the data service on the
logic tier when the user initiates a save.
Because each screen contains its own data workspace, data changes made in one screen are not
reflected in other screens. Data cannot be shared between screens, and each screen retains an
independent view of the data.
Other important concepts include the screen object, screen layout, and visual tree.
You can think of the screen object as a business object that contains no UI. When designing a
screen, you can access data in code and add items such as properties or screen parameters. All of these
objects are exposed in code through the screen object.
The screen layout and visual tree are concepts that emerge at runtime. We’ll describe both of these
in the “MVVM Applied to LightSwitch” section later in this chapter.

Hosting Process
LightSwitch applications are hosted using the Silverlight runtime. One of LightSwitch’s most useful
features is that an application can be configured to run either out of browser, as a desktop application, or
inside a browser, without having to be rewritten. You can switch an application from one mode to the
other by simply setting a radio button option in the properties of your LightSwitch project.
Browser applications are hosted by the Silverlight runtime inside the browser. Users install the
Silverlight runtime as a browser plug-in, and supported web browsers include Internet Explorer, Firefox,

12
www.it-ebooks.info


CHAPTER 1  FORMS OVER DATA AND BEYOND

Safari, and Chrome. Browser applications execute inside a sandbox, and access to features such as
Export to Excel is prohibited. Access to certain parts of the file system is also restricted.
Desktop applications are hosted by the Silverlight out-of-browser host service (sllauncher.exe).
LightSwitch configures your application to require elevated permissions, which give access to features
such as Export to Excel, and COM-based automation.
When you’re writing LightSwitch applications, it’s useful to know if your application is running as a
browser or a desktop application. Before you perform any COM-based operation such as automating
Outlook, it’s a good idea to check where your application is running by writing some code. Chapter 11
includes code that shows you how to do this.

WILL LIGHTSWITCH RUN ON MACS, LINUX, OR MOBILES?
A question that people regularly ask is whether LightSwitch will run on Macs, iPads, Linux, and various
brands of cell phones. The simple answer is that as long the platform supports a Silverlight 4.0 client,
LightSwitch will run. The mobile story is not as promising. It’s worth noting that Windows Mobile doesn’t
currently support LightSwitch because it uses a derivation of Silverlight 3.0.
All server side components must be deployed onto Windows servers.

The Shell UI
The shell UI is a key part of the LightSwitch presentation layer, and it controls what’s visible to the end
user. It provides the user interface logic that performs tasks such as logging in, generating, and activating
screens.
You can change various aspects of the shell’s behavior for each LightSwitch application using the
properties pane of your project (Figure 1-6).

Figure 1-6. Changing the shell and the theme settings in the project’s property tabs
LightSwitch ships with one standard default shell, which will be familiar to any LightSwitch
developer. As the LightSwitch market matures, additional shells from third party vendors and members
of the community will become available (either free or for sale).

13
www.it-ebooks.info


CHAPTER 1  FORMS OVER DATA AND BEYOND

Figure 1-7 illustrates the standard screen sections you’ll see using the default LightSwitch shell.
These include:


The screen region. The central area where screens are displayed.



The navigation region. Used for launching and activating screens.



The command region Displays command buttons such as Save and Refresh.



The validation region. Used for displaying any validation errors.

Figure 1-7. Default screen regions

14
www.it-ebooks.info


CHAPTER 1  FORMS OVER DATA AND BEYOND

Figure 1-8 shows the Outlook shell that was developed by Infragistics. It highlights just how radically
the look and feel of an application can be modified.
As shown in the illustration, this shell allows screens to be tiled rather than tabbed, it displays a
screen command bar section for each screen instead of showing a ribbon bar, and includes a slider
control on the right-hand side that lets you increase or decrease the number of screens shown in the
middle pane.

Figure 1-8. Infragistics’s Outlook style shell
If you choose to do so, you can also write your own custom shell extension, and Chapter 10 shows
you how to do this. When writing your own shell extensions, LightSwitch exposes various views models
that you can consume. The types of data that you can bind to in a custom shell include:


Current user,



Application logo,



Screen activation and navigation,



Active screens,



Screen commands,

15
www.it-ebooks.info


Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay

×