Chapter 16. Customizing Applications with Custom Controls

LightSwitch provides a rich extensibility model that allows professional developers to write enhancements and package them up into extensions, and developers of all skill levels can easily install these extensions and use them in their applications. Microsoft understands that developers need to accomplish disparate tasks, and so LightSwitch allows extending applications with custom controls. This does not necessarily mean modifying an application’s architecture. Instead, it means adding custom components that extend the existing default infrastructure.

This chapter explains how to build custom controls with Visual Studio 2010 and Silverlight 4, and how to bind such controls to data. You also learn how to integrate Bing Maps into your screens. Custom controls are actually one of the extensibility points in LightSwitch, so in Chapter 18, “LightSwitch Extensibility: Themes, Shells, Controls, and Screens,” you learn how to package them into extensions. The reason for splitting this material is that you can create custom controls for your own use (no need to share with other developers), but Chapter 18 is all about building and packaging extensions related to the user interface and explains how to package custom controls and publish them to the general public.


Software Requirements

As you discover in a few moments, building custom controls involves Silverlight 4 and additional project templates that are not available in the standalone edition of LightSwitch. Because of this, to fully work through the first and last sections in this chapter, you must have Visual Studio 2010 Professional or higher installed on your development machine. In addition, for custom control examples, you need to install the Silverlight Toolkit, available for free on CodePlex: http://silverlight.codeplex.com.


Building Custom Controls


What This Chapter Assumes About You

This chapter explains how to build custom controls for LightSwitch applications with Visual Studio 2010 and Silverlight 4. If you already have some experience programming with Silverlight, you will find this chapter easy to understand. If you have no Silverlight development experience, however, you might find this chapter challenging. As you can understand, a full discussion about Silverlight 4 is impossible here; it would require an entire book of its own. If you need to learn about Silverlight, visit the Microsoft developer portal (www.silverlight.net) or pick up Silverlight 4 Unleashed, by Laurent Bugnion.


As stated previously in this book, applications built with Visual Studio LightSwitch are 100% .NET applications based on Silverlight 4. The development environment ships with a number of class libraries built upon Silverlight that expose functionalities for accessing data but that also store common reusable controls, as typically happens in the .NET platform. This implies that a LightSwitch application can reference Silverlight class libraries; as a consequence, this also implies that a LightSwitch application can reference and use a Silverlight class library that exposes Silverlight user controls. In other words, you can create Silverlight class libraries and consume Silverlight user controls within a LightSwitch application to extend the user interface with custom components.

This is absolutely great because it opens any number of scenarios. Remember, however, that in Visual Studio LightSwitch, this is the only kind of reference you can add. You create custom controls in LightSwitch by adding a new Silverlight Class Library project to the current solution, and then you add to the new project one or more Silverlight user control items. Then you compose controls the way you already know, except for the data binding (which is explained later in this chapter). If you use Visual Studio LightSwitch, you cannot create custom controls because this particular task requires adding to the solution a new Silverlight project, but the IDE only allows creating LightSwitch applications. To create custom Silverlight controls, you need Microsoft Visual Studio 2010 Professional or higher with LightSwitch installed. This is a requirement if you want to create custom controls directly in your solution, but you can still consume compiled libraries exposing controls in the LightSwitch edition by simply adding a reference to a compiled dynamic link library (DLL) or by installing an extension. In this chapter, you also learn how to reference control libraries, which is the same in the standalone edition. From right now, you learn how to create and consume custom Silverlight controls in LightSwitch. You can create simple or complex controls. The process to create and use elements is exactly the same.

Creating Controls with Visual Studio 2010

The default screen templates in LightSwitch offer a complete infrastructure for displaying data in an appropriate way. Obviously, screens implement just general-purpose controls, but you will sometimes want capabilities that are not available with the built-in controls. Screens in LightSwitch generally use built-in controls, which can be primitive or composite. Primitive controls, such as the Text Box, can be considered simple controls because they are made of just one (visible) element. Composite controls are instead made of multiple simple elements that are aggregated into a complex control, such as the Date Picker or the Data Grid.

In Visual Studio LightSwitch, you can use both simple and complex controls. With Visual Studio 2010, you can create controls from scratch (for example, by inheriting an existing TextBox) or place an existing control (but that is not available in the LightSwitch default controls library) into a class library for use in your application. In this chapter, you learn how to build complex controls, which is a common scenario in the real world.

Remember the Invoice Management application discussed in previous chapters? So far, the application has reached a good quality level and currently implements the most important features available in LightSwitch. In real-world applications, however, you might need to handle situations that are more complex. For example, your boss might want to see a chart that shows products in stock. Advanced scenarios such as this are not covered by LightSwitch because of its particular nature. But you can still take advantage of custom controls to improve the user experience with complex, composite elements. In this section, you learn to leverage the power of screen extensibility by creating a complex control for data visualization by using controls from the Silverlight Toolkit.


Lightswitch Controls from Other Vendors

Important Microsoft partners have developed an ecosystem of LightSwitch controls that you can use with ease and for a small price. They are mentioned further in Chapter 17, “Implementing Printing and Reporting.” Take a look at DevExpress (www.devexpress.com) and Infragistics (www.infragistics.com) control suites for LightSwitch, which include LightSwitch-ready controls with functionalities similar to the Silverlight Toolkit.


To implement a custom control, you first open the Invoice Management project in Visual Studio 2010. When the project is available, select File, Add, New Project. Then, in the New Project dialog, select the Silverlight Class Library template available in the Silverlight templates folder under the Visual Basic (or Visual C#) node. Figure 16.1 shows what this dialog looks like.

Image

Figure 16.1. Adding a new Silverlight class library to the solution.

One Silverlight class library can contain multiple reusable controls, so the name for the new project can be quite generic. So, name the new project SilverlightHelperControls, and then click OK. If you have multiple versions of the Silverlight SDK installed, you are asked to specify the version you want to use. Select Silverlight 4 SDK and proceed. Now in Solution Explorer, you will see the new project available, as shown in Figure 16.2.

Image

Figure 16.2. The new project is visible in Solution Explorer.

As a default behavior, Visual Studio adds a class in the library, named Class1.vb (or class1.cs in C#). This class is not actually required in this scenario, so you can remove it by right-clicking its name in Solution Explorer and then clicking Delete. The next step is to add a user control to the new project. In Solution Explorer, right-click the project name and select Add, New Item. When the Add New Item dialog appears, select the Silverlight User Control template. This is a common task that you perform each time you want to implement a custom control. Name the new control ProductsInStockPieControl.xaml and click Add. Figure 16.3 shows this dialog.

Image

Figure 16.3. Adding a new user control to the project.

When the new user control is added to the project, Visual Studio shows the Silverlight designer, which includes the usual code editor for the XAML language and the actual designer, as shown in Figure 16.4.

Image

Figure 16.4. The designer for Silverlight.

Visual Studio automatically imports the required XML namespaces and by default provides a Grid container for children controls, which you could eventually replace with other panels. At this point, you are ready to create your custom control by aggregating existing controls.

Implementing and Aggregating Chart Controls

The Silverlight Toolkit offers, among other things, a number of chart controls that you can use for data visualization. Such controls can be embedded easily into LightSwitch screens and data-bound to entity collections to build high-quality, professional screens. In this section, you do the following:

• Implement a TabControl to provide multiple charts organized within tabs

• Bind controls to a collection of entities

• Implement a PieSeries and a TreeMap controls to show data in a more elegant fashion

In the XAML code editor, add the following XML namespaces:

xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
xmlns:toolkit="http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit"

These are required to take advantage of controls mentioned earlier. The code in Listing 16.1 shows how the user control XAML code must be implemented.

Listing 16.1. Building a Composite Control for Data Visualization


<Grid x:Name="LayoutRoot" Background="White" Width="320" Height="240">
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <!-- Declaring the TabControl-->
    <sdk:TabControl>
        <!-- Declaring the Tab items collection-->
        <sdk:TabControl.Items>
            <!-- Declaring the first tab-->
            <sdk:TabItem Header="Products Chart">
                <!-- Declaring a Chart container -->
                <toolkit:Chart x:Name="unitsInStockChart"
                         Background="LightSkyBlue"
                         BorderBrush="#000099"
                         BorderThickness="2"
                   Title="Situation of products in stock" Grid.Column="0" >
                    <toolkit:Chart.Series>
                        <!-- The PieSeries draws
                             a pie-chart based on the data binding -->
                        <toolkit:PieSeries Name="PieSeries1"
                         ItemsSource="{Binding Screen.Products}"
                         IsSelectionEnabled="False"
                         IndependentValueBinding="{Binding ProductName}"
                         DependentValueBinding="{Binding UnitsInStock}"
                         Title="Units in Stock" />
                    </toolkit:Chart.Series>
                </toolkit:Chart>
            </sdk:TabItem>

            <!-- Declaring the second tab item-->
            <sdk:TabItem Header="Product TreeMap">
                <!-- Declaring a TreeMap populated in data binding-->
                <toolkit:TreeMap
                         ItemsSource="{Binding Screen.Products}">
                    <toolkit:TreeMap.ItemDefinition>
                        <toolkit:TreeMapItemDefinition ValuePath="UnitsInStock">
                            <DataTemplate>
                                <Border
                                 Background="LightSkyBlue"
                                 BorderBrush="#000099" BorderThickness="2"
                                 CornerRadius="4">
                                    <TextBlock
                                     Text="{Binding ProductName}"
                                     VerticalAlignment="Center"
                                     TextAlignment="Center"
                                     TextWrapping="Wrap"/>
                                </Border>
                            </DataTemplate>
                        </toolkit:TreeMapItemDefinition>
                    </toolkit:TreeMap.ItemDefinition>
                </toolkit:TreeMap>
            </sdk:TabItem>
        </sdk:TabControl.Items>
    </sdk:TabControl>
</Grid>


The following are the most important points of interest in Listing 16.1:

• The Chart element acts like a container of chart series, enclosed in a Chart.Series collection.

• The PieSeries control draws a pie chart based on some properties: ItemsSource, which contains a collection of items that the chart will be drawn from; IndependentValueBinding, which represents the value shown on the Y axis; and DependentValueBinding, which represents the number of elements that compose the pie and that is based on the supplied property.

• The TreeMap control draws a rectangle containing subelements based on some properties: ItemsSource, which contains a collection of items that the chart will be drawn from; Treemap.ItemDefinition, which defines the data template that determines the appearance of the control (here ValuePath points to the property that determines which entity property the chart is drawn on); and the TextBlock element, which is data-bound to the product name.

Both the PieSeries and TreeMap controls are populated via the ItemsSource property, which receives the Products collection from the screen; this is accomplished by assigning the Screen.Products collection object to the ItemsSource property. You will immediately notice changes in the designer, although the data-visualization controls look empty at this point. Figure 16.5 shows the designer as it looks right now.

Image

Figure 16.5. The designer after the implementation of the controls.


Changing Colors

You can replace the colors used in the Background and BorderBrush properties for charts with other colors if you want.


After you build the project, you are ready to bind it to the user interface.

Binding the User Control to Data and the Screen

As you learned in previous chapters, screens in LightSwitch expose data via controls that the user utilizes to display or enter items. Because custom controls will become part of the user interface inside a screen, they must be data-bound to some data that the screen exposes. The best way to understand how this works is to add the newly created user control to the user interface (with the Search Products screen being the most appropriate place for it). So, in Solution Explorer, double-click the Search Products screen to open the Screen Designer. When ready, select the root element named Rows Layout, Search Products. Then, click Add Layout Item, Custom Control in the toolbar. Figure 16.6 shows both selections.

Image

Figure 16.6. Selecting a new layout item of type Custom Control.

As you can see, when you click such a button, you are offered three self-explanatory choices: Button, Group, and Custom Control. Click Custom Control to activate the Add Custom Control dialog, shown in Figure 16.7.

Image

Figure 16.7. The Add Custom Control dialog in its initial state.

The dialog lists a number of assemblies that expose user controls and that LightSwitch references by default. In addition, pay attention to the text box at the bottom of the dialog. This is where you effectively data-bind the new user control to the user interface by specifying the data to be bound, coming from the screen. You will see it in action in a few moments. You need to add a reference to the SilverlightHelperControls project created before and then grab the ProductsInStockPieControl control. So, click Add Reference, and the same named dialog will appear. Notice that it behaves exactly as you would expect from other kinds of projects in Visual Studio 2010. Select the Projects tab, and then the SilverlightHelperControls project, as shown in Figure 16.8.

Image

Figure 16.8. Adding a reference to the Silverlight project.

When the reference is added, you will find the new assembly available in the list of libraries. Expand it until the ProductsInStockPieControl control becomes visible; select the control, and then place the cursor in the data-binding text box. Figure 16.9 shows this. (Notice that the list of available assemblies may vary depending on previously referenced controls.)

Image

Figure 16.9. Specifying the data object for the custom control.

The logic in binding data is as follows: The Screen exposes a Products collection, which represents the data source for the control; the data binding to Products is made in the XAML code, so you leave unchanged the default selection on Screen. Notice that LightSwitch helps you understand which kinds of data objects are available when typing the dot (refer to Figure 16.9 for details). Even if we are not using this feature in this particular example, it will prove useful in lots of other situations.

After the custom control has been added to the user interface, you can move it to a different position by simply dragging it to the desired place. After you do so, open the Properties window pointing to the custom control. First, locate the Appearance group at the bottom of the window and select the Stretch option. This will ensure that the user control’s size adapts to the application’s window. Second, notice how the data binding is visible by locating the General tab at the top of the window.


Two-Way Data Binding

The current example demonstrates how to present data in a particular fashion, which means displaying information read-only. Sometimes your custom control will need to send information back to the user interface. If this is your situation, remember to add a Mode=TwoWay property setting to the Binding XAML markup extension.


At this point, click OK and you are ready to go. Before running the application, it is a good idea to replace the content of the Display Name field in the Properties window; it is set to ScreenContent by default. For instance, replace it with Products in stock, and then press F5 to run the application. After you open the Search Products screen, at the bottom of the product list, you will find the chart controls organized in tabs. Figure 16.10 shows an example of the pie chart, and Figure 16.11 shows the same example but shown within a TreeMap control.

Image

Figure 16.10. Representing the units in stock of products via a pie chart.

Image

Figure 16.11. Representing the units in stock via a TreeMap control.

Now that you know how custom controls can dramatically enhance the user experience in LightSwitch applications, you can provide additional customizations with different kinds of representations depending on the data you need to display.

Integrating Bing Maps

Bing Maps is a service from Microsoft that offers street map search, maps of the world, directions, and local information (such as stores, restaurants, or fuel) for free. Bing Maps includes satellite view, road view, and aerial view. Microsoft also released a Silverlight control that can be embedded in custom applications so that developers can offer a map service for easily displaying addresses. This control is named Bing Map Control, and because LightSwitch applications rely on Silverlight 4, it is easy to embed Bing Maps into your business applications. For example, it is perfect for showing the location of a customer in an interactive, detailed, and real fashion. In fact, this is actually the example that will be constructed in this section. Before going on, download the following:

• Bing Map Control for Silverlight 4. This is available from http://tinyurl.com/32opzsf.

• Visual Studio LightSwitch Training Kit, which has a full-blown extension walkthrough built upon Bing Maps and that generates an extension package useful for this section’s purposes. The Training Kit is available from http://bit.ly/mr11UA.

Just downloading this software is not enough, though, as explained in the next section.

Claiming Your Bing Maps Developer Keys

To use the Bing Map Control, you need to register (for free) as a developer in the Bing Maps Portal (www.BingMapsPortal.com) by using your Windows Live ID. Once registered, you need to claim a development key. You can claim up to five keys per account. Complete the following steps:

1. Go to www.bingmapsportal.com and sign in with your Windows Live ID.

2. Follow the instructions provided to register as a developer.

3. Once registered, click Create or View Keys on the left side of the page; you will be required to enter a new application name (or update an existing key).

4. Using Figure 16.12 as a reference, enter all the required information, such as the application name, URL, and type. With regard to the URL, because you are working offline, you can just add the local web server address (for example, http://localhost). For the application type, pick one from several available choices. For the purposes of this chapter, select Developer.

Image

Figure 16.12. Claiming a developer key in the Bing Maps Portal.

When you click Submit, the Developer Portal will give you a new developer key that for now you need to store in a secure place. You will use it later when the Bing Map Control is added to the LightSwitch application example.

Making Bing Maps Available to LightSwitch

The LightSwitch Training Kit contains a project to build a custom control extension for Bing Maps. With custom control extensions, other than the ability of offering new controls, which would only require Silverlight 4 code, you can also provide design-time support inside the IDE. To use it in your LightSwitch applications, follow these steps:

1. Open a new instance of Visual Studio, and then open the BingMapControl.sln solution, which is located in the LightSwitchTKLabsLightSwitchControlExtensions SourceEx1-CreatingACustomControlExtensionEnd folder of the Training Kit. (You can study this solution to understand how to build custom extensions.)

2. In Solution Explorer, ensure that the BingMapControl.Client project is correctly holding references to the Microsoft.Maps.MapControl.dll and Microsoft.Maps.MapControl.Common.dll assemblies. If not, add a reference to both assemblies, locating them in the installation folder of the Bing Maps Control.

3. Build the project, and then in the BingMapControl.VsixinDebug subfolder, you can find the BingMapControl.Vsix.vsix package.

4. Double-click this file to install the Bing Maps extension to Visual Studio 2010.

The Visual Studio Extension Installer asks for your permission before installing the extension, as shown in Figure 16.13.

Image

Figure 16.13. Installing the Bing Map Control as a Visual Studio extension.

Click Install, and after a few seconds the process is completed. Now you are ready to use Bing Maps in your LightSwitch applications. Before doing this, you need to make some small edits to your entities, as explained in the next section.

Updating Entities to Support Bing Maps

The goal of the current example is to display a customer’s location in the Bing Maps Control each time the user displays information about a particular customer. In the Invoice Management application example, a good place to accomplish this is the CustomerListDetails screen, so that the Bing Maps Control will be visible under the customer’s details.

The Bing Maps Control searches for a location by receiving a string that contains basic information about the location itself, such as the combination of a city name and address. Such a string is received by the control by binding it to an entity’s property. If you consider the Customer entity definition, you can see that no specific property stores the complete address of a customer, but there are some separate properties, such as Country, City, Address, and PostalCode.

At this point, you need to add two things: a new property of type String that holds the complete information about the customer’s location, and a bunch of code that builds such a string at runtime. In Solution Explorer, double-click the Customers data source. When the Entity Designer is available, add a new computed property called MapAddress of type String, not required. Next, in the Properties window, uncheck the Display by Default check box. Because the new property requires specific information, mark the Country, City, and Address properties as required. Figure 16.14 shows what the designer looks like and where you can find the previously mentioned visibility check box.

Image

Figure 16.14. Editing the Customer entity.

At this point, you must write some code that concatenates properties about the customer’s location into the MapAddress property. This is a computed property, so in the Properties window, click Edit Method. The code that updates the MapAddress property is the following:

Private Sub MapAddress_Compute(ByRef result As String)
    ' Set result to the desired field value
    result = Me.Address + " " + _
             Me.City + " " + _
             Me.PostalCode + " " + _
             Me.Country

End Sub

The current customer’s instance is received by both methods as an argument. Here you simply assign the value of MapAddress with a string concatenation that contains all the available location information. Now that you have made all the required edits to the entity, you can bind the Bing Map Control in the user interface.

Adding Bing Maps to Screens

To use the Bing Maps Control in a LightSwitch application, you must enable the Visual Studio extension for Bing Maps. To accomplish this, in Solution Explorer, double-click Properties. When the project’s properties designer is ready, select the Extensions tab. At this point, you will see a new extension named LightSwitch Bing Map Control available. You just need to check the Use in New Projects check box, as shown in Figure 16.15.

Image

Figure 16.15. Activating the LightSwitch extension for Bing Maps.

Now, in Solution Explorer, double-click the CustomerListDetails screen. When the Screen Designer is ready, drag the MapAddress property from the CustomerCollection element on the left side of the IDE onto the screen definition; the property must be added to the element named Vertical Stack, CustomerDetails, so that it is data-bound to the selected customer. At this point, the MapAddress property is bound to a TextBox control, which is the default choice. To display Bing Maps, you just need to replace the TextBox control with the Bing Map Control, as shown in Figure 16.16.

Image

Figure 16.16. Adding the Bing Map Control to the user interface.

The last step before running the application is to enter the developer key for Bing Maps in the Properties window. Figure 16.17 shows the Bing Maps Key property in the Properties window and demonstrates the design-time support that is available because the extension is installed.

Image

Figure 16.17. Entering the Bing Maps key.

Now press F5 and run the application. Open the Customer List Details screen and select a customer where all the location properties have been specified. Because of the background code, the MapAddress is populated correctly and data-bound to the Bing Maps Control, which can now display the customer’s location in Bing Maps, as shown in Figure 16.18.

Image

Figure 16.18. Integrating Bing Maps into screens.

The control’s toolbar enables users to zoom back and forward and to switch between the aerial and road view. Each time you select a different customer, the Bing Maps Control is immediately updated with the new location. Integrating LightSwitch with Bing Maps dramatically enhances the user experience and adds very interesting functionalities to your business applications.

Summary

As you learned in this chapter, Visual Studio LightSwitch is a general-purpose development environment and, because of this, it cannot cover every possible development scenario. However, LightSwitch enables developers to extend applications with custom controls that you build upon Silverlight 4 in Visual Studio 2010. You can build both simple and composite controls that are data-bound to entity properties (typically in the XAML code); then you can add custom controls as standalone elements in screens or as replacements for existing controls.

Custom controls are not the only way to extend screens. In fact, you can provide additional command buttons that you can associate with specific tasks by handling the CanExecute and Executed events, which is the typical demonstration of how LightSwitch applications follow the Model-View-ViewModel pattern.

In this chapter, you learned how to integrate the Bing Maps Control into LightSwitch screens to provide a visual and interactive representation of addresses, instead of displaying them as unresponsive strings. Your applications must also cover another important business scenario: printing and reporting. This is covered in the next chapter, where you will also learn why the current discussion is so important.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.93.12