Beispiel #1
0
        /// <summary>
        /// Get distribution list details and members count from AAD.
        /// </summary>
        /// <param name="groupIds">List of distribution list ids.</param>
        /// <returns>Count of members in distribution list.</returns>
        public async Task <List <DistributionList> > GetADGroupMemberCountBatchAsync(
            List <string> groupIds)
        {
            IEnumerable <List <string> > groupBatches = groupIds.SplitList(5);
            List <DistributionList>      dlGraphData  = new List <DistributionList>();

            string[] queries = new string[2] {
                "/groups/{0}/members?$select=displayName,mail,userType&$top=999", "/groups/{0}?$select=id,displayName,mail,mailNickname,mailEnabled"
            };

            foreach (List <string> groupBatch in groupBatches)
            {
                string[] scopes     = { "Group.Read.All" };
                string   graphQuery = $"https://graph.microsoft.com/v1.0/$batch";
                List <MSGraphBatchRequest> allRequests = MSGraphBatchRequestCreator.CreateBatchRequestPayloadForGroups(queries, "GET", groupBatch);
                MSGraphBatchRequestPayload payload     = new MSGraphBatchRequestPayload()
                {
                    Requests = allRequests,
                };

                List <MSGraphBatchResponse <dynamic> > responses = await this.protectedApiCallHelper.CallGraphApiPostOnBehalfOfUser(scopes, graphQuery, JsonConvert.SerializeObject(payload));

                if (responses != null)
                {
                    foreach (string group in groupBatch)
                    {
                        try
                        {
                            List <DistributionListMember> dlMember = this.protectedApiCallHelper.GetValue <List <DistributionListMember> >(JsonConvert.SerializeObject(responses.Find(s => s.Id == group).Body), "value");
                            DistributionList dlDetails             = this.protectedApiCallHelper.GetValue <DistributionList>(JsonConvert.SerializeObject(responses.Find(s => s.Id == group + '1')), "body");
                            if (dlDetails != null && dlMember != null)
                            {
                                dlDetails.NoOfMembers = dlMember.Where(x => (string.Equals(x.Type, "#microsoft.graph.group", StringComparison.OrdinalIgnoreCase) ||
                                                                             string.Equals(x.UserType, "member", StringComparison.OrdinalIgnoreCase))).Count();

                                dlGraphData.Add(dlDetails);
                            }
                        }
                        catch (Exception ex)
                        {
                            this.telemetryClient.TrackTrace($"An error occurred in GetADGroupMemberCountBatchAsync:  {group}", SeverityLevel.Error);
                            this.telemetryClient.TrackException(ex);
                        }
                    }
                }
            }

            return(dlGraphData);
        }
        /// <summary>
        /// Get User presence details in a batch.
        /// </summary>
        /// <param name="peoplePresenceDataArray">Array of People Presence Data object used to get presence information.</param>
        /// <returns>People Presence Data model data filled with presence information.</returns>
        public async Task <List <PeoplePresenceData> > GetBatchUserPresenceAsync(PeoplePresenceData[] peoplePresenceDataArray)
        {
            List <PeoplePresenceData> peoplePresenceDataList            = new List <PeoplePresenceData>();
            List <PeoplePresenceData> peoplePresenceDataListReturnValue = new List <PeoplePresenceData>();

            foreach (PeoplePresenceData member in peoplePresenceDataArray)
            {
                string userPrincipalName = member.UserPrincipalName.ToLower();
                if (!this.memoryCache.TryGetValue(userPrincipalName, out PeoplePresenceData peoplePresenceDataObj))
                {
                    peoplePresenceDataObj = new PeoplePresenceData()
                    {
                        UserPrincipalName = member.UserPrincipalName,
                        Id = member.Id,
                    };
                    peoplePresenceDataList.Add(peoplePresenceDataObj);
                }
                else
                {
                    peoplePresenceDataListReturnValue.Add(peoplePresenceDataObj);
                }
            }

            if (peoplePresenceDataList.Count > 0)
            {
                this.telemetryClient.TrackEvent($"GetBatchUserPresenceAsync. Getting presence from MS Graph. User Count : {peoplePresenceDataList.Count()}, users :{JsonConvert.SerializeObject(peoplePresenceDataList)}");

                string[] scopes = { "Presence.Read.All" };

                MemoryCacheEntryOptions options = new MemoryCacheEntryOptions
                {
                    AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(Convert.ToInt32(this.configuration["CacheInterval"])), // cache will expire in 60 seconds or 1 minutes
                };

                var presenceBatches = peoplePresenceDataList.SplitList(19); // MS Graph batch limit is 20

                foreach (var presenceBatch in presenceBatches)
                {
                    try
                    {
                        List <MSGraphBatchRequest> allRequests = MSGraphBatchRequestCreator.CreateBatchRequestPayloadForPresence("/users/{0}/presence", "GET", presenceBatch);
                        MSGraphBatchRequestPayload payload     = new MSGraphBatchRequestPayload()
                        {
                            Requests = allRequests,
                        };

                        List <MSGraphBatchResponse <dynamic> > responses = await this.protectedApiCallHelper.CallGraphApiPostOnBehalfOfUser(scopes, MSGraphBatchAPI, JsonConvert.SerializeObject(payload));

                        if (responses != null)
                        {
                            foreach (var presenceInfo in responses)
                            {
                                try
                                {
                                    string             presenceStatus = presenceInfo.Body.availability;
                                    string             userAADId      = presenceInfo.Body.id;
                                    PeoplePresenceData peoplePresence = new PeoplePresenceData()
                                    {
                                        Availability      = presenceStatus.ToLower() == "available" ? "Online" : presenceStatus,
                                        UserPrincipalName = presenceInfo.Id.ToLower(),
                                        Id = userAADId,
                                    };

                                    this.memoryCache.Set(peoplePresence.UserPrincipalName, peoplePresence, options);

                                    peoplePresenceDataListReturnValue.Add(peoplePresence);
                                }
                                catch (Exception ex)
                                {
                                    if (presenceInfo != null)
                                    {
                                        this.telemetryClient.TrackTrace($"GetBatchUserPresenceAsync. An error occurred: {ex.Message}. PeoplePresenceDataJObject : {JsonConvert.SerializeObject(presenceInfo)}", SeverityLevel.Error);
                                        this.telemetryClient.TrackException(ex);
                                    }
                                    else
                                    {
                                        this.telemetryClient.TrackTrace($"GetBatchUserPresenceAsync. An error occurred: {ex.Message} ", SeverityLevel.Error);
                                        this.telemetryClient.TrackException(ex);
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        if (presenceBatch != null)
                        {
                            this.telemetryClient.TrackTrace($"GetBatchUserPresenceAsync. An error occurred: {ex.Message}. PresenceBatch : {JsonConvert.SerializeObject(presenceBatch)}", SeverityLevel.Error);
                            this.telemetryClient.TrackException(ex);
                        }
                        else
                        {
                            this.telemetryClient.TrackTrace($"GetBatchUserPresenceAsync. An error occurred: {ex.Message} ", SeverityLevel.Error);
                            this.telemetryClient.TrackException(ex);
                        }
                    }
                }
            }
            else
            {
                this.telemetryClient.TrackEvent($"GetBatchUserPresenceAsync. Presence of all users found in memory.");
            }

            return(peoplePresenceDataListReturnValue);
        }