Showing posts with label MEF. Show all posts
Showing posts with label MEF. Show all posts

Friday, August 28, 2015

Okra App Framework for Windows 10 Universal

[Cross posted from the official Okra App Framework blog]

Okra App Framework v1.2

With the release of Windows 10, Microsoft have introduced the Universal Windows Platform with a single API set and one app package to target PCs, tablets, phones and more. Today’s release of version 1.2 of the Okra App Framework allows you to write apps that target Windows 10 devices.

New in version 1.2 is,

  • Windows 10 UAP support - Use the MVVM pattern to write a single app that runs on PCs, tablets and phones running Windows 10.
  • Windows 10 UAP Visual Studio Template - A basic Visual Studio template is available to get you started with developing Windows 10 apps.
  • Advanced Windows 10 features include,
    • Compiled binding support (see below)
    • Automatic support for hardware back buttons and tablet mode

You can get the Okra App Framework now by installing the Visual Studio extension, from NuGet or via GitHub. Full details on how to download the framework are available here.

Windows 10 Compiled Binding Support

Since the MVVM pattern relies heavily on data binding to bind the UI to the underlying view-model, data binding performance is very important. The Universal Windows Platform introduces “compiled binding” as a high performance data binding system.

To use compiled bindings you use the new x:Bind syntax,

<TextBlock Text="{x:Bind ViewModel.Title}"/>

Note however that these bindings do not bind to the DataContext, but instead to the page itself. To support this, the Okra App Framework v1.2 introduces the IViewModelBindable interface. This is applied to the page code-behind as shown below,

public sealed partial class MyPage : Page, IViewModelBindable
{
    ...

    public HomeViewModel ViewModel
    {
        get;
        private set;
    }

    public void SetViewModel(object viewModel)
    {
        this.ViewModel = viewModel as HomeViewModel;
        Bindings.Update();
    }
}

You can now take advantage of type-safe, high performance data binding using the x:Bind syntax in your Windows 10 projects.

Monday, June 29, 2015

Okra App Framework for Windows Phone 8.1 Released

Okra App Framework v1.1

I’m pleased to announce that version 1.1 of the Okra App Framework has been released. For Windows 8.1 development there is not much new to report - the same great MVVM framework designed with Windows apps in mind. The big news however is the official release of Windows Phone 8.1 support - it has been a couple of months since the beta release and I’ve no bug reports so here it is.

In summary the new NuGet packages include,

  • Windows 8.1 support - Create a new project using the Visual Studio templates and start using the MVVM pattern straight away.
  • Windows Phone 8.1 support - Simply add a new Windows Phone 8.1 project and reference the NuGet package. The programming model is the same as for Windows 8.1, and most of your code should be sharable between projects.
  • Portable Class Library support - In addition, a PCL version is included. This allows sharing of logic and view-models in a single portable binary between Windows and Windows Phone projects.

You can get the Okra App Framework now by installing the Visual Studio extension, from NuGet or via GitHub. Full details on how to download the framework are available here.

Windows 10, Android and iOS

In other news, Windows 10 support has now been merged into the master branch of the framework. Unfortunately NuGet currently does not have platform support for Windows 10, so this is not available via the NuGet packages. If you wish to experiment with the latest bits you can download and build the source code from the Okra.Core project on GitHub.

Additionally, many thanks go to Joel Fjordén who has made a start on Android and iOS support via Xamarin.Forms. This is only the start, but if you want to experiment with cross-platform development then there are specific NuGet packages on the Okra pre-release feed at https://www.myget.org/F/okra/ (add this in the NuGet settings and make sure you have prerelease packages enabled).

Sunday, April 26, 2015

Okra App Framework for Windows Phone 8.1 (beta)

[Cross posted from the Okra Framework blog]

Okra App Framework for Windows Phone 8.1

Following on from the recent v1.0 release of the Okra App Framework, preview support for Windows Phone 8.1 is now available. This will be wrapped up in an upcoming v1.1 release, but as of today a beta release is downloadable via NuGet (turn on support for preview versions and look for the v1.1.0-beta001 package).

This package includes,
  • Windows Phone 8.1 support - Simply add a new Windows Phone 8.1 project and reference the NuGet package. The programming model is the same as for Windows 8.1, and most of your code should be sharable between projects.
  • Portable Class Library support - In addition a PCL version is included, which allows sharing of logic and view-models in a single portable binary between Windows and Windows Phone projects.
Get in touch with any bugs or comments via the Okra.Core issue tracker.

Okra App Framework for Windows 10

In addition to the beta relase, progress is going well on a Windows 10 port of the Okra App Framework. Whilst this is not currently available via NuGet, you can check out and build the code via the Okra.Core/win-10 branch.

Friday, April 10, 2015

Okra App Framework v1.0 Released

[Cross posted from the new Okra Framework blog]


I am really happy to announce that version 1.0 of the Okra App Framework has officially been released. For those new to the framework, it is an MVVM framework designed from the ground up to be great for creating Windows apps. Dependency injection is baked in to allow you to create easy to maintain, test and reuse code. A number of advanced features allow simple integration with application settings, app-to-app sharing and search. In addition a full set of Visual Studio templates is available to get you started with MVVM development.
For more information checkout the Okra Framework website.
You can get the Okra App Framework now by installing the Visual Studio extension, from NuGet or GitHub. Full details on how to download the framework are available here.
In addition to the release of the framework we have,

Changes from v0.9.8

Okra App Framework vNext

The next step for the Okra App Framework v1.1 is to support other platforms, in particular Windows Phone 8.1 and preview support for Windows 10. Much of the development on these features is already complete so expect to see a beta release in the near future. You can check out progress and submit bugs and feature requests on the Okra.Core issue tracker. For more information on feature progress on the v1.1 release you can look at the v1.1.0 milestone progress page.

Monday, July 07, 2014

Windows Store MVVM Development with the Okra App Framework v0.9.7

After a bit of hiatus, the latest version of the Okra App Framework has been released. The v0.9.7 release of the Windows Store centric MVVM framework targets Windows 8.1, and focuses on tidying up some of the API surface prior to an upcoming v1.0 release.

How to Get The Okra App Framework

You can download the latest version of the Okra App Framework,

  • From NuGet: For the complete MVVM framework add the “Okra App Framework” NuGet package to your project.
  • Using the Visual Studio Extension: The official Okra App Framework Visual Studio extension has been updated for the latest release with all new project and item templates targeting Windows 8.1. Look for the “Windows Store MVVM Templates for the Okra App Framework” extension in the Visual Studio gallery or directly from the Extensions and Updates manager in Visual Studio.

New Features in This Release

  • The big change with this update is that the Okra App Framework is now targeting Windows 8.1 development. The framework makes the most of the recent improvements in the underlying operating system, with a number of changes reflecting the new API surface. Note however that this release no longer supports Windows 8.0 projects, which should continue to use v0.9.6.
  • All new Windows 8.1 project and item templates for Visual Studio. These are based upon the Visual Studio 2013 templates, but rewritten to take advantage of the MVVM pattern.
  • The Okra Data Framework is now available as a separate download (see the “Okra App Framework (Data Framework)” package in NuGet) so you can choose to use this independently of the core framework if desired.

Code Changes When Updating From v0.9.6

In readiness for a v1.0 release, a number of breaking changes have been made,

  • To simplify page activation the IActivatable interface in no longer generic. Instead of directly passing the page arguments and state, a PageInfo object is used instead.
  • // Old code using the Okra App Framework v0.9.6
     
    public class MyViewModel : ViewModelBase, IActivatable<string, string>
    {
        ...
     
        public void Activate(string arguments, string state)
        {
            this.Photo = GetPhoto(arguments);
            this.State = state;
        }
     
        public string SaveState()
        {
            return this.State;
        }
    }
     
    // New code using the Okra App Framework v.0.9.7
     
    public class MyViewModel : ViewModelBase, IActivatable
    {
        ...
     
        public void Activate(PageInfo pageInfo)
        {
            string arguments = pageInfo.GetArguments<string>();
            this.Photo = GetPhoto(arguments);
            this.State = pageInfo.GetState<string>("MyState");
        }
     
        public void SaveState(PageInfo pageInfo)
        {
            pageInfo.SetState<string>("MyState", this.State);
        }
    }
  • To allow more flexible navigation patterns a number of properties and methods have been moved from INavigationBase to INavigationStack (accessible from any INavigationBase via the NavigationStack property).
  • Since the Windows 8.1 update includes a system provided SettingsFlyout control, you no longer need to wrap any settings pages in a SettingsChrome control.

Wednesday, September 05, 2012

Convention Based Page Discovery With The Okra App Framework

One of the key features of the Okra App Framework for developing Windows 8 apps is the navigation framework with its support for the MVVM pattern. By default pages and view-models are marked with attributes so that the framework can locate them. In this post I will describe how you can enable an alternative convention based approach.

The Default Attribute Based Approach

When using the Okra App Framework navigation support all pages are represented by a page name. So that the framework can locate the associated pages and view-models these are normally attributed with either the PageExportAttribute or ViewModelExportAttribute respectively (for more information see my previous post). For example for a page named “Foo” the classes would be attributed as,

[PageExport("Foo")]
public sealed partial class FooPage : LayoutAwarePage
{
    ...
}
 
[ViewModelExport("Foo")]
public class FooViewModel
{
    ...
}

A Convention Based Approach

Often however there will be a common naming pattern throughout the application. In the example above all pages are named XxxPage and view-models named XxxViewModel, where “Xxx” is the associated page name. In a convention based approach you no longer need to apply attributes to classes. Instead they are automatically discovered based on a common naming system.

Since the standard Okra bootstrapper uses MEF for composition (for example when using the Okra.MEF NuGet package), we can use the MEF convention based discovery. To enable this we need to add the following code to the application bootstrapper,

public class AppBootstrapper : OkraBootstrapper
{
    ...
 
    // *** Overriden base methods ***
 
    protected override ContainerConfiguration GetContainerConfiguration()
    {
        ConventionBuilder conventionBuilder = new ConventionBuilder();
 
        conventionBuilder.ForTypesMatching(type => type.FullName.EndsWith("Page"))
                         .Export(builder => builder.AsContractType<object>()
                                                   .AsContractName("OkraPage")
                                                   .AddMetadata("PageName", type => type.Name.Substring(0, type.Name.Length - 4)));
 
        conventionBuilder.ForTypesMatching(type => type.FullName.EndsWith("ViewModel"))
                         .Export(builder => builder.AsContractType<object>()
                                                   .AsContractName("OkraViewModel")
                                                   .AddMetadata("PageName", type => type.Name.Substring(0, type.Name.Length - 9)));
 
        return GetOkraContainerConfiguration()
                .WithAssembly(typeof(AppBootstrapper).GetTypeInfo().Assembly, conventionBuilder);
    }
}

With this code in place we can greatly simplify our page and view-model definitions to the following. Note that since we follow the convention we no longer need to add any attributes.

public sealed partial class FooPage : LayoutAwarePage
{
    ...
}
 
public class FooViewModel
{
    ...
}

Summary

As I have shown, when using the Okra App Framework navigation support you can simplify app development by using a convention based approach to defining pages and view-models for the MVVM pattern.

A sample application demonstrating this is available from the Okra CodePlex downloads.

Wednesday, June 06, 2012

Cocoon Updated for Windows 8 Release Preview

You will be pleased to hear that I have just pushed an updated version of the Cocoon framework onto CodePlex that supports the Windows 8 Release Preview.

As usual the code is freely available for download from the Cocoon CodePlex site (to get the latest version go to the “Source Code” tab, select the first change set and use the “Download” link).

Using MEF in the Release Preview

As many of you will be aware, the Cocoon framework uses the Managed Extensibility Framework (MEF) by default for locating and composing applications. With the release of the Windows 8 Release Preview, MEF is not being distributed separately – for more details see the announcement on the BCL team blog.

You will therefore need to add MEF as a reference to your application via NuGet. The above link has more details however the steps are,

  1. Right click on your projects ‘References’ folder and select “Manage NuGet Packages…”
  2. Select “Online” in the left-hand pane and make sure that you have “Include Prerelease” selected rather then “Stable Only” at the top.
  3. Use the search box to search for “MEF”
  4. Select “MEF for web and Metro style apps” and click “Install”

Changes in tHis Release of Cocoon

In general most applications should not be affected by the changes in this version of Cocoon (apart for the fact that they will run on the Release Preview!). Changes of interest include,

  • All use of MEF has been modified to support the new version
  • The ‘CocoonBootstrapper’ no longer has an overridable GetPartCatalog() method and is replaced with GetContainerConfiguration().
  • The ISupportPlaceholder interface has been removed in the Release Preview. The VirtualizingVector<T> implementation has been updated to reflect these changes and now returns ‘null’ as a placeholder (as now expected by the standard XAML controls).
  • Many other updates and bug fixes

Tuesday, May 15, 2012

Getting Started with Cocoon Navigation – The Cocoon Bootstrapper

In my last post I introduced the navigation framework that is included as part of the freely available Cocoon framework (open source on CodePlex). This framework is designed to make page based Metro-style applications easy to construct in managed languages on Windows 8.

I previously discussed how easy it was to implement the Model-View-ViewModel (MVVM) pattern with Cocoon by simply annotating your view and view models with the ‘PageExport’ and ‘ViewModel’ export attributes respectively. Any view model can then navigate to another page by calling the INavigationManager.NavigateTo(…) method.

Since the Cocoon navigation framework is built on top of the Managed Extensibility Framework (MEF), the application is composed with the required dependencies as the user navigates through the application. MEF is a composition framework that is built into the .Net framework, that enables the construction of loosely-coupled, easily maintainable and testable applications to be composed automatically at run time. An introductory guide for those who are not familiar with MEF is available here.

What I have not covered previously however was how to navigate to the application’s first page when it is launched,

Launching Navigation Using The Cocoon Bootstrapper

To simplify the initialization of Cocoon based applications the framework includes the ‘CocoonBootstrapper’ class that can be used at startup. This manages the configuration of MEF for the most common scenarios, initialization of services and activation of the application.

To use the Cocoon bootstrapper you must first create an application specific class derived from the abstract ‘CocoonBootstrapper’ as shown below. For basic applications this class can be left empty, although the base implementation provides a number of extensibility points to enable more advanced features.

public class AppBootstrapper : CocoonBootstrapper
{
}


The next stage is to edit your application’s ‘App.xaml.cs’ file. Much of the code included with the Visual Studio templates can be removed (since this is handled by Cocoon) and the newly created bootstrapper is initialized as part of the constructor.


sealed partial class App : Application
{
    public App()
    {
        this.InitializeComponent();
 
        // Create and initialize the application bootstrapper
 
        AppBootstrapper bootstrapper = new AppBootstrapper();
        bootstrapper.Initialize();
    }
}


Defining the Application Home Page

The final step is to define the view and (optionally) the view model that is to be shown when your application is launched. Whilst the home page name can be modified the default value defined by the ‘SpecialPageNames.HomePage’ constant is generally all that is required.

Therefore the home page view is annotated as,

[PageExport(SpecialPageNames.HomePage)]
public sealed partial class HomePage : LayoutAwarePage
{
    public HomePage()
    {
        this.InitializeComponent();
    }
}

and the view model annotated as,

[ViewModelExport(SpecialPageNames.HomePage)]
public class HomeViewModel
{
    ...
}


The Cocoon navigation framework will then automatically locate, create and wire-up the home page on application launch.

Summary

Over the last two posts I have shown how easy the Cocoon navigation framework makes launching and navigating around Metro-style Windows 8 applications using the MVVM pattern. In the upcoming posts I will discuss some of the more advanced features you get when adopting Cocoon for navigation.

As usual the code is freely available for download from the Cocoon CodePlex site (to get the latest version go to the “Source Code” tab, select the first change set and use the “Download” link).

Monday, April 30, 2012

Navigation in Cocoon – MVVM for Metro-style apps

Over the next series of posts I’m going to introduce a new subsystem within the Cocoon framework for Metro-style applications written in managed languages.
Modern rich client applications often consist of a number of interconnected pages or views. For example consider the Windows 8 “Store”. This has a home page that acts as a hub the links to a number of category pages, which in turn link to the individual application detail pages. The user navigates forward through the application flow by clicking images, buttons or links. They can also navigate backwards by using a back button that is placed in the top left hand corner of each page. In addition there are ‘special pages’ such as search, or even the settings panes available from the settings charm.

There are a number of challenges for developers who wish to correctly implement such a navigation structure.

Navigation in Cocoon

Although not limited to this, the Cocoon framework is designed to work great with the Model-View-ViewModel (MVVM) pattern that has become common when designing XAML based applications. One problem when using this pattern is that you need some way of associating a view with a view-model. Often this is done by navigating directly to a page, and using a “ViewModelLocator” to identify and wire up the respective view-model.

In Cocoon a slightly different approach is used. Here, rather than navigating directly to a view, you navigate to a named page. Although the behaviour is extensible, by default Cocoon will use MEF (the built in composition framework included in .Net) to locate both the view and view-model associated with this page name, create and initialise instances of these and wire them together.

You can export any XAML view (for example the pages created by any of the Visual Studio templates) by adding the ‘PageExport’ attribute to the code-behind file,

[PageExport("BrowsePhotos")]
public sealed partial class BrowsePhotosPage : MyPhotoApp.Common.LayoutAwarePage
{
    public BrowsePhotosPage()
    {
        this.InitializeComponent();
    }
}

And similarly you can export the view-model using the ‘ViewModelExport’ attribute,


[ViewModelExport("BrowsePhotos")]
public class BrowsePhotosViewModel
{
    ...
}

The Navigation Manager

In order to navigate between pages, Cocoon includes a navigation manager that can be accessed by importing the INavigationManager interface through MEF (simplified by the fact that all views and view models in Cocoon are themselves are composed by MEF).


public interface INavigationManager
{
    bool CanGoBack { get; }
    
    ...
 
    void GoBack();
    void NavigateTo(string pageName);
    void NavigateTo(string pageName, object arguments);
}

The most interesting methods are the two overloads of ‘NavigateTo(…)’ that both take the page name to navigate to. The navigation manager will also keep track of the current navigation stack so that you can easily use the ‘CanGoBack’ property and ‘GoBack()’ method to traverse backwards through the previously visited pages.

For example we could add methods to our BrowsePhotos view model as such,


[ViewModelExport("BrowsePhotos")]
public class BrowsePhotosViewModel
{
    // *** Fields ***
 
    private readonly INavigationManager navigationManager;
 
    // *** Constructors ***
 
    [ImportingConstructor]
    public BrowsePhotosViewModel(INavigationManager navigationManager)
    {
        this.navigationManager = navigationManager;
    }
 
    // *** Command Methods ***
 
    public void ViewPhoto()
    {
        navigationManager.NavigateTo("ViewPhoto");
    }    
    
    public void NavigateBack()
    {
        navigationManager.GoBack();
    }
}

Summary


I have shown above how the Cocoon navigation framework allows you to easily construct a page based navigation structure for applications based upon the MVVM pattern. I have of course glossed over how you navigate to the first page of your application. I will discuss this further next time.

As usual the code is freely available for download from the Cocoon CodePlex site (to get the latest version go to the “Source Code” tab, select the first change set and use the “Download” link).

Sunday, April 22, 2012

Using MEF in Metro-style applications

Update 23 Aug 2012:

Since I originally wrote this post the standard .Net framework MEF implementation is no longer accessible from Windows 8 Windows Store applications. Instead MEF support is released out-of-band on NuGet as a specific "MEF for web and Windows Store apps" package. Once you have added this to your Windows 8 projects there is a slightly different programming model. For more information see the Microsoft.Compostion documentation.

In brief, you can set up composition with,

var configuration = new ContainerConfiguration()
        .WithAssembly(typeof(App).GetTypeInfo().Assembly);
var compositionHost = configuration.CreateContainer();
compositionHost.SatisfyImports(this);

Original post follows,  

In a slight change from talking about the Cocoon framework, today I’m going to discuss how you may use MEF (the Managed Extensibility Framework) in Windows 8 Metro-style applications. Hopefully the reason for this deviation will become clear in my next post.

What Is MEF?

I’m not going to explain MEF in detail as this has been discussed many times before and is described on MSDN. Succinctly, taken directly from the MEF CodePlex page,
The Managed Extensibility Framework (MEF) is a composition layer for .NET that improves the flexibility, maintainability and testability of large applications. MEF can be used for third-party plugin extensibility, or it can bring the benefits of a loosely-coupled plugin-like architecture to regular applications.
For Windows 8 Metro-style app developers it is the loosely-coupled architecture that is of most interest (since third-party extensibility will not be applicable to application packages delivered through the Windows Store). This allows the individual components of your application to be designed, written and tested separately. The instantiation, lifetimes and connections between components is then managed by MEF at runtime.

Using MEF in Windows 8 Metro-Style Applications

The good news is that MEF is included in the .Net base class libraries as part of the Metro-style application profile so is included in-the-box for all such applications. Unfortunately if you look at the documentation you will see references to ‘Assembly.GetExecutingAssembly()’ that is not available in the Metro-profile,

// Does not work in Metro-style applications
 
var catalog = new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly());

All is not lost however, as you can access the main application assembly using,

// This does work in Metro-style applications!
 
var catalog = new AssemblyCatalog(typeof(App).GetTypeInfo().Assembly);

Note that since GetTypeInfo() is an extension method on 'Type' you will have to add "using System.Reflection;" to the top of your source file. You can also reference other assemblies simply by picking a type contained in that assembly and replacing ‘App’ in the above snippet.

Therefore a more complete snippet that would find and compose all imports in the current class is,


var catalog = new AssemblyCatalog(typeof(App).GetTypeInfo().Assembly);
var compositionService = catalog.CreateCompositionService();
compositionService.SatisfyImportsOnce(this);


Summary

Hopefully this post will help anybody trying to integrate MEF with their Windows 8 Metro-style app development. Ultimately there is an ‘ApplicationCatalog’ that should allow you to generate a catalog from all assemblies within the app package however there is a known bug in the Consumer Preview bits.