Fetch all site collections using CSOM

We are trying to fetch all site collections in our SP Online tenant using the below code.

SPOSitePropertiesEnumerable prop = null;         prop = tenant.GetSitePropertiesFromSharePoint("0", true);         ctx.Load(prop);         ctx.ExecuteQuery();          List<SiteProperty> AllSiteVals = new List<SiteProperty>();         foreach (SiteProperties sp in prop)         {                 flag++;                 SiteProperty siteDetail = new SiteProperty                 {                     SiteTitle = sp.Title,                     SiteUrl = sp.Url                 };                 AllSiteVals.Add(siteDetail);          } 

However we see a huge discrepancy in the number of site collections being fetched from code (around 1450) and from the admin center (around 3600). We verified that we are missing many site collections which we should not.

How do we fix this?

To fix this issue we also tried looping thru using prop = tenant.GetSiteProperties(flag, true);

Issue is we get 265 sites in the first iteration and then it moves out of the loop.

help with csom script for SPO, adding user to same default sharepoint group on multiple sites

As described in the title, im trying to add a user to the same default sharepoint group on multiple sites with a csom powershell script. (e.g. “Visitors” group)

But the default groups has different names as the sites also have different names.

with the script below, how can i retrieve the group by only specifying “visitors” in the group name? In other words, that the group can be found by only specifiyng parts of the full group name, which is the group $ Web.SiteGroups.GetByName will retrieve.

Thank you for all tips and responses.

$ Sites = Import-Csv ‘c:\PS\sposites.csv’ (with one column named URL, with site url)

$ UserAccount = “test@domain.no”

$ GroupName= “Sitename Visitor”

foreach($ site in $ Sites.URL)


$  Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($  Site) $  Ctx.Credentials = $  Creds  $  Web = $  Ctx.Web $  Group = $  Web.SiteGroups.GetByName($  GroupName)  $  User=$  web.EnsureUser($  UserAccount)  $  Result = $  Group.Users.AddUser($  User) $  Ctx.Load($  Result) $  Ctx.ExecuteQuery()  write-host  -f Green "User '$  UserAccount' has been added to '$  GroupName'" 


CSOM site provisioning error: The request uses too many resources

I continue to get an error (sometimes) when provisioning a web using CSOM. According to this MSDN article, this error is returned when the CSOM request exceeds 2MB. I watched the call in Fiddler and the request is not greater that 2MB. What could the problem be? Below is the code and request/response from fiddler:

   using (ClientContext cc = new ClientContext(url))     {         cc.Credentials = new SharePointOnlineCredentials(username, password);         WebCreationInformation information = new WebCreationInformation();        information.WebTemplate = "CMSPUBLISHING#0";        information.Description = "My New Site";        information.Title = "My New Site";        information.Url = "newsite";        // Currently all English, could be extended to be configurable based on language pack usage         information.Language = 1033;         information.UseSamePermissionsAsParentSite = false;          cc.Web.Webs.Add(information);         cc.ExecuteQueryRetry(); } 

Fiddler Request:

<Request AddExpandoFieldTypeSuffix="true" SchemaVersion="" LibraryVersion="" ApplicationName=".NET Library" xmlns="http://schemas.microsoft.com/sharepoint/clientquery/2009"><Actions><ObjectPath Id="1158" ObjectPathId="1157" /><ObjectIdentityQuery Id="1159" ObjectPathId="1157" /></Actions><ObjectPaths><Method Id="1157" ParentId="923" Name="Add"><Parameters><Parameter TypeId="{8f9e9fbe-189e-492f-884f-98f9ef9cc4d6}"><Property Name="Description" Type="String"></Property><Property Name="Language" Type="Int32">1033</Property><Property Name="Title" Type="String">Manuals</Property><Property Name="Url" Type="String">manuals</Property><Property Name="UseSamePermissionsAsParentSite" Type="Boolean">false</Property><Property Name="WebTemplate" Type="String">CMSPUBLISHING#0</Property></Parameter></Parameters></Method><Property Id="923" ParentId="384" Name="Webs" /><Identity Id="384" Name="7e19049d-e009-2000-008d-b659834a548f|740c6a0b-85e2-48a0-a494-e0f1759d4aa7:site:a43f2ef7-f1aa-423a-ad26-59b66edef6bb:web:a30643dc-7034-47ae-b87e-119ef8a2975d" /></ObjectPaths></Request> 

Fiddler Response:

HTTP/1.1 200 OK Cache-Control: private Content-Type: application/json; charset=utf-8 Vary: Accept-Encoding Server: Microsoft-IIS/8.5 X-SharePointHealthScore: 0 X-SP-SERVERSTATE: ReadOnly=0 SPClientServiceRequestDuration: 7513 X-AspNet-Version: 4.0.30319 SPRequestGuid: 7e19049d-601e-2000-008d-b31e125c7e26 request-id: 7e19049d-601e-2000-008d-b31e125c7e26 X-RequestDigest: 0x1B109C2C5737406AB9E9A2983D743443F86CEF7D92CD6041BB1510FCDD2A4866A55C5BF0D32E4E55C4448C12C9727F191740AAF929E6353320C1CAE0FBBC1D16,07 May 2015 17:27:33 -0000 X-FRAME-OPTIONS: SAMEORIGIN X-Powered-By: ASP.NET MicrosoftSharePointTeamServices: X-Content-Type-Options: nosniff X-MS-InvokeApp: 1; RequireReadOnly P3P: CP="ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR SAMo CNT COM INT NAV ONL PHY PRE PUR UNI" Date: Thu, 07 May 2015 17:27:40 GMT Content-Length: 574  [ { "SchemaVersion":"","LibraryVersion":"16.0.4021.1200","ErrorInfo":{ "ErrorMessage":"Provisioning did not succeed. Details: Failed to initialize some site properties for Web at Url: 'https:\u002f\u002fslalomdev123.sharepoint.com\u002fsites\u002fPaulDev\u002fcompany\u002fACS\u002fmanuals' OriginalException: The request uses too many resources.","ErrorValue":null,"TraceCorrelationId":"7e19049d-601e-2000-008d-b31e125c7e26","ErrorCode":-2146232832,"ErrorTypeName":"Microsoft.SharePoint.SPException" },"TraceCorrelationId":"7e19049d-601e-2000-008d-b31e125c7e26" } ] 

Update editor of published version without affecting version number – CSOM

I am trying to copy files from one site collection to another including their version history and preserve the metadata using CSOM. I am almost there using the below logic for each version of the file. However I am not able to get this to work for major/published/X.0 versions.

1) Check out existing file (If not first version uploaded)

2) Upload the file version

3) Assign the document metadata and perform a checkin (either major or minor to match original files version history).

4) Use ValidateUpdateListItem to set the Editor and Modified values as they were overwritten by the checkin in step 3

This works in most scenarios and keeps the modified date. However if the version was a published version and minor versions are enabled this creates a new X.1 version.

Does anyone have a way of updating the Editor for a published version with minor versions enabled on the list that does not affect the version number? The only solutions I have found require server side code or temporarily disabling versioning which I cannot do!


CSOM only – this is client side C# code.

I cannot temporarily enable/disable versioning or minor versions on the library.

How to get All Users in User Profile Services Sharepoint 2013 Using CSOM

I need some function like bellow on CSOM. could you help me ?

if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $  null) {      Add-PSSnapin "Microsoft.SharePoint.PowerShell"  }   $  site = new-object Microsoft.SharePoint.SPSite("<<WebApplicationSiteUrl>>");   $  ServiceContext = [Microsoft.SharePoint.SPServiceContext]::GetContext($  site);    $  ProfileManager = new-object Microsoft.Office.Server.UserProfiles.UserProfileManager($  ServiceContext)     $  AllProfiles = $  ProfileManager.GetEnumerator()    foreach($  profile in $  AllProfiles)   {       $  DisplayName = $  profile.DisplayName       $  AccountName = $  profile[[Microsoft.Office.Server.UserProfiles.PropertyConstants]::AccountName].Value       write-host "Profile for account ", $  AccountName }   write-host "Finished."  $  site.Dispose() 

CSOM: How to know if a Web has completed its creation?

I have a service that creates a Sharepoint Online site using CSOM.

context.Web.Webs.Add(webCreationInformation); context.ExecuteQuery(); 

This site is created using a defined Template stored in the solutions of the Site Collection. However, the creation of the site can take its time: from 5 minutes to 20 minutes for the site to be ready (all lists created, all views, etc.) Since my ExecuteQuery always returns at 5 minutes (generally with a 503 error) it is impossible for me to know when the site has finished the creation process.

Is there a way to know when the site is available?

I have tried loading the Web object, and even if its not ready, I can load it without problems:

Web sourceWeb = context.Site.OpenWeb(webRelativeUrl); context.Load(sourceWeb); context.ExecuteQuery();  //this returns the Web even if the site has not finished the creation process 

I would like to have something like:

While(!web.IsReady) {   Thread.Sleep(60000); //60 seconds   context.Load(web, w => w.IsReady);   context.ExecuteQuery(); } 

However, I can’t seem to find any flag or value that can help me for this.

Thank you.

CSOM: Intermittent Tenant Errors “Exception has been thrown by the target of an invocation.”

We have been seeing intermittent “Exception has been thrown by the target of an invocation.” when querying the tenant this week.

This occurs when either creating a new site via the tenant, or trying to obtain site properties via the tenant using CSOM. The command works one minute, then stops working the next, and fluctuates between working and not working.

Has anyone else been experiencing these issues?

An example of one of the commands which intermittently fails:

SPOSitePropertiesEnumerableFilter filter = new SPOSitePropertiesEnumerableFilter() {     IncludeDetail = true }; var props = tenant.GetSitePropertiesFromSharePointByFilters(filter); tenant.Context.Load(props, p => p.NextStartIndexFromSharePoint); tenant.Context.ExecuteQuery(); 

CSOM get subsites times out

I’m trying to fetch all subsites (just those at the root level, not sub-subsites, etc.). But, I suspect due to volume (4,000+ subsites), the following times out.

clientContext.Load(     clientContext.Web.Webs,     w => w.Include(s => s.Url),     w => w.Include(s => s.RoleAssignments)); await clientContext.ExecuteQueryAsync(); 

I’ve tried increasing the timeout by setting clientContext.RequestTimeout = 600000;, but then instead of timing out, the query eventually results in error: The remote server returned an error: (503) Server Unavailable.

Is there some way I can paginate the results, or another way I can fetch a list of subsites that won’t result in a timeout?

HasPublishedVersion property using CSOM C#

I am using SharePoint C# CSOM to get items from the SharePoint 2010 site Document Library.

I need to check if the item has any published version. In SSOM we have to Property called HasPublishedVersion to check for the SPListItem.

Is there any similar column that I can use in CSOM c#? or is there any way I can check for published version in CSOM C#?