7/31/2011

The Anatomy of a LightSwitch Application Part 3 – the Logic Tier

Ref: LightSwitch.

The LightSwitch running application consist of three tiers—presentation, logic, and data storage. In the prior post we covered the presentation tier. In this post we will take a deeper look at the logic tier.
Just as a recap, the presentation tier is a Silverlight client application that can run as a desktop application (out-of-browser) or as a browser-hosted application. LightSwitch uses a 3-tier architecture where the client sends all requests to fetch and update data through a middle tier.
The primary job of the logic tier is data access and data processing. It is the go-between from the client to each of the data sources that have been added to the application. LightSwitch creates a data service in the logic tier for each data source. Each data service exposes a set of related entities via entity sets. There are query operations for fetching entities from the entity sets, and a single submit operation for sending added, modified and deleted entities for processing.
Each data service talks to its corresponding data source via a data source provider. These providers are implemented by LightSwitch. The LightSwitch developer doesn’t need to know about the underlying data access technologies employed in order to work with data or to write business logic.
Let’s dig into the details of data services, business logic, query operations, and submit operations. We’ll also look at some implementation details: data providers and transaction management.

Data Services

A data service encapsulates all access to a data source. A LightSwitch logic tier hosts any number of data services which are exposed as public service endpoints at the service boundary. Each data service exposes a number of queryable entity sets with operations for querying entities and an operation for submitting a change-set of added, updated and deleted entities. An entity set is a logical container for entities of the same entity type. Operations that fetch entities always fetch them from a given entity set. Likewise, operations that add, update, or delete entities update them through a given entity set.
If this terminology is new to you, you can think of an entity set as analogous to a SQL table. An entity instance is then analogous to a SQL row, and the properties of the entity type match the SQL columns. (Note that these are not equivalent concepts, but will help ground you in something familiar.)
At a more formal architectural level, LightSwitch chose to follow the Entity Data Model (EDM) for defining our data services. You can think of a LightSwitch data service as implementing an entity container having entity types, entity sets, association types, and association sets. We do not yet support complex types or function imports which are also part of the EDM. The LightSwitch developer needn’t be bothered with all these concepts. The LightSwitch tool makes importing or defining entity types and relationships straightforward and LightSwitch takes care of the rest.
To get a better understanding of the structure of a data service, let’s look at an example. The following diagram shows example Northwind data service with two entity sets, Customers and Orders. Each entity set has the default All and Single queries, and customers has an additional modeled query that selects the Active customers. It also has the default SaveChanges operation.
data service
Let’s now look at this in more detail. We’ll go over query operations, submit operations, custom operations, and how custom business logic is associated with the entity sets and operations.

Query Operations

A query operation requests a set of entities from an entity set in the data service, with optional filtering and ordering applied. Queries can have parameters and can return multiple or single results. A query can define specific filtering and ordering intrinsically. In addition to passing parameters, the caller can pass additional filter and ordering predicates to be performed by the query operation.
For each entity set, LightSwitch provides a default “All” and “Single” query. For example, for a Customers entity set, LightSwitch will generate Customers_All to return all of the customers and Customers_Single to return one customer by key. You can define additional query operations for an entity set that defines its own parameters, filters and ordering.
LightSwitch queries are composable so that new queries can be based on an existing one. For example you can define an ActiveCustomers, based on the built-in Customers_All, and then then define ActiveCustomersByRegion(string region) based on the ActiveCustomers query.
Query operations can have parameters that are used in the filter (where) clauses. LightSwitch also supports optional parameters. Optional parameters are a special case of nullable parameters. If the parameter value is null at runtime, LightSwitch omits the query clause that uses it. Optional parameters are useful in building up screens where the end-user may or may not provider certain filter criteria. For example, say you are defining a search query for Customers. You want to return all the customers, but if the “active” parameter is specified, you return only the active or inactive customers. You define the filter clause in the designer as follows, designating the parameter as an optional Boolean type.
anatomy query filter
LightSwitch generates a nullable Boolean parameter and interprets the where clause as follows:
where (!active.HasValue || customer.IsActive == active.Value)
A query can be designated as a singleton query by specifying “One” as the number of entities to return. A singleton query operation returns just one entity or null and the query is not further composable. The runtime behavior matches the LINQ SingleOrDefault behavior. It will throw an exception at runtime if the query returns more than one record.
Although a LightSwitch query operation can define filtering and ordering within the query, a client can compose additional query operators at the call site. For example, say you’ve defined the ActiveCustomers query which filters out only active customers and returns them ordered by the customer ID. Any LightSwitch business logic can then use LINQ to invoke this query and pass additional filters or ordering.
Dim query = From c As Customer In northwind.ActiveCustomers Where c.State = “WA” OrderBy c.ZipCode

Note that the additional Where and Orderby clauses get executed in the data service—not on the client. Not all of the IQueryable LINQ operators are supported—only those that we can serialize over WCF RIA Services. (See IDataServiceQueryable in the LightSwitch runtime API.)
During execution of the query, the operation passes through the query pipeline, during which you can inject custom server-side code. Here is a quick summary of the query pipeline.
1. Pre-processing
a. CanExecute – called to determine if this operation may be called or not
b. Executing – called before the query is processed
c. Pre-process query expression – provides the base query expression
2. Execution – LightSwitch passes the query expression to the data provider for execution
3. Post-processing
a. Executed – after the query is processed but before returning the results
b. OR ExecuteFailed – if the query operation failed
The bolded elements represent points in the pipeline where you can customize the query by adding custom code. In CanExecute, you can test user permissions to access the operation, or any other logic to determine if the operation is available. (LightSwitch also checks the CanRead status for the underlying entity set.) In the Executing phase, you can modify the transaction scope semantics. This is very advanced and typically not necessary. During the pre-processing phase, you can append additional query operators using LINQ. This is helpful because some data providers support more complex query expressions than can be modeled in LightSwitch or serialized from the client.
During the Execution phase, LightSwitch transforms the query expression into one that can be used directly by the given data provider. In some cases this involves transforming the data types used from LightSwitch specific entity types to entity types used by the underlying provider. More on this in the section below on data providers.

Submit Operations

Each data service has a single built-in operation called SaveChanges. This operation sends changed entities from the client to data service for processing.
SaveChanges operates on a change set. The client’s data workspace tracks one change set per data service. (See data workspace in prior post.) The change set includes all of the locally added, updated and deleted entities for that data service. The change set is serialized, sent to the data service, and is deserialized into a server-side data workspace. (Note that locally changed entities associated with a different data source are not included in the change set.) Execution in the data service follows the submit pipeline, which looks like this.
1. Pre-processing
a. SaveChanges_CanExecute – called to determine whether this operation is available or not
b. SaveChanges_Executing – called before the operation is processed
2. Process modified entities
a. Entity Validation – the common property validation is called for each modified entity (the same validation code that runs on the client)
b. EntitySet_Validate – called for each modified entity
c. EntitySet_Inserting – called for each added entity
d. EntitySet_Updating – called for each updated entity
e. EntitySet_Deleting – called for each deleted entity
3. Execution – LightSwitch passes all of the changes to the underlying data provider for processing
4. Post-process modified entities
a. EntitySet_Inserted b. EntitySet_Updated c. EntitySet_Deleted
5. Post-processing
a. SaveChanges_Executed b. OR SaveChanges_ExecuteFailed
Each modified entity in the change set gets processed at least once through the save pipeline.
If the validation phase fails for any entity, the pipeline stops and returns the error to the client. If the business logic in the Inserting, Updating or Deleting phases make additional changes, LightSwitch ensures that any newly added, modified or deleted entities also pass through the pipeline. This ensures that business logic is applied uniformly to all entities and entity sets.
In addition to the pipeline functions above, LightSwitch evaluates the per-entity set CanRead, CanInsert, CanUpdate, CanDelete for entity sets affected by the change set. LightSwitch rejects the change set if it a requested change to an entity set is not currently allowed.
If the processing succeeds, any modified entities are serialized back to the client. In this way, the client can get updated IDs, or observe any other changes made by the data service code.
LightSwitch uses optimistic concurrency for updates. If a concurrency violation occurs, the concurrency error is returned to the client where it can observe the proposed, current and server values.

Custom Operations (future)

Many real-world scenarios require general purpose operations that cannot be classified as either an entity query or a submit operation. These operations may be data-intensive, long-running, or require access to data or services that are not otherwise accessible from the client.
Although custom operations are definitely a part of the LightSwitch architectural roadmap, they did not make it into the first release. This was a difficult trade-off. I’m writing this now just to ensure you that we won’t forget about the importance of this and that we intend to publish some workarounds that are possible in v1.

Transaction Management

Transactions in the data service are scoped per data workspace. Each operation invocation gets its own data workspace instance and, in the default case, each data workspace uses its own independent transaction and its own DB connection. 
If an ambient transaction is available, the data workspace will use it and compose with other transactions within that transaction scope, but by default, there is no ambient transaction. The default isolation level for query operations is IsolationLevel.ReadCommitted. The default isolation level for submit operations is IsolationLevel.RepeatableRead. In neither case is DTC used by default.
The LightSwitch developer controls the default transaction scope, including enrollment in a distributed transaction, by creating his own transaction scope in the “Executing” phase of the pipeline, and then committing it in the “Executed” phase.
It is possible to transact changes to multiple different data sources simultaneously, but LightSwitch does not do this by default. We only save changes to a single data service, and thus to a single data source. If you need to save changes to a different data source within the current submit operation, you can create a new data workspace, make the changes there, and call its SaveChanges method. In this case, you can also control the transaction scope used by the new data workspace.
Note that changing the transaction scope within the query pipeline does not work in this release. This is an implementation limitation but may be fixed in a future release.

Data Providers

LightSwitch data workspaces aggregate data from different data sources. A single LightSwitch application can attach to many different kinds data sources. LightSwitch provides a single developer API for entities, queries and updates regardless of the data source kind. Internally, we have implemented three strategies to provide data access from the logic tier to the back-end storage tiers.
ADO.NET Entity Framework for access to SQL Server and SQL Azure
WCF Data Services for access to SharePoint 2010 via the OData protocol
A shim to talk to an in-memory WCF RIA DomainService for extensibility
LightSwitch uses existing .NET data access frameworks as a private implementation detail. We are calling them “data providers” in the abstract architectural sense. LightSwitch does not define a public provider API in the sense of ADO.NET data providers or Entity Framework providers. LightSwitch translates query expressions and marshals between the LightSwitch entity types and those used by the underlying implementation. (For access to SQL using Entity Framework, we use our entity types directly without further marshaling.)
For extensibility, LightSwitch supports calling into a custom RIA DomainService class as a sort of in-memory data adapter. LightSwitch calls the instance directly from our data service implementation to perform query and submit operations. The custom DomainService is not exposed as a public WCF service. (The [EnableClientAccess] attribute should not be applied.) Using this mechanism, a developer can use Visual Studio Professional to create a DomainService class that exposes entity types and implements the prescribed query, insert, update, and delete methods. LightSwitch infers a LightSwitch entity model based on the exposed entity types and infers an entity set based on the presence of a “default” query.

Summary

The LightSwitch logic tier hosts one or more data services. The LightSwitch client accesses goes through the data service to access data in a data source, such as a SQL database or a SharePoint site. Data services expose entity sets and operations. A query operation fetches entities from entity sets. The submit operation saves modified entities to entity sets. The data service implements a query pipeline and a submit pipeline to perform application-specific business logic.
In the next post we’ll take a quick look at the storage tier. This will detail the data sources we support, which storage features of the data sources we support, and how we create and update the data schema for the application-owned SQL database.

The Anatomy of a LightSwitch Application Series Part 2 – The Presentation Tier

Ref: LightSwitch.

We'll continue our exploration of the Anatomy of a LightSwitch Application by examining the presentation tier-also known as the client. A LightSwitch 1.0 client is a Silverlight 4.0 application. The client can run either as a Windows desktop application or hosted in a browser. The Windows desktop mode uses Silverlight's out-of-browser capability.
The client is responsible primarily for human interaction, data visualization and data entry. While these may sound simple, there really is a lot to it. The client should be easy to deploy and upgrade. It should have good looking, intuitive and functional visuals, including keyboard-accessibility. It must track data changes and updates and perform business logic such as data validation. It must handle threading and asynchrony, be responsive, and interact efficiently with the logic and data tiers. Even with all of the great .NET technologies available, there is a lot to putting it all together! The LightSwitch design philosophy aims to simplify creating great clients by providing a solid architectural foundation and letting the developer focus on the screens, data and logic that are specific to their business problem.
As Julius Caesar might say, the LightSwitch client est omnis divisa en partes tres. Or rather, it is divided into three parts, 1) the shell, 2) screens, and 3) the data workspace.
Even if you don't remember your Gallic War commentaries, let's divide and conquer to get a general understanding of the LightSwitch client. We'll cover the following areas.
  • The LightSwitch Shell
  • LightSwitch Business Objects and Business Rules (Screens and Entities)
  • The LightSwitch Screen
  • The LightSwitch Data Workspace

The LightSwitch Shell

The LightSwitch shell is made up of the hosting process, the shell UI, and the theming service.

Hosting Process

For a LightSwitch desktop application, we configure the application to allow out-of-browser install and we control the application startup sequence to ensure that the application is indeed installed and running in the out-of-browser host (sllauncher.exe). We configure desktop application to require elevated permissions. This gives LightSwitch desktop applications access Windows and Office automation and enables the built-in "Export to Excel" capability from within screens.
A LightSwitch browser application can be hosted within any browser and on any OS that Silverlight 4.0 supports. The application runs in the Silverlight sandbox. Access to OLE automation is not available (no "Export to Excel") and access to the Windows file system is restricted. LightSwitch handles the common problem where navigating away from the page or closing the browser would terminate the application when there are unsaved changes in a screen.
LightSwitch manages the application startup, upgrade, and shutdown sequences.

Shell UI

The application shell provides the root-level user interfaces for logging in, launching and activating screens. The shell UI is pluggable. LightSwitch comes with a default shell, but one can write a custom shell and plug it in via a LightSwitch Extension package. This design enforces consistent behavior in the application while allowing overall the look and feel to be highly customized.
The application shell follows the MVVM pattern. The UI controls (views) are pluggable. The LIghtSwitch runtime provides several shell-related view models that the shell view controls bind to. These include:
  • Current user
  • Application logo
  • Screen activation and navigation
  • Active screens
  • Screen commands
  • Screen validation errors
If this all sounds complicated, don't worry. The developer just uses the LightSwitch IDE to pick a pre-built shell-and it just works! You can use the Visual Studio Gallery to find and download shells that are published by the community and by vendors.

Theming Service

LightSwitch supports a basic level of theming to control colors, fonts, and to support the OS high-contrast themes. The intrinsic Silverlight controls support simple styling. LightSwitch goes one further by defining a set of styles as a theme and ensuring that the controls we use for the shell and in screens will select styles from the current theme. Themes are extensible and can be created and added via a LightSwitch Extension package.

Business Objects and Business Rules

LightSwitch business objects are the foundational components for defining the business logic of your application. There are two basic kinds of business objects: screens and entities. Screens represent a unit of work on the client (a client use-case) and entities represent an identifiable and durable piece of business data. When you define a business object in LightSwitch, you can also attach business rules to it. LightSwitch business rules help you to encapsulate the business logic where it belongs. No more putting all of your inventory update logic behind a button click event!
Business rules are associated with a business object or a member (a property or command) of the object. Business rules come in several categories:
Computed Property - a read-only property on an entity or screen that is dynamically evaluated
Validation Rule - a rule on an entity or screen property that returns a set of validation results based on the state of the object
Read-Only Rule - a rule on an entity or screen property that determines the present UI read-only state of the property
Can-Execute Rule - a rule on a command that determines whether it is presently available for execution
LightSwitch automatically evaluates and keeps track of these business rules. Evaluation is lazy and just-in-time: If no one is observing the state of a rule, the rule will not be evaluated. The rule is guaranteed to be up-to-date at the point you observe its value.
The result of a business rule is observable in the API from the Details property on the member to which the rule is applied. The Details property also includes other view-model state such as display name and description. Here are some example Details properties for a FirstName property and a PostOrder command.
customer.Details.Properties.FirstName.DisplayName
customer.Details.Properties.FirstName.IsReadOnly
customer.Details.Properties.FirstName.ValidationResults.HasErrors
screen.Details.Commands.PostOrder.CanExecute
Business rules are typically associated with a block of code-similar to an event handler. LightSwitch tracks the dependencies of the rule during runtime evaluation. In this way we know when the value of a rule is "dirty" and must be re-evaluated. So long as the code refers to data elements defined on itself or another business object, we can track it properly. However, if the code refers to something that is not defined on a business object, such as DateTime.Now, LightSwitch can't track that. But you can force re-evaluation of a rule programmatically.
Some business rules are declarative and specified at design-time. There are several built-in declarative validation rules. Declarative validation rules are also extensible. You can create new ones and publish them via a LightSwitch Extension package.

Screens

A LightSwitch screen represents and independent unit of work on the client. Each screen has isolated state from other screens-there is no shared data between screens. Multiple screens can be opened simultaneously, but the shell keeps track of a single active screen.
LightSwitch screens are made up of three layers of objects that follow the MVVM pattern. The screen object is the model, encapsulating the data and business logic. The screen layout defines a tree of view-models that define the logical layout of the screen. And the visual tree is the resulting presentation view. The visual tree is made up of actual Silverlight controls that are data-bound to the view-models in the screen layout.

Screen Object

The screen object is a LightSwitch business object that contains the data and business logic for a given screen-but no UI. It defines a sort of data-type for the screen's internal state. At design-time, developer writes code against the screen object's class to provide custom business logic for the screen.
When defining a screen, the developer can add properties (scalar or entity values), parameters (scalar values), screen collections (query results), and commands. For each of these members, LightSwitch tracks detail properties such as display name, enable and read-only states, the data-loaded state, and validation results. The detail properties provide additional model state for the screen layout.
Each instance of a running screen owns its own isolated state. No two screens can share the same copy of an entity, but each can have its own copy. This is all managed by the screen's data workspace which is described in more detail below.

Screen Layout

The screen layout is a tree of content items. A content item is a view model that represents a single element on the screen. It forms a data-bindable bridge between the screen object (model) and the visual tree (view). Each content item may represent some data item, list, or command that is reachable from the screen object. It may also represent a container for child content items. Each content item specifies a control type and properties that govern the display behavior. The control type is just a name that will be mapped at runtime to an appropriate visual control.
When a screen is created, the LightSwitch runtime builds the screen layout tree dynamically by interpreting the screen layout model that was persisted via the screen designer at design-time. Content items are accessible programmatically from screen code for advanced scenarios. In most cases, you will not need to access it to define the business logic for a screen, but it may be useful to control the presentation.

Screen Visual Tree

The visual tree is the actual tree of Silverlight controls that present the screen. The LightSwitch developer typically does not interact with the visual tree. LightSwitch builds the visual tree dynamically by walking the screen layout tree at runtime. The layout strategy specified by each content item node is used to activate the right Silverlight control. The control is then given the content item as its DataContext. The control binds to various properties of the content item in order to display such things as the current value, display name, or to determine child elements to display.
This dynamic layout strategy provides two important benefits. The first is professional 2D flow, spacing, control alignment, and automatic placement of labels. This is a huge time saver-no hours spent tweaking the layout margins, borders, alignment, etc. The second benefit is the ability to modify running screens when running from the LightSwitch tool. When the screen is in runtime design mode, the runtime editor simply modifies the screen layout and content items dynamically. The screen runtime can render the new visual tree dynamically and provide immediate live feedback to the developer.

Where's my XAML?

If you area already familiar with using the Silverlight presentation framework, you might be wondering where XAML is. The short answer is-there isn't any. LightSwitch developers aren't required to know XAML to build screens. LightSwitch saves the logical layout of the screen and dynamically creates the visual tree based on Silverlight controls that are registered for each data and layout type.
When you need more control of the UI, you can drop down to the XAML level by plugging in just about any Silverlight control as the presenter for any content item. You can even replace the entire screen. This feature allows you to wire-up an off-the-shelf control or to write your own. If you write your own, you can still inject LightSwitch data presenters and get the built-in presentation support for LightSwitch data elements.

Data Workspace

The data in a screen is managed by a data workspace. The data workspace tracks local copies of entities. An entity type represents a specific kind of data record. The entity encapsulates the business data, business logic, and durable storage for the data. The data workspace is responsible for fetching entities from a data service in the logic tier via entity queries, for tracking changes, and for sending updates back to data service for processing. The data workspace also tracks relationships between entities.

Data Service Client

When you add a data source to a LightSwitch application, we create a data service for accessing its data. The data services lives in the logic tier. The client accesses it via a data service client. A data workspace aggregates data from multiple sources by providing one data service client instance per data service.
For example, if you add a Northwind SQL data source and a MySharePoint data source, you'll see one data service client for each in the data workspace.
The data service client manages the entities and tracks changes (change set) for the corresponding data service. LightSwitch manages the granularity of updates in the following way: One screen has one screen Save command which invokes one data service with one change set which runs in one update transaction.
The data service client exposes entity query operations and update operations. In the following examples "Northwind" is a data service client.
var customer = this.DataWorkspace.Northwind.Customers_Single(customerId);this.DataWorkspace.Northwind.SaveChanges();

Entities

Entities are the center of gravity for data and business logic in a LightSwitch application. These represent persistent business data such as a Customer, an Invoice, a Book or a TimeCardEntry. In LightSwitch you can define new entity types and we will create the corresponding storage in SQL tables. Or you can import the schema from an existing data source and LightSwitch will define the corresponding entity types.
Entities encapsulate business logic including validation rules, data update rules, and have attributes that drive defaults for visualization and data entry. Entities are also shared between the client and the logic tier, so that you write business logic such as validation once and LightSwitch can execute it on both tiers.
In the client runtime, LightSwitch uses a pair of objects to represent an entity instance. There is a hidden, low-level data-transfer-object (DTO) that integrates with the WCF RIA Services client. A there is a public business object that encapsulates the business logic and provides view-model support for data binding. The section above regarding business objects applies. The entity has business rules for data validation, computed properties, and computed read-only status. The entity object has an API for getting to the simple data values on the entity and a more advanced API for accessing the validation status and various other attributes such as the default display name and description of each member.

Entity Relationships

LightSwitch models and manages relationships between entities. It supports cardinalities of many-to-one, many-to-zero-or-one, and one-to-zero-or-one. It does not support one-to-one and does not directly support many-to-many. You can, however, manage many-to-many relationships by using your own join entity.
LightSwitch creates navigation properties on entities to manage the entity or entities on the other side of the relationship. An entity reference property points to a single entity and an entity collection property points to many. Navigation properties encapsulate the details of foreign keys, so you don't typically deal with those directly. LightSwitch handles loading the related entities on-demand when the navigation property is requested.
We are all familiar with relationships within a single data source. LightSwitch also supports inter-data-source relationships. These relationships cannot guarantee referential integrity, but they are very convenient for managing associated external data that shares a common value such as an ID or an email address.

Entity Queries

LightSwitch models a table in the storage tier as an entity set in the logic tier. Each entity set is exposed by a data service client as a queriable entity sets and as query operations.
Query operations support query composition. This means that when the client invokes a query operation, it can send over additional query predicates to further refine the filter and ordering of the query. LightSwitch uses query composition to compose queries from screens and from LINQ queries in client-side business logic. Under the hood the LightSwitch client uses WCF RIA Services to create the query request and serialize it to a DomainService on the logic tier.
The LightSwitch client attempts to parallelize query execution as much as possible to improve client response times. For example, when a single screen attempts to load multiple lists, the queries are executed asynchronously and in parallel. Likewise, when two different screens run, their queries (and updates) are executed in parallel. However, LightSwitch business logic code loads data from queries and navigation properties synchronously to keep the API simple to use and easy to understand.
We will look into what happens in the logic tier during a query operation in a later post.

Entity Updates

The data service client exposes a single SaveChanges operation. This operation packages up the change set for that data service and sends it to the logic tier for processing. LightSwitch implements a DomainService (WCF RIA Services) in the logic tier to process the update.
LightSwitch ensures that the data is valid on the client before processing the SaveChanges operation. If the client data is valid, it is sent to the data service where it is validated again. If modified entities on the client have validation errors, the screen's Save command is automatically disabled to prevent the end-user from attempting to save bad data.
Just as with entity queries, there is a lot going on in the logic tier to process the update. We will get into those details in a later post when we cover the logic tier.

Summary

We came, we saw, and we conquered the client. Well, actually, there is a lot more to be said about all of this. We've looked briefly at the shell, screens, and the data workspace. In our next posts we'll look at the logic tier and the storage tier.

The Anatomy of a LightSwitch Application Series Part 1 - Architecture Overview

Ref: LightSwitch.
The announcement of Visual Studio LightSwitch this week has generated a lot of discussion, and as expected a number of questions about "what is LightSwitch really building under the covers?".  To help shed some light on that (sorry, could resist) we're putting together a blog series that takes a more in depth look at the Anatomy of a LightSwitch application.  We'll start with this high-level architectural overview and then drill into each architectural layer and other specific topics over the coming weeks. 
Here's an outline of topics we're thinking about:
With that, let's get started...
The Anatomy of a LightSwitch Application - Architecture Overview
Microsoft Visual Studio LightSwitch applications are built on a classic three-tier architecture. Each tier runs independently of the others and performs a specific role in the application. The presentation tier is responsible for human interaction with the application. Its primary concern is data visualization and editing. The logic tier processes requests from a client to fetch data, update data, or to perform other operations. This tier’s primary role is to shield direct access to the data from unwanted or invalid reads and updates. This helps to ensure the long-term integrity and security of the data. The data storage tier is responsible for durable storage of the application data.
A typical three-tier application

Designing a new three-tier application from scratch can be difficult and complex. Each tier presents a myriad of technology choices and internal system design. Each has distinct deployment and manageability concerns. Each must handle communications with the adjacent tier, and ensure secure access from trusted sources.
LightSwitch removes the complexity of building a three-tier application by making specific technology choices for you. You concentrate on the business logic and not the plumbing.
When we map the specific technologies used in LightSwitch to this architecture you find that the LightSwitch presentation tier is a Silverlight 4.0 application. It can run as a Windows desktop application or hosted in a browser. The LightSwitch logic tier exposes a set of WCF RIA DomainServices running in ASP.NET 4.0. The logic tier process can be hosted locally (on the end-user’s machine), on an IIS server, or in a Windows Azure WebRole. A LightSwitch application’s primary application storage uses SQL Server or SQL Azure and can consume data from existing SharePoint 2010 lists, databases accessible via an Entity Framework provider, and custom build WCF RIA DomainServices.
A LightSwitch 1.0 three-tier application

As you can see, a LightSwitch application is built on top of existing .NET technologies and proven architectural design patterns.

LightSwitch

Introduction to Visual Studio LightSwitch

Ref: LightSwitch.

Microsoft Visual Studio LightSwitch helps you solve specific business needs by enabling you to quickly create professional-quality business applications, regardless of your development skills. LightSwitch is a new addition to the Visual Studio family. Visual Studio LightSwitch is designed to simplify and shorten the development of typical forms-over-data business applications.
Introduction to LightSwitch
Most business applications have a large code base dedicated to addressing operations that create, read, update and delete elements (CRUD). Typically, in this kind of application, a large amount of time is spent on the following development tasks:
  • Writing code to interact with a data source.
  • Creating a User Interface.
  • Writing code to specify the business logic.
With LightSwitch, you can use databases which are automatically created or point to an existing data source without the need to write code. To help with the User Interface, LightSwitch provides Screens that are based on predefined templates and display data automatically by simply specifying which elements you want to show.
Regarding the business logic, simple validation such as required fields and minimum numeric values can be handled through a designer. LightSwitch also gives developers the ability to write more complex business logic code for various scenarios, such as saving changes to a data source or performing authorization operations.

Design Pattern - Composite

Definition
Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly. (include abstract class as a component of sub-class).

UML Class Diagram

Composite: when and where use it
- The Composite design pattern is an in-memory data structures with groups of objects, each of which contain individual items or other groups. A tree control is a good example of a Composite pattern. The nodes of the tree either contain an individual object (leaf node) or a group of objects (a subtree of nodes).  All nodes in the Composite pattern share a common interface which supports individual items as well as groups of items.
This common interface greatly facilitates the design and construction of recursive algorithms that iterate over each object in the Composite collection. 

- Fundamentally, the Composite pattern is a collection that you use to build trees and directed graphs. It is used like any other collection, such as, arrays, list, stacks, dictionaries, etc. 

Sample
- Component abstract class

- Component concrete class

- Main class


Ref: Gang of Four tutorial