Sunday, December 29, 2013

Windows Store app development - important things to remember

1. Pages are by default destroyed when navigating from them. This is in contrast to Windows Phone where pages are cached.
2. When your app moves out of the foreground, Windows waits for a few seconds to allow quick switching back to the app, then tries to suspend the app.
This is very nicely described here:
If your app doesn’t return from its suspending event handler within 5 seconds of receiving the suspending event, Windows will terminate it. It’s important not to do any heavy operations in your suspending event handler. Save your app data and return quickly.
3. When running app with debugger, the application is not suspended by the OS when it’s moving out of foreground. You need to use Suspend \ Resume menu in Visual Studio
More info:
4. MVVMCross doesn’t play nicely with the generated SuspensionManager
In App.xaml.cs, I removed SuspensionManager:
private void OnSuspending(object sender, SuspendingEventArgs e)
           var deferral = e.SuspendingOperation.GetDeferral();
            //await SuspensionManager.SaveAsync();

5. Windows App Certification Kit fails on Suspend
Following error can be thrown while no real suspend problem is present in the code:

Performance suspendError Found: The performance suspend test collected the following results:
Application Error: Application Suspend was not detected for application App. This could be because your application failed to suspend correctly. Please consider re-running the test avoid interacting with the application while tests are running. 
Make sure you have Visual Studio running under admin privileges.
More info:

6. Use Simulator to create screenshots for certification and check app in different resolutions.

7. How to create package and send it to customer and let him upload to his Windows Store account
The package needs to be created using the certificate generated with the customer’s Windows Store account.
For this, customer needs to first create a dummy app on his machine using Visual Studio. Suppose the customer reserves the ‘My App’ app name in the Windows Store:
1. Make a Windows Store app in Visual Studio (Blank App is fine), called MyApp
2 Once created, right click on the project and from context menu, choose Store \ Create App Packages ...
3. Choose Yes, click Next and sign in with the Windows Store account
4. In the list with reserved names, select select "My App" name
5. Click Create
6. Close dialog 'Package Creation Completed'
The customer needs to archive and send the whole project folder.

On my machine, in Visual Studio, double click on ‘Package.appxmanifest’ and in ‘Packaging’ tab click on Choose Certificate button and select the .pfx sent by the customer.
Make sure the ‘Package name’ and ‘Publisher display name’ corresponds to those from the app project generated by the customer.

Wednesday, December 11, 2013

Taking a screenshot on different mobile platforms

Button combination Screenshot location Link to official support
iOS Menu button + Power \ Lock Photos app \ depending on device: "Saved Photos" or "Camera Roll
Android Power \ Lock + Volume Down Gallery
Windows Phone Start (Windows flag) + Power \ Lock Photos hub \ Screenshots album


Goto 'C:\Users\[User]\AppData\Local\Android\android-sdk\tools
open ddms.bat or monitor.bat
Select the device.
In DDMS: Use Device menu\Screen Capture
in Monitor: Click on the photo camera icon from the toolbar.

Wednesday, November 13, 2013

ActionBarSherlock + Xamarin + MVVMCross


Short history of ActionBar in Android and Xamarin

1. ActionBar was first added in Android 3.0 (API Level 11).

2. ActionBarSherlock is a third-party library created by Jake Wharton, which brought ActionBar support for Android 2.x: “The library will automatically use the native action bar when appropriate or will automatically wrap a custom implementation around your layouts. This allows you to easily develop an application with an action bar for every version of Android from 2.x and up.”

ActionBarSherlock it’s not just about ActionBar support on Android 2.x, it also has some nice features not available in the Android’s ActionBar implementation.

3. In July 2013, Android Support Library revision 18 introduced a new v7 appcompat library which has ActionBar support for Android 2.1+.

4. Xamarin created a free component for their store as a binding for the ActionBarSherlock, called ‘ActionBarSherlock for Xamarin’.

5. Xamarin created a free component for the Android support Library v7 (rev 18)

I haven’t yet tried how the ActionBar works using the this support library.


Using ActionBar in Xamarin application with ActionBarSherlock Xamarin component

The steps are:

1. Create an Android application and add MvvmCross by NuGet. (MvvmCross creates and adds a FirstView activity to the project).

2. Add ActionBarSherlock for Xamarin component from Xamarin Components store

3. Make sure the Android project has ‘Compile using Android version’ and ‘Target Android version’ set to the latest Android version.

4. Add reference to Mono.Android.Support.v4

5. Add a MvvmCross implementation for SherlockFragmentActivity (MvxSherlockFragmentActivity).

   I create a folder ‘MvxSherlockActionBar’ in the Droid project and add to it these two files: MvxEventSourceSherlockFragmentActivity.cs MvxSherlockFragmentActivity.cs These add support for MvvmCross to SherlockActionBar.

6. Change the FirstView’s class parent from MvxActivity to MvxSherlockFragmentActivity and set the ActionBar’s theme

[Activity(Label = "View for FirstViewModel"] 
public class FirstView : MvxSherlockFragmentActivity
protected override void OnCreate(Bundle bundle)

You should use SherlockFragmentActivity::SupportActionBar property to use the ActionBar.

A very basic walkthrough to the Xamarin component: 
Xamarin also created a sample application using Xamarin ActionBarSherlock component and made its source code available It contains different examples of usage.

Sunday, September 22, 2013

Xamarin MVVMCross PCL Visual Studio issues


Introduction to MVVMCross setup

MVVMCross framework is suitable for Xamarin applications with the following structure:

- a platform-independent PCL Core (MyApp.Core) project containing your app logic like view models, services, models
- several platform specific applications projects (MyApp.Droid, MyApp.iOS, MyApp.Store)

Note that MVVMCross works with PCL targeting frameworks
’NET Framework 4.5’,
‘Silverlight 4 and higher’.
‘Windows Phone 7.5 and higher’,
‘.NET for Windows Store apps’

You don’t need to select all these, just the platforms you target but MVVMCross doesn’t work  with ‘.NET Framework 4.0’ or ‘Windows Phone 7’.

The problem

Because of the framework target profiles, Visual Studio by default won’t let you add a PCL project as reference to your Xamarin Android project in Visual Studio.
In the case of MVVMCross, you cannot add the Core PCL project to the application project.


The solutions I’ve seen:

#1. (Most popular) Create profiles for ‘Mono for Android’ and ‘MonoTouch’ in
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETPortable\v4.0\Profile\Profile104\SupportedFrameworks
This makes the two profiles available when creating the PCL and makes Visual Studio recognizing the PCL project compatible with the Xamarin app projects.

#2. Manually edit the Xamarin application projects to add reference to the PCL project. It will compile fine but with a warning generated about the possible framework incompatibility

#3.  The solution I am using: create PCL project and app project in Visual Studio, then use Xamarin Studio just to add the PCL project as reference to the application project. Then switch back and continue work in Visual Studio.

      (If you’ve been using the two profiles from method #1, remove them in advance. For this solution, you shouldn’t see them when creating the PCL, because they create an issue selecting the ‘WP7.5 and higher’ without these two profiles selected, see more below)

I also saw another way which involves using a WPF class library (you read it right).


Problems with having the ‘Mono for Android’ and ‘MonoTouch’ custom profiles

When using #1 with custom profiles, if you try to use NuGet in Visual Studio, Visual Studio will complain about the larger majority of the available toolkits in NuGet:


The reason is because most toolkits do not know about the ‘Mono for Android’ and ‘MonoTouch’ framework targets.
As a workaround, even if the operation failed, you can still manually add as references the toolkit assemblies downloaded by NuGet in the ‘packages’ folder. But that makes NuGet a bit less useful.

Another side issue I've noticed is with having the two profiles (‘Mono for Android’ and ‘MonoTouch’):
When you create a PCL project you cannot select 'Windows Phone 7.5 and higher' without also having the two profiles selected.
Without these two profiles selected, Visual Studio will automatically select ‘Windows Phone 7 and higher’ profile.

(Off topic about Json.NET: Json.NET happens to have a Xamarin component available in the but Xamarin currently does not have the Component feature for PCLs).

I am eager to hear other opinions, experiences, solutions, thoughts.

Wednesday, September 18, 2013

A first implementation of alert dialog support in Xamarin + MVVMCross

Update: You can use this MvvmCross plugin:
              At this moment however, the plugin doesn't have an implementation for Windows Phone and Windows Store, it's only for Android and iOS.

The implementation steps:
#1. In the Core PCL project, have the dialog interface declared in IDialogService.cs.
namespace MyApp.Core.Services
    public interface IDialogService
        Task<bool?> ShowAsync(string message, string title, string OKButtonContent, string CancelButtonContent);

#2. In the platform specific project, implement the dialog support. Example for Android:

namespace MyApp.Droid.Services
    public class DialogService : IDialogService
        public Task<bool?> ShowAsync(string message, string title, string OKButtonContent, string CancelButtonContent)
            var tcs = new TaskCompletionSource<bool?>();

            var mvxTopActivity = Mvx.Resolve<IMvxAndroidCurrentTopActivity>();
            AlertDialog.Builder builder = new AlertDialog.Builder(mvxTopActivity.Activity);
                   .SetPositiveButton(OKButtonContent, (s, args) =>
                   .SetNegativeButton(CancelButtonContent, (s, args) =>

            return tcs.Task;

Still in the platform specific project, register the service:

namespace MyApp.Droid
    public class Setup : MvxAndroidSetup
        public Setup(Context applicationContext) : base(applicationContext)

        protected override void InitializeLastChance()
            Mvx.RegisterSingleton<IDialogService>(new DialogService());

#4. In the view models, here is how I can call the display of the dialog:

void async DeleteUser()
    var result = await Mvx.Resolve<IDialogService>().Show("Are you sure you want to delete selected user?", "Confirmation", "OK", "Cancel");
    if(result == true)
        // delete user...

This is a first implementation of showing dialogs. There’s a lot of possible parameterization / customization, but it needs to take into account the capabilities and behavior of all platforms.
In tests, the IDialogService implementation obviously does not call showing a dialog, it does nothing.

One interesting discussion I had with Greg Shackles is about using a different approach than what I showed here: have the view full responsibility of displaying the dialog and communicate with view model using commands \ methods, etc. I understand the idea but I don't have a very clear way of doing this so until I see all the issues I think I will use this solution.

Localization in Xamarin + MVVMCross

Here is how I implement localization in my Xamarin MVVMCross (what a great pair!) app:
#1. In the Core PCL project, create resource (project properties \ Resources) and use editor to enter all localizable strings in the app (or, you might use localization tools which produce the .resx file).
     Make sure to select Public visibility for the members of the generated Resources class.image
     For the resource name, I usually use the actual string + 'Text':
         'Username' –> UsernameText. 
         'Change password' –> ChangePasswordText.
     For long strings, I try to give it a short distinctive name  + usage + 'Text':
         'NewAppVersionAvailableMessageText'  -> 'A new version of the application is currently available. Would you like to download it?'
         'DeleteUserConfirmationText'  ->  'Are you sure you want to delete selected user?'
#2. I have a BaseViewModel class derived from MvxViewModel serving as a base for all my view models. It uses an indexer to get the translated string value based on an index resource value  
public class ViewModelBase : MvxViewModel
    public string this[string index]
            return Resources.ResourceManager.GetString(index);

(for Android, but the idea is similar to other platforms too) In the layout, I am using MVVMCross binding to bind the controls to the view model’s indexer and pass the resource name:

<TextView local:MvxBind="Text [UsernameText]"
          android:layout_height="wrap_content" />

At runtime, because of the MVVMCross binding between the TextView’s Text property and view model indexer, the Text property will call the view model’s indexer using the ‘UsernameText’ as index.
This in turn calls ResourceManager.GetString which returns the localized string.

This setup works great. I haven’t yet tried it on all the platforms but it makes sharing a single set of localized strings. Also, the resource strings can be referenced by the statically typed properties of the Resources class.

If the application needs to switch the language at runtime, it should be enough to tell the view model to notify its bound controls to refresh their values. I haven’t tried it yet, but viewModel.RaisePropertyChanged(string.Empty) should work.

There are different approaches to localization, here are few links:
N=21 - Internationalisation - i18n - N+1 Days of MvvmCros (using the MVMCross plugin) 
Using resx-files for localization in MvvmCross (mentioned in the video) (interesting ideas)

I am happy to hear your thoughts on this approach.

Thursday, September 12, 2013

WebBrowser control compatibility

in WPF\WinForms app, the WebBrowser control runs in a compatibility mode
this means it will run in an earlier version than then the current version of the IE on the machine
to disable it, you need to setup a registry key

\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION


identify iPod model

Look on the back of the iPod and read the number "Model No. AXXXX"
Mine says A1367.
Then google the model number.

Thursday, September 05, 2013

Copy Paste stopped working

If Copy / Paste stops working it might because of a running Virtual PC / Remote desktop.
Close the Virtual PC / Remote desktop and it will start working again.

More info on this:

Disable Windows Narrator

I found myself hitting Space + Win keys accidentally many times.
This registry setting will disable Narrator.


How it works:
Windows has a feature to launch a debugger when an app is executed.
This can be done using the following String registry value:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\[AppName]\Debugger
What it's doing is it tells OS to launch debugger when the app is executed.
Usually Debugger value is the path of a debugger app like vsjitdebugger.exe.
In this case we put "%1" and it will simply fail.

More info on setting up a debugger launch for an app:

More info on different things which 'Image File Execution Options' can do:

This one goes into much low access details

Wednesday, September 04, 2013

Running multiple local sites in IIS


1. Create your site in IIS, e.g. Site1

2. Setup binding

IP Address:


3. edit C:\Windows\System32\Drivers\etc\hosts file

Repeat the same steps for other sites Site2

Note that you should choose your names carefully, you won’t be able to get to the sites on internet

Saturday, August 31, 2013

Run iPhone or iPad application in emulator


If you have an iOS app which you would like to send to a customer to see your progress you can do that easily, and without sending him the source code.

The customer needs to have a Mac and XCode installed with the same same version of the SDK you target in your app.

On the development machine:

1. Get simplaunch:

2. In Xcode, make sure compilation target is set to  “[ProjectName]\iPhone [x] Simulator”

     Compile your app (Project\Build or Command+B or RightWinKey+B)

3. Click on “Organizer” button (it’s in the right top of the XCode window)

4. Click the “Projects” tab and make sure your project is selected in the list from the left (it has the dot on the right of the name)

5. Click the arrow after the “Derived Data” path

6. Navigate to Build\Producs\Debug-iphonesimulator

7. Drag the [AppName].app on the “Simulator Bundler” icon on desktop

8. It will generate the bundled app is in the same folder with the source app

This is the app you can send to your customer.

On the customer machine, the customer needs to unarchive the file and run the app from inside (double-click it).


More info:

Friday, August 30, 2013

Android native development startup


#1. Download JDK 6
Java 7 is not officially supported by the Android SDK at this time. Please use the latest version of the Java 6 JDK.

For a 64 bit dev, note that the following trio is required:
  • 64-bit OS
  • 64-bit JDK
  • 64-bit Eclipse

#2.  Add the path to JDK (for example 'C:\Program Files\Java\jdk1.6.0_45\bin') to PATH environment variable.

#3. Download ‘Eclipse Standard’ from
It is not an installer but a .zip archive. Extract its content to a folder like D:\Eclipse

#4 Run eclipse.exe.
It will ask you to select a Workspace. By default it gives a location in C:\Users
Better choose something like D:\Eclipse\Workspaces\MyWorkspace

#5. Install ADT plugin for Eclipse (Android Development Tools)

#6. You might need to install platforms and packages
Emulator runs best using Intel image, so make sure it is selected for all platforms images you install (if available)


Keyboard shortcuts:

Copy and paste:

Thursday, August 29, 2013

PCL libraries overview

This is very good article on the PCL architecture and different ways to implement a PCL library:
Important quote:
“The code to use your library should also be simple.  That means the project referencing your library shouldn’t have to manage hooking up the platform specific part of your library with the portable part.  One way to do this is to have an initialize method in your platform specific part of your library which passes references to platform specific implementations down to the portable part of your library.  Here’s an example of what this could look like"
“For consumers of your library, it will be easier if the portable part of your library connects to the platform specific part with no action required on their part.  You can do this by having the portable part load the platform-specific part by calling Assembly.Load(), and using reflection to get the functionality it needs.  For an example of how to do this, see  the Portable Class Libraries Contrib project.  The code which handles this functionality is in the Source\Portable.Runtime\Adaptation folder.  The Reactive Extensions (Rx) also use this method to connect their portable System.Reactive.Core assembly with the platform-specific System.Reactive.PlatformServices assembly. “
A simple example of PCL is PCL Storage:
The project consists of a PCL project (platform independent) called PCLStorage.Abstractions and specific platform projects called PCLStorage.[PlatformName]
PCLStorage.Abstractions is referenced by all platform implementation projects (the PCLStorage.[PlatformName] projects).
It contains definitions of interfaces which platform implementations implement.
namespace PCLStorage
    public static class FileSystem
        public static IFileSystem Current { get; }

    public interface IFileSystem
        IFolder LocalStorage { get; }
        IFolder RoamingStorage { get; }

        Task<IFile> GetFileFromPathAsync(string path);
        Task<IFolder> GetFolderFromPathAsync(string path);

    public enum CreationCollisionOption
        GenerateUniqueName = 0,
        ReplaceExisting = 1,
        FailIfExists = 2,
        OpenIfExists = 3,

    public interface IFolder
        string Name { get; }
        string Path { get; }

        Task<IFile> CreateFileAsync(string desiredName, CreationCollisionOption option);
        Task<IFile> GetFileAsync(string name);
        Task<IList<IFile>> GetFilesAsync();

        Task<IFolder> CreateFolderAsync(string desiredName,
            CreationCollisionOption option);
        Task<IFolder> GetFolderAsync(string name);
        Task<IList<IFolder>> GetFoldersAsync();

        Task DeleteAsync();

    public enum FileAccess

    public interface IFile
        string Name { get; }
        string Path { get; }

        Task<Stream> OpenAsync(FileAccess fileAccess);
        Task DeleteAsync();

    public static class PortablePath
        public static char DirectorySeparatorChar { get; }
        public static string Combine(params string[] paths);
    public static class FileExtensions
        public static async Task<string> ReadAllTextAsync(this IFile file)
        public static async Task WriteAllTextAsync(this IFile file, string contents);

So when developer installs PCLStorage from NuGet for a specific project on a specific platofrm, NuGet manager will add as reference to the project the PCLStorage.Abstractions.dll PCL and the PCLStorage.[PlatformName].dll implementation.

In code, here’s how PCLStorage library is used:

public async Task PCLStorageSample()
    IFolder rootFolder = FileSystem.Current.LocalStorage;
    IFolder folder = await rootFolder.CreateFolderAsync("MySubFolder",
    IFile file = await folder.CreateFileAsync("answer.txt",
    await file.WriteAllTextAsync("42");

FileSystem.Current is instantiating the platform specific IFileSystem.

This code resides in a file in PCLStorage.dll PCL which is linked to other PCLStorage.[PlatfortmName].dll projects

PCLStorage.dll is not used besides just for holding files to be linked (it is not used as reference by any projects)

Why use ‘AppName.Droid’ for Xamarin Android apps and not ‘AppName.Android’


It looks like the if you use “Android” you end up having to use `global::Android` a lot.

So even if “Android” might look better than “Droid”, use “Droid”

Monday, August 26, 2013

Xamarin iOS app setup intro (Visual Studio)

To make the Visual Studio build iOS apps, you need to install Xamarin Studio on the Mac and possibly update your XCode version. Follow the requirements and instructions from
After all setup is done, in Visual Studio create a iOS \ Universal app.
Make sure you have Solution Platforms combo-box available in the standard command bar, otherwise click on the overflow button and choose Add\Remove buttons, and choose Solution Platforms. This combo-box should show iPhone and iPhoneSimulator options.
To connect to the mac machine, I am using VNC viewer:
In Visual Studio, running the app you might get an error on the mac: “The simulated application quit.” and an option to switch SDK.
Here’s the things I did to make it work:
- make sure you have Application name (‘HelloWorld_App1’), Identifier (‘com.helloworldapp’), Version (1) and Deployment Target (6.1) set.
- if you get the error, right click and select to dock the simulator.  I was able to select ‘Reset settings’ from the menu just before the error dialog appeared. If not try to delete ~/Library/Application Support/iPhone Simulator directory on your Mac

Other info on the iOS setup:

Monday, June 17, 2013

Svc handling in IIS

I bump into this issue every-time I am running on a new machine.
When trying to access WCF services, they do not work. That's because IIS by default does not handle it.

In Windows Features (Control Panel\Turn Windows features on or off), you need to make sure you have WCF Activation installed.

Thursday, June 06, 2013

More dynamic Android Fragments with MVVM and MVVMCross


Scenario: I need to create and load fragments dynamically (by code).

Example: I have a hierarchical data with categories and items, a category can contain items and other categories, like in Windows Explorer:


When user clicks on a folder icon, if it’s a folder, it will show the same view with folder’s child folders and items. If it’s an icon, we want to show just a label with the name of the item (in real-life, this can be rendering a document).

In Android, we will need

  1. an activity class and layout (or even a parent fragment) as host for the views. it will create and show the fragments dynamically by code,
  2. a fragment class and layout for the folder view (with a GridView)
  3. a fragment class and layout for the item view (with a TextView)

With MVVMCross, we will also have:

  1. a view-model class for the activity/parent fragment host
  2. a view-model class for the folder view
  3. a view-model class for the item view

With MVVM, when user clicks on a folder icon, the view-model is responsible to handle the event (by a Command) and trigger navigation to another fragment view, depending on the icon. But remember that the view-model must NOT directly instantiate and show the views, this is platform specific UI code.

In MVVMCross, we call MvxViewModel.ShowViewModel method to‘show’ the view-model. By default, what happens is, the MVVMCross finds the associated activity class (based on a name convention) and shows it. But In our case, this won’t work, because the view-models refer to fragments.

The solution is to use MVVMCross features to control the view creation mechanism.

MVVMCross has a built-in MvxAndroidViewPresenter class used to create and show an activity based on the view-model:

	public class MvxAndroidViewPresenter : IMvxAndroidViewPresenter, IMvxViewPresenter
public virtual void Show (MvxViewModelRequest request)
IMvxAndroidViewModelRequestTranslator mvxAndroidViewModelRequestTranslator = Mvx.Resolve<IMvxAndroidViewModelRequestTranslator> ();
Intent intentFor = mvxAndroidViewModelRequestTranslator.GetIntentFor (request);
this.Activity.StartActivity (intentFor);

We can tell MVVMCross to use instead our own view presenter implementation which creates and shows fragments inside our activity or parent fragment.

	public class CustomPresenter : MvxAndroidViewPresenter, ICustomPresenter
// map between view-model and fragment host which creates and shows the view based on the view-model type
private Dictionary<Type, IFragmentHost> dictionary = new Dictionary<Type, IFragmentHost>();

public override void Show(MvxViewModelRequest request)
IFragmentHost host;
if (this.dictionary.TryGetValue(request.ViewModelType, out host))
if (host.Show(request))

public void Register(Type viewModelType, IFragmentHost host)
this.dictionary[viewModelType] = host;

The class is responsible for keeping a mapping between view-model types and the hosts which will instantiate and show the fragments.

We can now can register it for MVVMCross to use it, this being done in the Setup class in the Android app:

public class Setup : MvxAndroidSetup
protected override IMvxAndroidViewPresenter CreateViewPresenter()
var customPresenter = new CustomPresenter();
return customPresenter;

Note that the custom presenter once registered in MVVMCross, will be called for ANY view-model, whenever we call MvvmViewModel : ShowViewModel<T>();

ICustomPresenter and IFragmentHost are some simple interfaces we define in our code in order to nicely decouple the MVVMCross custom view presenter from the fragment host:

public interface ICustomPresenter
void Register(Type viewModelType, IFragmentHost host);

public interface IFragmentHost
bool Show(MvxViewModelRequest request);

It makes sense for the activity class to implement the IFragmentHost interface:

public class MainView: MvxFragmentActivity, IFragmentHost
public bool Show(Cirrious.MvvmCross.ViewModelsMvxViewModelRequest request)
// create view model
var loaderService = Mvx.Resolve<IMvxViewModelLoader> ();
var viewModel = loaderService.LoadViewModel (request, null /* saved state */);

// decide which fragment to create based on the view-model type
var fragmentView = ...

// load fragment into view
var ft = fragmentManager.BeginTransaction ();
ft.Replace (Resource.Id.fragmentHost, fragmentView);
ft.AddToBackStack (null);
ft.Commit ();

Further more, we can have the activity have its own dictionary to keep a mapping between view-models and fragments, such that we can instantiate fragments based on the view-model class:

		// map between view-model and fragment which creates and shows the fragment based on the view-model type
private Dictionary<Type, Type> vmTypeFragmentTypeDictionary = new Dictionary<Type, Type>();

public bool ShowFragment(FragmentManager fragmentManager, MvxViewModelRequest request, bool addToBackstack)
Type fragmentType;
if (vmTypeFragmentTypeDictionary.TryGetValue (request.ViewModelType, out fragmentType)) {

// create view model
var loaderService = Mvx.Resolve<IMvxViewModelLoader> ();
var viewModel = loaderService.LoadViewModel (request, null /* saved state */);

// create fragment view and bind it to the view model
var fragmentView = Activator.CreateInstance (fragmentType) as MvxFragment;
fragmentView.ViewModel = viewModel;

// load fragment into view
var ft = fragmentManager.BeginTransaction ();
ft.Replace (Resource.Id.fragmentHost, fragmentView);
if (addToBackstack) {
ft.AddToBackStack (null);
ft.Commit ();
return true;
else {
return false;

public void Register(Type viewModelType, Type fragmentType)
vmTypeFragmentTypeDictionary[viewModelType] = fragmentType;

To make it reusable, we can even create a base class with this code, called for example MvxActivityFragmentHost and have the activity derive from it:

public class MvxActivityFragmentHost : MvxFragment, IFragmentHost

public class MainView : MvxActivityFragmentHost

Monday, June 03, 2013

make Android device available in Windows and copy the .apk to the device

First, I wasn't able to see the Android device available in Xamarin nor in Windows's USB-connected devices tray icon.

The solution to this is to go to Device Manager \ Other Devices, right click on the Android device item and select 'Update driver' and select to browse for the driver on your disk. Select the location of the Goodle USB driver, which is in the location of where Android SDK is installed (extras\google\usb_driver folder). It's a location similar to this one:


After this, the Android device item should be not disappear from the Device Manager \Others and also appear in the USB menu in tray icon.

When connectig the USB to the device, a ‘USB Mass Storage’ screen appears with this option.
In order to copy .apk to device, you need to turn on the USB storage.  
You can then copy the released and signed .apk file on the sd_card folder.
Then using the AppInstaller app (search on marketplace) you can select and install the app.

Alternatively, the app can be downloaded and installed from a web location.

You can also install an application using the adb (Android Debug Bridge)

adb install -r [path_to_apk]

the adb is in the Android tools directory: %LocalAppData%\Android\android-sdk\platform-tools (shift + right click in explorer on folder to show 'open command prompt from here')

More info on ADB:

Issues when deploying a release version of a Xamarin app made with MVVMCross on a device (Android)

First, you can send to someone the .apk file representing the app and he can install it on the device.
There are few deployment options:
  • Via a Website – A Xamarin.Android application can be made available for download on a website, from which users may then install the application by clicking on a link.
  • By e-mail – It is possible for users to install a Xamarin.Android application from their e-mail. The application will be installed when the attachment is opened with an Android-powered device.
  • Through a Market – There are several application marketplaces that exist for distribution, such as Google Play or Amazon App Store for Android.
See more here,_testing,_and_metrics/publishing_an_application
I am trying to deploy the app on a device by sending the .apk file to someone to test it on his device.
First, I need to compile the app in Release mode and sign it. When compiling, Xamarin produces a signed version of the app.
In the \bin\Release folder, there is yourapp.apk and yourapp-Signed.apk files.

Second, I encountered different problems when running the app in Release mode on the device, there were a number of issues with MVVMCross.

The issues are related to the Xamarin linker. If you look to the build properties of the Xamarin app (In Xamarin Studio, that's project Options \ Build \ Android Build \ General tab), there are few linker options:

  1. Don't Link
  2. Link SDK Assemblies
  3. Link All Assemblies

Linking is described in Xamarin docs:
'Don't Link' option produces the largest app files, linker not being enabled. The app will definitely work without an issue.
Issues start appearing with the two options, becausue with these two options, the linker is enabled.
The issues appear at runtime, for example I was getting MvvMCross errors written in the application output, mentioning about bindings / events not working right.

When using the 'Don't link' linker option, the app size was 20 MB! When switching to 'Link SDK Assemblies', it was 7 MB!
The idea is to use 'Link SDK Assemblies' linker option and do the necessary to make linker do the right thing.

A solution is to force the linker include code from MVVMCross, using a dummy class.

class LinkerIncludePlease
private void IncludeVisibility(View widget)
widget.Visibility = widget.Visibility + 1;
private void IncludeClick(View widget)
widget.Click += (s,e) => {};
private void IncludeRelativeLayout(RelativeLayout relativeLayout)
relativeLayout.Click += (s, e) => { };
public void Include(INotifyCollectionChanged changed)
changed.CollectionChanged += (s,e) => { var test = string.Format("{0}{1}{2}{3}{4}", e.Action,e.NewItems, e.NewStartingIndex, e.OldItems, e.OldStartingIndex); } ;

 More info here: (including the info and links from comments)

Note there are other options, in the same Build tab: Use shared Mono runtime and Fast assembly deployment. These are not meant to be used on Release (if you have over the options, the explanation is pretty good and you should get a good idea of how they work).

MvvmCross Android app with dynamic fragments

It’s not much different than implementing the app with Java, except using the MvvmCross MvxXXXX classes.
Let’s do a simple exercise: have an activity loading a fragment by code behind.
Here’s the code we need:

1. a MvxFragmentActivity derived class.  It is the corresponding to Android’s FragmentActivity class

[Activity(Label = "View for FirstViewModel")]
public class FirstView : MvxFragmentActivity
protected override void OnCreate(Bundle bundle)
this.AddChildView ();
void AddChildView()
var childView = new ChildView () {
ViewModel = new ChildViewModel()
var fm = this.SupportFragmentManager;
var ft = fm.BeginTransaction ();
ft.Add (Resource.Id.childViewHost, childView, "childView");
ft.Commit ();

2. a corresponding Android layout for it: FirstView.axml
  it needs to have a host widget for the fragment, let’s say a FrameLayout called childViewHost
<LinearLayout xmlns:android=""
android:id="@+id/childViewHost" />
</FrameLayout >

  3. a MvxFragment derived class. Note the MvvmCross BindingInflate method which makes binding work in the fragment
public class ChildView : MvxFragment
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
var ignored = base.OnCreateView(inflater, container, savedInstanceState);
return this.BindingInflate(Resource.Layout.ChildView, null);
4. a corresponding Android layout  for it: ChildView.axml. Let’s have a textbox bound to the ViewModel’s property
<LinearLayout xmlns:android=""

local:MvxBind="Text Hello"
android:id="@+id/textView2" />

Friday, May 24, 2013

ActionBarSherlock in Xamarin Android targeting Android 2.1

ActionBarSherlock is a library which is an extension of the ActionBar in Android. ActionBar appeared in Android 4.

Besides being an extension, this library works for version previous to Android 4, starting from Android 2.1


First, we need to build the ActionBarSherlock from scratch using Eclipse. (I had also to install ‘Android SDK Tools’ using the Android SDK Manger).

Second, we need to create a Xamarin Java Binding Library, which will create a bridge library for Xamarin based on the ActionBarSherlock Android library.

For these two steps, follow instructions from

To test the app, in the app’s Activit1, just use the sample  code also posted there (use the code from TabActivity class).


In order to target Android 2.1:

1. Change properties of the ActionBarSherlockBindings project to have Android minimum version 2.1

2. For the app, also change properties to have Android minimum version 2.1 (in Visual Studio, right click on project, Properties and from the dialog, it’s in the Application tab, ‘Minimum Android to target’)

3. On the app, we need to change it to target Android 4. This is specified in the AndroidManifest.xml file of the app

If it does not exist, in Visual Studio, go to the app properties, and click on ‘Android Manifest’ Tab and click to generate the file.

Once done, UI appears with options for the manifest,  set ‘Target API level’ to 14.


Also,  once I targeted Android 2.1, I had to make few changes in the sample code for it to work.

Some classes need to be replaced with classes from the Android.Support.V4.App (like Fragment) and a constant (ActionBar.NavigationModeTabs instead of ActionBar_Sherlock.ActionBarSherlock.ActionBarNavigationMode.Tabs)

Now the app can be tested on an Android 2.1 device or emulator.

Wednesday, May 22, 2013

First app with Xamarin Android and MVVMCross – gotchas

1. After installing Xamarin, create a new ‘Visual C# / Android / Android Application’ using Visual Studio, say ‘DemoApp.Android’ but have the solution called ‘DemoApp’.

2. Add an ‘Visual C# / Windows / Portable Class Library’ called DemoApp.Core.
   First select ‘Windows Phone 7.5 and later’ and then ‘Mono Android’ and ‘MonoTouch’. Note that Xamarin frameworks become available only if you select ‘Windows Phone 7.5 and later’

3. Make sure you have the latest NuGet installed. For this, in Visual Studio, go to Help \ About Microsoft Visual Studio.

4. Using NuGet, search for ‘mvvmcross’ and add ‘MVVMCross Hot Tuna Starter Pack’ to BOTH the DemoApp.Android and DemoApp.Core
In the DemoApp.Android, it creates a SplashScreen activity and layout, and a layout and a view in FirstView.axml and FirstView.cs respectively.
In the DemoApp.Core, it creates a FirstViewModel view model.

6. In DemoApp.Android, delete the Activity1.cs and Resources/Layout/Main.axml.

7. Run. It should run OK at this point.

Saturday, February 16, 2013

Saving state in Windows Phone 8 emulator



1. Export virtual machine just in case something bad happens.

2. Run your app from Visual Studio as you normally do OR open the emulator from Hyper-V

3. IMPORTANT: If you started emulator from Visual Studio, close Visual Studio, right click on the virtual machine and click Reset. This will make the virtual machine snapshot you will save next usable from Visual Studio.

4. Customize the Windows Phone OS as you want

5. Create a snapshot

6. Rename the snapshot with the same name as the parent (for example: ‘snapshot.720x1280.1024’)

7. Delete parent (DO NOT select Delete Snapshot Subtree)

9. Run emulator from Visual Studio.

Saturday, February 02, 2013

Windows Phone versions, Windows and Visual Studio versions

On are listed all the Windows Phone SDKs.


SDK 7.1

Targets devices with Windows Phone 7.0 and Windows Phone 7.5

Windows® Vista® (x86 and x64) with Service Pack 2 – all editions except Starter Edition

Windows 7 (x86 and x64) – all editions except Starter Edition

Visual Studio 2010 SP1


SDK 8.0

Targets devices with Windows Phone 8 and Windows Phone 7.5

Windows 8 64-bit (x64) client versions

Windows Phone 8 Emulator:

Windows 8 Pro edition or greater

Requires a processor that supports Second Level Address Translation (SLAT)

Visual Studio 2012


SDK 7.8

Adds two new emulator images to your existing Windows Phone SDK installation. This update supports both the Windows Phone SDK 7.1 and the Windows Phone SDK 8.0. Using this update, you can provide the Windows Phone 8 Start screen experience in your Windows Phone 7.5 apps. You can also test how your apps will run on Windows Phone 7.8 devices.

It’s for both SDK 7.1 or SDK 8 to enable developing for Windows Phone 7.5

Tuesday, January 15, 2013

Asynchrounous programming aka async and await support in Windows, Windows RT and Windows Phone

The new async/await syntax of C# 5 is natively supported in WinRT, .NET 4.5 and Windows Phone 8. Up until 22 Oct 2012 it was additionally available for .NET 4.0 and Silverlight 5 via the Async Targeting Pack from June 2012.

On 22 Oct 2012, Microsoft pre-released a package called Microsoft.Bcl.Async additionally for Silverlight 4, Windows Phone 7.5 and, what's probably most surprising, also for Portable Class Libraries targeting all these platforms:

Using async/await without .NET Framework 4.5:

To add a reference to the updated NuGet Package, right click the project, select “Manage Package References” and search for Microsoft.Bcl.Async. Make sure you selected the “Online” tab on the left hand side and the top left drop down says “Include Prerelease”.

Tuesday, January 08, 2013

WCF Data Services + oData + Entity Framework + Silverlight + Telerik simple application

At the time writing this article, WCF Data Services(previously known as ADO.NET Data Services) ships separately from .NET Framework and are distributed by NuGet.

This means, the namespace used is in the form Microsoft.Data.Service.* and not System.Data.Service* (like in .NET Framework). The new release supports oData v3, while the previous release of WCF Data Services existing in .NET Framework supports oData v1 and v2.

This is described here:

The Telerik suite has a nice support for WCF Data Services by the RadDataServiceDataSource class, which is able to bind the data from WCF Data Service to the UI.

One problem is Telerik was built against the .NET Framework support for WCF Data Services, not against the assemblies distributed by NuGet.

Read more about this here:


Steps to create the app:

1. Create a new Silverlight 5 application using Web Application project setting, and suppose the name of the app is SilverlightApplication1

The next steps refer to the web application:

2. I wanted to have a code behind class for the generated SilverlightApplication1TestPage.aspx, so I added a SilverlightApplication1TestPage.aspx.cs class, and in the SilverlightApplication1TestPage.aspx I added:

CodeBehind="SilverlightApplication1TestPage.aspx.cs" Inherits="SilverlightApplication1.Web.SilverlightApplication1TestPage"

Also, I made SilverlightApplication1TestPage to derive from System.Web.UI.Page

3. Add references to System.Data.Services, and System.Data.Services.Client to add support for WCF Data Services.

Also, rigth click on the web project and choose “Manage NuGet packages”. In the top right search box, search for Entity Framework and when found, click on Install button. It will add a reference to EntityFramework assembly.

4. Create a class for an entity called User:

public class User
    public virtual int Id { get; protected set; }
    public virtual string FirstName { get; protected set; }
    public virtual string LastName { get; protected set; }

The DataServiceKey and DataServiceEntity attribute need to be set to tell WCF Data Services which is the Id property of the class entity.

5. Create a class derived from DbContext, UserContext

public class UserContext : DbContext
        public DbSet<User> Users

        public UserContext(string connString) : base(connString)

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
            modelBuilder.Configurations.Add(new UserMapping());

We can expose the User entity by the WCF Data Service using a public property returning a DbSet of that entity

The DbContext constructor accepts a string which represents the connection string to the database

6. Add a UserMapping class which implements the mapping of the User entity to database, so for Entity Framework to know how to do it

public class UserMapping : EntityTypeConfiguration<User>

        public UserMapping()
            this.HasKey(t => t.Id);
            this.Property(t => t.FirstName).IsRequired().HasMaxLength(50);
            this.Property(t => t.LastName).IsRequired().HasMaxLength(50);

7. Right click on the web app project, and choose Add New Item/click on Web/WCF Data Service and choose UserService.svc as the name.

[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
    public class UserService : DataService<ObjectContext>
        public static void InitializeService(DataServiceConfiguration config)
            config.SetEntitySetAccessRule("*", EntitySetRights.All);
            config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
            config.UseVerboseErrors = true;

        protected override ObjectContext CreateDataSource()
            var connString = ConfigurationManager.ConnectionStrings["DBConnString"].ConnectionString;
            var context = ((IObjectContextAdapter)new UserContext(connString)).ObjectContext;
            context.ContextOptions.ProxyCreationEnabled = false;
            return context;

The ServiceBehavior attribute makes the web-service to include the exception in the fault details. It is important when debugging.

Fiddler is good to debug web-service issues and this attribute will make the exceptions visible in the response.

SetEntitySetAccessRule is important to set rights on entities.

TestQueryableSL is the name of the connection string to the database

8.  Add the following to the web.config:

    <add name="DBConnString"

  <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />

You should have a database called Test. If not, open SQL Server Management, and add a new database called Test.

In the Silverlight app:

9. Add a new class UserDataCtx:

public class UserDataCtx : UserContext
    public UserDataCtx()
        : base(new Uri("
http://localhost:4232/UserService.svc", UriKind.RelativeOrAbsolute))
Instead of 4232 port, use the port from right click on Web app project/ Web tab/Use Visual Studio Development Server/Specific port

This class is required in order to pass the Uri to the UserContext class


10. In MainPage.xaml add:


<Grid x:Name="LayoutRoot"
           <RowDefinition Height="*" />
           <RowDefinition Height="Auto" />
       <telerik:RadDataServiceDataSource Name="customersDataSource"
               <l:UserDataCtx />
       <telerik:RadGridView Grid.Row="0"
                            ItemsSource="{Binding DataView, ElementName=customersDataSource}"
                            IsBusy="{Binding IsBusy, ElementName=customersDataSource}"
                            ShowGroupPanel="False" />
       <telerik:RadDataPager Grid.Row="1"
                             Source="{Binding DataView, ElementName=customersDataSource}"
                             PageSize="10" />

11. Right click on the Silverlight project and add a new service reference. Click on the arrow button from Discover button, and choose ‘Services in this solution’

You should see UserService.svc in the list and selected.

In the Namespace text box, choose the name DataServices

12. Add reference to the Telerik.Windows.Controls/Data/DataServices/GridView/Input  and Telerik.Windows.Data