Gerald Versluis: Beauty and the beast – Use MVVM to unleash inner beauty

While your UI is very important (very, very important on mobile!) to your end-user, we must not forget that our project has to be maintainable and thus also has to be beautiful on the inside.

There are numerous techniques and design-patterns to help us with that. One of them is Model-View-ViewModel MVVM, which I will cover in this post.

MV.. Whaaaat?!

Many of you probably heard of the Model-View-Controller (MVC) or Model-View-Presenter (MVP) pattern which is somewhat the predecessor of the MVVM pattern.
MVVM’s main goal is to separate the GUI from the data and business logic and is a hot topic right now. While I could spend some time explaining why you should be using MVVM and how to do it from in a general way, I will be talking about a very specific framework I have been using in several projects now and how I implemented them in my Xamarin Forms apps.

FreshMvvm!

The framework I have been using in my projects is FreshMvvm, a simple yet very effective framework by Michael Ridland.

Initially I looked (briefly) at some more established frameworks like MvvmCross and MvvmLight. But they seemed to complex for the task (for now), which seems logical because they are adapted to work on mobile and more specifically Xamarin, while FreshMvvm is designed especially for Xamarin.Forms. Also, but this is a more personal taste, FreshMvvm has a more personal touch to it. Going to Michael’s website you can see his pretty face, he is open to suggestions and answers all of my questions by e-mail, that is just a big plus for me!

FreshMvvm works convention-based, which means that as long as you keep to naming conventions, the View will be matched to the appropriate ViewModel. And that’s where our first difference comes in; with FreshMvvm it is Pages (Views) and PageModels (ViewModels) to be more consistent with the mobile, Xamarin naming.

Let’s find out how easy this all is to implement in your app.

Out with the old…

First let’s see one old way of doing it. If we assume that you’ve created a PCL project then you will have four projects to start with and it will look something like this.

FreshMvvm.Sample Project Structure
FreshMvvm.Sample Project Structure

There is one shared project which, ideally, will contain all of your app logic and three platform specific projects. Depending on your preference you might be doing your layout in code or create them in XAML.
I like to do the layout in XAML, which is actually a big plus if you’re going to want to use MVVM. Although you could still define your pages in code, but as you might have discovered by now: I’m trying to encourage you to use XAML .

In the portable project I have a Pages folder which holds all of the pages for my app. Imagine a simple tabbed app. I would have one main page which specifies the different apps and one or more pages that hold the content of my tabs. So my app would pretty much look like this.

Different Pages
Different Pages

Nothing fancy, also in the XAML files nothing wild is going on, just a definition of how the tabs should look like.

// MainPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:pages="clr-namespace:FreshMvvm.Sample.Pages;assembly=FreshMvvm.Sample"
             x:Class="FreshMvvm.Sample.Pages.MainPage">
  <TabbedPage.Children>
    <pages:TabOnePage Title="Hello" />
    <pages:TabTwoPage Title="unicorn!" />
  </TabbedPage.Children>
</TabbedPage>

// TabOnePage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="FreshMvvm.Sample.Pages.TabOnePage">
  <Label Text="Hello" VerticalOptions="Center" HorizontalOptions="Center" />
</ContentPage>

// TabTwoPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="FreshMvvm.Sample.Pages.TabTwoPage">
  <StackLayout>
    <Label Text="unicorn!" VerticalOptions="Center" HorizontalOptions="Center" />
    <Button Text="Show me!" Clicked="Button_OnClicked"></Button>
  </StackLayout>
</ContentPage>

To be complete, let’s run this sample and see how it looks like for the non-geeks among us.

Simulator Screen Shot FreshMvvm sample
Simulator Screen Shot FreshMvvm sample

This is probably how you are used to do it, define some properties right in your screen and when something needs to happen, find the right event and do your thing!

While this works perfectly, it isn’t recommended in terms of the reusability and maintainability of your code. This is where MVVM comes in.

…In with the new!

As a modern software developer you want to keep your UI as clean as possible and doing just UI stuff. The same thing goes for your business logic.
To achieve that, using MVVM can help you! Let’s just dig in and I’ll explain along the way.

First lets get the NuGet package installed into our shared project.

FreshMvvm NuGet package
FreshMvvm NuGet package

As I mentioned earlier, FreshMvvm work convention-based. So first thing I will do is create a PageModels folder and create my PageModels, these have to inherit from the FreshBasePageModel.
Note; FreshMvvm does not have the ability to search in subfolders (for now) so just put your PageModels in the PageModels folder.

PageModels folder
PageModels folder

As you can see I’ve already added the PageModels for my two tab pages. Inside is nothing fancy, just the class definitions, of course inheriting from the FreshBasePageModel and some properties.

namespace FreshMvvm.Sample.PageModels
{
    public class TabOnePageModel : FreshBasePageModel
    {
        public string HelloText
        {
            get
            {
                return "Hello";
            }
        }
    }
}

namespace FreshMvvm.Sample.PageModels
{
    public class TabTwoPageModel : FreshBasePageModel
    {
        public string UnicornText
        {
            get
            {
                return "unicorn!";
            }
        }
    }
}

To have our pages use these properties we can use the built-in binding of Xamarin.Forms, you may already know them if you’ve used WPF or Silverlight before.
Here is how we change our XAML pages accordingly.

<!-- TabOnePage.xaml -->
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="FreshMvvm.Sample.Pages.TabOnePage">
  <Label Text="{Binding HelloText}" VerticalOptions="Center" HorizontalOptions="Center" />
</ContentPage>

<!-- TabTwoPage.xaml -->
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="FreshMvvm.Sample.Pages.TabTwoPage">
  <StackLayout>
    <Label Text="{Binding UnicornText}" VerticalOptions="Center" HorizontalOptions="Center" />
    <Button Text="Show me!" Clicked="Button_OnClicked"></Button>
  </StackLayout>
</ContentPage>

Notice how the Text attribute of our Labels have gone from a static text to a Binding on our PageModels. The button on the second Page hasn’t changed yet, I’ll come to that later on.

If we would now run our app you would see nothing. That is because there is no coupling between the Page and PageModel yet.
Another great thing about FreshMvvm is something called PageModel-to-PageModel navigation. So in code, you define which PageModel you want to show to the user and the framework automagically (by name, as we know now) finds the according View and shows it to the user.
By doing the navigation this way it also does the work for us to data-bind the Model to our View and thus filling it with data.

To make this work we have to open up the App.cs and create a page through FreshMvvm.

public App()
{
   // The root page of your application
   var mainPage = new FreshTabbedNavigationContainer();

   mainPage.AddTab<TabOnePageModel>("Hello", null);
   mainPage.AddTab<TabTwoPageModel>("unicorn!", null);
   MainPage = mainPage;
}

There are a few default page types that come with FreshMvvm out of the box, the FreshTabbedNavigationContainer is one of them.
This are predefined pages which most importantly define your layout and knows how to handle the navigation within your app.

Other predefined pages are: FreshNavigationContainer and the FreshMasterDetailNavigationContainer. For details on how they work exactly and how to implement you own I refer you to a blogpost by Michael himself.

Unfortunately I haven’t found a way to create a XAML-based container page. If you happen to know how, please let me know!

Now when we run our app, we see the same result as we did before, but we know that it’s a whole different show now. Instead of having to update our objects ourselves it all goes through binding, and even the binding to the view is done for us now! Awesome!

The last thing I promised have to explain to you is the button.
If you’re not used to using MVVM you probably stuff everything behind events of controls and do your stuff there. When you start using MVVM that should change. Everything in your UI is based on (bindable) properties.
So for the button we can use a property which is a Command. Which is pretty awesome because you can use it to execute the code-behind your button!
It also has some other perks, but you can find those out for yourself!

Let’s see how to bind a Command to our Button.

First, lets modify our TabTwoPage.xaml again

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="FreshMvvm.Sample.Pages.TabTwoPage">
  <StackLayout VerticalOptions="Center" HorizontalOptions="Center">
    <Label Text="{Binding UnicornText}" VerticalOptions="Center" HorizontalOptions="Center" />
    <Button Text="Show me!" Command="{Binding ShowUnicornCommand}"></Button>
  </StackLayout>
</ContentPage>

Notice how I replaced the Clicked event with the Command property.

But what does the implementation of the Command look like?

For this we need to go to our TabTwoPageModel.cs because of our naming conventions (you remembered right?) and create a property like this.

public class TabTwoPageModel : FreshBasePageModel
{
   public string UnicornText
   {
      get
      {
         return "unicorn!";
      }
   }

   public Command ShowUnicornCommand
   {
      get
      {
         return new Command(() =>
         {
            CoreMethods.PushPageModel<UnicornPageModel>("Unicorn.png", true);
         });
      }
   }
}

There are probably a few things to explain here.
First, I’m using an anonymous method here inline. You could also choose to create a separate method for it.
Second; where did that CoreMethods come from all of a sudden?!

This is also something that is provided by the FreshMvvm framework. This static class gives you some basic (or core if you like) methods for navigating through your app. Like I’ve mentioned before you can navigate by PageModels and the framework will find the right View for you.
Also you might like to show some alerts, etc. this is done through the CoreMethods as well.

Back to my shiny new Command. With this I tell my app to push a PageModel onto the NavigationStack and I specify an object that is given to the PageModel that is resolved to be. Lastly the boolean tells the screen if it is supposed to be modal or not.

Before I will go and run it now to see what happens there is one last thing that I want to show which are the methods you can override from the FreshBasePageModel in your own PageModel.
The one I will use right now is the Init method. The Init method takes an object parameter so it can basically be anything. As you might have guessed this is the object that in my case is “Unicorn.png”.
But this might as well have been a complex, lets say, Customer object which I provide to the customer detail screen for viewing.

public class UnicornPageModel : FreshBasePageModel
{
   public string ImagePath { get; private set; }

   public override void Init(object initData)
   {
      base.Init(initData);

      var imagePath = initData as string;

      if (string.IsNullOrWhiteSpace(imagePath))
      {
         CoreMethods.DisplayAlert("Error!", "Not an image path!", "OK");
         return;
      }

      ImagePath = imagePath;
      RaisePropertyChanged("ImagePath");
   }
}

So here you see how I have overridden the Init method. There is some error handling in here and eventually I set my data-bound property ImagePath.
This way you can provide your screen with the necessary object. Also there is a ReverseInit, which does the inverse. That method is called when I pop this screen (of course by the means of the CoreMethods) so you could do something with the returned object, like save your changed Customer details.
Besides the Init and ReverseInit there are also methods that are automagically wired to the ViewIsAppearing and Disappearing, which do what you might expect.

To finish this post lets have a looksy at the result…
Also the sample code for this project can be found on GitHub.

Unicorn screen
Unicorn screen

Xamarin: Getting Started with Xamarin.Forms 2.0’s Windows 10 Preview

With the release of Xamarin 4 came Xamarin.Forms 2.0, introducing new features and optimizations to help you build great native cross-platform mobile apps. In addition to ListView caching strategies, pinch gestures, and new properties came the first public preview of Xamarin.Forms for Windows 10 (UWP) applications. While Xamarin.Forms already supports Windows Phone and Store targets, […]

The post Getting Started with Xamarin.Forms 2.0’s Windows 10 Preview appeared first on Xamarin Blog.

Wallace B. (Wally) McClure: Xamarin C# and iOS9

Url: https://visualstudiomagazine.com/articles/2015/11/01/whats-in-ios-9.aspx

At the Apple Worldwide Developer Conference in September, the company introduced the first public beta of iOS 9 (as well as the first beta of OS X El Capitan). Xamarin got access to beta copies of iOS 9 at the same time as every other company, but almost immediately, Xamarin followed up the Apple announcements by making available Xamarin.iOS 9 and Xamarin Studio 6, which adds iOS 9 support.

Daniel Cazzulino: How Visual Studio builds on the Mac with Xamarin

When we started working for Xamarin as consultants, a couple years ago, it was nothing short of amazing for us that Xamarin had already achieved a pretty solid “F5 experience” with an app building on the Mac and debugging like any regular local .NET app. I had the same feeling the first time I did the same thing against an Azure website. Felt like magic (in the Arthur C. Clark way).

During the past year and a half since the we joined Xamarin, we iterated (among other things) on this key component of the developer experience, culminating in our most recent release, Xamarin 4. What started as a (more or less) batch process of “zip sources, HTTP post to Mac, build, run” (with frequent rebuilds needed), is now a fine-tuned granular incremental build system driven by MSBuild, connecting to the Mac over a resilient, auto-deployed and always-on messaging layer running on top of a bi-directional binary protocol over TCP, secured by an SSH tunnel.

At the user experience level, it might seem that little has changed other than a fancy new connection dialog. But as Tim Cook said “the only thing that changed is everything”, so I’ll go over the details of how it works today with the new Xamarin 4 experience.

MSBuild and Incremental Builds

For anything but trivial apps, achieving incremental builds is key for productivity: you don’t want to be copying unnecessary files over the network to the Mac, neither you want to be optimizing PNGs, compiling storyboards and what-not if none of the source files have changed.

MSBuild (and XBuild on the Mac) already support incremental builds, so the first challenge was to move away from batch-style of invoking XBuild remotely, to a fully “MSBuild-native” solution. Also, we wanted to share 100% of the build logic from Xamarin.iOS targets on the Mac. So the way it works today is:

Xamarin MSBuild Flow

You can see that exactly the same targets and tasks are shared between the Mac and Windows. This allows us to minimize inconsistencies between VS and XS builds. The only difference is that the Windows version of the tasks do a remote invocation to the Mac whenever the tasks that need to run on the Mac are executed. We evaluate tasks individually to determine if they must run remotely or if they can be run locally.

The unit of remote invocation to the Mac is the MSBuild Task.Execute

One example of a task that always runs remotely is compiling iOS storyboards, since the tools to do so are provided by Xcode. An example that doesn’t is the C# compiler itself, since the source code can be compiled to IL by Microsoft’s compiler on Windows without requiring a roundtrip to the Mac.

Some parts of the build are done on Windows, some parts on the Mac

The next step was to improve the targets to provide relevant Inputs/Outputs to enable incremental build. An interesting challenge there was that for MSBuild to determine that a given target doesn’t need run again (or that certain outputs are out of date with regards to their inputs), the Outputs files need to exist on the Windows side. But since all we need those output files for is for incremental build support, they are actually written as empty files on Windows :). MSBuild doesn’t care, as long as the timestamp on those files can be compared with the Inputs to detect the out-of-date items.

This mechanism existed prior to Xamarin 4, and we just replaced the underlying remote call protocol, which was almost trivial to do since the core changes to unify XS/VS builds had already been done. Our goal was to have at least comparable performance to our previous releases.

Now that the underlying communication infrastructure has shipped, we’ll focus on fine tuning the targets and tasks to leverage incremental build support even more. Our goal is to achieve substantial performance gains moving forward, and we could certainly use your feedback, especially if you find some cases where builds are considerably slower than local builds on the Mac with Xamarin Studio.

Remote Communication

The underlying communication facilities that Xamarin provides within Visual Studio are consumed by fairly independent components (we call them Agents):

  • Activation: ensures that the Mac is properly activated
  • Build: performs the remote build task invocation
  • Designer: provides the rendering for the iOS designer
  • IDB: provides similar functionality to ADB (Android Debug Bridge), hence the name, an acronym of iOS Debug Bridge (we don’t like the name so much nowadays ;)). Basically exposes list of simulators and devices available on the Mac
  • Stats: we support collecting some stats (execution time, payload sizes, etc.) for diagnostics.

Xamarin Communication Overview

From top to bottom, the flow is:

  1. When Xamarin starts within Visual Studio, it automatically establishes an SSH connection with the Mac, deploys the Broker (if necessary), starts it and then starts all the Agents (which you see in real-time in the status bar or the spinner icon tooltip on the connection dialog)
  2. Agents use the exposed API (IMessagingClient) to send/post/reply messages (remember it’s bidirectional!)
  3. The Messaging layer communicates over TCP/IP within the SSH tunel with the Broker, which forwards the message to the Mac-side agent that registered to receive the message.
  4. The process is the exact opposite if the Mac side agents need to communicate with the VS ones, which are in turn registered to receive certain messages.

In previous versions of Xamarin, an unexpected error on any of the individual components on the Mac could cause the whole build host to stop working, requiring manual intervention by restarting it. In Xamarin 4, we implemented process-level isolation for unrelated components:

Xamarin Process Model

One key change from our previous versions is that now Visual Studio drives the Mac side too. Since it connects remotely to the Mac via SSH as a local interactive user account, it can start processes, copy files, fetch logs, etc.

Visual Studio controls deployment, versioning and manages processes on the Mac

As shown in the previous image, there is another isolation boundary at the Visual Studio process level. This ensures that multiple instances of VS can simultaneously connect to the Mac seamlessly. The broker and individual agents can all be recycled independently too. The ports used by the broker and agents are negotiated automatically to avoid collisions too.

And as soon as Visual Studio disconnects from a Mac, all processes are stopped.

In a future post, I’ll go into more detail on the protocol underlying the Messaging layer. If you’re curious, it’s MQTT 🙂

Matt Ward: NuGet Support in Xamarin Studio 5.10

Xamarin Studio 5.10 was released last week as part of the Xamarin 4 release and it includes changes to the NuGet support.

Changes

  • Support NuGet 2.8.7.
  • Open readme.txt when a NuGet package is installed.
  • Support packages.config file named after the project.
  • Local Copy settings are preserved for references when updating packages.
  • Do not show Checking for package updates message in status bar.
  • Do not show warning in the status bar if a NuGet package has PowerShell scripts.
  • Prevent the solution being closed when NuGet packages are being added.
  • Removing a NuGet package does not update the Solution window when multiple solutions are open.
  • Prevent packages.config file being marked as deleted by Git after updating a pre-release NuGet package.
  • Prevent retargeting a NuGet package marking packages.config as deleted by Git.
  • Allow Microsoft.ApplicationInsights NuGet package to be installed.

More information on all the changes in Xamarin Studio 5.10 can be found in the release notes.

NuGet 2.8.7 support

Xamarin Studio now supports NuGet 2.8.7. NuGet 2.8.7 adds support for the Universal App Platform (UAP) target framework to support Windows 10 Application Development.

Open readme.txt when a NuGet package is installed

A NuGet package can contain a readme.txt file which Xamarin Studio will now open and display in the text editor when the NuGet package is installed or updated.

Preserve Local Copy on Updating Packages

The Local Copy setting on an assembly reference will now be preserved when updating a NuGet package or retargeting a NuGet package.

By default Local Copy is set to true for assembly references when installing a NuGet package. If you set Local Copy to false for one or more of these references then this setting will now be preserved when updating or retargeting the NuGet package.

Packages.config file named after project

NuGet supports multiple projects in the same directory each using their own packages.config file. To allow multiple projects in the same directory to each use their own NuGet packages you can name the packages.config file after each project. In the examples below the project filename is on the left and the corresponding packages.config filename is on the right.

  • Foo.csproj => packages.Foo.config
  • Bar.csproj => packages.Bar.config
  • Foo Bar.csproj => packages.Foo_Bar.config

Xamarin Studio now checks for the packages.ProjectName.config file first and will use it if it exists, otherwise it will fall back to the default behaviour and use the packages.config file.

Note that a new project without any NuGet packages will use a packages.config file by default. The basic procedure to enable a project specific packages.config file when creating a new project is:

  1. Create new project called Foo.
  2. Add a NuGet package to the Foo project.
  3. Rename the packages.config file to packages.Foo.config
  4. Reload the solution in Xamarin Studio.

Also note that if you remove all the NuGet packages from a project the packages.ProjectName.config file will be deleted and on adding a new NuGet package the default packages.config file will be used.

Do not show Checking for package updates message in status bar

Previously when Xamarin Studio was checking for NuGet package updates a message would appear in the status bar. This status bar message has now been removed since checking for NuGet package updates is a background task and does not prevent Xamarin Studio from being used.

Do not show warning in the status bar if a NuGet package has PowerShell scripts

Previously if a NuGet package was installed and it contained PowerShell scripts then a warning was shown in the status bar. Now this message is only shown in the Package Console window.

Prevent the solution being closed when NuGet packages are being added

A check is now made when Xamarin Studio is closed to see if NuGet packages are still being installed. If this is the case then a dialog will be displayed indicating that it is not currently possible to close Xamarin Studio allowing the NuGet package to finish installing.

Bug Fixes

Removing a NuGet package does not update the Solution window when multiple solutions are open

With two or more solutions opened at the same time the Packages folder would not be updated for all solutions when a NuGet package was removed. This was because Xamarin Studio was not refreshing the Packages folder for all solutions currently open.

Prevent packages.config file being marked as deleted by Git after updating pre-release NuGet package.

If there was only one pre-release NuGet package installed into a project and then a later version of the NuGet package was installed from the Add Packages dialog then the packages.config file was then being shown as deleted by Git instead of modified.

The packages.config file is deleted by NuGet after the old NuGet package is uninstalled if there are no NuGet packages referenced. A special case to handle this was added in Xamarin Studio 5.3 but that only handled updating a NuGet package from the Solution window. Now updating a pre-release from the Add Packages dialog is also handled.

Retargeting a NuGet package marks packages.config as deleted by Git

This is similar to the previous bug. Retargeting a NuGet package will uninstall and then install the NuGet package. If there is only one NuGet package in the project then the packages.config file is deleted and was causing Git to mark the file as deleted instead of updated.

Unable to install Microsoft.ApplicationInsights NuGet package

Xamarin Studio 5.9.2 added support for NuGet 2.8.5 but it was not possible to install the Microsoft.ApplicationInsights NuGet package into a project. It was possible to install it using Visual Studio with NuGet 2.8.3 or higher installed. The error reported by Xamarin Studio was:

Adding Microsoft.ApplicationInsights...
The 'Microsoft.ApplicationInsights' package requires NuGet client version '2.8.50313' or above, but the current NuGet version is '2.8.5.0'.

Xamarin Studio 5.10 now allows the Microsoft.ApplicationInsights NuGet package to be installed into a project.

Matthew Leibowitz: My New (First) Book and This Year

eBook: $32 | Print + eBook: $50

This has been a great year so far, I have released multiple new components on the Xamarin Component Store, committed thousands of lines of code into various repositories, and, finally had my book published!

It has been a long time coming, originally scheduled for about 6 months, but working full time had forced me to go a bit slower. So after 12 months of work, Packt Publishing, made my book, “Xamarin Mobile Development for Android Cookbook”, available to the world.

Beginning Writing

In September last year, they contacted me about authoring a book focused on more advanced concepts when developing Android apps using the Xamarin platform. I cover concepts ranging from using basic UI elements, to managing view states. I also show how one can make use of Bluetooth and NFC communication. Included in the topics are some that cover modern app development, such as making use of the Android support libraries to create modern apps that run on almost all versions of Android.

I won’t lie and say that the book was easy; writing is pretty hard. Once the topic is decided and the code ready, the actual readable text takes a bit of work. I feel that I was able to bring each recipe across in an easy-to-consume manner without compromising on the actual content. This is a lot of work in that it is sometimes hard to write a technical document without knowing the knowledge level of the reader.
In addition to that, sometimes I had to research why I did something. I have done something so many times that it has become automatic, and then I have to go and learn why. And then I sometimes realize that what I had been doing all this time was only one way…

All in all, I quite enjoyed writing, even if it meant very late nights. If I was to write another book, well, it might be some time in the future. I hope that my book sells well, not because of money, but it is an accomplishment. How many people can say they have written a book, and how many of those can say they wrote a good book. If this book sells well, then I would have achieved one of my life goals.

After I first found out about software development when I was 9 years old, I wanted to become a programmer. After the release of Windows, I wanted to be the new Bill Gates. I don’t think I’ll ever get to that level of awesomeness, but I can go for the other things. One of those things is to provide developers with tools that they can use to create the best that can be created.

Why I Started

When I started developing professionally, my projects were ASP.NET websites and Desktop applications. This is great, but typically those apps were company apps and only used during work hours. Mobile apps have always been a passion of mine in that they travel with the user. I have always liked being a back end developer as this is often the area where the “cool” work is done. The UI is great, don’t get me wrong, but almost all of them talk to some library or service.

During my years of development, I really grew to love my work more and more. This love grew into something that I want to share with the world. It started off by helping by brother do a bit of development. He now has built several games using many of the game creation tools. One of the coolest, and most cross-platform, is Scirra’s Construct 2. Recently, he has started using Unity 3D.

Another way I shared my love for development is though my code. I have several repositories on GitHub, which I try and update. I also use this account to update repositories in the community. Sometimes there is that awesome library, but just doesn’t have that feature… For example, there is this tiny library, NLipsum, that allows you to generate a chunk of lorerm ipsum. Although technically not very useful, it is often the simplest way to populate text fields. This library required no changes, but could only be used with desktop .NET platforms. In the age of mobile development, I was able to add a new project that created a Portable Class Library, which can be used everywhere. This is not a headlines-worthy change, but NLipsum is now more cross-platform than ever before.

Writing a book was just another way to share my knowledge and love of development with the world. I hope my book helps both the new guy on the block as well as the other guy that never got around to using In-App billing in his popular Android app. As a result, I am not going to tell you to buy my book… If you want to check it out, or use it to get started with Xamarin.Android apps, you can order it in both an ebook and/or print from Packt Publishing for $32.

James Montemagno: Access the Current Android Activity from Anywhere!

In the world of Android one of my biggest pain points over the years is that often you need access to the apps current Activity when writing libraries or abstracting out common functionality. For years I have been hacking around the issue by setting special Intent flags or more than likely creating a BaseActivity with a static “CurrentActivity” that is set when the page is started up. While this works short term for MY app, it completely falls down when you want to create Plugins or abstract an API into an interface of some sort. 

 When it comes down to it you just need that Activity, and it should be easy! This is why I have solve the issue once and for all with a secret hidden API that Google snuck in during the release of Ice Cream Sandwich (API 14) called ActivityLifecycleCallbacks. This is super undocumented, but from what Jérémie and I can gather Google introduced this so you can at any time figure out what the current activity. It must be implemented on your apps “Application” class and call RegisterActivityLifecycleCallbacks. After this though, you are all done. 

So, let me introduce to you my latest Plugin for Xamarin.Android called “CurrentActivity“. 

You guessed it, this plugin does 1 thing, lets you get access to the current activity. In fact the entire API is just 1 property:


/// The Current Activity
Activity Activity { get; set; }

The magic of this NuGet package and Plugin is that when you install it or if you are using it as a dependency in your own Plugin is that it lays down a “MainApplication.cs” file that ties into and implements the ActivityLifecycleCallbacks. BOOM! Done! Here is what that looks like:


using System;
using Android.App;
using Android.OS;
using Android.Runtime;
using Plugin.CurrentActivity;

namespace $rootnamespace$
{
	//You can specify additional application information in this attribute
    [Application]
    public class MainApplication : Application, Application.IActivityLifecycleCallbacks
    {
        public MainApplication(IntPtr handle, JniHandleOwnership transer)
          :base(handle, transer)
        {
        }

        public override void OnCreate()
        {
            base.OnCreate();
            RegisterActivityLifecycleCallbacks(this);
            //A great place to initialize Xamarin.Insights and Dependency Services!
        }

        public override void OnTerminate()
        {
            base.OnTerminate();
            UnregisterActivityLifecycleCallbacks(this);
        }

        public void OnActivityCreated(Activity activity, Bundle savedInstanceState)
        {
            CrossCurrentActivity.Current.Activity = activity;
        }

        public void OnActivityDestroyed(Activity activity)
        {
        }

        public void OnActivityPaused(Activity activity)
        {
        }

        public void OnActivityResumed(Activity activity)
        {
            CrossCurrentActivity.Current.Activity = activity;
        }

        public void OnActivitySaveInstanceState(Activity activity, Bundle outState)
        {
        }

        public void OnActivityStarted(Activity activity)
        {
            CrossCurrentActivity.Current.Activity = activity;
        }

        public void OnActivityStopped(Activity activity)
        {
        }
    }
}

Then if you want to access the current activity anywhere in your Android application, library, or plugin simply call: CrossCurrentActivity.Current.Activity and you will have the current activity.

If you already have subclassed Application, don’t worry as you can just copy and paste some code that I put in a readme text file in the project, or head over to my GitHub and learn more!

Xamarin: Contest: Show Us Your Favorite Xamarin 4 Feature!

In case you missed it, earlier this week we announced a major release – Xamarin 4. Xamarin 4 is all about empowering you with everything you need to create great mobile apps. We have made major enhancements to the way you build apps with the Xamarin Platform in Xamarin 4, such as Xamarin.Forms 2.0, rebuilt […]

The post Contest: Show Us Your Favorite Xamarin 4 Feature! appeared first on Xamarin Blog.