Skip to content
This repository has been archived by the owner on Nov 16, 2023. It is now read-only.

[ARCHIVED] Provides a repository of code snippets that use the Microsoft Graph to perform common tasks such as sending email, managing groups, and other activities from within a Xamarin.Forms app. This sample uses the Microsoft Graph .NET Client Library to work with data, and the Microsoft Authentication Library (MSAL) for authentication.

License

Notifications You must be signed in to change notification settings

microsoftgraph/xamarin-csharp-snippets-sample

Repository files navigation

[ARCHIVED] Microsoft Graph SDK Snippets Library for Xamarin.Forms

IMPORTANT

This project is being archived and replaced with the Build Xamarin apps with the Microsoft Graph .NET SDK training. As part of the archival process, we're closing all open issues and pull requests.

You can continue to use this sample "as-is", but it won't be maintained moving forward. We apologize for any inconvenience.

Table of contents

This sample project provides a repository of code snippets that use the Microsoft Graph to perform common tasks, such as sending email, managing groups, and other activities from within a Xamarin.Forms app. It uses the Microsoft Graph .NET Client SDK to work with data returned by Microsoft Graph.

The sample uses the Microsoft Authentication Library (MSAL) for authentication. The MSAL SDK provides features for working with the Azure AD v2.0 endpoint, which enables developers to write a single code flow that handles authentication for both users' work or school (Azure Active Directory) or personal (Microsoft) accounts, including Office 365, Outlook.com, and OneDrive accounts.

Important Note about the MSAL Preview

This library is suitable for use in a production environment. We provide the same production level support for this library as we do our current production libraries. During the preview we may make changes to the API, internal cache format, and other mechanisms of this library, which you will be required to take along with bug fixes or feature improvements. This may impact your application. For instance, a change to the cache format may impact your users, such as requiring them to sign in again. An API change may require you to update your code. When we provide the General Availability release we will require you to update to the General Availability version within six months, as applications written using a preview version of library may no longer work.

The app displays UI representing common user tasks, or 'stories'. Each story is comprised of one or more code snippets. The stories are grouped by the account type and permission level. The user can log into their account and run the selected stories. Each story turns green if it succeeds, and red if it fails. Additional information is sent to the Output window.

Prerequisites

This sample requires the following:

If you want to run the iOS project in this sample, you'll need the following:

You can use the Visual Studio Emulator for Android if you want to run the Android project.

Register the application

  1. Navigate to the the Azure portal - App registrations to register your app. Login using a Work or School Account.

  2. Select New registration. On the Register an application page, set the values as follows.

  • Set Name to Graph-Xamarin-CS-Snippets.
  • Set Supported account types to Accounts in any organizational directory.
  • Leave Redirect URI empty.
  • Choose Register.
  1. On the Graph-Xamarin-CS-Snippets page, copy and save the values for the Application (client) ID and the Directory (tenant) ID. You will need them in step 7.

  2. Select Certificates & secrets under Manage. Select the New client secret button. Enter a value in Description, select any option for Expires and choose Add.

  3. Copy the client secret value before leaving the page. You will need it in the next step.

  4. Open the sample solution in Visual Studio and then open the App.cs file. Change the CliendID string to the Application (client) ID value.

  5. Return to the Azure Active Directory management center. Select API permissions and then select Add a permission. On the panel that appears, choose Microsoft Graph and then choose Application permissions.

  6. Use the Select permissions search box to search for the following permissions: User.Read, Group.ReadWrite.All, Sites.Read.All, Files.ReadWrite.All, Tasks.ReadWrite, Directory.Read.All. Select the check box for each permission as it appears (note that the permissions will not remain visible in the list as you select each one). Select the Add permissions button at the bottom of the panel.

  7. Choose the Grant admin consent for [tenant name] button. Select Yes for the confirmation that appears.

Build and debug

Note: If you see any errors while installing packages during step 2, make sure the local path where you placed the solution is not too long/deep. Moving the solution closer to the root of your drive resolves this issue.

  1. Open the App.cs file inside the Graph_Xamarin_CS_Snippets (Portable) project of the solution.

    Screenshot of the Solution Explorer pane in Visual Studio, with App.cs file selected in the Graph_Xamarin_CS_Snippets project

  2. After you've loaded the solution in Visual Studio, configure the sample to use the client id that you registered by making this the value of the ClientId variable in the App.cs file.

    Screenshot of the ClientId variable in the App.cs file, currently set to an empty string.

  3. If you are planning on signing into the sample with a work or school account that does not have admin permissions, you'll need to comment out code that requests scopes that require admin permissions. If you don't comment out these lines, you won't be able to sign in with your work or school account (if you sign in with a personal account, these scope requests are ignored.)

    In the GetTokenForUserAsync() method of the AuthenticationHelper.cs file, comment out the following scope requests:

    	"https://graph.microsoft.com/Directory.AccessAsUser.All",
        "https://graph.microsoft.com/User.ReadWrite.All",
        "https://graph.microsoft.com/Group.ReadWrite.All",
    
  4. Select the project that you want to run. If you select the Universal Windows Platform option, you can run the sample on the local machine. If you want to run the iOS project, you'll need to connect to a Mac that has the Xamarin tools installed on it. (You can also open this solution in Xamarin Studio on a Mac and run the sample directly from there.) You can use the Visual Studio Emulator for Android if you want to run the Android project.

    Screenshot of the Visual Studio toolbar, with iOS selected as the start-up project.

  5. Press F5 to build and debug. Run the solution and sign in with either your personal or work or school account.

    Note You might have to open the Build Configuration Manager to make sure that the Build and Deploy steps are selected for the UWP project.

Run the sample

When launched, the app displays a list representing common user tasks, or 'stories'. Each story is comprised of one or more code snippets. The stories are grouped by the account type and permission level:

  • Tasks that are applicable to both work or school and personal accounts, such as getting and sending email, creating files, etc.
  • Tasks that are only applicable to work or school accounts, such as getting a user's manager or account photo.
  • Tasks that are only applicable to a work or school account with administrative permissions, such as getting group members or creating new user accounts.

Select the stories you want to execute, and choose the 'run selected' button. You'll be prompted to log in with your work or school or personal account. Be aware that if you log in with an account that doesn't have applicable permissions for the stories you've selected (for example, if you select stories that are applicable only to a work or school account, and then log in with a personal account), those stories will fail.

Each story turns green if it succeeds, and red if it fails. Additional information is sent to the Output window.

##How the sample affects your account data

This sample runs commands that create, read, update, or delete data. It will not edit or delete your actual account data. However, it may create and leave data artifacts in your account as part of its operation: when running commands that create, update or delete, the sample creates fake entities, such as new users or groups, so as not to affect your actual account data.

The sample may leave behind such fake entities in your account, if you choose stories that create or update entities. For example, choosing the run the 'update group' story creates a new group, then updates it. In this case, the new group remains in your account after the sample has run.

Add a snippet

This project includes two snippets files:

  • Groups\GroupSnippets.cs
  • Users\UserSnippets.cs.

If you have a snippet of your own that you would like to run in this project, just follow these three steps:

  1. Add your snippet to the snippets file. Be sure to include a try/catch block.

     public static async Task<string> GetMeAsync()
     {
         string currentUserName = null;
    
         try
         {
             var graphClient = AuthenticationHelper.GetAuthenticatedClientAsync();
    
             var currentUserObject = await graphClient.Me.Request().GetAsync();
             currentUserName = currentUserObject.DisplayName;
    
             if ( currentUserName != null)
             {
                 Debug.WriteLine("Got user: " + currentUserName);
             }
    
         }
    
  2. Create a story that uses your snippet and add it to the associated stories file. For example, the TryGetMeAsync() story uses the GetMeAsync() snippet inside the Users\UserStories.cs file:

     public static async Task<bool> TryGetMeAsync()
     {
         var currentUser = await UserSnippets.GetMeAsync();
    
         return currentUser != null;
     }        
    

Sometimes your story will need to run snippets in addition to the one that you're implementing. For example, if you want to update an event, you first need to use the CreateEventAsync() method to create an event. Then you can update it. Always be sure to use snippets that already exist in the snippets file. If the operation you need doesn't exist, you'll have to create it and then include it in your story. It's a best practice to delete any entities that you create in a story, especially if you're working on anything other than a test or developer account.

  1. Add your story to the story list in MainPage.xaml.cs (inside the CreateStoryList() method):

    snippetList.Children.Add(new CheckBox { StoryName = "Get Me", GroupName = "Users", AccountType = "All", RunStoryAsync = UserStories.TryGetMeAsync });

Now you can test your snippet. When you run the app, your story will appear as a new item. Select the check box for your snippet, and then run it. Use this as an opportunity to debug your snippet.

Questions and comments

We'd love to get your feedback about the Microsoft Graph Snippets Sample for Xamarin.Forms project. You can send your questions and suggestions to us in the Issues section of this repository.

Your feedback is important to us. Connect with us on Stack Overflow. Tag your questions with [MicrosoftGraph].

Contributing

If you'd like to contribute to this sample, see CONTRIBUTING.MD.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.

Additional resources

Copyright

Copyright (c) 2017 Microsoft. All rights reserved.

About

[ARCHIVED] Provides a repository of code snippets that use the Microsoft Graph to perform common tasks such as sending email, managing groups, and other activities from within a Xamarin.Forms app. This sample uses the Microsoft Graph .NET Client Library to work with data, and the Microsoft Authentication Library (MSAL) for authentication.

Topics

Resources

License

Code of conduct

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages