Click here to Skip to main content
15,881,089 members
Articles / Programming Languages / C# 4.0

A Random Walk Through of the LightSwitch Data Model

Rate me:
Please Sign up or sign in to vote.
4.93/5 (20 votes)
10 Sep 2011Ms-PL4 min read 41.3K   563   22   17
We will create a Silverlight Custom Control called “LightSwitch Explorer” that will display information about the collections of the screen that it is displayed on, raise methods, and switch screens.

image

Introduction

When you write code in the LightSwitch client layer, you have programmatic access to most of the application. This also applies when you use Silverlight Custom Controls. This is important because it saves you from writing a lot of code. A professional developer can be far more productive when creating a LightSwitch application than when they are coding a Silverlight application without using LightSwitch.

You have the option of Running a LightSwitch Application with a Blank Shell. When you do that, you still have access to all the features described in this article.

In this article, we will take a random walk through of the LightSwitch API (Application Programming Interface) to give you an idea of the programmatic access available to you from a LightSwitch Silverlight Custom Control (this also applies to LightSwitch Control Extensions).

image

This page describes the LightSwitch Data Model. There are a lot of classes covered, and the diagram is a very broad overview. However, it does describe the relationship between the major parts.

Note: You must have Visual Studio Professional (or higher) to create a Silverlight control using the method described in this article.

The LightSwitch Explorer Application

We will take our random walk through of the LightSwitch API by creating a sample LightSwitch application. We will create a Silverlight Custom Control called “LightSwitch Explorer” that will display information about the collections of the screen that it is displayed on, raise methods, and switch screens.

image

We create a simple LightSwitch application that allows Products and Orders to be managed.

image

One screen for Products.

image

One screen for Orders.

The Silverlight Control

image

Add a new project to the Solution.

image

We add a Silverlight Class Library.

image

We select Silverlight 4.

image

The Project will show in the Solution Explorer, we right-click on the Class1.cs file and delete it.

image

We add a New Item to the SilverlightControlLibrary project.

image

We add a Silverlight User Control, and call it LightSwitchExplorer.xaml.

image

We right-click on References, and select Add Reference.

image

We add references to:

  • Microsoft.LightSwitch
  • Microsoft.LightSwitch.Base.Client
  • Microsoft.LightSwitch.Client

This will allow access to the LightSwitch API in the code-behind file in the LightSwitchExplorer.xaml control.

image

We open the LightSwitchExplorer.xaml.cs file, and add the following using statements:

  • using Microsoft.LightSwitch;
  • using Microsoft.LightSwitch.Client;
  • using Microsoft.LightSwitch.Details;
  • using Microsoft.LightSwitch.Details.Client;
  • using Microsoft.LightSwitch.Model;
  • using Microsoft.LightSwitch.Presentation;
  • using System.Windows.Data;
  • using System.Collections;

image

We open the LightSwitchExplorer.xaml file, and change the markup to the following:

This add a Grid and three ListBoxes.

XML
<UserControl x:Class="SilverlightControlLibrary.LightSwitchExplorer"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">
    <Grid x:Name="LayoutRoot" Background="White">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="122*" />
            <ColumnDefinition Width="122*" />
            <ColumnDefinition Width="122*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="20*" />
            <RowDefinition Height="100*" />
            <RowDefinition Height="177*" />
        </Grid.RowDefinitions>
        <ListBox HorizontalAlignment="Stretch" 
           VerticalAlignment="Stretch" Margin="5,5,5,5"                   
           Name="lstMethods" Grid.Row="1" 
           Grid.Column="1"  />
        <ListBox HorizontalAlignment="Stretch" 
           VerticalAlignment="Stretch" Margin="5,5,5,5"
           Name="lstActiveScreens" Grid.Row="1"  />
        <ListBox HorizontalAlignment="Stretch" 
           VerticalAlignment="Stretch" Margin="4,5,5,5"                  
           Name="lstApplicationDetailsProperties" 
           Grid.Column="2" Grid.Row="1"  />
   </Grid>
</UserControl>

image

We drag and drop a DataGrid on the page.

This will automatically add the needed assemblies to support the DataGrid.

image

We click and drag the corners of the grid to size it so it fills the entire bottom half of the page.

image

In the Properties for the DataGrid, we check the box next to AutoGenerateColumns.

image

We drag and drop a Label above the first box and change its Content to “Active Screens”.

image

We add two more Labels and name them Methods and Collections.

Add Code to the Silverlight Control

image

Open the LightSwitchExplorer.xaml.cs file, and add the following code:

C#
// This property is created because it allows us to raise 
// "OnExplorerControlDataContextPropertyChanged"
// When the DataContext is updated
public static readonly DependencyProperty ExplorerControlDataContextProperty =
    DependencyProperty.Register("DummyProperty", typeof(IContentItem),
    typeof(LightSwitchExplorer),
    new PropertyMetadata(OnExplorerControlDataContextPropertyChanged));

image

Next, add this line after the InitializeComponent(); line:

C#
this.SetBinding(ExplorerControlDataContextProperty, new Binding());

This sets the binding for ExplorerControlDataContextProperty.

Add the following methods:

C#
#region ShowMethodsOnScreen
private static void ShowMethodsOnScreen(LightSwitchExplorer EC, 
                    IContentItem contentItem)
{
    // Fill the lstMethods ListBox with
    // a list of all Methods on the current Screen
    foreach (var item in contentItem.Screen.Details.Commands.All())
    {
        EC.lstMethods.Items.Add(item.Name);
    }
}
#endregion

#region ShowActiveScreens
private static void ShowActiveScreens(LightSwitchExplorer EC, 
                    IContentItem contentItem)
{
    // Fill the lstActiveScreens ListBox with a list of all Active Screens
    foreach (var item in contentItem.Screen.Details.Application.ActiveScreens)
    {
        EC.lstActiveScreens.Items.Add(item.Screen.Name);
    }
}
#endregion

#region ShowScreenCollections
private static void ShowScreenCollections(LightSwitchExplorer EC, 
               IContentItem contentItem)
{
    // Fill the lstApplicationDetailsProperties ListBox with a list of all 
    // Collections on the current Screen
    foreach (var item in contentItem.Screen.Details.Properties.All())
    {
        EC.lstApplicationDetailsProperties.Items.Add(
                         String.Format("{0}", item.Name));
    }
}
#endregion

Finally, add the following method that will raise the previous methods when the DataContext is set or changed:

C#
private static void OnExplorerControlDataContextPropertyChanged(
        DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    LightSwitchExplorer EC = (LightSwitchExplorer)d;
    IContentItem contentItem = (IContentItem)EC.DataContext;
    ShowActiveScreens(EC, contentItem);
    ShowMethodsOnScreen(EC, contentItem);
    ShowScreenCollections(EC, contentItem);
}

Insert the Silverlight Control into the Application

image

Build the Solution.

image

Open the EditableProductsGrid screen, and add a New Custom Control.

image

Click the Add Reference button.

image

Create a Project reference to the SilverlightControlLibrary project.

image

We will now be able to select the Custom Control we created.

image

In the Properties for the control, set the Label Position to None.

image

When we run the application, we see that the control displays the Active Screens, the methods on the current screen, and the Collections on the current screen.

Make the Explorer Control Interactive

image

Return to the Silverlight Control, and double-click on the Active Screens ListBox.

image

The method will be wired-up.

Use the following code for the method:

C#
private void lstActiveScreens_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    // Get the LightSwitch DataContext
    IContentItem contentItem = (IContentItem)this.DataContext;
    // The selected screen
    string strScreenName = (sender as ListBox).SelectedValue.ToString();
    // Get the selected Screen
    var SelectedScreen = (from ActiveScreens in 
            contentItem.Screen.Details.Application.ActiveScreens.AsQueryable()
            where ActiveScreens.Screen.Name == strScreenName
            select ActiveScreens).FirstOrDefault();
    if (SelectedScreen != null)
    {
        // Activate the selected Screen
        SelectedScreen.Activate();
    }
}

image

Double-click on the Methods ListBox.

Use the following code for the method:

C#
private void lstMethods_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    // Get the LightSwitch DataContext
    IContentItem contentItem = (IContentItem)this.DataContext;
    // The selected Method
    string strMethodName = (sender as ListBox).SelectedValue.ToString();
    var Method = (from Commands in contentItem.Screen.Details.Commands.All()
                  where Commands.Name == strMethodName
                  select Commands).FirstOrDefault();
    if (Method != null)
    {
        // Get a reference to the LightSwitch Screen
        var Screen =
        (Microsoft.LightSwitch.Client.IScreenObject)contentItem.Screen;
        Screen.Details.Dispatcher.BeginInvoke(() =>
        {
            Method.Execute();
        });
    }
}

image

Double-click on the Collections ListBox.

Use the following code for the method:

C#
private void lstApplicationDetailsProperties_SelectionChanged(object sender, 
                                  SelectionChangedEventArgs e)
{
    // Get the LightSwitch DataContext
    IContentItem contentItem = (IContentItem)this.DataContext;
    // The Property Name
    string strPropertyName = (sender as ListBox).SelectedValue.ToString();
    var Property = (from Properties in contentItem.Screen.Details.Properties.All()
                    where Properties.Name == strPropertyName
                    select Properties).FirstOrDefault();
    dataGrid1.ItemsSource = (IEnumerable)Property.Value;
}

The Explorer Control

image

Add the Explorer Control to the other pages of the application.

  • You can click on the Active Screens to switch screens
  • You can click on the Methods to execute them
  • You can click on the Collections to see their contents (and edit them)

This is Barely Scratching the Surface

This example barely touches upon all that is available to the LightSwitch developer. Information about the user, the complete database schema and data, and the entire application is available.

Operations that would normally take hundreds of lines of code to manually create in a Silverlight application can be achieved with half a dozen when using LightSwitch.

Special Thanks

A special thanks to Sheel Shah of Microsoft, because otherwise this article would not have been possible.

Further Reading

More LightSwitch Content

You can find a ton of articles on advanced Visual Studio LightSwitch programming at http://lightswitchhelpwebsite.com/.

History

  • 10th September, 2011: Initial version

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)


Written By
Software Developer (Senior) http://ADefWebserver.com
United States United States
Michael Washington is a Microsoft MVP. He is a ASP.NET and
C# programmer.
He is the founder of
AiHelpWebsite.com,
LightSwitchHelpWebsite.com, and
HoloLensHelpWebsite.com.

He has a son, Zachary and resides in Los Angeles with his wife Valerie.

He is the Author of:

Comments and Discussions

 
QuestionHow to bind SelectedItem of DataGrid to the screen query's SelectedItem property? Pin
Roger Martin31-Dec-11 10:54
professionalRoger Martin31-Dec-11 10:54 
AnswerRe: How to bind SelectedItem of DataGrid to the screen query's SelectedItem property? Pin
defwebserver31-Dec-11 12:06
defwebserver31-Dec-11 12:06 
GeneralRe: How to bind SelectedItem of DataGrid to the screen query's SelectedItem property? Pin
Roger Martin2-Jan-12 5:44
professionalRoger Martin2-Jan-12 5:44 
GeneralMy vote of 5 Pin
chirismirgh14-Oct-11 5:21
chirismirgh14-Oct-11 5:21 
GeneralRe: My vote of 5 Pin
defwebserver16-Oct-11 6:43
defwebserver16-Oct-11 6:43 
Thank you for voting Smile | :)
GeneralMy vote of 5 Pin
Marcelo Ricardo de Oliveira14-Sep-11 6:30
Marcelo Ricardo de Oliveira14-Sep-11 6:30 
GeneralRe: My vote of 5 Pin
defwebserver14-Sep-11 6:32
defwebserver14-Sep-11 6:32 
GeneralMy vote of 5 Pin
Filip D'haene13-Sep-11 11:47
Filip D'haene13-Sep-11 11:47 
GeneralRe: My vote of 5 Pin
defwebserver13-Sep-11 12:02
defwebserver13-Sep-11 12:02 
GeneralMy vote of 5 Pin
SmokYang13-Sep-11 7:33
SmokYang13-Sep-11 7:33 
GeneralRe: My vote of 5 Pin
defwebserver13-Sep-11 12:02
defwebserver13-Sep-11 12:02 
GeneralMy vote of 5 Pin
Kunal Chowdhury «IN»12-Sep-11 5:41
professionalKunal Chowdhury «IN»12-Sep-11 5:41 
GeneralRe: My vote of 5 Pin
defwebserver13-Sep-11 5:46
defwebserver13-Sep-11 5:46 
QuestionGood One Pin
powerbala12-Sep-11 4:45
powerbala12-Sep-11 4:45 
AnswerRe: Good One Pin
defwebserver12-Sep-11 5:24
defwebserver12-Sep-11 5:24 
GeneralMy vote of 5 Pin
Pete O'Hanlon12-Sep-11 4:00
mvePete O'Hanlon12-Sep-11 4:00 
GeneralRe: My vote of 5 Pin
defwebserver13-Sep-11 5:47
defwebserver13-Sep-11 5:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.