Consider the tale of two overworked individuals. Antonio is a senior developer in the IT department of a large bank with hundreds of branch offices. Dalia is the manager at one of these branches. She wants to bởi a better job of tracking computer assets. Who has what computer & how long have they had it? When was each printer và fax machine purchased và serviced? How much does the branch spend on peripherals & supplies each month?

Dalia e-mails Antonio và asks him lớn create an asset-tracking application. Antonio agrees this is needed & could save the bank significant sums of money, but he’s already fully committed to lớn other projects & has no time to help Dalia. He knows that Dalia is going to build the application herself in Excel or another end-user application, và this worries him because she’s likely going to lớn build a single-tier, self-contained application that won’t scale. But what can he do?

Fast forward six months. Dalia is a hero. She built her app và it has cut her branch’s computer spending by 25 percent while also increasing productivity due to lớn more efficient use of resources. Ngân hàng management decides that all of the branch offices should adopt this system & that the data should be centralized. Antonio is told lớn make this happen by the over of the month, và it’s now his nightmare lớn convert this application into something that resembles what he would have built if he had had the time. Good luck, Antonio!

Introducing Visual Studio LightSwitch

Visual Studio LightSwitch is designed lớn address this all-too-common scenario. LightSwitch is a new hàng hóa in the Visual Studio family aimed at developers of all skill levels who want to quickly create data-centric business applications for the desktop, Web and cloud. LightSwitch simplifies the development process because it does most of the development work for you. You don’t need khổng lồ write code lớn interact with databases & you don’t need to lớn manually lay out screens. You can concentrate on the business logic.

Bạn đang xem: Lightswitch

LightSwitch applications are based on Silverlight. They use proven n-tier architecture patterns based on Model-View-ViewModel (MVVM), as well as familiar .NET Framework technologies such as the Entity Framework và WCF RIA Services. LightSwitch applications can be deployed as desktop (out-of-browser) or browser-based applications. Desktop applications can leverage local hardware resources & work with applications such as Word and Excel. Both desktop và browser-based LightSwitch applications can be hosted on IIS và Azure.

The primary audience for LightSwitch is end-user developers such as Dalia. They’re information workers, IT professionals, business analysts and so on who vì chưng some development as part of their job. They aren’t professional developers, & they want a smooth on-ramp lớn development, built-in plumbing that handles common application requirements, & simple and flexible deployment options. In short, they want to lớn quickly build well-architected, data-centric applications that can be easily deployed & scaled.

Existing Visual Studio developers will often find LightSwitch an attractive addition to their toolset. LightSwitch installs on top of Visual Studio 2010 Professional và above. Visual Studio developers can build LightSwitch applications from scratch or they can mở cửa a LightSwitch application in Visual Studio và extend it. If Dalia had used LightSwitch to lớn build her application, Antonio could xuất hiện it and enhance it. Or Antonio could build the application in LightSwitch in potentially dramatically less time than if he started from scratch.

In this article, I’ll review a LightSwitch application used by the construction company arm of the ubiquitous Contoso Corp. The company wants to lớn manage customers và their projects. You can tải về the sample application I’ll be discussing here:


The first step in building a LightSwitch application, after choosing whether you want khổng lồ code in Visual Basic or Visual C#, is lớn define your data. You can create new tables or attach lớn external data sources. If you create tables from scratch, they’re added lớn the application database, which is a SQL server Express database. Chú ý that when it’s time to lớn deploy the application, you can choose any edition of SQL hệ thống to host the data. Khổng lồ work with external data, you can connect khổng lồ an external database such as SQL server or SQL Azure or any database for which you have an Entity Framework provider. You can also connect khổng lồ SharePoint lists or WCF RIA Services.

The sample application contains a Customer entity (table), as shown in Figure 1.

(click to zoom)

Figure 1 The Customer Entity

For each entity property, you can define not only the data type, but also whether the property is required, unique, searchable and displayed on screens by default. You can also specify alternate display labels và maximum lengths. For numeric và date properties, you can specify minimum and maximum values.

Rather than leave certain properties as strings or their default types, you can use built-in data types, also referred to lớn as custom business types. The phone and fax properties in the Customer entity use the Phone Number data type, & the e-mail property uses the thư điện tử Address data type. The built-in data types provide validation & will generate user-friendly runtime errors. There’s no need for you to lớn write code to validate that a phone number or email address is valid. In addition, the Phone Number data type includes built-in formatting, as shown in Figure 2.


Figure 2 The Built-In Phone Number Data Type Provides Validation & Formatting

There are also Date, Image and Money data types that all come with built-in editors, formatting và validation.

After adding properties khổng lồ an entity, you should reviews the entity’s Summary property, which describes the entity. It also becomes a hyperlink on tìm kiếm screens.

The screen displays all customers in a grid. Notice the Full Name column contains hyperlinks. When the user clicks a full name, LightSwitch displays the detail screen for that customer. As the LightSwitch developer, you don’t need khổng lồ write any code to lớn make this happen. Figure 3 shows the search Customers screen.


Figure 3 An Entity’s Summary Property Is a Hyperlink in search Screens

By default, LightSwitch uses the first string property as the entity’s Summary property. If there are no strings, it will use the first non-string property. In the sample application, customers are people & the first string in the Customer entity is LastName. Rather than use that as the Summary property, the Customer entity has a FullName property. This is a computed property. Khổng lồ make a property computed, you check Is Computed in the Properties window or click a button at the top of the designer, click Edit Method, and then write the following code to compute the value of the property (I’ll be using Visual Basic):

Private Sub FullName_Compute(ByRef result As String) result = Me.LastName + ", " + Me.FirstNameEnd SubTo make FullName the Summary property, simply select the Customer entity & set the Summary property lớn FullName.

Computed properties aren’t stored in a database. They’re computed at run time as properties of an entity. You can use computed properties for simple concatenations of names & addresses and also for calculated values such as year-to-date revenue or total value of outstanding invoices.

To create a relationship between entities, click the Relationship button in the Data Designer. In the địa chỉ cửa hàng New Relationship dialog box, select the two entities, the type of relationship và the delete behavior. The Customer entity has one-to-many relationships defined with the Project and Appointment entities. Therefore, Customer has a Projects property và an Appointments property. These two properties are collections.

You can not only create relationships between entities in a single data source, but also between entities in multiple data sources. LightSwitch will handle retrieving all of the data, presenting it khổng lồ users and saving changes. The ability lớn create federated relationships is a unique và compelling feature of LightSwitch.

Custom Validation Rules

In addition lớn using the validations provided by the built-in business types, you can địa chỉ custom business súc tích code, both at the screen and entity level. Screen validation code runs only on the client và validates screen properties và data. Entity property validation code runs on the client first and then on the middle tier. Users get immediate feedback & can correct errors before sending data lớn the middle tier. The validation ngắn gọn xúc tích also runs on the middle tier khổng lồ handle situations where data is changed by other users. This is a best practice in n-tier design.

To write validation code for an entity property, you can select the property in the Entity Designer and then select the appropriate method from the Write Code button drop-down list: Address1_Validate, for example (shown in Figure 4).

Figure 4 The Address1_Validate Method

Private Sub Address1_Validate(results As EntityValidationResultsBuilder) "Warn the user if the Address is empty If Me.Address1 = "" Then results.AddPropertyResult( "Address should not be empty. " và "Construction project cannot begin unless an address is supplied.", ValidationSeverity.Warning) end IfEnd SubEntityValidationResultsBuilder is a container for validation results. It can contain validation information, warnings and errors. Validation information and warnings present information to the user but don’t prevent the user from saving data. If the collection contains any validation errors, the user can’t save the data.

In the sample application, the user is warned if the address is empty. The user can still save the data. However, the code khổng lồ validate the ZIP code (shown in Figure 5) isn’t as forgiving.

Figure 5 The ZIP_Validate Method

Private Sub ZIP_Validate(results As EntityValidationResultsBuilder) If Me.ZIP "" Then "Enter the dash if not supplied & is 9 digits long If Me.ZIP.Length = 9 Then Me.ZIP = Me.ZIP.Substring(0, 5) + "-" + Me.ZIP.Substring(5) end If "Make sure valid zip code (5 or 5+4 format) If Not System.Text.RegularExpressions.Regex.IsMatch( Me.ZIP, "^d5$|^d5-d4$") Then results.AddPropertyError( "Please enter a valid US ZIP code. (ex. 98052 or 98052-1234)") over If kết thúc IfEnd SubIf the ZIP code isn’t in the proper format, the code adds a validation error. This will prevent the user from saving the invalid data. Figure 6 shows the results of leaving the address empty và entering an invalid ZIP code. The empty address generates a warning và the invalid ZIP code generates an error.


Figure 6 The Empty Address Generates a Warning While the Invalid ZIP Code Generates an Error


After you define your entities, the next step in building a LightSwitch application is khổng lồ design screens. LightSwitch includes the following predefined screen templates:

Details Screen This displays a single entity & can include related data in a grid.Editable Grid Screen This enables the editing of one or more items in a grid.List and Details Screen This displays a collection of items in a list. Selecting an thành phầm in the các mục displays the details for that item.New Data Screen This is a screen for creating a new item. The screen can also provide a grid to lớn enable the ability to địa chỉ related data at the same time.Search Data Screen This displays data returned from a query. Each tòa tháp includes a links to display the entity’s details screen.

These templates provide a good starting point for your screen layouts. Khổng lồ create a screen, you can right-click the solution or the Screens node in the Solution Explorer and select “Add Screen.” You can also click the Screen button in the Data Designer. When you create a screen, you select the type of screen & the primary screen data. You can select an entity or a query based on an entity. You can then specify related data you want to appear on the screen.

When you xuất hiện a Silverlight screen in Visual Studio, you see a kiến thiết canvas & XAML. When you mở cửa a screen in LightSwitch, you see the Screen Designer, as shown in Figure 7.


Figure 7 The Screen Designer Shows a Hierarchical View of the Controls on a Screen

On the left is the screen members list. This contains the items that are available on the screen. It includes the data items in each entity included in the screen. It also contains methods such as Close, Refresh and Save. On the right is the screen content tree. This is a hierarchical view of the controls on the screen and the data lớn which they’re bound. You can địa chỉ cửa hàng data items lớn the screen as needed. You can rearrange the screen controls as well as modify the screen layout. For example, you may want the customers danh sách on the left và orders on the right rather than customers on top and orders below. You can also mix various properties of controls, such as label text, whether a label appears, horizontal and vertical alignment, height and width.

After you create at least one screen, you can press F5 và run the application. The first screen you create is the application’s mặc định screen. You can change this on the Navigation tab of the Application Designer. LightSwitch applications automatically include an application shell, a navigation menu, a ribbon, a tabbed area for screens & data binding, as shown in Figure 8.


Figure 8 LightSwitch Applications Automatically Include an Application Shell, Menu & Ribbon

The application also has built-in dirty checking và concurrency handling. LightSwitch handles all the plumbing of a typical data-centric application for you so you don’t need lớn write any of that code.

The LightSwitch screen templates provide specific functionality. For example, a search screen contains a grid to lớn display items và a button to export those items to Excel. You can địa chỉ additional items as needed. The SearchCustomers screen (shown in Figure 8) has two additional buttons: an địa chỉ Customer button in the ribbon và an địa chỉ cửa hàng button in the grid’s header.

To địa chỉ a button lớn the ribbon, you can right-click Screen Command Bar in the Screen Designer và select add Button. Or you can expand the Screen Command Bar và select New Button from the địa chỉ cửa hàng button’s drop-down list, as shown in Figure 9. To add a button to lớn the grid, use the Command Bar contained in the grid.


Figure 9 The Screen Command Bar Contains the Buttons in the Application’s Ribbon

When you địa chỉ cửa hàng a button, LightSwitch prompts you for the name of the method that runs when the user clicks the button. You can right-click the button và select Edit Execute Code, and then write the code that executes. Both add buttons on the SearchCustomers screen điện thoại tư vấn the gridAddAndEditNew_Execute method, which calls the ShowCreateNewCustomer method. This is a LightSwitch built-in method that displays the CreateNewCustomer screen, as shown here:

Private Sub gridAddAndEditNew_Execute() Me.Application.ShowCreateNewCustomer()End SubJust lượt thích entities, screens have a number of events you can handle, as shown in Figure 10.


Figure 10 Access Screen event Handlers via the Write Code Button

The Run sự kiện occurs when a request is made khổng lồ display a screen. The Run event handler includes a handled argument. If you set this lớn true, you can prevent the screen from continuing. The InitializeDataWorkspace sự kiện occurs just before the screen data is retrieved. This is a good place for screen initialization code. The other events are self-explanatory. You might think that events such as Run or Saving are good places lớn put code that checks whether the user can perform actions such as xuất hiện the screen or save the data. However, you should put that code in the appropriate Access Control methods, such as CanRun at the screen cấp độ or CanUpdate at the entity level. Access control is a big feature of LightSwitch applications that I’ll discuss later.

LightSwitch development is designed to lớn be highly iterative. Developers can edit screens at run time while running in Debug Mode by clicking the thiết kế Screen button in the ribbon. This switches to lớn the screen’s Customization Mode, as shown in Figure 11.

(click to lớn zoom)

Figure 11 Users Can Edit Screens at Run Time and View Their Changes Immediately

Users can rearrange controls và set properties, click Save and see their changes immediately.

Knowing that a LightSwitch application is a Silverlight application, you may be wondering, “Where is the XAML?” A primary goal of LightSwitch is to make it much easier khổng lồ build applications. It therefore does not expose XAML at kiến thiết time. Rather, LightSwitch generates XAML at run time based on the screen design. This makes it dramatically easier for users lớn build applications. If you’re an experienced Silverlight developer, you might be thinking that this also limits your ability khổng lồ build the screens you’d like.

While this may be true if you’re only using Visual Studio LightSwitch, you have much more flexibility if you have LightSwitch on vị trí cao nhất of Visual Studio 2010 Professional or above. You can create your own Silverlight user controls and showroom them lớn LightSwitch screens, as well as use controls that aren’t included in LightSwitch. You can create composite controls or even entire screens that include custom logic, plus you can easily bind these user controls to lớn screen entities.

Another way to showroom functionality to lớn a LightSwitch application is lớn use an extension. There are six types of LightSwitch extensions: controls, screen templates, business types, shells (application look & feel), themes (colors và brushes for a shell) & custom data sources. You’ll need Visual Studio 2010 Professional or above and the Visual Studio 2010 SDK to lớn create a LightSwitch extension, but anyone can use them in their LightSwitch project, no matter what edition they have installed.

Extensions are distributed via VSIX packages. If you want to lớn make an extension broadly available, you can upload it khổng lồ the Visual Studio Gallery. It will then appear in the Extension Manager within LightSwitch. After installing an extension, you can enable it on the Extensions tab of the Application Designer. The Contoso Construction sample application uses a Bing bản đồ control extension to show the location of customers, as shown in Figure 12.


Figure 12 You Can Use LightSwitch Extensions, Such as the Bing bản đồ Control Extension, to Provide Additional Functionality in Your Applications


All screens are based on queries. The query for a Detail screen returns one row. The query for a List and Details screen returns one parent row and all of the related child rows. The query for a tìm kiếm or Editable Grid screen will return all rows by default. Cảnh báo that queries that return a number of rows don’t literally return all of the rows at once. The queries support paging by default. Lớn configure the paging, select the query in either the Screen or Query Designer & change the paging-related properties.

You can filter the data returned by a screen query that returns a collection of entities. To do this, click Edit Query in the Screen Designer. In the Query Designer, you can then địa chỉ Where & Sort clauses. You can also add parameters lớn queries.

Screen queries are specific lớn a particular screen. Although it’s quick and easy lớn modify a screen’s query, a better practice is lớn create a reusable query. For example, you may want customers sorted by company name on the customer search screen. However, customers may also appear in a modal window picker on the screen where you create new appointments và in an autocomplete text box on the screen that displays customers and their projects. Rather than add the same Sort to lớn three queries on three different screens, you can create one query and use it on the three screens.

To create a query, you can right-click on an entity in the Solution Designer và select showroom Query. You can name the query & then địa chỉ filtering, sorting and parameters. The CurrentAppointments query, shown in Figure 13, returns all appointments, sorted by start time, where the start time is now or later.


Figure 13 You Can Filter the Results of a Query & Specify the Sort Order

Once you’ve created a query, you can use it as the basis for screens. You can also use it as the basis for additional queries. For example, in the sample application, the CurrentAppointmentsByEmployee query starts with the CurrentAppointments query and then filters the results khổng lồ return only the appointments for a particular employee.

Access Control

Access control gives you the ability to control what actions users can take in an application. LightSwitch uses the standard ASP.NET membership and role providers khổng lồ enable both Windows & Forms authentication. You can authorize users to lớn perform actions by creating permissions, assigning them lớn users & then checking in code whether the user has a particular permission.

By default, all users can perform all actions in a LightSwitch application. Khổng lồ change this, xuất hiện the Application Designer và select the Access Control tab, as shown in Figure 14. Then select either Windows or Forms authentication. The built-in SecurityAdministration permission controls whether a user can see the security administration screens at run time. You use those screens khổng lồ assign permissions lớn users and add users if necessary. You can create additional permissions if desired. During development, you can turn off permissions by unchecking Granted for debug. This enables you to thử nghiệm the application using various combinations of permissions.


Figure 14 Specify Windows or Forms Authentication and Then Specify Additional Permissions

You can kiểm tra for permissions in code at the entity, screen & query levels. Entities provide CanDelete, CanInsert, CanRead and CanUpdate methods, which all run on the server. You can access these from the Write Code button drop-down các mục in the Data Designer. You can check for the appropriate permission và return false if the user isn’t permitted lớn take the associated action. For example, in the sample application, only administrators can modify employee data. The following code ensures this:

Private Sub Employees_CanDelete(ByRef result As Boolean) result = Me.Application.User.HasPermission( Permissions.SecurityAdministration)End SubPrivate Sub Employees_CanInsert(ByRef result As Boolean) result = Me.Application.User.HasPermission( Permissions.SecurityAdministration)End SubPrivate Sub Employees_CanUpdate(ByRef result As Boolean) result = Me.Application.User.HasPermission( Permissions.SecurityAdministration)End SubScreens provide a CanRun method, which runs on the client. You can use this method to lớn not mở cửa a screen if the user can’t view or modify the screen’s data. The following code ensures that only administrators can xuất hiện the ManageEmployees screen:

Private Sub ManageEmployees_CanRun(ByRef result As Boolean) result = Me.User.HasPermission(Permissions.SecurityAdministration)End SubDuring the deployment process, you’ll specify the user name and password of the administrator. At run time, the administrator creates roles & assigns users khổng lồ them. The administrator then assigns permissions to roles.


LightSwitch provides three models for deploying applications: two-tier desktop application, three-tier desktop application & three-tier website application.

A two-tier desktop application runs entirely on the over user’s computer as an out-of-browser Silverlight application. The UI and all the application’s middle-tier components run locally. The application connects khổng lồ the database directly in typical client-server fashion. This avoids the need for a website server. The application has access khổng lồ local resources, including COM or local files. COM tư vấn provides the ability to lớn control applications such as Word or Excel. Cảnh báo that desktop applications require Windows.

A three-tier desktop application runs as an out-of-browser Silverlight application hosted on IIS or Azure. The UI runs on the end user’s computer, while the middle-tier components run on the host server.

A three-tier web application runs as an in-browser Silverlight application hosted on IIS or Azure. The UI is browser-based and the middle-tier components run on the host server. Website applications don’t have access to COM or local resources, but they bởi vì provide the most reach across Mac và Windows OSes & multiple browsers.

To deploy an application, you first publish it. Lớn publish the application, click the Publish button on the Application Type tab in the Application Designer, as shown in Figure 15.


Figure 15 Specify Whether the Application Is a Two-Tier Desktop Application, Three-Tier Desktop Application or Three-Tier web Application

The LightSwitch Publish Application Wizard will then walk you through the publishing process.

If you publish the application as a two-tier desktop application, you’ll create a ClickOnce package. You’ll create a SQL server database that contains any local tables you created, as well as system tables. You can also specify where this database resides. If the application is used by a single person, you may locate the database on that user’s computer & use SQL vps Express. If the application will be used by more than one person, you’ll likely store the database on a network computer running SQL Server.

If you publish the application as a three-tier desktop or website application hosted on IIS, you can publish directly khổng lồ IIS if the vps is running the website Deployment Tool service. Otherwise, you can create an MSDeploy package and manually import it into IIS. If you publish the application lớn Azure, the wizard will prompt you for your account subscription ID, the service & storage accounts you’ll use, & an SSL certificate to lớn use. For more information on deployment & publishing to lớn Azure, see the deployment section of the LightSwitch Developer Center on MSDN (

The Simplest Way

Wrapping up, the primary audience for LightSwitch is end-user developers. These are people building applications to tư vấn business functions. They aren’t professional developers. They’re IT pros, information workers and others who vị some development as part of their job. They often have a need khổng lồ build applications that manage “things,” such as department computer assets or car fleets. They may need an application to lớn manage an event, such as a quarterly open house.

LightSwitch provides these users with a smooth on-ramp to development. It automatically builds the “plumbing” khổng lồ perform common application tasks, such as working with data, generating screens, exporting data to lớn Excel and more. It also provides a simple và flexible deployment model.

LightSwitch is the simplest way to lớn build data applications for the desktop and the cloud. The Dalias of the world can build the applications they need and then turn them over lớn the Antonios of the world to be extended và deployed. For more information on how to lớn build applications with LightSwitch, visit the LightSwitch Developer Center on MSDN (

Xem thêm: Soạn Văn 7 Bài Dấu Chấm Lửng Và Dấu Chấm Phẩy Trang 121 Sgk, Soạn Văn 7: Dấu Chấm Lửng Và Dấu Chấm Phẩy

Robert Green is a technical evangelist in the Developer Platform và Evangelism group at This is his second stint at From 2005 lớn 2010, he was a senior consultant with MCW Technologies, focused on developer training. He authored & coauthored a number of Visual Studio and .NET courses for AppDev ( Prior lớn that, in his first stint at, he was in Developer Tools sale and then community lead on the Visual Basic team.