SQL Server 2008 R2 Update for Developers Training Kit (June 2010 Update) – RTM Refresh Released!

SQL Server 2008 R2

Today Roger announced in his blog the availability of the SQL Server 2008 R2 Update for Developers Training Kit (June 2010 Update). This is the final update for this training kit and includes two additional modules covering SQL Server 2008 R2 related improvements in Excel 2010 and SharePoint 2010. Additionally, there were many updates to the original content in previous versions of the training kit to address changes in the final RTM release of SQL Server 2008 R2 (e.g. some UI changes, modifications in the API, minor bug fixing, etc).

You can download this new release at:

New modules added to the Training Kit

Excel 2010 & Sharepoint 2010

As I said previously, the Excel 2010 and SharePoint 2010 modules were included in the RTM release related with SQL Server 2008 R2 improvements:

  • Excel 2010 Module Excel 2010: Excel is the most popular data analysis tool in the world, and Excel 2010 offers a range of powerful data analysis and visualization improvements that makes it the ideal self-service analysis client. Slicers are new visual controls that provide quick, easy and interactive filtering. Sparklines are intense, simple word-sized graphics that make it easy to visualize data in-line with numbers. PivotTables support powerful new capabilities like named sets, what-if analysis (write-back), and pre-built calculations like percent of total, running totals and ranks. Charting has also been improved with an easier user interface, faster performance and expanded limits. SQL Server 2008 R2 introduces PowerPivot for Excel, a free Excel add-in that makes it possible for information workers to create their own powerful analytic models by combining and relating data from a wide variety of data sources.
  • SharePoint 2010 Module SharePoint 2010: SharePoint 2010 is the most popular business collaboration platform in the world for organizations of all sizes, and SharePoint 2010 Insights lets everyone access the business information they need to make good decisions. SharePoint 2010 Insights uses well-known applications and interfaces, people are comfortable from the start, and they know how to get the data they need. Excel Services makes it easy for anyone to publish their Excel workbooks in SharePoint 2010, including workbooks that use data from SQL Server 2008 R2 Analysis Services. From there, an entire team can access and analyze the same data from their web browser and rest assured that everyone has the right information. PerformancePoint Services is a new integrated capability in SharePoint 2010 Enterprise Edition that makes it easy to build flexible, highly interactive scorecards and dashboards using data from SQL Server 2008 R2 Analysis Services. SQL Server 2008 R2 PowerPivot for SharePoint makes it easy to publish analytic models created with SQL Server PowerPivot for Excel to SharePoint 2010 and share them with other users with Excel Services. SQL Server 2008 R2 Reporting Services supports SharePoint 2010 integration, making it easy to publish and access reports using familiar SharePoint paradigms.

Requirements

Enjoy

Mariano

SQL Server 2008 R2 Update for Developers Training Kit – March 2010 Update 2 Released!

Last Friday, Roger announced in his blog the availability of a new release of the SQL Server 2008 R2 Update for Developers Training Kit. This update contains new modules for Application and Multi-Server Management and StreamInsight with a lot of content for developers that want to learn and adopt these new features in SQL Server 2008 R2.

You can download the training kit from the Microsoft Download Center at:

If you do not want to download the training kit, but you do want to check what is inside it, you can review its content online in the Channel 9 Learning Center Courses at:

New ‘Application and Multi-Server Management’ module

Application and Multi-Server Management moduleSQL Server 2008 R2 introduces a set of improvements known as Application and Multi-Server Management (AMM) designed to reduce the cost and complexity of managing database servers and applications, and to help customers get more out of their SQL Server investments. Administrators can register all of their SQL Server instances and automatically collect data on utilization using a new role called a Utility Control Point (UCP). This data is consolidated and visualized using the new Utility Explorer in SQL Server Management Studio, allowing administrators to quickly isolate utilization problems and make more informed consolidation decisions.

This utilization data provides consolidated insight for both database server instances and database applications that are built using new data-tier application projects in Visual Studio 2010. Developers can now build a single unit of deployment for the data-tier portion of an application known as a DACPAC. A DACPAC contains metadata that describes all of the objects in a database application, as well as policies which govern their deployment.

A single DACPAC can be handed off to an administrator to deploy instead of collections of complicated Transact-SQL scripts. SQL Server 2008 R2 automatically evaluates the policies in the DACPAC during deployment for compliance, creates the associated database objects and registers the data-tier application. Upgrades are performed automatically from one version of a data-tier application to another, eliminating the need for administrators to perform manual upgrades.

If the database server is registered with a Utility Control Point, utilization data will be automatically collected for all registered data-tier applications and made visible in the Utility Explorer, enriching the administrator’s insight.

 

New ‘StreamInsight’ module

StreamInsight-Module SQL Server 2008 R2 introduces StreamInsight, a comprehensive development platform for building event-driven applications. While typical relational database applications are query-driven, event-driven applications are characterized by high event data rates, continuous standing queries, and millisecond latency requirements that make it impractical to store the data in a relational database for processing.

Event driven application workloads are common in many different industries, including manufacturing, oil and gas, utilities, financial services, health care, retail, web analytics, and data center monitoring. Developers turn to complex event processing (CEP) technology like StreamInsight to query, monitor and identify patterns and relationships from huge volumes of seemingly unrelated events, then trigger response actions when specific conditions are met.

 

Related Resources

SQL Server 2008 R2 Update for Developers Training Kit Released!

Microsoft SQL Server 2008 R2

As Roger announced in his blog, the first release of the SQL Server 2008 R2 Update for Developers Training Kit is available for free download from the Microsoft Download center at:

The SQL Server 2008 R2 Update for Developers Training Kit is ideal for developers who want to understand how to take advantage of the key improvements introduced in Microsoft SQL Server 2008 and Microsoft SQL Server 2008 R2 in their applications, as well as for developers who are new to SQL Server.

Stay tuned because new releases of this training kit are going to be published every two weeks approximately containing new labs, demos, presentations and videos related to SQL Server 2008 R2 features.

Training Kit Content

This release contains all the original content from the SQL Server 2008 Developer Training Kit (but targeting Microsoft SQL Server 2008 R2) and also the following new one:

  • How to build your first web application with SQL Server and ASP.NET: This hands-on lab shows how to connect to SQL Server and perform Create, Read, Update and Delete (CRUD) operations on SQL Server 2008 from an ASP.NET Web application. It also shows you how to work with images stored in SQL Server in a web application. This lab is ideal for developers who are new to building web applications with SQL Server and ASP.NET.
  • Data-tier Applications in SQL Server 2008 R2 and Visual Studio 2010: This hands-on lab shows how to perform the basic steps in creating, developing, deploying, managing and upgrading a Data-tier Application (DAC) using the new features in Microsoft SQL Server 2008 R2 and Microsoft Visual Studio 2010. It also shows some of the new IDE tools and enhancements included in Microsoft Visual Studio 2010 to work with Database projects.
  • Introduction To StreamInsight and Complex Event Processing: Microsoft SQL Server StreamInsight is Microsoft’s new Complex Event Processing technology to help businesses derive better insights by correlating event streams from multiple sources with near-zero latency. This hands-on lab shows how to leverage the new StreamInsight framework released as part of Microsoft SQL Server 2008 R2 while developing a StreamInsight sample application. It also explains the basics about Complex Event Processing.
  • Using the New Features of Reporting Services 2008 R2: This hands-on lab introduces the new features included in Microsoft SQL Server 2008 R2 Reporting Services like the Map Wizard to display geospatial data, the lookup functions in report expressions so that data from multiple datasets can be shown in a single data region and the capability to export report data to an Atom data feed. It also shows the new features in Report Builder 3.0.
  • PowerPivot in SQL Server 2008 R2: This hands-on lab introduces to the Microsoft SQL Server PowerPivot for Excel 2010 add-in and shows how to load data into it and how to create PowerPivot pivot tables. It also introduces DAX expressions for multidimensional calculations against PowerPivot data and explains how to publish PowerPivot workbooks to Microsoft SQL Server PowerPivot for SharePoint 2010.
  • 7 Introductory Videos: these videos introduce and review the new features and enhancements in Microsoft SQL Server 2008 and Microsoft SQL Server 2008 R2.
    • SQL Server 2008 R2 Update for Developers Overview Part I - SQL Server 2008 Review
    • SQL Server 2008 R2 Update for Developers Overview Part II - Introducing SQL Server 2008 R2
    • Introducing SQL Server 2008 R2 StreamInsight
    • Demo: Real Time Analytics with SQL Server 2008 R2 StreamInsight
    • Introducing SQL Server 2008 R2 Application and Multi-Server Management
    • Introducing SQL Server 2008 R2 Reporting Services
    • Introducing PowerPivot for Excel 2010 and SharePoint 2010

SQL Server 2008 R2 Update for Developers Training Kit

Resources

Enjoy

Mariano

Optional Checkable Tree View Control for .NET Compact Framework 3.5

Windows MobileDuring this month I was working with my teammates Julian Dominguez and Diego Perez on a project that targeted Window Mobile 6.0 and the .NET Compact Framework 3.5. The main objective of this project was to create a module for an existing mobile application to let users perform different surveys and allowing them to navigate and filter through the questions and answers (between other things).

Among all the requirements for this project, there was one that asked for a view to show a hierarchical list of the questions / answers of the survey grouped by their types. The special thing about this view was that only some items of the hierarchical list should be checkable. Julian and I tried to use the TreeView control included in the .NET Compact Framework, but this control does not allow you to choose which items are checkable and which are not. So we decided to extend the default TreeView and create an optional checkable TreeView control. These were the results:

Tree View Controls 

As you can see, in the default TreeView control (on the left) all the nodes has check boxes even the ones that are expandable. In the OptionalCheckableTreeView control (on the right) the expandable nodes are not checkable.

Implementation Details

Instead of setting the CheckBoxes property of the TreeView to true, we are using images to display the check boxes (either in checked or unchecked state) and the minus and plus icons to expand the tree.

To accomplish this we had to add support for the NodeMouseClick event, which is not available in the .NET Compact Framework. This event allows us to check / uncheck / expand / collapse the clicked node and also change the image index. We followed the guidance provided in the following articles in MSDN, with a few modifications:

Download

Download the C# source code from here. The ZIP file contains the following:

  • OptionalCheckableTreeView.sln: Contains the source code for the OptionalCheckableTreeView control.
  • OptionalCheckableTreeView.Sample.sln: Contains a sample application that uses the OptionalCheckableTreeView control.
Note: This code is provided “AS IS” with no warranties, and confers no rights.

Feedback is always appreciated!

Mariano

kick it on DotNetKicks.com

How To: Integrate a Prism v2 application with the Silverlight 3 Navigation Framework

The Silverlight 3 Beta release introduces a lot of new features and enhancements into the framework. One of them is Navigation, which allows us to easily implement navigation between UserControls / Pages, interact with the Browser History journal and define Uri mapping to map complex Uris with more friendly ones. To learn more about the Navigation Framework you can check the Navigation Framework video by Tim Heuer.

The purpose of this post is to provide an overview of the things that should be taken into account to use the Silverlight 3 Navigation Framework in a Prism v2 application, as well as the limitations / issues that you could come up with during the integration. I used the Remote Modularity QuickStart (shipped with the Composite Application Guidance for WPF and Silverlight - February 2009) as the base application and modified it to provide navigation among modules. As you can see in the image bellow, the original QS (in the left) shows all the modules at once and the updated one (in the right) provides navigation links to see each module page separately.

Remote Modularity QS using Navigation Framework

System Requirements

To be able to open the source code that accompanies this post and follow its guidance, you will need the following:

Note: Once you install the Silverlight 3 Beta Tools for Visual Studio, your development environment will be a Silverlight 3 Beta environment.  Visual Studio 2008 SP1 does not support multi-targeting for Silverlight applications so you will be unable to develop Silverlight 2 applications once these tools are installed.

Steps

The following are the general steps that I performed to add navigation functionality to the Remote Modularity QuickStart, but they could also be reused in other Prism v2 applications:

  1. Add a reference to the System.Windows.Controls.Navigation assembly in the Shell project. This assembly contains the Frame and Page controls needed to navigate and the classes that allow the mapping of the Uris.
  2. Add a Frame control to the Shell of the Silverlight application. The Frame control is the container for pages. It allows you to navigate to a Uri and exposes a bunch of useful events related to navigation.
    <UserControl x:Class=”RemoteModuleLoading.Shell”
       
        xmlns:navigation=”clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation”>
        …
        <StackPanel>
            <ItemsControl cal:RegionManager.RegionName=”LinkRegion”>
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <StackPanel Orientation=”Horizontal”/>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
                <ItemsControl.Items>
                    <HyperlinkButton Content=”Home” Tag=”Home”
                         cmd:Click.Command=”{Binding NavigateCommand}”
                         cmd:Click.CommandParameter=”{Binding RelativeSource={RelativeSource Self}, Path=Tag}” />
                </ItemsControl.Items>
            </ItemsControl>
            <navigation:Frame x:Name=”MainFrame” Source=”Home” />
        </StackPanel>
        …
    </UserControl>

  3. Add a UriMapper to the Application Resources in the App.xaml file.
    <Application
                 
                 xmlns:navcore=”clr-namespace:System.Windows.Navigation;assembly=System.Windows.Controls.Navigation”>
        <Application.Resources>
            <navcore:UriMapper x:Key=”uriMapper”>
                <navcore:UriMapping Uri=”Home” MappedUri=”/Views/Home.xaml” />
            </navcore:UriMapper>
        </Application.Resources>
    </Application>
  4. Add UriMappings inside the Initialize method of the Module class of each module. The UriMapping class allows us to display a more user friendly Url in the browser. Defining this mapping inside each module avoids having them hard-coded inside the Shell project.
    public void Initialize()
    {
        AddModuleUriMappings();
    
        this.regionManager.Regions["LinkRegion"].Add(new ModuleZLink());
    }
    
    private static void AddModuleUriMappings()
    {
        UriMapper mapper = (UriMapper)Application.Current.Resources["uriMapper"];
        mapper.UriMappings.Add(new UriMapping()
                            {
                                Uri = new Uri(“ModuleZ”, UriKind.Relative),
                                MappedUri = new Uri(“/ModuleZ;component/DefaultViewZ.xaml”,
                                                    UriKind.Relative)
                            });
    }

  5. For each module, add an UserControl containing an HyperlinkButton which points to the Uri previously mapped. This UserControl is added to the LinkRegion of the Shell when the module is initialized.
    <UserControl x:Class=”ModuleZ.ModuleZLink”
        xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
        xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
        xmlns:cal=”clr-namespace:Microsoft.Practices.Composite.Presentation.Commands;assembly=Microsoft.Practices.Composite.Presentation”>
    
        <HyperlinkButton Content=”Module Z” Tag=”ModuleZ”
                         cal:Click.Command=”{Binding NavigateCommand}”
                         cal:Click.CommandParameter=”{Binding RelativeSource={RelativeSource Self}, Path=Tag}” />
    
    </UserControl>

    Note: The value of the Tag property of the HyperlinkButton control is the Uri that will be used for navigate. Also notice that I’ve bound the Click event of the control to a NavigateCommand

    For more information related to commands, see Commands article in Prism v2 documentation.

  6. Create a global CompositeCommand to handle the navigation within the frame. In this way, all the links previously added will use the frame control defined in the Shell to perform the navigation when they are clicked.
    public Shell(IUnityContainer container, CommandProxy command)
    {
        InitializeComponent();
    
        this.container = container;
        command.NavigateCommand.RegisterCommand(new DelegateCommand<string>(this.OnNavigate));
    
        this.MainFrame.Navigated += new NavigatedEventHandler(this.MainFrame_Navigated);
        this.DataContext = command;
    }
    
    private void OnNavigate(string url)
    {
        this.MainFrame.Navigate(new Uri(url, UriKind.Relative));
    }

  7. Add a handler to the Navigated event of the frame control to perform dependency injection in the pages. This requires all the pages to use property injection instead of constructor injection.
    private readonly IUnityContainer container;
    
    private void MainFrame_Navigated(object sender, NavigationEventArgs e)
    {
        if (e.Content != null)
        {
            this.container.BuildUp(e.Content.GetType(), e.Content);
        }
    }

You can download the final solution from the Download section bellow.

Limitations / Issues when modules are loaded dynamically

When the modules are statically loaded, all the above steps work without problems. All the assemblies are declared in the AppManifest.xaml file of the Silverlight application and deployed / loaded before the application starts. Therefore, all the types and resources defined in the modules are available for navigation.

However, if the modules are dynamically loaded like in the Remote Modularity QuickStart, they are not included in the AppManifest.xaml file because their assemblies are deployed on demand by the CAL. This causes some problems when trying to crate an instance of a page class during the navigation. The exception you get says that the type specified in the x:Class attribute of the XAML could not be found in any loaded assembly. I’ve tried the following things to bypass this limitation without success:

  1. Modified the XapModuleTypeLoader class of the CAL to add all the AssemblyParts of the modules to the Deployment.Current.Parts collection. This caused no effect.
  2. Tried to add the assembly name to the x:Class attribute of each page. However, I was no able to specify the assembly in the x:Class attribute using the syntax x:Class=”namespace.classname;assembly=assemblyname” like the official Silverlight documentation explains. I got a compilation error saying that the value of the x:Class attribute is not a valid fully qualified class name.

Finally I opted for a workaround and found the following two possible ones:

  1. Remove code behind classes in module’s pages: If your pages do not contain any x:Class attribute the navigation will work smoothly. You can take advantage of all the features available in Silverlight 3 (like Bindings, Commands, StaticResources, etc) to avoid having a code behind class.
  2. Use a Placeholder page in the shell module to host module pages: If your pages are complex and you cannot avoid having code behind classes, you can create a page in the Shell module to which all modules can navigate. This placeholder page will receive as a QueryString parameter the type of the view that should contain, resolve it in the application Container and add it to its Content property. This logic should be placed in the Loaded event of the page.
    // Loaded event of the placeholder page
    private void ModulePlaceHolderPage_Loaded(object sender, RoutedEventArgs e)
    {
        string type = this.NavigationContext.QueryString["viewType"];
        UIElement moduleView = null;
    
        if ((type != null) && (Type.GetType(type) != null))
        {
            Type viewType = Type.GetType(type, false);
            moduleView = this.Container.Resolve(viewType) as UIElement;
        }
    
        // Show in the content place holder the module view
        this.Content = (moduleView != null) ? moduleView :
                                              new TextBlock()
                                              {
                                                  Foreground = new SolidColorBrush(Colors.Red),
                                                  TextWrapping = TextWrapping.Wrap,
                                                  Text = String.Format(CultureInfo.CurrentUICulture,
                                                                       “View {0} was not found.”, type)
                                              };
        this.Title = this.NavigationContext.QueryString["title"];
    }

    Each module should also define its own Uri mappings to point the placeholder page adding the right QueryString parameters.

    private static Uri CreateModuleUri()
    {
        string queryString = String.Format(“viewType={0}&title={1}”,
                                           typeof(DefaultViewY).AssemblyQualifiedName,   // View type
                                           “Module Y - RemoteModuleLoading Quickstart”); // Title
    
        // I added the base Uri of the placeholder page inside the Shell project.
        string modulePlaceHolderUri = Application.Current.Resources["placeHolderUri"] as string;
    
        return new Uri(String.Format(“{0}?{1}”, modulePlaceHolderUri, queryString), UriKind.Relative);
    }

Download

Download the C# source code from here. The file contains the following:

  • CAL folder: contains the source code of the Composite Application Library shipped with the Composite Application Guidance for WPF and Silverlight - February 2009.
  • LIB folder: contains assemblies required by the Composite Application Library.
  • RemoteModularityQuickstart folder: contains the updated Remote Modularity Quickstart to use navigation functionality with the Silverlight 3 Navigation Framework using workarounds described previously.
  • StaticModularityQuickstart folder: contains the updated Remote Modularity Quickstart to use navigation functionality with the Silverlight 3 Navigation Framework and modified to statically load modules.
Note: This code is provided “AS IS” with no warranties, and confers no rights.

Feedback is always appreciated!

Mariano

kick it on DotNetKicks.com

How To: Pass parameters to Commands Handlers in Composite UI Application Block (CAB) / SCSF

This week there were some questions in the SCSF Codeplex Forum asking for a way to pass custom parameters to a method marked as a Command Handler. As you may know, there is no out-of-the-box way to do it because they are raised internally by the Command class and, since you usually bind a command to a control event via the AddInvoker method, you cannot manage when the command is executed.

Additionally, the signature of a command handler is fixed and should always be like the following:

[CommandHandler(CommandNames.MyCommand)]
public void OnMyCommandHandler(object sender, EventArgs args)
{
    // The sender parameter is an instance of the Command class.
    Command cmd = sender as Command;

    // The args parameter is empty.
    bool f = (args == EventArgs.Empty);
} 

The instance of the Command class received in the sender parameter could be useful, for example, if you want to change the status of the command to Enabled, Disabled or Unavailable.

cmd.Status = CommandStatus.Disabled;

But, what if you want to share the same command handler for different command invokers (like several menu items) and perform some operations based on which item was the invoker? You will somehow need to receive a parameter describing which was the item that raised the command.

Workaround

A possible workaround to receive parameters using a command could be by not adding your items as invokers of the command and instead execute the command programmatically. If you do this, you could use the State collection of the RootWorkItem to pass parameters to the command.

To implement this workaround follow these steps (the code use the ToolStripMenuItem control but could be used with other toolstrip controls):

  1. Add the parameter that you want to receive in the command handler to the Tag property of your menu item control:
    ToolStripMenuItem item = new ToolStripMenuItem() { Text = “My Menu Item”, Tag = “My Tag”};

  2. Add a handler for the Click event to your menu item:
    item.Click += new EventHandler(Item_Click);
  3. In the Item_Click method, add the Tag of your item to the State collection of the RootWorkItem and execute the command programmatically:
    WorkItem.RootWorkItem.State["LastTag"] = item.Tag;
    WorkItem.Commands[CommandNames.CommandWithParameters].Execute();
  4. In the command handler, retrieve the Tag from the State collection:
    string tag = WorkItem.RootWorkItem.State["LastTag"] as string;

The following code shows a ModuleController class that demonstrates how the approach above could be implemented:

public class ModuleController : WorkItemController
{
    public override void Run()
    {
        AddServices();
        ExtendMenu();
        AddViews();
    }

    private void ExtendMenu()
    {
        AddTaggedMenuItem(“Menu Item 1″, “Tag 1″, UIExtensionSiteNames.ModulesMenu);
        AddTaggedMenuItem(“Menu Item 2″, “Tag 2″, UIExtensionSiteNames.ModulesMenu);
        AddTaggedMenuItem(“Menu Item 3″, “Tag 3″, UIExtensionSiteNames.ModulesMenu);
        AddTaggedMenuItem(“Menu Item 4″, “Tag 4″, UIExtensionSiteNames.ModulesMenu);
    }

    private void AddTaggedMenuItem(string menuText, string menuTag, string extensionSiteName)
    {
        ToolStripMenuItem menuItem = new ToolStripMenuItem() { Text = menuText, ToolTipText = menuText, Tag = menuTag };

        menuItem.Click += new EventHandler(MenuItem_Click);

        WorkItem.UIExtensionSites[extensionSiteName].Add(menuItem);
    }

    private void MenuItem_Click(object sender, EventArgs e)
    {
        ToolStripMenuItem item = sender as ToolStripMenuItem;

        if (item != null)
        {
            WorkItem.RootWorkItem.State["LastTag"] = item.Tag;
            WorkItem.Commands[CommandNames.CommandWithParameters].Execute();
        }
    }

    [CommandHandler(CommandNames.CommandWithParameters)]
    public void OnCommandWithParameters(object sender, EventArgs args)
    {
        string tag = WorkItem.RootWorkItem.State["LastTag"] as string;

        if (tag != null)
        {
            MessageBox.Show(“The tag received in the command handler is: ” + tag, “Tags”);
        }
    }

    // …
}

In this way, the State collection is used as a container for your custom command parameters.

 

Enjoy.

Migrating Prism v2 Silverlight applications from static to dynamic module loading

The P&P Sustained Engineering Team has published an article in the Composite WPF & Silverlight Knowledge Base that explains how to modify the Prism v2 Silverlight Reference Implementation so it uses Dynamic Module Loading. By doing this, each module generates its own XAP file and the ModulesCatalog.xaml file in the Shell project defines how modules should be loaded:

As I mentioned, the article targets the migration of the Silverlight Reference Implementation included in the Prism V2 - Drop 10, but you could use it as a guidance to migrate any Prism v2 Silverlight application from static to dynamic (remote) module loading. The main steps are:

  1. Update Silverlight class library projects to Silverlight application projects to generate XAP files
  2. Set up remote module loading by adding a ModulesCatalog.xaml file and modify the Bootstrapper class
  3. Create a Web Application Project to host the application

The team also published the following:

  • The PDF version of the article
  • The updated source code of the Silverligh RI
Disclaimer: The code is provided “AS IS” with no warranties, and confers no rights.

How To: Use the Ngen tool to improve the performance in CAB / SCSF applications

There are some scenarios, like applications with a very big number of modules and views, that could present performance issues at startup due to the just-in-time (JIT) compilation process. In these cases it could be useful to precompile the assemblies using the Ngen tool.

The Native Image Generator (Ngen.exe) is a tool that improves the performance of managed applications by creating native images, which are files containing compiled processor-specific machine code. This allows the runtime to use native images instead of using the just-in-time (JIT) compiler to compile the original assembly code in runtime. One disadvantage of native images is that you cannot use the Assembly.LoadFrom method to load them.

If you are a user of CAB / SCSF, you may be aware of the Module Loader Service. This service allows you to load modules’ assemblies at run time when the application starts. The default implementation of this service uses the Assembly.LoadFrom method to load the assemblies enumerated by the Module Enumerator Service. So, if you try to “Ngen a CAB based application”, the native images of all your modules are not going to be used (the modules will be JIT compiled like always).

Workaround: Change the Module Loader Service class to use Assembly.Load method

This workaround enables the usage of the Assembly.Load method instead of the Assembly.LoadFrom method in the Module Loader Service class. The only limitation is that the modules’ assemblies must be physically located in the application’s working directory. To apply the workaround follow these steps:

  1. If you have an SCSF solution, open the DependentModuleLoaderService.cs file located in the Services folder of the Infrastructure.Library project. If you are using CAB without SCSF, open the ModuleLoaderService.cs file located in the Services folder of the CompositeUI project.
  2. Replace the implementation of the Load(WorkItem workItem, params Assembly[] assemblies) method for the following one:
    public void Load(WorkItem workItem, params Assembly[] assemblies)
    {
        Guard.ArgumentNotNull(workItem, “workItem”);
        Guard.ArgumentNotNull(assemblies, “assemblies”);
    
        List<IModuleInfo> modules = new List<IModuleInfo>();
    
        foreach (Assembly assembly in assemblies)
        {
            ModuleInfo mi = new ModuleInfo(assembly);
            // Use Assembly’s Full Name instead of the Assembly’s File Name.
            mi.SetAssemblyFile(assembly.FullName);
            modules.Add(mi);
        }
    
        InnerLoad(workItem, modules.ToArray());
    }

  3. Replace the implementation of the LoadAssembly(string assemblyFile) method for the following one:
    private Assembly LoadAssembly(string assemblyName)
    {
        Guard.ArgumentNotNullOrEmptyString(assemblyName, “assemblyName”);
        Assembly assembly = null;
    
        try
        {
            // Use Assembly.Load instead of Assembly.LoadFrom
            assembly = Assembly.Load(assemblyName);
        }
        catch (Exception ex)
        {
            throw new ModuleLoadException(assemblyName, ex.Message, ex);
        }
    
        if (traceSource != null)
            traceSource.TraceInformation(Properties.Resources.LogModuleAssemblyLoaded, assemblyName);
    
        return assembly;
    }

  4. Replace the implementation of the GuardLegalAssemblyFile(IModuleInfo modInfo) method for the following one:
    private void GuardLegalAssemblyFile(IModuleInfo modInfo)
    {
        Guard.ArgumentNotNull(modInfo, “modInfo”);
        Guard.ArgumentNotNull(modInfo.AssemblyFile, “modInfo.AssemblyFile”);
    }

  5. Open your ProfileCatalog.xml file.
  6. Change the value of the AssemblyFile attribute of each of your ModuleInfo tags to the assembly’s Full Name:
    <ModuleInfo AssemblyFile=Module1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null />
    <ModuleInfo AssemblyFile=Module2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null />

Running Ngen on CAB based applications

When you run Ngen.exe on an assembly, it also generates native images for the all its dependencies (dependencies are determined from references in the assembly manifest). The only scenario in which you need to install a dependency separately is when the application loads it using reflection, for example by calling the Assembly.Load method.

This is the case for CAB / SCSF applications, so you must run Ngen for the your application executable (exe file) and all its modules. To do this follow these steps:

  1. Open a Visual Studio Command Prompt.
    Note: If you are running on Vista with the User Account Control (UAC) activated, you must open it with the option Run as administrator.
  2. Navigate to the directory where all your applications binaries are located and run the following command:
    ngen install YourApplication.exe

  3. Run the same command for all of your business and foundational modules.
    ngen install ModuleN.dll

Results

After applying the workaround on the BankTeller Quickstart and running Ngen to its binaries, the JIT compilation time was eliminated. To profile the application I used the ANTS Profiler.

  • Before generation the native images, the application presented some peaks in the JIT compilation time.
    Before generating the native images
  • After generating the native images, the JIT compilation time was eliminated.
    After generating the native images
Note: In order to perform profiling to native images, you must install them using the /Profile scenario as follows:

ngen install YourApplication.exe /Profile

 

Feedback is appreciated!

Mariano

Technorati Tags: ,,
kick it on DotNetKicks.com

How To: Load modules on demand that have dependencies using Composite WPF (Prism)

The Composite Application Guidance for WPF - June 2008 release brings out-of-the-box support to load modules on demand. The only thing that you need to do is set the StartupLoaded property of the module to false. This feature is provided by the following Module Enumerators classes:

  • The DirectoryLookupModuleEnumerator class that discovers modules in assemblies stored in a particular folder. This approach requires you to configure modules using attributes in code like the following:
    [Module(ModuleName = "ModuleB", StartupLoaded = false)]
    public class ModuleB : IModule
    {
        //…    
    }

    For more information see: Using the Directory Lookup Module Enumerator.

  • The ConfigurationModuleEnumerator class that discovers modules by reading the configuration file of the application. This approach requires a configuration file. The following code shows the content of a sample App.config file:
    <?xml version=1.0encoding=utf-8?>
    <configuration>
      <configSections>
        <section name=modulestype=Microsoft.Practices.Composite.Modularity.ModulesConfigurationSection, Microsoft.Practices.Composite/>
      </configSections>
      <modules>
        <module assemblyFile=Modules/ModuleA.dllmoduleType=ModuleA.ModuleAmoduleName=ModuleA/>
        <module assemblyFile=Modules/ModuleB.dllmoduleType=ModuleB.ModuleBmoduleName=ModuleBstartupLoaded=false />
      </modules>
    </configuration>

    For more information see: Using the Configuration Module Enumerator.

Specifying Modules Dependencies

The mentioned Module Enumerators allow you to specify dependencies on the modules. In this way the Module Loader initializes first all its dependent modules before loading it.

  • With the DirectoryLookupModuleEnumerator class the dependencies are specified with the ModuleDependecy attribute.
    [Module(ModuleName = "ModuleB", StartupLoaded = false)]
    [ModuleDependency("ModuleA")]
    public class ModuleB : IModule
    {
        //…    
    }
  • With the ConfigurationModuleEnumerator class the dependencies are specified with the depedencies node in the configuration file:
    <?xml version=1.0encoding=utf-8?>
    <configuration>
      <configSections>
        <section name=modulestype=Microsoft.Practices.Composite.Modularity.ModulesConfigurationSection, Microsoft.Practices.Composite/>
      </configSections>
      <modules>
        <module assemblyFile=Modules/ModuleA.dllmoduleType=ModuleA.ModuleAmoduleName=ModuleA/>
        <module assemblyFile=Modules/ModuleB.dllmoduleType=ModuleB.ModuleBmoduleName=ModuleBstartupLoaded=false” />
          <dependencies>
            <dependency moduleName=ModuleA/>
          </dependencies>
        </modules>
      </modules>
    </configuration>

The current release of the Composite Application Library do not bring support for loading modules on demand with dependencies. If you try to do this, you will get a ModuleLoadException exception with the message: A module declared a dependency on another module which is not declared to be loaded. Missing module(s).

Module Load Exception

Cause of the ModuleLoadException

To load a module the Composite Application Library provides the a Module Loader class. This class contains the Initialize method that receives the list of the modules that you want to load as a parameter.

public LoadModuleB(IModuleLoader moduleLoader, IModuleEnumerator moduleEnumerator)
{
    ModuleInfo[] modules = new ModuleInfo[] { moduleEnumerator.GetModule(“ModuleB”) };

    moduleLoader.Initialize(modules);
}

The Module Loader assumes that the list of modules passed to its Initialize method also includes the dependencies. That is why it throws the exception: A module declared a dependency on another module which is not declared to be loaded when you want to load a single module on demand with dependencies (the module’s dependencies are not present in the list).

Workaround

A workaround to solve this issue could be creating an extension method to the Module Enumerator class that returns the module and its dependencies. The following is a possible implementation:

using System.Linq;
using System.Collections.Generic;

// The namespace is important to make the extension method work.
namespace Microsoft.Practices.Composite.Modularity
{
    public static class ModuleEnumeratorExtensions
    {
        public static ModuleInfo[] GetModuleWithDependencies(this IModuleEnumerator moduleEnumerator, string moduleName)
        {
            List<ModuleInfo> moduleInfoList = new List<ModuleInfo>();
            ModuleInfo module = moduleEnumerator.GetModule(moduleName);
            moduleInfoList.Add(module);
            if (module.DependsOn != null)
            {
                foreach (string dependencyName in module.DependsOn)
                {
                    if (!moduleInfoList.Exists(existingModule => existingModule.ModuleName == dependencyName))
                    {
                        moduleInfoList.AddRange(GetModuleWithDependencies(moduleEnumerator, dependencyName));
                    }
                }
            }
            return moduleInfoList.ToArray();
        }
    }
}

Then, when you need to initialize a module on demand you can use the previous extension method in the following way:

public DefaultViewB(IModuleLoader moduleLoader, IModuleEnumerator moduleEnumerator)
{
    moduleLoader.Initialize( moduleEnumerator.GetModuleWithDependencies(“ModuleB”) );
}

 

Enjoy

Smart Client Software Factory (SCSF) GP source code with Installer that works on Visual Studio 2008 + SP1

A couple of months ago I announced in my blog that the P&P Sustained Engineering team had published an article in the SCSF Knowledge Base that describes the Known Issues and Fixes for the SCSF - April 2008 release running with Microsoft Visual Studio 2008 Service Pack 1.

The fixes for these issues included modifying the guidance package source code and register a custom one. So I decided to post the source code with the fixes including a setup project in order to create an installer for it.

Download it from here.

Disclaimer: This is not an official Microsoft release. Use it at your own risk.

Registering the Guidance Package using the installer

To register the guidance package using the custom installer performs the following steps:

  1. Open and build the GuidancePackage.sln solution to generate the installer.
  2. Navigate to the SmartClientFactorySetup\Debug folder.
  3. Close all instances of Visual Studio.
  4. Run the SmartClientFactoryPackageSetup.msi installer.
    Note: If you are running on Vista with the User Account Control (UAC) activated, you must run the installer with the option Run as administrator.

Manually registering the Guidance Package

To manually register the guidance package perform the following steps:

  1. Open the GuidancePackage.sln solution.
    Note: If you are running on Vista with the User Account Control (UAC) activated, you must open Visual Studio with the option Run as administrator.
  2. On the Tools menu of Visual Studio, click Guidance Package Manager.
  3. In the Guidance Package Manager dialog box, click Enable / Disable Packages.
  4. In the Enable and Disable Packages dialog box, select the Guidance Package Development check box.
  5. Click OK.
    Enabling the Guidance Package Development allows you to register a guidance package.
  6. Close all other instances of Visual Studio.
  7. Right-click the SmartClientFactoryPackage project, and then click Register Guidance Package.

For more information you can check the following article:

Using the Fixed Guidance Package

Once you have installed/registered the guidance package, you will be able to use the Smart Client Development for SP1 package (see the image below).

SmartClientDevelopmentForSP1

Enjoy.

Next Page »