Testing with Xamarin

On Monday, June 6, 2016 I will be debuting a new talk at Chicago Coder Conference 2016. The talk focuses on much of my research into UI Testing using Xamarin’s UI Testing framework. In addition, I will also talk about my experiences with unit testing both as a means to test application code and to validate UI functionality using the Moq library. UI Testing is a crucial step in the mobile application development process because of the disparity between devices, especially on Android. This talk will not just talk about it but will also show them working and tips for setting them up. I also hope to have a solid discussion around the various levels of testing and what goals are to be achieved.

Current slide deck and code are on my GitHub: https://github.com/xximjasonxx/ChicagoCoderConference2016

I look forward to seeing you at the talk. I also plan to give this talk again at a future session of the Chicago .NET Mobile User Group.

Android Object Serialization with Xamarin

Very often with Android you want to pass objects between activities. On iOS this is extremely easy as you are given a reference to the incoming ViewController and can easily pass the reference. On Android because of the Intent system this process becomes more complicated because many things within and without of your application can handle the intent. Thus, Android allows you to send Extra data with an intent.

We can leverage this same functionality within Xamarin rather easily. First, understand that all of your managed objects (that is C# objects) inherit from object. When you start to utilize native Android processes you need objects which inherit from Java.Lang.Object.  In doing this, you will find the need to implement a special constructor MyClass(IntPtr ptr, JniHandleOwnership jni) which must invoke the base constructor with the same signature. This constructor is commonly called when the object is being created by Android, as in the case of deserialization.

What this means is that you will need to implement wrapper classes for your PCL objects to handle the serialization.  To ease this process, I created a base class shown below.

 <pre>
namespace MarvelInfo.Droid.Models
{
    abstract class JavaSerializableObjectBase : Java.Lang.Object, ISerializable
    {
        protected JavaSerializableObjectBase()
        {
        }

        protected JavaSerializableObjectBase(IntPtr ptr, JniHandleOwnership jni) : base(ptr, jni)
        {
        }

        [Export("writeObject", Throws = new[] { typeof(IOException), typeof(ClassNotFoundException) })]
        void WriteObject(ObjectOutputStream stream)
        {
            Write(stream);
        }

        [Export("readObject", Throws = new[] { typeof(IOException), typeof(ClassNotFoundException) })]
        void ReadObject(ObjectInputStream stream)
        {
            Read(stream);
        }

        // asbtract methods
        protected abstract void Write(ObjectOutputStream stream);
        protected abstract void Read(ObjectInputStream stream);
    }
}
</pre>

Right off the bat, you can see we are using the ExportAttribute to mark the two methods in here in accordance with the serialization methods for Android Serialization(http://developer.android.com/reference/java/io/Serializable.html). These methods get called as we read from and write to the serialization engine. I have created this abstract class to simplify the implementation in the lower methods.

The most important thing to keep in mind with this process is the order. The way you write must match the way you read otherwise you the process will not work.  Here is an example of the JavaCharacter class which wraps my C# Character class.

<pre>
namespace MarvelInfo.Droid.Models
{
    internal class JavaCharacter : JavaSerializableObjectBase
    {
        private Common.Models.Character _character;

        public JavaCharacter(IntPtr ptr, JniHandleOwnership jni) : base(ptr, jni)
        {
            _character = new Common.Models.Character();
        }

        public JavaCharacter(Common.Models.Character character)
        {
            _character = character;
        }

        protected override void Write(ObjectOutputStream stream)
        {
            stream.WriteUTF(_character.Name);
            stream.WriteInt(_character.Id);
            stream.WriteUTF(_character.Description);
            stream.WriteObject(new JavaThumbnail(_character.Thumbnail));
            stream.WriteObject(new JavaComicCollection(_character.ComicCollection));
            stream.WriteObject(new JavaStoriesCollection(_character.StoriesCollection));

            stream.WriteInt(_character.Urls.Count);
            _character.Urls.Map(x =&gt; stream.WriteObject(new JavaUrlInfo(x)));
        }
        protected override void Read(ObjectInputStream stream)
        {
            _character.Name = stream.ReadUTF();
            _character.Id = stream.ReadInt();
            _character.Description = stream.ReadUTF();
            _character.Thumbnail = ((JavaThumbnail)stream.ReadObject()).GetThumbnail();
            _character.ComicCollection = ((JavaComicCollection)stream.ReadObject()).GetComicCollection();
            _character.StoriesCollection = ((JavaStoriesCollection)stream.ReadObject()).GetStoriesCollection();

            var urlCount = stream.ReadInt();
            _character.Urls = new List();
            for (int i = 0; i &lt; urlCount; i++)
                _character.Urls.Add(((JavaUrlInfo)stream.ReadObject()).GetUrlInfo());
        }

        public Common.Models.Character GetCharacter() { return _character; }
    }
}
</pre>

Each write has a corresponding read. The most interesting thing to note here is the writing of an int for the count of the list we write. As I said, we must have corresponding reads for writes so we serialize the count so we know how many reads to make.

When it comes to embedded objects, we can create new derivations of our base class and use the WriteObject and ReadObject methods which will invoke the serialization process on those objects. Below is an example of the class which reads and writes Thumbnail class which is held as a property on Character.

<pre>
namespace MarvelInfo.Droid.Models
{
    internal class JavaThumbnail : JavaSerializableObjectBase
    {
        private Thumbnail _thumbnail;

        public JavaThumbnail(Thumbnail thumbnail)
        {
            _thumbnail = thumbnail;
        }

        public JavaThumbnail(IntPtr ptr, JniHandleOwnership jni) : base(ptr, jni)
        {
            _thumbnail = new Thumbnail();
        }

        protected override void Read(ObjectInputStream stream)
        {
            _thumbnail.Path = stream.ReadUTF();
            _thumbnail.Extension = stream.ReadUTF();
        }

        protected override void Write(ObjectOutputStream stream)
        {
            stream.WriteUTF(_thumbnail.Path);
            stream.WriteUTF(_thumbnail.Extension);
        }

        public Thumbnail GetThumbnail() { return _thumbnail; }
    }
}
</pre>

It is a very straightforward and understandable process. Each method also contains a Get* method which enables me to return the C# object instance the deserialization process has built up via the readObject method.

I hope this helps you understand how to use serialization in your Xamarin.Android apps. I can understand the draw of creating a singleton and using that to hold data like this between Activities, but doing so limits your options within Android, since you wont be able to fully use the Intent system.

Chicago Code Camp 2016

This year I was selected to speak at Chicago Code camp on Xamarin End to End Development. This is the same talk I gave at Uplift a few months prior with some improvements based on the information gathered at Xamarin Evolve the week prior.

In addition to my presentation, I was asked by David Giard to participate in giving part of the keynote around why right now is such a good time to be a developer.  This was a tremendous honor and I really enjoyed it, even if there were a few technical hiccups during my section.

Overall, the event went exceptionally well and I got a ton of questions about Xamarin from the packed house that attended my session. It appears that the purchase of Xamarin by Microsoft has generated a surge in the interest of Xamarin, Miguel noted this as well at Evolve showing a dramatic upturn since the announcement.  To that end, I suggested to David Allen that a joint user group meeting between the .NET User Group downtown and the Mobile .NET User Group be held with a talk on Xamarin to take advantage of this upturn in interest.

In regards to Chicago Code Camp, all presentation assets (including the keynote demo) are located here: https://github.com/xximjasonxx/ChicagoCodeCamp2016

Chicago Code Camp 2016

For the second year in a row the committee running the Chicago Code Camp has invited me to speak at the event.  Chicago Code Camp is an awesome event and I credit it with being a big reason I looked to work and live in Chicago. This year I will be presenting my Xamarin.Forms End to End Development talk. As opposed to other Xamarin.Forms talks this one attempts to show Forms under real world scenarios.

Along with exploring Forms and Xamarin’s roots, we will dive into full coding examples where I show how to build an application from scratch. Beyond that I show off an MVVM style approach using FreshMVVM and explain how MVVM can help us build apps which are more testable by using ‘mocking’.

The conclusion of the talk focuses on Xamarin.Forms usage with the Xamarin UI Testing tool which enables scripted interactions to take place in an automated fashion; locally and in the cloud.  Hoping to see a lot of people there on April 30th.  Registration is already open for this event: http://www.eventbrite.com/e/chicago-code-camp-2016-registration-20983871324 This will be the second year at Illinois Institute of Technology.

Introducing Saitama

In the previous post I talked about the decision to explore a framework that would continue to allow our West Monroe teams to use the features we like from MVVMCross, namely dependency injection.  However, as a team we have come to realize that MVVMCross has limits with more complicated and UX intensive applications that cannot be overcome without significant effort.  Over the past week, I have been working on a framework that would satisfy our needs as a team.  It now has a name: Saitama.

Goals

I am a big believer in IoC and its role in modern software development.  I have had the chance to use it with many different frameworks throughout the course of my career.  My current favorite is AutoFac but previous to that I enjoyed using Ninject.  I am sure other developers have their favorites as well so I wanted to make the framework IoC framework agnostic, use whatever you like.

Obviously there are some popular frameworks so I tried to implement those as best as I could, but I left it open if someone has a favorite framework they want to use.  You can even extend to other platforms, although, right now, I am only supporting Android and iOS.

The Core

At the core of the framework (Saitama.Core) are two items: the abstract class InjectionContainerResolverBase and the interface IInjectionContainer.  Each serves a specific purpose and facilitates injection within the application by registering specific Injectable Base Types with the chosen IoC framework.

The process of IoC is extremely simple.  Register a bunch of dependencies, usually marked with interfaces and then, when creating a “base” type look for properties (or constructor arguments) matching those types and provide instances held within the container for those arguments/properties. Thus, when a developer is operating in their dervied class(es) they can be assured that dependencies are fulfilled.

Identifying these “base types” is the job of the resolver and while the core process is platform agnostic, the conventions used to “find” the base types differ platform to platform, this is why derivations should use one of the “platform” base classes (Saitama.Core.Platforms).

Once these registrations are made, the resolver returns an instance implementing IInjectionContainer which is used for injection throughout the rest of the app.

Bootstrapping

While this all sounds good, it is useless unless we have a means to kick off this registration process.  For that we look to the specific bootstrap class on each supported platform (UIApplicationDelegate on Apple and Application on Android).  Because we know the OS will call into methods on these classes before anything else, they are ideal places to start.  For now, we will focus on the iOS side.

The absolute first point at which the user can take control of their app in iOS is with WillFinishLaunching, our base class SaitamaApplicationDelegate (in Saitama.Apple) overrides this method and takes a few actions:

  1. It asks the derivation for its instance of InjectionContainerResolverBase. The responsibility here is for the developer to return a container (or some intermediary which can create a container) that has all dependencies registered with the exception of the base types
  2. The Resolver registers all base types by scanning a provided assembly (entry on iOS, executing on Android) for types matching a certain convention (the convention can be overridden). For each type found, the resolver will register it against the container
  3. The IInjectionContainer is extracted from the resolver and stored in an internal static property (more on this later). This contains the knowledge of how the fulfill dependencies on base types
  4. The injection container fulfills all dependencies on the bootstrap class. This allows the developer to begin working with the dependencies as soon as possible

It is at this point that our application starts up and we define our first view.  For iOS, I have created an abstract class to serve as the base for all ViewController types (Saitama.Apple).  This inheritance is crucial for Saitama.  Without it, the framework will not know how to resolve dependencies on base types, such as View Controller.  Here is an example of a View Controller for the Test App.

    public partial class HomeViewController : SaitamaViewController
    {
        public INumberService NumberService { get; private set; }

        public HomeViewController() : base("HomeViewController", null)
        {
        }

        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // Perform any additional setup after loading the view, typically from a nib.
            var alertView = new UIAlertView("Generated Number", string.Format("Your number is: {0}", NumberService.GetNumber()),
                                null, "Ok", null);
            alertView.Show();
        }
    }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

As you can see, this code is no different than what you would normally write.  In this case, I am using a Xib based approach, but the storyboard approach is also covered.

Prebuilt Containers

As it normally is, the hardest part is usually creating the IoC container to use for injection, at least that was always my experience with ASP .NET MVC.  To that end, I intend to supply container modules for both Android and iOS implemented using AutoFac and Ninject for both.  My hope is that it will be enough to show others how they might write their own.

Future Plans

The current codebase is still being built, with heavy focus on Android, confident that I will get through it soon.  Next steps after that will be to clean up the source code and GitHub repo.  Then, I will package it with Nuget and send it out into the world.

The Code

https://github.com/xximjasonxx/Saitama

Please let me know if you have any feedback.  I am always interested in how I can make this better.

Integrating IoC with Xamarin.iOS

At West Monroe we use Xamarin almost exclusively for our mobile application development.  There are a variety of reasons for this but a few of the notable ones are:

  • Code Uniformity – Other teams within the West Monroe technology practice utilize C# for software development. That Xamarin also employs C# for its platform makes the transition to and from the mobile team easier. Newcomers must still work to understand the specific platform, but they can rely on the fact that the language being used will be familiar to them
  • Code Sharing – This is a big advantage to any project using Xamarin. If a client wishes to build a native application using standard tools they must at least run two teams using different tools and languages.  Each team will need to create the same feature using a different language.  Xamarin alleviates this risk by enabling code uniformity and code sharing between platforms. Indeed, a major selling point for our clients is the flexibility to know that if they want an Android version the effort will be less than the effort to create the iOS version.

These reasons, as well as others have led our team to great success with many of the projects that have come our way. In addition, we consistently leverage MVVMCross (https://github.com/MvvmCross/MvvmCross) for our development as MVVM is a solid pattern and works well with Xamarin since you will have different views for each platform supported.

Recently, however, the teams have begun to notice problems with implementing MVVM on larger projects where the UX is of a considerably higher effort than apps in the past.  We are beginning to see a ceiling with what MVVM can do when forced upon a platform (iOS and Android) which are not built for the pattern.  Due to this we have begun exploring options for what to do in those cases where MVVM and MVVMCross simply do not make sense.

One of the things we really like about MVVMCross is the dependency resolution aspect which happens within view models. Having our services and their dependencies handled this way cleans up the code dramatically.  The following is my initial attempt at building AutoFac into a Xamarin.iOS project.

The AppDelegate

In every iOS application the AppDelegate class is the starting point, responsible for handling global lifecycle events, launching is no exception.  This makes it the best place to start our dependency mapping registration.  For this, I created the AutoFacUIApplicationDelegate class which takes care of the critical parts of registration; it inherits from UIApplicationDelegate which is what the AppDelegate normally inherits from.

Just to make it easy and eliminate the potential for conflict I have chosen to build the registration process at the “Will Finish Launching” point in the process.  Here is the code for the method:

        public override bool WillFinishLaunching(UIApplication application, NSDictionary launchOptions)
        {
            // create our container builder
            var builder = new ContainerBuilder();

            // access the assembly and register ALL classes which implement our custom base class
            var types = GetType().Assembly.DefinedTypes;
            foreach (var theType in types)
            {
                if (theType.BaseType == typeof(AutoFacUIController))
                    builder.RegisterType(theType).PropertiesAutowired();
            }

            // ask the user to register their dependencies
            RegisterDependencies(builder);

            // establish our static container
            _autoFacContainer = builder.Build();

            // return true
            return true;
        }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

The code here is still pretty rough, but it communicates the general idea.  The first goal is to register the types of all View Controllers which are going to use Dependency Injection, that is those that inherit from AutoFacUIController. By doing this, we can ensure that when injection occurs the ViewController type is registered with the IoC container.

Once this is complete, we pass the IContainerBuilder reference to RegisterDependencies which is a user method allowing for the definition of their dependencies.  Once this complete we build and assign the container to a static variable to enable it to be used elsewhere in the application.  Here is a look at the RegisterDependencies in my test app:

        protected override void RegisterDependencies(Autofac.ContainerBuilder builder)
        {
            builder.RegisterType<WorkplaceNameService>().As<INameService>();
        }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

This is a rather contrived example but this is where you could leverage AutoFac and register your types and modules as needed.

Our next goal is to be able to inject these dependencies into our view controllers.  The pattern we are going for is similar to what we see used in ASP .NET MVC and since iOS is built on an MVC approach (more MVP in my opinion) the pattern fits quite well.  We want to define properties on the View Controller that represent our dependencies.  We then want AutoFac to fulfill those properties as the page is loading up.

The first piece to understand here is the lifecycle of ViewController when they are displayed in iOS. Based on my analysis there are two lifecycle events that I can hook into for this process: LoadView (storyboards) and AwakeFromNib (Xib based development).  For the purpose of this test, we will ONLY focus on LoadView since we should all be using Storyboards for the majority of our UI development in iOS, Xamarin or otherwise.

The second thing to understand is how this will need to work.  We want to grab our static IoC container reference and the use it to fulfill our dependencies.  Here is the base LoadView method.

    public class AutoFacUIController : UIViewController
    {
        private IContainer _container;

        public AutoFacUIController(IntPtr ptr) : base(ptr)
        {
            _container = AutoFacUIApplicationDelegate.GetAutoFacContainer();
        }

        public AutoFacUIController()
        {
            
        }

        public override void LoadView()
        {
            // resolve all properties
            _container.InjectProperties(this);

            base.LoadView();
        }
    }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

The InjectProperties method call reflects on the current instance and finds properties whose declared type match a type registered with the IoC container.  The result is, as long as a class inherits from this class it will, when ViewDidLoad fires have all of its relevant dependency properties fulfilled.

Beyond

Obviously this is incredibly rough and relies on quite a bit of ceremony and it completely tied to AutoFac. Ideally, there is more automation and the IoC container is a personal choice rather than a forced one. Nevertheless it’s a good start and I hope to incorporate it into an API library that we can use at West Monroe for more complex projects where the MVVM gains are outweighed by the losses.

For now, I want to continue testing this approach under different situations.  If you are interested I have posted by code to GitHub and it will update as I move through this research process.

https://github.com/xximjasonxx/iOS_AutoFac

Xamarin and El Capitan

So recently I upgraded my development Mac from Yosemite to El Capitan and all of Xamarin projects stopped compiling a produced a NuGet related message with code 127. After some research I found out that this was directly related to the upgrade as a result Apple strips away third party binaries in /usr which is where Xamarin stores its mono link, this results in Xamarin Studio being unable to build.

Reading through various blogs on this the solution was to create a link back to the mono binary located in /Library/Frameworks/Mono.framework/Commands/mono in /usr/bin. If you do this on El Capitan you will likely receive an “Operation Not Permitted” message even if you use an sudo.

The reason for this is Apple, in El Capitan, has revoked the root user and runs El Capitan in “rootless” mode which disallow any user, event with sudo rights to modify certain directories, including /usr

Most of what I read indicating the need to log into the Mac in recovery mode and use the System Configuration utility to disable the “rootless”. However, try as I might, I could not find this utility in the recovery screen. In the end, this forum must pertaining to Xamarin.Mac (https://forums.xamarin.com/discussion/45683/xamarin-mac-10-11-fix-preview) held the fix for me.

Once you boot into the recovery code access the terminal (under Utilities) and issue the following command: csrutil disable – this will disable the “rootless” mode. Boot back into normal Mac and you should be able to perform the linking action from earlier which resulted in the Operation Not Permitted message.

Once you recreate the missing mono command restart Xamarin Studio and things should be working. Not sure when a fix from Xamarin is coming since I get why Apple went to “rootless” mode and I don’t like circumventing it. From what I have found this was known since early September and still not fixed after a month.