Click here to Skip to main content
Click here to Skip to main content

A Random Walk Through of the LightSwitch Data Model

, 10 Sep 2011
Rate this:
Please Sign up or sign in to vote.
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: http://msdn.microsoft.com/en-us/library/gg445195.aspx. 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.

<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 fill 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:

// 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:

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

This sets the binding for ExplorerControlDataContextProperty.

Add the following methods:

#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:

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:

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:

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:

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

License

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

Share

About the Author

defwebserver
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
LightSwitchHelpWebsite.com

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

He is the Author of:
Follow on   Twitter

Comments and Discussions

 
QuestionHow to bind SelectedItem of DataGrid to the screen query's SelectedItem property? PinmemberRoger Martin31-Dec-11 10:54 
AnswerRe: How to bind SelectedItem of DataGrid to the screen query's SelectedItem property? Pinmvpdefwebserver31-Dec-11 12:06 
GeneralRe: How to bind SelectedItem of DataGrid to the screen query's SelectedItem property? PinmemberRoger Martin2-Jan-12 5:44 
GeneralMy vote of 5 Pinmemberchirismirgh14-Oct-11 5:21 
GeneralRe: My vote of 5 Pinmvpdefwebserver16-Oct-11 6:43 
GeneralMy vote of 5 PinmvpMarcelo Ricardo de Oliveira14-Sep-11 6:30 
GeneralRe: My vote of 5 Pinmvpdefwebserver14-Sep-11 6:32 
GeneralMy vote of 5 PinmemberFilip D'haene13-Sep-11 11:47 
Excellent article!
 
Thanks for sharing. Smile | :)
GeneralRe: My vote of 5 Pinmvpdefwebserver13-Sep-11 12:02 
GeneralMy vote of 5 PinmemberSmokYang13-Sep-11 7:33 
GeneralRe: My vote of 5 Pinmvpdefwebserver13-Sep-11 12:02 
GeneralMy vote of 5 Pinmvp_ Kunal Chowdhury _12-Sep-11 5:41 
GeneralRe: My vote of 5 Pinmvpdefwebserver13-Sep-11 5:46 
QuestionGood One Pinmemberpowerbala12-Sep-11 4:45 
AnswerRe: Good One Pinmvpdefwebserver12-Sep-11 5:24 
GeneralMy vote of 5 PinprotectorPete O'Hanlon12-Sep-11 4:00 
GeneralRe: My vote of 5 Pinmvpdefwebserver13-Sep-11 5:47 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140827.1 | Last Updated 10 Sep 2011
Article Copyright 2011 by defwebserver
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid