Siêu thị PDFTải ngay đi em, trời tối mất

Thư viện tri thức trực tuyến

Kho tài liệu với 50,000+ tài liệu học thuật

© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

Pro Visual Studio LightSwitch 2011 Development pdf
PREMIUM
Số trang
719
Kích thước
20.9 MB
Định dạng
PDF
Lượt xem
1360

Pro Visual Studio LightSwitch 2011 Development pdf

Nội dung xem thử

Mô tả chi tiết

Leung

Duran

US $49.99

Shelve in

.NEt

User level:

Intermediate

www.apress.com

SOURCE CODE ONLINE

RELATED

BOOKS FOR PROFESSIONALS BY PROFESSIONALS®

Pro Visual Studio LightSwitch 2011

Development

Pro Visual Studio LightSwitch 2011 Development helps you build advanced busi￾ness 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.

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.

iii

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

iv

 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

xxv

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

 INTRODUCTION

xxvi

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!

 INTRODUCTION

xxvii

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.

 INTRODUCTION

xxviii

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.

 INTRODUCTION

xxix

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

 INTRODUCTION

xxx

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.

 INTRODUCTION

xxxi

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 SQL Server SharePoint

Entity set Table List

Entity type Column data type Field type

Entity object Row List item

Property Field 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.

P A R T 1



LightSwitch Concepts

C H A P T E R 1

3

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

CHAPTER 1  FORMS OVER DATA AND BEYOND

4

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).

CHAPTER 1  FORMS OVER DATA AND BEYOND

5

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.

Tải ngay đi em, còn do dự, trời tối mất!