Microsoft Graph API with UWP and Xamarin

Microsoft Graph API with UWP and Xamarin

graphapi1

Short introduction

Microsoft offers a lot of different services in the cloud. Mail, calendar, contacts or files. All these services are available for usage via dedicated web portals and applications. But not only. Now you can also access them with unified APIs wrapped in Graph SDK (available here). In this post you can learn how to use it with Universal Windows Apps and Xamarin Apps (Android and iOS). Just before you was boligated to register your applications via Azure Portal – so you had to have subscription. Now Microsoft did something special – you can register your apps having only Microsoft Account in Apps Portal described below. It make the whole process much faster.

What do I need to start?

1) Visual Studio 2015 Community (for free) or higher

2) Microsoft account

 

Let’s start

1) When you successfully created your Microsoft Account go to Apps portal and sign in.

graphapi15

You will see main panel where you can add new application:

graphapi2

2) Click “Add an app” and type the name:

graphapi3

3) Once application is created you can notice your app id and what is more important – Microsoft Graph Permissions. There are two types of them:

a. User Permissions (Delegated Permissions) – these permissions are set for selected user and are delegated privileges of the signed-in user, allowing the app to act as the user

b. Application Permissions – these permissions are set for the whole application and typically used by apps that run as a service without a signed-in user being present.

graphapi4

In this example we will use user permissions (delegated).

4) Let’s add some permissions for the user:

Click “add” and you will see list of all available permissions – note that you can see description for each of them:

graphapi5

Now select:

a. Contacts Read

b. Mail Read

c. People Read

Then save the configuration.

5) Now add platform and select mobile application. You should see that it is added like below:

graphapi14

That’s it! Now we can configure our mobile apps:

1) Create new project in Visual Studio – select cross-platform tab and below project template:

graphapi6

With this type of project we will make sure to have UWP, iOS and Android application templates.

Remember to rebuild project after creation.

You can also remove older Windows projects to have solution structure like below:

graphapi7

2) To access Graph Api we need to add some NuGet packages described below:

a. Right click on the solution and select “Manage NuGet packages for Solution” and search “Microsoft Graph”. Once you find it please add it to each project:

graphapi12

 

b. Second NuGet to add is called “Microsoft.Identity.Client” – please add it to each project:

graphapi16

3) Now it is time to add code responsible for authentication and connecting with Graph Api:

a. Open “App.xaml.cs” class. We need to initialize “PublicClientApplication” object with application id obtained form the apps portal. It should look like below:

public partial class App : Application
  {
    public static PublicClientApplication IdentityClientApp = null;
    static string ClientID = "<<your app id>>";
    public App()
    {
      InitializeComponent();
      IdentityClientApp = new PublicClientApplication(ClientID);
      MainPage = new MainPage();
    }
 }

b. Now create new folder called “GraphHelpers” and add new class called “GraphClientHelper”:

 public class GraphClientHelper
  {
    //Scopes with the information which specific data you want to retrieve (it was declared in apps portal):
     public static string[] Scopes = {
     "https://graph.microsoft.com/Mail.Read",
     "https://graph.microsoft.com/People.Read",
     "https://graph.microsoft.com/User.Read",
     "https://graph.microsoft.com/Contacts.Read"
     };
    public static string TokenForUser = null;
    public static DateTimeOffset Expiration;
    private static GraphServiceClient graphClient = null;

  public static GraphServiceClient GetAuthenticatedClient()
   {
    if (graphClient == null)
     {
       // Create Microsoft Graph client.
         try
         {
           graphClient = new GraphServiceClient(
           "https://graph.microsoft.com/v1.0",
           new DelegateAuthenticationProvider(
           async (requestMessage) =>
            {
              //Authenticate first if needed:
              var token = await GetTokenForUserAsync();
              requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
           }));
       return graphClient;
   }

  catch (Exception ex)
    {
      Debug.WriteLine("Could not create a graph client: " + ex.Message);
    }
  }

    return graphClient;
  }

    //Authenticate user and acquire token -this will display login dialog:
    public static async Task<string> GetTokenForUserAsync()
     {
       if (TokenForUser == null || Expiration <= DateTimeOffset.UtcNow.AddMinutes(5))
         {
          AuthenticationResult authResult = await App.IdentityClientApp.AcquireTokenAsync(Scopes);
         TokenForUser = authResult.Token;
         Expiration = authResult.ExpiresOn;
         }

     return TokenForUser;
  }

  //Sign out:
   public static void SignOut()
    {
     foreach (var user in App.IdentityClientApp.Users)
      {
        user.SignOut();
      }
   graphClient = null;
   TokenForUser = null;

  }
 }

4. Now we need to add code responsible for launching the authentication and connecting with Graph Api:

a. Open “MainPage.xaml.cs” in portable project and add code responsible for authentication and pulling data from Graph Api:

public partial class MainPage : ContentPage
 {
   //Before authentication you have to set platform parameters for each platform (iIO, Android and UWP):
    public IPlatformParameters platformParameters { get; set; }

    public MainPage()
    {
     InitializeComponent();
    }

  protected async override void OnAppearing()
   {

     App.IdentityClientApp.PlatformParameters = platformParameters;
     var graphClient = GraphClientHelper.GetAuthenticatedClient();

     var me = await graphClient.Me.Request().GetAsync();
     //InfoLabel is the name of label from MainPage view:
     InfoLabel.Text = me.DisplayName;
     InfoLabel.Text = me.JobTitle;
   }
 }

5. One more thing has to be done – for UWP and iOS we need to add Home Page Renderers:

UWP

Create class called “HomePageRenderer” and paste below code:

[assembly: ExportRenderer(typeof(GraphApiSample.MainPage), typeof(HomePageRenderer))]
namespace GraphApiSample.UWP
{
 class HomePageRenderer : PageRenderer
 {
   private GraphApiSample.MainPage page;
   protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Page> e)
    {
      base.OnElementChanged(e);
      page = e.NewElement as GraphApiSample.MainPage;
      page.platformParameters = new PlatformParameters();
   }
  }
}

iOS

Create class called “HomePageRenderer” and paste below code:

[assembly: ExportRenderer(typeof(GraphApiSample.MainPage), typeof(HomePageRenderer))]
namespace GraphApiSample.iOS
{
 class HomePageRenderer : PageRenderer
   {
    GraphApiSample.MainPage page;
    protected override void OnElementChanged(VisualElementChangedEventArgs e)
     {
      base.OnElementChanged(e);
      page = e.NewElement as GraphApiSample.MainPage;
     }
   public override void ViewDidLoad()
    {
     base.ViewDidLoad();
     page.platformParameters = new PlatformParameters(this);
   }
  }
}

Android

[assembly: ExportRenderer(typeof(GraphApiSample.MainPage), typeof(HomePageRenderer))]
namespace GraphApiSample.Droid
{
  class HomePageRenderer : PageRenderer
   {
    MainPage page;

    protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
     {
      base.OnElementChanged(e);
      page = e.NewElement as MainPage;
      var activity = this.Context as Activity;
      page.platformParameters = new PlatformParameters(activity);
   }
 }
}

6. Now launch the app (can be UWP) and see that login window is displayed. Once you enter credentials you can access the data via Graph Api:

graphapi13_3

Once you sign in you should see data displayed on the label.

You can also try it on other platforms (Android and iOS):

graphapi17

Sum up

Now you know how to integrate Microsoft Graph Api with your mobile applications. Remember that you can change permissions and adjust them for your needs.

If you would like to read more about Microsoft Graph please visit this page.

Whole sample is available on my GitHub.

Advertisements