public void CreateDeleteCreateSiteCollectionTest()
        {
            using (var tenantContext = TestCommon.CreateTenantClientContext())
            {
                var tenant = new Tenant(tenantContext);

                //Create site collection test
                string siteToCreateUrl = CreateTestSiteCollection(tenant, sitecollectionName);
                var siteExists = tenant.SiteExists(siteToCreateUrl);
                Assert.IsTrue(siteExists, "Site collection creation failed");

                //Delete site collection test: move to recycle bin
                tenant.DeleteSiteCollection(siteToCreateUrl, true);
                bool recycled = tenant.CheckIfSiteExists(siteToCreateUrl, "Recycled");
                Assert.IsTrue(recycled, "Site collection recycling failed");

                //Remove from recycle bin
                tenant.DeleteSiteCollectionFromRecycleBin(siteToCreateUrl, true);
                var siteExists2 = tenant.SiteExists(siteToCreateUrl);
                Assert.IsFalse(siteExists2, "Site collection deletion from recycle bin failed");

                //Create a site collection using the same url as the previously deleted site collection
                siteToCreateUrl = CreateTestSiteCollection(tenant, sitecollectionName);
                siteExists = tenant.SiteExists(siteToCreateUrl);
                Assert.IsTrue(siteExists, "Second site collection creation failed");
            }
        }
        public void CheckIfSiteExistsTest()
        {
            using (var tenantContext = TestCommon.CreateTenantClientContext()) {
                var tenant = new Tenant(tenantContext);
                var siteCollections = tenant.GetSiteCollections();

                var site = siteCollections.First();
                var siteExists1 = tenant.CheckIfSiteExists(site.Url, "Active");
                Assert.IsTrue(siteExists1);

                try {
                    var siteExists2 = tenant.CheckIfSiteExists(site.Url + "sites/aaabbbccc", "Active");
                    Assert.IsFalse(siteExists2, "Invalid site returned as valid.");
                }
                catch (ServerException) { }
            }
        }
        private static void CleanupAllTestSiteCollections(ClientContext tenantContext)
        {
            var tenant = new Tenant(tenantContext);

            var siteCols = tenant.GetSiteCollections();

            foreach (var siteCol in siteCols)
            {
                if (siteCol.Url.Contains(sitecollectionNamePrefix))
                {
                    try
                    {
                        // Drop the site collection from the recycle bin
                        if (tenant.CheckIfSiteExists(siteCol.Url, "Recycled"))
                        {
                            tenant.DeleteSiteCollectionFromRecycleBin(siteCol.Url, false);
                        }
                        else
                        {
                            // Eat the exceptions: would occur if the site collection is already in the recycle bin.
                            try
                            {
                                // ensure the site collection in unlocked state before deleting
                                tenant.SetSiteLockState(siteCol.Url, SiteLockState.Unlock);
                            }
                            catch { }

                            // delete the site collection, do not use the recyle bin
                            tenant.DeleteSiteCollection(siteCol.Url, false);
                        }
                    }
                    catch (Exception ex)
                    {
                        // eat all exceptions
                        Console.WriteLine(ex.ToString());
                    }
                }
            }
        }
        public void CreateDeleteSiteCollectionTest()
        {
            using (var tenantContext = TestCommon.CreateTenantClientContext())
            {
                var tenant = new Tenant(tenantContext);

                //Create site collection test
                string siteToCreateUrl = CreateTestSiteCollection(tenant, sitecollectionName);
                var    siteExists      = tenant.SiteExists(siteToCreateUrl);
                Assert.IsTrue(siteExists, "Site collection creation failed");

                //Delete site collection test: move to recycle bin
                tenant.DeleteSiteCollection(siteToCreateUrl, true);
                bool recycled = tenant.CheckIfSiteExists(siteToCreateUrl, "Recycled");
                Assert.IsTrue(recycled, "Site collection recycling failed");

                //Remove from recycle bin
                tenant.DeleteSiteCollectionFromRecycleBin(siteToCreateUrl, true);
                var siteExists2 = tenant.SiteExists(siteToCreateUrl);
                Assert.IsFalse(siteExists2, "Site collection deletion from recycle bin failed");
            }
        }
Exemple #5
0
        public void CreateDeleteCreateSiteCollectionTest()
        {
            using (var tenantContext = TestCommon.CreateTenantClientContext())
            {
                var tenant = new Tenant(tenantContext);

                //Create site collection test
                Console.WriteLine("CreateDeleteCreateSiteCollectionTest: step 1");
                string siteToCreateUrl = CreateTestSiteCollection(tenant, sitecollectionName);
                Console.WriteLine("CreateDeleteCreateSiteCollectionTest: step 1.1");
                var siteExists = tenant.SiteExists(siteToCreateUrl);
                Console.WriteLine("CreateDeleteCreateSiteCollectionTest: step 1.1");
                Assert.IsTrue(siteExists, "Site collection creation failed");

                //Delete site collection test: move to recycle bin
                Console.WriteLine("CreateDeleteCreateSiteCollectionTest: step 2");
                tenant.DeleteSiteCollection(siteToCreateUrl, true);
                Console.WriteLine("CreateDeleteCreateSiteCollectionTest: step 2.1");
                bool recycled = tenant.CheckIfSiteExists(siteToCreateUrl, "Recycled");
                Console.WriteLine("CreateDeleteCreateSiteCollectionTest: step 2.2");
                Assert.IsTrue(recycled, "Site collection recycling failed");

                //Remove from recycle bin
                Console.WriteLine("CreateDeleteCreateSiteCollectionTest: step 3");
                tenant.DeleteSiteCollectionFromRecycleBin(siteToCreateUrl, true);
                Console.WriteLine("CreateDeleteCreateSiteCollectionTest: step 3.1");
                var siteExists2 = tenant.SiteExists(siteToCreateUrl);
                Console.WriteLine("CreateDeleteCreateSiteCollectionTest: step 3.2");
                Assert.IsFalse(siteExists2, "Site collection deletion from recycle bin failed");

                //Create a site collection using the same url as the previously deleted site collection
                Console.WriteLine("CreateDeleteCreateSiteCollectionTest: step 4");
                siteToCreateUrl = CreateTestSiteCollection(tenant, sitecollectionName);
                Console.WriteLine("CreateDeleteCreateSiteCollectionTest: step 4.1");
                siteExists = tenant.SiteExists(siteToCreateUrl);
                Console.WriteLine("CreateDeleteCreateSiteCollectionTest: step 4.2");
                Assert.IsTrue(siteExists, "Second site collection creation failed");
            }
        }
        private static void CleanupAllTestSiteCollections(ClientContext tenantContext)
        {
            var tenant = new Tenant(tenantContext);

            var siteCols = tenant.GetSiteCollections();

            foreach (var siteCol in siteCols)
            {
                if (siteCol.Url.Contains(sitecollectionNamePrefix))
                {
                    try
                    {
                        // Drop the site collection from the recycle bin
                        if (tenant.CheckIfSiteExists(siteCol.Url, "Recycled"))
                        {
                            tenant.DeleteSiteCollectionFromRecycleBin(siteCol.Url, false);
                        }
                        else
                        {
                            // Eat the exceptions: would occur if the site collection is already in the recycle bin.
                            try
                            {
                                // ensure the site collection in unlocked state before deleting
                                tenant.SetSiteLockState(siteCol.Url, SiteLockState.Unlock);
                            }
                            catch { }

                            // delete the site collection, do not use the recyle bin
                            tenant.DeleteSiteCollection(siteCol.Url, false);
                        }
                    }
                    catch (Exception ex)
                    {
                        // eat all exceptions
                        Console.WriteLine(ex.ToString());
                    }
                }
            }
        }
Exemple #7
0
        public ActionResult SiteStatus(NewSiteProperties props)
        {
            var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);
            var baseUrl   = $"{spContext.SPHostUrl.Scheme}://{spContext.SPHostUrl.Host}";

            // Build the admin URL
            var adminUrl = new Uri(baseUrl.Insert(baseUrl.IndexOf("."), "-admin"));

            // Get the access token
            string accessToken = TokenHelper.GetAppOnlyAccessToken(
                TokenHelper.SharePointPrincipal,
                adminUrl.Authority,
                TokenHelper.GetRealmFromTargetUrl(adminUrl)).AccessToken;

            // Check if the site exists and is "Active" if it does we return the View
            // If it is not "Active" yet, we return the "WaitingOnSite" view with a spinner
            using (var ctx = TokenHelper.GetClientContextWithAccessToken(adminUrl.ToString(), accessToken))
            {
                Tenant tenant = new Tenant(ctx);

                // Checks to see if site is created yet.
                var isSiteAvailable = tenant.CheckIfSiteExists($"{baseUrl}/sites/{props.Url}", "Active");


                if (!isSiteAvailable)
                {
                    // This view uses JavaScript to refresh every 10 seconds to check if the site has been created
                    return(View("WaitingOnSite"));
                }
                else
                {
                    // Convert the URL to Absolute so we can provide a link to the new site collection
                    props.Url = $"{baseUrl}/sites/{props.Url}";
                    return(View(props));
                }
            }
        }
Exemple #8
0
        private void bkWorkerProcess_DoWorkAsync(object sender, DoWorkEventArgs e)
        {
            try
            {
                //
                string siteUrl   = txtSite.Text;
                string userName  = txtUser.Text;
                string password  = txtPassword.Text;
                string whiteList = txtWhiteList.Text;



                (sender as BackgroundWorker).ReportProgress(5, "The configuration process was started");

                //if (siteUrl.Substring(siteUrl.Length - 1) == "/")
                //{
                //    siteUrl = siteUrl.Substring(0, siteUrl.Length - 1);
                //}


                OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();



                using (var clientContext = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteAdminUrl, userName, password))
                {
                    (sender as BackgroundWorker).ReportProgress(10, "Getting access to admin site");

                    Tenant adminSite = new Tenant(clientContext);

                    var siteName = txtSite.Text;



                    Regex pattern = new Regex("[&_,.;:/\"!@$%^+=\\|<>{}#~*? ]");
                    siteName = pattern.Replace(siteName, string.Empty);

                    Microsoft.SharePoint.Client.Site site = null;

                    if (adminSite.CheckIfSiteExists("https://jreckner.sharepoint.com/sites/" + siteName, "Active"))
                    {
                        throw new Exception("The site: " + txtSite.Text + ", already exists. Please choose another name.");
                    }

                    var siteCreationProperties = new SiteCreationProperties();

                    var sitedesign = new OfficeDevPnP.Core.Entities.SiteEntity();

                    string[] owners = { txtUser.Text };
                    (sender as BackgroundWorker).ReportProgress(15, "Creating site collection");
                    //CommunicationSiteCollectionCreationInformation modernteamSiteInfo = new CommunicationSiteCollectionCreationInformation
                    //{
                    //    Description = "",
                    //    Owner = txtUser.Text,
                    //    SiteDesignId = new Guid("6a3f7a23-031b-4072-bf24-4193c14af65f"),
                    //    Title = txtSite.Text,
                    //    Lcid = 1033,
                    //    AllowFileSharingForGuestUsers = false,
                    //    Url = "https://jreckner.sharepoint.com/sites/" + siteName

                    //};

                    TeamSiteCollectionCreationInformation modernteamSiteInfo = new TeamSiteCollectionCreationInformation()
                    {
                        DisplayName = txtSite.Text,
                        //Owners = owners,
                        //Alias = "https://jreckner.sharepoint.com/sites/" + siteName,
                        Alias       = siteName,
                        Lcid        = 1033,
                        IsPublic    = true,
                        Description = ""
                    };


                    var result = Task.Run(async() => { return(await clientContext.CreateSiteAsync(modernteamSiteInfo)); }).Result;


                    siteUrl = result.Url;

                    var properties = adminSite.GetSitePropertiesByUrl(siteUrl, true);

                    clientContext.Load(properties);
                    site = adminSite.GetSiteByUrl(siteUrl);
                    Web web = site.RootWeb;
                    clientContext.Load(web);
                    ListCreationInformation doclist = new ListCreationInformation()
                    {
                        Title        = "Document Library",
                        TemplateType = 101,
                    };
                    web.Lists.Add(doclist);
                    (sender as BackgroundWorker).ReportProgress(20, "Creating Document Library");
                    clientContext.ExecuteQuery();



                    (sender as BackgroundWorker).ReportProgress(30, "Configuring WhiteList");

                    properties.SharingDomainRestrictionMode = SharingDomainRestrictionModes.AllowList;
                    properties.SharingAllowedDomainList     = whiteList;

                    properties.SharingCapability = SharingCapabilities.ExternalUserSharingOnly;
                    properties.Update();
                    clientContext.ExecuteQuery();
                }



                using (var ctx = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
                {
                    (sender as BackgroundWorker).ReportProgress(40, "Copy disclaimer file");
                    callResponseFlow(siteUrl, userName, userName);

                    (sender as BackgroundWorker).ReportProgress(50, "Getting access to site collection");



                    Web web = ctx.Web;
                    ctx.Load(web);

                    ctx.ExecuteQueryRetry();

                    var page2 = ctx.Web.AddClientSidePage("HomePageDisclaimer.aspx", true);
                    page2.AddSection(CanvasSectionTemplate.OneColumn, 5);

                    CanvasSection section = new CanvasSection(page2, CanvasSectionTemplate.OneColumn, page2.Sections.Count + 1);
                    page2.Sections.Add(section);
                    page2.PageTitle  = "Disclaimer";
                    page2.LayoutType = ClientSidePageLayoutType.Home;
                    page2.DisableComments();
                    page2.PromoteAsHomePage();
                    page2.PageHeader.LayoutType = ClientSidePageHeaderLayoutType.NoImage;
                    page2.Save();
                    (sender as BackgroundWorker).ReportProgress(60, "Generating disclaimer Page");

                    // Check if file exists
                    //Microsoft.SharePoint.Client.Folder folder = ctx.Web.GetFolderByServerRelativeUrl(ctx.Web.ServerRelativeUrl + "/" + library);
                    var documentFile = ctx.Web.GetFileByServerRelativeUrl(ctx.Web.ServerRelativeUrl + "/" + library + "/" + fileName);
                    web.Context.Load(documentFile, f => f.Exists); // Only load the Exists property
                    web.Context.ExecuteQuery();
                    if (documentFile.Exists)
                    {
                        Console.WriteLine("File exists!!!!");

                        //}

                        ctx.Load(documentFile);
                        ctx.Load(documentFile, w => w.SiteId);
                        ctx.Load(documentFile, w => w.WebId);
                        ctx.Load(documentFile, w => w.ListId);
                        ctx.Load(documentFile, w => w.UniqueId);
                        ctx.ExecuteQuery();

                        //if (documentFile != null)
                        //{ //si el documento existe
                        var pdfWebPart = page2.InstantiateDefaultWebPart(DefaultClientSideWebParts.DocumentEmbed);
                        var url        = new Uri(ctx.Web.Url + "/" + library + "/" + fileName);

                        pdfWebPart.Properties["siteId"]            = documentFile.SiteId;
                        pdfWebPart.Properties["webId"]             = documentFile.WebId;
                        pdfWebPart.Properties["listId"]            = documentFile.ListId;
                        pdfWebPart.Properties["uniqueId"]          = documentFile.UniqueId;
                        pdfWebPart.Properties["file"]              = url.AbsoluteUri;
                        pdfWebPart.Properties["serverRelativeUrl"] = documentFile.ServerRelativeUrl;
                        pdfWebPart.Properties["wopiurl"]           = String.Format("{0}/_layouts/15/{1}?sourcedoc=%7b{2}%7d&action=interactivepreview", web.Url, "WopiFrame.aspx", documentFile.UniqueId.ToString("D"));
                        pdfWebPart.Properties["startPage"]         = 1;
                        page2.AddControl(pdfWebPart, section.Columns[0]);
                        (sender as BackgroundWorker).ReportProgress(80, "Configuring webpart");
                        page2.Save();
                        page2.Publish();
                    }
                    else
                    {
                        throw (new Exception("We can't not find the disclaimer file, please upload it to the site at Document library as 'Disclaimer.pdf' and apply the configuration again."));
                    }
                }

                (sender as BackgroundWorker).ReportProgress(100, "All configuration was applied correctly!!!");
                //MessageBox.Show("All configuration was applied correctly!!!");
            }
            catch (Exception ex)
            {
                string errormessage = "";
                errormessage = ex.Message;
                if (ex.InnerException != null)
                {
                    errormessage = ex.InnerException.Message;
                }

                (sender as BackgroundWorker).ReportProgress(0, "Error: " + ex.Message);
            }
            finally {
                finishprocess = true;
            }
        }
Exemple #9
0
        /// <summary>
        /// Adds a SiteEntity by launching site collection creation and waits for the creation to finish
        /// </summary>
        /// <param name="tenant">A tenant object pointing to the context of a Tenant Administration site</param>
        /// <param name="properties">Describes the site collection to be created</param>
        /// <param name="removeSiteFromRecycleBin">It true and site is present in recycle bin, it will be removed first from the recycle bin</param>
        /// <param name="wait">If true, processing will halt until the site collection has been created</param>
        /// <returns>Guid of the created site collection and Guid.Empty is the wait parameter is specified as false</returns>
        public static Guid CreateSiteCollection(this Tenant tenant, SiteEntity properties, bool removeFromRecycleBin = false, bool wait = true)
        {
            if (removeFromRecycleBin)
            {
                if (tenant.CheckIfSiteExists(properties.Url, SITE_STATUS_RECYCLED))
                {
                    tenant.DeleteSiteCollectionFromRecycleBin(properties.Url);
                }
            }

            SiteCreationProperties newsite = new SiteCreationProperties();

            newsite.Url                  = properties.Url;
            newsite.Owner                = properties.SiteOwnerLogin;
            newsite.Template             = properties.Template;
            newsite.Title                = properties.Title;
            newsite.StorageMaximumLevel  = properties.StorageMaximumLevel;
            newsite.StorageWarningLevel  = properties.StorageWarningLevel;
            newsite.TimeZoneId           = properties.TimeZoneId;
            newsite.UserCodeMaximumLevel = properties.UserCodeMaximumLevel;
            newsite.UserCodeWarningLevel = properties.UserCodeWarningLevel;
            newsite.Lcid                 = properties.Lcid;

            try
            {
                SpoOperation op = tenant.CreateSite(newsite);
                tenant.Context.Load(tenant);
                tenant.Context.Load(op, i => i.IsComplete, i => i.PollingInterval);
                tenant.Context.ExecuteQuery();

                if (wait)
                {
                    //check if site creation operation is complete
                    while (!op.IsComplete)
                    {
                        System.Threading.Thread.Sleep(op.PollingInterval);
                        op.RefreshLoad();
                        if (!op.IsComplete)
                        {
                            try
                            {
                                tenant.Context.ExecuteQuery();
                            }
                            catch (WebException webEx)
                            {
                                // Context connection gets closed after action completed.
                                // Calling ExecuteQuery again returns an error which can be ignored
                                LoggingUtility.Internal.TraceWarning((int)EventId.ClosedContextWarning, webEx, CoreResources.TenantExtensions_ClosedContextWarning);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // Eat the siteSubscription exception to make the same code work for MT as on-prem April 2014 CU+
                if (ex.Message.IndexOf("Parameter name: siteSubscription") == -1)
                {
                    throw;
                }
            }

            // Get site guid and return. If we create the site asynchronously, return an empty guid as we cannot retrieve the site by URL yet.
            Guid siteGuid = Guid.Empty;

            if (wait)
            {
                siteGuid = tenant.GetSiteGuidByUrl(new Uri(properties.Url));
            }
            return(siteGuid);
        }
Exemple #10
0
        /// <summary>
        /// Adds a SiteEntity by launching site collection creation and waits for the creation to finish
        /// </summary>
        /// <param name="tenant">A tenant object pointing to the context of a Tenant Administration site</param>
        /// <param name="properties">Describes the site collection to be created</param>
        /// <param name="removeFromRecycleBin">It true and site is present in recycle bin, it will be removed first from the recycle bin</param>
        /// <param name="wait">If true, processing will halt until the site collection has been created</param>
        /// <param name="timeoutFunction">An optional function that will be called while waiting for the site to be created. If set will override the wait variable. Return true to cancel the wait loop.</param>
        /// <returns>Guid of the created site collection and Guid.Empty is the wait parameter is specified as false. Returns Guid.Empty if the wait is cancelled.</returns>
        public static Guid CreateSiteCollection(this Tenant tenant, SiteEntity properties, bool removeFromRecycleBin = false, bool wait = true, Func <TenantOperationMessage, bool> timeoutFunction = null)
        {
            if (removeFromRecycleBin)
            {
                if (tenant.CheckIfSiteExists(properties.Url, SITE_STATUS_RECYCLED))
                {
                    tenant.DeleteSiteCollectionFromRecycleBin(properties.Url);
                }
            }

            SiteCreationProperties newsite = new SiteCreationProperties();

            newsite.Url                  = properties.Url;
            newsite.Owner                = properties.SiteOwnerLogin;
            newsite.Template             = properties.Template;
            newsite.Title                = properties.Title;
            newsite.StorageMaximumLevel  = properties.StorageMaximumLevel;
            newsite.StorageWarningLevel  = properties.StorageWarningLevel;
            newsite.TimeZoneId           = properties.TimeZoneId;
            newsite.UserCodeMaximumLevel = properties.UserCodeMaximumLevel;
            newsite.UserCodeWarningLevel = properties.UserCodeWarningLevel;
            newsite.Lcid                 = properties.Lcid;

            SpoOperation op = tenant.CreateSite(newsite);

            tenant.Context.Load(tenant);
            tenant.Context.Load(op, i => i.IsComplete, i => i.PollingInterval);
            tenant.Context.ExecuteQueryRetry();

            // Get site guid and return. If we create the site asynchronously, return an empty guid as we cannot retrieve the site by URL yet.
            Guid siteGuid = Guid.Empty;

            if (timeoutFunction != null)
            {
                wait = true;
            }
            if (wait)
            {
                // Let's poll for site collection creation completion
                if (WaitForIsComplete(tenant, op, timeoutFunction, TenantOperationMessage.CreatingSiteCollection))
                {
                    // Restore of original flow to validate correct working in edog after fix got committed
                    if (properties.Url.ToLower().Contains("spoppe.com"))
                    {
                        siteGuid = tenant.GetSiteGuidByUrl(new Uri(properties.Url));
                    }
                    else
                    {
                        // Return site guid of created site collection
                        try
                        {
                            siteGuid = tenant.GetSiteGuidByUrl(new Uri(properties.Url));
                        }
                        catch (Exception ex)
                        {
                            // Eat all exceptions cause there's currently (December 16) an issue in the service that can make tenant API calls fail in combination with app-only usage
                            Log.Error("Temp eating exception due to issue in service (December 2016). Exception is {0}.",
                                      ex.ToDetailedString());
                        }
                    }
                }
            }
            return(siteGuid);
        }
Exemple #11
0
 public static bool CheckIfSiteExistsInTenant(this Web web, string siteUrl, string status)
 {
     Tenant tenant = new Tenant(web.Context);
     return tenant.CheckIfSiteExists(siteUrl, status);
 }
        public static bool CheckIfSiteExistsInTenant(this Web web, string siteUrl, string status)
        {
            Tenant tenant = new Tenant(web.Context);

            return(tenant.CheckIfSiteExists(siteUrl, status));
        }
        public void CreateDeleteSiteCollectionTest()
        {
            using (var tenantContext = TestCommon.CreateTenantClientContext())
            {
                var tenant = new Tenant(tenantContext);

                //Create site collection test
                Console.WriteLine("CreateDeleteSiteCollectionTest: step 1");
                string siteToCreateUrl = CreateTestSiteCollection(tenant, sitecollectionName);
                Console.WriteLine("CreateDeleteSiteCollectionTest: step 1.1");
                var siteExists = tenant.SiteExists(siteToCreateUrl);
                Console.WriteLine("CreateDeleteSiteCollectionTest: step 1.2");
                Assert.IsTrue(siteExists, "Site collection creation failed");

                //Delete site collection test: move to recycle bin
                Console.WriteLine("CreateDeleteSiteCollectionTest: step 2");
                tenant.DeleteSiteCollection(siteToCreateUrl, true);
                Console.WriteLine("CreateDeleteSiteCollectionTest: step 2.1");
                bool recycled = tenant.CheckIfSiteExists(siteToCreateUrl, "Recycled");
                Console.WriteLine("CreateDeleteSiteCollectionTest: step 2.2");
                Assert.IsTrue(recycled, "Site collection recycling failed");

                //Remove from recycle bin
                Console.WriteLine("CreateDeleteSiteCollectionTest: step 3");
                tenant.DeleteSiteCollectionFromRecycleBin(siteToCreateUrl, true);
                Console.WriteLine("CreateDeleteSiteCollectionTest: step 3.1");
                var siteExists2 = tenant.SiteExists(siteToCreateUrl);
                Console.WriteLine("CreateDeleteSiteCollectionTest: step 3.2");
                Assert.IsFalse(siteExists2, "Site collection deletion from recycle bin failed");
            }
        }
        private async static Task CreateInfrastructuralSiteCollectionAsync(SetupInformation info)
        {
            Uri infrastructureSiteUri = new Uri(info.InfrastructuralSiteUrl);
            Uri tenantAdminUri        = new Uri(infrastructureSiteUri.Scheme + "://" +
                                                infrastructureSiteUri.Host.Replace(".sharepoint.com", "-admin.sharepoint.com"));
            Uri sharepointUri = new Uri(infrastructureSiteUri.Scheme + "://" +
                                        infrastructureSiteUri.Host + "/");
            var siteUrl           = info.InfrastructuralSiteUrl.Substring(info.InfrastructuralSiteUrl.IndexOf("sharepoint.com/") + 14);
            var siteCreated       = false;
            var siteAlreadyExists = false;

            var accessToken = await AzureManagementUtility.GetAccessTokenSilentAsync(
                tenantAdminUri.ToString(), ConfigurationManager.AppSettings["O365:ClientId"]);

            AuthenticationManager am = new AuthenticationManager();

            using (var adminContext = am.GetAzureADAccessTokenAuthenticatedContext(
                       tenantAdminUri.ToString(), accessToken))
            {
                adminContext.RequestTimeout = Timeout.Infinite;

                var tenant = new Tenant(adminContext);

                // Check if the site already exists, and eventually removes it from the Recycle Bin
                if (tenant.CheckIfSiteExists(info.InfrastructuralSiteUrl, "Recycled"))
                {
                    tenant.DeleteSiteCollectionFromRecycleBin(info.InfrastructuralSiteUrl);
                }

                siteAlreadyExists = tenant.SiteExists(info.InfrastructuralSiteUrl);
                if (!siteAlreadyExists)
                {
                    // Configure the Site Collection properties
                    SiteEntity newSite = new SiteEntity();
                    newSite.Description          = "PnP Partner Pack - Infrastructural Site Collection";
                    newSite.Lcid                 = (uint)info.InfrastructuralSiteLCID;
                    newSite.Title                = newSite.Description;
                    newSite.Url                  = info.InfrastructuralSiteUrl;
                    newSite.SiteOwnerLogin       = info.InfrastructuralSitePrimaryAdmin;
                    newSite.StorageMaximumLevel  = 1000;
                    newSite.StorageWarningLevel  = 900;
                    newSite.Template             = "STS#0";
                    newSite.TimeZoneId           = info.InfrastructuralSiteTimeZone;
                    newSite.UserCodeMaximumLevel = 0;
                    newSite.UserCodeWarningLevel = 0;

                    // Create the Site Collection and wait for its creation (we're asynchronous)
                    tenant.CreateSiteCollection(newSite, true, true, (top) =>
                    {
                        if (top == TenantOperationMessage.CreatingSiteCollection)
                        {
                            var maxProgress = (100 / (Int32)SetupStep.Completed);
                            info.ViewModel.SetupProgress += 1;
                            if (info.ViewModel.SetupProgress >= maxProgress)
                            {
                                info.ViewModel.SetupProgress = maxProgress;
                            }
                        }
                        return(false);
                    });
                }
            }

            await Task.Delay(5000);

            using (var adminContext = am.GetAzureADAccessTokenAuthenticatedContext(
                       tenantAdminUri.ToString(), accessToken))
            {
                adminContext.RequestTimeout = Timeout.Infinite;

                var  tenant = new Tenant(adminContext);
                Site site   = tenant.GetSiteByUrl(info.InfrastructuralSiteUrl);
                Web  web    = site.RootWeb;

                adminContext.Load(site, s => s.Url);
                adminContext.Load(web, w => w.Url);
                adminContext.ExecuteQueryRetry();

                // Enable Secondary Site Collection Administrator
                if (!String.IsNullOrEmpty(info.InfrastructuralSiteSecondaryAdmin))
                {
                    Microsoft.SharePoint.Client.User secondaryOwner = web.EnsureUser(info.InfrastructuralSiteSecondaryAdmin);
                    secondaryOwner.IsSiteAdmin = true;
                    secondaryOwner.Update();

                    web.SiteUsers.AddUser(secondaryOwner);
                    adminContext.ExecuteQueryRetry();
                }
                siteCreated = true;
            }

            if (siteAlreadyExists || siteCreated)
            {
                accessToken = await AzureManagementUtility.GetAccessTokenSilentAsync(
                    sharepointUri.ToString(), ConfigurationManager.AppSettings["O365:ClientId"]);

                using (ClientContext clientContext = am.GetAzureADAccessTokenAuthenticatedContext(
                           info.InfrastructuralSiteUrl, accessToken))
                {
                    clientContext.RequestTimeout = Timeout.Infinite;

                    Site site = clientContext.Site;
                    Web  web  = site.RootWeb;

                    clientContext.Load(site, s => s.Url);
                    clientContext.Load(web, w => w.Url);
                    clientContext.ExecuteQueryRetry();

                    // Override settings within templates, before uploading them
                    UpdateProvisioningTemplateParameter("Responsive", "SPO-Responsive.xml",
                                                        "AzureWebSiteUrl", info.AzureWebAppUrl);
                    UpdateProvisioningTemplateParameter("Overrides", "PnP-Partner-Pack-Overrides.xml",
                                                        "AzureWebSiteUrl", info.AzureWebAppUrl);

                    // Apply the templates to the target site
                    ApplyProvisioningTemplate(web, "Infrastructure", "PnP-Partner-Pack-Infrastructure-Jobs.xml");
                    ApplyProvisioningTemplate(web, "Infrastructure", "PnP-Partner-Pack-Infrastructure-Templates.xml");
                    ApplyProvisioningTemplate(web, "", "PnP-Partner-Pack-Infrastructure-Contents.xml");

                    // We to it twice to force the content types, due to a small bug in the provisioning engine
                    ApplyProvisioningTemplate(web, "", "PnP-Partner-Pack-Infrastructure-Contents.xml");
                }
            }
            else
            {
                // TODO: Handle some kind of exception ...
            }
        }
        private void CreateSiteCollection(SiteCollectionProvisioningJob job)
        {
            using (PnPMonitoredScope Log = new PnPMonitoredScope("CreateSiteCollection"))
            {
                // build site collection url
                String siteUrl = String.Format("{0}{1}",
                                               ConfigurationHelper.GetConfiguration.HostSiteUrl.Substring(0, ConfigurationHelper.GetConfiguration.HostSiteUrl.LastIndexOf("/") + 1),
                                               job.RelativeUrl.TrimStart('/'));

                // get provisioning template
                var provisioningTemplate = GetProvisioningTemplate(job.PnPTemplate);

                if (provisioningTemplate != null)
                {
                    job.BaseTemplate = string.IsNullOrEmpty(provisioningTemplate.BaseSiteTemplate)
                        ? (string.IsNullOrEmpty(job.BaseTemplate)
                            ? ConfigurationHelper.GetConfiguration.BaseSiteTemplate
                            : job.BaseTemplate)
                        : provisioningTemplate.BaseSiteTemplate;
                }
                else
                {
                    job.BaseTemplate = string.IsNullOrEmpty(job.BaseTemplate)
                            ? ConfigurationHelper.GetConfiguration.BaseSiteTemplate
                            : job.BaseTemplate;
                }

                using (var adminContext = AppOnlyContextProvider.GetAppOnlyContext(ConfigurationHelper.GetConfiguration.TenantAdminUrl))
                {
                    adminContext.RequestTimeout = Timeout.Infinite;

                    // Create the Site Collection and wait for its creation (we're asynchronous)
                    var tenant = new Tenant(adminContext);

                    // check if site collection already exists and in active state.
                    if (tenant.CheckIfSiteExists(siteUrl, Constants.Site_Status_Active))
                    {
                        Log.LogError($"Site collection with url \"{siteUrl}\" already exists.");
                    }
                    else
                    {
                        Log.LogInfo($"Creating site collection \"{job.RelativeUrl}\" with template {job.BaseTemplate})");

                        try
                        {
                            tenant.CreateSiteCollection(new SiteEntity()
                            {
                                Description         = job.Description,
                                Title               = job.Title,
                                Url                 = siteUrl,
                                SiteOwnerLogin      = ConfigurationHelper.GetConfiguration.PrimarySiteCollectionAdministrator,
                                StorageMaximumLevel = job.StorageMaximumLevel,
                                StorageWarningLevel = job.StorageWarningLevel,
                                Template            = job.BaseTemplate,
                                Lcid                = ((provisioningTemplate != null && provisioningTemplate.RegionalSettings != null) &&
                                                       provisioningTemplate.RegionalSettings.LocaleId > 0)
                                        ? uint.Parse(provisioningTemplate.RegionalSettings.LocaleId.ToString())
                                        : job.Language,
                                TimeZoneId = ((provisioningTemplate != null && provisioningTemplate.RegionalSettings != null) &&
                                              provisioningTemplate.RegionalSettings.TimeZone > 0)
                                        ? provisioningTemplate.RegionalSettings.TimeZone
                                        : job.TimeZone,
                            }, removeFromRecycleBin: true, wait: true);
                        }
                        catch (Exception exception)
                        {
                            Log.LogError($"Error occured while creating site collection {job.RelativeUrl}");

                            if (tenant.SiteExists(siteUrl))
                            {
                                tenant.DeleteSiteCollection(siteUrl, useRecycleBin: false);
                            }

                            throw exception;
                        }
                    }

                    if (provisioningTemplate != null)
                    {
                        Log.LogInfo($"Applying provisioning template {provisioningTemplate.DisplayName}");
                        ApplyProvisioningTemplate(provisioningTemplate, siteUrl);
                    }

                    Log.LogInfo($"Site collection {siteUrl} provisioned successfully.");
                }
            }
        }