You are browsing the archive for Development.

More Complete WP7 Mango Database Update Walkthrough

September 15, 2011 in Silverlight, Uncategorized, Windows Phone 7

The MSDN documentation gives a walkthrough of how to update a local database application on the Windows Phone over time. The documentation gives quite a bit of detail but seems to miss a likely scenario. So let’s investigate the process step-by-step.

Initial Version

We are creating the first version of our application and decide that we need a User database table with the following columns: Name (primary key), LastAccessedDate

So we create a User class as follows:

[Table]
public class User : INotifyPropertyChanged, INotifyPropertyChanging
{
  private string name;
  private DateTime? lastAccessed;

  [Column(IsPrimaryKey = true, CanBeNull = false, AutoSync = AutoSync.OnInsert)]
  public string Name
  {
  get { return name; }
  set
    {
      NotifyPropertyChanging("Name");
      name = value;
      NotifyPropertyChanged("Name");
    }
  }

  [Column]
  public DateTime? LastAccessed
  {
    get { return lastAccessed; }
    set
    {
      NotifyPropertyChanging("LastAccessed");
      lastAccessed = value;
      NotifyPropertyChanged("LastAccessed");
    }
  }

  // Version column aids update performance.
  [Column(IsVersion = true)]
  private Binary version;

  // INotifyPropertyChanged Members
  // INotifyPropertyChanging Members
}

Read the rest of this entry →

WP 7.5 Mango ISETool Gotcha

September 15, 2011 in Silverlight

The Isolated Storage Explorer (ISETool.exe) is a command-line tool that comes with the Windows Phone SDK.  It allows you to copy files and directories from isolated storage on the phone (or emulator) to your PC file system.  One use for this is to take snapshots of your database over different versions in order to test upgrade scenarios.

To copy from the emulator’s isolated storage to your computer’s file system use:

ISETool.exe ts xd 11111111-2222-3333-4444-555555555555 “C:\MyApp\DbVersion1″

Where:

  • ts – take snapshot
  • xd – emulator
  • guid – product GUID from WPAppManifest.xml
  • desktop dir – where to copy the isolated storage files

 

To later copy those files from my desktop directory back to isolated storage on the emulator, use:

ISETool.exe rs xd 11111111-2222-3333-4444-555555555555 “C:\MyApp\DbVersion1\IsolatedStore”

 

In this case rs means restore snapshot.

But the restoring wasn’t working for me.  I would restore the snapshot, run my code and no database would be found so my code would create a new database.  It took me a few times to notice that what I was doing wrong was reusing the take snapshot command line and changing ts to rs.

But the problem with that is that the directory that you specify with ts is different than the one needed for rs.  Notice that rs adds “\IsolatedStore” to the end.

Hopefully this will save you from pulling  a few hairs out.

Free Event: Silverlight Firestarter – 2 Dec 2010

November 12, 2010 in Silverlight

Silverlight Firestarter: The Future of Silverlight Starts Now

Learn what the future holds for Silverlight at this online event.

Register today: http://www.silverlight.net/news/events/firestarter/

Silverlight Performance Analysis tool – Coming Soon

November 12, 2010 in Silverlight, Windows Phone 7

At PDC10 as part of the keynote, Scott Guthrie showed off the soon-to-be-released Silverlight Performance Analysis tool that would allow developers to profile their Windows Phone 7 applications and identify bottlenecks in frame rate and CPU and relate that back to specific storyboards and even Visual Tree elements.

The below screenshots were taken from the keynote video and you can see the timings at the bottom if you want to watch the video:

image

In addition to debugging on the device, you can profile the app by selecting Silverlight Performance Analysis:

perf1

The device will then be prepared for profiling:

perf2

After running the application, a graphical summary will be created with execution time on the x-axis.  It shows color-coded frame rates (green is good, red is bad) and relates that to CPU-usage and specific Storyboards:

perf3

In the above example, it appears that the first Storyboard might be leading to increased CPU usage and a degraded frame rate.  You can highlight and drill down to see details for a specific time frame (from approx 4.5 to 7.5 seconds into the profiling session):

perf4

The next screen shows CPU and GPU metrics as well as a list of warnings.  The first entry warns about 35 instances of ColorAnimation:

perf5

Scrolling down, you will see an Element Summary:

perf6

Followed by a Frames section with a CPU usage graph:

perf7

And finally the ability to drill down the Visual Tree and see problems highlighted:

perf8

This tool would be very helpful in analyzing app performance on the device.  ScottGu did not give a specific release date for this or any additional tools that might be coming.

Today I saw that there is a Silverlight Firestarter event scheduled for December 2, 2010 and wonder if the tool will be ready to release then. 

image

It would make a great time to announce it.

A Caliburn.Micro recipe: filters « Marco Amendola

August 10, 2010 in Silverlight, WPF

image

Extension to Caliburn.Micro to allow implementation of filters similar to what is found in Caliburn.

A Caliburn.Micro recipe: filters « Marco Amendola

MVVM with Caliburn.Micro

July 30, 2010 in Silverlight, Windows Phone 7

Silverlight, WPF, and Windows Phone 7 developers should consider using the Model-View-ViewModel (MVVM) pattern for developing their LOB applications.  One choice for MVVM is Caliburn.Micro developed by Rob Eisenberg.

 

Here is a link to the documentation topics:

  • Recipes
    • SimpleContainer

 

I know Rob has been working on some WP7 goodness that should be out soon.  Looking forward to the release.

Infragistics XamWebOutlookBar & Caliburn

June 14, 2010 in Silverlight

Last week I set out to build a simple Caliburn sample that included the Infragistics Silverlight XamWebOutlookBar.  I made progress and got to a point where Rob Eisenberg was able to help me get the rest of the way.  The approach I was taking was trying to figure out what conventions I should add to get Caliburn to recognize the XamWebOutlookBar.  Rob’s answer was that not everything needs to be a convention.

When you run the application, you will see the XamWebOutlookBar hosted in a sidebar.  Both groups shown in the OutlookBar have corresponding ViewModels that in turn have associated Views:

image

At the end of the article is a link to the project source code.  In order to get the project to compile, you will need to download the Infragistics assemblies and add references to the following:

image

A trial of Infragistics can be downloaded from here.

Here is the final project structure:

image

Application

In typical Caliburn style, the App.xaml has been changed to a CaliburnApplication:

<cal:CaliburnApplication xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
             xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
             xmlns:cal="clr-namespace:Caliburn.PresentationFramework.ApplicationModel;assembly=Caliburn.PresentationFramework"
             x:Class="InfragisticsCaliburn.App">
    <Application.Resources>
    </Application.Resources>
</cal:CaliburnApplication>

In App.xaml.cs, we setup MEF as the container and the use MEF to find the ShellViewModel:

protected override IServiceLocator CreateContainer()
{
    return new MEFAdapter(CompositionHost.Initialize(new AssemblyCatalog(Assembly.GetExecutingAssembly())));
}

protected override object CreateRootModel()
{
    var shell = ServiceLocator.Current.GetInstance<IShell>();

    if (IsRunningOutOfBrowser && HasElevatedPermissions)
        MainWindow.Closing += (s, args) => { args.Cancel = !ServiceLocator.Current.GetInstance<IShell>().CanShutdown(); };

    return shell;
}

ViewModels

MEF is able to find ShellViewModel in the container using the IShell type because it implements IShell and Exports itself as IShell:

[Export(typeof(IShell))]
public class ShellViewModel : ScreenConductor<IScreen>, IShell
{
    private readonly MainViewModel _firstScreen;

    [ImportingConstructor]
    public ShellViewModel(MainViewModel firstScreen)
    {
        _firstScreen = firstScreen;
    }

    protected override void OnInitialize()
    {
        this.OpenScreen(_firstScreen);
    }

}

Because of the ImportingConstructor attribute, an instance of MainViewModel is created.  The class is implemented as:

[Export(typeof(MainViewModel))]
public class MainViewModel : ScreenConductor<ISidebarItem>.WithCollection.OneScreenActive
{
    [ImportingConstructor]
    public MainViewModel([ImportMany] IEnumerable<ISidebarItem> sidebars)
    {
        Screens.AddRange(sidebars);
        this.OpenScreen(Screens.First());
    }
}

For the XamWebOutlookBar implementation, the important thing to note is that MainViewModel is setup as a ScreenConductor that manages ISidebarItem instances where only one sidebar screen is active at a time.  The ImportingConstructor attribute then finds all items registered in the MEF container as ISidebarItem.

In this example, both ContentAViewAModel and ContentBViewModel are similar:

[Export(typeof(ISidebarItem))]
public class ContentAViewModel : Screen, ISidebarItem
{
    string message = "ContentA is working";

    public ContentAViewModel()
    {
        DisplayName = "Content A Header";
    }

    public string Message
    {
        get { return message; }
        set
        {
            message = value;
            NotifyOfPropertyChange(() => Message);
        }
    }

    public string Icon
    {
        get { return @"../../Images/briefcase2.png"; }
    }
}

Each of the ViewModels export themselves as ISidebarItem, inherit from Screen, and implement ISidebarItem.

Views

In MainView.xaml, the DisplayName and Icon properties are used to render the group’s header and icon:

<igOB:XamWebOutlookBar x:Name="sidebarOutlookBar" 
        MinimizedWidth="35" AllowMinimized="True" 
        NavigationPaneMinimized="sidebarOutlookBar_NavigationPaneMinimized"
        NavigationPaneExpanding="sidebarOutlookBar_NavigationPaneExpanding"
        VerticalAlignment="Stretch" HorizontalAlignment="Stretch"
        GroupsSource="{Binding Screens}">
    <igOB:XamWebOutlookBar.GroupContentTemplate>
        <DataTemplate>
            <ContentControl cal:View.Model="{Binding}" />
        </DataTemplate>
    </igOB:XamWebOutlookBar.GroupContentTemplate>
    <igOB:XamWebOutlookBar.GroupHeaderTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding DisplayName}" />
        </DataTemplate>
    </igOB:XamWebOutlookBar.GroupHeaderTemplate>
    <igOB:XamWebOutlookBar.DefaultLargeIconTemplate>
        <DataTemplate>
            <Image Source="{Binding Icon, Converter={StaticResource stringToImageSourceConverter}}"/>
        </DataTemplate>
    </igOB:XamWebOutlookBar.DefaultLargeIconTemplate>
    <igOB:XamWebOutlookBar.DefaultSmallIconTemplate>
        <DataTemplate>
            <Image Source="{Binding Icon, Converter={StaticResource stringToImageSourceConverter}}"/>
        </DataTemplate>
    </igOB:XamWebOutlookBar.DefaultSmallIconTemplate>
</igOB:XamWebOutlookBar>

Notice the GroupsSource property is bound to the Screens property that the ViewModel inherits from its base class.  The ContentControl for each group is set to the ViewModel representing the group.  The group header is bound to the DisplayName property and the small and large icons are set to the Icon property.

The Message property is bound in the View for the group content:

<UserControl x:Class="InfragisticsCaliburn.Views.ContentAView"
    xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
    xmlns:xhttp://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">
        <TextBlock x:Name ="Message"/>
    </Grid>
</UserControl>

Download the source of the project here.

Caliburn Book: Chapters 1-3

June 7, 2010 in Silverlight

Many months ago I put learning about the Caliburn framework on my “to do” list.  A few weeks ago I started the task and decided to write a book about it.  I don’t think that I am expert enough at the framework to actually publish a book.  Not yet anyway.  But I figured if I could grok it well enough to write about it that I would be well on my way to learning the framework. 

You can download the book from here.

The first chapter is a simple introduction to Caliburn.  Chapter 2 walks you through a simple, Hello Caliburn, application.  Chapter 3 is more ambitious and walks you through various aspects of the framework using the Silverlight GameLibrary sample.  It covers the same topics that Rob Eisenberg covered in his MIX10 talk.  There is also an Appendix included that lists some of the conventions found in Caliburn.

If I decide to write additional chapters, then I would include:

  • Adding to Conventions
  • Overriding Conventions
  • TDD and Caliburn
  • Caliburn extensibility points
  • IResult implementations
  • Coroutines in more depth
  • UI patterns besides MVVM

There is likely much more to Caliburn that I don’t even know what I don’t know yet.

Please reply with any feedback, corrections, further explanations, or additional chapter ideas.

If a book is ever published about Caliburn, Rob should be the one to do it.

Windows Phone 7 Presentation at Desert Code Camp 2010

May 17, 2010 in Silverlight, Windows Phone 7

Last Saturday I presented at my second Desert Code Camp.  The presentation PowerPoint and code for “Windows Phone 7 Silverlight MVVM App the Test-Driven Way” is now available.

View more presentations from Mark Tucker.

The code consists of two phone projects.  If you run the first, you will get the application UI. Running the second will bring up the test viewer.

Get the code here.

NOTE:

I told those attending the session that a video of the presentation would be available.  But due to an issue with Camtasia Studio, the video was not recorded.

Thanks again to all those who attended the presentation.  Let me know about the COOL apps you write for WP7.

Ninject vs. MEF for ASP.NET MVC Apps

April 23, 2010 in ASP.NET MVC

This week I have been looking at using a dependency injection container for an MVC 2 application.  Since I am using .NET Framework 4 with Managed Extensibility Framework (MEF) built in, it is one option to consider.  I have also heard good things about Ninject.  So lets do a quick comparison between Ninject and MEF with the simplest of implementations.

Ninject

To start off, I downloaded the .NET Framework 3.5 release of Ninject assembly and then reference that as I recompile the Ninject.Web.MVC assembly for .NET 4. Then I created a new ASP.NET MVC 2 project and reference those assemblies:

image

Next I modified the MvcApplication class in Global.asax.cs to inherit from NinjectHttpApplication and use the OnApplicationStarted and CreateKernal overrides to wire Ninject


public class MvcApplication : NinjectHttpApplication
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

    }

    protected override void OnApplicationStarted()
    {
        AreaRegistration.RegisterAllAreas();
        RegisterRoutes(RouteTable.Routes);

        RegisterAllControllersIn(Assembly.GetExecutingAssembly());
    }

    protected override IKernel CreateKernel()
    {
        var modules = new INinjectModule[]
            {
                new WebModule()
            };

        return new StandardKernel(modules);
    }

 

To associate an interface to an implementation, I create a WebModule class that inherits from NinjectModule:

Read the rest of this entry →