Monday, May 14, 2012

A MonoDroid MvvmCross experiment in autocomplete


I got asked a question about implementing Mono for Android/MonoDroid autocomplete support on Jabbr - http://jabbr.net/#/rooms/mvvmcross
After some hacking at a Google Books API sample, then I created a sample - see the video at:
This example works using a new alpha databinding Autocomplete class and adaptor within the MvvmCross framework. It may be that these classes never actually make the cut to be full time framework members - in which case they can live in some external library instead.
The basic functionality uses databinding on 3 new properties:
  • PartialText - which is a partial text string - sent from the View to the ViewModel
  • ItemsSource - which is the set of current items available for the supplied PartialText - sent from the ViewModel to the View
  • SelectedObject - which is the current selected item - sent from the View to the ViewModel
You can see these setup in the binding xml as:
<Mvx.MvxBindableAutoCompleteTextView
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  local:MvxItemTemplate="@layout/listitem_book"
  local:MvxBind="{'Text':{'Path':'EnteredText','Mode':'TwoWay'},
  'ItemsSource':{'Path':'AutoCompleteSuggestions'},
  'PartialText':{'Path':'CurrentTextHint'},
  'SelectedObject':{'Path':'CurrentBook'}}"
    />
Note that because of the Android threading model it is essential that every change in PartialText is met by an eventual signalled change in ItemsSource - and this should be a single change in object collection rather than lots of small changes.
Note that this sample uses "simple binding" rather than the full Mvx framework and as a result there is slightly more threading to worry about in the ViewModel.
The binding view and its adapter are not simple code to follow - the binding code is fairly abstract in nature - but they can be found in:
One Two Three
If you are doing anything network-linked then in the long term I believe it may be better to implement a new autocomplete view rather than to use the built into Android today!
And if you are doing an autocomplete sample, then I highly recommend the google books api - it's simple to use and fab for demos :)

Portable Class Libraries in MvvmCross vNext


The first version of MvvmCross provided an excellent way to share ViewModel, Model and Service code between WP7, WindowsRT, MonoTouch and Mono for Android.

This was achieved using solutions where every project platform had:
  • a platform specific UI project containing code unique to that platform (e.g. UI widgets and views)
  • a platform specific class library which was exactly the same code across all projects – the only difference between the different platforms was a difference in the project library/build type.
For example, see the TwitterSearch hierarchy:




This type of solution works really well as a cross platform development architecture - it encourages code reuse, its easy to work in and it delivers product :)

However, there are a few things that I feel could be done better:
  1. Maintaining the different projects requires manual cut and paste maintenance which is tedious and error prone. There is a tool that can help with this – the Project Linker Synchronization Tool - http://msdn.microsoft.com/en-us/library/ff921108(v=PandP.20).aspx – but it only helps a bit…
  2. While the tools from Microsoft and Xamarin were first class, and while plugins like VSMonoTouch and VSMono help fill some gaps, there are still issues with refactoring. Fundamentally the above code architecture forces the project hierarchies to be independent, and this means it is impossible to do automated refactoring across all the hierarchies – and I find automated refactoring a very important tool for development.
  3. Because there are separate project hierarchies and separate build projects, it encourages developers to add non-portable code and to add things like ”#define”
  4. I expect this architecture will become less maintainable when I try to add Silverlight, WPF, WP8, MonoMac and PlayStationStudio to the MvvmCross platform. 

These portability ideas and questions are of course not new – they have been highlighted and discussed before by many other developers, including lots of notable “big fish” in the cross platform development community:

My personal hope for vNext for me is that MvvmCross will be able to achieve portability using the next generation of Portable Class Libraries.

What is a Portable Class Library?

The Portable Class Library tools provide:
  • a special class library project type
  • a set of portability profile definitions – each of which defines an “API level” which libraries must conform to in order for them to be portable. 
When a portable library project is built, then it builds against a given profile, but it only when the code is linked that the platform specific implementations of those APIs are actually located.

To understand PCLs more, Jeremy Likeness did a great 3 part blog post – see http://csharperimage.jeremylikness.com/2012/03/understanding-portable-library-by.html

What’s needed in PCLs for MvvmCross?


The profile I’ve been using in MvvmCross for my PCL work is “Profile 104”

This profile includes:

  • mscorlib 
  • system.core.dll 
  • system.net.dll 
  • system.runtime.serialization.dll 
  • system.servicemodel.dll 
  • system.servicemodel.web.dll 
  • a very small part of system.windows.dll 
  • system.xml.dll 
  • system.xml.linq.dll 

Almost all of these are supported directly in the MonoTouch and MonoDroid platforms, although a very small amount of type redirection and substitution is needed for System.net.dll and system.windows.dll

This is achieved through using dedicated “shim” assemblies which simply redirect the Type load calls from (for example) System.Net.IPAddress in System.Net.dll to System.Net.IPAddress in Monodroid’s System.dll
You can see this redirection in action for MonoDroid in:
By using this profile 104, then I have managed to get the solution down to a much smaller size:

 

Moreover, within this solution above:
  • builds for all of WP7, Droid and Touch within VisualStudio 
  • allows automated refactoring 
  • has no manual cut and paste steps required 
  • the build executables run on WP7 and Droid straight from the VS2010 environment. 
  • Behind the scenes there is now a superb new MvvmCross library and plugin architecture which also uses PCLs – and this makes producing and extending MvvmCross much easier. 

So… what’s remaining to do?


There's one major challenge remaining:
  • I can’t yet get this project to build and run within MonoDevelop on the Mac – so I can’t deploy onto an iOS device. 
This is obviously quite a serious problem!

However, the good news is that the latest Beta versions of MonoDevelop do seem to contain some new support for PCL :)

Currently I’m still playing with this support but the initial result looks good – I can at least load the same VS2010 solution inside MonoDevelop - and the PCL projects and their references all look to be present and correct.

I’m currently investigating some problems with incompatibilities between some core System.Core definitions – especially around System.Action and System.Func - and I do still have to find a way to get System.Windows.dll (touch) and System.Net.dll (touch) into the MonoTouch GAC.

However, this feels really close now…. The future is close… and it’s already looking awesome :)

Thursday, May 10, 2012

One pattern for error handling in MvvmCross


One pattern for how to handle errors/exceptions during async calls in MvvmCross is available in the BestSellers example: MvvmCross BestSellers Sample
BestSellers uses 2 techniques that I find I've used quite a lot in MvvmCross applications:
  • the use of BaseViewModel classes for shared ViewModel code like error handling
  • the use of an app level "error router" to get errors from the ViewModels to UI notifications like UIAlertViews, Toasts and/or MessageBoxes.

At a more detailed level, what BestSellers does is:
Each ViewModel uses a direct call to a webservice for book information. For example the Category List is constructed as:
    public CategoryListViewModel()
    {
        AsyncLoad();
    }

    private void AsyncLoad()
    {
        GeneralAsyncLoad(URL_CATEGORIES, ProcessResult);
    }
where GeneralAsyncLoad is defined in a shared BaseViewModel:
    protected void GeneralAsyncLoad(string url, Action responseStreamHandler)
    {
        try
        {
            IsLoading = true;
            var request = WebRequest.Create(url);
            request.BeginGetResponse((result) => GeneralProcessResponse(request, result, responseStreamHandler), null);
        }
        catch (ThreadAbortException)
        {
            throw;
        }
        // obviously we could do better than catching all `Exception` here!
        catch (Exception exception)
        {
            IsLoading = false;
            ReportError("Sorry - problem seen " + exception.Message);
        }
    }
The ReportError method within the above exception handler uses an injected object - anIErrorReporter.
This injected object is initialised as a singleton during App construction - seeErrorApplicationObject in App.cs
During their construction and setup, the UI projects all subscribe to events from that same singleton - but using an IErrorSource interface instead or IErrorReporter.
This then allows each platform to display it's own error display - e.g.:

Obviously, if you need error handling as well as error displaying - e.g. if you want to retry the asynchronous operation or if you want to load an offline copy of data instead - then you can add this to your error handling within the ViewModel and the BaseViewModel.

Using Custom ViewModelLocators in MvvmCross


In MvvmCross, the "container" for ViewModelLocators is the MvxApplication object. By default it uses a convention based MvxDefaultViewModelLocator which just tries to construct ViewModel instances by using their declared constructors which have string parameters.
If you would like to use your own ViewModel locator, then the easiest way is simple to inherit from MvxViewModelLocator and to provide either public Properties or public Methods which return your ViewModel instances:
e.g:
public class MyViewModelLocator : MvxViewModelLocator
{
    public MyFirstViewModel CreateFirst()
    {
        return new MyFirstViewModel();
    }

    public MySecondViewModel CreateSecond(string aParameter)
    {
        var someLookup1 = ComplicatedStaticThing1.Lookup(aParameter);
        var viewModel = new MySecondViewModel(someLookup1);

        var someLookup2 = ComplicatedStaticThing2.Lookup(aParameter, someLookup1);
        viewModel.DoSomething(someLookup2);

        return viewModel;
    }

    private readonly MyThirdViewModel _third = new MyThirdViewModel();
    public MyThirdViewModel Third
    {
        get
        {
            return _third;
        }
    }
}
If you want to go even lower than this, then you can also implement IMvxViewModelLocator directly instead.
To add the ViewModelLocator to the application, simply instantiate and add it inside your app - e.g:
public class App 
    : MvxApplication
    , IMvxServiceProducer
{
    public App()
    {
        this.RegisterServiceInstance(new StartApplicationObject());

        base.AddLocator(new MyViewModelLocator());

        // to disable the default ViewModelLocator, use:
        // base.UseDefaultViewModelLocator = false;
    }
}

Note: - apart from for design time data, I now very rarely find the need to implement custom ViewModelLocator - in general everything I want to do can be done within the ViewModel construction.

Adding custom bindings in MvvmCross for Android/MonoDroid


The MvvmCross binding framework automatically adds one-way bind (from ViewModel to View) to all existing public Properties on any MonoDroid/Android View/widget.
If the public Property isn't of the correct type (e.g. it's some Android enumeration instead of a View), then you can use an IMvxValueConverter to do a conversion.
If you want to do 2-way binding, or there isn't a public Property for what you want to bind to, then you fairly easily do a custom binding. For an example of this, see the custom IsFavorite 2 way binding in the conference sample
This code adds a new bindable pseudo-property "IsFavorite" to every Android Button.
... this is initialised in Setup.cs using code like:
    protected override void FillTargetFactories(MvvmCross.Binding.Interfaces.Bindings.Target.Construction.IMvxTargetBindingFactoryRegistry registry)
    {
        base.FillTargetFactories(registry);

        registry.RegisterFactory(
                    new MvxCustomBindingFactory<Button>(
                       "IsFavorite", 
                       (button) => new FavoritesButtonBinding(button)));
    }
... and the binding code is:
public class FavoritesButtonBinding
    : MvxBaseAndroidTargetBinding
{
    private readonly Button _button;
    private bool _currentValue;

    public FavoritesButtonBinding(Button button)
    {
        _button = button;
        _button.Click += ButtonOnClick;
    }

    private void ButtonOnClick(object sender, EventArgs eventArgs)
    {
        _currentValue = !_currentValue;
        SetButtonBackground();
        FireValueChanged(_currentValue);
    }

    public override void SetValue(object value)
    {
        var boolValue = (bool)value;
        _currentValue = boolValue;
        SetButtonBackground();
    }

    private void SetButtonBackground()
    {
        if (_currentValue)
        {
            _button.SetBackgroundResource(Resource.Drawable.star_gold_selector);
        }
        else
        {
            _button.SetBackgroundResource(Resource.Drawable.star_grey_selector);
        }
    }

    protected override void Dispose(bool isDisposing)
    {
        if (isDisposing)
        {
            _button.Click -= ButtonOnClick;
        }
        base.Dispose(isDisposing);
    }

    public override Type TargetType
    {
        get { return typeof(bool); }
    }

    public override MvxBindingMode DefaultMode
    {
        get { return MvxBindingMode.TwoWay; }
    }
}

Presenting modal UIViewControllers in MonoTouch using MvvmCross


MvvmCross starts from the premise that all ViewModels are just "normal pages" - so in iOS/MonoTouch that means UIViewControllers presented using a UINavigationController.
To move away from this premise - towards tabbed displays, modal displays, split controllers, popups, etc - then you can adjust the Presenter logic within your MonoTouch app.
The presenter's job is to implement:
public interface IMvxTouchViewPresenter
{
    void Show(MvxShowViewModelRequest view);
    void Close(IMvxViewModel viewModel);
    void CloseModalViewController();
    void ClearBackStack();
    bool PresentModalViewController(UIViewController controller, bool animated);
    void NativeModalViewControllerDisappearedOnItsOwn();
}
The presenter used for your app is selected in AppDelegate construction - e.g. see how theTwitterSearch builds different presenters for iPhone and iPad.

Fortunately, for simple Modal support, one of the standard presenters available isMvxModalSupportTouchViewPresenter.cs
This presenter looks to see if the view being presented has the IMvxModalTouchView marker interface - it tests view is IMvxModalTouchView. If this interface is present, then it uses modal presentation for the view instead of "normal navigation".
To use this, change your AppDelegate code to something:
    public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {
        window = new UIWindow(UIScreen.MainScreen.Bounds);

        // initialize app for single screen iPhone display
        var presenter = new MvxModalSupportTouchViewPresenter(this, window);
        var setup = new Setup(this, presenter);
        setup.Initialize();

        // start the app
        var start = this.GetService();
        start.Start();

        window.MakeKeyAndVisible();

        return true;
    } 
Then add the marker interface to your modal View(s):
 public class MyView : MvxBindingTouchViewController, IMvxModalTouchView
 {
      // ....
 }

Tuesday, May 01, 2012

If you install Visual Studio 11 and VSMonoTouch stops building with mscorlib problems...

If you install Visual Studio 11 and VSMonoTouch stops building with mscorlib problems...

or if you are seeing problems referencing simple Core types like System.Action...

Then:

1. Set the flag in Properties > Build > Advanced ... which says "Do not include mscorlib"

2. Make sure you have followed the vsmonotouch setup instructions:

A note on mscorlib.dll

The MonoTouch templates does not include an explicity reference to mscorlib.dll. The default behavior of Visual Studio 2010 is that all projects contain an implied reference to mscorlib.dll. The problem is that the implied version of mscorlib.dll is different from the MonoTouch mscorlib.dll, which will give you warnings in the editor. The project will compile just fine without the reference.

The other problem is how Visual Studio 2010 will not let you add a new reference to mscorlib.dll as it allready have that reference implied. The way to work around this is to add it manually by editing the .csproj file.

  <ItemGroup>
    <Reference Include="mscorlib" />
    <Reference Include="monotouch" />
    <Reference Include="System" />
    <Reference Include="System.Xml" />
    <Reference Include="System.Core" />    
  </ItemGroup> 

Visual Studio will now pick up the MonoTouch version of mscorlib.dll, and the project will still build just fine in MonoDevelop. The next update of the extension will enable you to automatically add this reference if missing.