Friday 29 May 2015

Calling Office 365 Unified API(Preview) from .Net Native Application

The Office 365 unified API provides developers with a single endpoint for accessing all Office 365 data and relationships, including Users, Groups, Files, Mail, Calendar, Contacts and Office Graph. Office 365 Unified API removes the complexity in accessing Office 365 data and makes development simpler. Client libraries to access Office 365 API are available for .Net, Android and iOS platforms.  I’ll explain the process of developing a sample application using the Office 365 Unified API client library for .Net platform. 

For developing a .Net application with Office 365 Unified API client library the below prerequisites have to be met 

1.       Visual Studio 2013 or higher

2.       Office 365 Tenant ( Trial subscription can be used)

3.       Microsoft Azure Tenant (Trial subscription can be used).  

Note: The Azure subscription should be tied to the Office 365 account.
Once we have the prerequisites ready we can start with development of .net application.  The first step is to register the application we are developing in Azure.

Register the application Microsoft Azure

  1. Logon to Azure Management Portal, using your Azure AD credentials.
  2. Click Active Directory on the left menu, then select the directory for your Office 365  tenant.
  3. Click Applications from the top menu.
  4. Click Add from the bottom tray.
  5. On the What do you want to do? page, select Add an application my organization is developing.
  6. On the Tell us about your application page, enter the application name as O365UnifiedAPITest and select the type as NATIVE CLIENT APPLICATION.
  7. Click the arrow on the bottom right to move to next page.
  8. On the Application information page, specify http://localhost/Office365APITest as Redirect URI, and then click the tick mark on bottom right.
  9. Once the application has been added, you will be taken to the Quick Start page for the application. From the application page, click Configure from the top menu.
  10. Copy the value specified for Client ID on the Configure page and save it to notepad or similar tool.
  11. Click Add application button under permissions to other applications section and in the dialog box that opens, select the Office 365 unified API (preview) application and click the tick mark on bottom right.
  12. On the application configuration page, select Office 365 unified API (preview) and select Read directory data permission.
  13. Click Save in the bottom menu.
After registering the application in Azure we can go about developing our .Net application. For this example I will be using a Windows Form application that displays user details in a grid.

1.       Fire up Visual Studio 2013 and create a new Windows Form application.

2.       Add the below the Office 365 Unified API client library and dependencies from NuGet packages
    1. Active Directory Authentication Library
    2. Office 365 unified API client library (preview)
    3. Microsoft OData Proxy Extensions Library for .NET
       3.       Add a button and data grid to the Windows Form

4.       Add the below code to the button click event to initialize Office 365 unified API client

Uri O365APIURI= new Uri(APIRootURL);

       Microsoft.Graph.GraphService graphclient = new

        Microsoft.Graph.GraphService(O365APIURI,   async () => await GetToken());

APIRootURL is the URL of the Office 365 Unified API which is of the form


 
5.       GetToken function passed in the GraphService constructor gets the access token for our application and prompting for Azure credentials.  The function will be implemented as below

public async Task<string> GetToken()

        {
            var redirectUri = new Uri(RedirectURL);

            AuthenticationContext authenticationContext =

            new AuthenticationContext(LoginUrl, false);

            if (AuthToken == "")

            {
                AuthenticationResult AuthnResult = authenticationContext.AcquireToken(

                             ResourceUrl,

                             AppClientId,

                             RedirectUri,

                             PromptBehavior.Always
                         );

                AuthToken = AuthnResult.AccessToken;

            }
            return AuthToken;

        }
In this code above, the AuthenticationContext class is exposed by ADAL for .NET and handles the authorization and token acquisition process. LoginUrl is the URL of the Azure login page which is https://login.microsoftonline.com/common. Next we call the AcquireToken method on the AuthenticationContext object and pass ResourceUrl, AppClientId and RedirectUri as parameters. The RedirectUri is the REPLY URI and AppClientId is the CLIENT ID of the app we have configured for the app in Azure during application registration process. ResourceUrl is a string with value of "https://graph.microsoft.com”.

The AcquireToken method will display the Azure login page and prompt for credentials. After successful sign in to Azure, the access token is acquired and can be used in subsequent calls to the Office 365 unified API.

6.       Next create a method that will get the list of users from Office 365 whose type is Member. The method will be implemented as below
public async Task<List<IUser>> GetUsersAsync(Microsoft.Graph.GraphService client)

        {
            List<IUser> userList = null;

            var graphClient = client;

             var userResult = await graphClient.users.Where(u => u.userType == "Member").ExecuteAsync();

             userList = userResult.CurrentPage.ToList();

             return userList;
   }

In the code above ExecuteAsync method fetches the users and the where clause is used to filter only members. 

7.       We then invoke the GetUsersAsync method from button click event and bind the result to data grid.
  List<IUser> userList  = await GetUsersAsync(graphclient);
dataGridView1.DataSource = userList;

8.       When we execute the application and hit the button, user will be prompted to Azure login and after successful login user list will be displayed in the data grid.


We saw an example of calling Office 365 Unified API from a .Net native application. Office 365 Unified API provides many other options for accessing and manipulating data from Office 365 services. Click here to for the complete reference of Office 365 Unified API.