Using Native Facebook Login Button in Xamarin.Forms QA

On 9th of March 2018 I wrote an article “Using Native Facebook Login Button in Xamarin.Forms” which turned out to be the second popular article on my blog. Since then, thanks for my readers, I received many additional questions which I decided to answer in this separate article. However, before diving into those questions, I would like to take a step back and talk about Facebook SDK in relation to Xamarin.

Facebook SDK is available for Xamarin.Android and Xamarin.iOS but not for Xamarin.Forms. This might be the most confusing part, especially if you are working with Facebook SDK on Xamarin.Forms for the first time. Luckily, the problem could be easily solved, please follow the original article.

Now the question is “Do you actually need to integrate the official Facebook Login component to your app?”. What if you want a fully customised button instead of the official look and feel? What if you just want to obtain an authentication token from Facebook and pass it to your backend? By the end of the day we just want to be productive and write as less code as possible, right? If I just described your case please refer to my other article where this can be achieved with a couple lines of code with a ready made wrapper for Xamarin.Forms. Continue reading “Using Native Facebook Login Button in Xamarin.Forms QA”

Mocking Xamarin.Essentials

Xamarin.Essentials provides developers with cross-platform APIs for their mobile applications.

If you never heard about Xamarin.Essentials you should get familiar with it as soon as possible! It is a great collection of APIs that is very easy to use and integrate to your projects. You can find more information in the official documentation.

In order to keep the things as simple as possible and easy as possible to pick up for new contributors, all the APIs are written in a static way. The first reaction of developers would be to immediately raise their eyebrows and ask:  “Why so? How are we going to unit test that?”. The answer in most cases is easier than you may think at first. Continue reading “Mocking Xamarin.Essentials”

Dynamically changing the selected tab tint color in Xamarin.Forms

Android

droid

Since Xamarin.Forms 3.1 a TabbedPage.BarSelectedItemColor property has been introduced and we can simply use it to achieve our goal.

XAML:

<TabbedPage
    xmlns:android="clr-namespace:Xamarin.Forms.PlatformConfiguration.AndroidSpecific;assembly=Xamarin.Forms.Core"
    android:TabbedPage.BarSelectedItemColor="Red">
</TabbedPage>

C#:

Xamarin.Forms.PlatformConfiguration.AndroidSpecific.TabbedPage.SetBarSelectedItemColor(%tabbedPage%, %color%);

iOS

ios

Unfortunately on iOS we have to implement the solution ourselves. Luckily there is a TintColor property on a UITabBar that we can use. Continue reading “Dynamically changing the selected tab tint color in Xamarin.Forms”

Dynamically changing the status bar appearance in Xamarin.Forms

 

Aug-18-2018 13-11-19

Usually there is a need in changing the status bar appearance to match the application theme at least once. In more advanced cases the appearance of the status bar may change multiple times, due different colour themes on different screens within the application.

Status bar appearance is about it’s background and text colours. Both properties has their own limitations on different platforms, however we could manipulate both with the solution described below.

Our goal is simple, we want to be able to switch the status bar appearance between  LightTheme and DarkTheme at runtime:

public interface IStatusBarStyleManager
{
    void SetLightTheme();
    void SetDarkTheme();
}

Android

Background colour

Since Android Lollipop (21) it is possible to set a custom status bar background colour by simply defining it in style.xml with a key  colorPrimaryDark or programatically (check below).

Text colour

Since Android M (23) it is possible to set a predefined status bar text colour theme to light or dark.

Implementation

public class StatusBarStyleManager : IStatusBarStyleManager
{
    public void SetDarkTheme()
    {
        if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
        {
            Device.BeginInvokeOnMainThread(() =>
            {
                var currentWindow = GetCurrentWindow();
                currentWindow.DecorView.SystemUiVisibility = 0;
                currentWindow.SetStatusBarColor(Android.Graphics.Color.DarkCyan);
            });
        }
    }

    public void SetLightTheme()
    {
        if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
        {
            Device.BeginInvokeOnMainThread(() =>
            {
                var currentWindow = GetCurrentWindow();
                currentWindow.DecorView.SystemUiVisibility = (StatusBarVisibility)SystemUiFlags.LightStatusBar;
                currentWindow.SetStatusBarColor(Android.Graphics.Color.LightGreen);
            });
        }
    }

    Window GetCurrentWindow()
    {
        var window = CrossCurrentActivity.Current.Activity.Window;

        // clear FLAG_TRANSLUCENT_STATUS flag:
        window.ClearFlags(WindowManagerFlags.TranslucentStatus);

        // add FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag to the window
        window.AddFlags(WindowManagerFlags.DrawsSystemBarBackgrounds);

        return window;
    }
}

Please note that I am using Current Activity Plugin for Xamarin.Android in order to get a reference to the current displayed activity.

iOS

Background colour

In iOS the status bar background colour by default matching the colour of the navigation bar. In other words, we don’t have to explicitly set the background colour of the status bar if we want it to match the background colour of the navigation bar.

Text colour

Since iOS 7 it is possible to set a predefined status bar text colour theme to light or dark. However, we will have to manipulate the Info.plist. Since status bar behaviour is determined by view controllers by default, we have to disable this:

<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>

Next, we can define a default text colour theme:

<key>UIStatusBarStyle</key>
<string>UIStatusBarStyleDefault</string>

Implementation

public class StatusBarStyleManager : IStatusBarStyleManager
{
    public void SetDarkTheme()
    {
        Device.BeginInvokeOnMainThread(() =>
        {
            UIApplication.SharedApplication.SetStatusBarStyle(UIStatusBarStyle.LightContent, false);
            GetCurrentViewController().SetNeedsStatusBarAppearanceUpdate();
        });
    }

    public void SetLightTheme()
    {
        Device.BeginInvokeOnMainThread(() =>
        {
            UIApplication.SharedApplication.SetStatusBarStyle(UIStatusBarStyle.Default, false);
            GetCurrentViewController().SetNeedsStatusBarAppearanceUpdate();
        });
    }

    UIViewController GetCurrentViewController()
    {
        var window = UIApplication.SharedApplication.KeyWindow;
        var vc = window.RootViewController;
        while (vc.PresentedViewController != null)
            vc = vc.PresentedViewController;
        return vc;
    }
}

Conclusion

At first this topic may seem very confusing, especially on Android, however it turned out to be very simple and easily achievable as you can se above. The code can be found on github.

Retrieving Facebook User Access Token in Xamarin.Forms

Few months ago I wrote an article about Using Native Facebook Login Button in Xamarin.Forms where I explained how to retrieve user access token using Facebook SDK. It is still a valid read and a good solution, however, recently I discovered that there is a shorter way to achieve almost the same thing.

In this article we will learn how to retrieve Facebook user access token, using a custom button (not native) with just a few lines of code. I assume that you know how to create a Facebook application and configure your Android and iOS projects. If I am mistaken please refer to my previous article.

There is an open source project Facebook Client Plugin that allow you to login, share and query Facebook using static API. It has a good documentation and good well known developers behind it. As you may already understand we are going to use it to retrieve user access token from Facebook in our project.

Here is the recipe:

  1. Create and configure Facebook app (more info here or here).
  2. Add Plugin.FacebookClient NuGet package to .NET Standard and platform targeting projects.
  3. Configure platform targeting projects (more info here or here).
  4. Add a custom Facebook login button to your Page/View.
  5. Bind a command to the previously created button with the next code:
    var fbLoginResponse=
        awaitCrossFacebookClient.Current.LoginAsync(newstring[]{“email”});
    if(fbLoginResponse.Status == FacebookActionStatus.Completed)
    {
        var fbUserAccessToken=CrossFacebookClient.Current.ActiveToken;
        // TODO: Use the fb access token
    }
    else
    {
        // Something went wrong
    }

That should be it!

You could create a wrapper interface and class to make this code testable, to be able to inject it as a dependency and to adjust it to your needs. This solution might be less configurable, however, the integration is very easy and the amount of code is miserable compare to the previous solution.

Big thanks to CrossGeeks!

Immutable Models in MVVM

10-22-04 025
Source: flickr/ Jeff Attaway

MVVM

The first M stands for Model – an implementation of the application’s domain model that includes a data model along with business and validation logic. Examples of model objects include repositories, business objects, data transfer objects (DTOs), Plain Old CLR Objects (POCOs), and generated entity and proxy objects.

definition source

Immutability

In object-oriented and functional programming, an immutable object(unchangeable object) is an object whose state cannot be modified after it is created. This is in contrast to a mutable object (changeable object), which can be modified after it is created.

definition source

Why bother?

Imagine the next simple situation, your application downloads a JSON,  deserialises it to an object and then presents the downloaded data. You would expect the downloaded data to be one-to-one to the data on the remote server, however the data can be accidentally or intentionally mutated. Continue reading “Immutable Models in MVVM”

Archiving your code

simple_comic_zip

Intro

Title of this blog post may sound very weird in 2018 while github / vsts / bitbucket are still up and running. However, it still seems to be very common to archive your solution and upload it to cloud or send it by email. Don’t ask me why, it is just still there.

The most painful and annoying mistake you can make is to include dependencies that can be easily downloaded or compiled code. Painful because it may significantly increase the size of the archive and annoying because you may have to download it for hours because of it. Continue reading “Archiving your code”