// Get the direct reports of a specified user. // This snippet requires an admin work account. public async Task <List <ResultsItem> > GetDirectReports(GraphServiceClient graphClient, string id) { List <ResultsItem> items = new List <ResultsItem>(); // Get user's direct reports. IUserDirectReportsCollectionWithReferencesPage directs = await graphClient.Users[id].DirectReports.Request().GetAsync(); if (directs?.Count > 0) { foreach (User user in directs) { // Get user properties. items.Add(new ResultsItem { Display = user.DisplayName, Id = user.Id, Properties = new Dictionary <string, object> { { Resource.Prop_Upn, user.UserPrincipalName }, { Resource.Prop_Id, user.Id } } }); } } return(items); }
public IEnumerable <List <DirectoryObject> > GetDirectReports(User user, CancellationToken token) { //string request = client.BaseUrl + $"/users/{user.Id}/directReports"; IUserDirectReportsCollectionWithReferencesPage page = null; try { page = client.Users[user.Id].DirectReports.Request().GetAsync(token).Result; } catch (Exception ex) { HandleException(ex, null, messageOnlyExceptions, $"Get direct reports for user: {user.DisplayName}"); } while (page != null) { yield return(page.ToList()); if (page.NextPageRequest == null) { break; } page = page.NextPageRequest.GetAsync(token).Result; } }
/// <inheritdoc/> internal override async Task <IEnumerable <DirectoryObject> > CallGraphServiceWithResultAsync(IGraphServiceClient client, IReadOnlyDictionary <string, object> parameters, CancellationToken cancellationToken) { string userId = (string)parameters["UserId"]; int maxCount = (int)parameters["MaxResults"]; string propertiesToSelect = (string)parameters["PropertiesToSelect"]; // Create the request first then apply the Top() after IUserDirectReportsCollectionWithReferencesRequest request = client.Users[userId].DirectReports.Request().Select(propertiesToSelect); if (maxCount > 0) { request = request.Top(maxCount); } IUserDirectReportsCollectionWithReferencesPage result = await request.GetAsync(cancellationToken).ConfigureAwait(false); // Again only return the top N results but discard the other pages if the manager has more than N direct reports return(result.CurrentPage); }
// Gets the signed-in user's direct reports. // This snippet doesn't work with consumer accounts. public static async Task <IUserDirectReportsCollectionWithReferencesPage> GetDirectReportsAsync() { IUserDirectReportsCollectionWithReferencesPage directReports = null; try { var graphClient = AuthenticationHelper.GetAuthenticatedClient(); directReports = await graphClient.Me.DirectReports.Request().GetAsync(); foreach (User direct in directReports) { Debug.WriteLine("Got direct report: " + direct.DisplayName); } return(directReports); } catch (ServiceException e) { Debug.WriteLine("We could not get direct reports: " + e.Error.Message); return(null); } }
public static void UserModeRequests() { try { //********************************************************************* // setup Microsoft Graph Client for user. //********************************************************************* if (Constants.ClientIdForUserAuthn != "ENTER_YOUR_CLIENT_ID") { client = AuthenticationHelper.GetAuthenticatedClientForUser(); } else { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("You haven't configured a value for ClientIdForUserAuthn in Constants.cs. Please follow the Readme instructions for configuring this application."); Console.ResetColor(); Console.ReadKey(); return; } } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Acquiring a token failed with the following error: {0}", ex.Message); if (ex.InnerException != null) { //You should implement retry and back-off logic per the guidance given here:http://msdn.microsoft.com/en-us/library/dn168916.aspx //InnerException Message will contain the HTTP error status codes mentioned in the link above Console.WriteLine("Error detail: {0}", ex.InnerException.Message); } Console.ResetColor(); Console.ReadKey(); return; } Console.WriteLine("\nStarting user-mode requests..."); Console.WriteLine("\n=============================\n\n"); // GET current user try { User user = client.Me.Request().GetAsync().Result; Console.WriteLine("Current user: Id: {0} UPN: {1}", user.Id, user.UserPrincipalName); } catch (Exception e) { Console.WriteLine("\nError getting /me user {0} {1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""); } // Get current user photo (work or school accounts only). Returns an exception if no photo exists. try { Stream userPhoto = client.Me.Photo.Content.Request().GetAsync().Result; Console.WriteLine("Got stream photo"); } catch (Exception e) { Console.WriteLine("\nError getting user photo {0} {1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""); } // Get current user's direct reports (work or school accounts only) try { IUserDirectReportsCollectionWithReferencesPage directReports = client.Me.DirectReports.Request().GetAsync().Result; if (directReports.Count == 0) { Console.WriteLine(" no reports"); } else { foreach (User user in directReports) { Console.WriteLine(" Id: {0} UPN: {1}", user.Id, user.UserPrincipalName); } } } catch (Exception e) { Console.WriteLine("\nError getting directReports {0} {1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""); } // Get current user's manager (work or school accounts only). Returns an exception if no manager exists. try { DirectoryObject currentUserManager = client.Me.Manager.Request().GetAsync().Result; User user = client.Users[currentUserManager.Id].Request().GetAsync().Result; Console.WriteLine("\nManager Id: {0} UPN: {1}", user.Id, user.UserPrincipalName); } catch (Exception e) { Console.WriteLine("\nError getting manager {0} {1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""); } // Get current user's files try { List <DriveItem> items = client.Me.Drive.Root.Children.Request().GetAsync().Result.Take(5).ToList(); foreach (DriveItem item in items) { if (item.File != null) { Console.WriteLine(" This is a folder: Id: {0} WebUrl: {1}", item.Id, item.WebUrl); } else { Console.WriteLine(" File Id: {0} WebUrl: {1}", item.Id, item.WebUrl); } } } catch (Exception e) { Console.WriteLine("\nError getting files {0} {1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""); } // Get current user's messages try { List <Message> messages = client.Me.Messages.Request().GetAsync().Result.Take(5).ToList(); if (messages.Count == 0) { Console.WriteLine(" no messages in mailbox"); } foreach (Message message in messages) { Console.WriteLine(" Message: {0} received {1} ", message.Subject, message.ReceivedDateTime); } } catch (Exception e) { Console.WriteLine("\nError getting messages {0} {1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""); } // Get current user's events try { List <Event> events = client.Me.Events.Request().GetAsync().Result.Take(5).ToList(); if (events.Count == 0) { Console.WriteLine(" no events scheduled"); } foreach (Event _event in events) { Console.WriteLine(" Event: {0} starts {1} ", _event.Subject, _event.Start); } } catch (Exception e) { Console.WriteLine("\nError getting events {0} {1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""); } // Get current user's contacts try { List <Contact> contacts = client.Me.Contacts.Request().GetAsync().Result.Take(5).ToList(); if (contacts.Count == 0) { Console.WriteLine(" You don't have any contacts"); } foreach (Contact contact in contacts) { Console.WriteLine(" Contact: {0} ", contact.DisplayName); } } catch (Exception e) { Console.WriteLine("\nError getting contacts {0} {1}", e.Message, e.InnerException != null ? e.InnerException.Message : ""); } // Get the top 10 users and create a recipient list (to be used later) IList <Recipient> messageToList = new List <Recipient>(); // Get 10 users List <User> users = client.Users.Request().GetAsync().Result.Take(10).ToList(); foreach (User user in users) { Recipient messageTo = new Recipient(); EmailAddress emailAdress = new EmailAddress(); emailAdress.Address = user.UserPrincipalName; emailAdress.Name = user.DisplayName; messageTo.EmailAddress = emailAdress; messageToList.Add(messageTo); } // Get current user User currentUser = client.Me.Request().GetAsync().Result; Recipient currentUserRecipient = new Recipient(); EmailAddress currentUserEmailAdress = new EmailAddress(); currentUserEmailAdress.Address = currentUser.UserPrincipalName; currentUserEmailAdress.Name = currentUser.DisplayName; currentUserRecipient.EmailAddress = currentUserEmailAdress; messageToList.Add(currentUserRecipient); // Send mail to signed in user and the recipient list Console.WriteLine(); Console.WriteLine("Sending mail...."); Console.WriteLine(); try { ItemBody messageBody = new ItemBody(); messageBody.Content = "<report pending>"; messageBody.ContentType = BodyType.Text; Message newMessage = new Message(); newMessage.Subject = "\nCompleted test run from console app."; newMessage.ToRecipients = messageToList; newMessage.Body = messageBody; client.Me.SendMail(newMessage, true).Request().PostAsync(); Console.WriteLine("\nMail sent to {0}", currentUser.DisplayName); } catch (Exception) { Console.WriteLine("\nUnexpected Error attempting to send an email"); throw; } // The operations in this method require admin-level consent. Uncomment this line // if you want to run the sample with a non-admin account. // You'll also need to uncomment the Group.Read.All permission scope in AuthenticationHelper.cs //GetDetailsForGroups(); }