getEnumerator causing collection has not been initialized error inside of async call inside of a loop in a script editor web part

This is an issue I’ve been struggling with – What I am doing is using a script editor web part and when a user clicks the button, I check to see if a list exists inside of a loop (in this example, it could be called Data1 – Data10) and if so, then I want to pull all of the items from that list based on the query, which is based on filters with other controls (Ignore the datepickers/filters – I know the query works)

The problem I’m hitting is that I’m running these async calls inside of my ‘does the list exist’ loop and getting to the getEnumerator line where I receive the error :

Error: The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.

I had previously posted a simplified version of this question and didn’t receive a response so was hoping if I posted the entirety of my solution that it may give me an answer.

Thanks

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js "></script>     <link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">     <script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>     <script type="text/javascript" language="javascript">      $  (function() {         $  ( "#datepickerStart" ).datepicker();         $  ( "#datepickerEnd" ).datepicker();     });      var valStopped = 10;     var allItems;     function getListData()      {         var _clientContext;         var _web;         _clientContext = new SP.ClientContext.get_current();         _web = _clientContext.get_web();         var lists = _web.get_lists();         _clientContext.load(lists,'Include(Title)');         //Get all lists...         var listTitle = "";         var arrayOfMatchedLists = [];         var responses = {exists:false,record:0};         var arrayOfPromises = [];          for (var j = 1; j < valStopped; j++) //loop through all potential lists and see if they exist         {             listTitle = "Data" + j;             arrayOfPromises.push(get_isListExists(listTitle,j,function(listExists,counter){             if (listExists){                 responses = {exists:listExists,record:counter};                 arrayOfMatchedLists.push(responses);             }             },function(sender,args){}));         }         $  .when.apply($  , arrayOfPromises).done(function() {         var largest = 0;         for (var item in arrayOfMatchedLists)          {         //Get the largest list index             if (arrayOfMatchedLists[item].record > largest)             {                 largest = arrayOfMatchedLists[item].record;             }         }         populateList(largest);             });      }       function populateList(counter)      {      for (var i = 1; i <= counter; i++)         {              var _clientContext;             var _web;             _clientContext = new SP.ClientContext.get_current();             _web = _clientContext.get_web();             var listTitle = "Data" + i; //+ i;             var list = _web.get_lists().getByTitle(listTitle);             var myquery = new SP.CamlQuery();             if ($  ("Data6").val() !== "All") //get Data6 as a filter if it's not all, else don't use Data6 as a filter.             {                 myquery.set_viewXml('<View><ViewFields><FieldRef Name=\'Data1\'/><FieldRef Name=\'Data2\'/><FieldRef Name=\'Data3\'/><FieldRef Name=\'Data4\'/><FieldRef Name=\'Data5\'/><FieldRef Name=\'Data6\'/><FieldRef Name=\'Data7\'/><FieldRef Name=\'Data8\'/><FieldRef Name=\'Data9\'/><FieldRef Name=\'Data10\'/></ViewFields></View>');             }             //else set query as all facilities             allItems = list.getItems(myquery);              _clientContext.load(allItems, 'Include(Data1,Data2,Data3,Data4,Data5,Data6,Data7,Data8,Data9,Data10)');             _clientContext.executeQuery(Function.createDelegate(this, this.onQuerySucceeded()), Function.createDelegate(this, this.onQueryFailed));         }                }      function onQuerySucceeded()      {         var Data1 = null;         var Data2 = null;         var Data3 = null;         var Data4 = null;         var Data5 = null;         var Data6 = null;         var Data7 = null;         var Data8 = null;         var Data9 = null;         var Data10 = null;         var txtHTML = "";          console.log("before enum");         var listEnumerator = allItems.getEnumerator();         console.log("get enumerator");             while (listEnumerator.moveNext()) {                     console.log("before got current");                     var currentItem = listEnumerator.get_current();                     console.log("got current");                     Data1 = currentItem.get_item('Data1');                     Data2 = currentItem.get_item('Data2');                     Data3 = currentItem.get_item('Data3');                     Data4 = currentItem.get_item('Data4');                     Data5 = currentItem.get_item('Data5');                     Data6 = currentItem.get_item('Data6');                     Data7 = currentItem.get_item('Data7');                     Data8 = currentItem.get_item('Data8');                     Data9 = currentItem.get_item('Data9');                     Data10 = currentItem.get_item('Data10');                     var row = document.createElement("tr");                      txtHTML = txtHTML + "<tr>";                     txtHTML = txtHTML + "<td>";                     if (Data1 != null) {                         txtHTML = txtHTML + "<p>" + Data1 + "</p>";                     }                     txtHTML = txtHTML + "</td>";                      txtHTML = txtHTML + "<td>";                     if (Data2 != null) {                         txtHTML = txtHTML + "<p>" + Data2 + "</p>";                     }                     txtHTML = txtHTML + "</td>";                      txtHTML = txtHTML + "<td>";                     if (Data3 != null) {                         txtHTML = txtHTML + "<p>" + Data3 + "</p>";                     }                     txtHTML = txtHTML + "</td>";                      txtHTML = txtHTML + "<td>";                     if (Data4 != null) {                         txtHTML = txtHTML + "<p>" + Data4 + "</p>";                     }                     txtHTML = txtHTML + "</td>";                                                      txtHTML = txtHTML + "<td>";                     if (Data5 != null) {                         txtHTML = txtHTML + "<p>" + Data5 + "</p>";                     }                     txtHTML = txtHTML + "<td>";                     if (Data6 != null) {                         txtHTML = txtHTML + "<p>" + Data6 + "</p>";                     }                     txtHTML = txtHTML + "</td>";                         txtHTML = txtHTML + "<td>";                     if (Data7 != null) {                         txtHTML = txtHTML + "<p>" + Data7 + "</p>";                     }                     txtHTML = txtHTML + "</td>";                         txtHTML = txtHTML + "<td>";                     if (Data8 != null) {                         txtHTML = txtHTML + "<p>" + Data8 + "</p>";                     }                     txtHTML = txtHTML + "</td>";                         txtHTML = txtHTML + "<td>";                     if (Data9 != null) {                         txtHTML = txtHTML + "<p>" + Data9 + "</p>";                     }                     txtHTML = txtHTML + "</td>";                         txtHTML = txtHTML + "<td>";                     if (Data10 != null) {                         txtHTML = txtHTML + "<p>" + Data10 + "</p>";                     }                     txtHTML = txtHTML + "</td>";                         txtHTML = txtHTML + "</tr>";             }             console.log("ran");         $  ("#tblCustomListData").append(txtHTML);     }      function onQueryFailed(sender, args)      {         alert("failed Message" + args.get_message());     }      function get_isListExists(listTitle, counter, OnSuccess, OnError){          var ctx = SP.ClientContext.get_current();         var web = ctx.get_web();         var lists = web.get_lists();         ctx.load(lists);          var outValue = $  .Deferred();         ctx.executeQueryAsync(           function() {           if (counter <= valStopped){             var listExists = false;               var le = lists.getEnumerator();             while (le.moveNext()) {                     var list = le.get_current();                     if(list.get_title() == listTitle) {                         listExists = true;                         break;                     }                 }                 }            outValue.resolve();           OnSuccess(listExists,counter);           OnError();             });         return outValue.promise();     }  </script>        <p> Data6: <select id="Data6">       <option value="Op1">Op1</option>       <option value="Op2">Op2</option>       <option value="Op3">Op3</option>       <option value="Op4">Op4</option>       <option value="Op5">Op5</option>       <option value="Op6">Op6</option>     </select> </p>     <p>Start Date: <input type="text" id="datepickerStart">     End Date: <input type="text" id="datepickerEnd"></p>     <center><button ID="retrieveList" onclick="ExecuteOrDelayUntilScriptLoaded(getListData(), 'sp.js');return false">Retrieve List</button></center></br>     <table id="tblCustomListData" border="1">         <thead>             <tr>                 <th>Data1                 </th>                 <th>Data2                 </th>                 <th>Data3                 </th>                 <th>Data4                 </th>                 <th>Data5                 </th>                 <th>Data6                 </th>                 <th>Data7                 </th>                 <th>Data8                 </th>                 <th>Data9                 </th>                 <th>Data10                 </th>                                    </tr>         </thead>     </table> 

Creating Site Collection – Access Denied

I am remotelly installing SP 2013 via AutoSPInstaller and I am having trouble during script while its try to create site collection.

 -------------------------------------------------------------- --------------------------------------------------------------  - Creating web applications...  - Web app "Portal" already provisioned.  - Setting up managed paths for "http://portal.asd.local:80"   - Setting up explicit managed path "help" at "http://portal.asd.local:80" and HNSCs...  - Done setting up managed paths at "http://portal.asd.local:80" --------------------------------------------------------------  - Applying object cache accounts to "http://portal.asd.local:80"...  - Done applying object cache accounts to "http://portal.asd.local:80"  - Checking for Site Collection "http://portal.asd.local"...  - Creating Site Collection "http://portal.asd.local"... --------------------------------------------------------------  - Script halted!   Exception             : System.UnauthorizedAccessException:                         0x80070005Access denied.                            at Microsoft.SharePoint.SPGlobal.HandleUnauthorizedAccessException(UnauthorizedAccessExceptio                         n ex)                            v Microsoft.SharePoint.Library.SPRequest.CreateSite(Guid gApplicationId, String bstrUrl, Int                         32 lZone, Guid gSiteId, Guid gDatabaseId, String bstrDatabaseServer, String bstrDatabaseName, S                         tring bstrDatabaseUsername, String bstrDatabasePassword, String bstrTitle, String bstrDescripti                         on, UInt32 nLCID, String bstrOwnerLogin, String bstrOwnerUserKey, String bstrOwnerName, String                         bstrOwnerEmail, String bstrSecondaryContactLogin, String bstrSecondaryContactUserKey, String bs                         trSecondaryContactName, String bstrSecondaryContactEmail, Boolean bADAccountMode, Boolean bHost                         HeaderIsSiteName, Int32 iDatabaseVersionMajor, Int32 iDatabaseVersionMinor, Int32 iDatabaseVers                         ionBuild, Int32 iDatabaseVersionRevision, String bstrSiteSchemaVersion)                            v Microsoft.SharePoint.Administration.SPSiteCollection.Add(SPContentDatabase database, SPSit                         eSubscription siteSubscription, String siteUrl, String title, String description, UInt32 nLCID,                          Int32 compatibilityLevel, String webTemplate, String ownerLogin, String ownerName, String owne                         rEmail, String secondaryContactLogin, String secondaryContactName, String secondaryContactEmail                         , String quotaTemplate, String sscRootWebUrl, Boolean useHostHeaderAsSiteName, Boolean override                         CompatibilityRestriction)                            v Microsoft.SharePoint.PowerShell.SPCmdletNewSite.CreateDataObject()                            v Microsoft.SharePoint.PowerShell.SPNewCmdletBase`1.InternalProcessRecord()                            v Microsoft.SharePoint.PowerShell.SPCmdlet.ProcessRecord() TargetObject          : Microsoft.SharePoint.PowerShell.SPCmdletNewSite CategoryInfo          : InvalidData: (Microsoft.Share...SPCmdletNewSite:SPCmdletNewSite) [New-SPSite], UnauthorizedAcce                         ssException FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletNewSite ErrorDetails          : InvocationInfo        : System.Management.Automation.InvocationInfo ScriptStackTrace      : at CreateWebApp, C:\Install\AutoSPInstaller\AutoSPInstaller\AutoSPInstallerFunctions.ps1: line                         2790                         at CreateWebApplications, C:\Install\AutoSPInstaller\AutoSPInstaller\AutoSPInstallerFunctions.p                         s1: line 2575                         at Setup-Farm, C:\Install\AutoSPInstaller\AutoSPInstaller\AutoSPInstallerMain.ps1: line 209                         at , C:\Install\AutoSPInstaller\AutoSPInstaller\AutoSPInstallerMain.ps1: line 408                         at , : line 1 PipelineIterationInfo : {} PSMessageDetails      :    ----------------------------------- | Automated SP2013 install script | | Started on: 11. 9. 2015 17:49:13 | | Aborted:    11. 9. 2015 17:50:48 | ----------------------------------- 

I have tried a lot of things

  1. Try to running SharePoint Product Configuration Wizard manually to see if it stabilizes my farm, then try run the script again
  2. Manually set user policy to SuperUser and SuperReader in SP Central Adminsitration to my site collection (as said link on line 2790 in AutoSPInstallerFunctions.ps1 – see Error msg)
  3. checked (System cryptography: FIPS)
  4. Added all avaible DB users all permission (just for control) not working
  5. Set the pool identity from SP_AppPool to Network Service + add SP_Farm into “Log on as a service” and “Log on as a batch” in Local Secuirty Policy
  6. Delete all database, users, web aplications, disconnect the farm via SP Product config wizard and try to run it all over again

None of these working

Is is possible that this problem is due to remote install? because i am getting out of relevant google page to search.

Thank you in advance

/////EDIT////// Source code from AutoSPinstaller that creating it ( @Waqas Sarwar MCSE )

 # =================================================================================== # Func: CreateWebApp # Desc: Create the web application # =================================================================================== Function CreateWebApp([System.Xml.XmlElement]$  webApp) {     Get-MajorVersionNumber $  xmlinput     # Look for a managed account that matches the web app type, e.g. "Portal" or "MySiteHost"     $  webAppPoolAccount = Get-SPManagedAccountXML $  xmlinput $  webApp.Type     # If no managed account is found matching the web app type, just use the Portal managed account     if (!$  webAppPoolAccount)     {         $  webAppPoolAccount = Get-SPManagedAccountXML $  xmlinput -CommonName "Portal"         if ([string]::IsNullOrEmpty($  webAppPoolAccount.username)) {throw " - `"Portal`" managed account not found! Check your XML."}     }     $  webAppName = $  webApp.name     $  appPool = $  webApp.applicationPool     $  dbPrefix = Get-DBPrefix $  xmlinput     $  database = $  dbPrefix+$  webApp.Database.Name     $  dbServer = $  webApp.Database.DBServer     # Check for an existing App Pool     $  existingWebApp = Get-SPWebApplication | Where-Object { ($  _.ApplicationPool).Name -eq $  appPool }     $  appPoolExists = ($  existingWebApp -ne $  null)     # If we haven't specified a DB Server then just use the default used by the Farm     If ([string]::IsNullOrEmpty($  dbServer))     {         $  dbServer = $  xmlinput.Configuration.Farm.Database.DBServer     }     $  url = $  webApp.url     $  port = $  webApp.port     $  useSSL = $  false     $  installedOfficeServerLanguages = (Get-Item "HKLM:\Software\Microsoft\Office Server$  env:spVer.0\InstalledLanguages").GetValueNames() | ? {$  _ -ne ""}     # Strip out any protocol value     If ($  url -like "https://*") {$  useSSL = $  true}     $  hostHeader = $  url -replace "http://","" -replace "https://",""     if (((Get-WmiObject Win32_OperatingSystem).Version -like "6.2*" -or (Get-WmiObject Win32_OperatingSystem).Version -like "6.3*") -and ($  env:spVer -eq "14"))     {         Write-Host -ForegroundColor White " - Skipping setting the web app directory path name (not currently working on Windows 2012 w/SP2010)..."         $  pathSwitch = @{}     }     else     {         # Set the directory path for the web app to something a bit more friendly         ImportWebAdministration         # Get the default root location for web apps         $  iisWebDir = (Get-ItemProperty "IIS:\Sites\Default Web Site\" -name physicalPath -ErrorAction SilentlyContinue) -replace ("%SystemDrive%","$  env:SystemDrive")         if (!([string]::IsNullOrEmpty($  iisWebDir)))         {             $  pathSwitch = @{Path = "$  iisWebDir\wss\VirtualDirectories$  webAppName-$  port"}         }         else {$  pathSwitch = @{}}     }     # Only set $  hostHeaderSwitch to blank if the UseHostHeader value exists has explicitly been set to false     if (!([string]::IsNullOrEmpty($  webApp.UseHostHeader)) -and $  webApp.UseHostHeader -eq $  false)     {         $  hostHeaderSwitch = @{}     }     else {$  hostHeaderSwitch = @{HostHeader = $  hostHeader}}     if (!([string]::IsNullOrEmpty($  webApp.useClaims)) -and $  webApp.useClaims -eq $  false)     {         # Create the web app using Classic mode authentication         $  authProviderSwitch = @{}     }     else # Configure new web app to use Claims-based authentication     {         If ($  ($  webApp.useBasicAuthentication) -eq $  true)         {             $  authProvider = New-SPAuthenticationProvider -UseWindowsIntegratedAuthentication -UseBasicAuthentication         }         Else         {             $  authProvider = New-SPAuthenticationProvider -UseWindowsIntegratedAuthentication         }         $  authProviderSwitch = @{AuthenticationProvider = $  authProvider}         If ((Gwmi Win32_OperatingSystem).Version -like "6.0*") # If we are running Win2008 (non-R2), we may need the claims hotfix         {             [bool]$  claimsHotfixRequired = $  true             Write-Host -ForegroundColor Yellow " - Web Applications using Claims authentication require an update"             Write-Host -ForegroundColor Yellow " - Apply the http://go.microsoft.com/fwlink/?LinkID=184705 update after setup."         }     }     if ($  appPoolExists)     {         $  appPoolAccountSwitch = @{}     }     else     {         $  appPoolAccountSwitch = @{ApplicationPoolAccount = $  ($  webAppPoolAccount.username)}     }     $  getSPWebApplication = Get-SPWebApplication | Where-Object {$  _.DisplayName -eq $  webAppName}     If ($  getSPWebApplication -eq $  null)     {         Write-Host -ForegroundColor White " - Creating Web App `"$  webAppName`""         New-SPWebApplication -Name $  webAppName -ApplicationPool $  appPool -DatabaseServer $  dbServer -DatabaseName $  database -Url $  url -Port $  port -SecureSocketsLayer:$  useSSL @hostHeaderSwitch @appPoolAccountSwitch @authProviderSwitch @pathSwitch | Out-Null         If (-not $  ?) { Throw " - Failed to create web application" }     }     Else {Write-Host -ForegroundColor White " - Web app `"$  webAppName`" already provisioned."}     SetupManagedPaths $  webApp     If ($  useSSL)     {         $  SSLHostHeader = $  hostHeader         $  SSLPort = $  port         $  SSLSiteName = $  webAppName         if (((Get-WmiObject Win32_OperatingSystem).Version -like "6.2*" -or (Get-WmiObject Win32_OperatingSystem).Version -like "6.3*") -and ($  env:spVer -eq "14"))         {             Write-Host -ForegroundColor White " - Assigning certificate(s) in a separate PowerShell window..."             Start-Process -FilePath "$  PSHOME\powershell.exe" -Verb RunAs -ArgumentList "-Command `". $  env:dp0\AutoSPInstallerFunctions.ps1`; AssignCert $  SSLHostHeader $  SSLPort $  SSLSiteName; Start-Sleep 10`"" -Wait         }         else {AssignCert $  SSLHostHeader $  SSLPort $  SSLSiteName}     }      # If we are provisioning any Office Web Apps, Visio, Excel, Access or PerformancePoint services, we need to grant the generic app pool account access to the newly-created content database     # Per http://technet.microsoft.com/en-us/library/ff829837.aspx and http://autospinstaller.codeplex.com/workitem/16224 (thanks oceanfly!)     If ((ShouldIProvision $  xmlinput.Configuration.OfficeWebApps.ExcelService -eq $  true) -or `         (ShouldIProvision $  xmlinput.Configuration.OfficeWebApps.PowerPointService -eq $  true) -or `         (ShouldIProvision $  xmlinput.Configuration.OfficeWebApps.WordViewingService -eq $  true) -or `         (ShouldIProvision $  xmlinput.Configuration.EnterpriseServiceApps.VisioService -eq $  true) -or `         (ShouldIProvision $  xmlinput.Configuration.EnterpriseServiceApps.ExcelServices -eq $  true) -or `         (ShouldIProvision $  xmlinput.Configuration.EnterpriseServiceApps.AccessService -eq $  true) -or `         (ShouldIProvision $  xmlinput.Configuration.EnterpriseServiceApps.AccessServices -eq $  true) -or `         (ShouldIProvision $  xmlinput.Configuration.EnterpriseServiceApps.PerformancePointService -eq $  true))     {         $  spservice = Get-SPManagedAccountXML $  xmlinput -CommonName "spservice"         Write-Host -ForegroundColor White " - Granting $  ($  spservice.username) rights to `"$  webAppName`"..." -NoNewline         $  wa = Get-SPWebApplication | Where-Object {$  _.DisplayName -eq $  webAppName}         $  wa.GrantAccessToProcessIdentity("$  ($  spservice.username)")         Write-Host -ForegroundColor White "OK."     }     if ($  webApp.GrantCurrentUserFullControl -eq $  true)     {         $  currentUser = "$  env:USERDOMAIN$  env:USERNAME"         $  wa = Get-SPWebApplication | Where-Object {$  _.DisplayName -eq $  webAppName}         if ($  wa.UseClaimsAuthentication -eq $  true) {$  currentUser = 'i:0#.w|' + $  currentUser}         Set-WebAppUserPolicy $  wa $  currentUser "$  env:USERNAME" "Full Control"     }     WriteLine            ConfigureObjectCache $  webApp      if ($  webApp.SiteCollections.SelectSingleNode("SiteCollection")) # Only go through these steps if we actually have a site collection to create     {         ForEach ($  siteCollection in $  webApp.SiteCollections.SiteCollection)         {             $  dbPrefix = Get-DBPrefix $  xmlinput             $  getSPSiteCollection = $  null             $  siteCollectionName = $  siteCollection.Name             $  siteURL = $  siteCollection.siteURL             $  CompatibilityLevel = $  siteCollection.CompatibilityLevel             if (!([string]::IsNullOrEmpty($  CompatibilityLevel))) # Check the Compatibility Level if it's been specified             {                 $  CompatibilityLevelSwitch = @{CompatibilityLevel = $  CompatibilityLevel}             }             else {$  CompatibilityLevelSwitch = @{}}             if (!([string]::IsNullOrEmpty($  ($  siteCollection.CustomDatabase)))) # Check if we have specified a non-default content database for this site collection             {                 $  siteDatabase = $  dbPrefix+$  siteCollection.CustomDatabase             }             else # Just use the first, default content database for the web application             {                 $  siteDatabase = $  database             }             # If an OwnerAlias has been specified, make it the primary, and the currently logged-in account the secondary. Otherwise, make the app pool account for the web app the primary owner             if (!([string]::IsNullOrEmpty($  ($  siteCollection.Owner))))             {                 $  ownerAlias = $  siteCollection.Owner             }             else             {                 $  ownerAlias = $  webAppPoolAccount.username             }             $  LCID = $  siteCollection.LCID             $  siteCollectionLocale = $  siteCollection.Locale             $  siteCollectionTime24 = $  siteCollection.Time24             # If a template has been pre-specified, use it when creating the Portal site collection; otherwise, leave it blank so we can select one when the portal first loads             $  template = $  siteCollection.template             If (($  template -ne $  null) -and ($  template -ne ""))             {                 $  templateSwitch = @{Template = $  template}             }             else {$  templateSwitch = @{}}             if ($  siteCollection.HostNamedSiteCollection -eq $  true)             {                 $  hostHeaderWebAppSwitch = @{HostHeaderWebApplication = $  ($  webApp.url)+":"+$  ($  webApp.port)}             }             else {$  hostHeaderWebAppSwitch = @{}}             Write-Host -ForegroundColor White " - Checking for Site Collection `"$  siteURL`"..."             $  getSPSiteCollection = Get-SPSite -Limit ALL | Where-Object {$  _.Url -eq $  siteURL}             If (($  getSPSiteCollection -eq $  null) -and ($  siteURL -ne $  null))             {                 # Verify that the Language we're trying to create the site in is currently installed on the server                 $  culture = [System.Globalization.CultureInfo]::GetCultureInfo(([convert]::ToInt32($  LCID)))                 $  cultureDisplayName = $  culture.DisplayName                 If (!($  installedOfficeServerLanguages | Where-Object {$  _ -eq $  culture.Name}))                 {                     Write-Warning "You must install the `"$  culture ($  cultureDisplayName)`" Language Pack before you can create a site using LCID $  LCID"                 }                 Else                 {                     $  siteDatabaseExists = Get-SPContentDatabase -Identity $  siteDatabase -ErrorAction SilentlyContinue                     if (!$  siteDatabaseExists)                     {                         Write-Host -ForegroundColor White " - Creating new content database `"$  siteDatabase`"..."                         New-SPContentDatabase -Name $  siteDatabase -WebApplication (Get-SPWebApplication $  webApp.url) | Out-Null                     }                     Write-Host -ForegroundColor White " - Creating Site Collection `"$  siteURL`"..."                     $  site = New-SPSite -Url $  siteURL -OwnerAlias $  ownerAlias -SecondaryOwner $  env:USERDOMAIN$  env:USERNAME -ContentDatabase $  siteDatabase -Description $  siteCollectionName -Name $  siteCollectionName -Language $  LCID @templateSwitch @hostHeaderWebAppSwitch @CompatibilityLevelSwitch -ErrorAction Stop                      # JDM Not all Web Templates greate the default SharePoint Croups that are made by the UI                     # JDM These lines will insure that the the approproprate SharePoint Groups, Owners, Members, Visitors are created                     $  primaryUser = $  site.RootWeb.EnsureUser($  ownerAlias)                     $  secondaryUser = $  site.RootWeb.EnsureUser("$  env:USERDOMAIN$  env:USERNAME")                     $  title = $  site.RootWeb.title                     Write-Host -ForegroundColor White " - Ensuring default groups are created..."                     $  site.RootWeb.CreateDefaultAssociatedGroups($  primaryUser, $  secondaryUser, $  title)                      # Add the Portal Site Connection to the web app, unless of course the current web app *is* the portal                     # Inspired by http://www.toddklindt.com/blog/Lists/Posts/Post.aspx?ID=264                     $  portalWebApp = $  xmlinput.Configuration.WebApplications.WebApplication | Where {$  _.Type -eq "Portal"} | Select-Object -First 1                     $  portalSiteColl = $  portalWebApp.SiteCollections.SiteCollection | Select-Object -First 1                     If ($  site.URL -ne $  portalSiteColl.siteURL)                     {                         Write-Host -ForegroundColor White " - Setting the Portal Site Connection for `"$  siteCollectionName`"..."                         $  site.PortalName = $  portalSiteColl.Name                         $  site.PortalUrl = $  portalSiteColl.siteUrl                     }                     If ($  siteCollectionLocale)                     {                         Write-Host -ForegroundColor White " - Updating the locale for `"$  siteCollectionName`" to `"$  siteCollectionLocale`"..."                         $  site.RootWeb.Locale = [System.Globalization.CultureInfo]::CreateSpecificCulture($  siteCollectionLocale)                     }                     If ($  siteCollectionTime24)                     {                         Write-Host -ForegroundColor White " - Updating 24 hour time format for `"$  siteCollectionName`" to `"$  siteCollectionTime24`"..."                         $  site.RootWeb.RegionalSettings.Time24 = $  ([System.Convert]::ToBoolean($  siteCollectionTime24))                     }                     $  site.RootWeb.Update()                 }             }             Else {Write-Host -ForegroundColor White " - Skipping creation of site `"$  siteCollectionName`" - already provisioned."}             if ($  siteCollection.HostNamedSiteCollection -eq $  true)             {                 Add-LocalIntranetURL ($  siteURL)                 # Updated so that we don't add URLs to the local hosts file of a server that's not running the Foundation Web Application service                 if ($  xmlinput.Configuration.WebApplications.AddURLsToHOSTS -eq $  true -and !(($  xmlinput.Configuration.Farm.Services.SelectSingleNode("FoundationWebApplication")) -and !(ShouldIProvision $  xmlinput.Configuration.Farm.Services.FoundationWebApplication -eq $  true)))                 {                     # Add the hostname of this host header-based site collection to the local HOSTS so it's immediately resolvable locally                     # Strip out any protocol and/or port values                     $  hostname,$  null = $  siteURL -replace "http://","" -replace "https://","" -split ":"                     AddToHOSTS $  hostname                 }             }             WriteLine         }     }     else     {         Write-Host -ForegroundColor Yellow " - No site collections specified for $  ($  webapp.url) - skipping."     } }  # =================================================================================== 

Restore site collection in SharePoint online give error

I want to restore a root site collection from recycle bin in SharePoint online it give bellow error:

I tried using SharePoint online management shell bellow command

 Restore-SPODeletedSite -Identity https://TheSiteName.sharepoint.com/ 

I tried using the interface it also did not worked and give bellow error:

Sorry, something went wrong There is no site in the current site subscription matching the HiddenSiteSelection control's value. 

How to handle “Optimistic Locking” on a collection with ETag headers?

Consider endpoint /projects that returns a list of projects with the following headers:

HTTP/1.1 200 OK Etag: "superEtag" 

The etag value represents a hash of the entire collection and it does not allow a client to update a single resource e.g. /projects/1.

Fetching the resources individually makes no sense, so how can I handle optimistic locking with a collection?

Access denied to site collection administrator

I am facing a very strange issue.

I have two web applications. Inside those applications are two site collections each. When I log in as site collection administrator I can access all three site collections except one. When I try to access that particular site in browser I get message:

Sorry, this site hasn’t been shared with you.

This user is added in Site Collection Administrator section of all 4 sites but only 1 site has problem.

I have even added site collection admin in User Policy in CA and gave FULL RIGHTS and FULL READ permissions.

Did iisreset, restart SQL server and SharePoint timer server but no luck. How do I solve this issue?

EDIT

User NT AUTHORITY was missing from user policy of problematic web application (not that it should have any effect because other site collection are working fine in this web application) but still I added this user and noticed that:

In problematic web application it appears as i:0#.w|NT AUTHORITY

While in other web application it appears as NT AUTHORITY

Given a SharePoint site collection URL, how can you determine if it is SharePoint Online or SharePoint On-Prem?

I would like to be able to determine if a SharePoint web application URL is a SharePoint online instance or not.

Previously, I used to think that you could check to see if a sharepoint web application URL had the form https://{tenantname}.sharepoint.com to see if it was a sharepoint online instance URL.

But now I’ve seen Office 365 sharepoint online urls that looks like https://prefix.mycompany.com.

Is there some simple way to check a URL for sharepoint online versus sharepoint on prem?

I’d rather not have to add a “SharePoint Online” checkbox in my UI.

SP 2019 site collection subsites and site settings clicks showing odd errors

I am working with SP on prem 2019. On a web app, I have classic site collection added as root. For some reason, I am seeing odd behavior, see summary below:

  1. Sometimes, upon accessing the root site url, it shows access required or sorry you don’t have access errors.

  2. There are three sub sites created, upon trying to access these sub sites, it shows access required message.

  3. When clicked on site settings for these sub sites, it shows sorry you dont have access error.

  4. When clicked on Navigation under site settings, it says “you dont have access” or 403 forbidden errors.

  5. Even when configuring terms for a term set in term store, for term driven url, when clicking on browse, it shows forbidden again.

I am farm admin, site collection admin and part of site owner group. Also I have a user policy spin up that gives me full control at the web app.

I checked the ULS logs as well, it seems that something is wrong with authentication, see some notes below from ULS logs.

SPFederationAuthenticationModule.IsRedirectToLogOnPage: Detected a redirection but the redirect is not to a known signin page: https://.****.com/SitePages/Home.aspx**

System.UnauthorizedAccessException: Access denied., StackTrace: at Microsoft.SharePoint.SPWeb.GetFileOrFolderProperties(SPResourcePath path, ListDocsFlags listDocsFlags,

Here is he correlation iD i found in log: 7650f89e-c806-1011-5f50-aaf413e759f9

Its driving me nuts, I have not been able to find out the cause.Can someone please assist what could be wrong.

Convert/Change the built-in root site collection into a communication hub site

when we start a new office 365 project, we will have a classic team site created for us at the root https://ourcomapnyname.sharepoint.com/. but now we want to follow the flat structure of sites and star using hub sites. so for this i am not sure what are the appraochies we can follow to :-

  1. convert the current classic team site into a communication site. we need to convert it into a communication site, since this is the template advised (by Microsoft) to be used for hub sites. as we want to set our root site collection to be the parent hub site for our company .

so what are the approaches we can follow? can i simply delete the root site collection, then create a new communication modern site at the root url of our tenant?