2

I want to add and remove user to/from Office 365 Group. I tried using C# code but got error : "User does not exist or is not unique".

After searching on the web I can't find solution.So i tried with JavaScript. I successfully add the user with JavaScript but can't removing it from office 365 group.

Edit: Here is my code for removing user. I have a Listbox which contains all users & I have to remove only users who exist in listbox & also in group. I am selecting Group from Dropdownlist.


    function removeUsers()
    {
    try {
parm = document.getElementById('ddlGroup.id'); // ddlGroup - DropdownList to select Group grouptext = parm.options[parm.selectedIndex].text;

var groupCollection = clientContext.get_web().get_siteGroups(); visitorsGroup = groupCollection.getByName(grouptext.trim()); selUser = document.getElementById('<%=listAllUsers.ClientID%>'); var listLength = selUser.options.length; for (var i = 0; i < listLength; i++) { var usr2 = clientContext.get_web().ensureUser(selUser.options[i].value); var userCollection = visitorsGroup.get_users(); var grp, usr; var isExist = false; // is user exist if(userCollection.count > 0) { for(var i=0; i < userCollection.count; i++) { if(userCollection[i].get_loginName() == usr2.get_loginName()) { isExist = true; } } } if (isExist == true) { if (usr2 != null) { userCollection.remove(usr2); clientContext.load(userCollection); } } else { continue; } } clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed)); } catch (e) { alert("Error in removing users:" + e.message + e.stack); } } function onQuerySucceeded() { alert("User(s) removed Successfully"); } function onQueryFailed(sender, args) { alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace()); }
  • 1
    Showing code of what you've tried to remove a user might help – Eric Alexander Dec 7 '14 at 16:03
  • Now, I put a code above. – Ronak Patel Dec 8 '14 at 9:04
5

The error:

The user does not exist or is not unique

most probably occurs since user could not be found.

The list of methods that could be utilized for removing a user from group:

The following examples demonstrate how to remove User from Group using SP.UserCollection.removeByLoginName

JSOM example

function removeUserFromGroup(userLoginName,groupName,success,error)
{
    var ctx = SP.ClientContext.get_current()
    var web = ctx.get_web();
    var group = web.get_siteGroups().getByName(groupName);
    group.get_users().removeByLoginName(userLoginName); 
    ctx.executeQueryAsync( 
       function(){
           success();
       },
       error);
}

Usage

var userLoginName = 'i:0#.f|membership|username@tenant.onmicrosoft.com';
removeUserFromGroup(userLoginName,'Team Site Members',
function(){
    console.log('User has been removed from Group');
},
function(sender,args){
    console.log(args.get_message());
});  

REST example

function removeUserFromGroup(webUrl,userLoginName,groupName)
{
    var url = webUrl + "/_api/web/sitegroups/getbyname('" +  encodeURIComponent(groupName) + "')/users/removebyloginname(@u)?@u='" + encodeURIComponent(userLoginName) + "'";
    return $.ajax({
        url: url,
        method: "POST",
        contentType: "application/json;odata=verbose",
        headers: {
           "Accept": "application/json;odata=verbose",
           "X-RequestDigest": $("#__REQUESTDIGEST").val()
        }
    });
}

Usage

var userLoginName = 'i:0#.f|membership|username@tenant.onmicrosoft.com';
var groupName = 'Team Site Members';
removeUserFromGroup(_spPageContextInfo.webAbsoluteUrl,userLoginName,groupName)
.done(function(data)
{
   console.log('User has been removed from Group');
})
.fail(
function(error){
    console.log(JSON.stringify(error));
});
1

Using REST

You can REST endpoints for removing users from groups

http://msdn.microsoft.com/en-us/library/office/dn531432(v=office.15).aspx#bk_UserCollectionRemoveByLoginName

executor.executeAsync({
  url: "<app web url>/_api/SP.AppContextSite(@target)/web/sitegroups(7)/users
    /removebyloginname(@v)?@v='i%3A0%23.f%7Cmembership%7Cuser%40domain.onmicrosoft.com'
    &@target='<host web url>'",
  method: "POST",
  success: successHandler,
  error: errorHandler
});

Using Server Object Model

web.AllowUnsafeUpdates = true;
SPGroupCollection collGroups = web.SiteGroups;
SPUserCollection usercoll = siteobj.RootWeb.SiteUsers;
int ID = oWeb.Users[UserName].ID;
usercoll.RemoveByID(ID);
web.Update();
web.AllowUnsafeUpdates = false;

Using Client Side Object Model

ClientContext client = new ClientContext(SITEURL);
client.ExecuteQuery();
Web website = client.Web;
client.Load(website, w => w.AllProperties, w => w.SiteGroups, w => w.SiteUserInfoList, w => w.Webs,w => w.Title);
client.ExecuteQuery();
GroupCollection groupCollection = website.SiteGroups;
client.Load(groupCollection, groups => groups.Include(grps => grps.Users, grps => grps.Title));
client.ExecuteQuery();
User user;
foreach (Group group in groupCollection)
{
   if (group.Title.Equals("GroupName"))
   {
        user = group.Users.GetByLoginName(“UserName”);
        group.Users.Remove(user);           
        group.Update();
        website.Update();
        client.ExecuteQuery();
        break;
    }
}

Using JavaScript Object Model

var clientContext = new SP.ClientContext(siteUrl);
var oWeb = clientContext.get_web()
var collGroup = oWeb.get_siteGroups();
var oGroup = collGroup.getById(7); //Change 7 based on the group's id
var oUser = oGroup.get_users();
clientContext.load(oUser);
var user = web.ensureUser("domain\username);
oUser.removeByLoginName(user.get_loginName());   

clientContext.executeQueryAsync(Function.createDelegate(this, onQuerySucceeded), Function.createDelegate(this, onQueryFailed));

function onQuerySucceeded(){
    alert('User Removed');
}

function onQueryFailed() {
    alert('Failed');
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.