コード例 #1
0
        /// <summary>
        /// Add a site collection administrator to a site collection
        /// </summary>
        /// <param name="web">Site to operate on</param>
        /// <param name="adminLogins">Array of admins loginnames to add</param>
        /// <param name="addToOwnersGroup">Optionally the added admins can also be added to the Site owners group</param>
        public static void AddAdministrators(this Web web, List <UserEntity> adminLogins, bool addToOwnersGroup = false)
        {
            var users = web.SiteUsers;

            web.Context.Load(users);

            foreach (var admin in adminLogins)
            {
                UserCreationInformation newAdmin = new UserCreationInformation();

                newAdmin.LoginName = admin.LoginName;
                //User addedAdmin = users.Add(newAdmin);
                User addedAdmin = web.EnsureUser(newAdmin.LoginName);
                web.Context.Load(addedAdmin);
                web.Context.ExecuteQueryRetry();

                //now that the user exists in the context, update to be an admin
                addedAdmin.IsSiteAdmin = true;
                addedAdmin.Update();

                if (addToOwnersGroup)
                {
                    web.AssociatedOwnerGroup.Users.AddUser(addedAdmin);
                    web.AssociatedOwnerGroup.Update();
                }
                web.Context.ExecuteQueryRetry();
            }
        }
コード例 #2
0
        /// <summary>
        /// Add a site collection administrator to a site collection
        /// </summary>
        /// <param name="web">Site to operate on</param>
        /// <param name="adminLogins">Array of admins loginnames to add</param>
        /// <param name="addToOwnersGroup">Optionally the added admins can also be added to the Site owners group</param>
        public static void AddAdministrators(this Web web, List<UserEntity> adminLogins, bool addToOwnersGroup = false)
        {
            var users = web.SiteUsers;
            web.Context.Load(users);

            foreach (var admin in adminLogins)
            {
                UserCreationInformation newAdmin = new UserCreationInformation();

                newAdmin.LoginName = admin.LoginName;
                //User addedAdmin = users.Add(newAdmin);
                User addedAdmin = web.EnsureUser(newAdmin.LoginName);
                web.Context.Load(addedAdmin);
                web.Context.ExecuteQuery();

                //now that the user exists in the context, update to be an admin
                addedAdmin.IsSiteAdmin = true;
                addedAdmin.Update();

                if (addToOwnersGroup)
                {
                    web.AssociatedOwnerGroup.Users.AddUser(addedAdmin);
                    web.AssociatedOwnerGroup.Update();
                }
                web.Context.ExecuteQuery();
            }
        }
コード例 #3
0
ファイル: SecurityExtensions.cs プロジェクト: vcx/PnP
        /// <summary>
        /// Adds a user to a group
        /// </summary>
        /// <param name="web">web to operate against</param>
        /// <param name="groupName">Name of the group</param>
        /// <param name="userLoginName">Loginname of the user</param>
        public static void AddUserToGroup(this Web web, string groupName, string userLoginName)
        {
            if (string.IsNullOrEmpty(groupName))
            {
                throw new ArgumentNullException("groupName");
            }

            if (string.IsNullOrEmpty(userLoginName))
            {
                throw new ArgumentNullException("userLoginName");
            }

            //Ensure the user is known
            UserCreationInformation userToAdd = new UserCreationInformation();

            userToAdd.LoginName = userLoginName;
            User user = web.EnsureUser(userToAdd.LoginName);

            web.Context.Load(user);
            //web.Context.ExecuteQuery();

            //Add the user to the group
            var group = web.SiteGroups.GetByName(groupName);

            web.Context.Load(group);
            web.Context.ExecuteQuery();
            if (group != null)
            {
                web.AddUserToGroup(group, user);
            }
        }
コード例 #4
0
        private void AddOrRemoveUserToGroup(IEnumerable <string> groupIDs, UserOpType operationType, ClientContext clientContext)
        {
            if (groupIDs.Count() > 0)
            {
                string          userID    = txtUserID.Text;
                GroupCollection collGroup = clientContext.Web.SiteGroups;

                UserCreationInformation userCreationInfo = new UserCreationInformation();
                userCreationInfo.LoginName = userID;

                foreach (string groupID in groupIDs)
                {
                    Group oGroup = collGroup.GetById(Convert.ToInt32(groupID));
                    if (operationType.Equals(UserOpType.AddUser))
                    {
                        oGroup.Users.Add(userCreationInfo);
                        clientContext.ExecuteQuery();
                    }
                    else
                    {
                        User user = oGroup.Users.GetByLoginName(userID);
                        oGroup.Users.Remove(user);
                        clientContext.ExecuteQuery();
                    }
                } //  foreach (string group
            }     // if (groups.Count() > 0)
        }
コード例 #5
0
        private void InitFromCreationInformationUser(UserCreationInformation userCreationInformation)
        {
            this.Email = userCreationInformation.Email;

            var principal = SimPrincipal.FromInstance(this.Instance);

            principal.LoginName = userCreationInformation.LoginName;
            principal.Title     = userCreationInformation.Title;
        }
コード例 #6
0
        /// <summary>
        /// Imports the new SiteUsers to the target SharePoint.
        /// </summary>
        /// <exception cref="ElementsMigrationException">If the migration fails</exception>
        private void ImportNewUsers()
        {
            Console.WriteLine("import new Users...");
            Logger.AddMessage("import new Users...");
            UserCollection sourceUserCollection = this.GetAllUser(SourceClientContext);
            UserCollection targetUserCollection = this.GetAllUser(TargetClientContext);

            HashSet <string> targetUserNames = targetUserCollection.GetAllLoginNames();

            foreach (var sourceUser in sourceUserCollection)
            {
                if (!targetUserNames.Contains(sourceUser.LoginName))
                {
                    Console.WriteLine("Import user '{0}'", sourceUser.LoginName);
                    Logger.AddMessage("import User '" + sourceUser.LoginName + "'");

                    UserCreationInformation creationObject = new UserCreationInformation();
                    creationObject.Email     = sourceUser.Email;
                    creationObject.LoginName = sourceUser.LoginName;
                    creationObject.Title     = sourceUser.Title;

                    User targetUser = targetUserCollection.Add(creationObject);

                    try
                    {
                        targetUser.IsSiteAdmin = sourceUser.IsSiteAdmin;
                    }
                    catch (PropertyOrFieldNotInitializedException)
                    {
                    }

                    try
                    {
                        targetUser.Tag = sourceUser.Tag;
                    }
                    catch (PropertyOrFieldNotInitializedException)
                    {
                    }
                }
                else
                {
                    Console.WriteLine("user '{0}' is already on target server. nothing to import.", sourceUser.LoginName);
                    Logger.AddMessage("don't have to import user '" + sourceUser.LoginName + "'");
                }
            }

            try
            {
                TargetClientContext.ExecuteQuery();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception during importing the SiteUsers.", e);
                Logger.AddMessage("Exception during importing the Users. Error = " + e.Message);
                throw new ElementsMigrationException("Exception during importing the SiteUsers.", e);
            }
        }
コード例 #7
0
        static void Enter_Group(string Login, string nombre)
        {
            ClientContext context = new ClientContext("[siteurl]");

            context.Credentials = new NetworkCredential("[username]", "[password]");
            GroupCollection         _GroupCollection = context.Web.SiteGroups;
            Group                   grupo            = _GroupCollection.GetById(6);
            UserCreationInformation UCI = new UserCreationInformation();

            UCI.Title     = nombre;
            UCI.LoginName = @Login;
            User usuario = grupo.Users.Add(UCI);
            Web  web     = context.Web;

            context.Load(web);
            context.ExecuteQuery();
            Move_Users();
        }
コード例 #8
0
        public void AssignPermissionToCatalogLists(string listName, ClientContext catalogContext, string userEmail,
                                                   string role, IConfigurationRoot configuration)
        {
            string          tempUserEmail       = userEmail;
            GroupCollection groupCollection     = catalogContext.Web.SiteGroups;
            Group           group               = groupCollection.GetByName(configuration["General:MatterUsersGroup"].ToString());
            Principal       teamMemberPrincipal = catalogContext.Web.EnsureUser(userEmail.Trim());

            catalogContext.Load(teamMemberPrincipal, teamMemberPrincipalProperties => teamMemberPrincipalProperties.Title,
                                teamMemberPrincipalProperties => teamMemberPrincipalProperties.LoginName);
            catalogContext.ExecuteQuery();

            UserCreationInformation userInfo = new UserCreationInformation();

            userInfo.LoginName = teamMemberPrincipal.LoginName;
            userInfo.Email     = userEmail;
            group.Users.Add(userInfo);
            catalogContext.ExecuteQuery();
        }
コード例 #9
0
ファイル: UpdateMatter.cs プロジェクト: sgryphon/mattercenter
        public void AssignPermissionToCatalogLists(string listName, ClientContext catalogContext, string userEmail,
                                                   string role, IConfigurationRoot configuration)
        {
            string tempUserEmail = userEmail;

            if (!userEmail.Contains(configuration["General:Tenant"].ToString()))
            // i: 0#.f|membership|venkatmuppa3_outlook.com#ext#@msmattercela.onmicrosoft.com
            {
                tempUserEmail = userEmail.Replace("@", "_");
                tempUserEmail = $"i:0#.f|membership|{tempUserEmail}#EXT#@{configuration["General:Tenant"].ToString()}";
            }
            GroupCollection groupCollection = catalogContext.Web.SiteGroups;
            Group           group           = groupCollection.GetByName("Matter Center Users");

            UserCreationInformation userInfo = new UserCreationInformation();

            userInfo.LoginName = tempUserEmail;
            userInfo.Email     = userEmail;
            group.Users.Add(userInfo);
            catalogContext.ExecuteQuery();
        }
コード例 #10
0
ファイル: SecurityExtensions.cs プロジェクト: yangecnu/PnP
        /// <summary>
        /// Adds a user to a group
        /// </summary>
        /// <param name="web">web to operate against</param>
        /// <param name="groupName">Name of the group</param>
        /// <param name="userLoginName">Loginname of the user</param>
        public static void AddUserToGroup(this Web web, string groupName, string userLoginName)
        {
            //Ensure the user is known
            UserCreationInformation userToAdd = new UserCreationInformation();

            userToAdd.LoginName = userLoginName;
            User user = web.EnsureUser(userToAdd.LoginName);

            web.Context.Load(user);
            //web.Context.ExecuteQuery();

            //Add the user to the group
            var group = web.SiteGroups.GetByName(groupName);

            web.Context.Load(group);
            web.Context.ExecuteQuery();
            if (group != null)
            {
                web.AddUserToGroup(group, user);
            }
        }
コード例 #11
0
ファイル: RERProjectStatement.svc.cs プロジェクト: nganbui/SP
        /// <summary>
        /// Add users to existing group
        /// </summary>
        /// <param name="grp"></param>
        /// <param name="clientContext"></param>
        /// <param name="users"></param>
        private static void AddUsertoGroup(Group grp, ClientContext clientContext, List<FieldUserValue> users)
        {
            try
            {
                if (grp != null)
                {
                    // remove all users from existed group
                    UserCollection listofUsers = grp.Users;
                    clientContext.Load(listofUsers);
                    clientContext.ExecuteQuery();
                    if (listofUsers.Count > 0)
                    {
                        foreach (User existedUser in listofUsers)
                        {
                            if (existedUser != null)
                                listofUsers.RemoveById(existedUser.Id);

                        }

                        clientContext.ExecuteQuery();

                    }
                    // readd to this group
                    foreach (FieldUserValue member in users)
                    {
                        User user = null;
                        user = clientContext.Web.GetUserById(member.LookupId);
                        clientContext.Load(user);
                        clientContext.ExecuteQuery();
                        if (user != null)
                        {

                            UserCreationInformation userCreationInfo = new UserCreationInformation();
                            userCreationInfo.Email = user.Email;
                            userCreationInfo.LoginName = user.LoginName;
                            userCreationInfo.Title = user.Title;

                            User oUser = grp.Users.Add(userCreationInfo);

                            clientContext.ExecuteQuery();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.Write(e.Message);

            }
        }
コード例 #12
0
        public void AssignPermissionToCatalogLists(string listName, ClientContext catalogContext, string userEmail, 
            string role, IConfigurationRoot configuration)
        {
            string tempUserEmail = userEmail;            
            GroupCollection groupCollection = catalogContext.Web.SiteGroups;
            Group group = groupCollection.GetByName(configuration["General:MatterUsersGroup"].ToString());
            Principal teamMemberPrincipal = catalogContext.Web.EnsureUser(userEmail.Trim());
            catalogContext.Load(teamMemberPrincipal, teamMemberPrincipalProperties => teamMemberPrincipalProperties.Title,
                                                teamMemberPrincipalProperties => teamMemberPrincipalProperties.LoginName);
            catalogContext.ExecuteQuery();           

            UserCreationInformation userInfo = new UserCreationInformation();
            userInfo.LoginName = teamMemberPrincipal.LoginName;
            userInfo.Email = userEmail;
            group.Users.Add(userInfo);
            catalogContext.ExecuteQuery();
        }
コード例 #13
0
ファイル: Class1.cs プロジェクト: aglesaint/sharepointSite
        public string CreateSite(string urlRoot_, string siteUrl_, string title_, string administrator_, XmlDocument params_)
        {

            using (ClientContext ctx = new ClientContext(urlRoot_))
            {
                ctx.Credentials = SelectCreds(params_);
                Web rootWeb = ctx.Web;
                ctx.Load(rootWeb);
                ctx.ExecuteQuery();

                // Site web
                WebCreationInformation wci = new WebCreationInformation();
                wci.Url = siteUrl_;
                wci.Title = title_;
                wci.Language = Convert.ToInt32(params_.DocumentElement.Attributes["Langue"].Value);
                wci.WebTemplate = params_.DocumentElement.Attributes["Template"].Value;
                wci.Description = "";
                wci.UseSamePermissionsAsParentSite = false;
                Web newWeb = ctx.Web.Webs.Add(wci);
               

                // Paramétrage du site
                // Masterpage
                /*         newWeb.MasterUrl = ctx.Web.ServerRelativeUrl + params_.DocumentElement.Attributes["MasterPage"].Value;
                         newWeb.CustomMasterUrl = ctx.Web.ServerRelativeUrl + params_.DocumentElement.Attributes["MasterPage"].Value;
                         // Features à desactiver
                         XmlNode feats = params_.DocumentElement.SelectSingleNode("/CNPCloud/FeaturesToDeactivate");
                         foreach (XmlNode xnf in feats.ChildNodes)
                         {
                             newWeb.Features.Remove(new Guid(xnf.Attributes["Id"].Value), true);
                         }
                 */

                /* 
                 * Groupe administrateur du site en cours 
                 * 
                 */
                  XmlNode groupAdmin = params_.DocumentElement.SelectSingleNode("/CNPCloud/GroupAdmin");
                  GroupCreationInformation gcadmin = new GroupCreationInformation();
                  gcadmin.Title = siteUrl_ + groupAdmin.Attributes["Suffix"].Value;
                  Group gAdmins = newWeb.SiteGroups.Add(gcadmin);
                  gAdmins.Owner = ctx.Web.EnsureUser(params_.DocumentElement.Attributes["SPAdmin"].Value);
                  UserCreationInformation uci = new UserCreationInformation();
                  uci.LoginName = administrator_;
                  gAdmins.Users.Add(uci);
                  gAdmins.Update();
    
                  SetRoleForGroup(ctx, newWeb, gAdmins, groupAdmin.Attributes["Role"].Value);
                  newWeb.AssociatedOwnerGroup = gAdmins;
                  newWeb.Update();

                  /* 
                   * Creation des groupes supplémentaire 
                   * ex: <GroupsToCreate>	
                   *       <Group Suffix="_Collaborateurs" Role="Modification"/>
                   */
                  XmlNode groups = params_.DocumentElement.SelectSingleNode("/CNPCloud/GroupsToCreate");
                     foreach (XmlNode xng in groups.ChildNodes)
                     {
                         GroupCreationInformation gci = new GroupCreationInformation();
                         gci.Title = siteUrl_ + xng.Attributes["Suffix"].Value;
                         Group g = newWeb.SiteGroups.Add(gci);
                         g.Owner = gAdmins;
                         g.Update();
                         SetRoleForGroup(ctx, newWeb, g, xng.Attributes["Role"].Value);
                     }





                     /*
                     GroupCreationInformation gcAdmin = new GroupCreationInformation();
                     gcAdmin.Title = siteUrl_ + "_Admins";
                    gAdmins = newWeb.SiteGroups.Add(gcAdmin);
                     gAdmins.Owner = ctx.Web.EnsureUser(params_.Attributes["SPAdmin"].Value);
                     UserCreationInformation uci = new UserCreationInformation();
                     uci.LoginName = administrator_;
                     gAdmins.Users.Add(uci);
                     gAdmins.Update();
                     SetRoleForGroup(ctx, newWeb, gAdmins, RoleType.WebDesigner);
                     /*
                      // Collab
                      GroupCreationInformation gcCollab = new GroupCreationInformation();
                      gcCollab.Title = siteUrl_ + "_Collaborateurs";
                      Group gCollab = newWeb.SiteGroups.Add(gcCollab);
                      gCollab.Owner = gAdmins;
                      gCollab.Update();
                      SetRoleForGroup(ctx, newWeb, gCollab, RoleType.Contributor);

                      // Lecteur
                      GroupCreationInformation gcVisit = new GroupCreationInformation();
                      gcVisit.Title = siteUrl_ + "_Visiteurs";
                      Group gVisit = newWeb.SiteGroups.Add(gcVisit);
                      gVisit.Owner = gAdmins;
                      gVisit.Update();
                      SetRoleForGroup(ctx, newWeb, gVisit, RoleType.Reader);
                      */


                ctx.ExecuteQuery();

                return "OK";
            }

        }
コード例 #14
0
        public void AddUser(int groupId, UserCreationInformation userInfo, Action<bool,Exception> reply)
        {
            ClientRequestSucceededEventHandler addUserSuccessHandler = null;
            ClientRequestFailedEventHandler addUserFailureHandler = null;

            Web website = _client.Web;
            GroupCollection groupCollection = website.SiteGroups;                        
            Group group = groupCollection.GetById(groupId);            
            User addUser = group.Users.Add(userInfo);
            group.Users.AddUser(addUser); 
            group.Update();

            addUserSuccessHandler = (s, e) =>
            {
                reply(true,null);
            };
            addUserFailureHandler = (s, e) =>
            {
                Logger.AddLog(_log, e.Exception);
                reply(false,e.Exception);
            };

            _client.ExecuteQueryAsync(addUserSuccessHandler, addUserFailureHandler);
        }
コード例 #15
0
        /*
         * Create User
         * */
        public void Create(string siteUrl, string domain, string ouName, string userName, string password, string givenName, string surName, string email, int[] groupIds, out string err) {
            err = "";
            if (!Exist(userName)) {
                using (PrincipalContext context = GetPrincipalContext(this.STORE_PATH)) {
                    UserPrincipal user = new UserPrincipal(context, userName, password, true);
                    //User Log on Name
                    try {
                        user.Name = givenName + " " + surName;
                        user.UserPrincipalName = userName;
                        user.GivenName = givenName;
                        user.Surname = surName;
                        user.EmailAddress = email;
                        user.Enabled = true;
                        user.PasswordNeverExpires = true;
                        user.Save();
                    }
                    catch (Exception ex) {
                        err = ex.Message;
                    }
                }
            }
            if (groupIds == null)
                return;

            if (groupIds.Length == 0)
                return;

            try {
                ClientContext ctx = new ClientContext(siteUrl);
                ctx.Credentials = new NetworkCredential(M_ADMIN, M_PASSWORD, M_DOMAIN);
                GroupCollection groups = ctx.Web.SiteGroups;
                ctx.Load(groups, gs => gs.Include(g => g.Id));
                ctx.ExecuteQuery();

                UserCreationInformation uci = new UserCreationInformation();
                uci.Email = email;
                uci.LoginName = "i:0#.w|"+domain + "\\" + userName;
                uci.Title = givenName + " " + surName;

                foreach (Group g in groups) {
                    if (groupIds.Contains(g.Id))
                        g.Users.Add(uci);
                }
                ctx.ExecuteQuery();
            }
            catch (Exception ex) {
                err = ex.Message;
            }

        }
コード例 #16
0
        /// <summary>
        /// Adds a user to a group
        /// </summary>
        /// <param name="web">web to operate against</param>
        /// <param name="groupName">Name of the group</param>
        /// <param name="userLoginName">Loginname of the user</param>
        public static void AddUserToGroup(this Web web, string groupName, string userLoginName)
        {
            if (string.IsNullOrEmpty(groupName))
                throw new ArgumentNullException("groupName");

            if (string.IsNullOrEmpty(userLoginName))
                throw new ArgumentNullException("userLoginName");

            //Ensure the user is known
            UserCreationInformation userToAdd = new UserCreationInformation();
            userToAdd.LoginName = userLoginName;
            User user = web.EnsureUser(userToAdd.LoginName);
            web.Context.Load(user);
            //web.Context.ExecuteQuery();

            //Add the user to the group
            var group = web.SiteGroups.GetByName(groupName);
            web.Context.Load(group);
            web.Context.ExecuteQuery();
            if (group != null)
            {
                web.AddUserToGroup(group, user);
            }
        }
コード例 #17
0
        private void AddOrRemoveUserToGroup(IEnumerable<int> groupIDs, UserOpType operationType, ClientContext clientContext, string userID)
        {
            if (groupIDs.Count() > 0)
            {
                GroupCollection collGroup = clientContext.Web.SiteGroups;

                UserCreationInformation userCreationInfo = new UserCreationInformation();
                userCreationInfo.LoginName = userID;

                foreach (int groupID in groupIDs)
                {
                    Group oGroup = collGroup.GetById(groupID);
                    if (operationType.Equals(UserOpType.AddUser))
                    {
                        oGroup.Users.Add(userCreationInfo);
                        clientContext.ExecuteQuery();
                    }
                    else
                    {
                        User user = oGroup.Users.GetByLoginName(userID);
                        oGroup.Users.Remove(user);
                        clientContext.ExecuteQuery();
                    }
                } //  foreach (string group
            } // if (groups.Count() > 0)            
        }
コード例 #18
0
        static void Main(string[] args)
        {
            String UserName = "******";

            Console.WriteLine("please enter the password");
            SecureString Password = GetPassword();

            using (ClientContext con = new ClientContext("https://acuvatehyd.sharepoint.com/teams/My_Site"))
            {
                con.Credentials = new SharePointOnlineCredentials(UserName, Password);
                GroupCollection siteGroups = con.Web.SiteGroups;
                con.Load(siteGroups);
                con.ExecuteQuery();
                foreach (Group g in siteGroups)
                {
                    Console.WriteLine(g.Title + "\n" + g.Id);
                    Console.WriteLine();
                }
                Group membersGroup = siteGroups.GetByName("only ADD Permissions");
                con.Load(membersGroup.Users);
                con.ExecuteQuery();
                foreach (User member in membersGroup.Users)
                {
                    Console.WriteLine(member.Title + "\n");
                }
                UserCreationInformation NewUser = new UserCreationInformation();
                NewUser.Email     = "*****@*****.**";
                NewUser.LoginName = "nrfsecw.com";
                NewUser.Title     = "Mr.Ussrerc";

                membersGroup = siteGroups.GetByName("only ADD Permissions");
                bool IsUserNotExist = false;
                try
                {
                    User Checkuser = membersGroup.Users.GetByEmail("*****@*****.**");
                    con.Load(Checkuser);
                    con.ExecuteQuery();
                }
                catch (Exception e)
                {
                    IsUserNotExist = true;
                }
                if (IsUserNotExist)
                {
                    User member = con.Web.EnsureUser("*****@*****.**");
                    member.Title = "thisthitle";
                    member.Update();
                    User U = membersGroup.Users.AddUser(member);
                    con.ExecuteQuery();
                }


                //User U=membersGroup.Users.Add(NewUser);
                ////con.Load(U);
                //con.ExecuteQuery();
                con.Load(membersGroup.Users);
                con.ExecuteQuery();
                foreach (User member in membersGroup.Users)
                {
                    Console.WriteLine(member.Title + "\t" + member.Email + "\t" + member.LoginName + "\n");
                }
            }
            Console.ReadKey();
        }
コード例 #19
0
        public void UpdateUserGroups(Data.User user, List<Data.Group> updateGroups, List<Group> groupCollection, Action<bool,Exception> reply)
        {          
            ClientRequestSucceededEventHandler updateGroupSuccessHandler = null;
            ClientRequestFailedEventHandler updateGroupFailureHandler = null;
            User userSCOM;

            updateGroupSuccessHandler = (s, e) =>
            {              
               reply(true,null);
            };

            updateGroupFailureHandler = (s, e) =>
            {
                Logger.AddLog(_log, e.Exception);
                reply(false, e.Exception);
            };

            UserCreationInformation userInfo = new UserCreationInformation()
            {
                LoginName = user.AccountName,
                Title = user.Name
            };

            foreach (Data.Group og in updateGroups)
            {
                foreach (Group ig in groupCollection)
                {
                    if (og.Name.Equals(ig.Title))
                    {
                        if (og.IsSelected)
                        {
                            userSCOM = ig.Users.Add(userInfo);
                            ig.Users.AddUser(userSCOM);
                        }
                        else
                        {
                            userSCOM = ig.Users.GetByLoginName(userInfo.LoginName);
                            ig.Users.Remove(userSCOM);
                        }
                        og.IsModified = false;
                        ig.Update();
                    }
                }
            }
            _client.ExecuteQueryAsync(updateGroupSuccessHandler, updateGroupFailureHandler);

        }
コード例 #20
0
ファイル: Program.cs プロジェクト: nganbui/SP
        /// <summary>
        /// Add users to existed group
        /// </summary>
        /// <param name="grp"></param>
        /// <param name="clientContext"></param>
        /// <param name="users"></param>
        private static void AddUsertoGroup(Group grp, ClientContext clientContext, List<FieldUserValue> users)
        {
            try
            {
                if (grp != null)
                {
                    // add user to this group
                    foreach (FieldUserValue member in users)
                    {
                        User user = null;
                        user = clientContext.Web.GetUserById(member.LookupId);
                        clientContext.Load(user);
                        clientContext.ExecuteQuery();
                        if (user != null)
                        {
                            // add user to corresponding group
                            UserCreationInformation userCreationInfo = new UserCreationInformation();
                            userCreationInfo.Email = user.Email;
                            userCreationInfo.LoginName = user.LoginName;
                            userCreationInfo.Title = user.Title;

                            User oUser = grp.Users.Add(userCreationInfo);
                            clientContext.ExecuteQuery();

                            // add user to Contact list
                            List contactlist = clientContext.Web.Lists.GetByTitle(ConfigurationManager.AppSettings["contactlist"].ToString());
                            if (contactlist != null)
                            {
                                var loginname = user.LoginName;
                                // get user Information from User Profile
                                PersonProperties userProfile = GetUserInformation(clientContext, loginname);
                                // in case not able to get user information from User Profile -- > get user Info from SP Information list (userCreationInfo)
                                var accountName = userProfile.IsPropertyAvailable("AccountName")==true ? userProfile.UserProfileProperties["AccountName"].ToString() : user.LoginName;
                                ListItemCollection items = null;
                                bool isExist = ItemExists(contactlist, accountName, out items);
                                if (!isExist)
                                {
                                    var lastname = user.Title.IndexOf(" ") > 0 ? user.Title.Substring(user.Title.IndexOf(" ")) : user.Title;
                                    ListItemCreationInformation contactInfo = new ListItemCreationInformation();
                                    ListItem newItem = contactlist.AddItem(contactInfo);
                                    newItem["AccountName"] = accountName;
                                    newItem["Title"] = userProfile.IsPropertyAvailable("AccountName") == true ? userProfile.UserProfileProperties["LastName"].ToString() : lastname;
                                    newItem["FullName"] = userProfile.IsPropertyAvailable("AccountName") == true ? userProfile.UserProfileProperties["PreferredName"].ToString() : user.Title;
                                    newItem["Email"] = userProfile.IsPropertyAvailable("AccountName") == true ? user.Email : user.Email;
                                    newItem["Company"] = userProfile.IsPropertyAvailable("AccountName") == true ? userProfile.UserProfileProperties["Department"].ToString() : string.Empty;
                                    newItem["JobTitle"] = userProfile.IsPropertyAvailable("AccountName") == true ? userProfile.Title : string.Empty;
                                    newItem["WorkPhone"] = userProfile.IsPropertyAvailable("AccountName") == true ? userProfile.UserProfileProperties["WorkPhone"].ToString() : string.Empty;
                                    newItem["WorkFax"] = userProfile.IsPropertyAvailable("AccountName") == true ? userProfile.UserProfileProperties["Fax"].ToString() : string.Empty;
                                    newItem["WorkAddress"] = userProfile.IsPropertyAvailable("AccountName") == true ? userProfile.UserProfileProperties["SPS-Location"].ToString() : string.Empty;
                                    newItem["CellPhone"] = userProfile.IsPropertyAvailable("AccountName") == true  ? userProfile.UserProfileProperties["CellPhone"].ToString() : string.Empty;
                                    newItem["WebPage"] = userProfile.IsPropertyAvailable("AccountName") == true ? userProfile.UserUrl : string.Empty;
                                    newItem.Update();
                                    clientContext.ExecuteQuery();
                                }
                            }

                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.Write(e.Message);

            }
        }