Пример #1
0
        public List <UserViewModel> Get(string search)
        {
            var viewModel = new List <UserViewModel>();
            var token     = _tokenService.Get();

            GraphServiceClient graphClient = new GraphServiceClient(token.AuthProvider);

            IGraphServiceUsersCollectionPage users = graphClient.Users
                                                     .Request()
                                                     .Filter(search != null ? $"startswith(givenName, '{search}') or startswith(surName, '{search}') or startswith(displayName, '{search}') or startswith(mail, '{search}') or startswith(userPrincipalName, '{search}')" : "")
                                                     .Top(_recordsLimit)
                                                     .GetAsync().Result;

            foreach (var user in users.CurrentPage)
            {
                viewModel.Add(new UserViewModel
                {
                    Id                = user.Id,
                    DisplayName       = user.DisplayName,
                    BusinessPhones    = user.BusinessPhones,
                    GivenName         = user.GivenName,
                    JobTitle          = user.JobTitle,
                    Mail              = user.Mail,
                    MobilePhone       = user.MobilePhone,
                    OfficeLocation    = user.OfficeLocation,
                    PreferredLanguage = user.PreferredLanguage,
                    Surname           = user.Surname,
                    UserPrincipalName = user.UserPrincipalName
                });
            }
            return(viewModel);
        }
Пример #2
0
        private string GetNextLink(IGraphServiceUsersCollectionPage graphUsers)
        {
            var gusers   = (GraphServiceUsersCollectionPage)graphUsers;
            var nextLink = (gusers.AdditionalData.ContainsKey("@odata.nextLink")) ? gusers.AdditionalData["@odata.nextLink"] as string : "";

            return(nextLink);
        }
        public async Task <IViewComponentResult> InvokeAsync()
        {
            IGraphServiceUsersCollectionPage users   = null;
            List <Microsoft.Graph.User>      MyUsers = null;

            users = await _graphClient.Users.Request()
                    .Select("displayName,mail,userPrincipalName")
                    .GetAsync();

            MyUsers = new List <Microsoft.Graph.User>();



            foreach (var u in users)
            {
                MyUsers.Add(new Microsoft.Graph.User
                {
                    Id                = u.Id,
                    DisplayName       = u.DisplayName,
                    Mail              = u.Mail,
                    UserPrincipalName = u.UserPrincipalName
                });
            }
            return(View(users));
        }
Пример #4
0
        // Get all users.
        public async Task <List <ResultsItem> > GetUsers(GraphServiceClient graphClient)
        {
            List <ResultsItem> items = new List <ResultsItem>();

            // Get users.
            IGraphServiceUsersCollectionPage users = await graphClient.Users.Request().GetAsync();

            // Populate the view model.
            if (users?.Count > 0)
            {
                foreach (User user in users)
                {
                    // Filter out conference rooms.
                    string displayName = user.DisplayName ?? "";
                    if (!displayName.StartsWith("Conf Room"))
                    {
                        // Get user properties.
                        items.Add(new ResultsItem
                        {
                            Display = user.DisplayName,
                            Id      = user.Id
                        });
                    }
                }
            }
            return(items);
        }
Пример #5
0
        public async Task <IList <Models.User> > GetUsersAsync()
        {
            try
            {
                IGraphServiceUsersCollectionPage users = await graphClient.Users.Request(requestOptions).Top(20)
                                                         .Select(e => new { e.DisplayName, e.UserPrincipalName, e.UserType, e.AssignedLicenses })
                                                         .GetAsync();

                List <Models.User> values = new List <Models.User>();
                foreach (User user in users.CurrentPage)
                {
                    Models.User value = new Models.User()
                    {
                        ObjectId          = user.Id,
                        UserName          = user.DisplayName,
                        UserPrincipalName = user.UserPrincipalName,
                        UserType          = user.UserType
                    };
                    values.Add(value);
                }
                return(values);
            }
            catch
            {
                throw;
            }
        }
Пример #6
0
        public IEnumerable <List <User> > FindUsersStartsWith(string field, string text, CancellationToken token)
        {
            IGraphServiceUsersCollectionPage page = null;

            try
            {
                page = client.Users.Request()
                       .Filter($"startswith({field}, '{text}')")
                       .GetAsync(token).Result;
            }
            catch (Exception ex)
            {
                HandleException(ex, null, messageOnlyExceptions, "");
            }

            while (page != null)
            {
                yield return(page.ToList());

                if (page.NextPageRequest == null)
                {
                    break;
                }
                page = page.NextPageRequest.GetAsync(token).Result;
            }
        }
Пример #7
0
        /// <summary>
        /// Gets the users in a tenant.
        /// </summary>
        /// <param name="accessToken">The access token for MS Graph.</param>
        /// <returns>
        /// A list of users
        /// </returns>
        public async Task <IEnumerable <User> > GetUsersAsync(string accessToken)
        {
            IGraphServiceUsersCollectionPage users = null;

            try
            {
                PrepareAuthenticatedClient(accessToken);

                // Using Graph SDK to get users, filtering by active ones and returning just id and userPrincipalName field
                users = await graphServiceClient.Users.Request()
                        .Filter($"accountEnabled eq true")
                        .Select("id, userPrincipalName")
                        .GetAsync();

                if (users?.CurrentPage.Count > 0)
                {
                    return(users);
                }
            }
            catch (ServiceException e)
            {
                Debug.WriteLine("We could not retrieve the user's list: " + $"{e}");
                return(null);
            }

            return(users);
        }
Пример #8
0
        /// <summary>
        /// Gets the users in a tenant.
        /// </summary>
        /// <param name="accessToken">The access token for MS Graph.</param>
        /// <returns>
        /// A list of users
        /// </returns>
        public async Task <List <User> > GetUsersAsync(string accessToken)
        {
            List <User> allUsers = new List <User>();

            try
            {
                PrepareAuthenticatedClient(accessToken);
                IGraphServiceUsersCollectionPage users = await graphServiceClient.Users.Request().GetAsync();

                // When paginating
                //while(users.NextPageRequest != null)
                //{
                //    users = await users.NextPageRequest.GetAsync();
                //}

                if (users?.CurrentPage.Count > 0)
                {
                    foreach (User user in users)
                    {
                        allUsers.Add(user);
                    }
                }
            }
            catch (ServiceException e)
            {
                Debug.WriteLine("We could not retrieve the user's list: " + $"{e}");
                return(null);
            }

            return(allUsers);
        }
Пример #9
0
        public async Task <IEnumerable <DirectoryUser> > GetDirectoryUsersAsync(string searchTerm)
        {
            if (string.IsNullOrEmpty(searchTerm))
            {
                throw new ArgumentNullException(nameof(searchTerm));
            }

            if (searchTerm.Length < 3)
            {
                throw new ValidationException("The searchTerm must be at least 3 characters long.");
            }

            List <DirectoryUser> directoryUsers = new List <DirectoryUser>();

            IGraphServiceUsersCollectionPage users = await _graphClient.SearchUsersAsync(searchTerm);

            if (users?.Count > 0)
            {
                foreach (User user in users)
                {
                    var directoryUser = user.MapToDirectoryUser();

                    directoryUsers.Add(directoryUser);
                }
            }

            return(directoryUsers);
        }
Пример #10
0
        public async Task FindUserAsync_Should_ThrowException_IfResultIsNull()
        {
            IGraphServiceUsersCollectionPage collectionPage = null;

            _mockUsersCollectionRequest.Setup(x => x.GetAsync()).Returns(Task.FromResult(collectionPage));

            await Assert.ThrowsAsync <EntityNotFoundException>(() => _remoteGraphService.FindActiveUserAsync(string.Empty));
        }
Пример #11
0
 private IEnumerable <Models.User> ToUserObjects(IGraphServiceUsersCollectionPage graphUsers)
 {
     return(graphUsers.Select(graphUser => new Models.User()
     {
         UserId = graphUser.Id,
         DisplayName = graphUser.DisplayName
     }));
 }
        public async Task <string> GetUserMap()
        {
            IGraphServiceClient client = await _graphService.GetGraphServiceClient();

            IGraphServiceUsersCollectionPage userList = await client.Users.Request().GetAsync();

            Users users = new Users();

            users.resources.AddRange(_mapper.Map <List <models.User> >(userList));

            return(JsonConvert.SerializeObject(userList, Formatting.Indented));
        }
Пример #13
0
        private static void DisplayUsers(IGraphServiceUsersCollectionPage users)
        {
            Console.WriteLine(users.Count);

            int counter = 0;

            foreach (var user in users)
            {
                counter++;
                Console.WriteLine($"{counter:000} | {user.Id} => {user.DisplayName} <{user.UserPrincipalName}>");
            }
        }
        private async Task<PrincipalsViewModel> MapUsers(IGraphServiceUsersCollectionPage source)
        {
            PrincipalsViewModel result = new PrincipalsViewModel();

            if (source != null)
            {
                foreach (var u in source.Where(us => !String.IsNullOrEmpty(us.Mail)))
                {
                    result.Principals.Add(await MapUser(u));
                }
            }

            return result;
        }
        public async Task <IReadOnlyList <UserEntity> > GetAllUsersAsync()
        {
            List <User> users = new List <User>();

            try
            {
                IGraphServiceUsersCollectionPage iGraphServiceUsersCollectionPage = await _graphServiceClient.Users
                                                                                    .Request()
                                                                                    .Select($"id," +
                                                                                            $" userPrincipalName," +
                                                                                            $" givenName," +
                                                                                            $" surname")
                                                                                    .Top(50)
                                                                                    .GetAsync();

                var userPageIterator = PageIterator <User> .CreatePageIterator(_graphServiceClient,
                                                                               iGraphServiceUsersCollectionPage,
                                                                               entity => { users.Add(entity); return(true); });

                await userPageIterator.IterateAsync();
            }

            catch (ServiceException ex)
            {
                if (ex.StatusCode == System.Net.HttpStatusCode.TooManyRequests)
                {
                    _logger.LogError(LoggerEvents.MicrosoftGraphTooManyRequests, string.Concat(ex.Message, " ", ex.InnerException?.Message));
                    var retryAfter = ex.ResponseHeaders.RetryAfter.Delta.Value;
                    await Task.Delay(TimeSpan.FromSeconds(retryAfter.TotalSeconds));
                    await GetAllUsersAsync();
                }

                else
                {
                    throw;
                }
            }

            var userEntities = users
                               .Select(u => new UserEntity()
            {
                Id        = u.Id,
                Email     = u.UserPrincipalName,
                FirstName = u.GivenName,
                LastName  = u.Surname
            })
                               .ToList();

            return(userEntities);
        }
Пример #16
0
        private async Task <PrincipalsViewModel> MapUsers(IGraphServiceUsersCollectionPage source)
        {
            PrincipalsViewModel result = new PrincipalsViewModel();

            if (source != null)
            {
                foreach (var u in source.Where(us => !String.IsNullOrEmpty(us.Mail)))
                {
                    result.Principals.Add(await MapUser(u));
                }
            }

            return(result);
        }
        private async Task <List <User> > GetUsersAsync(IGraphServiceClient client)
        {
            IGraphServiceUsersCollectionPage data = await client.Users.Request().Top(500).GetAsync().ConfigureAwait(false);

            List <User> users = new List <User>(data.CurrentPage);

            while (data.NextPageRequest != null)
            {
                data = await data.NextPageRequest.GetAsync(CancellationToken).ConfigureAwait(false);

                users.AddRange(data.CurrentPage);
            }

            return(users);
        }
        private static async Task <IEnumerable <User> > CallGraphApiOnBehalfOfUser(string accessToken)
        {
            // Call the Graph API and retrieve the user's profile.
            GraphServiceClient graphServiceClient  = GetGraphServiceClient(accessToken);
            IGraphServiceUsersCollectionPage users = await graphServiceClient.Users.Request()
                                                     .Filter($"accountEnabled eq true")
                                                     .Select("id, userPrincipalName")
                                                     .GetAsync();

            if (users != null)
            {
                return(users);
            }
            throw new Exception();
        }
Пример #19
0
        private async Task <PrincipalsViewModel> MapUsers(IGraphServiceUsersCollectionPage source)
        {
            PrincipalsViewModel result = new PrincipalsViewModel();

            if (source != null)
            {
                foreach (var u in source)
                {
                    u.Mail = (string.IsNullOrEmpty(u.Mail)) ? u.UserPrincipalName : u.Mail;
                    result.Principals.Add(await MapUser(u));
                }
            }

            return(result);
        }
Пример #20
0
        /// <summary>
        /// Executes the operations associated with the cmdlet.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            IGraphServiceUsersCollectionPage data = Graph.Users.Request().GetAsync().ConfigureAwait(false).GetAwaiter().GetResult();
            List <User> users = new List <User>();

            users.AddRange(data.CurrentPage);

            while (data.NextPageRequest != null)
            {
                data = data.NextPageRequest.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult();
                users.AddRange(data.CurrentPage);
            }

            WriteObject(users, true);
        }
Пример #21
0
        public async Task <List <Microsoft.Graph.User> > GetUserList()
        {
            List <Microsoft.Graph.User>      userResult  = new List <Microsoft.Graph.User>();
            GraphServiceClient               graphClient = new GraphServiceClient(new AzureAuthenticationProvider());
            IGraphServiceUsersCollectionPage users       = await graphClient.Users.Request().Top(500).GetAsync(); // The hard coded Top(500) is what allows me to pull all the users, the blog post did this on a param passed in

            userResult.AddRange(users);

            while (users.NextPageRequest != null)
            {
                users = await users.NextPageRequest.GetAsync();

                userResult.AddRange(users);
            }
            return(userResult);
        }
Пример #22
0
        public static async Task <string> getUserUid(string upn)
        {
            GraphServiceClient gsc = await AuthenticationHelper.GetGraphServiceClientAsUser();

            IGraphServiceUsersCollectionPage iucp = await gsc.Users.Request().Filter("UserPrincipalName eq '" + upn + "'").GetAsync();

            IList <User> ul = iucp.CurrentPage;

            if (ul.Count != 1)
            {
                return(null);
            }
            User u = ul.First();

            return(u.AdditionalData["objectId"].ToString());
        }
Пример #23
0
        public async Task <NeoQueryData> CollectDataAsync()
        {
            this.UserIDs = new List <string>();
            NeoQueryData  querydata    = new NeoQueryData();
            List <object> propertylist = new List <object>();

            IGraphServiceUsersCollectionRequest request = Connector.Instance.Client.Users.Request();

            request.Top(999);

            IGraphServiceUsersCollectionPage page = null;

            await Connector.Instance.MakeGraphClientRequestAsync(async() =>
            {
                page = await request.GetAsync();
            });

            while (page != null)
            {
                foreach (User user in page.CurrentPage)
                {
                    this.UserIDs.Add(user.Id);

                    propertylist.Add(new
                    {
                        ID      = user.Id,
                        Enabled = user.AccountEnabled,
                        UPN     = user.UserPrincipalName,
                        Name    = user.DisplayName
                    });
                }

                if (page.NextPageRequest == null)
                {
                    break;
                }

                await Connector.Instance.MakeGraphClientRequestAsync(async() =>
                {
                    page = await page.NextPageRequest.GetAsync();
                });
            }

            querydata.Properties = propertylist;
            return(querydata);
        }
        // Returns all of the users in the directory of the signed-in user's tenant.
        public static async Task <IGraphServiceUsersCollectionPage> GetUsersAsync()
        {
            IGraphServiceUsersCollectionPage users = null;

            try
            {
                var graphClient = AuthenticationHelper.GetAuthenticatedClient();
                users = await graphClient.Users.Request().GetAsync();

                return(users);
            }

            catch (ServiceException e)
            {
                Debug.WriteLine(SampleStrings.GetUsersFailedDebug + e.Error.Message);
                return(null);
            }
        }
Пример #25
0
        /// <summary>
        /// The following example shows how to initialize the MS Graph SDK
        /// </summary>
        /// <param name="app"></param>
        /// <param name="scopes"></param>
        /// <returns></returns>
        private static async Task CallMSGraphUsingGraphSDK(IConfidentialClientApplication app, string[] scopes)
        {
            // Prepare an authenticated MS Graph SDK client
            GraphServiceClient graphServiceClient = GetAuthenticatedGraphClient(app, scopes);


            List <User> allUsers = new List <User>();

            try
            {
                IGraphServiceUsersCollectionPage users = await graphServiceClient.Users.Request().GetAsync();

                Console.WriteLine($"Found {users.Count()} users in the tenant");
            }
            catch (ServiceException e)
            {
                Console.WriteLine("We could not retrieve the user's list: " + $"{e}");
            }
        }
        /// <summary>
        /// Get paginated user list from the current user AzureAD
        /// </summary>
        /// <param name="_tenantID"></param>
        /// <param name="_clientId"></param>
        /// <param name="_clientSecret"></param>
        /// <returns>MS Graph user enumerable with users emails</returns>
        private async Task <IEnumerable <User> > GetUserList(string _tenantID, string _clientId, string _clientSecret)
        {
            try
            {
                GraphServiceClient graphServiceClient = GetGraphServiceClient(_tenantID, _clientId, _clientSecret);

                IGraphServiceUsersCollectionPage users = await graphServiceClient.Users.Request()
                                                         .Filter($"accountEnabled eq true")
                                                         .Select("mail, displayName")
                                                         .GetAsync();

                return(users);
            }
            catch (Exception e)
            {
                _logger.LogError(e.ToString());
                return(new List <User>());
            }
        }
Пример #27
0
        /// <summary>
        /// GetUsersAsync.
        /// </summary>
        /// <param name="name">name.</param>
        /// <returns>Task contains List of Users.</returns>
        public async Task <List <User> > GetUserAsync(string name)
        {
            List <User> items = new List <User>();

            var optionList   = new List <QueryOption>();
            var filterString = $"startswith(displayName, '{name}') or startswith(givenName,'{name}') or startswith(surname,'{name}') or startswith(mail,'{name}') or startswith(userPrincipalName,'{name}')";

            optionList.Add(new QueryOption("$filter", filterString));

            IGraphServiceUsersCollectionPage users = null;

            // Get the current user's profile.
            try
            {
                users = await this._graphClient.Users.Request(optionList).GetAsync();
            }
            catch (ServiceException ex)
            {
                throw GraphClient.HandleGraphAPIException(ex);
            }

            if (users?.Count > 0)
            {
                foreach (User user in users)
                {
                    // Filter out conference rooms.
                    string displayName = user.DisplayName ?? string.Empty;
                    if (!displayName.StartsWith("Conf Room"))
                    {
                        // Get user properties.
                        items.Add(user);
                    }

                    if (items.Count >= 10)
                    {
                        break;
                    }
                }
            }

            return(items);
        }
Пример #28
0
        public async Task <IGraphServiceUsersCollectionPage> GetUsers(ODataQueryOptions queryOptions)
        {
            IGraphServiceUsersCollectionPage requestTask = null;
            string filter = queryOptions.Filter == null ? "" : queryOptions.Filter.RawValue;

            try
            {
                requestTask = await graphClient.Users
                              .Request()
                              .Filter(filter)
                              .Select($"id,displayName,identities,{customerNumberAttributeName},{webRoleAttributeName},{ TenantIdAttributeName},{ CompanyIdAttributeName}")
                              .GetAsync();
            }
            catch (Exception ex)
            {
                // return ex;
            }

            return(requestTask);
        }
Пример #29
0
        // Returns all of the users in the directory of the signed-in user's tenant.
        public static async Task <IGraphServiceUsersCollectionPage> GetUsersAsync()
        {
            IGraphServiceUsersCollectionPage users = null;

            try
            {
                var graphClient = AuthenticationHelper.GetAuthenticatedClient();
                users = await graphClient.Users.Request().GetAsync();

                foreach (var user in users)
                {
                    Debug.WriteLine("User: "******"We could not get users: " + e.Error.Message);
                return(null);
            }
        }
Пример #30
0
        /// <inheritdoc/>
        internal override async Task <IEnumerable <User> > CallGraphServiceWithResultAsync(IGraphServiceClient client, IReadOnlyDictionary <string, object> parameters, CancellationToken cancellationToken)
        {
            string nameToSearch       = (string)parameters["NameToSearch"];
            int    maxCount           = (int)parameters["MaxResults"];
            string propertiesToSelect = (string)parameters["PropertiesToSelect"];

            string filterClause = $"startsWith(displayName, '{nameToSearch}') or startsWith(surname, '{nameToSearch}') or startsWith(givenname, '{nameToSearch}')";

            IGraphServiceUsersCollectionRequest request = client.Users.Request().Filter(filterClause).Select(propertiesToSelect);

            // Apply the Top() filter if there is a value to apply
            if (maxCount > 0)
            {
                request = request.Top(maxCount);
            }

            IGraphServiceUsersCollectionPage result = await request.GetAsync(cancellationToken).ConfigureAwait(false);

            // The "Top" clause in Graph is just more about max number of results per page.
            // This is unlike SQL where by the results are capped to max. In this case we will just
            // take the result from the first page and don't move on.
            return(result.CurrentPage);
        }
Пример #31
0
        public static List <User> GetAllUsers()
        {
            //Query using Graph SDK (preferred when possible)
            GraphServiceClient graphServiceClient = GetAuthenticatedGraphClient();

            List <User> AllUsers   = new List <User>();
            String      Properties = "displayName";
            IGraphServiceUsersCollectionPage users = graphServiceClient.Users.Request().Select(Properties).GetAsync().Result;
            bool QueryIncomplete = false;

            do
            {
                QueryIncomplete = false;
                AllUsers.AddRange(users);
                if (users.NextPageRequest != null)
                {
                    users           = users.NextPageRequest.GetAsync().Result;
                    QueryIncomplete = true;
                }
            } while (QueryIncomplete);

            return(AllUsers);
        }