2

I deleted a user in Users and groups management of Office 365. But his information is still in Site Collection's All users.

How can I check if a user was deleted or not? Using Client Object Model.

2

There are couple of ways to check the user existence. You can check following options:

var targetSite = new Uri("siteurl");
            var login = "username";
            var password = "password";
            var securePassword = new SecureString();
            foreach (char c in password)
            {
                securePassword.AppendChar(c);
            }

            var onlineCredentials = new SharePointOnlineCredentials(login, securePassword);

            using (ClientContext clientContext = new ClientContext(targetSite))
            {


                clientContext.Credentials = onlineCredentials;

                Web web = clientContext.Web;
                User spuser = web.EnsureUser("test user"); // This will give exception if user does not exist.

  // otherwise you can user collection and check if user exists of not.
                UserCollection users = web.SiteUsers;
                List userinfos = web.SiteUserInfoList;
                clientContext.Load(users);
                clientContext.Load(spuser);
                clientContext.Load(userinfos);


                clientContext.ExecuteQuery();
                foreach (User user in users)
                {
                    if (user.LoginName == "")
                    { }
                }

            }
        }
  • if user is already in Site Collection All users, EnsureUser will still return SPUser object properly. – Thanhma San Jul 1 '14 at 7:02
  • If the user exists but is not in the site collection yet, EnsureUser will add the user to the hidden userinfolist. Depending on your use case you might not want that, so keep it in mind. Use the profile service to check for existence otherwise. – Jasper Dec 10 '15 at 11:52
1

Windows PowerShell for SharePoint Online contains Get-SPOUser cmdlet to return the SharePoint Online user or security group accounts that match a given search criteria.

The similar CSOM example to determine whether user exist in a site collection:

public static bool ExistsSPOUser(Tenant tenant, string siteUrl,string loginName)
{
    var ctx = tenant.Context;
    var loginResult = tenant.EncodeClaim(loginName);
    ctx.ExecuteQuery();
    var encLoginName = loginResult.Value;

    var rootWeb = tenant.GetSiteByUrl(siteUrl).RootWeb;
    var siteUsers = rootWeb.SiteUsers;
    var usersResult = ctx.LoadQuery(siteUsers.Include(u => u.LoginName).Where(u => u.LoginName == encLoginName));
    ctx.ExecuteQuery();
    return usersResult.Any();
}

Prerequisites: SharePoint Online Client Components SDK

Usage

using (var ctx = new ClientContext(tenantUrl))
{

     ctx.Credentials = new SharePointOnlineCredentials(userName, securePassword);
     var tenant = new Tenant(ctx);
     if (!ExistsSPOUser(tenant,"https://contoso.sharepoint.com/", "username@contoso.onmicrosoft.com"))
     {
         Console.WriteLine("User not found");   
     }
}
  • I think siteUrl shoud be contoso**-admin** or it will result in Current site is not a tenant administration site. error. But in my case, site to check isn't root site like this, my URL is kind of contoso.sharepoint.com/sites/TEST/TEST and I'm facing not a tenant administration site problem. Is there any workaround? – Thanhma San Jul 1 '14 at 10:17
  • Not exactly, siteUrl parameter is the actual site Url against which user have to be verified, but tenantUrl parameter corresponds to Tenant Url (contoso-admin.sharepoint.com ) – Vadim Gremyachev Jul 1 '14 at 10:23
  • I've tested the specified code and it works for me – Vadim Gremyachev Jul 1 '14 at 10:25
  • I got this error The site https://xxx.sharepoint.com/sites/xxx/xxx is not properly formed. at the ExecuteQuery to get usersResult. – Thanhma San Jul 2 '14 at 1:11
  • @VadimGremyachev I'm trying to achieve a slightly different approach, I need to check if a specific user (not current user) is currently logged in into a specific sharepoint online root site, is that possible using only the user login email and the site url? – Eliya Amanoeel Jan 25 '16 at 16:30
0

You can tried to implement the following which retrieve profile data then you can check if the user still exist or not from output created.

#Create People Manager object to retrieve profile data
$Output = "D:\Output.csv"
$Headings = "Name","Email","OneDrive URL","Phone","Job Title","Department"
$Headings -join "," | Out-File -Encoding default -FilePath $Output

$PeopleManager = New-Object Microsoft.SharePoint.Client.UserProfiles.PeopleManager($Context)
Foreach ($User in $Users)
    {
    $UserProfile = $PeopleManager.GetPropertiesFor($User.LoginName)
    $Context.Load($UserProfile)
    $Context.ExecuteQuery()
    If ($UserProfile.Email -ne $null)
        {
        $UPP = $UserProfile.UserProfileProperties
        $Properties = $UserProfile.DisplayName,$UserProfile.Email,$UserProfile.PersonalUrl, $UPP.WorkPhone,$UPP.'SPS-JobTitle',$UPP.Department
        $Properties -join "," | Out-File -Encoding default -Append -FilePath $Output
        }  
    }

The original post: http://blogs.technet.com/b/fromthefield/archive/2014/02/27/office365-retrieve-user-profiles-using-csom.aspx

  • Thank you, but is it available in COM? – Thanhma San Jun 30 '14 at 11:01
  • i have added another answer using COM. Hope any helps – Supermode Jul 1 '14 at 1:47
0

Using COM approach, i believe you can do something like this. Again you might need to tweak to suit your requirements.

var user;
var visitorsGroup;
var userCollection;
function getGroups() {
    var clientContext = new SP.ClientContext();
    var groupCollection = clientContext.get_site().get_rootWeb().get_siteGroups();

    visitorsGroup = groupCollection.getById(7);//GroupID

    user = clientContext.get_web().get_currentUser();
    userCollection = visitorsGroup.get_users();
    clientContext.load(user);
    clientContext.load(visitorsGroup);
    clientContext.load(userCollection);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded() {
    for (var index = 0; index < userCollection.get_count(); index++) {
        if (userCollection.itemAt(index).get_loginName() === user.get_loginName()) {
          alert("User present in this group");
            return;
        }
    }
alert("User notpresent in this group");
return ;
}
function onQueryFailed(sender, args) { 
    alert("User notpresent in this group");
return ;   
}

link:http://aviralchawda.blogspot.com.au/

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.