public async Task <string> CreateTeamSiteCollectionAsync(TeamSiteCollectionRequest request)
        {
            var X509Cert    = GetX509Certificate2();
            var accessToken = await graphClientApi.AcquireTokenAsync(X509Cert);

            using var authmanager = new AuthenticationManager();
            using var context     = authmanager.GetAzureADAppOnlyAuthenticatedContext(
                      AppConfigurations.SpoUrlAdmin,
                      AppConfigurations.ClientID,
                      AppConfigurations.TenantID,
                      X509Cert);

            var teamSiteCollection = new TeamSiteCollectionCreationInformation
            {
                Alias       = request.Alias,
                DisplayName = request.DisplayName,
                Description = request.Description,
                Lcid        = (uint)request.Language,
                Owners      = request.Owners == null || request.Owners.Length == 0
                    ? new[] { AppConfigurations.SpoUserAdmin }
                    : request.Owners
            };

            await SiteCollection.CreateTeamSiteViaGraphAsync(context, teamSiteCollection, noWait : true, graphAccessToken : accessToken);

            return($"{AppConfigurations.SpoUrl}/sites/{request.Alias}");
        }
        public ICustomActivityResult Execute()
        {
            try
            {
                //Open the Tenant Administration Context with the Tenant Admin Url
                using (ClientContext clientContext = new ClientContext(InstanceAdminURL))
                {
                    SecureString secureString = new SecureString();
                    Password.ToList().ForEach(secureString.AppendChar);
                    clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
                    clientContext.Credentials        = new SharePointOnlineCredentials(UserName, secureString);

                    NormalizeURL();
                    string instanceUrl = InstanceAdminURL.Replace("-admin", "");

                    if (SiteTemplate.Contains("SITEPAGEPUBLISHING"))
                    {
                        CommunicationSiteCollectionCreationInformation communicationSiteInfo = new CommunicationSiteCollectionCreationInformation
                        {
                            Title      = SiteTitle,
                            Url        = instanceUrl,
                            SiteDesign = CommunicationSiteDesign.Blank,
                            Owner      = SiteOwnerLogin
                        };

                        var createCommSite = clientContext.CreateSiteAsync(communicationSiteInfo).Result;
                    }
                    else
                    {
                        var teamSite = new TeamSiteCollectionCreationInformation
                        {
                            Description = SiteTitle,
                            DisplayName = SiteName,
                            Alias       = SiteName,
                            Owners      = new string[] { SiteOwnerLogin },
                            IsPublic    = true
                        };

                        var createModernSite = clientContext.CreateSiteAsync(teamSite).Result;
                    }

                    clientContext.ExecuteQuery();
                }

                return(this.GenerateActivityResult(GetActivityResult));
            }
            catch (Exception e)
            {
                throw new Exception(string.Format("Error creating site '{0}'. {1}", SiteName, e.Message));
            }
        }
示例#3
0
       private static async void CreateTeamSite()
        {
            try
            {
                string siteName;
                Console.Write("Enter Site Name - \n");
                siteName = Console.ReadLine();
                Console.WriteLine("You entered", siteName);

                string description;
                Console.Write("Enter a description for site - \n");
                description = Console.ReadLine();
                Console.WriteLine("You entered ", description);

                string alis;
                Console.Write("Enter alis - \n");
                alis = Console.ReadLine();
                Console.WriteLine("You entered ", alis);

                TeamSiteCollectionCreationInformation modernteamSiteInfo = new TeamSiteCollectionCreationInformation();

                modernteamSiteInfo.DisplayName = siteName;
                modernteamSiteInfo.Description = description;
                modernteamSiteInfo.Alias = alis;
                modernteamSiteInfo.IsPublic = true;

                var createModernSite = await globalctx.CreateSiteAsync(modernteamSiteInfo);

                Console.WriteLine("site created ....");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }
        /// <summary>
        /// BETA: Creates a Team Site Collection
        /// </summary>
        /// <param name="clientContext"></param>
        /// <param name="siteCollectionCreationInformation"></param>
        /// <returns></returns>
        public static async Task <ClientContext> CreateSiteAsync(this ClientContext clientContext, TeamSiteCollectionCreationInformation siteCollectionCreationInformation)
        {
            await new SynchronizationContextRemover();

            return(await SiteCollection.CreateAsync(clientContext, siteCollectionCreationInformation));
        }
        public override TokenParser ProvisionObjects(Tenant tenant, Model.ProvisioningHierarchy hierarchy, string sequenceId, TokenParser tokenParser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(CoreResources.Provisioning_ObjectHandlers_Provisioning))
            {
                var sequence = hierarchy.Sequences.FirstOrDefault(s => s.ID == sequenceId);
                if (sequence != null)
                {
                    var siteUrls = new Dictionary <Guid, string>();

                    TokenParser siteTokenParser = null;


                    foreach (var sitecollection in sequence.SiteCollections)
                    {
                        ClientContext siteContext = null;

                        switch (sitecollection)
                        {
                        case TeamSiteCollection t:
                        {
                            TeamSiteCollectionCreationInformation siteInfo = new TeamSiteCollectionCreationInformation()
                            {
                                Alias          = tokenParser.ParseString(t.Alias),
                                DisplayName    = tokenParser.ParseString(t.Title),
                                Description    = tokenParser.ParseString(t.Description),
                                Classification = tokenParser.ParseString(t.Classification),
                                IsPublic       = t.IsPublic
                            };

                            var groupSiteInfo = Sites.SiteCollection.GetGroupInfo(tenant.Context as ClientContext, siteInfo.Alias).GetAwaiter().GetResult();
                            if (groupSiteInfo == null)
                            {
                                WriteMessage($"Creating Team Site {siteInfo.Alias}", ProvisioningMessageType.Progress);
                                siteContext = Sites.SiteCollection.Create(tenant.Context as ClientContext, siteInfo);
                            }
                            else
                            {
                                if (groupSiteInfo.ContainsKey("siteUrl"))
                                {
                                    WriteMessage($"Using existing Team Site {siteInfo.Alias}", ProvisioningMessageType.Progress);
                                    siteContext = (tenant.Context as ClientContext).Clone(groupSiteInfo["siteUrl"], applyingInformation.AccessTokens);
                                }
                            }
                            if (t.IsHubSite)
                            {
                                RegisterAsHubSite(tenant, siteContext.Url, t.HubSiteLogoUrl);
                            }
                            if (!string.IsNullOrEmpty(t.Theme))
                            {
                                var parsedTheme = tokenParser.ParseString(t.Theme);
                                tenant.SetWebTheme(parsedTheme, siteContext.Url);
                                tenant.Context.ExecuteQueryRetry();
                            }
                            siteUrls.Add(t.Id, siteContext.Url);
                            if (!string.IsNullOrEmpty(t.ProvisioningId))
                            {
                                _additionalTokens.Add(new SequenceSiteUrlUrlToken(null, t.ProvisioningId, siteContext.Url));
                                siteContext.Web.EnsureProperty(w => w.Id);
                                _additionalTokens.Add(new SequenceSiteIdToken(null, t.ProvisioningId, siteContext.Web.Id));
                                siteContext.Site.EnsureProperties(s => s.Id, s => s.GroupId);
                                _additionalTokens.Add(new SequenceSiteCollectionIdToken(null, t.ProvisioningId, siteContext.Site.Id));
                                _additionalTokens.Add(new SequenceSiteGroupIdToken(null, t.ProvisioningId, siteContext.Site.GroupId));
                            }
                            break;
                        }

                        case CommunicationSiteCollection c:
                        {
                            var siteUrl = tokenParser.ParseString(c.Url);
                            if (!siteUrl.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase))
                            {
                                var rootSiteUrl = tenant.GetRootSiteUrl();
                                tenant.Context.ExecuteQueryRetry();
                                siteUrl = UrlUtility.Combine(rootSiteUrl.Value, siteUrl);
                            }
                            CommunicationSiteCollectionCreationInformation siteInfo = new CommunicationSiteCollectionCreationInformation()
                            {
                                ShareByEmailEnabled = c.AllowFileSharingForGuestUsers,
                                Classification      = tokenParser.ParseString(c.Classification),
                                Description         = tokenParser.ParseString(c.Description),
                                Lcid  = (uint)c.Language,
                                Owner = tokenParser.ParseString(c.Owner),
                                Title = tokenParser.ParseString(c.Title),
                                Url   = siteUrl
                            };
                            if (Guid.TryParse(c.SiteDesign, out Guid siteDesignId))
                            {
                                siteInfo.SiteDesignId = siteDesignId;
                            }
                            else
                            {
                                if (!string.IsNullOrEmpty(c.SiteDesign))
                                {
                                    siteInfo.SiteDesign = (CommunicationSiteDesign)Enum.Parse(typeof(CommunicationSiteDesign), c.SiteDesign);
                                }
                                else
                                {
                                    siteInfo.SiteDesign = CommunicationSiteDesign.Showcase;
                                }
                            }
                            // check if site exists
                            if (tenant.SiteExists(siteInfo.Url))
                            {
                                WriteMessage($"Using existing Communications Site at {siteInfo.Url}", ProvisioningMessageType.Progress);
                                siteContext = (tenant.Context as ClientContext).Clone(siteInfo.Url, applyingInformation.AccessTokens);
                            }
                            else
                            {
                                WriteMessage($"Creating Communications Site at {siteInfo.Url}", ProvisioningMessageType.Progress);
                                siteContext = Sites.SiteCollection.Create(tenant.Context as ClientContext, siteInfo);
                            }
                            if (c.IsHubSite)
                            {
                                RegisterAsHubSite(tenant, siteInfo.Url, c.HubSiteLogoUrl);
                            }
                            if (!string.IsNullOrEmpty(c.Theme))
                            {
                                var parsedTheme = tokenParser.ParseString(c.Theme);
                                tenant.SetWebTheme(parsedTheme, siteInfo.Url);
                                tenant.Context.ExecuteQueryRetry();
                            }
                            siteUrls.Add(c.Id, siteInfo.Url);
                            if (!string.IsNullOrEmpty(c.ProvisioningId))
                            {
                                _additionalTokens.Add(new SequenceSiteUrlUrlToken(null, c.ProvisioningId, siteInfo.Url));
                                siteContext.Web.EnsureProperty(w => w.Id);
                                _additionalTokens.Add(new SequenceSiteIdToken(null, c.ProvisioningId, siteContext.Web.Id));
                                siteContext.Site.EnsureProperties(s => s.Id, s => s.GroupId);
                                _additionalTokens.Add(new SequenceSiteCollectionIdToken(null, c.ProvisioningId, siteContext.Site.Id));
                                _additionalTokens.Add(new SequenceSiteGroupIdToken(null, c.ProvisioningId, siteContext.Site.GroupId));
                            }
                            break;
                        }

                        case TeamNoGroupSiteCollection t:
                        {
                            var        siteUrl  = tokenParser.ParseString(t.Url);
                            SiteEntity siteInfo = new SiteEntity()
                            {
                                Lcid           = (uint)t.Language,
                                Template       = "STS#3",
                                TimeZoneId     = t.TimeZoneId,
                                Title          = tokenParser.ParseString(t.Title),
                                Url            = tokenParser.ParseString(t.Url),
                                SiteOwnerLogin = tokenParser.ParseString(t.Owner),
                            };
                            WriteMessage($"Creating Team Site with no Office 365 group at {siteUrl}", ProvisioningMessageType.Progress);
                            if (tenant.SiteExists(siteUrl))
                            {
                                WriteMessage($"Using existing Team Site at {siteUrl}", ProvisioningMessageType.Progress);
                                siteContext = (tenant.Context as ClientContext).Clone(siteUrl, applyingInformation.AccessTokens);
                            }
                            else
                            {
                                tenant.CreateSiteCollection(siteInfo, false, true);
                                siteContext = tenant.Context.Clone(siteUrl, applyingInformation.AccessTokens);
                            }
                            if (t.IsHubSite)
                            {
                                RegisterAsHubSite(tenant, siteContext.Url, t.HubSiteLogoUrl);
                            }
                            if (!string.IsNullOrEmpty(t.Theme))
                            {
                                var parsedTheme = tokenParser.ParseString(t.Theme);
                                tenant.SetWebTheme(parsedTheme, siteContext.Url);
                                tenant.Context.ExecuteQueryRetry();
                            }
                            siteUrls.Add(t.Id, siteContext.Url);
                            if (!string.IsNullOrEmpty(t.ProvisioningId))
                            {
                                _additionalTokens.Add(new SequenceSiteUrlUrlToken(null, t.ProvisioningId, siteContext.Url));
                                siteContext.Web.EnsureProperty(w => w.Id);
                                _additionalTokens.Add(new SequenceSiteIdToken(null, t.ProvisioningId, siteContext.Web.Id));
                                siteContext.Site.EnsureProperties(s => s.Id, s => s.GroupId);
                                _additionalTokens.Add(new SequenceSiteCollectionIdToken(null, t.ProvisioningId, siteContext.Site.Id));
                                _additionalTokens.Add(new SequenceSiteGroupIdToken(null, t.ProvisioningId, siteContext.Site.GroupId));
                            }
                            break;
                        }
                        }

                        var web = siteContext.Web;

                        foreach (var subsite in sitecollection.Sites)
                        {
                            var subSiteObject = (TeamNoGroupSubSite)subsite;
                            web.EnsureProperties(w => w.Webs.IncludeWithDefaultProperties(), w => w.ServerRelativeUrl);
                            siteTokenParser = CreateSubSites(hierarchy, siteTokenParser, sitecollection, siteContext, web, subSiteObject);
                        }
                    }

                    // System.Threading.Thread.Sleep(TimeSpan.FromMinutes(10));

                    WriteMessage("Applying templates", ProvisioningMessageType.Progress);
                    var currentSite = "";

                    var provisioningTemplateApplyingInformation = new ProvisioningTemplateApplyingInformation();
                    provisioningTemplateApplyingInformation.AccessTokens     = applyingInformation.AccessTokens;
                    provisioningTemplateApplyingInformation.MessagesDelegate = applyingInformation.MessagesDelegate;
                    provisioningTemplateApplyingInformation.ProgressDelegate = (string message, int step, int total) =>
                    {
                        applyingInformation.ProgressDelegate?.Invoke($"{currentSite} : {message}", step, total);
                    };
                    provisioningTemplateApplyingInformation.SiteProvisionedDelegate = applyingInformation.SiteProvisionedDelegate;

                    foreach (var sitecollection in sequence.SiteCollections)
                    {
                        currentSite = sitecollection.ProvisioningId != null ? sitecollection.ProvisioningId : sitecollection.Title;

                        siteUrls.TryGetValue(sitecollection.Id, out string siteUrl);
                        if (siteUrl != null)
                        {
                            using (var clonedContext = tenant.Context.Clone(siteUrl, applyingInformation.AccessTokens))
                            {
                                var web = clonedContext.Web;
                                foreach (var templateRef in sitecollection.Templates)
                                {
                                    var provisioningTemplate = hierarchy.Templates.FirstOrDefault(t => t.Id == templateRef);
                                    if (provisioningTemplate != null)
                                    {
                                        provisioningTemplate.Connector = hierarchy.Connector;
                                        //if (siteTokenParser == null)
                                        //{
                                        siteTokenParser = new TokenParser(web, provisioningTemplate, applyingInformation);
                                        foreach (var token in _additionalTokens)
                                        {
                                            siteTokenParser.AddToken(token);
                                        }
                                        //}
                                        //else
                                        //{
                                        //    siteTokenParser.Rebase(web, provisioningTemplate);
                                        //}
                                        WriteMessage($"Applying Template", ProvisioningMessageType.Progress);
                                        new SiteToTemplateConversion().ApplyRemoteTemplate(web, provisioningTemplate, provisioningTemplateApplyingInformation, true, siteTokenParser);
                                    }
                                    else
                                    {
                                        WriteMessage($"Referenced template ID {templateRef} not found", ProvisioningMessageType.Error);
                                    }
                                }

                                if (siteTokenParser == null)
                                {
                                    siteTokenParser = new TokenParser(tenant, hierarchy, applyingInformation);
                                    foreach (var token in _additionalTokens)
                                    {
                                        siteTokenParser.AddToken(token);
                                    }
                                }

                                foreach (var subsite in sitecollection.Sites)
                                {
                                    var subSiteObject = (TeamNoGroupSubSite)subsite;
                                    web.EnsureProperties(w => w.Webs.IncludeWithDefaultProperties(), w => w.ServerRelativeUrl);
                                    siteTokenParser = ApplySubSiteTemplates(hierarchy, siteTokenParser, sitecollection, clonedContext, web, subSiteObject, provisioningTemplateApplyingInformation);
                                }
                            }
                        }
                    }
                }
                return(tokenParser);
            }
        }
示例#6
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;
            }
        }
示例#7
0
 private async Task <ClientContext> createSite(TeamSiteCollectionCreationInformation properties, ClientContext ctx)
 {
     return(await ctx.CreateSiteAsync(properties));
 }
        public override TokenParser ProvisionObjects(Tenant tenant, Model.ProvisioningHierarchy hierarchy, string sequenceId, TokenParser tokenParser, ApplyConfiguration configuration)
        {
            using (var scope = new PnPMonitoredScope(CoreResources.Provisioning_ObjectHandlers_Provisioning))
            {
                bool nowait = false;
                if (configuration != null)
                {
                    nowait = configuration.Tenant.DoNotWaitForSitesToBeFullyCreated;
                }
                var sequence = hierarchy.Sequences.FirstOrDefault(s => s.ID == sequenceId);
                if (sequence != null)
                {
                    var siteUrls = new Dictionary <Guid, string>();

                    TokenParser siteTokenParser = null;

                    var tenantThemes = tenant.GetAllTenantThemes();
                    tenant.Context.Load(tenantThemes);
                    tenant.Context.ExecuteQueryRetry();

                    foreach (var sitecollection in sequence.SiteCollections)
                    {
                        ClientContext siteContext = null;

                        switch (sitecollection)
                        {
                        case TeamSiteCollection t:
                        {
                            TeamSiteCollectionCreationInformation siteInfo = new TeamSiteCollectionCreationInformation()
                            {
                                Alias          = tokenParser.ParseString(t.Alias),
                                DisplayName    = tokenParser.ParseString(t.Title),
                                Description    = tokenParser.ParseString(t.Description),
                                Classification = tokenParser.ParseString(t.Classification),
                                IsPublic       = t.IsPublic,
                                Lcid           = (uint)t.Language
                            };
                            if (Guid.TryParse(t.SiteDesign, out Guid siteDesignId))
                            {
                                siteInfo.SiteDesignId = siteDesignId;
                            }

                            var groupSiteInfo = Sites.SiteCollection.GetGroupInfoAsync(tenant.Context as ClientContext, siteInfo.Alias).GetAwaiter().GetResult();
                            if (groupSiteInfo == null)
                            {
                                string graphAccessToken = null;
                                try
                                {
                                    graphAccessToken = PnPProvisioningContext.Current.AcquireCookie(Core.Utilities.Graph.GraphHelper.MicrosoftGraphBaseURI);
                                }
                                catch
                                {
                                    graphAccessToken = PnPProvisioningContext.Current.AcquireToken(Core.Utilities.Graph.GraphHelper.MicrosoftGraphBaseURI, null);
                                }
                                WriteMessage($"Creating Team Site {siteInfo.Alias}", ProvisioningMessageType.Progress);
                                siteContext = Sites.SiteCollection.Create(tenant.Context as ClientContext, siteInfo, configuration.Tenant.DelayAfterModernSiteCreation, noWait: nowait, graphAccessToken: graphAccessToken);
                            }
                            else
                            {
                                if (groupSiteInfo.ContainsKey("siteUrl"))
                                {
                                    WriteMessage($"Using existing Team Site {siteInfo.Alias}", ProvisioningMessageType.Progress);
                                    siteContext = (tenant.Context as ClientContext).Clone(groupSiteInfo["siteUrl"], configuration.AccessTokens);
                                }
                            }
                            if (t.IsHubSite)
                            {
                                siteContext.Load(siteContext.Site, s => s.Id);
                                siteContext.ExecuteQueryRetry();
                                RegisterAsHubSite(tenant, siteContext.Url, siteContext.Site.Id, t.HubSiteLogoUrl, t.HubSiteTitle, tokenParser);
                            }
                            if (!string.IsNullOrEmpty(t.Theme))
                            {
                                var parsedTheme = tokenParser.ParseString(t.Theme);
                                if (tenantThemes.FirstOrDefault(th => th.Name == parsedTheme) != null)
                                {
                                    tenant.SetWebTheme(parsedTheme, siteContext.Url);
                                    tenant.Context.ExecuteQueryRetry();
                                }
                                else
                                {
                                    WriteMessage($"Theme {parsedTheme} doesn't exist in the tenant, will not be applied", ProvisioningMessageType.Warning);
                                }
                            }
                            if (t.Teamify)
                            {
                                try
                                {
                                    WriteMessage($"Teamifying the O365 group connected site at URL - {siteContext.Url}", ProvisioningMessageType.Progress);
                                    siteContext.TeamifyAsync().GetAwaiter().GetResult();
                                }
                                catch (Exception ex)
                                {
                                    WriteMessage($"Teamifying site at URL - {siteContext.Url} failed due to an exception:- {ex.Message}", ProvisioningMessageType.Warning);
                                }
                            }
                            if (t.HideTeamify)
                            {
                                try
                                {
                                    WriteMessage($"Teamify prompt is now hidden for site at URL - {siteContext.Url}", ProvisioningMessageType.Progress);
                                    siteContext.HideTeamifyPrompt().GetAwaiter().GetResult();
                                }
                                catch (Exception ex)
                                {
                                    WriteMessage($"Teamify prompt couldn't be hidden for site at URL - {siteContext.Url} due to an exception:- {ex.Message}", ProvisioningMessageType.Warning);
                                }
                            }
                            siteUrls.Add(t.Id, siteContext.Url);
                            if (!string.IsNullOrEmpty(t.ProvisioningId))
                            {
                                _additionalTokens.Add(new SequenceSiteUrlUrlToken(null, t.ProvisioningId, siteContext.Url));
                                siteContext.Web.EnsureProperty(w => w.Id);
                                _additionalTokens.Add(new SequenceSiteIdToken(null, t.ProvisioningId, siteContext.Web.Id));
                                siteContext.Site.EnsureProperties(s => s.Id, s => s.GroupId);
                                _additionalTokens.Add(new SequenceSiteCollectionIdToken(null, t.ProvisioningId, siteContext.Site.Id));
                                _additionalTokens.Add(new SequenceSiteGroupIdToken(null, t.ProvisioningId, siteContext.Site.GroupId));
                            }
                            break;
                        }

                        case CommunicationSiteCollection c:
                        {
                            var siteUrl = tokenParser.ParseString(c.Url);
                            if (!siteUrl.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase))
                            {
                                var rootSiteUrl = tenant.GetRootSiteUrl();
                                tenant.Context.ExecuteQueryRetry();
                                siteUrl = UrlUtility.Combine(rootSiteUrl.Value, siteUrl);
                            }
                            CommunicationSiteCollectionCreationInformation siteInfo = new CommunicationSiteCollectionCreationInformation()
                            {
                                ShareByEmailEnabled = c.AllowFileSharingForGuestUsers,
                                Classification      = tokenParser.ParseString(c.Classification),
                                Description         = tokenParser.ParseString(c.Description),
                                Lcid  = (uint)c.Language,
                                Owner = tokenParser.ParseString(c.Owner),
                                Title = tokenParser.ParseString(c.Title),
                                Url   = siteUrl
                            };
                            if (Guid.TryParse(c.SiteDesign, out Guid siteDesignId))
                            {
                                siteInfo.SiteDesignId = siteDesignId;
                            }
                            else
                            {
                                if (!string.IsNullOrEmpty(c.SiteDesign))
                                {
                                    siteInfo.SiteDesign = (CommunicationSiteDesign)Enum.Parse(typeof(CommunicationSiteDesign), c.SiteDesign);
                                }
                                else
                                {
                                    siteInfo.SiteDesign = CommunicationSiteDesign.Showcase;
                                }
                            }
                            // check if site exists
                            if (tenant.SiteExistsAnywhere(siteInfo.Url) == SiteExistence.Yes)
                            {
                                WriteMessage($"Using existing Communications Site at {siteInfo.Url}", ProvisioningMessageType.Progress);
                                siteContext = (tenant.Context as ClientContext).Clone(siteInfo.Url, configuration.AccessTokens);
                            }
                            else if (tenant.SiteExistsAnywhere(siteInfo.Url) == SiteExistence.Recycled)
                            {
                                var errorMessage = $"The requested Communications Site at {siteInfo.Url} is in the Recycle Bin and cannot be created";
                                WriteMessage(errorMessage, ProvisioningMessageType.Error);
                                throw new RecycledSiteException(errorMessage);
                            }
                            else
                            {
                                WriteMessage($"Creating Communications Site at {siteInfo.Url}", ProvisioningMessageType.Progress);
                                siteContext = Sites.SiteCollection.Create(tenant.Context as ClientContext, siteInfo, configuration.Tenant.DelayAfterModernSiteCreation, noWait: nowait);
                            }
                            if (c.IsHubSite)
                            {
                                siteContext.Load(siteContext.Site, s => s.Id);
                                siteContext.ExecuteQueryRetry();
                                RegisterAsHubSite(tenant, siteInfo.Url, siteContext.Site.Id, c.HubSiteLogoUrl, c.HubSiteTitle, tokenParser);
                            }
                            if (!string.IsNullOrEmpty(c.Theme))
                            {
                                var parsedTheme = tokenParser.ParseString(c.Theme);
                                if (tenantThemes.FirstOrDefault(th => th.Name == parsedTheme) != null)
                                {
                                    tenant.SetWebTheme(parsedTheme, siteInfo.Url);
                                    tenant.Context.ExecuteQueryRetry();
                                }
                                else
                                {
                                    WriteMessage($"Theme {parsedTheme} doesn't exist in the tenant, will not be applied", ProvisioningMessageType.Warning);
                                }
                            }
                            siteUrls.Add(c.Id, siteInfo.Url);
                            if (!string.IsNullOrEmpty(c.ProvisioningId))
                            {
                                _additionalTokens.Add(new SequenceSiteUrlUrlToken(null, c.ProvisioningId, siteInfo.Url));
                                siteContext.Web.EnsureProperty(w => w.Id);
                                _additionalTokens.Add(new SequenceSiteIdToken(null, c.ProvisioningId, siteContext.Web.Id));
                                siteContext.Site.EnsureProperties(s => s.Id, s => s.GroupId);
                                _additionalTokens.Add(new SequenceSiteCollectionIdToken(null, c.ProvisioningId, siteContext.Site.Id));
                                _additionalTokens.Add(new SequenceSiteGroupIdToken(null, c.ProvisioningId, siteContext.Site.GroupId));
                            }
                            break;
                        }

                        case TeamNoGroupSiteCollection t:
                        {
                            var siteUrl = tokenParser.ParseString(t.Url);
                            TeamNoGroupSiteCollectionCreationInformation siteInfo = new TeamNoGroupSiteCollectionCreationInformation()
                            {
                                Lcid        = (uint)t.Language,
                                Url         = siteUrl,
                                Title       = tokenParser.ParseString(t.Title),
                                Description = tokenParser.ParseString(t.Description),
                                Owner       = tokenParser.ParseString(t.Owner)
                            };
                            if (tenant.SiteExistsAnywhere(siteUrl) == SiteExistence.Yes)
                            {
                                WriteMessage($"Using existing Team Site at {siteUrl}", ProvisioningMessageType.Progress);
                                siteContext = (tenant.Context as ClientContext).Clone(siteUrl, configuration.AccessTokens);
                            }
                            else if (tenant.SiteExistsAnywhere(siteUrl) == SiteExistence.Recycled)
                            {
                                var errorMessage = $"The requested Team Site at {siteUrl} is in the Recycle Bin and cannot be created";
                                WriteMessage(errorMessage, ProvisioningMessageType.Error);
                                throw new RecycledSiteException(errorMessage);
                            }
                            else
                            {
                                WriteMessage($"Creating Team Site with no Office 365 group at {siteUrl}", ProvisioningMessageType.Progress);
                                siteContext = Sites.SiteCollection.Create(tenant.Context as ClientContext, siteInfo, configuration.Tenant.DelayAfterModernSiteCreation, noWait: nowait);
                            }
                            if (t.Groupify)
                            {
                                if (string.IsNullOrEmpty(t.Alias))
                                {
                                    // We generate the alias, if it is missing
                                    t.Alias = t.Title.Replace(" ", string.Empty).ToLower();
                                }

                                // In case we need to groupify the just created site
                                var groupifyInformation = new TeamSiteCollectionGroupifyInformation
                                {
                                    Alias           = t.Alias,          // Mandatory
                                    Classification  = t.Classification, // Optional
                                    Description     = t.Description,
                                    DisplayName     = t.Title,
                                    HubSiteId       = Guid.Empty,        // Optional, so far we skip it
                                    IsPublic        = t.IsPublic,        // Mandatory
                                    KeepOldHomePage = t.KeepOldHomePage, // Optional, but we provide it
                                    Lcid            = (uint)t.Language,
                                    Owners          = new string[] { t.Owner },
                                };
                                tenant.GroupifySite(siteUrl, groupifyInformation);
                            }
                            if (t.IsHubSite)
                            {
                                siteContext.Load(siteContext.Site, s => s.Id);
                                siteContext.ExecuteQueryRetry();
                                RegisterAsHubSite(tenant, siteContext.Url, siteContext.Site.Id, t.HubSiteLogoUrl, t.HubSiteTitle, tokenParser);
                            }
                            if (!string.IsNullOrEmpty(t.Theme))
                            {
                                var parsedTheme = tokenParser.ParseString(t.Theme);
                                if (tenantThemes.FirstOrDefault(th => th.Name == parsedTheme) != null)
                                {
                                    tenant.SetWebTheme(parsedTheme, siteContext.Url);
                                    tenant.Context.ExecuteQueryRetry();
                                }
                                else
                                {
                                    WriteMessage($"Theme {parsedTheme} doesn't exist in the tenant, will not be applied", ProvisioningMessageType.Warning);
                                }
                            }
                            siteUrls.Add(t.Id, siteContext.Url);
                            if (!string.IsNullOrEmpty(t.ProvisioningId))
                            {
                                _additionalTokens.Add(new SequenceSiteUrlUrlToken(null, t.ProvisioningId, siteContext.Url));
                                siteContext.Web.EnsureProperty(w => w.Id);
                                _additionalTokens.Add(new SequenceSiteIdToken(null, t.ProvisioningId, siteContext.Web.Id));
                                siteContext.Site.EnsureProperties(s => s.Id, s => s.GroupId);
                                _additionalTokens.Add(new SequenceSiteCollectionIdToken(null, t.ProvisioningId, siteContext.Site.Id));
                                _additionalTokens.Add(new SequenceSiteGroupIdToken(null, t.ProvisioningId, siteContext.Site.GroupId));
                            }
                            break;
                        }
                        }

                        var web = siteContext.Web;

                        if (siteTokenParser == null)
                        {
                            siteTokenParser = new TokenParser(tenant, hierarchy, configuration.ToApplyingInformation());
                            foreach (var token in _additionalTokens)
                            {
                                siteTokenParser.AddToken(token);

                                // Add the token to the global token parser, too
                                tokenParser.AddToken(token);
                            }
                        }

                        foreach (var subsite in sitecollection.Sites)
                        {
                            var subSiteObject = (TeamNoGroupSubSite)subsite;
                            web.EnsureProperties(w => w.Webs.IncludeWithDefaultProperties(), w => w.ServerRelativeUrl);
                            siteTokenParser = CreateSubSites(hierarchy, siteTokenParser, sitecollection, siteContext, web, subSiteObject);
                        }

                        siteTokenParser = null;
                    }

                    // System.Threading.Thread.Sleep(TimeSpan.FromMinutes(10));

                    WriteMessage("Applying templates", ProvisioningMessageType.Progress);
                    var currentSite = "";

                    var provisioningTemplateApplyingInformation = configuration.ToApplyingInformation();
                    provisioningTemplateApplyingInformation.ProgressDelegate = (string message, int step, int total) =>
                    {
                        configuration.ProgressDelegate?.Invoke($"{currentSite} : {message}", step, total);
                    };

                    foreach (var sitecollection in sequence.SiteCollections)
                    {
                        currentSite = sitecollection.ProvisioningId != null ? sitecollection.ProvisioningId : sitecollection.Title;

                        siteUrls.TryGetValue(sitecollection.Id, out string siteUrl);
                        if (siteUrl != null)
                        {
                            using (var clonedContext = tenant.Context.Clone(siteUrl, configuration.AccessTokens))
                            {
                                var web = clonedContext.Web;
                                foreach (var templateRef in sitecollection.Templates)
                                {
                                    var provisioningTemplate = hierarchy.Templates.FirstOrDefault(t => t.Id == templateRef);
                                    if (provisioningTemplate != null)
                                    {
                                        provisioningTemplate.Connector = hierarchy.Connector;
                                        //if (siteTokenParser == null)
                                        //{
                                        siteTokenParser = new TokenParser(web, provisioningTemplate, configuration.ToApplyingInformation());
                                        foreach (var token in _additionalTokens)
                                        {
                                            siteTokenParser.AddToken(token);
                                        }
                                        //}
                                        //else
                                        //{
                                        //    siteTokenParser.Rebase(web, provisioningTemplate);
                                        //}
                                        WriteMessage($"Applying Template", ProvisioningMessageType.Progress);
                                        new SiteToTemplateConversion().ApplyRemoteTemplate(web, provisioningTemplate, provisioningTemplateApplyingInformation, true, siteTokenParser);
                                    }
                                    else
                                    {
                                        WriteMessage($"Referenced template ID {templateRef} not found", ProvisioningMessageType.Error);
                                    }
                                }

                                if (siteTokenParser == null)
                                {
                                    siteTokenParser = new TokenParser(tenant, hierarchy, configuration.ToApplyingInformation());
                                    foreach (var token in _additionalTokens)
                                    {
                                        siteTokenParser.AddToken(token);
                                    }
                                }

                                foreach (var subsite in sitecollection.Sites)
                                {
                                    var subSiteObject = (TeamNoGroupSubSite)subsite;
                                    web.EnsureProperties(w => w.Webs.IncludeWithDefaultProperties(), w => w.ServerRelativeUrl);
                                    siteTokenParser = ApplySubSiteTemplates(hierarchy, siteTokenParser, sitecollection, clonedContext, web, subSiteObject, provisioningTemplateApplyingInformation);
                                }

                                if (sitecollection.IsHubSite)
                                {
                                    RESTUtilities.ExecuteGet(web, "/_api/web/hubsitedata(true)").GetAwaiter().GetResult();
                                }
                            }
                        }
                    }
                }
                return(tokenParser);
            }
        }
示例#9
0
 /// <summary>
 /// BETA: Creates a Team Site Collection
 /// </summary>
 /// <param name="clientContext"></param>
 /// <param name="siteCollectionCreationInformation"></param>
 /// <returns></returns>
 public static async Task <ClientContext> CreateSiteAsync(this ClientContext clientContext, TeamSiteCollectionCreationInformation siteCollectionCreationInformation)
 {
     return(await SiteCollection.CreateAsync(clientContext, siteCollectionCreationInformation));
 }