/// <summary>
        /// Disables Site Classifications settings for the target tenant
        /// </summary>
        /// <param name="accessToken">The OAuth accessToken for Microsoft Graph with Azure AD</param>
        public static void DisableSiteClassifications(string accessToken)
        {
            if (string.IsNullOrEmpty(accessToken))
            {
                throw new ArgumentException("Specify a valid accesstoken", nameof(accessToken));
            }
            // GET https://graph.microsoft.com/beta/settings
            string directorySettingsUrl  = $"{GraphHttpClient.MicrosoftGraphBetaBaseUri}settings";
            var    directorySettingsJson = GraphHttpClient.MakeGetRequestForString(directorySettingsUrl, accessToken);
            var    directorySettings     = JsonConvert.DeserializeObject <DirectorySettingTemplates>(directorySettingsJson);

            // Retrieve the setinngs for "Group.Unified"
            var unifiedGroupSetting = directorySettings.Templates.FirstOrDefault(t => t.DisplayName == "Group.Unified");

            if (unifiedGroupSetting != null)
            {
                // DELETE https://graph.microsoft.com/beta/settings
                string deleteDirectorySettingUrl = $"{GraphHttpClient.MicrosoftGraphBetaBaseUri}settings/{unifiedGroupSetting.Id}";
                GraphHttpClient.MakeDeleteRequest(
                    deleteDirectorySettingUrl,
                    accessToken: accessToken);
            }
            else
            {
                throw new ApplicationException("Missing DirectorySettingTemplate for \"Group.Unified\"");
            }
        }
        /// <summary>
        /// Enables Site Classifications for the target tenant
        /// </summary>
        /// <param name="accessToken">The OAuth accessToken for Microsoft Graph with Azure AD</param>
        /// <returns>The list of Site Classification values</returns>
        public static SiteClassificationsSettings GetSiteClassificationsSettings(string accessToken)
        {
            if (string.IsNullOrEmpty(accessToken))
            {
                throw new ArgumentException("Specify a valid accesstoken", nameof(accessToken));
            }
            // GET https://graph.microsoft.com/beta/directorySettingTemplates
            string directorySettingsUrl  = $"{GraphHttpClient.MicrosoftGraphBetaBaseUri}settings";
            var    directorySettingsJson = GraphHttpClient.MakeGetRequestForString(directorySettingsUrl, accessToken);
            var    directorySettings     = JsonConvert.DeserializeObject <DirectorySettingTemplates>(directorySettingsJson);

            // Retrieve the setinngs for "Group.Unified"
            var unifiedGroupSetting = directorySettings.Templates.FirstOrDefault(t => t.DisplayName == "Group.Unified");

            if (unifiedGroupSetting != null)
            {
                var siteClassificationsSettings = new SiteClassificationsSettings();
                var classificationList          = unifiedGroupSetting.SettingValues.FirstOrDefault(v => v.Name == "ClassificationList");
                if (classificationList != null)
                {
                    siteClassificationsSettings.Classifications = classificationList.Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                }
                var guidanceUrl = unifiedGroupSetting.SettingValues.First(v => v.Name == "UsageGuidelinesUrl");
                if (guidanceUrl != null)
                {
                    siteClassificationsSettings.UsageGuidelinesUrl = guidanceUrl.Value;
                }
                var defaultClassification = unifiedGroupSetting.SettingValues.First(v => v.Name == "DefaultClassification");
                if (defaultClassification != null)
                {
                    siteClassificationsSettings.DefaultClassification = defaultClassification.Value;
                }
                return(siteClassificationsSettings);
            }
            else
            {
                throw new ApplicationException("Missing DirectorySettingTemplate for \"Group.Unified\"");
            }
        }
        /// <summary>
        /// Returns the classification value of an Office 365 Group.
        /// </summary>
        /// <param name="groupId">ID of the unified Group</param>
        /// <param name="accessToken">The OAuth 2.0 Access Token to use for invoking the Microsoft Graph</param>
        /// <returns>Classification value of a Unified group</returns>
        public static string GetGroupClassification(string groupId, string accessToken)
        {
            if (String.IsNullOrEmpty(groupId))
            {
                throw new ArgumentNullException(nameof(groupId));
            }

            if (String.IsNullOrEmpty(accessToken))
            {
                throw new ArgumentNullException(nameof(accessToken));
            }

            string classification = string.Empty;

            try
            {
                string getGroupUrl = $"{GraphHttpClient.MicrosoftGraphV1BaseUri}groups/{groupId}";

                var getGroupResult = GraphHttpClient.MakeGetRequestForString(
                    getGroupUrl,
                    accessToken: accessToken);

                JObject groupObject = JObject.Parse(getGroupResult);

                if (groupObject["classification"] != null)
                {
                    classification = Convert.ToString(groupObject["classification"]);
                }
            }
            catch (ServiceException e)
            {
                classification = e.Error.Message;
            }

            return(classification);
        }
        /// <summary>
        /// Enables Site Classifications for the target tenant
        /// </summary>
        /// <param name="accessToken">The OAuth accessToken for Microsoft Graph with Azure AD</param>
        /// <param name="classificationList">The list of classification values</param>
        /// <param name="defaultClassification">The default classification</param>
        /// <param name="usageGuidelinesUrl">The URL of a guidance page</param>
        public static void EnableSiteClassifications(string accessToken, IEnumerable <String> classificationsList, String defaultClassification = "", String usageGuidelinesUrl = "")
        {
            if (string.IsNullOrEmpty(accessToken))
            {
                throw new ArgumentException("Specify a valid accesstoken", nameof(accessToken));
            }
            if (classificationsList == null || !classificationsList.Any())
            {
                throw new ArgumentException("Specify one or more classifications", nameof(classificationsList));
            }
            if (usageGuidelinesUrl == null)
            {
                throw new ArgumentException("Specify a valid URL or an empty string to not set this value", nameof(usageGuidelinesUrl));
            }
            if (!classificationsList.Contains(defaultClassification))
            {
                throw new ArgumentException("The default classification specified is not available in the list of specified classifications", nameof(defaultClassification));
            }

            // GET https://graph.microsoft.com/beta/directorySettingTemplates
            string directorySettingTemplatesUrl  = $"{GraphHttpClient.MicrosoftGraphBetaBaseUri}directorySettingTemplates";
            var    directorySettingTemplatesJson = GraphHttpClient.MakeGetRequestForString(directorySettingTemplatesUrl, accessToken);
            var    directorySettingTemplates     = JsonConvert.DeserializeObject <DirectorySettingTemplates>(directorySettingTemplatesJson);

            // Retrieve the setinngs for "Group.Unified"
            var unifiedGroupSetting = directorySettingTemplates.Templates.FirstOrDefault(t => t.DisplayName == "Group.Unified");

            if (unifiedGroupSetting != null)
            {
                var directorySettingValues = new Dictionary <String, String>();
                foreach (var v in unifiedGroupSetting.SettingValues)
                {
                    switch (v.Name)
                    {
                    case "UsageGuidelinesUrl":
                        directorySettingValues.Add(v.Name, usageGuidelinesUrl);
                        break;

                    case "ClassificationList":
                        directorySettingValues.Add(v.Name, classificationsList.Aggregate((s, i) => s + ", " + i));
                        break;

                    case "DefaultClassification":
                        directorySettingValues.Add(v.Name, defaultClassification);
                        break;

                    default:
                        directorySettingValues.Add(v.Name, v.DefaultValue);
                        break;
                    }
                }

                // POST https://graph.microsoft.com/beta/settings
                string newDirectorySettingUrl    = $"{GraphHttpClient.MicrosoftGraphBetaBaseUri}settings";
                var    newDirectorySettingResult = GraphHttpClient.MakePostRequestForString(
                    newDirectorySettingUrl,
                    content: new
                {
                    templateId = unifiedGroupSetting.Id,
                    values     = from v in directorySettingValues select new { name = v.Key, value = v.Value },
                },
                    contentType: "application/json",
                    accessToken: accessToken);
            }
            else
            {
                throw new ApplicationException("Missing DirectorySettingTemplate for \"Group.Unified\"");
            }
        }
        /// <summary>
        /// Updates Site Classifications settings for the target tenant
        /// </summary>
        /// <param name="accessToken">The OAuth accessToken for Microsoft Graph with Azure AD</param>
        /// <param name="classificationsList">The list of classification values</param>
        /// <param name="defaultClassification">The default classification</param>
        /// <param name="usageGuidelinesUrl">The URL of a guidance page</param>
        public static void UpdateSiteClassificationsSettings(String accessToken, IEnumerable <String> classificationsList = null, String defaultClassification = "", String usageGuidelinesUrl = "")
        {
            if (string.IsNullOrEmpty(accessToken))
            {
                throw new ArgumentException("Specify a valid accesstoken", nameof(accessToken));
            }
            // GET https://graph.microsoft.com/beta/settings
            string directorySettingsUrl  = $"{GraphHttpClient.MicrosoftGraphBetaBaseUri}settings";
            var    directorySettingsJson = GraphHttpClient.MakeGetRequestForString(directorySettingsUrl, accessToken);
            var    directorySettings     = JsonConvert.DeserializeObject <DirectorySettingTemplates>(directorySettingsJson);

            // Retrieve the setinngs for "Group.Unified"
            var unifiedGroupSetting = directorySettings.Templates.FirstOrDefault(t => t.DisplayName == "Group.Unified");

            if (unifiedGroupSetting != null)
            {
                foreach (var v in unifiedGroupSetting.SettingValues)
                {
                    switch (v.Name)
                    {
                    case "UsageGuidelinesUrl":
                        if (usageGuidelinesUrl != null)
                        {
                            v.Value = usageGuidelinesUrl;
                        }
                        break;

                    case "ClassificationList":
                        if (classificationsList != null && classificationsList.Any())
                        {
                            v.Value = classificationsList.Aggregate((s, i) => s + ", " + i);
                        }
                        break;

                    case "DefaultClassification":
                        if (usageGuidelinesUrl != null)
                        {
                            v.Value = defaultClassification;
                        }
                        break;

                    default:
                        break;
                    }
                }

                // PATCH https://graph.microsoft.com/beta/settings
                string updateDirectorySettingUrl    = $"{GraphHttpClient.MicrosoftGraphBetaBaseUri}settings/{unifiedGroupSetting.Id}";
                var    updateDirectorySettingResult = GraphHttpClient.MakePatchRequestForString(
                    updateDirectorySettingUrl,
                    content: new
                {
                    templateId = unifiedGroupSetting.Id,
                    values     = from v in unifiedGroupSetting.SettingValues select new { name = v.Name, value = v.Value },
                },
                    contentType: "application/json",
                    accessToken: accessToken);
            }
            else
            {
                throw new ApplicationException("Missing DirectorySetting for \"Group.Unified\"");
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Returns the users delta in the current domain filtered out with a custom OData filter. If no <paramref name="deltaToken"/> has been provided, all users will be returned with a deltatoken for a next run. If a <paramref name="deltaToken"/> has been provided, all users which were modified after the deltatoken has been generated will be returned.
        /// </summary>
        /// <param name="accessToken">The OAuth 2.0 Access Token to use for invoking the Microsoft Graph</param>
        /// <param name="deltaToken">DeltaToken to indicate requesting changes since this deltatoken has been created. Leave NULL to retrieve all users with a deltatoken to use for subsequent queries.</param>
        /// <param name="filter">OData filter to apply to retrieval of the users from the Microsoft Graph</param>
        /// <param name="orderby">OData orderby instruction</param>
        /// <param name="selectProperties">Allows providing the names of properties to return regarding the users. If not provided, the standard properties will be returned.</param>
        /// <param name="startIndex">First item in the results returned by Microsoft Graph to return</param>
        /// <param name="endIndex">Last item in the results returned by Microsoft Graph to return</param>
        /// <param name="retryCount">Number of times to retry the request in case of throttling</param>
        /// <param name="delay">Milliseconds to wait before retrying the request. The delay will be increased (doubled) every retry.</param>
        /// <returns>List with User objects</returns>
        public static Model.UserDelta ListUserDelta(string accessToken, string deltaToken, string filter, string orderby, string[] selectProperties = null, int startIndex = 0, int endIndex = 999, int retryCount = 10, int delay = 500)
        {
            if (String.IsNullOrEmpty(accessToken))
            {
                throw new ArgumentNullException(nameof(accessToken));
            }

            Model.UserDelta userDelta = new Model.UserDelta
            {
                Users = new List <Model.User>()
            };
            try
            {
                // GET https://graph.microsoft.com/v1.0/users/delta
                string getUserDeltaUrl = $"{GraphHttpClient.MicrosoftGraphV1BaseUri}users/delta?";

                if (selectProperties != null)
                {
                    getUserDeltaUrl += $"$select={string.Join(",", selectProperties)}&";
                }
                if (!string.IsNullOrEmpty(filter))
                {
                    getUserDeltaUrl += $"$filter={filter}&";
                }
                if (!string.IsNullOrEmpty(deltaToken))
                {
                    getUserDeltaUrl += $"$deltatoken={deltaToken}&";
                }
                if (!string.IsNullOrEmpty(orderby))
                {
                    getUserDeltaUrl += $"$orderby={orderby}&";
                }

                getUserDeltaUrl = getUserDeltaUrl.TrimEnd('&').TrimEnd('?');

                int currentIndex = 0;

                while (true)
                {
                    var response = GraphHttpClient.MakeGetRequestForString(
                        requestUrl: getUserDeltaUrl,
                        accessToken: accessToken);

                    var userDeltaResponse = JsonConvert.DeserializeObject <Model.UserDelta>(response);

                    if (!string.IsNullOrEmpty(userDeltaResponse.DeltaToken))
                    {
                        userDelta.DeltaToken = HttpUtility.ParseQueryString(new Uri(userDeltaResponse.DeltaToken).Query).Get("$deltatoken");
                    }

                    foreach (var user in userDeltaResponse.Users)
                    {
                        currentIndex++;

                        if (currentIndex >= startIndex && currentIndex <= endIndex)
                        {
                            userDelta.Users.Add(user);
                        }
                    }

                    if (userDeltaResponse.NextLink != null && currentIndex < endIndex)
                    {
                        getUserDeltaUrl = userDeltaResponse.NextLink;
                    }
                    else
                    {
                        break;
                    }
                }
            }
            catch (ServiceException ex)
            {
                Log.Error(Constants.LOGGING_SOURCE, CoreResources.GraphExtensions_ErrorOccured, ex.Error.Message);
                throw;
            }
            return(userDelta);
        }