Xamarin

FreshMvvm Quick Start Guide

FreshMvvm is designed to be easy and simple. So getting started is also fairly simple.

Step 1. Start new project

Start a new Xamarin.Forms Project using Portable Class Libraries.

Step 2. Obtain FreshMvvm from Nuget

Obtain FreshMvvm from Nuget by searching for FreshMvvm, make sure to do this on your Xamarin.Forms PCL project.

Step 3. Create QuoteList Page

Once you’ve got the packages you can then create your first Page and PageModel. In the Xamarin.Forms PCL project, let’s create a QuoteListPage.xaml and corresponding QuoteListPageModel.cs.

QuoteListPage.xaml

<?xml version="1.0" encoding="UTF-8"?>
<BasePage xmlns="http://xamarin.com/schemas/2014/forms" 
		xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
		x:Class="FreshMvvmSampleApp.QuoteListPage">
	<BasePage.Content>
		<ListView ItemsSource="{Binding Quotes}" SelectedItem="{Binding SelectedQuote}"  >
			<ListView.ItemTemplate>
				<DataTemplate>
					<TextCell Text="{Binding Total}" Detail="{Binding CustomerName}"></TextCell>
				</DataTemplate>
			</ListView.ItemTemplate>
		</ListView>
	</BasePage.Content>
</BasePage>

QuoteListPageModel.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
[ImplementPropertyChanged] // uses fody for property changed
public class QuoteListPageModel : FreshBasePageModel
{
    IDatabaseService _databaseService;
 
    public QuoteListPageModel (IDatabaseService databaseService) // injected from IOC
    {
        _databaseService = databaseService;
    }
 
    public ObservableCollection<Quote> Quotes { get; set; }
 
    public override void Init (object initData)
    {
        Quotes = new ObservableCollection<Quote> (_databaseService.GetQuotes ());
    }
 
    // Methods are automatically wired up to page
    protected override void ViewIsAppearing (object sender, System.EventArgs e)
    {
        CoreMethods.DisplayAlert ("Page is appearing", "", "Ok");
        base.ViewIsAppearing (sender, e);
    }
 
    protected override void ViewIsDisappearing (object sender, System.EventArgs e)
    {
        base.ViewIsDisappearing (sender, e);
    }
 
    // This is called when a page id pop'd
    public override void ReverseInit (object value)
    {
        var newContact = value as Quote;
        if (!Quotes.Contains (newContact)) {
            Quotes.Add (newContact);
        }
    }
 
    public Command AddQuote {
        get {
            return new Command (async () => {
                await CoreMethods.PushPageModel<QuotePageModel> ();
            });
        }
    }
 
    Quote _selectedQuote;
 
    public Quote SelectedQuote {
        get {
            return _selectedQuote;
        }
        set {
            _selectedQuote = value;
            if (value != null)
                QuoteSelected.Execute (value);
        }
    }
 
    public Command<Quote> QuoteSelected {
        get {
            return new Command<Quote> (async (quote) => {
                await CoreMethods.PushPageModel<QuotePageModel> (quote);
            });
        }
    }

Step 4. Create Quote Page

We will also need a page which shows the details of a quote. So we can create a QuotePage.xaml and a corresponding QuotePageModel.cs.

QuotePage.xaml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version="1.0" encoding="UTF-8"?>
<BasePage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="FreshMvvmSampleApp.QuotePage">
    <BasePage.Content>
        <StackLayout Padding="15">
            <Label Text="Quote Amount" ></Label>
            <Entry Text="{Binding Quote.Total}"></Entry>
            <Label Text="Customer Name" ></Label>
            <Entry Text="{Binding Quote.CustomerName}"></Entry>
            <Button Text="Save" Command="{Binding SaveCommand}"></Button>
            <BoxView HeightRequest="30"></BoxView>
            <Button Text="Test Modal" Command="{Binding TestModal}"></Button>
        </StackLayout>
    </BasePage.Content>
</BasePage>

QuotePageModel.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
[ImplementPropertyChanged]
public class QuotePageModel : FreshBasePageModel
{
    IDatabaseService _databaseService;
 
    public Quote Quote { get; set; }
 
    public QuotePageModel (IDatabaseService databaseService)
    {
        _databaseService = databaseService;
    }
 
    public override void Init (object initData)
    {           
        Quote = initData as Quote;
        if (Quote == null)
            Quote = new Quote ();
    }
 
    public Command SaveCommand {
        get {
            return new Command (async () => {
                _databaseService.UpdateQuote (Quote);
                await CoreMethods.PopPageModel ();
            });
        }
    }
 
    public Command TestModal {
        get {
            return new Command (async () => {
                await CoreMethods.PushPageModel<ModalPageModel> (null, true);
            });
        }
    }
}

 Step 5. Setup Navigation

You have the options of using a built-in navigation or implement your own.

With the built in navigation items you have the options of:

  1. FreshNavigationContainer – Which is a basic navigation with push and pop

  2. FreshMasterDetailNavigationContainer – Use for a master detail style app

  3. FreshTabbedNavigationContainer – User for a tabbed style app

  4. For some thing more complex you can implement IFreshNavigationService

In this sample we can use a tabbed style app. In your Xamarin.Forms PCL open your App.cs and in the constructor add the following code.

1
2
3
4
5
var tabbedNavigation = new FreshTabbedNavigationContainer ();
 
tabbedNavigation.AddTab<ContactListPageModel> ("Contacts", null);
 
MainPage = tabbedNavigation;

And that’s it, we now have made the first steps to implementing FreshMvvm. If you wanted a different Navigation style then you could use one of the other types of built in Navigation or even implement your own.

The great sample project similar to this can be found in the sample directory on the project.

https://github.com/rid00z/FreshMvvm

 

FreshMvvm – A Mvvm Framework designed for Xamarin.Forms

Now available via Nuget FreshMvvm is a Mvvm framework that’s designed specifically for Xamarin.Forms. The reason I say it’s designed for Xamarin.Forms is because it plays on Xamarin.Forms strengths and fills in ONLY the missing parts. It has a requirement for Xamarin.Forms and therefore is smart and can do thing such as wiring up the BindingContext and Page events.

Some of the feature for FreshMvvm include:

  • PageModel to PageModel Navigation

  • Automatic wiring of BindingContext

  • Automatic wiring of Page events (eg appearing)

  • Basic methods on PageModel (init, reverseinit)

  • Built in IOC Container

  • PageModel Constructor Injection

  • Basic methods available in Model, like Alert

  • Built in Navigation containers for SimpleNavigation, Tabbed and MasterDetail

How does it compare to other Mvvm options?

  • It’s super light and super simple

  • It’s specifically designed for Xamarin.Forms, nothing else does this currently

  • Designed to be easy to learn and develop (great when your not ready for RxUI)

  • Uses a Convention over Configuration

The Story

I was part-way into a Xamarin Traditional application when Xamarin.Forms was released. I wanted to move the project onto Xamarin.Forms but on that project I was using MvvmCross. At that time MvvmCross had no support for Xamarin.Forms, so I had the option of 1) adapting MvvmCross, 2) finding an alternative or 3) rolling my own Mvvm. The best part about MvvmCross was it’s two-way databinding to the native iOS/Android controls but since Xamarin.Forms already had the Databinding builtin, that wasn’t useful and the size with MvvmCross was an overhead when I didn’t require it. I also wasn’t able to find an alternative that I could easily move to. So that I could keep it simple and flexible, I ended up rolling my own Mvvm.

It’s grown up from this post on rolling your own Mvvm for Xamarin.Forms. I try hard to keep the simplicity of rolling your own Mvvm for Xamarin.Forms.

It was never a plan to create a framework but after presenting my Mvvm solution at a few events, I found many people wanted it and seemed to be really interested in it. Also considering I’ve been using this Framework in all my projects from the start of Xamarin.Forms I know that it works, so I created FreshMvvm and that’s how it was born.

Conventions

This Framework, while simple, is also powerful and uses a Convention over Configuration style.

Note Different to standard naming conventions, FreshMvvm uses Page and PageModel instead of View and ViewModel, this is inline with Xamarin.Forms using Pages

  • A Page must have a corresponding PageModel, with naming important so a QuotePageModel must have a QuotePage The BindingContext on the page will be automatically set with the Model

  • A PageModel can have a Init method that takes a object

  • A PageModel can have a ReverseInit method that also take a object and is called when a model is poped with a object

  • PageModel can have dependancies automatically injected into the Constructor

Navigation

The Primary form of Navigation in FreshMvvm is PageModel to PageModel, this essentially means our views have no idea of Navigation.

So to Navigate between PageModels use:

1
await CoreMethods.PushPageModel<QuotePageModel>(); // Pushes on navigation stack
1
await CoreMethods.PushPageModel<QuotePageModel>(null, true); // Pushes a Modal

The engine for Navigation in FreshMvvm is done via a simple interface, with methods for Push and Pop. Essentially these methods can control the Navigation of the application in any way they like.

1
2
3
4
5
public interface IFreshNavigationService
{
   Task PushPage(Page page, FreshBasePageModel model, bool modal = false);
   Task PopPage(bool modal = false);
}

This is what you as a consumer will need to implement, and then register in the IOC Container.

Within the PushPage and PopPage you can do any type of navigation that you like, this can from a simple navigation to a advanced nested navigation.

The Framework contains some built in Navigation containers for the different types of Navigation.

Basic Navigation – Built In

1
2
3
4
5
var page = FreshBasePageModel.ResolvePageModel<MainMenuPageModel> ();
 
var basicNavContainer = new FreshNavigationContainer (page);
 
MainPage = basicNavContainer;

Master Detail – Built In

1
2
3
4
5
6
7
8
9
var masterDetailNav = new FreshMasterDetailNavigationContainer ();
 
masterDetailNav.Init ("Menu");
 
masterDetailNav.AddPage<ContactListPageModel> ("Contacts", null);
 
masterDetailNav.AddPage<QuoteListPageModel> ("Pages", null);
 
MainPage = masterDetailNav;

Tabbed Navigation – Built In

1
2
3
4
5
6
7
var tabbedNavigation = new FreshTabbedNavigationContainer ();
 
tabbedNavigation.AddTab<ContactListPageModel> ("Contacts", null);
 
tabbedNavigation.AddTab<QuoteListPageModel> ("Pages", null);
 
MainPage = tabbedNavigation;

Implementing Custom Navigation

It’s possible to setup any type of Navigation by implementing IFreshNavigationService.There’s a sample of this in Sample Application named CustomImplementedNav.cs.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/// <summary>
/// This is a sample custom implemented Navigation. It combines a MasterDetail and a TabbedPage.
/// </summary>
public class CustomImplementedNav : Xamarin.Forms.MasterDetailPage, IFreshNavigationService
{
    FreshTabbedNavigationContainer _tabbedNavigationPage;
    Page _contactsPage, _quotesPage;
 
    public CustomImplementedNav ()
    {   
        SetupTabbedPage ();
        CreateMenuPage ("Menu");
        RegisterNavigation ();
    }
 
    void SetupTabbedPage()
    {
        _tabbedNavigationPage = new FreshTabbedNavigationContainer ();
        _contactsPage = _tabbedNavigationPage.AddTab<ContactListPageModel> ("Contacts", null);
        _quotesPage = _tabbedNavigationPage.AddTab<QuoteListPageModel> ("Quotes", null);
        this.Detail = _tabbedNavigationPage;
    }
 
    protected void RegisterNavigation()
    {
        FreshIOC.Container.Register<IFreshNavigationService> (this);
    }
 
    protected void CreateMenuPage(string menuPageTitle)
    {
        var _menuPage = new ContentPage ();
        _menuPage.Title = menuPageTitle;
        var listView = new ListView();
 
        listView.ItemsSource = new string[] { "Contacts", "Quotes", "Modal Demo" };
 
        listView.ItemSelected += async (sender, args) =>
        {
 
            switch ((string)args.SelectedItem) {
            case "Contacts":
                _tabbedNavigationPage.CurrentPage = _contactsPage;
                break;
            case "Quotes":
                _tabbedNavigationPage.CurrentPage = _quotesPage;
                break;
            case "Modal Demo":
                var modalPage = FreshPageModelResolver.ResolvePageModel<ModalPageModel>();
                await PushPage(modalPage, null, true);
                break;
            default:
            break;
            }
 
            IsPresented = false;
        };
 
        _menuPage.Content = listView;
 
        Master = new NavigationPage(_menuPage) { Title = "Menu" };
    }
 
    public virtual async Task PushPage (Xamarin.Forms.Page page, FreshBasePageModel model, bool modal = false)
    {
        if (modal)
            await Navigation.PushModalAsync (new NavigationPage(page));
        else
            await ((NavigationPage)_tabbedNavigationPage.CurrentPage).PushAsync (page); 
    }
 
    public virtual async Task PopPage (bool modal = false)
    {
        if (modal)
            await Navigation.PopModalAsync ();
        else
            await ((NavigationPage)_tabbedNavigationPage.CurrentPage).PopAsync (); 
    }
}

Inversion of Control (IOC)

So that you don’t need to include your own IOC container, FreshMvvm comes with a IOC container built in. It’s using TinyIOC underneith, but with different naming to avoid conflicts.

To Register services in the container use Register:

1
FreshIOC.Container.Register<IDatabaseService, DatabaseService> ();

To obtain a service use Resolve:

1
FreshIOC.Container.Resolve<IDatabaseService> ();

*This is also what drives constructor injection.

PageModel – Constructor Injection

When PageModels are pushed services that are in the IOC container can be pushed into the Constructor.

1
2
3
4
5
6
7
8
public class ContactListPageModel : FreshBasePageModel
{
    IDatabaseService _databaseService;
 
    public ContactListPageModel (IDatabaseService databaseService)
    {
        _databaseService = databaseService;
    }

PageModel Important Methods

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/// <summary>
/// The previous page model, that's automatically filled, on push
/// </summary>
public FreshBasePageModel PreviousPageModel { get; set; }
 
/// <summary>
/// A reference to the current page, that's automatically filled, on push
/// </summary>
public Page CurrentPage { get; set; }
/// <summary>
/// Core methods are basic built in methods for the App including Pushing, Pop and Alert
/// </summary>
public IPageModelCoreMethods CoreMethods { get; set; }
 
/// <summary>
/// This method is called when a page is Pop'd, it also allows for data to be returned.
/// </summary>
/// <param name="returndData">This data that's returned from </param>
public virtual void ReverseInit(object returndData) { }
 
/// <summary>
/// This method is called when the PageModel is loaded, the initData is the data that's sent from pagemodel before
 
/// </summary>
/// <param name="initData">Data that's sent to this PageModel from the pusher</param>
public virtual void Init(object initData) { }
 
/// <summary>
/// This method is called when the view is disappearing.
/// </summary>
protected virtual void ViewIsDisappearing (object sender, EventArgs e)
{
 
}
 
/// <summary>
/// This methods is called when the View is appearing
/// </summary>
protected virtual void ViewIsAppearing (object sender, EventArgs e)
{
}

The CoreMethods

Each PageModel has a property called ‘CoreMethods’ which is automatically filled when a PageModel is pushed, it’s the basic functions that most apps need like Alerts, Pushing, Poping etc.

1
2
3
4
5
6
7
8
9
10
public interface IPageModelCoreMethods
{
   Task DisplayAlert (string title, string message, string cancel);
   Task<string> DisplayActionSheet (string title, string cancel, string destruction, params string[] buttons);
   Task<bool> DisplayAlert (string title, string message, string accept, string cancel);
   Task PushPageModel<T>(object data, bool modal = false) where T : FreshBasePageModel;
   Task PopPageModel(bool modal = false);
   Task PopPageModel(object data, bool modal = false);
   Task PushPageModel<T>() where T : FreshBasePageModel;
}

 

Sample PageModel

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
[ImplementPropertyChanged] // Use Fody for Property Changed Notifications
public class QuoteListPageModel : FreshBasePageModel
{
   IDatabaseService _databaseService;
 
   //These are automatically filled via Constructor Injection IOC
   public QuoteListPageModel (IDatabaseService databaseService)
   {
       _databaseService = databaseService;
   }
 
   public ObservableCollection<Quote> Quotes { get; set; }
 
   public override void Init (object initData)
   {
       Quotes = new ObservableCollection<Quote> (_databaseService.GetQuotes ());
   }
 
   //The Framework support standard functions list appeaing and disappearing
   protected override void ViewIsAppearing (object sender, System.EventArgs e)
   {
       CoreMethods.DisplayAlert ("Page is appearing", "", "Ok");
       base.ViewIsAppearing (sender, e);
   }
 
   protected override void ViewIsDisappearing (object sender, System.EventArgs e)
   {
       base.ViewIsDisappearing (sender, e);
   }
 
   //This is called when a pushed Page returns to this Page
   public override void ReverseInit (object value)
   {
       var newContact = value as Quote;
 
       if (!Quotes.Contains (newContact)) {
           Quotes.Add (newContact);
       }
   }
 
   public Command AddQuote {
       get {
           return new Command (async () => {
               //Push A Page Model
 
               await CoreMethods.PushPageModel<QuotePageModel> ();
           });
       }
   }
 
   Quote _selectedQuote;
   public Quote SelectedQuote {
       get {
           return _selectedQuote;
       }
       set {
           _selectedQuote = value;
           if (value != null)
               QuoteSelected.Execute (value);
       }
   }
 
   public Command<Quote> QuoteSelected {
       get {
           return new Command<Quote> (async (quote) => {
               await CoreMethods.PushPageModel<QuotePageModel> (quote);
           });
       }
   }
}
 
So please take a look at it on <a href="https://github.com/rid00z/FreshMvvm">github</a> or nuget. 
 
If you have any questions please contact me via <a href="http://www.michaelridland.com">http://www.michaelridland.com</a>. 
 
Thanks
 
Michael

Top 10 Tips for Building an Apple Watch App

Unless you’ve been living under a rock then you already know about the Apple Watch, have ordered one or your wearing one right now. At the moment I’ve been getting my head around how WatchKit apps will work for my the apps of my clients. The truth be told is that not all apps need a WatchKit component, but many do.

After using an Apple Watch in real, one thing I noticed was the inability to edit calendar events, huh? You can add them but you can’t edit them. Actually in regards to most of the built in apps, there isn’t alot of editing operations. After a lengthy conversation with a product manager at Apple, Apple see’s the Watch primarily being used for super super short intervals, 3-5 seconds. Quickly reading an email or replying to a text message. So essentially we need to keep this in mind when we develop any Watch Apps.

1. Re-think your design from the ground app, don’t just take your Phone app and the images from that app and display it on the watch.

2. Five-Ten Seconds is the amount of time you should keep a users attention, anything more and they should pull their phone out.

3. Bluetooth is slow, and even slower on the device. You need to keep everything lean, compress images, keep images the exact size and no bigger, only update items that have changed (if you even need to). Do you need to upload images or can you use text?

4. Keep is simple, only show the exact data a user needs. If for example your using TripAdvisor, what does the user need to see? The rating, the name and address maybe one more thing, no need to overload the screen you’ve only got 5 seconds anyway.

5. The watch is slow and your app needs to be fast. Lazy-Load for fast startup and then background pre-load where possible, cache where possible, show splash/loading screens. Also another reason to use less content in your apps.

6. Use hand off, this is essential, if you’ve given a user a notification and they jump into your watch app it’s likely they might want to continue the action in further detail on their device. An example would be a user looking at a email and might want to reply on the phone, when the user opens their phone then it must deep link into the mail app with the email open (it already does this btw). This is all available to you as a developer via the WKInterfaceController.

7. Let the iPhone do the work. Communication between your iPhone app and watch app is simple, so don’t be afraid to pass tasks/operations back to the phone.

8. Use dictation – User input is a keystone of useful applications, so while you’ve only got a ‘short time’ with the user it’s still possible to get some input.

9. You only have 10 UI elements in Total, but they can be deeply nested and can be used to create advanced views.

10. Get a Watch and use it. You can’t expect that you’ll be able to create a good user experience unless you live the same user experience. As the saying goes eat your own dog food.

The Apple watch is only a first release product, it’s just a given that the apps and device aren’t going to be overly refined but it’s definitely a glimpse into the future. Oh and FYI it’s not called a iWatch, it’s not, so please don’t call it a iWatch.

Please drop me an email if you have any questions or queries about the Apple Watch, I’m always keen to help people.

Thanks

Michael

 

 

WWDC 2015 for a Xamarin Developer n+1 Series

WWDC-2015-invitation

How much can happen in a week? … well a lot, last week I was honoured to be announced as a Xamarin MVP, I purchased my first Apple Watch and… I’ve been lucky enough to win a golden ticket for the Apple World Wide Developers conference (WWDC). When I say win I mean pay apple $1999 AUD for the privilege to attend the conference. The ‘winning’ part is that there’s 9 million apple developers and many thousands apply to attend, so apple have a lottery in which attendee’s are selected at random.

WWDC is on June 8th – June 12th 2015, in San Francisco and will take place at Moscone West. There’s likely to be some new software announcements for iOS and OSX, possibly some more watch features and maybe even a 4K Apple TV. There’s over 100 technical sessions, 1000’s of apple engineers, hands-on labs and the apple design awards.

As an engineer I’m really keen to attend the technical sessions and get my hands dirty with some hands-on labs, maybe a little swift to c# conversion will be in order.

Given that I’ve been lucky enough to win a ticket to WWDC this year I thought it would only be fair if I shared the journey with other Xamarin developers. I’ll be giving daily overviews of different announcements and if possible providing technical detail from the conference, converting the swift applications into C# and F#.

This series of posts will be named ‘WWDC for a Xamarin Developer n+1’… Stay tuned… I think we’ll have some fun!

Michael

50 Shades of Xamarin

One of my favourite parts of Xamarin is it’s flexibility. Using Xamarin and Xamarin.Forms you can actually jump between Native API’s, Forms APIs and Html5 (generated at locally or on the server). This flexibility has enabled me to develop a range of different solutions for clients based on their situation, I wasn’t sandboxed to Native or PhoneGap, I could mash up anything. The best part is that you can mix these up to with seamless experiences between them.

Here’s a graph showing the percentages of technologies I’ve used in my most recent Xamarin Apps, you’ll see some are Forms only, some are Native only, some are a mix of all.

Do you have some Html5 that’s already mobile friendly? Go ahead use Xamarin then you’ll also be able to add in a sexy Native Menu using Xamarin Traditional
Do you have a Xamarin traditional app but need some Crud forms? Go ahead add in Xamarin.Forms, it can be used in Micro Areas of your application.
Do you have a Xamarin.Forms app but need to add a little HTML? Go ahead with Xamarin you can easily show Html5.

With Xamarin the Mobile world is your oyster and your possibilities endless…

50 Shades of Xamarin

 

Thanks

Michael

Debugging Xamarin app network calls on OSX with iOS Simulator

This blog is a quick tip for people trying to debug network calls in their Xamarin/Xamarin.Forms app while on OSX.

While we take it for granted to debug network calls in our web browsers these days, when it comes to a native app it’s not so apparent, especially if you’re on OSX. Note*, this post is for OSX if your using Windows this forum post might help.

In my research I couldn’t find a free debugging proxy but the old faithful Charles Debugging proxy works well.

While you think it might be as simple as opening up Charles there’s actually a few quirks.

Using Charles with iOS Simulator

Thankfully the latest version of Charles proxy can automatically register the certificate on your simulator devices. To do this open Charles and from the Help menu option select ‘Install Charles CA SSL Certificate in iOS Simulators’.

Screen Shot 2015-03-15 at 8.53.09 pm

… run the app in the iOS simulator and that should work right? wrong!

If you’re using Xamarin/Xamarin.Forms and the standard System.Net.HttpClient then this code is fully managed code and will not communicate with the local OS to discover the proxy settings. Luckily we have a little saving grace in that the HttpClient allows for different underlying network implementations, in iOS the native network library is called CFNetwork library. Miguel has previously blogged about this.

Now that’s great but how do I get it working in my Xamarin.Forms app? Well considering the CFNetwork is a Native iOS binding we can’t actually reference it from our Forms PCL, we need to create a dependancy that’s sets it up for us.

It’s the standard way to create a dependancy.

1. Define a interface in our PCL

1
2
3
4
public interface IHttpClientHandlerFactory
{
    HttpClientHandler GetHttpClientHandler();
}

2. Create the Native implementation of the interface

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[assembly: Xamarin.Forms.Dependency(typeof(HttpClientHandlerFactory))]
 
namespace App.iOS
{
    public class HttpClientHandlerFactory : IHttpClientHandlerFactory
    {
        public HttpClientHandler GetHttpClientHandler()
        {
            return new System.Net.Http.HttpClientHandler {
                Proxy = CoreFoundation.CFNetwork.GetDefaultProxy(),
                UseProxy = true
            };
        }
    }
}

3. Use the Native implementation

Note* as I’ve only implemented this in my iOS app I’ve got logic which only uses the custom HttpClientHandler when the factory exists.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var handlerFactory = Xamarin.Forms.DependencyService.Get<IHttpClientHandlerFactory> ();
if (handlerFactory == null) 
{
    client = new HttpClient() {
        BaseAddress = new Uri (ServiceUrl),
    };
} 
else 
{
    var handler = handlerFactory.GetHttpClientHandler ();
    client = new HttpClient(handler) {
        BaseAddress = new Uri (ServiceUrl),
    };
}  

Once you’v done that, first run Charles and then debug your app in the simulator and you should see the network calls come in.

Happy Debugging…

How to WIN with Xamarin.Forms

‘Xamarin is not ready’ a statement I heard recently. What do you think?

Anyone that’s experienced in Xamarin knows this is an inaccurate statement, there’s been a huge amount of successful Native applications built with Xamarin including apps like RDIO, Storyo and iCircuit and apps from large corporations like Banks, Tesco and Microsoft. You probably already know I’m a Xamarin lover, but in this blog I’m going to give you a real honest view.

While the statement is inaccurate I can also understand how someone could come to this conclusion, especially if their first experience is with Forms and even more so if they’ve had Native app development experience before. The reason for this is that 1) Xamarin.Forms is still only months old (some argue it’s still beta quality), to be perfectly honest when Xamarin.Forms was released it did kind of match the promises but it was buggy and lacking features so it was basically a beta release (when compared with Microsoft products). 2) When you come from a experienced App development background there’s certain ways you want an app to work and with Forms it can be difficult to break out of the standard API and do you own thing. Initially I struggled with this and was a little frustrated. I eventually learnt to ‘not to fight the framework’ As Xamarin.Forms is a abstract API which means certain there’s ways it works and strengths/weaknesses, it’s a trade off.

The first thing you need to understand is that Xamarin is not Xamarin.Forms, the core of what made Xamarin famous is ‘Xamarin  Traditional’ eg Xamarin.iOS and Xamarin.Android. ‘Xamarin Traditional’ is absolutely rock solid, when you develop an app in ‘Xamarin Traditional’ it can be as fast, stable and functional as any Native app.

While there’s issues with Forms, I’ve adopted it in the majority of apps. Why? Because even though it kinda sucks, it sucks less than all the other options like 1) building/coding it on all platforms 2) a clunky PhoneGap app. If you know how to harness it’s goods part and avoid the bad parts then it’s actually very powerful, especially how you can jump in/out of Native Code/Bind Native libraries and even use HybridWebViews. Over the past 6 months I’ve delivered many Forms apps for clients so below I’m going to give some tips on how you can WIN with Xamarin.Forms.

Understand what the Framework can and can’t do

Xamarin.Forms is an abstraction on the top of Xamarin.iOS and Xamarin.Android it’s major advantage is that you can program to a single api(with Databinding) and have it render natively, but there’s a bunch of caveats for example 1) ListView performance isn’t great, so it’s not recommended for super large lists of data 2) Sometimes renderering of pages with many controls is slow. Now both these issues can be worked around, in both these cases you can use a custom renderer.

Don’t fight the Framework

This is a big one others have also commented on this. This one become especially challenging for people experienced in native apps/xamarin traditional as normally they(like me) bring in certain expectations and ways they want things to work. In Xamarin.Forms you need to let go any preconceptions of how you want something to work, you need to learn the Xamarin.Forms way to do it. If you try to treat Xamarin.Forms like a iOS API then it’s going to be painful.

Use the Forums

One of the great places to keep updated and have questions answered is the Xamarin forums, it’s the most active place for Xamarin.Forms even more active than StackOverflow. I definitely recommend spending some time in the forums, new releases and updates are notified on these forums. The address is forums.xamarin.com.

Learn from github

As most developers know the best way to learn code is to read and write code. When learning Xamarin.Forms I found the github the most useful resource, James and Craig from Xamarin have some great github repos and there’s also the official one from Xamarin.

Xamarin.Forms Xaml is not WPF

WPF is Xaml and so it Xamarin.Forms so it makes logical sense that if your good at WPF you’ll be good at Forms, but this far from the truth now and probably into the future. WPF was built for a single platform and built by the creators of that platform(Microsoft) with a huge amount of resources, so even on v1 it was very functional and stable. Xamarin.Forms is very different for a few reasons 1) it was built for multiple platforms 2) it was built by a small team and released very early 2)  it still suffers low-common dominator issues. As it stands if you’re building a serious app with Xamarin.Forms it’s likely you’ll hit the limits of Forms in the first few days and you’ll end up spending a lot of time in custom renders programming the Native API. Which isn’t a problem really, as the native API’s are great, it’s only a problem if you think you whole app is going to be Xaml and a WPF developer is going to rock at it.

Use it on the correct app

Using Xamarin.Forms is a trade off, the advantage of Forms is that you’ve got a single API which maps to native controls but the disadvantage is that it’s a abstract API and your bound to the API unless you want to do custom renderers. Taking the RunKeeper app for an example, as it stands in Jan 2015 in Xamarin.Forms you definitely wouldn’t be able to pull off the RunKeeper app and the best option is to use Xamarin.Traditional.

Dig into the source

In Xamarin Studio your able to look at the source for Xamarin.Forms using the built in Assembly viewer and there’s also products that allow you to decompile source such as reflector or ILSpy.

In a normal work day on Xamarin.Forms I’ll dig into a custom renderers code at least once. I found this insanely useful as it allows me to understand what’s going on underneath the surface in Xamarin.Forms and work around issues or come up with creative solutions to issues.

Some bonus places to keep upto date with Xamarin.Forms

Xamarin Weekly Newsletter – always manages to find some blogs that I’ve missed.

Xamarin Documentation – it’s a bit behind the githubs/forums but it’s still good

Planet Xamarin – this is the compiled blogs of many Xamarin Guru’s

Sydney Xamarin Guy – can’t forget my blog of course

Hopefully this blog post has giving you some insights into Xamarin.Forms and how to be productive with Xamarin.Forms.

Thanks

Michael

 

 

 

 

Evolve 2014 Summary: Extending Xamarin.Forms with Custom Controls – Jason Smith, Xamarin

I’m going to be doing a series of blog posts on the Xamarin Evolve 2014 Conference, they’ll be detailed summaries of the sessions.

My first one, Extending Xamarin.Forms with custom controls by Jason Smith, was a very very good session. Jason is a lead dev on Xamarin.Forms, this is fairly clear in the session as he goes into great details and his Q&A was amazingly insightful.

Intro

To begin with Jason explains that the amount of APIs on iOS and Android are huge.

  • iOS 33,000 APIs
  • Android 40,000 APIs

He then shows a quote from Albert Einstein.

“Everything should be made as simple as possible, but not simpler” – Albert Einstein

Jason then explains that “Writing code is about managing complexity”,  “Complexity is what makes your app special, but complexity is also what makes your app hard to develop.”

  • “Complexity is a source of bugs”
  • “Complexity is what makes your app amazing”
  • “Complexity is a necessary evil”

I understand Jason’s point in this, as personally I’ve always thought ‘managing complexity’ was a important part of what software developers do. It’s also very true in Xamarin and Xamarin.Forms as in order to build apps that users love we need to add this complexity.

Custom Renderers

A renderer is what turns a button into a button:

To start off Jason shows a basic framework of an app built with Xamarin.Forms, it’s a very basic app. He then proceeds to tell us how to use the built in styles to do styling for Xamarin.Forms. Once done the app looks nicely styled but Jason then moves on to show us how it can be taken to the next level with custom renderers.

Jason explains that Export Renderer is the bases of Renderers, he also explains that the reason Export Renderer is on the assembly is because it’s more performant to read attributes from the assembly that the classes.

Jason’s first sample of a custom renderer is a CircleImageRenderer that inherits from ImageRenderer. I’ll include some important points that Jason makes.

The OnElementChanged method is the most important method when using custom renderers. It tells you the element your watching has changed, therefore you must adapt and change. It’s possible for a ListView to reuse renderers rather than new up new renderers. You must be aware of this. He describes the best way to handle this, as per the screenshot further down this post.

When handling the OnElementChanged event you initially check if the Control is null, then if the old element is null unhook old events, if the new element is not null then hook the new events.

Jason then demonstrates a loading view custom renderer,  interestingly Jason uses a single ContentPage and fades in the loading view as the content then hides it and swaps the content with the view he actually wants.

Jason claims it’s the coolest loading view of all time and it’s actually fairly impressive, well for geek programmers anyway.

He then continues and explains a bug that we might hit when developing Xamarin.Forms Custom Controls.

OnElementChanged event gets called many times, well as many times as we choose. Sometimes it’s once and sometimes it’s hundreds. But you do need to handle this, as SetNativeControl needs to be set one time.

Bad Code

Screen Shot 2014-12-10 at 8.30.28 am

Better Code

Screen Shot 2014-12-11 at 8.31.59 am

 

The (good) Pattern:

– First check if your control is null, if null create a new control.

– If your old element is not null, then unsubscribe

– If your new element is not null, then subscribe

 

Q & A:

Attendee: Is the only way to set renderers is to export them?

Jason: The answer is yes, renderers are only associated through exporting. Jason also makes a point saying that *dont override the default renderers, make a custom subclass.

The attendee then suggests that you can’t use two renderers for a single control. Jason confirms this is correct.

 

Attendee: An attendee wanted to know about the roadmap in regards to transitions.

Jason: It’s on the radar and it’s something we want to do.

 

Attendee: Is there any plans to swap out the service locator so we could have multiple renderers for a control?

Jason: At the moment it’s not possibly and not exactly on the radar either.

 

Attendee: Mentions that Jason did a great presentation and doesn’t give himself enough credit, as Jason and his team has really built something special.

 

Attendee: What about extending layouts?

Jason: At the moment you can subclass layouts, the Layout is internal but soon it will be exposed to you.

 

Attendee:  So in layouts we can add our own sprite kits etc

Jason:  Yes, this should work and be fairly easy

 

Attendee: Can you explain what’s in 1.3 release

Jason: Styles, Behaviours, Triggers, Dynamic Resources, Styles Based on Dynamic Resources (which is new to the whole world).

 

Attendee: Is there any plans to add more gestures to Xamarin.Forms? What about popups?

Jason: Popups will be added. Generally people want two gestures Long Tap and Swipe. Well we’ve got something better coming context actions, so on your cell you set the context action and easily add mailbox swipe style cells.

*I’ll be very interested in seeing what context actions are, I feel like they could be something amazing.

 

Attendee: Wondering why you created Xamarin.Forms on Android to be a single Activity rather than multiple activity?

Jason: At the time we started fragments weren’t fully back ported. Google was promoting the single activity approach. The navigation in Activities didn’t fully map to the Xamarin.Form navigation.

 

Attendee: We use alot of 3rd party components and many time these 3rd part components require a native View or ViewController. At the moment we use a Custom Renderer as this is the only way to do this right now, will there be better ways in the future, some sort of Native Hookiness?

Jason: Yes there will be some Native Hookiness.

 

Attendee: Is there intention to make some sort of UI Designer, Xamarin.Forms Designer.

Jason: The big question, the elephant in the room. There is an intention is to make something that will really help with designing Xamarin.Forms, will that be a drag and drop designer? Probably not! Why, because it’s actually not that useful in a cross platform scenario, because you want a live preview. What you really want is live Xaml coding and a popup of the stuff on all three platforms. I’m not announcing anything coming at any point other than saying it would be really stupid for us not to do it. That is not a blood contract so please don’t kill me.

 

Attendee: I notice a lot of the support around Xamarin.Forms is centred around phones, do you think Xamarin.Forms will be a good solutions for tablets?

Jason: It means that tablets are supported but it’s not automatically adapted to it. It’s your job to adapt Xamarin.Forms to tablet. Which basically means you need to change your layouts to adapt to the tablet.

*Which is how it always is/was on mobile development.

 

Summary

This was a great video for myself as it was related to the work I do every day, it also provided some great insights into the future of Xamarin.Forms.

Thanks to Jason for the great presentation.

Here’s a link to the video if you want to watch.

Michael

 

 

 

Hack Day Sydney – 6/12/14 – call for presentations!

It’s nearly that time again! The 6/12/14 will be the next Xamarin Hack Day in Sydney.

This time we’re going to have two tracks a ‘introductory’ and a ‘advanced’ track. We need presenters for both.

I’ve included a basic layout below:

Introductory:

The introductory will have a similar format to the latest one in Brisbane.

Advanced:

I’m keen to hear about any type of presentation. It could be Xamarin.Forms, Windows Phone, Android/iOS, deployment, CI, F#, C#, ReactiveUI, Mono, IDE etc.

If you want to present twitter me @rid00z or email me here: http://www.michaelridland.com/about/

If you want to attend then signup at the website.

ps, if your in Melbourne there’s a hack day in the weekend before 29/11/14. 

 

Should I use Xamarin for Mobile Development? YES you should!

Should I use Xamarin for Mobile Development?  – This a very important question and a question that can cost you alot of time and money if you get it wrong. After wasting many months of my time playing with open web platforms I eventually found Xamarin and since then I’ve not found anything that compares.

So that answer is YES! In my opinion Xamarin is hands down one of the best mobile development platforms available in the market today. Many people don’t know what they’re missing out on by not using Xamarin so I’m going to highlight some reasons I think people should be using Xamarin.

1) It’s Native but with 80%+ code share?

So for those that aren’t aware of Xamarin or how it works, Xamarin allows you to develop apps for iOS, Android and Mac from a single code base. When I say this I don’t mean in a webview or customised API, it actually uses the Native APIs. So for example when developing on Xamarin.iOS you’ll be using UIKit which is the same API that a native developer would be using.

2) C# and F# are Modern languages

C# might not be the hipster language of the year but it is a continually evolving language with solid features like type inference, dynamic types,  language integrated query (LINQ), async/await and first class functions. C# is designed for developing large robust applications. And for the functional types there’s F#.

Both languages have been aggressively developed for many years and it’s not slowing down, C# 6 and F# 4 are soon to be released. If you’ve seen C# a few years ago I encourage you to give it another go as it’s evolved in leaps and bounds.

3) async/await

.. ‘wait but javascript is all async’ i hear you say…  C#/F# async/await is different to what people normally think async is. C#/F# async/await tackles the callback hell problems in rich clients, anyone who works with rich clients will know of these problems. This is a problem that’s attempted to be solved with promises and generators but neither are at the level of async/await.

Here’s a little before/after sample:

Before:

doAsync1(function () {

doAsync2(function () {

doAsync3(function () {

doAsync4(function () {

      })
     })
   })
})
After:

await doAsync1()
await doAsync2()
await doAsync3()
await doAsync4()

4) Watches, Google Glass wearables and the future of devices.

In case you haven’t noticed the future isn’t just mobiles it’s wearables, devices and IOT. Xamarin has same day support for all these platforms including android wear, google glass, Amazon TV and more. As I’ve said before Xamarin uses the Native APIs and compiles down to native so using Xamarin you’re in the perfect position develop all modern platforms.

5) It’s ready now!

All the time I hear people say ‘html is a fast moving target’ or ‘it will get there eventually’. Xamarin is here now, it’s Native and it’s cross platform. Why wait to have a great app when you can have it now and as a bonus know that your application is future proof for future devices.

6) It’s fast and stable

From personal experience the Xamarin traditional (Xamarin.iOS and Xamarin.Android) platform is solid, fast and stable. You’d be hard pressed to find a problem with the core parts of the platform, any app bugs will likely be your own bugs.

7) Documentation

The documentation for Xamarin is solid and there’s 100s of sample app on github. Provided by Xamarin and others in the community.

8) Xamarin.Forms

So how about 100% codeshare and still be Native? Xamarin.Forms allows you to program against a single API and have that single API mapped to native controls on each platform. Hanselman describes it well, ‘Write Once Run Everywhere AND Be Native’.

It’s still early days for the product but the top component developers like Telerik and DevExpress are already developing components for Xamarin.Forms.

9) It’s the best of all worlds (Hybrid and Native)

If you’ve taken a look at my Xamarin mashup blog you’d already know that the possibilities with Xamarin are vast, you can essentially create your own Cordova and you can completely integrate it with your C# Mvvm/c# Native Code. So you have the full power of the .net framework to build your client application architecture which becomes very useful when you have complex requirements like Offline.

10) Large Community

Xamarin uses the .net framework and because of this it’s inherited the pre-existing community, this means that even though it’s a fairly new platform we already have support for Awesome projects like Json.net, Fody and ReactiveExtensions/ReactiveUI.

11) Profitable Innovative Company

Xamarin as a company has a passion for enabling mobile developers to deliver leading experiences. Their products cost money Yes.. but it’s good for us as customers. I see many people complain about the pricing but Xamarin charging money for products allows them to put money back into building amazing products for us. This year at Evolve Xamarin released some great new products including Insights – Analytics Cloud Service, a faster Android emulator, Test Cloud and a performance profiler. In the future Xamarin is on the rise and this means our tools are only going to get better and better.

This is why I choose Xamarin and I think you should too….

If you have any questions regarding Xamarin or need any help please contact me I’m always happy to help.

Thanks

Michael