Skip to content

Tag: PCL

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.

Navigation using MVVM Light

MVVM Light is one of many free MVVM frameworks available today. As the name implies, MVVM Light is a lightweight framework that allows the developer to utilize as much or as little of the framework as is needed.

Conversely, other MVVM frameworks are more of an “all or nothing” design. The problem with the “all or nothing” design is that they essentially replace the base system that you are developing on. For instance, if you are developing with Xamarn.Forms, and you adopt one of beefier MVVM frameworks, the framework will completely override a large percentage of how Forms was intended to operate. This can cause major frustration when reading blogs, tutorials, and other coding examples.

As we discussed in the previous post, Forms utilizes XAML for UI implementations and thus is intended to follow the MVVM design pattern. That being said, a large percentage of Xamarin developers (including myself) agree that Forms does not by default correctly handle navigation using the MVVM pattern because the Views dictate the navigation logic not the ViewModels.

For anyone that is just starting out with Forms, navigation can be very frustrating. Fortunately, there is an easy solution to move navigation logic from the Views to the ViewModels using MVVM Light.

We first need to add the MVVM Light package to each project in our solution (PCL, Android, iOS, and any flavor of Windows that you are supporting).

  1. Right click Packages in the solution explorer
  2. Click Add Packages
  3. Use NuGet’s search function to find MVVM Light libraries only package (Id: MvvmLightLibs, Author: Laurent Bugnion (GalaSoft))
  4. Add Package (to each project)

MVVM Light will add the dependency CommonServiceLocator package by Microsoft. Before we implement our navigation service, we need a way to globally access this service so that all ViewModels have access. This is where the Locator comes into play.

In the PCL project, create a folder called Services. Within the Services folder create a class called Locator. We only want one Locator for the entire application, so we will follow the singleton pattern and make the Locator constructor static.

There are three main components to this class, the string constants at the top, the constructor, and various properties with getters. The constants act as keys for each page registered for the navigation service. The constructor handles all the registration of services and ViewModels; ViewModels do not have to be created within the locator, they can be instantiated by the view. Finally we expose the Navigation Service and ViewModel instances with property getters.

Next, let’s implement the NavigationService. In the same folder as the Locator, create a class called NavigationService. This class will implement the MVVM Light (GalaSoft) INavigationService interface. Add the following methods and properties:

At this point, we still do not have a globally accessible NavigationService. Open the class code-behind that implements Application; this is usually called App.xaml.cs. Add the following locator property:

Our ViewModels are now able to completely handle our navigation logic using App.Locator.NavigationService.NavigateTo(PAGE KEY).

Example:  App.Locator.NavigationService.NavigateTo(Locator.SecondPage);

This tutorial is based off of Mark’s Blog.

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!