private async Task<PrincipalsViewModel> GetUsers(string nameToSearch, IGraphServiceUsersCollectionRequest request = null)
        {
            PrincipalsViewModel result = new PrincipalsViewModel();

            var filteredUsers = await graphClient.Users.Request()
                    .Select("DisplayName,UserPrincipalName,Mail")
                    .Filter($"startswith(DisplayName,'{nameToSearch}') or startswith(UserPrincipalName,'{nameToSearch}') or startswith(Mail,'{nameToSearch}')")
                    .GetAsync();

            var t = await MapUsers(filteredUsers);
            result.Principals.AddRange(t.Principals);

            if (filteredUsers.NextPageRequest != null)
            {
                var additionalUsers = await GetUsers(nameToSearch, filteredUsers.NextPageRequest);

                if (additionalUsers.Principals.Count > 0)
                {
                    result.Principals.AddRange(additionalUsers.Principals);
                }
            }

            return result;
        }
示例#2
0
        private async Task <PrincipalsViewModel> GetUsers(string nameToSearch, IGraphServiceUsersCollectionRequest request = null)
        {
            PrincipalsViewModel result = new PrincipalsViewModel();

            var filteredUsers = await graphClient.Users.Request()
                                .Select("DisplayName,UserPrincipalName,Mail")
                                .Filter($"startswith(DisplayName,'{nameToSearch}') or startswith(UserPrincipalName,'{nameToSearch}') or startswith(Mail,'{nameToSearch}')")
                                .GetAsync();

            var t = await MapUsers(filteredUsers);

            result.Principals.AddRange(t.Principals);

            if (filteredUsers.NextPageRequest != null)
            {
                var additionalUsers = await GetUsers(nameToSearch, filteredUsers.NextPageRequest);

                if (additionalUsers.Principals.Count > 0)
                {
                    result.Principals.AddRange(additionalUsers.Principals);
                }
            }

            return(result);
        }
 static IGraphServiceUsersCollectionRequest Filter(this IGraphServiceUsersCollectionRequest users, List <Filter> filters, QueryDescription queryDescription)
 {
     string ToFilter(Filter f)
     {
         if (f is FilterCondition fc)
         {
             return(fc.Operation switch
             {
                 FilterOperation.EqualTo => ToGraphField(fc.Token) + " eq " + ToStringValue(fc.Value),
                 FilterOperation.DistinctTo => ToGraphField(fc.Token) + " ne " + ToStringValue(fc.Value),
                 FilterOperation.GreaterThan => ToGraphField(fc.Token) + " gt " + ToStringValue(fc.Value),
                 FilterOperation.GreaterThanOrEqual => ToGraphField(fc.Token) + " ge " + ToStringValue(fc.Value),
                 FilterOperation.LessThan => ToGraphField(fc.Token) + " lt " + ToStringValue(fc.Value),
                 FilterOperation.LessThanOrEqual => ToGraphField(fc.Token) + " le " + ToStringValue(fc.Value),
                 FilterOperation.StartsWith => "startswith(" + ToGraphField(fc.Token) + "," + ToStringValue(fc.Value) + ")",
                 FilterOperation.EndsWith => "endswith(" + ToGraphField(fc.Token) + "," + ToStringValue(fc.Value) + ")",
                 FilterOperation.NotStartsWith => "not startswith(" + ToGraphField(fc.Token) + "," + ToStringValue(fc.Value) + ")",
                 FilterOperation.NotEndsWith => "not endswith(" + ToGraphField(fc.Token) + "," + ToStringValue(fc.Value) + ")",
                 FilterOperation.IsIn => "(" + ((object[])fc.Value !).ToString(a => ToGraphField(fc.Token) + " eq " + ToStringValue(a), " OR ") + ")",
                 FilterOperation.IsNotIn => "not (" + ((object[])fc.Value !).ToString(a => ToGraphField(fc.Token) + " eq " + ToStringValue(a), " OR ") + ")",
                 FilterOperation.Contains or
                 FilterOperation.Like or
                 FilterOperation.NotContains or
                 FilterOperation.NotLike or
                 _ => throw new InvalidOperationException(fc.Operation + " is not implemented in Microsoft Graph API")
             });
         }
 /// <summary>
 /// Initializes the NextPageRequest property.
 /// </summary>
 public void InitializeNextPageRequest(IBaseClient client, string nextPageLinkString)
 {
     if (!string.IsNullOrEmpty(nextPageLinkString))
     {
         this.NextPageRequest = new GraphServiceUsersCollectionRequest(
             nextPageLinkString,
             client,
             null);
     }
 }
示例#5
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);
        }
        private static async Task GetUsers(IGraphServiceUsersCollectionRequest request, ITargetBlock <User> target, CancellationToken token)
        {
            var page = await GraphHelper.ExecuteWithRetryAndRateLimit(async() => await request.GetAsync(token), token, 0);

            foreach (User user in page.CurrentPage)
            {
                target.Post(user);
            }

            while (page.NextPageRequest != null)
            {
                page = await GraphHelper.ExecuteWithRetryAndRateLimit(async() => await page.NextPageRequest.GetAsync(token), token, 0);

                foreach (User user in page.CurrentPage)
                {
                    target.Post(user);
                }
            }
        }
示例#7
0
        public async Task <Results.UsersResult> SearchUsersAsync(IGraphServiceUsersCollectionRequest request, string keyword)
        {
            try
            {
                Results.UsersResult usersResult = new Results.UsersResult();
                string query = string.Format("startswith(displayName,'{0}') or startswith(userPrincipalName,'{0}')", keyword);
                IGraphServiceUsersCollectionPage users;
                if (request == null)
                {
                    users = await graphClient.Users.Request(requestOptions).Top(4)
                            .Filter(query)
                            .Select(e => new { e.DisplayName, e.UserPrincipalName, e.UserType, e.AssignedLicenses })
                            .GetAsync();
                }
                else
                {
                    users = await request.GetAsync();
                }

                usersResult.NextPageRequest = users.NextPageRequest;

                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);
                }

                usersResult.Users = values;

                return(usersResult);
            }
            catch
            {
                throw;
            }
        }
        public static async Task <User[]> GetAllAsync(this IGraphServiceUsersCollectionRequest pagedCollectionRq)
        {
            var list = new List <User>();

            var collectionRequest = pagedCollectionRq;

            while (true && collectionRequest != null)
            {
                var pageList = await collectionRequest.GetAsync();

                if (pageList.CurrentPage.Count > 0)
                {
                    list.AddRange(pageList.CurrentPage);
                    collectionRequest = pageList.NextPageRequest;
                }
                else
                {
                    break;
                }
            }
            return(list.ToArray());
        }
示例#9
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);
        }
示例#10
0
        public async System.Threading.Tasks.Task TestBatch()
        {
            IUserRequest meRequest = graphClient.Me.Request();
            IGraphServiceUsersCollectionRequest newUserRequest = graphClient.Users.Request();                               // We have the ./users URL, query parameters, and request headers.

            User newUser = new User();

            newUser.DisplayName       = "New User";
            newUser.UserPrincipalName = "*****@*****.**";

            IDirectoryObjectWithReferenceRequest managerRequest = graphClient.Me.Manager.Request();                         // We have the /me/manager URL, query parameters, and request headers.
            IDriveItemChildrenCollectionRequest  driveRequest   = graphClient.Me.Drive.Root.Children.Request();             // We have the /me/drive/root/children URL, query parameters, and request headers.

            IEducationRootRequest eduRequest = graphClient.Education.Request();                                             // We have the /education URL, query parameters, and request headers.

            BatchContainer batchContainer = new BatchContainer();
            BatchPart      part1          = batchContainer.AddToBatch(meRequest, Method.GET);                               // I don't think we need a copy of the BatchPart.

            batchContainer.AddToBatch(driveRequest, Method.GET);
            batchContainer.AddToBatch(eduRequest, Method.GET);
            batchContainer.AddToBatch(newUserRequest, Method.POST, 4, newUser, new BatchPart[] { part1 });                  // We have to use reflection to determine which HttpVerb method we are using, and then, what
                                                                                                                            // the return type will be. This might be costly batch scenario can contain a large number
            BatchResponse response = await graphClient.Batch.PostAsync(batchContainer);                                     // of requests across many batches. I think we want to avoid reflection.

            User me = (User)response.batchResponses.Where(i => i.id == 1).First().body;                                     // No auto-deserialization.

            User me2 = (User)response.batchResponses.Where(i => i.body.GetType() == typeof(User)).FirstOrDefault().body;

            foreach (BatchResponsePart part in response.batchResponses)
            {
                var responseItem = part.body; // If we deserialize into a dynamic object, the customer would have
                int statusCode   = part.status;
            }

            Assert.IsNotNull(me.UserPrincipalName);
        }
示例#11
0
            public async Task <IEnumerable <MMM.User> > GetNextPage(bool next)
            {
                IGraphServiceUsersCollectionPage users = null;

                // We only support forward paging
                if (next)
                {
                    if (_next == null)
                    {
                        users = await _graphClient.Users.Request()
                                .Top(_pageSize)
                                .Filter(BuildFilter())
                                .GetAsync();
                    }
                    else
                    {
                        users = await _next.GetAsync();
                    }
                }

                _next = users.NextPageRequest;

                return(users.Select(user => user.ConvertObject <MMM.User>()));
            }
        public static async Task <User[]> GetAllAsync(this IGraphServiceUsersCollectionRequest request)
        {
            var collectionPage = await request.GetAsync();

            return(await GetAllAsync(collectionPage));
        }
            public async Task<IEnumerable<MMM.User>> GetNextPage(bool next)
            {
                IGraphServiceUsersCollectionPage users = null;

                // We only support forward paging
                if (next)
                {
                    if (_next == null)
                    {
                        users = await _graphClient.Users.Request()
                                            .Top(_pageSize)
                                            .Filter(BuildFilter())
                                            .GetAsync();
                    }
                    else
                    {
                        users = await _next.GetAsync();
                    }
                }

                _next = users.NextPageRequest;

                return users.Select(user => user.ConvertObject<MMM.User>());
            }
示例#14
0
        public static IGraphServiceUsersCollectionRequest Where(this IGraphServiceUsersCollectionRequest a, Expression <Predicate <User> > predicate)
        {
            string p = compilePredicate(predicate);

            return(a.Filter(p));
        }