MvvmCross – Part One

In Xamarin studio I’ll create a new solution called Jokes with a class library (PCL) called Jokes.Core. The “Core” is the convention that MvvmCross uses for the project containing your business logic, can be changed to something else. After the project is created I’ll add the MvvmCross nuget package. That added references to the MvvmCross HotTuna libraries but also created an App.cs file and a ViewModels/FirstViewModel.cs file. App.cs is the entry point of our application, all it does is to initialize the IoC container that comes with MvvmCross and set the start page for the application, in this case FirstViewModel, which I’ll rename to MainPageViewModel.

Next thing I’ll do is to add Models folder with a Person class. The person class is very simple, first and last name properties and a full name that is the first and the last name concatenated.

Then I’ll go to the MainPageViewModel and I’ll add properties for FirstName, LastName and Greeting. The greeting will be composed from the text “Hello” and the full name of the person. The important thing about the ViewModels is that they need to implement the interface INotifyPropertyChanged which is the interface responsible for making the databinding work. MvvmCross gives us a basic implementation of INotifyPropertyChanged with the base class MvxViewModel.

Now I’ll go ahead and a unit test project called Jokes.Core.Tests and I’ll write a test for the MainPageViewModel that when the FirstName is “John” and the LastName is “Smith” the greeting will be “Hello John Smith”. Test passes.

Next step – I’ll add a new Android project called Jokes.Droid and I’ll add MvvmCross nuget to it. I have to add a reference to the the Core project and rename FirstView to MainPage (by convention that needs to match the MainPageViewModel from the Core project so the view model locator can find it)

Execute SQL scripts as part of EF code first db initialization

Create a folder for sql scripts and put all *.sql files there. Set the build action of the sql files to EmbeddedResource. Call ExecuteScripts(context) method below from the Seed(context) method of your db initializer.

private void ExecuteScripts(DbContext context)
{
    foreach (var script in GetScripts())
    {
        string sql = GetFromResources(script);
        if (!string.IsNullOrWhiteSpace(sql))
        {
            context.Database.ExecuteSqlCommand(sql);
        }
    }
}

private IEnumerable GetScripts()
{
    return GetType().Assembly
        .GetManifestResourceNames()
        .Where(r => r.EndsWith(".sql"));
}

private string GetFromResources(string resourceName)
{
    using (var stream = GetType().Assembly.GetManifestResourceStream(resourceName))
    {
        using (var reader = new StreamReader(stream))
        {
            return reader.ReadToEnd();
        }
    }
}

Adding a page title for WinPhone in Xamarin.Forms

I’ve been playing with Xamarin.Forms for the last few days. While it is pretty impressive that you can build an iPhone, Android and WinPhone app from the same codebase, I get a feeling that WinPhone is a second class citizen. One of the first things that bugged me is that you do not get the standard WinPhone page titles “for free”. Here is some XAML to fix that:

<!-- WinPhone page title -->
<StackLayout>
   <StackLayout.IsVisible>
       <OnPlatform x:TypeArguments="x:Boolean">
           <OnPlatform.iOS>false</OnPlatform.iOS>
           <OnPlatform.Android>false</OnPlatform.Android>
           <OnPlatform.WinPhone>true</OnPlatform.WinPhone>
       </OnPlatform>
   </StackLayout.IsVisible>
   <Label Text="APPLICATION TITLE" TranslationX="4" TranslationY="4" />
   <Label Text="page title" Font="64" TranslationY="-12"/>
</StackLayout>

Hopscotch

Hopscotch is a little phone game that I started about two years ago and never got to finish. This week I started from scratch and published it in one day. The design of the game as well as the icon which I created from a screenshot turned out pretty great. And my six year old daughter absolutely loves the game, makes me feel so proud…

258x67_WPS_Download_cyan

Conference Call

The Conference Call app allows you to select an invitation for a conference call from your calendar and dial into the call with one press of a button.

If you encounter an invitation that cannot be parsed properly please forward it to us and we will update the app accordingly.

258x67_WPS_Download_cyan

Converting event based async calls to Task

Working on a new WinPhone app the other day I encountered an interesting problem which made me scratch my head quite a bit. I needed to read the list of appointments from the phone’s calendar. No big deal, right? Using the MVVM pattern I created a separate view model for my page and a service where I wanted to put all my phone specific stuff. The initial signature of my method was

public IEnumerable<Appointment> GetAppointments();

When trying to implement the method I found out that the calendar API uses the old style event based async pattern (EAP). I tried couple of different methods to wrap the async call and the result from the event in a single method call and failed miserably. After that I tried changing the method to the new async/await style. I knew I had to return a Task<T> so the signature of my method became

public Task<IEnumerable<Appointment>> GetAppointments();

But I still did not know how to make it work. And then I finally came across the TaskCompletionSource class that already solves my problem:

public Task<IEnumerable<Appointment>> GetAppointments()
{
    return Task.Run(() =>
    {
        var tcs = new TaskCompletionSource<IEnumerable<Appointment>>();

        var appts = new Appointments();
        appts.SearchCompleted += (o, e) =>
        {
            tcs.TrySetResult(e.Results);
        };
        appts.SearchAsync(DateTime.Today, DateTime.Today.AddDays(1), "appointments");

        return tcs.Task;
    });
}

Beautiful, isn’t it?

MvvmCross

In the seventies, just before I was born, Xerox (where I spent half of my career) invented MVC (model-view-controller). There are many variations of the pattern one of which is MVVM (model-view-viewmodel). While the differences between the various flavors of MVC, MVP, MVVM, etc. are in my opinion purely academic, there is absolutely no doubt in my mind that following a pattern like that can make the dev’s life a lot easier. There is somewhat of a high price for entry and a bit of a learning curve, but once you commit to it, there is no going back.

The essence of MVVM is that you separate your data (the model) from you presentation (the view) and you put all your UI logic in the view-model, where it can be developed and tested separately from the view itself. When targeting multiple platforms, in the ideal case you can reuse your models and view models across the different platforms and only code separate views.

There are several different MVVM libraries (MVVM Light, Caliburn, etc.) but it is important to understand that you do not need to bring a library in order to do MVVM, it just makes things easier. I’ve never used mvvmcross before but it promises to deliver databinding on windows, android and ios with reusable view models. It also contains a simple IoC container as well as few other tools and plugins.

mvvmcross is available as a nuget package. you add it to your projects, follow the provided (short) to-do list and you are in business. I was able to wire up a win store app with two views, view models, a service, etc. in maybe 15 or 20 minutes. Tomorrow – droids for breakfast 🙂 …

Multi-platform development with c#

The life of the mobile developer today is not easy at all. The market is segmented with at least 3 major players (counting Microsoft, not counting Blackberry). Clients/users want native look and feel and native performance on each platform. Tools like PhoneGap promising write-once-run-everywhere with html5/css/javascript unfortunately just don’t deliver on that promise.

In the recent years Microsoft, knowing that it is not quite winning the post-PC battle is trying to lure the developers to write apps for winphone/win8 by providing the best dev tools and a relatively easy path (with the partnership with xamarin) to porting apps from android or ios to winphone/win8.

Besides code reuse, there is another also important aspect of mobile (or not) development: using a modern and powerful language. In the recent years Java is trailing behind c# (catching up but still not there) and objective-c is so not in the same league as the other two that apple had to introduce a whole new language to replace it few month ago. And c# is almost everywhere – on the client, on the server, on a device, in the cloud – devs can use the same skills and the same tools for any type or size project. (in all honesty that mostly applies to javascript too – with the exception of the nice tools part).

So in the following days I’ll create a small demo of a LOB application on all mobile platforms using visual studio, c#, xamarin, an mvvm library, etc. My goal is to have a form and call a service with the data from the form writing as little code as reasonable and reusing it as much as possible.

Pipes for Windows 8

The Windows 8 version of Pipes is in the store and got a 1000 downloads in the first week. Working on the first update already with a “big orange button”™ for rate and review as well as few smaller improvements.

Download from Windows Store