Skip to content

Tag: Xamarin

Adding a SQLite database to Xamarin.Forms

SQLite Logo
Source: Wikipedia (https://en.wikipedia.org/wiki/SQLite)

SQLite is an excellent choice for local storage within a mobile application. It is lightweight and with virtually zero configuration. Adding SQLite to a Xamarin.Forms project is fairly straightforward:

1. Add the nuget package SQLite-net PCL to each project (PCL, Android, & iOS)
Author = Frank A Krueger
ID = sqlite-net-pcl

2. Add an interface to the PCL project called: ISQLiteService.cs

3. Add a class to the iOS project called: SQLiteService.cs

4. Add a class to the Android project also called SQLiteService.cs

5. Add a class to the PCL project called: BaseItem.cs

6. Add a class to the PCL project called: Database.cs

7. To create a table model, simply create a class with public properties (with getters and setters) of the types and names of each field in the table. The class should inherit from BaseItem; this adds an auto incrementing ID field.

8. Create an instance of Database.cs called: database
To create a table simply call database.CreateTable();

Xamarin.Forms SQLiteExample ScreenshotYou now have a fully functioning database in Forms. To see a database in action, checkout out my example project on GitHub.

 

If you have any comments, questions, or suggestions, feel free to leave a comment below.

Creating a hamburger menu in Xamarin.Forms

Amazon Hamburger Menu
Source: Amazon iOS App (Amazon.com)

One of the most common navigation design patterns for applications and websites is none other than the hamburger menu. While the effectiveness of this type of navigation is greatly debated in the industry, no one can dispute that consumers have, for better or worse, acclimated to these menus. Many of the bigger players in the industry have utilized these menus within their applications (e.g. Amazon, Facebook, Google… to name a few).

Regardless of which side of the fence you are on, implementing a hamburger menu is dead simple in Forms. Xamarin has cleverly disguised their implementation as “Master-Detail Page.”

To create a hamburger menu:

1. Add a new class to your project called: MenuPage
2. Have MenuPage inherit from ContentPage
// TODO: Customize the MenuPage to your heart’s content (with navigation logic, Buttons, ListViews, Labels, etc).

3. Add a second new class to your project called: HomePage (call it whatever)
4. Have HomePage also inherit from ContentPage

5. Add a third new class to your project called: RootPage
6. Have the new class inherit from MasterDetailPage

7. In the constructor of App.xaml.cs, create a new instance of RootPage
8. Create a new instance of MenuPage
9. Assign MenuPage to the Master property of RootPage
10. In the same constructor, create a new instance of a NavigationPage, add a new instance of HomePage as the argument for the NavigationPage
11. Assign the instance of NavigationPage to the Detail property of RootPage

The NavigationPage becomes your navigation stack. Therefore, if you want to push a new page onto the stack (from your MenuPage), simply call:

App.NavigationPage.Navigation.PushAsync(PAGE)

Or pop a page off the stack (from your MenuPage):

App.NavigationPage.Navigation.PopAsync()

To replace the HomePage with another page:

Xamarin will automatically provide a hamburger menu button within your navigation bar. I have found the default navigation bar to be a royal pain to customize. My recommendation would be to implement your own custom header bar. If you do create a custom header, simply call RootPage.IsPresented = true; to open the menu drawer. Set it to false to close it.

// UPDATE: as requested, here is an example project

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.