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

Ultimate guide to ASP.NET MVC and Xamarin.Forms Mashups

In this blog I show you how to take an asp.net application and then code share both Razor Views and Business logic with a Xamarin.Forms native application. This integration will allow full sharing between the application, so changes to the Razor views or Business Logic will apply to both projects. The mobile application will also work completely offline in which the Razor Views and Business Logic run completely locally on the device.

And that’s just the start of it! Imagine being able to jump in and out of native/web elements, sharing razor views when it’s a good fit and then jumping into a gorgeous native UI when you like.

This blog takes a already existing ASP.NET MVC project that’s been setup as a sample application with typical Views, Script and Styles.

Video: Seamless Native and Hybrid

Video: 3Way Communication between C#/Native and Hybrid/JS Integration

Diagram: Shared Files Setup

Hybrid Razor File Setup

Diagram: Offline Support with Shared Views and Logic

Offline Mode

Step 1. Create new solutions

Create a new Xamarin.Forms PCL solution and place it in a directory next to the asp.net MVC project. Because we’re sharing files between projects the directory setup is important. In this case we can call it JellyBeanTracker.Mobile.

Step 2. Adding the external files and RazorTemplatePreprocessor

In this example I’ve added the files from the MVC project into the XF PCL project as ‘linked’ files. Create a new directory called ‘External’ and add the following files as per the screenshot. ps, to add files right click the directory and hit add files, Xamarin studio will then ask you if you’d like to link or copy files, in this case you need to link.

Screen Shot 2014-08-13 at 8.15.13 am

Secondly you need to add the javascript files and css files to the resources directory on each of the platform projects, as per screenshot.

Screen Shot 2014-08-13 at 8.20.55 am

For each of the razor files you need to right click->properties and set the Custom tool to the RazorTemplatePreprocessor.

Screen Shot 2014-08-13 at 8.22.15 am

Step 3. Clone and Add the MVCPolyfils into your Xamarin.Forms Project

Available here: https://github.com/rid00z/MVCPolyFils

Step 4. Use the Polyfils

On the Razor page remove @model and replace with @inherits System.Web.Mvc.WebViewPage<T> (from MVCPolyfils).

This step is required to have the file work in both MVC and the Xamarin.

Screen Shot 2014-08-19 at 9.29.47 pm

Step 5. Install Xamarin.Forms.Labs which has a HybridWebView

I’ve done a few modifications to the Xamarin.Forms.Labs project to get this to work and only just put it in my fork, so you’ll need to get the code from my fork until it gets put in the actual project.

https://github.com/rid00z/Xamarin-Forms-Labs

Step 6. Setup the Xamarin.Forms Project, with the Page and PageModels

This step requires knowledge of Xamarin.Forms, if you’ve not used Xamarin.Forms before then there’s some good videos over here: http://www.michaelridland.com/mobile/xamarin-hack-day-talks-thanks-retrospective/

Step 7. Sharing Business Logic and Offline

It’s possible to have shared business logic between both of the projects. You can share it via file linking, PCL or a shared project. In my sample application I’ve used file linking so it’s the same as the razor files.

In order to share business logic between asp.net and Xamarin Native you need to code your business logic classes against abstractions/interfaces. If we take a look at the JellyBeanGraph Calculator we can see that it uses a IDataSource for it’s calculations.

The IDataSource needs to be implemented in two or three places, two places if you’re not supporting offline and three place if you are supporting offline. As you can see in the sample project there’s two sources in the Xamarin project, a LocalDataSource and a RemoteDataSource. These two classes a switched between depending on if it’s online or offline.

LocalDataSource

RemoteDataSource

Step 8. Diff Logic in Razor Views using compiler directives

It’s not highly recommended to have logic within your Razor views but it is possible to have different view logic between the platforms. If you’re using file linking the best option is it use #ifdefs, to do this you need to add a compiler Symbol to the native project, as per screen shot.

Screen Shot 2014-08-14 at 8.10.36 am

Once you’ve setup the compiler Symbol you can then add setup a static IsNative boolean value in a shared file. As per below.

Screen Shot 2014-08-20 at 9.32.21 am

Finally you can add different functionality for the Native applications within your Razor views.

Screen Shot 2014-08-20 at 9.32.40 am

Step 8. Partial Views and Shared Partials

In the open source project I’ve release with this blog post there’s the ability to use Partial views within the Xamarin app. If you provide the classname as a string into the partial the framework will pick it up and run the razor view locally. In order to have the partials work on both the MVC and Xamarin application you need to have the partial views come from a static variable on a class.

Step 9. Combining the Javascript Logic

It’s also possible to take your javascript files and share them with Xamarin. Mostly they will just function as normal unless you’re doing ajax calls to collect the data. In the case you’re doing ajax calls and want to support offline then you need to communication back and forth between the C#/native and javascript.

There’s three type of communication available in this solution using the HybridWebView (soon to be)in Xamarin.Forms.Labs

a) Injecting javascript from c#

b) Calling a c# method from javascript

c) Calling a c# Func and returning into a closure

Step 9a. Injecting Javascript

Using the HybridWebView available in Xamarin.Forms you’re able to execute javascript from outside a webview. This is as easy as calling a method named InjectJavaScript, as per example below.

1
2
string data = JsonConvert.SerializeObject (PageModel.GraphData).Replace ("\r\n", "");
_hybridWebView.InjectJavaScript ("JellyBeanTrackerApp.buildChartStr('" + data + "');");

 Step 9b. Calling Native Methods

Also using the HybridWebView you’re able to call Native methods, so this is going from within javascript running in the web view out to a native method written in c#. As a little side note, this works with Mvvm so your business logic is contained within your view model.

Registering a method with the HybridWebView.

1
2
3
_hybridWebView.RegisterCallback ("EditVisible", (data) => {
  PageModel.EditVisible.Execute(data);
});

Calling the native method from javascript

1
2
3
$('#editVisible').click(function() {
  Native('EditVisible', JellyBeanTrackerApp.currentChartData);
});

The c# method that’s called from the javascript.

1
2
3
4
5
6
7
8
public Command<string> EditVisible
{
  get {
    return new Command<string> ((data) => {
      PushViewModel<ManageGraphPageModel>(data, true);
    });
  }
}

 Step 9c. Calling Native Funcs with Closure support

This one I’m a bit proud of as it’s pretty sweet. Using the HybridWebView you now have the ability to call a Native function and the return values of the Native function is injected back into the original closure. Also same as above this works with Mvvm.

Registering the Function in the WebView

1
2
3
_hybridWebView.RegisterNativeFunction ("GetGraphData", (input) => {
  return PageModel.GetGraphData(input);
});

Calling the function from javascript with the closure being called on return.

1
2
3
4
5
$('#getGraphData').click(function() {
    NativeFunc('GetGraphData', null, function (returnData) {
        JellyBeanTrackerApp.buildChartStr(returnData);
    } );
});

The c# function that runs

1
2
3
4
5
6
7
8
9
public Func<string, object[]> GetGraphData
{
  get {
    return (data) => {
      GraphData = new JellyBeanGraphCalculator (_dataSourceFactory.GetDataSource ()).GetGraphData();
      return new object[] { GraphData };
    };
  }
}

Step 10. Debugging from Safari

Another thing I should mention is Safari has the ability to debug UIWebViews, the setup details can be found here.

Just another (awesome)tool for the belt!

This is just one tool for the belt, it’s not the only mobile architecture that you can implement. There’s also the traditional Xamarin approach(Native UI for each platform) and Xamarin.Forms approaches which are still great architectures for mobile applications.

So when should you use this Hybrid type solution?

My personal belief is that using the HybridWebView is acceptable when the view is Not highly interactive as when interacting with a user you want to have everything looking and feeling native. Really it’s up to you to decided and initially it’s good to prototype and test within a device. Of course when you’ve got a large investment in web/mvc assets this is also a good choice.

All the code is available on https://github.com/rid00z/JellyBeanTracker, currently it’s only working with iOS devices. I will attempt add other platforms soon.

Thanks

 

 

Xamarin Hack Day Talks, Thanks and Retrospective

In June this year I put together a Xamarin hack day(with some amazing help by SSW)  in Sydney. The idea of the Hack Day was to get Sydney’s most experienced Xamarin professionals and people who want to learn Xamarin together for a day of learning and loving Xamarin. The day started with some presentations on various Xamarin technology’s and then the attendees sat down with their laptops to code with the help of the Xamarin experts.

The vibe of the day was great as everyone was very helpful towards each other and attendees were able to help each other.

People are doing amazing things in Xamarin, we all know this but the problem is that we’re all so busy making great products that we don’t get the time to share notes and that’s why I wanted to start the Xamarin hack day. Thanks to SSW the Xamarin hack day has become even more than I expected, it’s now global. Xamarin hack day events will be hosed worldwide including Brisbane, Melbourne, Hong Kong and more. Visit the Xamarin Hack Day website to find out more details on locations.

I would like to thank the experts and presenters Filip, Alec, Geoffrey, David and Rod. I’d also like to thank Adam Cogan and the SSW team for hosting the event and the huge amount of effort they put into the website. A big thank you to all the attendees who made the day a success.

We’re always taking feedback and improving the days for the attendees, so future hack days are only going to get better. I’ve embedded the videos below for your viewing pleasure.

Please sign up for the next Hack Day at http://xamarinhackday.com/

 

Introduction to Xamarin

Xamarin.Forms Deep Dive

Introduction to iBeacons with Xamarin

Rolling your own Mvvm for Xamarin.Forms

Update: I’ve taken the best parts of this post and put into a Frameworks that’s a super simple Mvvm framework for Xamarin.Forms, it’s available on github and nuget.

In this blog I give an example of how to roll your own Mvvm in Xamarin.Forms. This Mvvm is convention based and in this case I’ve used the Page/PageModel naming rather than Model/ViewModel naming, but you can change it to View/ViewModel if you like. This blog is based off a sample app that’s available on github.

Conventions in this sample.

  • A Page must have a corresponding PageModel, with naming important so a QuotePageModel must have a QuotePage
  • A Page can have a Init Method with no parameters
  • A Page can have a PageModel property which is the view model
  • The BindingContext on the page will be automatically set with the Model
  • A model can have a Init method that takes a object
  • A model can have a ReverseInit method that also take a object and is called when a model is poped with a object

 Lets see a Page

And the corresponding PageModel

Navigating Models

You can push and pop pages from your view models using PushPageModel() and PopPageModel methods.

Eg. PushPageModel<QuotePageModel>(quote);

But before you can do that you need to implement and register a IRootNavigation service. In my case I’ve used a ContainerPage and registered that as the NavigationHandler

//Register the Root Navigation
var containerPage = new RootContainerPage ();
TinyIoC.TinyIoCContainer.Current.Register<IRootNavigation> (containerPage);

Implementing Property Changed

You’ll notice that I don’t manually implement property change events, instead I used a opensource project called Fody/PropertyChanged. You can install this from nuget.

 

Inversion of Control/TinyIOC

Dependencies on ViewPage constructors will be automatically resolved. Use TinyIOC to register dependencies.

//Register the database service
TinyIoC.TinyIoCContainer.Current.Register<IDatabaseService, DatabaseService> ();

Where’s the magic?

If you want to know where the magic is happening then take a look at BasePageModel.cs in the sample application.

Platform Dependencies

This app makes use of platform dependancies for SQLite.

Unit Testing

If we follow the conventions then Models are loosely coupled and easily testable.

You can pass in mocked dependencies into Models and test. See an example here:

 

Please go and have a look at the code on github.

https://github.com/rid00z/XamarinFormsQuoteApp

 

Thanks

 

Michael

 

 

Xamarin.Forms Intro Part 2 – Build a Custom Control Library

UPDATE: In my example I use the namespace Xamarin.Forms, this is probably not the best namespace to use, it’s better to use CompanyName.Forms or Community.Forms.

This is the second part in a two part series introduction Xamarin.Forms. In the first part we demonstrated a basic app with Xamarin.Forms. In this part we will create a custom control library.

The library has four projects, the common PCL with references to Xamarin.Forms and a project for each of the platforms with references to Xamarin.Forms and Xamarin.Forms.Platform.(platform name), as per screenshot below.

Screen Shot 2014-06-03 at 9.47.21 pm

 

All the projects each have single important class, the PCL has a View class which in my case is the CalendarView while the platforms have a ViewRenderer which in this case is CalendarViewRenderer.

Xamarin.Forms.Calendar (Portable) – CalendarView.cs

Just to understand how it works from a consumer perspective, this  class is referenced from the calling PCL (eg the CalendarViewSample). It’s the only class you have to worry about as a consumer of the library. The renderers are called by the platform.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
namespace Xamarin.Forms.Calendar
{
    public class CalendarView : View
    {
        public CalendarView ()
        {
        }
 
        public void NotifyDateSelected(DateTime dateSelected)
        {
            if (DateSelected != null)
                DateSelected (this, dateSelected);
        }
 
        public event EventHandler<DateTime> DateSelected;
    }
}

Xamarin.Forms.Calendar.Droid – CalendarViewRenderer.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
[assembly: ExportRenderer (typeof (Xamarin.Forms.Calendar.CalendarView), typeof (CalendarViewRenderer))]
 
namespace Xamarin.Forms.Calendar.Platform.Droid
{
    public class CalendarViewRenderer : NativeRenderer 
    {
        private const string TAG = "Xamarin.Forms.Calendar";
 
        CalendarView _view;
        CalendarPickerView _pickerView;
 
        public CalendarViewRenderer ()
        {
        }
 
        protected override void OnModelChanged (VisualElement oldModel, VisualElement newModel)
        {
            _view = (CalendarView)newModel;
 
            base.OnModelChanged (oldModel, newModel);
 
            LayoutInflater inflatorservice = 
                              (LayoutInflater) Context.GetSystemService(Android.Content.Context.LayoutInflaterService);
            var containerView = 
                                (LinearLayout)inflatorservice.Inflate (Resource.Layout.calendar_picker, null, false);
 
            _pickerView = containerView.FindViewById<CalendarPickerView>(Resource.Id.calendar_view);
            _pickerView.Init (new DateTime (2014, 6, 1), new DateTime (2014, 6, 30))
                .InMode (CalendarPickerView.SelectionMode.Single);
 
            _pickerView.OnDateSelected += (s, e) => {
                _view.NotifyDateSelected(e.SelectedDate);
            };
 
            SetNativeControl (containerView);
        }
    }
}

In the class above I just override the OnModelChanged method and then in that method I create a UI element. Then I wire up the OnDateSelected event and call the event on the View(which in turn goes into the consumers PCL). Finally I call SetNativeControl that add the view onto the page.

You’ll also notice the ExportRenderer line which is a assembly attribute and it links the View and the Renderers. All the other platforms are similar to this.

Xamarin.Forms.Calendar.iOS – CalendarViewRenderer.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
[assembly: ExportRenderer (typeof (CalendarView), typeof (CalendarViewRenderer))]
 
namespace Xamarin.Forms.Calendar
{
    public class CalendarViewRenderer : NativeRenderer 
    {
        CalendarView _view;
        public CalendarViewRenderer ()
        {
        }
 
        protected override void OnModelSet (VisualElement model)
        {
            _view = (CalendarView)model;
            base.OnModelSet (model);
 
            var calendarView = new CalendarMonthView(DateTime.Now, true);
 
            calendarView.OnDateSelected += (date) => {
                _view.NotifyDateSelected(date);
            };
 
            base.SetNativeControl (calendarView);
        }           
    }
}

Xamarin.Forms.Calendar.WP – CalendarViewRenderer.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
[assembly: ExportRenderer(typeof(CalendarView), typeof(CalendarViewRenderer))]
 
namespace Xamarin.Forms.Calendar.Platform.WP
{
    public class CalendarViewRenderer : ViewRenderer<Xamarin.Forms.Calendar.CalendarView, WPControls.Calendar>
    {
        protected override void OnModelSet()
        {
            base.OnModelSet();
            var calendar = new WPControls.Calendar();
            calendar.DateClicked +=
                (object sender, WPControls.SelectionChangedEventArgs e) =>
                {
                    Model.NotifyDateSelected(e.SelectedDate);
                };
            this.SetNativeControl(calendar);
        }
    }
}

So that’s it, creating custom controls for the Xamarin.Forms platform is pretty simple. I hope others can also enjoy making their own controls for the platform, I look forward to seeing what the community can create.

There source code for this project available on github: https://github.com/rid00z/Xamarin.Forms.Calendar

I’ve also done a little demo video, see below:


 

Xamarin Forms – Build Your First App – Part 1

When I first heard about Xamarin.Forms I was really excited, having the ability to code your UI in a single PCL/Shared projects and have them run natively on all platforms is very cool. It really is Write Once, Run Everywhere AND Be Native

After many years experience with Monotouch.Dialog moving to Xamarin.Forms felt very natural, they are very close in implementation. Xamarin.Forms is really the next iteration of Dialog.

Below I’ll show you my first app in Xamarin.Forms. My first app isn’t just a Forms app, it’s actually Xamarin.Forms control that works on all platforms. In this post I’m going to take you over the sample app that makes use of the library. The primary reason I’ve done this demonstration is because I would like others to follow in my footsteps and create powerful controls for Xamarin.Forms. The more we share and work together the more useful the platform becomes.

Note there’s a demo video here:
Note there’s the github Calendar project here:
Note in a future blog I will go over how to create your own Xamarin.Forms controls libraries.

What the app looks like on each platform(these are real native UI components):

Screen Shot 2014-06-02 at 11.38.44 pm     Screen Shot 2014-06-02 at 11.43.53 pm     Screen Shot 2014-06-02 at 11.45.35 pm

The common code that used for the UI:

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
public class SampleCalendarPage : ContentPage 
{
    CalendarView _calendarView;
    StackLayout _stacker;
 
    public SampleCalendarPage ()
    {
        Title = "Calendar Sample";
 
        _stacker = new StackLayout ();
        Content = _stacker;
 
        _calendarView = new CalendarView() {
            VerticalOptions = LayoutOptions.Start,
            HorizontalOptions = LayoutOptions.CenterAndExpand
        };
        _stacker.Children.Add (_calendarView);
        _calendarView.DateSelected += (object sender, DateTime e) => {
            _stacker.Children.Add(new Label() 
                { 
                    Text = "Date Was Selected" + e.ToString("d"),
                    VerticalOptions = LayoutOptions.Start,
                    HorizontalOptions = LayoutOptions.CenterAndExpand,
                });
        };
 
    }
}

The (Android)platform code:

1
2
Xamarin.Forms.Forms.Init (this, bundle);
SetPage (App.GetMainPage ());

The (iOS)platform code:

1
window.RootViewController = App.GetMainPage ().CreateViewController ();

The (Windows Phone)platform code

1
Content = Xamarin.Forms.CalendarSampleApp.App.GetMainPage().ConvertPageToUIElement(this);

Now this is a trivial app, but as you can imagine as the application becomes more complex your UI code will stay in your common library and work across all platforms.

Xamarin.Forms is a very creative solution to the cross platform problem and I’m looking forward to seeing it’s progression.

A demo video of Xamarin.Forms

Please take a look at the code available on github:
https://github.com/rid00z/Xamarin.Forms.Calendar

If you have any questions or want any help with anything Xamarin please contact me as I’m happy to help out.

Tips for Offline in Azure Mobile Services on Xamarin.iOS

To Offline or not to Offline? On one hand it adds a fair amount of code complexity but in those times when a user is doing a very important task and a connection is lost they’re not going to be very happy when their app just stops working.

In wanting a high quality product I’ve been on the search for ways to support offline in my app. I discovered that the Azure Mobile Services team had Offline support in their client library.

The deep dive tutorial gives a good overview of the Offline support. At the moment the support it targeted towards Windows Mobile so there’s a few tricks to get it working on Xamarin.iOS. I’m going to go over the steps I had to take to get it working in a simple in Xamarin.iOS project in Xamarin Studio, in some parts I have to jump over to Visual Studio because the nuget support in Xamarin studio is a few versions behind.

You can check out the Offline in Azure Mobile Service deep dive tutorial here.

There is a azure mobile services package in the Xamarin Component Store but at the moment you actually need the prerelease version. So to get it working you need to use nuget from Visual Studio, personally I had to get from the component store and copy the assembles from another project to override the component store assemblies but you *should* just be able to open the project in visual studio and install the prerelease package. Installing this from the package manager in Xamarin Studio it  included:

  • Microsoft.WindowsAzure.Mobile.Ext
  • Microsoft.WindowsAzure.Mobile
  • Newtonsoft.Json
  • System.Net.Http.Extensions
  • System.Net.Http.Primitives
  • System.Net.Http

The second package you need is the SQLiteStore which is also prerelease and also needs to be downloaded from visual studio.

The third package/assembly you’ll need is a SQLitePCL that works with Xamarin.iOS, thankfully someone has already been working on it and added a pull request that add Xamarin support to SQLitePCL. https://sqlitepcl.codeplex.com/SourceControl/network/forks/mattleibow/SQLitePCL/contribution/6607
You’ll need to clone this then add a reference to the SQLitePCL project and the SQLitePCL.Ext.iOS project, I had to change the SQLitePCL to profile78 to get it working.

One other issue I encountered was that the SQLitePCL couldn’t load the iOS platform specific code, the reason for this is that the assembly wasn’t used by any project directly (it’s loaded via Reflection) so it didn’t load the assembly.

So in the Application.Main you just need to reference the provider for the extension into a dummy variable.

1
var platform = SQLite3Provider.Instance;