public async Task <Graph.Group> CreateUnifiedGroupForPropertyAsync(GraphServiceClient graphService, string graphAccessToken, ListItem propertyItem, IEnumerable <Graph.User> members)
        {
            var propertyTitle       = propertyItem["Title"] as string;
            var propertyOwnerName   = propertyItem["sl_owner"] as string;
            var querypropertyOwners = (await graphService.Users.Request().Filter(string.Format("displayName eq '{0}'", propertyOwnerName)).GetAsync()).CurrentPage;
            var propertyOwner       = querypropertyOwners.Count > 0 ? querypropertyOwners[0] : null;

            if (propertyOwner == null)
            {
                return(null);
            }
            // Create Office 365 Group
            string  groupId   = string.Empty;
            dynamic groupJSON = new JObject();

            groupJSON.displayName     = propertyTitle;
            groupJSON.mailNickname    = propertyTitle.Replace(" ", "");
            groupJSON.securityEnabled = false;
            groupJSON.mailEnabled     = true;
            groupJSON.description     = "Property Group";
            groupJSON.groupTypes      = new JArray("Unified");
            HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Post, string.Format("{0}groups", AADAppSettings.GraphResourceUrl));

            message.Content = new StringContent(groupJSON.ToString(), System.Text.Encoding.UTF8, "application/json");
            message.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", graphAccessToken);
            using (HttpClient client = new HttpClient())
            {
                var responseMessage = await client.SendAsync(message);

                if (responseMessage.StatusCode != System.Net.HttpStatusCode.Created)
                {
                    throw new System.Web.Http.HttpResponseException(responseMessage.StatusCode);
                }

                var payload = await responseMessage.Content.ReadAsStringAsync();

                groupId = JObject.Parse(payload)["id"].ToString();
            }
            var group = await graphService.Groups[groupId].Request().GetAsync() as Graph.Group;

            // Add users to Office 365 Group
            var groupMembers  = new HashSet <Graph.User>(members);
            var groupOwners   = new HashSet <Graph.User>();
            var adminUserName = _currentUserName;
            var queryAdmins   = (await graphService.Users.Request().Filter(string.Format("mail eq '{0}'", adminUserName)).GetAsync()).CurrentPage;
            var admin         = queryAdmins.Count > 0 ? queryAdmins[0] : null;

            if (admin != null)
            {
                groupMembers.Add(admin);
                groupOwners.Add(admin);
            }
            if (propertyOwner != null)
            {
                groupMembers.Add(propertyOwner);
                groupOwners.Add(propertyOwner);
            }

            foreach (var user in groupMembers.OfType <Graph.User>())
            {
                try
                {
                    await GraphServiceExtension.AddUserToGroupMembersAsync(graphService, group, user, graphAccessToken);
                }
                catch { }
            }

            foreach (var user in groupOwners.OfType <Graph.User>())
            {
                try
                {
                    await GraphServiceExtension.AddUserToGroupOwnersAsync(graphService, group, user, graphAccessToken);
                }
                catch { }
            }

            return(group);
        }
        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);
        }