예제 #1
0
        public async Task <IActionResult> UpdateUser([FromRoute] string id, [FromBody] UserDto userRequest)
        {
            try
            {
                if (string.IsNullOrEmpty(id) || string.IsNullOrWhiteSpace(id))
                {
                    return(BadRequest());
                }

                // Initialize the GraphServiceClient.
                GraphServiceClient client = await MicrosoftGraphClient.GetGraphServiceClient();

                var user = new Microsoft.Graph.User
                {
                    DisplayName = userRequest.DisplayName,
                    GivenName   = userRequest.GivenName,
                    Surname     = userRequest.Surname,
                };

                await client.Users[id].Request().UpdateAsync(user);

                return(NoContent());
            }
            catch (ServiceException ex)
            {
                if (ex.StatusCode == HttpStatusCode.BadRequest)
                {
                    return(BadRequest());
                }
                else
                {
                    return(NotFound());
                }
            }
        }
예제 #2
0
        private List <SharedFolder> recurseFolders(Microsoft.Graph.User user, DriveItem folder)
        {
            List <SharedFolder> partialResult = new List <SharedFolder>();                                           // return case variable
            var childItems = graphClient.Users[user.Id].Drive.Items[folder.Id].Children.Request().GetAsync().Result; // list child items of inbound folder

            System.Threading.Thread.Sleep(50);                                                                       // spaces out API calls

            foreach (var child in childItems)
            {
                if (child.Folder != null) // Check if item is a folder
                {
                    Console.WriteLine(" . . . . Folder Debug " + child.Name);
                    if (child.Shared != null) // Check if folder is shared, if it is shared, check permissions and stop recursing
                    {
                        Console.Write(" (SHARED) ");
                        // Create folder object to store permissions
                        SharedFolder temp = new SharedFolder(child.Id, child.WebUrl, user.Id);

                        // Request Permissions on folder
                        var permissions = graphClient.Users[user.Id].Drive.Items[child.Id].Permissions.Request().GetAsync().Result;

                        // Loop Through all Permissions
                        int count = 0;
                        foreach (var permission in permissions)
                        {
                            String grantedTo = null;
                            if (permission.GrantedTo != null) // GrantedTo refers to an in tenant object that this folder is shared with
                            {
                                grantedTo = permission.GrantedTo.User.Id;
                                if (grantedTo != user.Id && exclusionCheck(grantedTo) && grantedTo != null)
                                {
                                    // permission is found
                                    temp.SharedWith.Add(permission);

                                    // output
                                    file.WriteLine(user.DisplayName + ";" + user.Id + ";" + child.Id + ";" + permission.Id + ";" + grantedTo);
                                    System.Console.WriteLine(user.DisplayName + ";" + user.Id + ";" + child.Id + ";" + permission.Id + ";" + grantedTo);
                                    file.Flush();
                                    count++;
                                }
                            }
                            else // exception case indicates an external link share
                            {
                                temp.SharedWith.Add(permission);
                            }
                        }

                        if (count > 0)
                        {
                            partialResult.Add(temp);
                        }
                    }
                    else // if folder is not shared, go down one level
                    {
                        partialResult.AddRange(recurseFolders(user, child));
                    }
                }
            }
            return(partialResult);
        }
예제 #3
0
    /// <summary>
    /// Get the user's email from the Graph API's User object
    /// </summary>
    /// <param name="graphUser"></param>
    /// <returns></returns>
    private string GetUserEmailFromGraphADUser(Microsoft.Graph.User graphUser)
    {
        string emailCandidate;

        switch (_configSyncGroups.EmailMapping)
        {
        //Use the name of the principal in AzureAD
        case ProvisionConfigExternalDirectorySync.UserEmailMapping.UserPrincipalName:
            emailCandidate = graphUser.UserPrincipalName;
            IwsDiagnostics.Assert(!string.IsNullOrWhiteSpace(emailCandidate), "814-705: User principal name is NULL");
            return(emailCandidate.Trim());

        //If the user has another email address listed, use it
        case ProvisionConfigExternalDirectorySync.UserEmailMapping.PreferAzureProxyPrimaryEmail:
            emailCandidate = GetUserEmailFromGraphADUser_TryPrimaryProxyEmailLookup(graphUser);
            //If no email candidate was found, use the principal name
            if (string.IsNullOrWhiteSpace(emailCandidate))
            {
                emailCandidate = graphUser.UserPrincipalName;
                IwsDiagnostics.Assert(!string.IsNullOrWhiteSpace(emailCandidate), "1009-1210: User principal name is NULL");
            }
            return(emailCandidate.Trim());


        default:     //Unknown mode
            IwsDiagnostics.Assert(false, "1009-1208: Unknown user email mapping mode");
            throw new Exception("1009-1208: Unknown user email mapping mode");
        }
    }
예제 #4
0
    /// <summary>
    /// Get the user's email from the Graph API's User object
    /// </summary>
    /// <param name="graphUser"></param>
    /// <returns></returns>
    private string GetUserEmailFromGraphADUser(Microsoft.Graph.User graphUser)
    {
        string emailCandidate = graphUser.UserPrincipalName;

        IwsDiagnostics.Assert(!string.IsNullOrWhiteSpace(emailCandidate), "814-705: User principal name is NULL");
        return(emailCandidate.Trim());
    }
예제 #5
0
        public async System.Threading.Tasks.Task <List <string> > getUserDisplayNamesAsync(string[] userIDs)
        {
            List <String> displayNames = new List <string>();

            foreach (String userID in userIDs)
            {
                // Check for UID
                if (Guid.TryParse(userID, out Guid result))
                {
                    // Check if AAD Object in in cache
                    if (graphCache.ContainsKey(userID))
                    {
                        displayNames.Add(graphCache[userID]);
                    }
                    else
                    {
                        Microsoft.Graph.User user = await GraphHelper.GetUserById(userID, clientId);

                        graphCache.Add(user.Id, user.UserPrincipalName);
                        displayNames.Add(user.UserPrincipalName);
                    }
                }
                else
                {
                    displayNames.Add(userID);
                }
            }
            return(displayNames);
        }
예제 #6
0
        // GET: UserProfile
        public async Task <ActionResult> Index()
        {
            string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

            try
            {
                GraphServiceClient graphServiceClient = GetAuthenticatedGraphServiceClient();

                // use the token for querying the graph to get the user details
                User me = await graphServiceClient.Me.Request().GetAsync();

                return(View(me));
            }
            catch (AdalException eee)
            {
                // if the above failed, the user needs to explicitly re-authenticate for the app to obtain the required token
                ViewBag.Error = "An error has occurred. Details: " + eee.Message;
                return(View("Relogin"));
            }
            catch (Exception)
            {
                // Return to error page.
                return(RedirectToAction("ShowError", "Error"));
            }
        }
        /// <summary>
        /// Create a new user with the parameters provided.
        /// </summary>
        /// <param name="firstName">The user's first name.</param>
        /// <param name="lastName">The user's last name.</param>
        /// <param name="displayName">The user's display name.</param>
        /// <param name="pwd">The user's plain-text password.</param>
        /// <returns>A new local User object from the graph.</returns>
        /// <remarks>
        /// The required MailNickname will be the first name, a dot, and a last name. The required
        /// userPrincipalName will be the same with the first domain (the .onmicrosoft.com) added
        /// to the end of the name.
        /// </remarks>
        public async Task <User> AddUser(string firstName, string lastName, string displayName, string pwd)
        {
            var user = new User
            {
                GivenName       = firstName, Surname = lastName, DisplayName = displayName,
                PasswordProfile = new PasswordProfile
                {
                    Password = pwd,
                    ForceChangePasswordNextSignIn = false
                },
                PasswordPolicies  = "DisablePasswordExpiration",
                AccountEnabled    = false,
                MailNickname      = firstName + "." + lastName,
                UserPrincipalName = firstName + "." + lastName + "@" + domains[0].Id
            };

            try
            {
                var ret = await client.Users.Request().AddAsync(user);

                return(ret);
            }
            catch (ServiceException se)
            {
                throw new UserException(
                          $"A {se.StatusCode} occured building and adding user {user.UserPrincipalName} to the directory: {se.Error.Message} Check the inner exception for details.",
                          user, se);
            }
        }
예제 #8
0
        public async Task <ActionResult> SendSurvey(Survey Survey, string ToRecipients)
        {
            // Split the recipient list
            string[] recipients = ToRecipients.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

            // Create a Graph client
            GraphServiceClient graphClient = new GraphServiceClient(
                new DelegateAuthenticationProvider(AddAccessToken));

            // Get the sender's email address
            Microsoft.Graph.User sender = await graphClient.Me.Request().GetAsync();

            string senderEmail = sender.Mail;

            try
            {
                var createSurveyResult = await CreateSurveyInService(Survey, senderEmail, recipients);

                // Send the survey
                string[] errors = await SendSurvey(
                    createSurveyResult.SurveyId.ToString(),
                    Survey,
                    createSurveyResult.Participants,
                    createSurveyResult.Expiration.ToString(),
                    graphClient);

                return(Json(errors));
            }
            catch (Exception ex)
            {
                return(Json(ex.Message));
            }
        }
예제 #9
0
        public async Task <Microsoft.Graph.User> Get(string userPrincipalName)
        {
            GraphServiceClient graphClient = new GraphServiceClient(new AzureAuthenticationProvider());

            Microsoft.Graph.User user = await graphClient.Users[userPrincipalName].Request().GetAsync();
            return(user);
        }
예제 #10
0
        public async Task <IList <Microsoft.Graph.Contact> > GetMyEmailContacts(GraphServiceClient graphClient)
        {
            Microsoft.Graph.User me = await graphClient.Me.Request().Select("mail,userPrincipalName").GetAsync();

            var contacts = me.Contacts;

            return(contacts);
        }
 private static async Task <Microsoft.Graph.User> UpdateUserAsync(GraphServiceClient client, string userIdToUpdate)
 {
     Microsoft.Graph.User user = new Microsoft.Graph.User()
     {
         MobilePhone = "555-555-1212"
     };
     return(await client.Users[userIdToUpdate].Request().UpdateAsync(user));
 }
예제 #12
0
 private string GetUserAttribute(Microsoft.Graph.User user, string extensionName)
 {
     if (user.AdditionalData == null || !user.AdditionalData.ContainsKey(extensionName))
     {
         return(null);
     }
     return((string)user.AdditionalData[extensionName]);
 }
예제 #13
0
        /// <summary>
        /// Get the current user's email address from their profile.
        /// </summary>
        /// <returns></returns>
        public async Task <string> GetMyEmailAddressAsync()
        {
            // Get the current user.
            // The app only needs the user's email address, so select the mail and userPrincipalName properties.
            // If the mail property isn't defined, userPrincipalName should map to the email for all account types.
            Microsoft.Graph.User me = await GraphClient.Me.Request().Select("mail,userPrincipalName").GetAsync();

            return(me.Mail ?? me.UserPrincipalName);
        }
예제 #14
0
 /// <summary>
 /// Add a user to specified Group
 /// </summary>
 /// <param name="targetGroupName"></param>
 /// <param name="asUser"></param>
 /// <param name="sourceGroupName"></param>
 private void AddUserToGroupProvisioningTrackingManager(string targetGroupName, Microsoft.Graph.User graphUser, ProvisionConfigExternalDirectorySync.SynchronizeGroupToGroup targetGroup)
 {
     //Because the request code can run async, and the collection management used is not designed to be thread-safe
     //we are going to serialize adding users to the collection.
     lock (_lock_AddUserToGroupProvisioningTrackingManager)
     {
         AddUserToGroupProvisioningTrackingManager_Inner(targetGroupName, graphUser, targetGroup);
     }
 }
예제 #15
0
        //public async Task<ActionResult> GoToRegister(CompanyLicenseViewModel cModel)
        public async Task <ActionResult> GoToRegister()
        {
            GraphServiceClient graphClient1 = SDKHelper.GetAuthenticatedClient();
            IGraphServiceOrganizationCollectionPage organization = await graphService.GetOrganisationInfo(graphClient1);

            if (organization.Count == 0)
            {
                return(View("~/Views/Shared/GoToLogin.cshtml"));
            }

            GraphServiceClient graphClient2 = SDKHelper.GetAuthenticatedClient();

            // Get the current user's email address.
            //Microsoft.Graph.User me = await graphClient.Me.Request().Select("mail, userPrincipalName, displayName, jobTitle").GetAsync();
            Microsoft.Graph.User me = await graphService.GetUserInfo(graphClient2);

            //me.Mail ?? me.UserPrincipalName;
            string email       = me.Mail ?? me.UserPrincipalName;
            string displayName = me.DisplayName;
            string companyName = organization.CurrentPage[0].DisplayName;
            string website     = organization.CurrentPage[0].VerifiedDomains.ElementAt(0).Name; //me.MySite;
            string jobTitle    = me.JobTitle;

            RegistrationViewModel model = new RegistrationViewModel();

            model.EmailID       = email;
            model.CustomerName  = displayName;
            model.DomainName    = website;
            model.Name          = companyName;
            model.BusinessTitle = jobTitle;
            //model.CustomerType = cModel.CompanyLicenseType;
            model.CustomerType = "Premium";

            ViewBag.PageType = "Register";

            //ViewBag.citieslist = _cityRepository.GetAllElements().Select(x => new SelectListItem
            //{
            //    Value = x.CityName,
            //    Text = x.CityName
            //});


            ViewBag.countrieslist = _cityRepository.GetAllElements().Select(x => new { x.CountryName }).OrderBy(x => x.CountryName).ToList().Distinct().Select(x => new SelectListItem
            {
                Value = x.CountryName,
                Text  = x.CountryName
            });

            ViewBag.industrieslist = _industryRepository.GetAllElements().OrderBy(x => x.IndustryName).ToList().Select(x => new SelectListItem
            {
                Value = x.IndustryName,
                Text  = x.IndustryName
            });

            return(View("~/Views/Registration/Register.cshtml", model));
        }
    /// <summary>
    /// Add a user to specified Group
    /// </summary>
    /// <param name="groupSyncInstructions"></param>
    /// <param name="singleGroupMembershipManager"></param>
    /// <param name="graphUser"></param>
    private void AddUserToGroupProvisioningTrackingManager(
        ProvisionFromDirectoryGroupsMembershipManager.SingleGroupManager singleGroupMembershipManager,
        Microsoft.Graph.User graphUser)
    {
        string emailCandidate = GetUserEmailFromGraphADUser(graphUser);

        IwsDiagnostics.Assert(!string.IsNullOrWhiteSpace(emailCandidate), "843-706: User principal name is NULL");

        singleGroupMembershipManager.AddUser(emailCandidate);
    }
예제 #17
0
        public async Task UpdateUserAsync(User user)
        {
            var userPatch = new Microsoft.Graph.User();

            userPatch.DisplayName    = user.Name;
            userPatch.AdditionalData = new Dictionary <string, object>();
            userPatch.AdditionalData[GetUserAttributeExtensionName(Constants.UserAttributes.CompanyId)] = user.CompanyId;
            userPatch.AdditionalData[GetUserAttributeExtensionName(Constants.UserAttributes.DelegatedUserManagementRole)] = user.DelegatedUserManagementRole;
            await this.graphClient.Users[user.Id].Request().UpdateAsync(userPatch);
        }
예제 #18
0
        public async Task <Microsoft.Graph.User> GetUserAsync(string userId)
        {
            var user = new Microsoft.Graph.User()
            {
                Mail        = "*****@*****.**",
                GivenName   = "John",
                Surname     = "Doe",
                DisplayName = "test student",
                Id          = userId
            };

            return(user);
        }
예제 #19
0
 public static bool VerifyAccess(this Microsoft.Graph.User user, string orgId, OrganizationOptions options)
 {
     if (!user.AdditionalData.Any())
     {
         return(false);
     }
     if (user.AdditionalData == null || user.AdditionalData.ContainsKey(options.OrgIdExtensionName))
     {
         var orgData = user.AdditionalData[options.OrgIdExtensionName].ToString();
         return(string.Equals(orgData, orgId, StringComparison.OrdinalIgnoreCase));
     }
     return(false);
 }
예제 #20
0
        public static void Users(User user)
        {
            var gremlinVertices = new List <GremlinVertex>();
            var userVertex      = new GremlinVertex(user.Id, nameof(User));

            userVertex.AddProperty(CosmosDbHelper.CollectionPartitionKey, user.Id.GetHashCode());
            userVertex.AddProperty(nameof(user.UserPrincipalName), user.UserPrincipalName ?? string.Empty);
            userVertex.AddProperty(nameof(user.Mail), user.Mail ?? string.Empty);
            userVertex.AddProperty(nameof(user.DisplayName), user.DisplayName?.ToUpper() ?? string.Empty);
            gremlinVertices.Add(userVertex);

            CosmosDbHelper.RunImportVerticesBlock.Post(gremlinVertices);
        }
        /// <summary>
        /// Add the provided User to the graph.
        /// </summary>
        /// <param name="user">The User.</param>
        /// <returns>The updated User object.</returns>
        /// <remarks>Required fields are: DisplayName, PasswordProfile,AccountEnabled (true or false),
        /// MailNickname, UserPrincipalName.
        /// </remarks>
        public async Task <User> AddUser(User user)
        {
            try
            {
                var ret = await client.Users.Request().AddAsync(user);

                return(ret);
            }
            catch (ServiceException se)
            {
                throw new UserException(
                          $"A {se.StatusCode} occured adding user {user.UserPrincipalName} to the directory: {se.Error.Message} Check the inner exception for details.",
                          user, se);
            }
        }
예제 #22
0
        public async Task <UpdateContactInfoByIdOutputData> Execute(UpdateContactInfoByIdInputData request)
        {
            UpdateContactInfoByIdOutputData response = null;

            try
            {
                var changeUser = new Microsoft.Graph.User
                {
                    MobilePhone   = request.User.Phone,
                    StreetAddress = request.User.Address
                };

                await Graph.Users[request.User.GUID].Request()
                .UpdateAsync(changeUser);

                var result = await Graph.Users[request.User.GUID].Request()
                             .Select(u => new
                {
                    u.Id,
                    u.DisplayName,
                    u.Department,
                    u.Mail,
                    u.MailNickname,
                    u.MobilePhone,
                    u.Birthday,
                    u.CreatedDateTime,
                    u.JobTitle,
                    u.StreetAddress
                })
                             .GetAsync();


                response = new UpdateContactInfoByIdOutputData
                {
                    User = new UserModel(result)
                };

                logger.Information(
                    $"Type: GetUserByIdActivity; Method: Execute; Info: Update info by Id: {request.User.GUID} successfully");
            }
            catch (Exception e)
            {
                logger.Error($"Type: UpdateContactInfoByIdActivity; Method: Execute; Error: {e.Message}");
                throw;
            }

            return(await Task.FromResult(response));
        }
예제 #23
0
        public async Task OnPost()
        {
            var form = Request.Form;

            if (form.TryGetValue("userDeleteId", out var value))
            {
                await GraphApiConnector.DeleteUser(value);
            }
            else
            {
                Microsoft.Graph.User user;

                var list = new List <ObjectIdentity>();

                if (users.Where(a => a.Username.Equals(form["userId"])).Any())
                {
                    list = GraphApiConnector.users.Where(a => a.Id.Equals(form["userId"])).First().Identities.ToList();
                    list.Where(identity => identity.SignInType.Equals("emailAddress")).First().IssuerAssignedId = form["EmailAddress"];

                    user = new Microsoft.Graph.User
                    {
                        Id             = form["userId"],
                        AccountEnabled = true,
                        DisplayName    = form["DisplayName"],
                        CreationType   = "LocalAccount",
                        Identities     = list
                    };
                    await GraphApiConnector.UpdateUser(user);
                }
                else
                {
                    list.Add(new ObjectIdentity
                    {
                        SignInType       = "emailAddress",
                        Issuer           = "emsfiiot.onmicrosoft.com",
                        IssuerAssignedId = form["EmailAddress"]
                    });

                    user = new Microsoft.Graph.User
                    {
                        Id              = form["userId"],
                        AccountEnabled  = true,
                        DisplayName     = form["DisplayName"],
                        CreationType    = "LocalAccount",
                        PasswordProfile = new PasswordProfile
                        {
                            ForceChangePasswordNextSignInWithMfa = true,
                            Password = "******"
        private static FabricGraphApiUser CreateMicrosoftGraphUser(string id, string displayName, string givenName, string surname, string email = null, string tenantId = "null")
        {
            var user = new Microsoft.Graph.User()
            {
                UserPrincipalName = displayName,
                GivenName         = givenName,
                DisplayName       = displayName,
                Surname           = surname,
                Id   = id,
                Mail = email
            };

            return(new FabricGraphApiUser(user)
            {
                TenantId = tenantId
            });
        }
예제 #25
0
        public static void Users(User _)
        {
            if (_usersOutput.IsCompleted)
            {
                _usersOutput = new BlockingCollection <JsonBase>();
                _usersWriter = Extensions.StartOutputWriter(_usersOutput);
            }

            _usersOutput.Add(new Models.BloodHound.User
            {
                Name       = _.DisplayName,
                Properties = new Dictionary <string, object>
                {
                    { nameof(_.Id), _.Id },
                    { nameof(_.UserPrincipalName), _.UserPrincipalName },
                    { nameof(_.Mail), _.Mail }
                }
            });
        }
예제 #26
0
        private async Task <PrincipalViewModel> MapUser(Microsoft.Graph.User u)
        {
            if (u == null)
            {
                return(null);
            }

            PrincipalViewModel user = new PrincipalViewModel()
            {
                UserPrincipalName = u.UserPrincipalName,
                DisplayName       = u.DisplayName,
                Mail      = u.Mail,
                FirstName = u.GivenName,
                LastName  = u.Surname,
                JobTitle  = u.JobTitle
            };

            return(user);
        }
예제 #27
0
        private static async Task <ClaimsPrincipal> UpdateUserRole(ClaimsPrincipal user, string role, string id, string extensionId, IGraphServiceClient graphClient)
        {
            var             claims    = user.Claims.Append(new Claim("extension_zaprole", role));
            ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(user.Identity, claims));

            Thread.CurrentPrincipal = principal;

            IDictionary <string, object> extensions = new Dictionary <string, object>();

            extensions.Add($"extension_{extensionId}_zaprole", role);

            var adUser = new Microsoft.Graph.User
            {
                AdditionalData = extensions
            };

            int retries = 0;

            async Task updateUser(string userId)
            {
                try
                {
                    await graphClient.Users[userId].Request().UpdateAsync(adUser);
                }
                catch (Exception exception)
                {
                    await Task.Delay(1000);

                    retries++;
                    if (retries > 2)
                    {
                        throw exception;
                    }

                    await updateUser(id);
                }
            }

            await updateUser(id);

            return(principal);
        }
        private static async Task <Microsoft.Graph.User> CreateUserAsync(GraphServiceClient client)
        {
            Microsoft.Graph.User user = new Microsoft.Graph.User()
            {
                AccountEnabled    = true,
                GivenName         = "Melissa",
                Surname           = "Darrow",
                DisplayName       = "Melissa Darrow",
                MailNickname      = "MelissaD",
                UserPrincipalName = "*****@*****.**",
                PasswordProfile   = new PasswordProfile()
                {
                    Password = "******",
                    ForceChangePasswordNextSignIn = true
                }
            };
            var requestNewUser = client.Users.Request();

            return(await requestNewUser.AddAsync(user));
        }
예제 #29
0
        public static async Task <string> GetUserEmail(string accessToken)
        {
            GraphServiceClient client = new GraphServiceClient(
                new DelegateAuthenticationProvider(
                    async(requestMessage) =>
            {
                requestMessage.Headers.Authorization =
                    new AuthenticationHeaderValue("Bearer", accessToken);
            }));

            // Get the user's email address
            try
            {
                Microsoft.Graph.User user = await client.Me.Request().GetAsync();

                return(user.Mail);
            }
            catch (ServiceException ex)
            {
                return(string.Format("#ERROR#: Could not get user's email address. {0}", ex.Message));
            }
        }
        public async Task <Tuple <bool, string, Microsoft.Graph.User> > GetUserByEmail(GraphServiceClient graphClient, string UserEmailAddress)
        {
            bool   ActionStatus = false;
            string message      = string.Empty;

            Microsoft.Graph.User returnUser = null;

            try
            {
                IGraphServiceUsersCollectionPage _usersFilteredId = await graphClient.Users.Request().Filter($"Mail eq '" + UserEmailAddress + "' or UserPrincipalName eq '" + UserEmailAddress + "'").GetAsync();

                returnUser = _usersFilteredId.FirstOrDefault();

                ActionStatus = true;
                message      = "Valid user found";
            }
            catch (Exception ex)
            {
                message = ex.Message + (ex.InnerException != null ? Environment.NewLine + ex.InnerException.Message : "");
            }

            return(new Tuple <bool, string, Microsoft.Graph.User>(ActionStatus, message, returnUser));
        }
        public async Task AddGroupsAndUsersAsync(GraphServiceClient graphService, string graphAccessToken)
        {
            List<string> newUsers = new List<string>();

            #region Create AD Group

            var groupsDict = new Dictionary<string, Graph.Group>();

            XmlNode groupItems = sampleData.SelectSingleNode("//List[@name='AD Groups']");

            foreach (XmlNode item in groupItems.ChildNodes)
            {
                string displayName = item.Attributes["DisplayName"].Value;
                string description = item.Attributes["Description"].Value;
                string mailNickname = item.Attributes["MailNickname"].Value;

                var group = await GraphServiceExtension.GetGroupByDisplayNameAsync(graphService, displayName);
                if (group == null)
                {
                    group = await GraphServiceExtension.AddGroupAsync(graphService, mailNickname, displayName, description);
                }
                groupsDict.Add(displayName, group as Graph.Group);
            }

            #endregion

            #region Create AD Users

            XmlNode userItems = sampleData.SelectSingleNode("//List[@name='AD Users']");
            foreach (XmlNode item in userItems)
            {
                string displayName = item.Attributes["DisplayName"].Value;
                string userPrincipalName = item.Attributes["PrincipalName"].Value;
                string password = item.Attributes["Password"].Value;
                string ownGroupDisplayName = item.Attributes["GroupsDisplayName"].Value;
                string jobTitle = item.Attributes["JobTitle"].Value;
                string companyName = item.Attributes["CompanyName"].Value;
                string officeLocation = item.Attributes["OfficeLocation"].Value;
                string mobilePhone = item.Attributes["MobilePhone"].Value;
                string businessPhone = item.Attributes["BusinessPhone"].Value;

                var queryUser = (await graphService.Users.Request().Filter(string.Format("displayName eq '{0}'", displayName)).GetAsync()).CurrentPage;//await GraphServiceExtension.GetFirstUserAsync(graphService, i => i.DisplayName == displayName);
                Graph.User user = queryUser.Count > 0 ? queryUser[0] : null;
                if (user == null)
                {
                    List<string> bp = new List<string>();
                    bp.Add(businessPhone);
                    user = new Graph.User
                    {
                        DisplayName = displayName,
                        UserPrincipalName = userPrincipalName + "@" + AppSettings.DemoSiteCollectionOwner.Split('@')[1],
                        PasswordProfile = new PasswordProfile
                        {
                            Password = password,
                            ForceChangePasswordNextSignIn = false
                        },
                        UsageLocation = "US",
                        AccountEnabled = true,
                        MailNickname = userPrincipalName,
                        JobTitle = jobTitle,
                        Department = companyName,
                        OfficeLocation = officeLocation,
                        BusinessPhones = bp
                    };

                    user = await GraphServiceExtension.AddUserAsync(graphService, user);
                    await GraphServiceExtension.AssignLicenseAsyncViaHttpClientAsync(graphService, graphAccessToken, user as Graph.User);
                }

                if (groupsDict.ContainsKey(ownGroupDisplayName)
                    && (await GraphServiceExtension.GetGroupMembersAsync(graphService, ownGroupDisplayName))
                    .Where(i => i.UserPrincipalName == user.UserPrincipalName).Count() == 0)
                {
                    try
                    {
                        await GraphServiceExtension.AddUserToGroupMembersAsync(graphService, groupsDict[ownGroupDisplayName], user, graphAccessToken);
                    }
                    catch { }
                }

                newUsers.Add(user.UserPrincipalName);
            }

            #endregion

            AddUsersToSPGroup(newUsers);
        }