Introduction to Visual Studio LightSwitch

[Infragistics] Mihail Mateev / Wednesday, September 1, 2010

Introduction to Visual Studio LightSwitch

LightSwitch is primarily targeted at developers who need to rapidly product business applications.  It is part of the Visual Studio family and when you get into writing code you are in the VS IDE.

 

Overview

 Visual Studio LightSwitch helps you rapidly produce line of business applications by optimizing for the most common application patterns (data + screens + code).  LightSwitch allows you to create desktop applications (the default) or browser applications.  The applications you produce follow a classic three-tier architecture and are built on top of .NET (Entities, WCF RIA Services), Silverlight, ASP.NET, with access to multiple sources of data like SQL Server and SharePoint. LightSwitch implements the best practices in the User Experience Design

 To get a technical rundown about Infragistics and LightSwitch, check out IG resident LightSwitch expert Matt Van Horn’s blog here.

Architecture:

Microsoft Visual Studio LightSwitch applications are built on 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.

 

Important Features:

  • There is no visual form designer - at least, not in the traditional Microsoft style we have become used to.

 

 

Visual Studio LightSwitch Designer

 

  • LightSwitch has runtime form customization. Actually it is not quite "runtime", but only works when running in the debugger. When you run a screen, you get a "Customize Screen" button:

 

 

  • LightSwitch is model driven. When you create a LightSwitch application you are writing out XAML, not the XAML you know that defines a WPF layout, but XAML to define an application. If you look at the ApplicationDefinition.lsml file - it starts like this:

 

 

  • LightSwitch uses business data types, not just programmer data types. I mean types like EmailAddress, Image, Money and PhoneNumber:

 

  • There is a relationship builder that is genuinely easy to use, but which still handles tricky things like many-to-many relationships and cascading deletes.

 

  • LightSwitch is a database application builder that does not use SQL. The query designer is entirely visual, and behind the scenes Linq (Language Integrated Query) is everywhere.

 

  • LightSwitch applications are cloud-ready. In the final release (but not the beta) you will be able to publish to Windows Azure. Even in the beta, LightSwitch apps always use WCF RIA Services, which means they are web-oriented applications. Data sources supported in the beta are SQL Server, SharePoint and generic WCF RIA Services. Apparently in the final release Access will be added

 

Create a Sample LighSwitch Application:

In this article I will create a LightSwitch application, using C#.
Application will present a data for products, customers and orders.
Data will be stored in a local SQL Server 2008 Database and will be created when build an application.

 

Requirements:

 

It could be a problem if install it on a production environment and share code with other team members that has no this version of Silverlight.

 

  • Hardware Requirements

Minimum: 1.6 GHz CPU, 192 MB RAM, 1024x768 display, 5400 RPM hard disk

Recommended: 2.2 GHz or higher CPU, 384 MB or more RAM, 1280x1024 display, 7200 RPM or higher hard disk

On Windows Vista: 2.4 GHz CPU, 768 MB RAM

1.3 GB of available disk space for the full installation

 

Steps to implement a sample application:

  • 1. Create a new LightSwicth Application (Visual C#).
  • 2. Create a sample data for products, customers, orders and order lists
  • 3. Add search screens for products, customers and orders tables.
  • 4. Add custom new data screen and detail screen for products.
  • 5. Add list and details screen for customers.
  • 6. Run the sample application.

 

Create a new LightSwicth Application

Start Visual Studio LightSwitch. Create a new project-> LightSwicth Application (Visual C#).

 

 

Create a sample data for products, customers, orders and order lists

Database for the LightSwitch sample application contains four tables:

Products, Customers, Orders and OrderLists.

IGProducts table contains data for IG Products.
(all data except product names is imaginary).

 

 IGCustomers table contains data for sample customers:

 

IGOrders table contains data for orders. There is a data of the order, relations to order list (list with a products and lumber of licenses for each order)
and customer, who made the order.

 OrderList table contains a list of products and number of licenses for a specific order.

 

 

Relationships between tables are created with UI via Add:relationship and selecting the table in a relationship with a current one:

 Add a Choice List for ProductCategory field in the IGProducts table.

ChoiceList is a list of possible values (something like an enum).

 Select a Choice List link.

 

 Add items in a list.

 Add a custom validation for FirstName and LastName in the IGCustomers table:

 

For the FirstName and LastName fields in Properties page select a link Custom Validation":

    public partial class IGCustomers

    {

        partial void FirstName_Validate(EntityValidationResultsBuilder results)

        {

            // results.AddPropertyError("<Error-Message>");

            if (this.FirstName != null &&

                    !System.Text.RegularExpressions.Regex.IsMatch(this.FirstName, @"^[a-zA-Z]+$"))

            {

                results.AddPropertyError("Invalid characters in FirstName. Only alphabets allowed.");

            }

 

 

        }

 

        partial void LastName_Validate(EntityValidationResultsBuilder results)

        {

            // results.AddPropertyError("<Error-Message>");

 

            if (this.LastName != null &&

                   !System.Text.RegularExpressions.Regex.IsMatch(this.LastName, @"^[a-zA-Z]+$"))

            {

                results.AddPropertyError("Invalid characters in LastName. Only alphabets allowed.");

            }

 

        }

    }

 


Code behind is a simple C# code that checks if string values contains no alphabetical symbols.

Make a field OrderTotal in the IGOrders computed and edit a method for its calculation:

In the Properties grid check "IsComputed" and select "Edit Method":

    public partial class IGOrders

    {

        partial void OrderTotal_Compute(ref string result)

        {

            double sum = 0;

            foreach (OrderList list in this.OrderListItems)

            {

                if (list.IGProducts != null)

                {

                    sum += list.Quantity * (double)list.IGProducts.Price;

                }               

            }

 

            // Set result to the desired field value

            result = String.Format("{0:0.00}", sum);

        }

    }

 

Code behind is a simple C# code that makes a sum for all product prices in the order list , multiplied by number of licenses.

The application database is placed in %Application Folder%\Bin\Data folder.

 

  •  Add search screens for products, customers and orders tables

 

SearchIGCustomers screen editor

 

  • Add custom new data screen and detail screen for products.

Add a screens for create a product and edit a product:

CreateNewIGProducts screen has a different size for Image Editor, used for logo.

 

Add a custom code ExecuteCommand methods for create product and edit product commands in IGProducts:

    public partial class EditableIGProductsGrid

    {

        partial void gridEditSelected_CanExecute(ref bool result)

        {

            // Write your code here.

 

        }

 

        partial void gridEditSelected_Execute()

        {

            // Write your code here.

            int id = this.IGProductsCollection.SelectedItem.Id;

            Application.ShowIGProductsDetail(id);

        }

 

        partial void gridAddAndEditNew_CanExecute(ref bool result)

        {

            // Write your code here.

 

        }

 

        partial void gridAddAndEditNew_Execute()

        {

            // Write your code here.

            Application.ShowCreateNewIGProducts();

        }

    }

 

C# code behind shows the specified screens.

  • Add list and details screen for customers and products.

 

Add a List and Detail Screen for IGCustomers table. Do the same for IGProducts.

 

IGCustomersListDetail screen designer.

  • Run the sample application:

 

The start screen - IGProducts editable screen.

 

Using a custom IGProductDetail screen.

 

SearchIGCustomers screen proposes an easy powerful searching.

 

IGCustomersListDetail is a list and detail screen for customers that proposes all customers maintain in one screen.

Source code of the demo application you could download here: