Friday, 19 February 2016

Get list of site collections with CSOM in SharePoint Online

We can easily get the list of all site collections from a Office 365 tenant using SharePoint's client object model (CSOM) in C#. In this article, I am going to write C# code sample to retrieve all site collections in a SharePoint tenant and get all site collection users and administrators.

Before proceed, you need to download and install the SharePoint Server 2013 Client Components SDK and add the following dlls in your project reference.

- Microsoft.Online.SharePoint.Client.Tenant.dll
- Microsoft.SharePoint.Client.dll
- Microsoft.SharePoint.Client.Runtime.dll

The below C# code retrieves all sites collection from the given SharePoint tenant. You have to provide your own tenant url, admin username and password.
using Microsoft.Online.SharePoint.TenantAdministration;
using Microsoft.SharePoint.Client;
// ---------------------------------
private static void GetAllSiteCollections()
{
    SPOSitePropertiesEnumerable prop = null;

    var password = new SecureString();
    foreach (char c in "MyPassword".ToCharArray()) password.AppendChar(c);
    var credentials = new SharePointOnlineCredentials("admin@MyTenant.onmicrosoft.com", password);
    var ctx = new ClientContext("https://MyTenant-admin.sharepoint.com/");
    ctx.Credentials = credentials;

    Tenant tenant = new Tenant(ctx);
    prop = tenant.GetSiteProperties(0, true);
    ctx.Load(prop);
    ctx.ExecuteQuery();
    foreach (SiteProperties sp in prop)
    {
        Console.WriteLine(sp.Title + " => " + sp.Url);
        Console.WriteLine("---------------------------");
    }
}

Get all site collection users and administrators

The above C# code only returns site collection information, to get site collection associated users and administrators, we need to load site users from site collection context and and execute the query again.
using Microsoft.Online.SharePoint.TenantAdministration;
using Microsoft.SharePoint.Client;
// ---------------------------------
private static void GetAllSiteCollectionsAndUsers()
{
    SPOSitePropertiesEnumerable prop = null;

    var password = new SecureString();
    foreach (char c in "MyPassword".ToCharArray()) password.AppendChar(c);
    var credentials = new SharePointOnlineCredentials("admin@MyTenant.onmicrosoft.com", password);
    var ctx = new ClientContext("https://MyTenant-admin.sharepoint.com/");
    ctx.Credentials = credentials;

    Tenant tenant = new Tenant(ctx);
    prop = tenant.GetSiteProperties(0, true);
    ctx.Load(prop);
    ctx.ExecuteQuery();
    foreach (SiteProperties sp in prop)
    {                        
        var context = new ClientContext(sp.Url);
        context.Credentials = sp.Context.Credentials;
        var web = context.Web;
        context.Load(web, w => w.SiteUsers);
        context.ExecuteQuery();
                
        var admins = string.Join(";", web.SiteUsers.Where(u => u.IsSiteAdmin).Select(a => a.Title).ToList());
        var users = string.Join(";", web.SiteUsers.Where(u => !u.IsSiteAdmin).Select(a => a.Title).ToList());

        Console.WriteLine(sp.Title + " => " + sp.Url);
        Console.WriteLine("Administrators  => " + admins);
        Console.WriteLine("Users  =>  " + users);
        Console.WriteLine("---------------------------");
    }
}

Advertisements
Advertisements

6 comments:

  1. I fail to authenticate even though I am logged into my admin site, so I can confirm the url, username & password. I am also unable to authenticate with Invoke-WebRequest in powershell, same credentials. However, I am able to authenticate using connect-sposervice, and then verify my connection using Get-SPOSite!

    ReplyDelete
    Replies
    1. what error you r receiving?

      Delete
    2. An unhandled exception of type 'System.Xml.XmlException' occurred in System.Xml.dll

      Additional information: For security reasons DTD is prohibited in this XML document. To enable DTD processing set the DtdProcessing property on XmlReaderSettings to Parse and pass the settings into XmlReader.Create method.

      But this is caused by failure to authenticate.

      Delete
  2. I believe that the actual error message is misleading. I believe it is an authentication failure.


    An unhandled exception of type 'System.Xml.XmlException' occurred in System.Xml.dll

    Additional information: For security reasons DTD is prohibited in this XML document. To enable DTD processing set the DtdProcessing property on XmlReaderSettings to Parse and pass the settings into XmlReader.Create method.

    ReplyDelete
    Replies
    1. I looked in Fiddler, and it looks like no authorization header is being sent.

      Delete
    2. Hi RicKK, very sorry to see that u still not solved your problem. I will try once again and get back to you.

      Delete