Skip to content

Tag: Portable Class Library

Enabling TLS 1.2 in Xamarin.Forms

For the life of me, I cannot understand why Transport Layer Security (TLS) 1.2 is not yet supported out of the box for Xamarin. According to Xamarin’s website, this is due to the fact that Mono still only supports TLS 1.0.

Xamarin has provided special handler’s that will leverage platform specific API’s that enable TLS 1.2; unfortunately, these handlers are not Portable Class Library (PCL) friendly and support only the most recent platform operating systems. I don’t know about you, but the mobile apps that I develop can’t be that picky in respect to the devices I support. I wish I only had to support the latest and greatest :p.

Fortunately, there is a simple solution that is both PCL friendly and can support older OS’s. This means that we can use this within a Xamarin.Forms solution.

  1. Right click packages (in the solution explorer)
  2. Click Add Packages…
  3. Search “ModernHttpClient”
  4. Find the following package: Id = modernhttpclient, Author = Paul Betts
  5. Add the package to EACH project package folder (PCL, Android, iOS,…)

// NOTE: ModernHttpClient has to be installed within each project due to how bait-and-switch libraries work.

Next, add the following packages to the PCL project:

  1. Id = Microsoft.Bcl, Author = Microsoft
  2. Id = Microsoft.Bcl.Build, Author = Microsoft
  3. Id = Microsoft.Net.Http, Author = Microsoft

You are now ready to start writing REST code. The secret behind ModernHttpClient is that it will use a bait-and-switch technique that will utilize the native platform handlers that support TLS 1.2. Simply use the following message handler: NativeMessageHandler().

Below is a rudimentary code sample without error handling (within the PCL):

 

Using Dependency Services with Xamarin.Forms

When developing with Xamarin.Forms, you will quickly find yourself in a situation where some of the native platforms’ functionalities were not implemented in the Forms API. In these situations, you can use the power of a Dependency Service to access the native Xamarin for each platform.

For example, say you want to access the devices’ GPS functionality. Each platform has GPS capabilities, yet function slightly differently. In a situation like this, using a dependency service will provide you access to all the native functionality on each platform within the shared code of the portable class library (PCL).

A dependency service is exactly what it sounds like. Within the PCL project, you will have a service (interface) that abstracts the functionality that you need access to in each platform. Within each platform project, you will create the native implementation that correlates with your shared abstraction.

Let’s go ahead and implement a simple dependency service. Forms does not provide access to your application’s cookie storage. While the cookie storage is handled automatically for WebViews and other network requests, you may need to access the cookies directly.

1. Within the PCL project, create an interface file called: INativeCookieService.cs

2. Add the methods and properties you are abstracting

3. Within the Android project, create a class called: NativeCookieService.cs

4. Add the assembly attribute:
[assembly: Dependency(typeof(MyCoolApp.Droid.NativeCookieService))]

5. Have the class implement: INativeCookieService

6. Add the native functionality

7. Repeat steps 3 – 6 for iOS (and Windows if you are supporting Windows). Make sure to use the iOS namespace rather than the Android on step 4

Whenever you need to use the native functionality within the PCL, you simply make the call:

What is a Custom Renderer?!

One of the most initially confusing, yet essential components to Xamarin.Forms are custom renderers. If you look at almost any advanced feature or customization tutorial for Forms, you are likely to run into the term custom renderer. But what the heck is a custom renderer?!? Everyone seems to reference the use of them, yet no one seems to take the time to thoroughly explain what they are and how they work.

Custom renderers are really simple once you understand the foundation behind how Forms renderers the user interface. Forms maps every UI element to each of the native platforms’ UI elements. In other words, Forms has generic views/controls that are referenced in XAML and are transformed into the native platforms equivalent view. For example, Forms has a Xamarin.Forms.Button class, which gets rendered to UIKit.UIButton on iOS, and android.widget.Button on Android. Essentially, a renderer is simply a mapping between a Forms element, and a platform’s native element. A custom renderer goes one step further; the developer, can override or extend Xamarin’s renderer.

Why would we ever want to change Xamarin’s default renderer? While Xamarin implements a majority of our UI/UX needs, we might need more granular control over the look or behavior of our views.

How do we create a custom renderer? A simple scenario (yet annoying) that requires the use of a custom renderer is when you want to prevent autocorrect on an Entry field when rendered on iOS. An Entry field is Forms’ version of a textbox. Unfortunately, by default on iOS, the textbox has autocorrection and first letter capitalization turned on, yet Forms does not provide a simple way to disable these settings. This is an example of a situation where a custom renderer is required to accomplish our goal.

Suppose you have a simple login page that uses an Entry field for the username and password:

Notice that we are using the default Entry tags in the LoginPage’s XAML. The magic does not happen within the portable class library (PCL); rather, all of our customization will be handled in each platforms’ native project.

  1. For this example, create a folder in the iOS project called: Renderers
  2. Within that new folder, create a new class called: CustomEntryRenderer
  3. Add the following line to the class before the namespace: [assembly: ExportRenderer(typeof(Entry), typeof(MyCoolApp.iOS.CustomEntryRenderer))]
  4. Have the class inherit from: EntryRenderer
  5. Override: OnElementChanged

Within a custom renderer class, there are two important properties to be aware of, Control and Element. The Control property refers to the platform’s native view. The Element is the Forms’ mapping to the Control. For this simple example, we only need to manipulate two settings on the native Control, AutocapitalizationType and AutocorrectionType.

Now, whenever we use an Entry element within our PCL project, this custom renderer will override the default iOS renderer due to the assembly reference we added before the namespace. One nice design aspect to note is that the our views are blissfully unaware of the custom renderer (i.e. they are loosely coupled). That also means that since we did not implement an Android custom renderer, Android will continue to use the default renderer.

Xamarin.Forms Structure

In the previous blog post, we created a Xamarin.Forms Portable Class Library (PCL) solution. In this blog post, we will discuss the actual file structure of that same solution and deploy it to an actual simulator.

Hello Forms Root Solution StructureAfter creating the solution, you will notice three separate projects (i.e. HelloForms, HelloForms.Droid, and HelloForms.iOS). If you are at all familiar with Xamarin native projects, the structure of the Android and iOS Forms projects are virtually identical to the native. Adversely, you will notice an additional project named HelloForms; this is the PCL.

HelloForms iOS ProjectThe PCL acts as the core of your application and will contain a majority of your code (if this is not the case, you should probably stick with Xamarin native).

Contained within the iOS project, is a file named Main.cs. This file acts as the main entry into your iOS application. Main.cs will simply instantiate our AppDelegate.cs file.

Inside our AppDelegate.cs file is where the Forms magic begins. Forms is first initialized and a new instance of the PCL’s App.cs class is loaded.

HelloForms Android ProjectBefore we discuss the PCL App.cs class, let’s switch over to see how Android launches. Inside the Android project, you will find the MainActivity.cs file. Android simplifies the process by combining the entire launch process into this one file. The MainActivity.cs file both acts as the main entry into the application and also initializes Forms and instantiates the PCL’s App.cs class. Android does not use the MainActivity.cs file as the entry point due to the name, it is used because it contains the “MainLauncher = true” attribute.

HelloForms PCL ProjectBoth platforms have now entered PCL land. If we open the PCL project, we can now look inside the App.cs file… However, an App.cs class does not seem to exist. If you recall from the last blog post, we opted to use XAML to build our UI. Therefore, App.cs is actually called, App.xaml. You will notice that there is an expandable indicator next to the App.xaml file. Once you expand the file, you will see an App.xaml.cs file nested below the App.xaml file. App.xaml.cs is the C# code behind our XAML file. Inside our code behind file, we have a constructor which sets the first page for our application, and the self explanatory OnStart(), OnSleep(), and OnResume() methods. We will use the App.xaml.cs class in later blog posts to accomplish more advanced functionality.

From the App.xaml.cs code behind, we discover that HelloFormsPage() is set as our MainPage. This is simply a template page that was created when we created the solution. We can change this later; however, let’s use it for this example. In Xamarin.Forms, pages are views that occupy the entire screen. This page is essentially the equivalent to a UIViewController’s UIView in iOS or an Activity’s View in Android. Similar to the App.cs file, the HelloFormsPage is made up of both a XAML file and a C# code behind file.

We will go much deeper into XAML in later blog posts; however, just so you can get a taste for it, open the HelloFormsPage.xaml file. You will notice on line 3 that there is a Label. Update the text from “Welcome to Xamarin Forms!” to “Hello Xamarin.Forms” (be careful, the text for this label must be encapsulated in double quotes). Save your changes.

Xamarin Studio Set As Startup ProjectWe are now ready to build and launch our application. Right click on the iOS project, and select “Set As Startup Project”. Xamarin Studio Start Debugging IconYou can now select the build and deploy icon (looks like the play icon you would find on a tv remote).  This will build the application and deploy it to an iOS simulator on your Mac. To stop the application, you can hit the stop icon in Xamarin Studio (same button location as the play icon).

To launch the Android application, right click on the Android project, and select “Set As Startup Project”. Click the play icon (aka Build and Deploy). A default Android emulator should launch.

Android HelloForms App iOS HelloForms App

Congrats on building your first Xamarin.Forms app!

Switching to Xamarin.Forms?

After attending Xamarin Evolve16 this year, Xamarin.Forms appears to have significantly matured since its introduction two years ago. Having only developed using Xamarin.iOS and Xamarin.Android, I had limited exposure to Forms prior to the conference. While at the conference during trainings and conference sessions, it became clear that Xamarin is really pushing the adoption of Forms.

So the question becomes, what is Forms and should I use it? The main business case for using Xamarin is the ability to share as much code between platforms as possible. Xamarin native allows developers to share a majority of their business logic and models, yet you are still stuck having to write a UI for each platform. The most simplistic way I can describe Forms is that it is Xamarin’s attempt to abstract the UI for extensive code sharing and still deliver native (or nearly native) performance and design. Xamarin claims that they were able to share more than 90% of the code for their 2016 Evolve app between Android, iOS, and Windows.

Xamarin Evolve 2016 Android App Code SharingXamarin Evolve 2016 iOS App Code Sharing Xamarin Evolve 2016 Windows App Code Sharing

Images Source

My first impression to this claim was, this sounds too good to be true, so what’s the catch? The catch to using Forms, is that you “lose” the granular control over your UI and the simplicity of platform specific APIs. My previous statement must be qualified because it is not entirely accurate. Before I can explain further, I first have to explain the structure of a Forms application.

Xamarin Forms PCL Solution StructureA Forms solution contains a project for each platform you intend to target. Therefore, you will have a project for Android, iOS, and each flavor of Windows that you decide to support. Also within the solution, you will have an additional project called the PCL or portable class library. Think of the PCL as the core of your application where a majority of all your code lives. Inside the PCL is the Xamarin.Forms NuGet package, which contains all the required libraries to build a Forms application. The primary difference between a native Xamarin app and a Forms app is the PCL. In other words, a Forms app is exactly the same as a native Xamarin app but with additional libraries. This technically means you have access to all the native Xamarin APIs as before (with a catch).

With a rudimentary understanding of the Forms structure, I can now explain my original claim about losing some native control. Since the purpose of using Forms to build your application is to maximize code sharing, this creates complexities when you need to access platform specific features or complete control over your design. While I technically have access to all the native Xamarin APIs, I have to jump through additional hoops in order to utilize them.

The two main approaches to access the native APIs are to use either a custom renderer or a dependency service. A custom renderer allows you to create native UI elements (such as a UIKit.UIView in iOS or a Android.Views.View in Android) for each platform and then integrate them back into a Forms page or view.  A dependency service allows you to access device specific functionality such as the built-in cameras or GPS.

If we have access to all the native APIs, why don’t we always build Xamarin apps using Forms? Two significant reasons why you should weigh your options before making a decision are performance and path of least resistance. Performance is a factor because the entire UI in a Forms application is a compilation of custom renderers contained within the Xamarin.Forms package. This means that there is an additional performance cost to rendering your views. If your application is graphics intensive or uses a large amount of memory, the end users might notice your application not working smoothly. The path of least resistance comes into play depending on the complexity of your application. If your application requires access to a large amount of the native platform APIs and has significant custom UI needs, you will be spending as much if not more time writing custom renders and dependency services as you were attempting to save by sharing more code between platforms. On the other hand, if it is more important to share code between platforms than direct access to the native APIs, Forms is a strong contender. Xamarin provides a quick one page PDF to help you decide which camp your app falls into.

Over the next few months, I will be writing about my experience of porting existing Xamarin.Android and Xamarin.iOS eCommerce apps over to Xamarin.Forms. After evaluating and testing Forms, my team feels that we could benefit from the adoption of Forms. We believe our existing apps fall under the 80/20 rule, 80% of our apps require very little advance custom UIs and platform specific features, while 20% does. Our hope is that the 80% saves us more development time than the 20% of additional overhead. I hope my experience will help others make the right decision for their apps.