Saturday, December 14, 2013

v3.1.1 beta

The first beta of the first Net4.5 only release of MvvmCross is uploaded to nuget and binaries are on github too - https://github.com/MvvmCross/MvvmCross-Binaries/tree/v3.1.



The changes since v3.0.14 are big:
  • Switch to profile 158 for all portable assemblies
  • Switch to WP8 for all WindowsPhone projects - plus System.Windows.Interactivity dependency updated to 3.9.5
  • Fragging now uses the Google Xamarin.Android v4 support library rather than the Mono.Android one.
  • Html email fix for Android
  • Changes to nuget referencing (especially WP8 and SL5)
  • To avoid angst, the existing SQLite plugin is no longer marked "obsolete" - I still encourage everyone to switch to the new community plugin as it is the better plugin (and I encourage people to step forwards to take over the admin of this too!)
  • Improved helper method for subscribing to Interaction events
  • A draft IMvxComposeEmailTaskEx interface has been added to the mail plugin allowing attachments and multiple addresses on some platforms. More work is still needed here



Further notes:
  • General MvvmCross user consensus seemed to be that profile 78 was preferred to profile 158. Given this, we'll definitely continue to look at how/when/if to switch to 78 in the near future. However, right now today I wanted to start getting releases out, and the switch of reflection API for profile 78 would have caused too long a delay in this (especially in testing/debugging/fixing on all platforms).

  • In the v3.1 branch, there are also ongoing changes and improvements to both MonoMac and XamMac support - especially with heroic inputs from tofutim. However, these inputs are not today included in the released nuget stream or in the binary packages.

Saturday, December 07, 2013

NDC London Talk - Data-Bind Everything

I spoke at the first NDC London conference this week.


It was a great conference - really good to see and meet so many devs here in my home city.


I gave a talk on the opening morning about how we'd created and extended a data-binding engine for MvvmCross.


Sadly, there's no recording of this talk available, but I've put the slides and the code online - I hope they make some sense to someone :)


Slides:



Code: https://github.com/slodge/BindingTalk

Saturday, November 16, 2013

MvvmCross 3.0.14

After 3 betas, I've now pushed 3.0.14 to nuget and to the binary repo :)


This is probably the last 3.0.x release


The next release will hopefully be 3.1.x - for this next version we will drop Windows Phone 7.x support and aim to more fully support the new releases from Xamarin/Microsoft (Xamasoft?)


For my latest on how to use nuget with Xamarin, please see the run-through in http://slodge.blogspot.co.uk/2013/11/quick-run-through-using-pcls-in.html



The changes in 3.0.14 over 3.0.13 are:
  • Changes to nuspec files for more generic targets (I believe switching nuget to the latest 2.7.2 release will also help some users)
  • Improvements in intrinsic boolean conversions
  • Optimisation in nested bindings - changes to reduce the number of times source properties are fetched during updates
  • Fix for spinner which caches the DataContext when a child window is switched off of the screen and then back in again (without going through an Adapter GetView)
  • Virtual keyword additions to allow additional overrides for CreatingBinding and for GetIoCParameterValues
  • Changes to ValueCombiners to allow them to better support UnsetValue - these now return the UnsetValue if any child is Unset
  • Redirecting the Progress value in the Seekbar so that reflection is not used (very minor optimisation)
  • Refactoring of Android layout inflation code - allowing custom view creation if required
  • Provision of some Folder methods for the MvvmCross File plugin on WindowsStore (Win8/WinRT)
  • A fix for MvxLinearLayout refresh issues
  • A change of protected API for CreateBindingView in MvxAdapter - it now returns an IMvxListItem instead of an MvxListItem (this method is seldom overridden - but is a breaking change if you did override it)
  • A fix for ThreadUtils - Wpf Package
  • A fix for ViewModel creation for activities displayed via external Intents - e.g. from Mail or push links
  • Change to Droid and Touch collections/lists - nullify the datacontexts of individual listview items when removed
  • Wpf ThreadUtils assembly has been added
  • Improvements in binding parsing of properties beginning with and containing underscores
  • Improved error messages when binding fails
  • Binding for Android RatingBar control
  • ShouldReturn binding for iOS
  • Fix to Or logic in ValueCombiner
  • Provision for default parameters in ViewModel Init methods
  • Inclusion of additional LinkerPleaseInclude entries for Android
  • Trace optimisation - no messages shown for null datacontexts


Any problems/issues, please do report them via forums, stackoverflow or via github issues

Thursday, November 14, 2013

Quick run through - using PCLs in Xamarin.Android and Xamarin.iOS with mvvmcross

Following up from yesterday's annoucements, I've just recorded a quick "new project" run-through for PCLs with iOS and Android.


This run-through shows that the process isn't perfect right now - there are a few tweaks along the way - but overall it's a HUGE step in the right direction and you should hopefully be able to get your projects up and running quite quickly.



The source of what I built is on: https://github.com/slodge/Demo


Note that I am using the latest nuget - 2.7.2 - downloaded from http://visualstudiogallery.msdn.microsoft.com/27077b70-9dad-4c64-adcf-c7cf6bc9970c


The video is on:






If you've got questions, ideas, suggestions please do start a conversations somewhere - maybe on the MSDN or Xamarin forums, or maybe on Stackoverflow. Please do this in public somewhere - it's great to have open source conversations in public :)


Please do also write your own blog posts and make your own videos - it's fab seeing what others are doing :)

Profiles in the new Portable World

There was lots of great news yesterday - including Microsoft shipping lots of their PCL libraries under a new permissive license and Xamarin working with Microsoft and shipping working PCL support to stable




For those of you who are already ahead of the curve and working with PCLs across all the modern platforms, then this is all really great news. It really reaffirms the direction MvvmCross has been following for the last 18 months.


However, there are some teething problem right now and I'm afraid solid information about what has shipped and how it works is a bit thin on the ground right now.


Right now, if you want to carry on working with PCLs and MvvmCross, then I think some of the steps you may need to take are:

  • If you want to build on Mac, then you may need to change the profile of your PCL from 104 to something newer - with many people currently seeming to choose profile 158. To do this is as simple as editing the csproj file. However, please be aware that doing this will remove support for Windows Phone 7.5 - profile 158 only supports Windows Phone 8 and higher
  • If building Droid projects outside of Visual Studio, you may also need to remove the assembly references to the MvvmCross System.Windows.dll and System.Net.dll - and you may instead need to use the assemblies of the same names that now ship from Xamarin
  • If using nuget, then you may need to update to the latest release (2.7.2) and you may need to use the latest prerelease 3.0.14-beta3 packages from MvvmCross - these are available if you select "include prereleases" inside nuget


Obviously these instructions are "a little sketchy" right now. Sorry - we're doing are best to work with the information that's available. It's not yet really clear what the current state is - how stable the released things are. Hopefully, we'll all learn a lot in the coming days :)


It does seem like Microsoft have forced the retirement of WP7.x development - so it does look likely that we will retire WP7.x support from MvvmCross


It may also be that the future of MvvmCross (v3.1?) lies in one of the 4.5 profiles - like profile 78 - rather than in the 4.0 profiles like 104 or 158. However, this depends a bit on how well the new open Bcl packages can work with Xamarin - and it depends on how we find a way to continue our Silverlight and Unity3D support.


I'll be back with more definitive news real soon :)


The future is portable... and it's now? :)

Wednesday, November 13, 2013

3.0.14-beta3 pushed to nuget

Have updated the build


Have pushed to nuget


Have also pushed VS2012 only binaries to the binaries repo (in theory the XS-built binaries are no longer needed)

In addition to Beta2, Beta3 has:


  • Changes to nuspec files for more generic targets (I believe switching nuget to the latest 2.7.2 release may also help some users)
  • Optimisation in nested bindings - changes to reduce the number of times source properties are fetched during updates
  • Fix for spinner which caches the DataContext when a child window is switched off of the screen and then back in again (without going through an Adapter GetView)
  • Virtual keyword additions to allow additional overrides for CreatingBinding and for GetIoCParameterValues
  • Changes to ValueCombiners to allow them to better support UnsetValue - these now return the UnsetValue if any child is Unset
  • Redirecting the Progress value in the Seekbar so that reflection is not used (very minor optimisation)
  • Refactoring of Android layout inflation code - allowing custom view creation if required
  • Provision of some Folder methods for the MvvmCross File plugin on WindowsStore (Win8/WinRT)





Beyond this, the features included in 3.0.14 beyond 3.0.13 remain:


  • A fix for MvxLinearLayout refresh issues
  • A change of protected API for CreateBindingView in MvxAdapter - it now returns an IMvxListItem instead of an MvxListItem (this method is seldom overridden - but is a breaking change if you did override it)
  • A fix for ThreadUtils - Wpf Package
  • A fix for ViewModel creation for activities displayed via external Intents - e.g. from Mail or push links
  • Change to Droid and Touch collections/lists - nullify the datacontexts of individual listview items when removed
  • Wpf ThreadUtils assembly has been added
  • Improvements in binding parsing of properties beginning with and containing underscores
  • Improved error messages when binding fails
  • Binding for Android RatingBar control
  • ShouldReturn binding for iOS
  • Fix to Or logic in ValueCombiner
  • Provision for default parameters in ViewModel Init methods
  • Inclusion of additional LinkerPleaseInclude entries for Android
  • Trace optimisation - no messages shown for null datacontexts

Portable support is changing within Xamarin right now - but the news is mainly at the "announcement" level right now - as we get details through then we will update MvvmCross to make sure we can all get on with doing dev work instead of setup :)

Thursday, November 07, 2013

N=42 - Is my ViewModel visible? Can I kill it?

Today's N+1 is all about whether or not your ViewModel is Visible - and about how to kill it when it gets removed from the screen.


This is a fairly FAQ topic - see questions like http://stackoverflow.com/questions/15961664/viewmodel-lifecycle-when-does-it-get-disposed and http://stackoverflow.com/questions/19816819/how-are-views-and-viewmodels-freed-up-in-mvvmcross


MvvmCross doesn't provide any built-in event notification - but it is easy to add it for your app.


In this video, I show how to add and invoke interfaces like these to some view models which are shown by a standard MvvmCross presenter:




If you have custom presentation, then you'll need to adapt this technique to suit your needs - but, since it is your custom presentation, then you should hopefully be in the best place to do this.


The source for today's video is in https://github.com/MvvmCross/NPlus1DaysOfMvvmCross/tree/master/N-42-Lifecycles


The video itself is:




The audio skips in the first few seconds - making me sound even odder than normal ;)


For a full N+1 index, please see Aboo's fabulous work on http://mvvmcross.wordpress.com

Wednesday, November 06, 2013

Why you should always Dispose your HttpWebResponse objects

I very recently came across a "hard to solve" issue.


Well, it certainly felt like one...


The problem showed itself via all my HttpWebRequest's blocking - they didn't timeout, they didn't exception - they just blocked.


I couldn't work out what was causing this - and the situation was complicated because the servers I were talking to were quite complicated - they were PHP apps running on Apache, but hiding behind nginx running node.js middleware.


The one thing I could see was that just before things went wrong, these servers were returning "chunked" HTTP 1.1 responses.


The problem also looked more complicated because when I used Fiddler to try to debug the issue, then the problem disappeared (this is because Fiddler alterred the way the responses were received - it doesn't quite mirror responses perfectly - for chunked responses it concatenates them)


Some research led me to various blog posts, stackoverflow answers, etc which all suggested issues - e.g. things like http://blog.degree.no/2011/06/webclient-httpwebresponse-problems-with-chunked-transfer-encoding/


I wrote a test harness, got the case reproducible and then reached out to some friends in MS to see if I had found a genuine issue.


I had, of course, not found one....


Instead, one of the MS guys answered quickly and from his gut:

my gut feel is that you aren’t emptying the body of the first request when using HttpWebRequest.  Can you ensure you are reading the entire body of the first request before sending the second one with HttpWebRequest?


I checked all our calls....


... and in one of them we weren't reading the response at all.


... so I added a `Dispose()` to the response there (instead of reading its stream)


... and that caused the Http stack to start behaving again


... :)


So, it seems like what was happening was that when this "Chunked Transfer Encoding" occurred, then the HttpWebRequest stack got "stuck" waiting for code to read the incomplete response - and this prevented future calls from working.


So the moral of the story is: Dispose() your HttpWebResponse objects - or, if not, at least read them in their entirety.


It's also worth noting: this problem didn't really show up when we switched the code to the newer HttpClient - so, if you are looking at new code, then please do use HttpClient instead!


Thanks especially and hugely to @dsplaisted and @theesj for pointing out (using just their guts) the error. Hopefully by posting this here, it will help others.... 

Monday, November 04, 2013

3.0.14-beta2 on nuget

Have updated the build

In addition to Beta1, Beta2 has:

  • A fix for MvxLinearLayout refresh issues
  • A change of protected API for CreateBindingView in MvxAdapter - it now returns an IMvxListItem instead of an MvxListItem (this method is seldom overridden - but is a breaking change if you did override it)
  • A fix for ThreadUtils - Wpf Package
  • A fix for ViewModel creation for activities displayed via external Intents - e.g. from Mail or push links


Overall, the features included in 3.0.14 beyond 3.0.13 remain:


  • Change to Droid and Touch collections/lists - nullify the datacontexts of individual listview items when removed
  • Wpf ThreadUtils assembly has been added
  • Improvements in binding parsing of properties beginning with and containing underscores
  • Improved error messages when binding fails
  • Binding for Android RatingBar control
  • ShouldReturn binding for iOS
  • Fix to Or logic in ValueCombiner
  • Provision for default parameters in ViewModel Init methods
  • Inclusion of additional LinkerPleaseInclude entries for Android
  • Trace optimisation - no messages shown for null datacontexts

Saturday, November 02, 2013

3.0.14 Beta1 on nuget

The latest build - 3.0.14-Beta1 - has survived some preliminary testing and is now on nuget


There is one significant change which may break client apps in this build.


The change is to do with the way that collection items have their DataContext set to null when the bindings are cleared. It should help prevent a problem that Blewzman reported when he used long-living nested static collections in his viewmodels.



This change may effect your existing views, valueconverters and bindings if they don't cope well with null DataContexts.



For example, in the ApiExamples project this required me to add a check for null to the Convert method:

         protected override string Convert(string value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
         {
             if (value == null)
                 return null;
             return value.Replace((string)parameter, string.Empty);
         }
 

Overall, the features included in 3.0.14 beyond 3.0.13 are:

  • Change to Droid and Touch collections/lists - nullify the datacontexts of individual listview items when removed
  • Wpf ThreadUtils assembly has been added
  • Improvements in binding parsing of properties beginning with and containing underscores
  • Improved error messages when binding fails
  • Binding for Android RatingBar control
  • ShouldReturn binding for iOS
  • Fix to Or logic in ValueCombiner
  • Provision for default parameters in ViewModel Init methods
  • Inclusion of additional LinkerPleaseInclude entries for Android
  • Trace optimisation - no messages shown for null datacontexts

Saturday, October 26, 2013

An awesome alternative i18n implementation - opcode bags badge #2

Earlier this year, Stefan posted an article about how to integrate resx files with the MvvmCross localisation framework - http://opendix.blogspot.ch/2013/05/using-resx-files-for-localization-in.html


Recently Andrei - opcode - has taken the same resx files and pushed them in a different direction.


He looked at the existing Json code and he didn't like it... As he said, "I went through the N+1 video and tried to understand localization using the Json localization plugin but it almost made me cry"... so instead of crying he went off and created an alternative implementation - using resx files directly from ViewModels to allow i18n text bindings like:



"Text [UsernameText]"
android:layout_width="wrap_content" android:layout_height="wrap_content" />


This alternative option is awesome. It fits exactly with one of the fundamental principles of MvvmCross - that people should write the code they want to write - the app is the king!


If you want to learn more about this approach then the blog post and code is at: http://enginecore.blogspot.co.uk/2013/09/localization-in-xamarin-mvvmcross_18.html


Awesome!



Friday, October 25, 2013

An Awesome Detroit Mobile MvvmCross presentation from Rob Gibbens

Rob Gibbens recently gave a full MvvmCross introduction to the @DetMobileNet group.


I don't know much about this... but from the feedback it sure looks awesome!





Well deserving of a shiny badge of awesomeness - great work Rob!



MvvmCross.Mac awesomeness from Tim and Kevin

One of the goals for MvvmCross v3 was support for MonoMac and Xamarin.Mac


Kevin - @deapsquatter - at CentraStage has been pushing this work forwards for over 6 months now and has blogged about specific parts like Mac NSTableView support


More recently, Tim - @tofutim - at loqu8 has been pushing forwards with PCL code from the tip of v3.


Together, they've got our .mac support into a good state - as you can see:





This is .... of course.... awesome - doubly so! And I'm delighted to give Tim a first badge of awesomeness and Kevin his 4th


 

Thursday, October 24, 2013

More more more more awesome plugins from the big Cheese - badge #5

Regular MvvmCross users will already know Cheesebaron - he's already got **4** badges of awesomeness...


And today he gets number **5**!


The reason - he's posted lots of new plugins to his github repo - https://github.com/cheesebaron/Cheesebaron.MvxPlugins/


Beyond the Azure Access Control plugin I blogged about last month, these include:


  • an SMS plugin
  • a Settings plugin (with a notable assist for James M)
  • a basic phone info plugin
  • a Connectivity plugin



Beyond these, Cheesebaron's also really proactive and helpful on the MvvmCross Github issues, on Stackoverflow and on the Xamarin forums - applying skill and expertise to help lots of devs every day. So as well as badge #5 I'm delighted to say that Cheesebaron's now also a full admin on the MvvmCross repos.


Awesome NYC Code Camp samples from Greg Shackles - badge #2 !

In September Greg Shackles gave an awesome talk about multi-platform C# development at the New York Code Camp





The code for this talk is particularly awesome - it uses file linking rather than PCLs and it fully takes advantage of Task and of lots of the awesome async features in C#5 and Xamarin 2.0 - take a look at it on https://github.com/gshackles/NycCodeCamp8



It's a huge pleasure to announce badge #2 for Greg - thanks Greg - awesome code and awesome presenting!





A UserInteraction plugin - from Brian Chance - awesome again!

One of the common questions when writing Mvvm ViewModel code is "How do I show a MessageBox?"


There are a few answers around to this on StackOverflow - e.g. using an interaction helper or using a dialog service


However, for simple message boxes or for a simple message prompt, BrianChance has provided this open source plugin - https://github.com/brianchance/MvvmCross-UserInteraction


So now showing a message is as easy as:




This is awesome - and it happily earns Brian badge #2 - thanks Brian!



Using the Infragistics Nuclios Grid control with MvvmCross binding - awesome from Blake Davidson

Recently, Blake Davidson - @davidsonblake86 - has posted this blog post -
http://davidsonblake.wordpress.com/2013/10/15/single-row-gridview-using-mvvmcross-infragistics-nuclios-and-xamarin-ios/ - showing how monkeys can easily be databound into an Infragistics grid from an MvvmCross ViewModel.





Infragistics have been long-term supporters of MvvmCross and it's really awesome to see their controls databound this way!


Blake - thank you hugely for his awesomeness - an awesome badge of thanks!



Developers Developers Developers - awesome up North from Ross Dargan

Ross Dargan gave this presentation at DDD North recently:



It covers lots of MvvmCross topics - including file sharing, PCLs, IoC and Mvvm - and it comes with lots of awesome samples in https://github.com/rossdargan/Talks


Awesome stuff - and well deserving of a badge of awesomeness - thanks, Ross!



Awesome profiling and optimising from Miha Markic

Earlier this month we shipped 3.0.13 - this included lots of improvements - including a couple of speed optimisations for Android binding.


These came from some work Miha Markic has done in profiling Xamarin.Android using high frequency counters - see his excellent blog post on the topic about it on http://blog.rthand.com/post/2013/09/12/Poor-mans-performance-profiling.aspx


This is awesome work - really helping MvvmCross to keep improving - and hugely deserving of a first badge of awesomeness - thanks Mika!




Hawkes Bay awesomeness from Sean Cross

Sean Cross recently gave this Hot Tuna talk in Hawkes Bay, NZ:





It's awesome! And well deserving of a badge of awesomeness - top talking Sean!





More Montemagno awesomeness - sliding Nav Drawers

Following on from last month's badge for MvxUIRefreshControl, this month we've seen 2 superb new samples from James Montemagno:




The samples for these are fab - especially the monkey based sample for Android 'hamburger' menus:



You can take a look at the source on - https://github.com/jamesmontemagno/Xam.NavDrawer


These monkeys are awesome :) And they are very well deserving of James' second badge of awesomeness - thanks James!


Wednesday, October 09, 2013

3.0.13 - pushed to nuget

I've now pushed 3.0.13 to nuget :)


Thanks to everyone who's contributed code, ideas and assistance - I'm well behind on badges now - so many of you are awesome! I will catch up on badges soon!



Note that there are some potentially breaking changes in 3.0.13 - marked in bold in the change list below.

The most obvious of these will be in:
Other more subtle breaking changes may come out of some of the binding optimizations - if any bugs appear, please do report them (with reproduction examples if possible).


-----


The main changes from 3.0.12 are:


  • added UnsetValue and DoNothing binding constants to allow richer ValueConverter implementation (note that these constants are not fully supported across all Windows platforms)
  • changed binding implementation so that many more binders will now block feedback loops
  • changed binding implementation so that many more binders will now attempt value coercion when setting values on a target
  • optimised text binding in Droid and Touch - 'label' controls will be set directly using non-reflection and using one-way binding as default
  • optimisations for one-way binding - event subscription is not removed
  • added an IMvxInteraction helper interface to assist with 'dialog' user interactions
  • cleared up 'mixed spellings' of Initialisation/Initialization - the US spelling 'Initialization' is now used everywhere (this may break some overrides in people's Setup code)
  • event `Raise` extension methods now moved into shared code - into CrossCore
  • fragment inflation no longer causes an error message in trace
  • fixed two missing event hook calls in Android dialog code
  • Binding DataContext's now have a DataContextChanged event
  • By default, views can now be named with postfix 'View' or 'ViewController' on iOS, 'View' or 'Activity' on Android, 'View' or 'Page' on WindowsPhone/Store, 'View' or 'Control' on WPF
  • Small optimisation in internationalisation converter
  • Improved access to MasterNavigationController in Touch presenters - as requested via @deapsquatter's blog
  • Improved override capabilities for AndroidLifetime monitoring object
  • Improved error message for users using viewmodels from mutliple assemblies
  • Weak referencing is now used in Rio field binding
  • Added a new location interface into the location plugin - the old one still works but is now marked obsolete
  • Added a simple Reachability implementation for Android in the Network plugin
  • Fixed a "To" regression in the Android email plugin
  • Added simple UIView/View/Control boolean "Hidden" bindings for all platforms
  • FluentBindings can now use `FullyDescribed` and `SourceDescribed` methods to describe contents - e.g. Bind(textField).FullyDescribed("Text MyConverter(Property1)") and Bind(textField).For(t => t.Text).SourceDescribed("MyConverter(Property1)") - the previous Described method (which is SourceDescribed) is now marked as Obsolete
  • Integrated lots of Android Dialog changes from @csteeg - many improvements in usability and stability (if you have overridden GetViewImpl the signature has now changed)
  • Included improved Bitmap resource drawable binding from @Cheesebaron and @scatria
  • Fixed misaligned ViewDidAppear/Disappear calls in event source UIViewController
  • Added MvxRadioGroup from @BenGladman for Android (it's fab!)
  • Added SimplePickerElement from @BenPage for Android Dialog
  • Fixed ambiguous construction issue with MvxColor - and unit tests for the default RGB color value converters
  • Added named MvxColors class based on Mono standard name set
  • Merged Mac binding and Mvvm code from @loqu8 and @deapsquatter - Mac has separate solution currently (more on this soon hopefully)
  • Improved TeamCity buildability via @loqu8 
  • INotifyCollectionChanged event is LinkerPleaseInclude included within MvvmCross core library
  • Android Download image loader can use "res:" prefix for images
  • Android MvxImageView exposes DefaultImagePath and ErrorImagePath properties (matches iOS API now)
  • Android MvxImageView no longer has a IntPtr constructor
  • ToString error messages improved for binding debugging
  • Android MvxSpinner now uses radio elements by default 
  • Android MvxBaseListItem now supports ICheckable
  • Github projects have moved into /MvvmCross organisation

ios7 ... I seem to be using this code a lot

Most of my UIView layout changes for ios7 seem to come down to just adding:


Changes to custom bindings in v3.0.13

3.0.13 does include some breaking changes as we've changed some underlying APIs for custom bindings.


Sorry for this - these type of API changes are something we try to avoid - but in this case there were some good reasons.


We've changed the API for two key reasons:

  1. Improved Performance - we've found that by splitting the target binding event subscription out into a separate public API then we can achieve better binding performance for OneWay bindings
  2. Improved Functionality - we've identified that more bindings can benefit from auto-type coercion and from auto-change-loop removal by moving the SetValue helpers from the PropertyInfo-based bindings to a lower level.

With those justifications out of the way, the key changes you should make to any custom binding in v3.0.13 or later are:


Move event subscriptions into SubscribeToEvents

This isn't essential - but is good practice. If the user specifies OneWay binding, then this change will provide them with a small performance improvement with each binding.

Code before change:


Code after change:


Move value setting code from SetValue into SetValueImpl

This change is essential.With this change, then the MvvmCross base classes will provide additional type coercion for you (e.g. MvvmCross will automatically convert strings to ints)

Without it, you will get a compiler error saying: "Error 3 'YourTargetBinding' does not implement inherited abstract member 'MvxConvertingTargetBinding.SetValueImpl(object, object)'

Code before change:


Code after change:



Sorry again for any inconvenience caused by this change - we've tried very hard not to make breaking changes to APIs since we signed the v3 APIs off on March 1st this year - but in this case the benefits were worth it!

Tuesday, October 08, 2013

3.0.13 - release candidate built - just a bit more testing to complete....

Binaries for 3.0.13 release candidate have now been built- they are in https://github.com/MvvmCross/MvvmCross-Binaries/releases/tag/3.0.13


I've also merged and tagged the source in v3 - https://github.com/MvvmCross/MvvmCross/releases/tag/3.0.13


I've got a few more tests to complete tomorrow morning - it's looking good so far :) - I hope to push 3.0.13 packages to nuget midday tomorrow UK time :)


Thanks for your patience. I'll update with more full release notes when it ships :)

Sunday, October 06, 2013

3.0.13-beta4 testing update

I'm still running through 3.0.13-beta4 and testing it against all the projects in https://github.com/MvvmCross/MvvmCross-Tutorials/ plus against some of the N+1 (some of the key items not covered in those tutorials)

So far the build seems very solid.

I've found one blocking issue:

- some Android.Dialog issues with tapping on specific cells (e.g. datetime) - currently this is under investigation at the tail end of https://github.com/MvvmCross/MvvmCross/pull/363

Apart from that, it's not taken me very long at all to update the projects. The main issue I've encountered is changes in PCL setup each time (e.g. changing to use Xamarin's System.Windows assembly for each Touch project) and I've really only found a few minor issues with:


- one new exception thrown (and handled lower down) during double-string conversion - now masked in https://github.com/MvvmCross/MvvmCross/commit/219b9f37ea0db61a8e53954b6dabb50fd8410bca
- one missing setup call in Console projects (added in https://github.com/MvvmCross/MvvmCross/commit/a0e43434b5e25c017ffdad50a5978bde897d0b18)
- a misleading color debug output in https://github.com/MvvmCross/MvvmCross/commit/49cf0e91084a7de391e5fe35331ad6d637d85c84


So... I'm hopeful we'll be able to ship 3.0.13 to stable very soon :)

Saturday, October 05, 2013

"Every time I update using nuget I get FirstView added again :("

If this is happening to you... then the easiest thing to do is to remove the "MvvmCross" and "MvvmCross HotTuna StarterPack" packages from your project - instead rely just on the 'assembly only' packages like "MvvmCrossLibraries" and "CrossCore"


To do this, just edit the packages.config files in your projects.


This gist shows you what I do - what the config file looks like before and after:


Build 3.0.13-beta4 shipped to MvvmCross-Binaries and nuget

I've tagged, built and shipped 3.0.13-beta4

I will be testing it more tomorrow...

If all goes well I plan to ship this as "stable" soon.

Thanks to everyone who's contributed code, ideas and assistance - I'm well behind on badges now - so many of you are awesome! I will catch up on badges soon!

Note that there are some potentially breaking changes in 3.0.13 - marked in bold below. The most obvious of these will be in the changes across MvvmCross to consistently use the US spelling "Initialize" rather than UK spelling "Initialise". Other more subtle breaking changes may come out of some of the binding optimizations - if any bugs appear, please do report them (with reproduction examples if possible).

The main changes from 3.0.12 are:

  • added UnsetValue and DoNothing binding constants to allow richer ValueConverter implementation (note that these constants are not fully supported across all Windows platforms)
  • changed binding implementation so that many more binders will now block feedback loops
  • changed binding implementation so that many more binders will now attempt value coercion when setting values on a target
  • optimised text binding in Droid and Touch - 'label' controls will be set directly using non-reflection and using one-way binding as default
  • optimisations for one-way binding - event subscription is not removed
  • added an IMvxInteraction helper interface to assist with 'dialog' user interactions
  • cleared up 'mixed spellings' of Initialisation/Initialization - the US spelling 'Initialization' is now used everywhere (this may break some overrides in people's Setup code)
  • event `Raise` extension methods now moved into shared code - into CrossCore
  • fragment inflation no longer causes an error message in trace
  • fixed two missing event hook calls in Android dialog code
  • Binding DataContext's now have a DataContextChanged event
  • By default, views can now be named with postfix 'View' or 'ViewController' on iOS, 'View' or 'Activity' on Android, 'View' or 'Page' on WindowsPhone/Store, 'View' or 'Control' on WPF
  • Small optimisation in internationalisation converter
  • Improved access to MasterNavigationController in Touch presenters - as requested via @deapsquatter's blog
  • Improved override capabilities for AndroidLifetime monitoring object
  • Improved error message for users using viewmodels from mutliple assemblies
  • Weak referencing is now used in Rio field binding
  • Added a new location interface into the location plugin - the old one still works but is now marked obsolete
  • Added a simple Reachability implementation for Android in the Network plugin
  • Fixed a "To" regression in the Android email plugin
  • Added simple UIView/View/Control boolean "Hidden" bindings for all platforms
  • FluentBindings can now use `FullyDescribed` and `SourceDescribed` methods to describe contents - e.g. Bind(textField).FullyDescribed("Text MyConverter(Property1)") and Bind(textField).For(t => t.Text).SourceDescribed("MyConverter(Property1)") - the previous Described method (which is SourceDescribed) is now marked as Obsolete
  • Integrated lots of Android Dialog changes from @csteeg - many improvements in usability and stability (if you have overridden GetViewImpl the signature has now changed)
  • Included improved Bitmap resource drawable binding from @Cheesebaron and @scatria
  • Fixed misaligned ViewDidAppear/Disappear calls in event source UIViewController
  • Added MvxRadioGroup from @BenGladman for Android (it's fab!)
  • Added SimplePickerElement from @BenPage for Android Dialog
  • Fixed ambiguous construction issue with MvxColor - and unit tests for the default RGB color value converters
  • Added named MvxColors class based on Mono standard name set
  • Merged Mac binding and Mvvm code from @loqu8 - Mac has separate solution currently (more on this soon hopefully)
  • Improved TeamCity buildability via @loqu8

Thursday, October 03, 2013

N=41 - More Android maps - more advanced - N+1

Today we carry on to a finalé in our trip through data-bound maps on Android.

 
This maps tutorial follows on from:


For demos in the video, I use a real device - sorry for the bad camera work!


I also mess up a few times - sorry :)


I also try some really advanced stuff with making a bindable fragment - for which I make no apologies :)


For really working out how to use Google Maps - see https://developers.google.com/maps/documentation/android/views - it's actually very good documentation!




The source code for today is on: https://github.com/MvvmCross/NPlus1DaysOfMvvmCross/tree/master/N-41-Maps



The video:




For a full and wonderful N+1 index, see: http://mvvmcross.wordpress.com/

GitHub repos have moved across to https://github.com/MvvmCross

I've finally moved all the MvvmCross repos out of my personal account and across into https://github.com/MvvmCross


Hopefully most of the existing hyperlinks and git references should get redirected by the magic of GitHub.


Moving forwards, I do hope and plan that this should allow more people to use MvvmCross and to contribute to MvvmCross more easily. I'm slowly moving things forwards - I'm still very much learning how to do this stuff :)

Wednesday, October 02, 2013

N=40 First Part of Maps on Android - N+1

Today we move on to maps on Android.

 
This maps tutorial follows on from:


To get maps working we use the Google Play Services component - see https://components.xamarin.com/gettingstarted/googleplayservices for how get started on this.



For demos in the video, I use a real device - sorry for the bad camera work!



If you want to try to get maps working on an emulator, then I recommend you take a look at http://www.genymotion.com/ - although I don't think this plays nicely with the WP8 emulator or with the Intel HAXM driver either :(



The source code for today is on: https://github.com/slodge/NPlus1DaysOfMvvmCross/tree/master/N-40-Maps



The video:







Sorry again about the demos by hand rather than in a simulator - and for the pauses while I gather my thoughts each time :)


For a full and wonderful N+1 index, see: http://mvvmcross.wordpress.com/

Tuesday, October 01, 2013

3.0.13-beta2 packages pushed to nuget

I've pushed some 'pre-release' packages to nuget with the latest code from the BindingChanges branch.


This code is definitely pre-release at present - there are a few days of testing ahead of me updating and testing all the samples.


This code also includes a few potential breaking changes - so it is possible that it may eventually be released as 3.1 rather than 3.0. This decision and timeline also depends on Xamarin's release schedule for PCL support - which is outside of Mvx's control. There is still a chance that this support may require us to switch to a different profile - still waiting to find out any information at all on this.



The main changes from 3.0.12 are:

  • added UnsetValue and DoNothing binding constants to allow richer ValueConverter implementation (note that these constants are not fully supported across all Windows platforms)
  • changed binding implementation so that many more binders will now block feedback loops
  • changed binding implementation so that many more binders will now attempt value coercion when setting values on a target
  • optimised text binding in Droid and Touch - 'label' controls will be set directly using non-reflection and using one-way binding as default
  • optimisations for one-way binding - event subscription is not removed
  • added an IMvxInteraction helper interface to assist with 'dialog' user interactions
  • cleared up 'mixed spellings' of Initialisation/Initialization - the US spelling 'Initialization' is now used everywhere (this may break some overrides in people's Setup code)
  • event `Raise` extension methods now moved into shared code - into CrossCore
  • fragment inflation no longer causes an error message in trace
  • fixed two missing event hook calls in Android dialog code
  • Binding DataContext's now have a DataContextChanged event
  • By default, views can now be named with postfix 'View' or 'ViewController' on iOS, 'View' or 'Activity' on Android, 'View' or 'Page' on WindowsPhone/Store, 'View' or 'Control' on WPF
  • Small optimisation in internationalisation converter
  • Improved access to MasterNavigationController in Touch presenters - as requested via @deapsquatter's blog
  • Improved override capabilities for AndroidLifetime monitoring object
  • Improved error message for users using viewmodels from mutliple assemblies
  • Weak referencing is now used in Rio field binding


Several of these  are potential breaking changes - so please be careful to test your apps if you do choose to update.


This code is definitely pre-release at present - there are a few days of testing ahead of me updating and testing all the samples....

Friday, September 27, 2013

A checklist for asking good questions

I love answering questions about MvvmCross (and more besides) and I spend lots of time doing it.

Often the questions are a joy to answer - and they help add lots to MvvmCross itself.

Here's a checklist of tips to help make sure your question is a joy to answer. It's stolen and adapted from Jon Skeet at: http://msmvps.com/blogs/jon_skeet/archive/2012/11/24/stack-overflow-question-checklist.aspx

  • Have you done some research before asking the question? 
  • If you found anything relevant did you include that in your question?
  • Have you explained what you've already tried to solve your problem? 
  • If your program throws an exception or performs 'incorrectly', have you tried to reproduce the behaviour in a small test app?
  • Have you specified which language and platform you're using, including version numbers where relevant? 
  • If your question includes code, have you written it in a way that will allow others to run it? Are there missing parts? Have you cut out as much excess code as you can?
  • If your question includes code, have you checked that it's correctly formatted? 
  • If your code doesn't compile, have you included the exact compiler error? 
  • If your question doesn't include code, are you sure it shouldn't? 
  • If your program throws an exception, have you included the exception, with both the message and the stack trace?
  • If your program throws an exception or performs 'incorrectly', have you included any trace or log messages that might be useful?
  • If your program produces different results to what you expected, have you stated what you expected, why you expected it, and the actual results?
  • If your question is related to anything locale-specific (languages, time zones) have you stated the relevant information about your system (e.g. your current time zone)?
  • Have you checked that your question looks reasonable in terms of formatting? 
  • Have you checked the spelling and grammar to the best of your ability?
  • Have you read the whole question to yourself carefully, to make sure it makes sense and contains enough information for someone coming to it without any of the context that you already know?  
  • If you've included a technical term is it going to be clear to a reader what you meant by that term - e.g. if you asked "I want to display a notification" then does that mean just some/any visual indication or does it mean an Android notification?
  • Does your title describe the question you've asked?
  • Have you asked about just one thing? Answering one specific question is much easier than answering several different things at the same time.
And one more....
  • Have you tried squeezing a technical question into 140 characters on Twitter? If you have, please delete your tweet and try asking with more detail on StackOverflow or on a forum. 

Thanks to Jon Skeet for the base list at: http://msmvps.com/blogs/jon_skeet/archive/2012/11/24/stack-overflow-question-checklist.aspx - and for posts like http://msmvps.com/blogs/jon_skeet/archive/2010/08/29/writing-the-perfect-question.aspx too

Wednesday, September 25, 2013

N=39 - CrossLight on Xamarin.iOS/MonoTouch (aka Project Chimp)

This video is a follow on from http://slodge.blogspot.co.uk/2013/06/n30-crosslight-aka-project-chimp-n1.html where I showed how to use the MvvmCross binding layer in Android without using the higher layers (the navigation service, the plugin loader, the thread dispatcher, etc).


In this video I quickly do the same thing for Xamarin.iOS.


The process is pretty simple:


1. Add references to the CrossCore and Binding assemblies for MvvmCross (in the video I use nuget CrossCore package - https://www.nuget.org/packages/MvvmCross.HotTuna.CrossCore/)

2. Add a small setup class and call it from your appdelegate start code



3. Add you ViewModel - and INotifyPropertyChanged will do

4. Adjust your ViewController so that it can do data-binding to an instance of your ViewModel



5. Run :)


The code for today is at: https://github.com/slodge/NPlus1DaysOfMvvmCross/tree/master/N-39-CrossLight-Touch


The video is:




For a full index of N+1 videos, see http://mvvmcross.wordpress.com

N=38 - More maps and more zombies

Today, I tried to extend the N=37 Maps Xamarin.iOS sample into 4 new directions:

  1. A draggable annotation that updates it's location in the ViewModel
  2. An ObservableCollection of annotations.
  3. A mechanism to update the map center from the ViewModel
  4. A mechanism to update the ViewModel from map panning



The code for this is on: https://github.com/slodge/NPlus1DaysOfMvvmCross/tree/master/N-38-Maps


The video is:



Disclaimer: I only tested on iOS6 - and there were a few animation details there that needed a little smoothing... I've not tested them on iOS5 or iOS7 yet - expect more there too!


For a full index of N+1 videos, see http://mvvmcross.wordpress.com

Thursday, September 19, 2013

N=37 - Maps and Zombies part 1 - N+1 Days of MvvmCross

After a slightly longer than planned summer break, I'm finally returning to these recordings. Sorry about the elongated break, but I'm back now, and hoping to cover some more advanced topics :)


To start with, I thought I'd try some mapping. This is going to take a few videos to get completed.... just easing back into this process.


First up:

  • we create just a PCL and an iOS project
  • we add an MKMapView view
  • we databind some annotations to the ViewModel

The video for this is:


I'm afraid I did get interrupted during the recording, so you might hear someone asking if I wanted a beer - but I didn't - I don't drink and screencast ;)


The code for this is in: https://github.com/slodge/NPlus1DaysOfMvvmCross/tree/master/N-37-Maps


The index of N+1's is on http://mvvmcross.wordpress.com, but we also have a copy on the wiki - https://github.com/slodge/MvvmCross/wiki

Sunday, September 15, 2013

Awesome issue hunting and fixing from @brianchance

Over the last coupe of months we've had some awesome fixes sent to us from Githubber Brian Chance

These have included a big project tidy up to help us remove "System.ServiceModel" references and an important fix for our MonoTouch.Dialog port - which has helped us work out some long-standing issues with StyledStringElement.

Small fixes and pulls like these are awesome - keeping on top of issues like this is really core to MvvmCross - it's awesomely important.

Brian - a huge thanks to you ... and a badge of awesomeness - thank you!


PullToAwesome - an awesome MvxUIRefreshControl from James Montemagno

Implementing Pull-To-Refresh in iOS is lovely and simple... and now with this gist from James Montemagno (@jamesmontemagno) databinding that Pull-To-Refresh is really simple too.

Read more about this on:

- James' blog - http://motzcod.es/post/59125989518/mvxuirefreshcontrol-for-mvvmcross
- the Gist - https://gist.github.com/jamesmontemagno/6323125

Simple, Beautiful... and Awesome... it earns James his first badge of awesomeness - thanks for the awesomeness :)




Shinobi Charting with MvvmCross applied - awesome from SammyD

SammyD - also known as @iwantmyrealname - recently posted an awesome blog post and an open source repo on how to combine the very sleek and sexy Shinobi charts with Mvvm on Xamarin.iOS.

You can read more about this on http://www.shinobicontrols.com/blog/posts/2013/09/04/mvvm-charting-with-shinobicharts-and-mvvmcross



It's an awesome read - with an awesome open source repo behind it. Thanks @iwantmyrealname - very well deserving of a badge of awesomeness - thanks!

 

An awesome plugin to allow integration with Azure Access Control - from the @CheeseBaron

Microsoft's Azure ACS provides big cloud identity services.

It's got a wide range of uses - it's useful for new apps wanting to integrate with Google, Facebook, and Live authentication and for companies wanting to authenticate with established Active Directory servers.

The great news is that @Cheesebaron has provided a MvvmCross plugin to allow your apps to integrate with it - he's built it for Xamarin.iOS, Xamarin.Droid and WindowsPhone - and he's made it available open source at https://github.com/Cheesebaron/Cheesebaron.MvxPlugins/tree/master/AzureAccessControl

This is, of course, AWESOME .... and it bags @Cheesebaron his 4th badge of awesomeness - thanks Tomasz for all the awesomesauce :)


Sunday, September 08, 2013

3.0.12 pushed to MvvmCross-Binaries (not quite on Nuget yet)

I've just pushed build 3.0.12 to https://github.com/slodge/MvvmCross-Binaries/

It will appear on Nuget when I can work out what's broken on https://nuget.codeplex.com/discussions/456158 (apparently this is a nuget.org problem - and should be fixed tomorrow)

This build is pretty similar to the 3.0.11-beta build that I know many of you have been using for the last week.

This is the first build to be linked against the new 'async' and 'PCL' Mono 3 based releases from Xamarin.

There seems to be some issues with the latest releases from Xamarin - especially concerning https://bugzilla.xamarin.com/show_bug.cgi?id=14520 - so other patches may follow soon.


Possible breaking changes in 3.0.12 are:
  • Updates for Xamarin PCL support - iOS apps must now use the Mono 'System.Windows' PCL shim and not the ones previously supplied by MvvmCross.

    This Mono 'System.Windows' assembly should be present in the 'Add Reference...|Assemblies|Framework' list after you have connected Visual Studio to your Mac and have synced the SDK. However, I have personally had some issues with this (sometimes it has asked me to sync every few minutes...)

    Using this Mono Shim may report in some 'warnings' about different strong-named System.Windows assemblies during linking from the MonoTouch compiler - but these warnings (so far) seem to result only in slightly slower link times.
  • Updates for Xamarin PCL support - all PCL projects should currently build as Profile 104 on both PC and Mac (previously we had to specify 'Profile1' for Mac support)
  • The default constructors in the MvvmCross Dialog port of StyledStringElement now match the main MonoTouch.Dialog implementations - this clears #402 and#328 but may effect any users currently relying on the current implementation (to workaround any problems, use the constructor which allows cell type to be specified)
 
Other noteworthy changes for MvvmCross in 3.0.12 are:

  • small changes to unify `Adapter` configuration across all Android list-based views (all can now be passed null in the constructor) - #390
  • small fix in Email plugin for empty cc field - #385
  • a new `IMvxViewModelByNameRegistry` interface which allows plugins to register ViewModels if they want to - #405
  • StyledStringElement Visible implemented - #403


As an aside... some of you may be wondering what happened to 3.0.11? It kind of got confused in the build process... so I decided to clean and build 3.0.12 instead - sorry!

Thursday, July 25, 2013

Xamarin 4.8 Stable... not sure....

If any MvvmCross get asked today if they want to upgrade to 4.8, then my advice is "wait"


Unfortunately, if you do a fresh install on a Mac, then try the sequence "File->New->Portable Class Library" then that library will not build. The build gives lots of errors about "predefined type XXX is not defined or imported"


I think this will probably be easy to fix - it will probably be down to the PCL reference assemblies - but until some brave leading-edge adventurers have worked this out, then it might be wise to "wait" and not to install the 4.8.0 version


 Hopefully soon this will get resolved - then we can async/await :) :) :)


Wednesday, July 24, 2013

Map Annotation DataBinding

From my answer to http://stackoverflow.com/questions/17816684/using-mvvmcross-how-can-i-bind-a-list-of-annotations-to-a-mapview/17834923#17834923





Subscribing to changing collections is one of the corner-stones of Data-Binding and relies on a little knowledge of the INotifyCollectionChanged interface.

Within the MvvmCross source, there are a few example classes which show how to subscribe to collections and their change notifications - e.g. MvxViewGroupExtensions.cs in Droid and MvxTableViewSource.cs in Touch

The core to the technique is to create an Adapter or Source object which listens for changes either in the whole list or to parts of the list and which takes action accordingly.

The same type of approach applies for maps with multiple - but markers - although we don't yet have any helper classes for this.



Without actually having a Mac or iOS device to hand, here are roughly the steps I'd take to create a wrapper...

Assuming I had a Model object like:

public class House
{
    public double Lat { get; set; }
    public double Lng { get; set; }
    public string Name { get; set; }
}

Inside a ViewModel like:

public class FirstViewModel : MvxViewModel
{
    public ObservableCollection HouseList { get; set; }
}

With this done, then in the View we can create an annotation class for each House - e.g. something like:

public class HouseAnnotation : MKAnnotation
{
    public HouseAnnotation(House house)
    {
        // Todo - the details of actually using the house here.
        // in theory you could also data-bind to the house too (e.g. if it's location were to move...)
    }

    public override CLLocationCoordinate2D Coordinate { get; set; }
}

We could then create a HouseAnnotationManager who's responsibility would be to manage the translation of changes in the HouseList being mapped to changes in the annotations being displayed on the map.

To do this, we would give the manager methods to:
  1. Create a single annotation:

    private MKAnnotation CreateAnnotation(House house)
    {
        return new HouseAnnotation(house);
    }
    
    
  2. Add an annotation to the map (and to a local lookup table)

    private void AddAnnotationFor(House house)
    {
        var annotation = CreateAnnotation(house);
        _annotations[house] = annotation;
        _mapView.AddAnnotation(annotation);
    }
    
    
  3. Remove an annotation from the map (and from a local lookup table)

    private void RemoveAnnotationFor(House house)
    {
        var annotation = _annotations[house];
        _mapView.RemoveAnnotation(annotation);
        _annotations.Remove(house);
    }
    
    
  4. Do the same actions for lists:

    private void AddAnnotations(IList newItems)
    {
        foreach (House house in newItems)
        {
            AddAnnotationFor(house);
        }
    }
    
    private void RemoveAnnotations(IList oldItems)
    {
        foreach (House house in oldItems)
        {
            RemoveAnnotationFor(house);
        }
    }
    
    
  5. Respond to INotifyCollection changes:

    private void OnItemsSourceCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        switch (e.Action)
        {
            case NotifyCollectionChangedAction.Add:
                AddAnnotations(e.NewItems);
                break;
            case NotifyCollectionChangedAction.Remove:
                RemoveAnnotations(e.OldItems);
                break;
            case NotifyCollectionChangedAction.Replace:
                RemoveAnnotations(e.OldItems);
                AddAnnotations(e.NewItems);
                break;
            case NotifyCollectionChangedAction.Move:
                // not interested in this
                break;
            case NotifyCollectionChangedAction.Reset:
                ReloadAllAnnotations();
                break;
            default:
                throw new ArgumentOutOfRangeException();
        }
    }
    
    
  6. Respond to whole list changes:

    // MvxSetToNullAfterBinding isn't strictly needed any more 
    // - but it's nice to have for when binding is torn down
    [MvxSetToNullAfterBinding]
    public virtual IEnumerable ItemsSource
    {
        get { return _itemsSource; }
        set { SetItemsSource(value); }
    }
    
    protected virtual void SetItemsSource(IEnumerable value)
    {
        if (_itemsSource == value)
            return;
    
        if (_subscription != null)
        {
            _subscription.Dispose();
            _subscription = null;
        }
        _itemsSource = value;
        if (_itemsSource != null && !(_itemsSource is IList))
            MvxBindingTrace.Trace(MvxTraceLevel.Warning,
                                  "Binding to IEnumerable rather than IList - this can be inefficient, especially for large lists");
    
        ReloadAllAnnotations();
    
        var newObservable = _itemsSource as INotifyCollectionChanged;
        if (newObservable != null)
        {
            _subscription = newObservable.WeakSubscribe(OnItemsSourceCollectionChanged);
        }
    }
    
With this all written, then your ViewModel can have a private _manager field and can create and data-bind it as:

        _manager = new HouseAnnotationManager(myMapView);

        var set = this.CreateBindingSet();
        set.Bind(_manager).To(vm => vm.HouseList);
        set.Apply();


Overall, this might look something like: https://gist.github.com/slodge/6070386

Disclaimer: this code hasn't been compiled let alone run, but the approach is basically correct (I think)



The same basic approach should also work in Android - although in Android you'll also have to fight a battle against the setup - Ant, Google Play v2 and all that jazz.



If you wanted to do further map manipulations - e.g. changing the map center and zoom when a house is added, then this can obviously be done from within overrides of methods such as AddAnnotation within your manager.





The full gist is:

Tuesday, July 23, 2013

MvvmCross 3.0.10 binaries released to nuget, GitHub and skydrive

3.0.10 is a fairly small release - just a few small patches to 3.0.9 from 10 days ago.


I really hope this might be the last release before we switch to Xamarin official PCLs - I might even label those releases 3.1.x


The list of 3.0.10 changes is:
  • minor nuspec file fix - ResourceLoader now availble for WPF
  • a DataContext is now non-virtual everywhere - this may be a breaking change for anyone who was overriding it in their tableviewcells, in an MvxView or in a MvxFrameControl. The recommended solution for the breaking change is to use Binding for all DataContext changes.
  • UIDatePicker now has a "Time" binding - can be used to bind to  a TimeSpan - see ApiExamples project for use
  • In order to support textbox to decimal number binding (see #350), we've changed the binding layer so that:
    1. source (viewModel) bindings do not update the ViewModel if the new value Equals the existing value
    2. for the specific cases of double, float and decimal source values the target bindings do a text-numeric equivalent comparison before setting the UI
  • Fixed "whole object" binding which was broken in 3.0.9 by the Tibet binding changes - the workaround for this in 3.0.9 was to use a period "." for the whole object path (see http://stackoverflow.com/questions/17729282/error-when-making-bind-observablecollectionstring-for-a-mvxlistview/17729996#17729996)
  • Minor changes to design time helpers for Visibility and Color
  • Fixed the MvxPickerViewModel to allow its choice list to be updated dynamically (#354)
  • Groups of Bindings can now be removed from a BindingContext using a ClearKey. To specify the ClearKey for FluentBinding, use the `.WithClearBindingKey(key)` extension (linked to http://stackoverflow.com/questions/17680846/mvvmcross-clearbindings-how-to-use-in-touch and #358)

I've run this build against our unit tests (more still needed), against a significant chunk of the MvvmCross-Tutorials samples, and against some 'new project' tests. All seemed good :) Hopefully this release hasn't broken too much .... as I'm off on holiday real soon :)

Monday, July 22, 2013

Playing with Constraints - FluentConstraints and FluentLayouts for Xamarin.iOS

Update: code now fully shared at https://github.com/slodge/Cirrious.FluentLayout


If you've watched any of the N+1 series - http://mvvmcross.wordpress.com/ - then you'll no doubt have seen me writing a lot of repetitive, error-prone layout code like:


       var textView = new UITextField(new RectangleF(10, 100, 300, 30));
       Add(textView);
       textView.InputView = picker;
       var label = new UILabel(new RectangleF(10, 130, 300, 30));
       Add(label);


All of this repetitive, error-prone layout code was... of course... unnecessary.  The problem was that I am a dinosaur and sometimes it takes me time to learn what I should be doing...


iOS6 is now almost a year old - and part of iOS6 was a new layout system called constraints. The basic idea behind these constraints is that it allows you to specify relationships between the layouts of UIView objects and their attribute values- so that you can, for example, ask one view to set its Top equal to the Bottom of another view. When you do this, then iOS/UIKit will then try to work out the layout for you at runtime.


I've been playing with these today and they are fabulous - especially when coupled with the power of C# - expect to see more of them in my demos soon!


One gist of code that really makes this lovely is Frank's Easy Layout DSL - see http://praeclarum.org/post/45690317491/easy-layout-a-dsl-for-nslayoutconstraint



This expression based library let's you use simple C# statements to define your layout - it's best summarised by code - see his picture which shows how to layout a button and a text box:





For my experiments I decided to see if I could create a Fluent-style API for the same type of effect. I've nothing against the 'Easy Layout DSL' - I just wanted to learn the constraints for myself, plus I wanted to see if using a Fluent approach gave me more composability and reusability.


What I wanted to do was to see if I could define Frank's 'text and button' layout using Fluent code like:


            View.AddConstraints(
                    button.AtTopOf(View).Plus(vPadding),
                    button.AtRightOf(View).Minus(hPadding),
                    button.Width().EqualTo(ButtonWidth),
 
                    text.AtLeftOf(View, hPadding),
                    text.ToLeftOf(button, hPadding),
                    text.WithSameTop(button)
                );


It turned out that it took a bit longer than I had hoped - there were a few gotchas along the way, mainly to do with "TranslateAutoresizingMaskIntoConstraints" - but within a couple of hours I had this working :)


And once I had that working, I then started to play....


What would a form layout look like?

View.AddConstraints(
 
    fNameLabel.AtTopOf(View, vMargin),
    fNameLabel.AtLeftOf(View, hMargin),
    fNameLabel.ToLeftOf(sNameLabel, hMargin),
 
    sNameLabel.WithSameTop(fNameLabel),
    sNameLabel.AtRightOf(View, hMargin),
    sNameLabel.WithSameWidth(fNameLabel),
 
    fNameField.WithSameWidth(fNameLabel),
    fNameField.WithSameLeft(fNameLabel),
    fNameField.Below(fNameLabel, vMargin),
 
    sNameField.WithSameLeft(sNameLabel),
    sNameField.WithSameWidth(sNameLabel),
    sNameField.WithSameTop(fNameField),
 
    numberLabel.WithSameLeft(fNameLabel),
    numberLabel.ToLeftOf(streetLabel, hMargin),
    numberLabel.Below(fNameField, vMargin),
    numberLabel.WithRelativeWidth(streetLabel, 0.3f),
 
    streetLabel.WithSameTop(numberLabel),
    streetLabel.AtRightOf(View, hMargin),
 
    numberField.WithSameLeft(numberLabel),
    numberField.WithSameWidth(numberLabel),
    numberField.Below(numberLabel, vMargin),
 
    streetField.WithSameLeft(streetLabel),
    streetField.WithSameWidth(streetLabel),
    streetField.WithSameTop(numberField),
 
    townLabel.WithSameLeft(fNameLabel),
    townLabel.WithSameRight(streetLabel),
    townLabel.Below(numberField, vMargin),
 
    townField.WithSameLeft(townLabel),
    townField.WithSameWidth(townLabel),
    townField.Below(townLabel, vMargin),
 
    zipLabel.WithSameLeft(fNameLabel),
    zipLabel.WithSameWidth(townLabel),
    zipLabel.Below(townField, vMargin),
 
    zipField.WithSameLeft(townLabel),
    zipField.WithSameWidth(zipLabel),
    zipField.Below(zipLabel, vMargin),
 
    debug.WithSameLeft(townLabel),
    debug.WithSameWidth(zipLabel),
    debug.AtBottomOf(View, vMargin)
 
); 
 
... although I think there are some opportunities to shorten that code and perhaps also to use some code-based hints too!


Could I create a generic vertical scrolling StackPanel/LinearLayout?


 public static IEnumerable<FluentLayout> 
       VerticalStackPanelConstraints(
          this UIView parentView, 
          Margins margins,
          params UIView[] views)
 {
     margins = margins ?? new Margins();
 
     UIView previous = null;
     foreach (var view in views)
     {
        yield return view.Left()
                         .EqualTo()
                         .LeftOf(parentView)
                         .Plus(margins.Left);
        yield return view.Width()
                         .EqualTo()
                         .WidthOf(parentView)
                         .Minus(margins.Right + margins.Left);
        if (previous != null)
           yield return view.Top()
                            .EqualTo()
                            .BottomOf(previous)
                            .Plus(margins.Top);
        else
           yield return view.Top()
                            .EqualTo()
                            .TopOf(parentView)
                            .Plus(margins.Top);
        previous = view;
     }
     if (parentView is UIScrollView)
        yield return previous.Bottom()
                             .EqualTo()
                             .BottomOf(parentView)
                             .Minus(margins.Bottom);
 }


Adaptive!

One key thing to note about these constraint-based UIs is that they are adaptive - e.g. when you rotate the phone then the layout adapts:

 




The code

The code I created is currently sitting in https://github.com/slodge/MvvmCross-Tutorials/tree/master/QuickLayout/Cirrious.FluentLayout - along with a test MvvmCross project (one level up).


It may later move into an MvvmCross plugin - or into core MvvmCross - but for now it's just sitting there in Tutorials. License is Ms-PL as per normal.


A video demo - laying out a tipcalc view





More?

With all this said and done, whether or not you prefer declarative or Imperative UI code is very much a matter of taste... but one question that I'm wondering at the moment is whether I could use the same UI code to create layouts in different environments - whether the same `AtTopOf`, `ToLeftOf` type calls could be used to generate UIKit, Xaml or Axml... but that question will have to wait for another day....