[Huawei Developers] devwithzachary:
Xamarin (Microsoft) is a multi-system development platform for mobile services that many developers use. Many AppGallery Connect services now support Xamarin, including Auth Service. Here I’ll explain on how to integrate Auth Service into your Xamarin.Android app and use the 3rd party auth support for Facebook.

Install the Xamarin environment and project setup.​

You’ll need to first download and install Visual Studio 2019.

Open Visual Studio and select Mobile development with .NET to install the Xamarin environment.

Next make sure you have enabled the Auth Service in AppGallery Connect.

Open Visual Studio, click Create a new project in the start window, select Mobile App (Xamarin.Forms), and set the app name and other required information.

Right-click your project and choose Manage NuGet Packages.

Search for the Huawei.Agconnect.Auth package on the displayed page and install it.

Download the JSON service file from your AppGallery project and add it into the *Assets directory in your project.

Create a new class named HmsLazyInputStreams.cs, and implement the following code to read the JSON file.

using System;
using System.IO;
using Android.Content;
using Android.Util;
using Huawei.Agconnect.Config;

namespace AppLinking1
{
public class HmsLazyInputStream : LazyInputStream
{
public HmsLazyInputStream(Context context)
: base(context)
{
}

public override Stream Get(Context context)
{
try
{
return context.Assets.Open("agconnect-services.json");
}
catch (Exception e)
{
Log.Error("Hms", $"Failed to get input stream" + e.Message);
return null;
}
}
}
}

Right-click your project and choose Properties. Click Android Manifest on the displayed page and set a package name

Follow the process that Facebook describes to setup your application with their platform. Details can be found here

Finally the last thing we need to do is install the Xamarin Facebook login package.

Right-click your project and choose Manage NuGet Packages. Search for Xamarin.Facebook.Login.Android and install it.

Implement Facebook Auth​

Create a login button within your application, this will use the below code to start the login process getting the specific requested account details from Facebook and process this using the call back.

private void ImgFacebook_Click(object sender, EventArgs e){
callBackManager = CallbackManagerFactory.Create();
ICollection<string> collection = new List<string>();
collection.Add("public_profile");
collection.Add("user_friends");
LoginManager.Instance.LogInWithReadPermissions(this, collection);
LoginManager.Instance.RegisterCallback(callBackManager, new FacebookCallback(this));
}

The Facebook Callback then looks like:

private class FacebookCallback : Java.Lang.Object, IFacebookCallback {
LoginActivity loginActivity;
public FacebookCallback(LoginActivity loginActivity) {
this.loginActivity = loginActivity;
}
public void OnCancel() {
Log.Debug("IFacebookCallback", "Cancelled.");
}

public void OnError(FacebookException error) {
Log.Error("IFacebookCallback", "Failed: " + error.Message);
}

public void OnSuccess(Java.Lang.Object result) {
LoginResult loginResult = (LoginResult)result;

Log.Debug("IFacebookCallback", "Facebook login successfuly. Access token: " + loginResult.AccessToken.Token);
IAGConnectAuthCredential credential = FacebookAuthProvider.CredentialWithToken(loginResult.AccessToken.Token);
try {
AGConnectAuth connectAuth = AGConnectAuth.Instance;
var signInResult = AGConnectAuth.Instance.SignInAsync(credential);

ISignInResult result = await signInResult;

if (signInResult.Status.Equals(System.Threading.Tasks.TaskStatus.RanToCompletion)){
Log.Debug(TAG, signInResult.Result.ToString());
StartActivity(new Intent(this, typeof(MainActivity)));
Finish();
}
} catch (Exception ex) {
Log.Error(TAG, ex.Message);
Toast.MakeText(this, "SignIn failed: " + ex.Message, ToastLength.Long).Show();
}

}
}

In the OnSuccess method, we have obtained the access token and generated a credential for Facebook Login, and called SignInAsync to pass the credential for sign-in.

Finally, forward OnActivityResult to the callBackManager.

if (requestCode == 64206){
callBackManager.OnActivityResult(requestCode, (int)resultCode, data);
}

The result code 64206 is defined by Facebook in its Login SDK. It is used to identify the callback for Facebook Login when there are multiple callbacks in OnActivityResult. An interesting fact is that, the hexadecimal value of 64206 is 0xFACE, which is a little trick from Facebook.