示例#1
0
        protected void btnRegister_Click(object sender, EventArgs e)
        {
            //Validate Selections for student
            if (chkRoles.Items[0].Selected)
            {
                if (string.IsNullOrEmpty(ddlMajors.SelectedItem.Value))
                {
                    rfvMajor.IsValid = false;
                }
                else
                {
                    rfvMajor.IsValid = true;
                }

                if (string.IsNullOrEmpty(ddlCollege.SelectedItem.Value))
                {
                    rfvCollege.IsValid = false;
                }
                else
                {
                    rfvCollege.IsValid = true;
                }
            }
            else
            {
                rfvMajor.IsValid   = true;
                rfvCollege.IsValid = true;
            }

            if (rfvMajor.IsValid && rfvCollege.IsValid)
            {
                AccessManagementService AccMng = new AccessManagementService();

                OlescUser        newUser        = new OlescUser();
                UserProfile      newUserProfile = new UserProfile();
                List <OlescRole> role           = new List <OlescRole>();

                newUser.Email    = txtEmail.Text;
                newUser.Password = txtPassword.Text;

                newUserProfile.FirstName = txtFirstName.Text;
                newUserProfile.LastName  = txtLastName.Text;
                newUserProfile.College   = ddlCollege.SelectedItem.Text;
                newUserProfile.Major     = ddlMajors.SelectedItem.Text;

                /* 2 fot now only testing, should change (2 is Student)*/
                //role.Add(new DAL.role() { ID = int.Parse(radRole.SelectedValue) };
                role = chkRoles.Items
                       .Cast <ListItem>()
                       .Where(ci => ci.Selected)
                       .Select(ci => new OlescRole()
                {
                    ID = int.Parse(ci.Value)
                })
                       .ToList();

                // If registration
                Result <OlescUser> result = AccMng.Register(newUser, newUserProfile, role);

                if (result.isSuccess)
                {
                    UrlUtility.Redirect(WebsitePages.REGISTRATION_PAGE, "success");
                }
                else
                {
                }
            }
        }
        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)
                            {
                                WriteMessage($"Creating Team Site {siteInfo.Alias}", ProvisioningMessageType.Progress);
                                siteContext = Sites.SiteCollection.Create(tenant.Context as ClientContext, siteInfo, configuration.Tenant.DelayAfterModernSiteCreation, noWait: nowait);
                            }
                            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);
                            }
                        }

                        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);
            }
        }
示例#3
0
 private void OnNavigate(object sender, RequestNavigateEventArgs e)
 {
     UrlUtility.Open(e.Uri.AbsoluteUri);
 }
示例#4
0
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                var context = web.Context as ClientContext;

                web.EnsureProperties(w => w.ServerRelativeUrl, w => w.RootFolder.WelcomePage);

                // Check if this is not a noscript site as we're not allowed to update some properties
                bool isNoScriptSite = web.IsNoScriptSite();

                foreach (var page in template.Pages)
                {
                    var url = parser.ParseString(page.Url);

                    if (!url.ToLower().StartsWith(web.ServerRelativeUrl.ToLower()))
                    {
                        url = UrlUtility.Combine(web.ServerRelativeUrl, url);
                    }

                    var exists = true;
                    Microsoft.SharePoint.Client.File file = null;
                    try
                    {
                        file = web.GetFileByServerRelativeUrl(url);
                        web.Context.Load(file);
                        web.Context.ExecuteQueryRetry();
                    }
                    catch (ServerException ex)
                    {
                        if (ex.ServerErrorTypeName == "System.IO.FileNotFoundException")
                        {
                            exists = false;
                        }
                    }
                    if (exists)
                    {
                        if (page.Overwrite)
                        {
                            try
                            {
                                scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Pages_Overwriting_existing_page__0_, url);

#pragma warning disable 618
                                if (page.WelcomePage && url.Contains(web.RootFolder.WelcomePage))
#pragma warning restore 618
                                {
                                    web.SetHomePage(string.Empty);
                                }

                                file.DeleteObject();
                                web.Context.ExecuteQueryRetry();
                                web.AddWikiPageByUrl(url);
                                if (page.Layout == WikiPageLayout.Custom)
                                {
                                    web.AddLayoutToWikiPage(WikiPageLayout.OneColumn, url);
                                }
                                else
                                {
                                    web.AddLayoutToWikiPage(page.Layout, url);
                                }
                            }
                            catch (Exception ex)
                            {
                                scope.LogError(CoreResources.Provisioning_ObjectHandlers_Pages_Overwriting_existing_page__0__failed___1_____2_, url, ex.Message, ex.StackTrace);
                            }
                        }
                    }
                    else
                    {
                        try
                        {
                            scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Pages_Creating_new_page__0_, url);

                            web.AddWikiPageByUrl(url);
                            if (page.Layout == WikiPageLayout.Custom)
                            {
                                web.AddLayoutToWikiPage(WikiPageLayout.OneColumn, url);
                            }
                            else
                            {
                                web.AddLayoutToWikiPage(page.Layout, url);
                            }
                        }
                        catch (Exception ex)
                        {
                            scope.LogError(CoreResources.Provisioning_ObjectHandlers_Pages_Creating_new_page__0__failed___1_____2_, url, ex.Message, ex.StackTrace);
                        }
                    }

#pragma warning disable 618
                    if (page.WelcomePage)
#pragma warning restore 618
                    {
                        web.RootFolder.EnsureProperty(p => p.ServerRelativeUrl);
                        var rootFolderRelativeUrl = url.Substring(web.RootFolder.ServerRelativeUrl.Length);
                        web.SetHomePage(rootFolderRelativeUrl);
                    }

#if !SP2013
                    bool webPartsNeedLocalization = false;
#endif
                    if (page.WebParts != null & page.WebParts.Any())
                    {
                        if (!isNoScriptSite)
                        {
                            var existingWebParts = web.GetWebParts(url);

                            foreach (var webPart in page.WebParts)
                            {
                                if (existingWebParts.FirstOrDefault(w => w.WebPart.Title == parser.ParseString(webPart.Title)) == null)
                                {
                                    WebPartEntity wpEntity = new WebPartEntity();
                                    wpEntity.WebPartTitle = parser.ParseString(webPart.Title);
                                    wpEntity.WebPartXml   = parser.ParseString(webPart.Contents.Trim(new[] { '\n', ' ' }), "~sitecollection", "~site");
                                    var wpd = web.AddWebPartToWikiPage(url, wpEntity, (int)webPart.Row, (int)webPart.Column, false);
#if !SP2013
                                    if (webPart.Title.ContainsResourceToken())
                                    {
                                        // update data based on where it was added - needed in order to localize wp title
#if !SP2016
                                        wpd.EnsureProperties(w => w.ZoneId, w => w.WebPart, w => w.WebPart.Properties);
                                        webPart.Zone = wpd.ZoneId;
#else
                                        wpd.EnsureProperties(w => w.WebPart, w => w.WebPart.Properties);
#endif
                                        webPart.Order            = (uint)wpd.WebPart.ZoneIndex;
                                        webPartsNeedLocalization = true;
                                    }
#endif
                                }
                            }
                            var allWebParts = web.GetWebParts(url);
                            foreach (var webpart in allWebParts)
                            {
                                parser.AddToken(new WebPartIdToken(web, webpart.WebPart.Title, webpart.Id));
                            }
                        }
                        else
                        {
                            scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_Pages_SkipAddingWebParts, page.Url);
                        }
                    }

#if !SP2013
                    if (webPartsNeedLocalization)
                    {
                        page.LocalizeWebParts(web, parser, scope);
                    }
#endif

                    file = web.GetFileByServerRelativeUrl(url);
                    file.EnsureProperty(f => f.ListItemAllFields);

                    if (page.Fields.Any())
                    {
                        var item = file.ListItemAllFields;
                        foreach (var fieldValue in page.Fields)
                        {
                            item[fieldValue.Key] = parser.ParseString(fieldValue.Value);
                        }
                        item.Update();
                        web.Context.ExecuteQueryRetry();
                    }
                    if (page.Security != null && page.Security.RoleAssignments.Count != 0)
                    {
                        web.Context.Load(file.ListItemAllFields);
                        web.Context.ExecuteQueryRetry();
                        file.ListItemAllFields.SetSecurity(parser, page.Security);
                    }
                }
            }
            return(parser);
        }
        /// <summary>
        /// Process the metadata copying (as defined in the used page layout mapping)
        /// </summary>
        public void Transform()
        {
            if (this.pageLayoutMappingModel != null)
            {
                bool   isDirty             = false;
                bool   listItemWasReloaded = false;
                string contentTypeId       = null;

                // Set content type
                if (!string.IsNullOrEmpty(this.pageLayoutMappingModel.AssociatedContentType))
                {
                    contentTypeId = CacheManager.Instance.GetContentTypeId(this.page.PageListItem.ParentList, pageLayoutMappingModel.AssociatedContentType);
                    if (!string.IsNullOrEmpty(contentTypeId))
                    {
                        // Load the target page list item, needs to be loaded as it was previously saved and we need to avoid version conflicts
                        this.targetClientContext.Load(this.page.PageListItem);
                        this.targetClientContext.ExecuteQueryRetry();
                        listItemWasReloaded = true;

                        this.page.PageListItem[Constants.ContentTypeIdField] = contentTypeId;
                        this.page.PageListItem.UpdateOverwriteVersion();
                        isDirty = true;
                    }
                }

                // Determine content type to use
                if (string.IsNullOrEmpty(contentTypeId))
                {
                    // grab the default content type
                    contentTypeId = this.page.PageListItem[Constants.ContentTypeIdField].ToString();
                }

                if (this.pageLayoutMappingModel.MetaData != null)
                {
                    // Handle the taxonomy fields
                    bool targetSitePagesLibraryLoaded = false;
                    List targetSitePagesLibrary       = null;
                    foreach (var fieldToProcess in this.pageLayoutMappingModel.MetaData.Field)
                    {
                        // Process only fields which have a target field set...
                        if (!string.IsNullOrEmpty(fieldToProcess.TargetFieldName))
                        {
                            if (!listItemWasReloaded)
                            {
                                // Load the target page list item, needs to be loaded as it was previously saved and we need to avoid version conflicts
                                this.targetClientContext.Load(this.page.PageListItem);
                                this.targetClientContext.ExecuteQueryRetry();
                                listItemWasReloaded = true;
                            }

                            // Get information about this content type field
                            var targetFieldData = CacheManager.Instance.GetPublishingContentTypeField(this.page.PageListItem.ParentList, contentTypeId, fieldToProcess.TargetFieldName);

                            if (targetFieldData == null)
                            {
                                LogWarning($"{LogStrings.TransformCopyingMetaDataFieldSkipped} {fieldToProcess.TargetFieldName}", LogStrings.Heading_CopyingPageMetadata);
                            }
                            else
                            {
                                if (targetFieldData.FieldType == "TaxonomyFieldTypeMulti" || targetFieldData.FieldType == "TaxonomyFieldType")
                                {
                                    if (!targetSitePagesLibraryLoaded)
                                    {
                                        var sitePagesServerRelativeUrl = UrlUtility.Combine(targetClientContext.Web.ServerRelativeUrl, "sitepages");
                                        targetSitePagesLibrary = this.targetClientContext.Web.GetList(sitePagesServerRelativeUrl);
                                        this.targetClientContext.Web.Context.Load(targetSitePagesLibrary, l => l.Fields.IncludeWithDefaultProperties(f => f.Id, f => f.Title, f => f.Hidden, f => f.InternalName, f => f.DefaultValue, f => f.Required));
                                        this.targetClientContext.ExecuteQueryRetry();
                                        targetSitePagesLibraryLoaded = true;
                                    }

                                    switch (targetFieldData.FieldType)
                                    {
                                    case "TaxonomyFieldTypeMulti":
                                    {
                                        var taxFieldBeforeCast = targetSitePagesLibrary.Fields.Where(p => p.Id.Equals(targetFieldData.FieldId)).FirstOrDefault();
                                        if (taxFieldBeforeCast != null)
                                        {
                                            object fieldValueToSet = null;

                                            if (!string.IsNullOrEmpty(fieldToProcess.Functions))
                                            {
                                                // execute function
                                                var evaluatedField = this.functionProcessor.Process(fieldToProcess.Functions, fieldToProcess.Name, CastToPublishingFunctionProcessorFieldType(targetFieldData.FieldType));
                                                if (!string.IsNullOrEmpty(evaluatedField.Item1))
                                                {
                                                    if (!string.IsNullOrEmpty(evaluatedField.Item2))
                                                    {
                                                        List <string> termInfoStrings = new List <string>();
                                                        if (evaluatedField.Item2.Contains("§"))
                                                        {
                                                            string[] termInfoStringList = evaluatedField.Item2.Split(new string[] { "§" }, StringSplitOptions.RemoveEmptyEntries);
                                                            termInfoStrings.AddRange(termInfoStringList);
                                                        }
                                                        else
                                                        {
                                                            termInfoStrings.Add(evaluatedField.Item2);
                                                        }

                                                        if (termInfoStrings.Count > 0)
                                                        {
                                                            fieldValueToSet = new Dictionary <string, object>();
                                                            List <Dictionary <string, object> > termsToSetList = new List <Dictionary <string, object> >();

                                                            foreach (var term in termInfoStrings)
                                                            {
                                                                string[] termValueParts = term.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);

                                                                if (termValueParts.Length == 2)
                                                                {
                                                                    Dictionary <string, object> termsToSet = new Dictionary <string, object>();
                                                                    (termsToSet as Dictionary <string, object>).Add("Label", termValueParts[0]);
                                                                    (termsToSet as Dictionary <string, object>).Add("TermGuid", termValueParts[1]);
                                                                    termsToSetList.Add(termsToSet);
                                                                }
                                                            }

                                                            (fieldValueToSet as Dictionary <string, object>).Add("_Child_Items_", termsToSetList.ToArray());
                                                        }
                                                    }
                                                }
                                            }

                                            // No value was set via the function processing, so let's stick with the default
                                            if (fieldValueToSet == null)
                                            {
                                                fieldValueToSet = this.publishingPageTransformationInformation.SourcePage[fieldToProcess.Name];
                                            }

                                            if (this.publishingPageTransformationInformation.SourcePage.FieldExists(fieldToProcess.Name))
                                            {
                                                var taxField = this.targetClientContext.CastTo <TaxonomyField>(taxFieldBeforeCast);

                                                if (fieldValueToSet is TaxonomyFieldValueCollection)
                                                {
                                                    var valueCollectionToCopy   = (fieldValueToSet as TaxonomyFieldValueCollection);
                                                    var taxonomyFieldValueArray = valueCollectionToCopy.Select(taxonomyFieldValue => $"-1;#{taxonomyFieldValue.Label}|{taxonomyFieldValue.TermGuid}");
                                                    var valueCollection         = new TaxonomyFieldValueCollection(this.targetClientContext, string.Join(";#", taxonomyFieldValueArray), taxField);
                                                    taxField.SetFieldValueByValueCollection(this.page.PageListItem, valueCollection);
                                                    isDirty = true;
                                                    LogInfo($"{LogStrings.TransformCopyingMetaDataField} {targetFieldData.FieldName}", LogStrings.Heading_CopyingPageMetadata);
                                                }
                                                else if (fieldValueToSet is Dictionary <string, object> )
                                                {
                                                    var taxDictionaryList     = (fieldValueToSet as Dictionary <string, object>);
                                                    var valueCollectionToCopy = taxDictionaryList["_Child_Items_"] as Object[];

                                                    List <string> taxonomyFieldValueArray = new List <string>();
                                                    for (int i = 0; i < valueCollectionToCopy.Length; i++)
                                                    {
                                                        var taxDictionary = valueCollectionToCopy[i] as Dictionary <string, object>;
                                                        taxonomyFieldValueArray.Add($"-1;#{taxDictionary["Label"].ToString()}|{taxDictionary["TermGuid"].ToString()}");
                                                    }

                                                    if (valueCollectionToCopy.Length > 0)
                                                    {
                                                        var valueCollection = new TaxonomyFieldValueCollection(this.targetClientContext, string.Join(";#", taxonomyFieldValueArray), taxField);
                                                        taxField.SetFieldValueByValueCollection(this.page.PageListItem, valueCollection);
                                                        isDirty = true;
                                                        LogInfo($"{LogStrings.TransformCopyingMetaDataField} {targetFieldData.FieldName}", LogStrings.Heading_CopyingPageMetadata);
                                                    }
                                                    else
                                                    {
                                                        // Publishing field was empty, so let's skip the metadata copy
                                                        LogInfo(string.Format(LogStrings.TransformCopyingMetaDataTaxFieldEmpty, targetFieldData.FieldName), LogStrings.Heading_CopyingPageMetadata);
                                                    }
                                                }
                                                else
                                                {
                                                    // Publishing field was empty, so let's skip the metadata copy
                                                    LogInfo(string.Format(LogStrings.TransformCopyingMetaDataTaxFieldEmpty, targetFieldData.FieldName), LogStrings.Heading_CopyingPageMetadata);
                                                }
                                            }
                                            else
                                            {
                                                // Log that field in page layout mapping was not found
                                                LogWarning(string.Format(LogStrings.Warning_FieldNotFoundInSourcePage, fieldToProcess.Name), LogStrings.Heading_CopyingPageMetadata);
                                            }
                                        }
                                        break;
                                    }

                                    case "TaxonomyFieldType":
                                    {
                                        var taxFieldBeforeCast = targetSitePagesLibrary.Fields.Where(p => p.Id.Equals(targetFieldData.FieldId)).FirstOrDefault();
                                        if (taxFieldBeforeCast != null)
                                        {
                                            object fieldValueToSet = null;

                                            if (!string.IsNullOrEmpty(fieldToProcess.Functions))
                                            {
                                                // execute function
                                                var evaluatedField = this.functionProcessor.Process(fieldToProcess.Functions, fieldToProcess.Name, CastToPublishingFunctionProcessorFieldType(targetFieldData.FieldType));
                                                if (!string.IsNullOrEmpty(evaluatedField.Item1))
                                                {
                                                    if (!string.IsNullOrEmpty(evaluatedField.Item2))
                                                    {
                                                        string[] termValueParts = evaluatedField.Item2.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);

                                                        if (termValueParts.Length == 2)
                                                        {
                                                            fieldValueToSet = new Dictionary <string, object>();

                                                            (fieldValueToSet as Dictionary <string, object>).Add("Label", termValueParts[0]);
                                                            (fieldValueToSet as Dictionary <string, object>).Add("TermGuid", termValueParts[1]);
                                                        }
                                                    }
                                                }
                                            }

                                            // No value was set via the function processing, so let's stick with the default
                                            if (fieldValueToSet == null)
                                            {
                                                fieldValueToSet = this.publishingPageTransformationInformation.SourcePage[fieldToProcess.Name];
                                            }

                                            if (this.publishingPageTransformationInformation.SourcePage.FieldExists(fieldToProcess.Name))
                                            {
                                                var taxField = this.targetClientContext.CastTo <TaxonomyField>(taxFieldBeforeCast);
                                                TaxonomyFieldValue taxValue = new TaxonomyFieldValue();

                                                if (fieldValueToSet is TaxonomyFieldValue)
                                                {
                                                    taxValue.Label    = (fieldValueToSet as TaxonomyFieldValue).Label;
                                                    taxValue.TermGuid = (fieldValueToSet as TaxonomyFieldValue).TermGuid;
                                                    taxValue.WssId    = -1;
                                                    taxField.SetFieldValueByValue(this.page.PageListItem, taxValue);
                                                    isDirty = true;
                                                    LogInfo($"{LogStrings.TransformCopyingMetaDataField} {targetFieldData.FieldName}", LogStrings.Heading_CopyingPageMetadata);
                                                }
                                                else if ((fieldValueToSet is Dictionary <string, object>))
                                                {
                                                    var taxDictionary = (fieldValueToSet as Dictionary <string, object>);
                                                    taxValue.Label    = taxDictionary["Label"].ToString();
                                                    taxValue.TermGuid = taxDictionary["TermGuid"].ToString();
                                                    taxValue.WssId    = -1;
                                                    taxField.SetFieldValueByValue(this.page.PageListItem, taxValue);
                                                    isDirty = true;
                                                    LogInfo($"{LogStrings.TransformCopyingMetaDataField} {targetFieldData.FieldName}", LogStrings.Heading_CopyingPageMetadata);
                                                }
                                                else
                                                {
                                                    // Publishing field was empty, so let's skip the metadata copy
                                                    LogInfo(string.Format(LogStrings.TransformCopyingMetaDataTaxFieldEmpty, targetFieldData.FieldName), LogStrings.Heading_CopyingPageMetadata);
                                                }
                                            }
                                            else
                                            {
                                                // Log that field in page layout mapping was not found
                                                LogWarning(string.Format(LogStrings.Warning_FieldNotFoundInSourcePage, fieldToProcess.Name), LogStrings.Heading_CopyingPageMetadata);
                                            }
                                        }
                                        break;
                                    }
                                    }
                                }
                            }
                        }
                    }

                    // Persist changes
                    if (isDirty)
                    {
                        this.page.PageListItem.UpdateOverwriteVersion();
                        targetClientContext.Load(this.page.PageListItem);
                        targetClientContext.ExecuteQueryRetry();
                        isDirty = false;
                    }

                    string bannerImageUrl = null;

                    // Copy the field metadata
                    foreach (var fieldToProcess in this.pageLayoutMappingModel.MetaData.Field)
                    {
                        // check if the source field name attribute contains a delimiter value
                        if (fieldToProcess.Name.Contains(";"))
                        {
                            // extract the array of field names to process, and trims each one
                            string[] sourceFieldNames = fieldToProcess.Name.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToArray();

                            // sets the field name to the first "valid" entry
                            fieldToProcess.Name = this.publishingPageTransformationInformation.GetFirstNonEmptyFieldName(sourceFieldNames);
                        }

                        // Process only fields which have a target field set...
                        if (!string.IsNullOrEmpty(fieldToProcess.TargetFieldName))
                        {
                            if (!listItemWasReloaded)
                            {
                                // Load the target page list item, needs to be loaded as it was previously saved and we need to avoid version conflicts
                                this.targetClientContext.Load(this.page.PageListItem);
                                this.targetClientContext.ExecuteQueryRetry();
                                listItemWasReloaded = true;
                            }

                            // Get information about this content type field
                            var targetFieldData = CacheManager.Instance.GetPublishingContentTypeField(this.page.PageListItem.ParentList, contentTypeId, fieldToProcess.TargetFieldName);

                            if (targetFieldData == null)
                            {
                                LogWarning($"{LogStrings.TransformCopyingMetaDataFieldSkipped} {fieldToProcess.TargetFieldName}", LogStrings.Heading_CopyingPageMetadata);
                            }
                            else
                            {
                                if (targetFieldData.FieldType != "TaxonomyFieldTypeMulti" && targetFieldData.FieldType != "TaxonomyFieldType")
                                {
                                    if (this.publishingPageTransformationInformation.SourcePage.FieldExists(fieldToProcess.Name))
                                    {
                                        object fieldValueToSet = null;

                                        if (!string.IsNullOrEmpty(fieldToProcess.Functions))
                                        {
                                            // execute function
                                            var evaluatedField = this.functionProcessor.Process(fieldToProcess.Functions, fieldToProcess.Name, CastToPublishingFunctionProcessorFieldType(targetFieldData.FieldType));
                                            if (!string.IsNullOrEmpty(evaluatedField.Item1))
                                            {
                                                fieldValueToSet = evaluatedField.Item2;
                                            }
                                        }
                                        else
                                        {
                                            fieldValueToSet = this.publishingPageTransformationInformation.SourcePage[fieldToProcess.Name];
                                        }

                                        if (fieldValueToSet != null)
                                        {
                                            if (targetFieldData.FieldType == "User" || targetFieldData.FieldType == "UserMulti")
                                            {
                                                if (fieldValueToSet is FieldUserValue)
                                                {
                                                    // Publishing page transformation always goes cross site collection, so we'll need to lookup a user again
                                                    // Important to use a cloned context to not mess up with the pending list item updates
                                                    try
                                                    {
                                                        // Source User
                                                        var fieldUser = (fieldValueToSet as FieldUserValue).LookupValue;
                                                        // Mapped target user
                                                        fieldUser = this.userTransformator.RemapPrincipal(this.sourceClientContext, (fieldValueToSet as FieldUserValue));

                                                        // Ensure user exists on target site
                                                        var ensuredUserOnTarget = CacheManager.Instance.GetEnsuredUser(this.page.Context, fieldUser);
                                                        if (ensuredUserOnTarget != null)
                                                        {
                                                            // Prep a new FieldUserValue object instance and update the list item
                                                            var newUser = new FieldUserValue()
                                                            {
                                                                LookupId = ensuredUserOnTarget.Id
                                                            };
                                                            this.page.PageListItem[targetFieldData.FieldName] = newUser;
                                                        }
                                                        else
                                                        {
                                                            // Clear target field - needed in overwrite scenarios
                                                            this.page.PageListItem[targetFieldData.FieldName] = null;
                                                            LogWarning(string.Format(LogStrings.Warning_UserIsNotMappedOrResolving, (fieldValueToSet as FieldUserValue).LookupValue, targetFieldData.FieldName), LogStrings.Heading_CopyingPageMetadata);
                                                        }
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        LogWarning(string.Format(LogStrings.Warning_UserIsNotResolving, (fieldValueToSet as FieldUserValue).LookupValue, ex.Message), LogStrings.Heading_CopyingPageMetadata);
                                                    }
                                                }
                                                else
                                                {
                                                    List <FieldUserValue> userValues = new List <FieldUserValue>();
                                                    foreach (var currentUser in (fieldValueToSet as Array))
                                                    {
                                                        try
                                                        {
                                                            // Source User
                                                            var fieldUser = (currentUser as FieldUserValue).LookupValue;
                                                            // Mapped target user
                                                            fieldUser = this.userTransformator.RemapPrincipal(this.sourceClientContext, (currentUser as FieldUserValue));

                                                            // Ensure user exists on target site
                                                            var ensuredUserOnTarget = CacheManager.Instance.GetEnsuredUser(this.page.Context, fieldUser);
                                                            if (ensuredUserOnTarget != null)
                                                            {
                                                                // Prep a new FieldUserValue object instance
                                                                var newUser = new FieldUserValue()
                                                                {
                                                                    LookupId = ensuredUserOnTarget.Id
                                                                };

                                                                userValues.Add(newUser);
                                                            }
                                                            else
                                                            {
                                                                LogWarning(string.Format(LogStrings.Warning_UserIsNotMappedOrResolving, (currentUser as FieldUserValue).LookupValue, targetFieldData.FieldName), LogStrings.Heading_CopyingPageMetadata);
                                                            }
                                                        }
                                                        catch (Exception ex)
                                                        {
                                                            LogWarning(string.Format(LogStrings.Warning_UserIsNotResolving, (currentUser as FieldUserValue).LookupValue, ex.Message), LogStrings.Heading_CopyingPageMetadata);
                                                        }
                                                    }

                                                    if (userValues.Count > 0)
                                                    {
                                                        this.page.PageListItem[targetFieldData.FieldName] = userValues.ToArray();
                                                    }
                                                    else
                                                    {
                                                        // Clear target field - needed in overwrite scenarios
                                                        this.page.PageListItem[targetFieldData.FieldName] = null;
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                this.page.PageListItem[targetFieldData.FieldName] = fieldValueToSet;

                                                // If we set the BannerImageUrl we also need to update the page to ensure this updated page image "sticks"
                                                if (targetFieldData.FieldName == Constants.BannerImageUrlField)
                                                {
                                                    bannerImageUrl = fieldValueToSet.ToString();
                                                }
                                            }

                                            isDirty = true;

                                            LogInfo($"{LogStrings.TransformCopyingMetaDataField} {targetFieldData.FieldName}", LogStrings.Heading_CopyingPageMetadata);
                                        }
                                    }
                                    else
                                    {
                                        // Log that field in page layout mapping was not found
                                        LogWarning(string.Format(LogStrings.Warning_FieldNotFoundInSourcePage, fieldToProcess.Name), LogStrings.Heading_CopyingPageMetadata);
                                    }
                                }
                            }
                        }
                    }

                    // Persist changes
                    if (isDirty)
                    {
                        // If we've set a custom thumbnail value then we need to update the page html to mark the isDefaultThumbnail pageslicer property to false
                        if (!string.IsNullOrEmpty(bannerImageUrl))
                        {
                            this.page.PageListItem[Constants.CanvasContentField] = SetIsDefaultThumbnail(this.page.PageListItem[Constants.CanvasContentField].ToString());
                        }

                        this.page.PageListItem.UpdateOverwriteVersion();
                        targetClientContext.Load(this.page.PageListItem);
                        targetClientContext.ExecuteQueryRetry();


                        isDirty = false;
                    }
                }
            }
            else
            {
                LogDebug("Page Layout mapping model not found", LogStrings.Heading_CopyingPageMetadata);
            }
        }
示例#6
0
        protected override void ExecuteCmdlet()
        {
            if (ParameterSetName == "AsFile")
            {
                if (!System.IO.Path.IsPathRooted(Path))
                {
                    Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path);
                }
                FileName = System.IO.Path.GetFileName(Path);
            }

            SelectedWeb.EnsureProperty(w => w.ServerRelativeUrl);

            var folder  = SelectedWeb.EnsureFolder(SelectedWeb.RootFolder, Folder);
            var fileUrl = UrlUtility.Combine(folder.ServerRelativeUrl, FileName);

            ContentType targetContentType = null;

            //Check to see if the Content Type exists.. If it doesn't we are going to throw an exception and block this transaction right here.
            if (ContentType != null)
            {
                try
                {
                    var list = SelectedWeb.GetListByUrl(folder.ServerRelativeUrl);


                    if (!string.IsNullOrEmpty(ContentType.Id))
                    {
                        targetContentType = list.GetContentTypeById(ContentType.Id);
                    }
                    else if (!string.IsNullOrEmpty(ContentType.Name))
                    {
                        targetContentType = list.GetContentTypeByName(ContentType.Name);
                    }
                    else if (ContentType.ContentType != null)
                    {
                        targetContentType = ContentType.ContentType;
                    }
                    if (targetContentType == null)
                    {
                        ThrowTerminatingError(new ErrorRecord(new ArgumentException($"Content Type Argument: {ContentType} does not exist in the list: {list.Title}"), "CONTENTTYPEDOESNOTEXIST", ErrorCategory.InvalidArgument, this));
                    }
                }
                catch
                {
                    ThrowTerminatingError(new ErrorRecord(new ArgumentException($"The Folder specified ({folder.ServerRelativeUrl}) does not have a corresponding List, the -ContentType parameter is not valid."), "RELATIVEPATHNOTINLIBRARY", ErrorCategory.InvalidArgument, this));
                }
            }

            // Check if the file exists
            if (Checkout)
            {
                try
                {
                    var existingFile = SelectedWeb.GetFileByServerRelativeUrl(fileUrl);
                    existingFile.EnsureProperty(f => f.Exists);
                    if (existingFile.Exists)
                    {
                        SelectedWeb.CheckOutFile(fileUrl);
                    }
                }
                catch
                { // Swallow exception, file does not exist
                }
            }
            Microsoft.SharePoint.Client.File file;
            if (ParameterSetName == "AsFile")
            {
                file = folder.UploadFile(FileName, Path, true);
            }
            else
            {
                file = folder.UploadFile(FileName, Stream, true);
            }

            if (Values != null)
            {
                var item = file.ListItemAllFields;

                foreach (var key in Values.Keys)
                {
                    item[key as string] = Values[key];
                }

                item.Update();

                ClientContext.ExecuteQueryRetry();
            }
            if (ContentType != null)
            {
                var item = file.ListItemAllFields;
                item["ContentTypeId"] = targetContentType.Id.StringValue;
                item.Update();
                ClientContext.ExecuteQueryRetry();
            }

            if (Checkout)
            {
                SelectedWeb.CheckInFile(fileUrl, CheckinType.MajorCheckIn, CheckInComment);
            }


            if (Publish)
            {
                SelectedWeb.PublishFile(fileUrl, PublishComment);
            }

            if (Approve)
            {
                SelectedWeb.ApproveFile(fileUrl, ApproveComment);
            }

            WriteObject(file);
        }
示例#7
0
        protected override void ExecuteCmdlet()
        {
            var serverRelativeUrl = string.Empty;

            var webUrl = CurrentWeb.EnsureProperty(w => w.ServerRelativeUrl);

            if (!Url.ToLower().StartsWith(webUrl.ToLower()))
            {
                serverRelativeUrl = UrlUtility.Combine(webUrl, Url);
            }
            else
            {
                serverRelativeUrl = Url;
            }

            File file;

            file = CurrentWeb.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(serverRelativeUrl));

            ClientContext.Load(file, f => f.Exists, f => f.Versions.IncludeWithDefaultProperties(i => i.CreatedBy));
            ClientContext.ExecuteQueryRetry();

            if (file.Exists)
            {
                var versions = file.Versions;

                switch (ParameterSetName)
                {
                case ParameterSetName_ALL:
                {
                    if (Force || ShouldContinue("Remove all versions?", Resources.Confirm))
                    {
                        versions.DeleteAll();
                        ClientContext.ExecuteQueryRetry();
                    }
                    break;
                }

                case ParameterSetName_BYID:
                {
                    if (Force || ShouldContinue("Remove a version?", Resources.Confirm))
                    {
                        if (!string.IsNullOrEmpty(Identity.Label))
                        {
                            if (Recycle.IsPresent)
                            {
                                versions.RecycleByLabel(Identity.Label);
                            }
                            else
                            {
                                versions.DeleteByLabel(Identity.Label);
                            }
                            ClientContext.ExecuteQueryRetry();
                        }
                        else if (Identity.Id != -1)
                        {
                            if (Recycle.IsPresent)
                            {
                                versions.RecycleByID(Identity.Id);
                            }
                            else
                            {
                                versions.DeleteByID(Identity.Id);
                            }
                            ClientContext.ExecuteQueryRetry();
                        }
                    }
                    break;
                }
                }
            }
            else
            {
                throw new PSArgumentException("File not found", nameof(Url));
            }
        }
示例#8
0
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            var webModelHost = modelHost.WithAssertAndCast <WebModelHost>("modelHost", value => value.RequireNotNull());
            var definition   = model.WithAssertAndCast <WebNavigationSettingsDefinition>("model",
                                                                                         value => value.RequireNotNull());

            var spObject = GetWebNavigationSettings(webModelHost, definition);
            var web      = webModelHost.HostWeb;

            var assert = ServiceFactory.AssertService
                         .NewAssert(definition, spObject)
                         .ShouldNotBeNull(spObject);

            var publishingWeb = PublishingWeb.GetPublishingWeb(web);

            //  web??/_layouts/15/AreaNavigationSettings.aspx
            // extra protection, downbloading HTML page and making sure checkboxes are there :)

            //<input name="ctl00$PlaceHolderMain$globalNavSection$ctl02$globalIncludeSubSites" type="checkbox" id="ctl00_PlaceHolderMain_globalNavSection_ctl02_globalIncludeSubSites" checked="checked">
            //<input name="ctl00$PlaceHolderMain$globalNavSection$ctl02$globalIncludePages" type="checkbox" id="ctl00_PlaceHolderMain_globalNavSection_ctl02_globalIncludePages" disabled="disabled">


            //<input name="ctl00$PlaceHolderMain$currentNavSection$ctl02$currentIncludeSubSites" type="checkbox" id="ctl00_PlaceHolderMain_currentNavSection_ctl02_currentIncludeSubSites">
            //<input name="ctl00$PlaceHolderMain$currentNavSection$ctl02$currentIncludePages" type="checkbox" id="ctl00_PlaceHolderMain_currentNavSection_ctl02_currentIncludePages" disabled="disabled">
            var pageUrl = UrlUtility.CombineUrl(web.Url, "/_layouts/15/AreaNavigationSettings.aspx");

            var client = new WebClient();

            client.UseDefaultCredentials = true;

            var pageContent = client.DownloadString(new Uri(pageUrl));
            CQ  j           = pageContent;

            // so not only API, but also real checboxed on browser page check
            var globalSubSites      = j.Select("input[id$='globalIncludeSubSites']").First();
            var globalSubSitesValue = globalSubSites.Attr("checked") == "checked";

            var globalIncludePages      = j.Select("input[id$='globalIncludePages']").First();
            var globalIncludePagesValue = globalIncludePages.Attr("checked") == "checked";

            var currentIncludeSubSites      = j.Select("input[id$='currentIncludeSubSites']").First();
            var currentIncludeSubSitesValue = currentIncludeSubSites.Attr("checked") == "checked";

            var currentIncludePages      = j.Select("input[id$='currentIncludePages']").First();
            var currentIncludePagesValue = currentIncludePages.Attr("checked") == "checked";

            if (definition.GlobalNavigationShowSubsites.HasValue)
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.GlobalNavigationShowSubsites);

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = (publishingWeb.Navigation.GlobalIncludeSubSites && globalSubSitesValue)
                                  == s.GlobalNavigationShowSubsites
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.GlobalNavigationShowSubsites, "GlobalNavigationShowSubsites is null");
            }

            if (definition.GlobalNavigationShowPages.HasValue)
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.GlobalNavigationShowPages);

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = (publishingWeb.Navigation.GlobalIncludePages && globalIncludePagesValue)
                                  == s.GlobalNavigationShowPages
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.GlobalNavigationShowPages, "GlobalNavigationShowPages is null");
            }

            if (definition.CurrentNavigationShowSubsites.HasValue)
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.CurrentNavigationShowSubsites);

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = (publishingWeb.Navigation.CurrentIncludeSubSites && currentIncludeSubSitesValue)
                                  == s.CurrentNavigationShowSubsites
                    });
                });
            }

            else
            {
                assert.SkipProperty(m => m.CurrentNavigationShowSubsites, "CurrentNavigationShowSubsites is null");
            }

            if (definition.CurrentNavigationShowPages.HasValue)
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.CurrentNavigationShowPages);

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = (publishingWeb.Navigation.CurrentIncludePages && currentIncludePagesValue)
                                  == s.CurrentNavigationShowPages
                    });
                });
            }

            else
            {
                assert.SkipProperty(m => m.CurrentNavigationShowPages, "CurrentNavigationShowPages is null");
            }


            // items count
            if (definition.GlobalNavigationMaximumNumberOfDynamicItems.HasValue)
            {
                var globalDynamicChildLimitValue =
                    ConvertUtils.ToInt(web.AllProperties[BuiltInWebPropertyId.GlobalDynamicChildLimit]);

                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.GlobalNavigationMaximumNumberOfDynamicItems);

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = s.GlobalNavigationMaximumNumberOfDynamicItems == globalDynamicChildLimitValue
                    });
                });
            }
            else
            {
                assert.SkipProperty(d => d.GlobalNavigationMaximumNumberOfDynamicItems,
                                    "GlobalNavigationMaximumNumberOfDynamicItems is null or empty");
            }

            if (definition.CurrentNavigationMaximumNumberOfDynamicItems.HasValue)
            {
                var currentDynamicChildLimitValue =
                    ConvertUtils.ToInt(web.AllProperties[BuiltInWebPropertyId.CurrentDynamicChildLimit]);

                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.CurrentNavigationMaximumNumberOfDynamicItems);

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = s.CurrentNavigationMaximumNumberOfDynamicItems == currentDynamicChildLimitValue
                    });
                });
            }
            else
            {
                assert.SkipProperty(d => d.CurrentNavigationMaximumNumberOfDynamicItems,
                                    "CurrentNavigationMaximumNumberOfDynamicItems is null or empty");
            }

            if (definition.DisplayShowHideRibbonAction.HasValue)
            {
                var displayShowHideRibbonActionValue =
                    ConvertUtils.ToBool(web.AllProperties[BuiltInWebPropertyId.DisplayShowHideRibbonActionId]);

                // If displayShowHideRibbonActionValue has no value, property should be skipped, but I don't know how to get ShouldBeEqualIfHasValue to work

                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.DisplayShowHideRibbonAction);

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = s.DisplayShowHideRibbonAction.Value == displayShowHideRibbonActionValue.Value
                    });
                });
            }
            else
            {
                assert.SkipProperty(d => d.DisplayShowHideRibbonAction,
                                    "DisplayShowHideRibbonAction is null or empty");
            }

            // nav sources
            if (!string.IsNullOrEmpty(definition.GlobalNavigationSource))
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.GlobalNavigationSource);

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = s.GlobalNavigationSource == spObject.GlobalNavigation.Source.ToString()
                    });
                });
            }
            else
            {
                assert.SkipProperty(d => d.GlobalNavigationSource,
                                    "GlobalNavigationSource is null or empty");
            }

            if (!string.IsNullOrEmpty(definition.CurrentNavigationSource))
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.CurrentNavigationSource);

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = s.CurrentNavigationSource == spObject.CurrentNavigation.Source.ToString()
                    });
                });
            }
            else
            {
                assert.SkipProperty(d => d.CurrentNavigationSource,
                                    "CurrentNavigationSource is null or empty");
            }

            if (definition.AddNewPagesToNavigation.HasValue)
            {
                if (!string.IsNullOrEmpty(definition.GlobalNavigationSource) ||
                    !string.IsNullOrEmpty(definition.CurrentNavigationSource))
                {
                    assert.ShouldBeEqual((p, s, d) =>
                    {
                        var srcProp = s.GetExpressionValue(m => m.AddNewPagesToNavigation);

                        return(new PropertyValidationResult
                        {
                            Tag = p.Tag,
                            Src = srcProp,
                            Dst = null,
                            IsValid = s.AddNewPagesToNavigation.Value == spObject.AddNewPagesToNavigation
                        });
                    });
                }
                else
                {
                    assert.SkipProperty(d => d.AddNewPagesToNavigation,
                                        "AddNewPagesToNavigation requires GlobalNavigationSource or CurrentNavigationSource to be not null");
                }
            }
            else
            {
                assert.SkipProperty(d => d.AddNewPagesToNavigation,
                                    "AddNewPagesToNavigation is null");
            }

            if (definition.CreateFriendlyUrlsForNewPages.HasValue)
            {
                if (!string.IsNullOrEmpty(definition.GlobalNavigationSource) ||
                    !string.IsNullOrEmpty(definition.CurrentNavigationSource))
                {
                    assert.ShouldBeEqual((p, s, d) =>
                    {
                        var srcProp = s.GetExpressionValue(m => m.CreateFriendlyUrlsForNewPages);

                        return(new PropertyValidationResult
                        {
                            Tag = p.Tag,
                            Src = srcProp,
                            Dst = null,
                            IsValid = s.CreateFriendlyUrlsForNewPages.Value == spObject.CreateFriendlyUrlsForNewPages
                        });
                    });
                }
                else
                {
                    assert.SkipProperty(d => d.CreateFriendlyUrlsForNewPages,
                                        "CreateFriendlyUrlsForNewPages requires GlobalNavigationSource or CurrentNavigationSource to be not null");
                }
            }
            else
            {
                assert.SkipProperty(d => d.CreateFriendlyUrlsForNewPages,
                                    "CreateFriendlyUrlsForNewPages is null");
            }
        }
示例#9
0
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            var hostClientContext = ExtractHostClientContext(modelHost);

            var parentWeb  = ExtractWeb(modelHost);
            var definition = model.WithAssertAndCast <WebDefinition>("model", value => value.RequireNotNull());

            var currentWebUrl = GetCurrentWebUrl(parentWeb.Context, parentWeb, definition);
            var spObject      = GetExistingWeb(hostClientContext.Site, parentWeb, currentWebUrl);
            var context       = spObject.Context;

            context.Load(spObject,
                         w => w.HasUniqueRoleAssignments,
                         w => w.Description,
                         w => w.Url,
                         w => w.Language,
                         w => w.WebTemplate,
                         w => w.Configuration,
                         w => w.Title,
                         w => w.Id,
                         w => w.Url
                         );



            context.ExecuteQueryWithTrace();

            var assert = ServiceFactory.AssertService
                         .NewAssert(definition, spObject)
                         .ShouldBeEqual(m => m.Title, o => o.Title)
                         .ShouldBeEqual(m => m.LCID, o => o.GetLCID())
                         .ShouldBeEqual(m => m.UseUniquePermission, o => o.HasUniqueRoleAssignments);

            if (!string.IsNullOrEmpty(definition.WebTemplate))
            {
                assert.ShouldBeEqual(m => m.WebTemplate, o => o.GetWebTemplate());
                assert.SkipProperty(m => m.CustomWebTemplate);
            }
            else
            {
                assert.SkipProperty(m => m.WebTemplate);
                assert.SkipProperty(m => m.CustomWebTemplate);
            }

            if (!string.IsNullOrEmpty(definition.Description))
            {
                assert.ShouldBeEqual(m => m.Description, o => o.Description);
            }
            else
            {
                assert.SkipProperty(m => m.Description, "Description is null or empty. Skipping.");
            }

            if (!string.IsNullOrEmpty(definition.Description))
            {
                assert.ShouldBeEqual(m => m.Description, o => o.Description);
            }
            else
            {
                assert.SkipProperty(m => m.Description, "Description is null or empty. Skipping.");
            }


            assert.ShouldBeEqual((p, s, d) =>
            {
                if (!parentWeb.IsObjectPropertyInstantiated("Url"))
                {
                    parentWeb.Context.Load(parentWeb, o => o.Url);
                    parentWeb.Context.ExecuteQueryWithTrace();
                }

                var srcProp = s.GetExpressionValue(def => def.Url);
                var dstProp = d.GetExpressionValue(ct => ct.Url);

                var srcUrl = s.Url;
                var dstUrl = d.Url;

                srcUrl = UrlUtility.RemoveStartingSlash(srcUrl);

                var dstSubUrl = dstUrl.Replace(parentWeb.Url + "/", string.Empty);

                return(new PropertyValidationResult
                {
                    Tag = p.Tag,
                    Src = srcProp,
                    Dst = dstProp,
                    IsValid = srcUrl == dstSubUrl
                });
            });

            var supportsAlternateCssAndSiteImageUrl = ReflectionUtils.HasProperties(spObject, new[]
            {
                "AlternateCssUrl",
                "SiteLogoUrl"
            });

            if (supportsAlternateCssAndSiteImageUrl)
            {
                if (!string.IsNullOrEmpty(definition.AlternateCssUrl))
                {
                    var alternateCssUrl = ReflectionUtils.GetPropertyValue(spObject, "AlternateCssUrl");

                    assert.ShouldBeEqual((p, s, d) =>
                    {
                        var srcProp = s.GetExpressionValue(def => def.AlternateCssUrl);
                        var isValid = true;

                        isValid = s.AlternateCssUrl.ToUpper().EndsWith(alternateCssUrl.ToString().ToUpper());

                        return(new PropertyValidationResult
                        {
                            Tag = p.Tag,
                            Src = srcProp,
                            Dst = null,
                            IsValid = isValid
                        });
                    });
                }
                else
                {
                    assert.SkipProperty(m => m.AlternateCssUrl);
                }

                if (!string.IsNullOrEmpty(definition.SiteLogoUrl))
                {
                    var siteLogoUrl = ReflectionUtils.GetPropertyValue(spObject, "SiteLogoUrl");

                    assert.ShouldBeEqual((p, s, d) =>
                    {
                        var srcProp = s.GetExpressionValue(def => def.SiteLogoUrl);
                        var isValid = true;

                        isValid = s.SiteLogoUrl.ToUpper().EndsWith(siteLogoUrl.ToString().ToUpper());

                        return(new PropertyValidationResult
                        {
                            Tag = p.Tag,
                            Src = srcProp,
                            Dst = null,
                            IsValid = isValid
                        });
                    });
                }
                else
                {
                    assert.SkipProperty(m => m.SiteLogoUrl);
                }
            }

            else
            {
                TraceService.Critical((int)LogEventId.ModelProvisionCoreCall,
                                      "CSOM runtime doesn't have Web.AlternateCssUrl and Web.SiteLogoUrl methods support. Skipping validation.");

                assert.SkipProperty(m => m.AlternateCssUrl, "AlternateCssUrl is null or empty. Skipping.");
                assert.SkipProperty(m => m.SiteLogoUrl, "SiteLogoUrl is null or empty. Skipping.");
            }


            var supportsLocalization = ReflectionUtils.HasProperties(spObject, new[]
            {
                "TitleResource", "DescriptionResource"
            });

            if (supportsLocalization)
            {
                if (definition.TitleResource.Any())
                {
                    assert.ShouldBeEqual((p, s, d) =>
                    {
                        var srcProp = s.GetExpressionValue(def => def.TitleResource);
                        var isValid = true;

                        foreach (var userResource in s.TitleResource)
                        {
                            var culture        = LocalizationService.GetUserResourceCultureInfo(userResource);
                            var resourceObject = ReflectionUtils.GetPropertyValue(spObject, "TitleResource");

                            var value = ReflectionUtils.GetMethod(resourceObject, "GetValueForUICulture")
                                        .Invoke(resourceObject, new[] { culture.Name }) as ClientResult <string>;

                            context.ExecuteQuery();

                            isValid = userResource.Value == value.Value;

                            if (!isValid)
                            {
                                break;
                            }
                        }

                        return(new PropertyValidationResult
                        {
                            Tag = p.Tag,
                            Src = srcProp,
                            Dst = null,
                            IsValid = isValid
                        });
                    });
                }
                else
                {
                    assert.SkipProperty(m => m.TitleResource, "TitleResource is NULL or empty. Skipping.");
                }

                if (definition.DescriptionResource.Any())
                {
                    assert.ShouldBeEqual((p, s, d) =>
                    {
                        var srcProp = s.GetExpressionValue(def => def.DescriptionResource);
                        var isValid = true;

                        foreach (var userResource in s.DescriptionResource)
                        {
                            var culture        = LocalizationService.GetUserResourceCultureInfo(userResource);
                            var resourceObject = ReflectionUtils.GetPropertyValue(spObject, "DescriptionResource");

                            var value = ReflectionUtils.GetMethod(resourceObject, "GetValueForUICulture")
                                        .Invoke(resourceObject, new[] { culture.Name }) as ClientResult <string>;

                            context.ExecuteQuery();

                            isValid = userResource.Value == value.Value;

                            if (!isValid)
                            {
                                break;
                            }
                        }

                        return(new PropertyValidationResult
                        {
                            Tag = p.Tag,
                            Src = srcProp,
                            Dst = null,
                            IsValid = isValid
                        });
                    });
                }
                else
                {
                    assert.SkipProperty(m => m.DescriptionResource, "DescriptionResource is NULL or empty. Skipping.");
                }
            }
            else
            {
                TraceService.Critical((int)LogEventId.ModelProvisionCoreCall,
                                      "CSOM runtime doesn't have Web.TitleResource and Web.DescriptionResource() methods support. Skipping validation.");

                assert.SkipProperty(m => m.TitleResource, "TitleResource is null or empty. Skipping.");
                assert.SkipProperty(m => m.DescriptionResource, "DescriptionResource is null or empty. Skipping.");
            }
        }
示例#10
0
        public override void WithResolvingModelHost(ModelHostResolveContext modelHostContext)
        {
            var modelHost      = modelHostContext.ModelHost;
            var model          = modelHostContext.Model;
            var childModelType = modelHostContext.ChildModelType;
            var action         = modelHostContext.Action;

            var listModelHost = modelHost.WithAssertAndCast <ListModelHost>("modelHost", value => value.RequireNotNull());

            var web  = listModelHost.HostWeb;
            var list = listModelHost.HostList;

            var listViewDefinition = model as ListViewDefinition;
            var context            = web.Context;

            if (typeof(WebPartDefinitionBase).IsAssignableFrom(childModelType) ||
                childModelType == typeof(DeleteWebPartsDefinition))
            {
                var targetView            = FindView(list, listViewDefinition);
                var serverRelativeFileUrl = string.Empty;

                Folder targetFolder = null;

                if (list.BaseType == BaseType.DocumentLibrary)
                {
                    targetFolder = FolderModelHandler.GetLibraryFolder(list.RootFolder, "Forms");
                }

                if (targetView != null)
                {
                    serverRelativeFileUrl = targetView.ServerRelativeUrl;
                }
                else
                {
                    context.Load(list.RootFolder);
                    context.ExecuteQueryWithTrace();

                    //  maybe forms files?
                    // they aren't views, but files

                    if (list.BaseType == BaseType.DocumentLibrary)
                    {
                        serverRelativeFileUrl = UrlUtility.CombineUrl(new[]
                        {
                            list.RootFolder.ServerRelativeUrl,
                            "Forms",
                            listViewDefinition.Url
                        });
                    }
                    else
                    {
                        serverRelativeFileUrl = UrlUtility.CombineUrl(new[]
                        {
                            list.RootFolder.ServerRelativeUrl,
                            listViewDefinition.Url
                        });
                    }
                }

                var file = web.GetFileByServerRelativeUrl(serverRelativeFileUrl);
                context.Load(file);
                context.ExecuteQueryWithTrace();



                var listItemHost = ModelHostBase.Inherit <ListItemModelHost>(listModelHost, itemHost =>
                {
                    itemHost.HostFolder = targetFolder;
                    //itemHost.HostListItem = folderModelHost.CurrentListItem;
                    itemHost.HostFile = file;

                    itemHost.HostList = list;
                });

                action(listItemHost);
            }
            else
            {
                action(listModelHost);
            }
        }
示例#11
0
        public override void ProvisionObjects(Web web, ProvisioningTemplate template)
        {
            Log.Info(Constants.LOGGING_SOURCE_FRAMEWORK_PROVISIONING, CoreResources.Provisioning_ObjectHandlers_ListInstances);

            if (template.Lists.Any())
            {
                var rootWeb = (web.Context as ClientContext).Site.RootWeb;
                if (!web.IsPropertyAvailable("ServerRelativeUrl"))
                {
                    web.Context.Load(web, w => w.ServerRelativeUrl);
                    web.Context.ExecuteQueryRetry();
                }

                web.Context.Load(web.Lists, lc => lc.IncludeWithDefaultProperties(l => l.RootFolder.ServerRelativeUrl));
                web.Context.ExecuteQueryRetry();
                var existingLists     = web.Lists.AsEnumerable <List>().Select(existingList => existingList.RootFolder.ServerRelativeUrl).ToList();
                var serverRelativeUrl = web.ServerRelativeUrl;

                var createdLists = new List <ListInfo>();

                #region Lists

                foreach (var list in template.Lists)
                {
                    if (existingLists.FindIndex(x => x.Equals(UrlUtility.Combine(serverRelativeUrl, list.Url), StringComparison.OrdinalIgnoreCase)) == -1)
                    {
                        var listCreate = new ListCreationInformation();
                        listCreate.Description  = list.Description;
                        listCreate.TemplateType = list.TemplateType;
                        listCreate.Title        = list.Title;

                        // the line of code below doesn't add the list to QuickLaunch
                        // the OnQuickLaunch property is re-set on the Created List object
                        listCreate.QuickLaunchOption = list.OnQuickLaunch ? QuickLaunchOptions.On : QuickLaunchOptions.Off;

                        listCreate.Url = list.Url.ToParsedString();
                        listCreate.TemplateFeatureId = list.TemplateFeatureID;

                        var createdList = web.Lists.Add(listCreate);
                        createdList.Update();
                        web.Context.Load(createdList, l => l.BaseTemplate);
                        web.Context.ExecuteQueryRetry();

                        if (!String.IsNullOrEmpty(list.DocumentTemplate))
                        {
                            createdList.DocumentTemplateUrl = list.DocumentTemplate.ToParsedString();
                        }

                        // EnableAttachments are not supported for DocumentLibraries and Surveys
                        // TODO: the user should be warned
                        if (createdList.BaseTemplate != (int)ListTemplateType.DocumentLibrary && createdList.BaseTemplate != (int)ListTemplateType.Survey)
                        {
                            createdList.EnableAttachments = list.EnableAttachments;
                        }

                        createdList.EnableModeration = list.EnableModeration;

                        createdList.EnableVersioning = list.EnableVersioning;
                        if (list.EnableVersioning)
                        {
                            createdList.MajorVersionLimit = list.MaxVersionLimit;

                            if (createdList.BaseTemplate == (int)ListTemplateType.DocumentLibrary)
                            {
                                // Only supported on Document Libraries
                                createdList.EnableMinorVersions    = list.EnableMinorVersions;
                                createdList.DraftVersionVisibility = (DraftVisibilityType)list.DraftVersionVisibility;

                                // TODO: User should be notified that MinorVersionLimit and DraftVersionVisibility will not be applied
                                if (list.EnableMinorVersions)
                                {
                                    createdList.MajorWithMinorVersionsLimit = list.MinorVersionLimit; // Set only if enabled, otherwise you'll get exception due setting value to zero.

                                    // DraftVisibilityType.Approver is available only when the EnableModeration option of the list is true
                                    if (DraftVisibilityType.Approver ==
                                        (DraftVisibilityType)list.DraftVersionVisibility)
                                    {
                                        if (list.EnableModeration)
                                        {
                                            createdList.DraftVersionVisibility =
                                                (DraftVisibilityType)list.DraftVersionVisibility;
                                        }
                                        else
                                        {
                                            // TODO: User should be notified that DraftVersionVisibility is not applied because .EnableModeration is false
                                        }
                                    }
                                    else
                                    {
                                        createdList.DraftVersionVisibility = (DraftVisibilityType)list.DraftVersionVisibility;
                                    }
                                }
                            }
                        }

                        createdList.OnQuickLaunch = list.OnQuickLaunch;
                        if (createdList.BaseTemplate != (int)ListTemplateType.DiscussionBoard)
                        {
                            createdList.EnableFolderCreation = list.EnableFolderCreation;
                        }
                        createdList.Hidden = list.Hidden;
                        createdList.ContentTypesEnabled = list.ContentTypesEnabled;

                        createdList.Update();

                        web.Context.Load(createdList.Views);
                        web.Context.Load(createdList, l => l.Id);
                        web.Context.Load(createdList, l => l.RootFolder.ServerRelativeUrl);
                        web.Context.Load(createdList.ContentTypes);
                        web.Context.ExecuteQueryRetry();

                        // Remove existing content types only if there are custom content type bindings
                        List <Microsoft.SharePoint.Client.ContentType> contentTypesToRemove =
                            new List <Microsoft.SharePoint.Client.ContentType>();
                        if (list.RemoveExistingContentTypes && list.ContentTypeBindings.Count > 0)
                        {
                            foreach (var ct in createdList.ContentTypes)
                            {
                                contentTypesToRemove.Add(ct);
                            }
                        }

                        ContentTypeBinding defaultCtBinding = null;
                        foreach (var ctBinding in list.ContentTypeBindings)
                        {
                            createdList.AddContentTypeToListById(ctBinding.ContentTypeId, searchContentTypeInSiteHierarchy: true);
                            if (ctBinding.Default)
                            {
                                defaultCtBinding = ctBinding;
                            }
                        }

                        // default ContentTypeBinding should be set last because
                        // list extension .SetDefaultContentTypeToList() re-sets
                        // the list.RootFolder UniqueContentTypeOrder property
                        // which may cause missing CTs from the "New Button"
                        if (defaultCtBinding != null)
                        {
                            createdList.SetDefaultContentTypeToList(defaultCtBinding.ContentTypeId);
                        }

                        // Effectively remove existing content types, if any
                        foreach (var ct in contentTypesToRemove)
                        {
                            ct.DeleteObject();
                            web.Context.ExecuteQueryRetry();
                        }
                        createdLists.Add(new ListInfo {
                            CreatedList = createdList, ListInstance = list
                        });

                        TokenParser.AddToken(new ListIdToken(web, list.Title, createdList.Id));

                        TokenParser.AddToken(new ListUrlToken(web, list.Title, createdList.RootFolder.ServerRelativeUrl.Substring(web.ServerRelativeUrl.Length + 1)));
                    }
                }

                #endregion

                #region FieldRefs

                foreach (var listInfo in createdLists)
                {
                    if (listInfo.ListInstance.FieldRefs.Any())
                    {
                        foreach (var fieldRef in listInfo.ListInstance.FieldRefs)
                        {
                            var field = rootWeb.GetFieldById <Field>(fieldRef.Id);
                            if (field != null)
                            {
                                if (!listInfo.CreatedList.FieldExistsById(fieldRef.Id))
                                {
                                    var createdField = listInfo.CreatedList.Fields.Add(field);
                                    if (!string.IsNullOrEmpty(fieldRef.DisplayName))
                                    {
                                        createdField.Title = fieldRef.DisplayName;
                                    }
                                    createdField.Hidden   = fieldRef.Hidden;
                                    createdField.Required = fieldRef.Required;

                                    createdField.Update();
                                }
                            }
                        }
                        listInfo.CreatedList.Update();
                        web.Context.ExecuteQueryRetry();
                    }
                }

                #endregion

                #region Fields

                foreach (var listInfo in createdLists)
                {
                    if (listInfo.ListInstance.Fields.Any())
                    {
                        foreach (var field in listInfo.ListInstance.Fields)
                        {
                            XElement fieldElement = XElement.Parse(field.SchemaXml.ToParsedString());
                            var      id           = fieldElement.Attribute("ID").Value;

                            Guid fieldGuid = Guid.Empty;
                            if (Guid.TryParse(id, out fieldGuid))
                            {
                                if (!listInfo.CreatedList.FieldExistsById(fieldGuid))
                                {
                                    var listIdentifier = fieldElement.Attribute("List") != null?fieldElement.Attribute("List").Value : null;

                                    if (listIdentifier != null)
                                    {
                                        // Temporary remove list attribute from fieldElement
                                        fieldElement.Attribute("List").Remove();
                                    }

                                    var fieldXml = fieldElement.ToString();
                                    listInfo.CreatedList.Fields.AddFieldAsXml(fieldXml, false, AddFieldOptions.DefaultValue);
                                }
                            }
                        }
                    }
                    listInfo.CreatedList.Update();
                    web.Context.ExecuteQueryRetry();
                }

                #endregion


                #region Views

                foreach (var listInfo in createdLists)
                {
                    var list        = listInfo.ListInstance;
                    var createdList = listInfo.CreatedList;

                    if (list.Views.Any() && list.RemoveExistingViews)
                    {
                        while (createdList.Views.Any())
                        {
                            createdList.Views[0].DeleteObject();
                        }
                        web.Context.ExecuteQueryRetry();
                    }

                    foreach (var view in list.Views)
                    {
                        var viewDoc = XDocument.Parse(view.SchemaXml);

                        var displayNameXml = viewDoc.Root.Attribute("DisplayName");
                        if (displayNameXml == null)
                        {
                            throw new ApplicationException("Invalid View element, missing a valid value for the attribute DisplayName.");
                        }
                        var viewTitle = displayNameXml.Value;

                        // Type
                        var viewTypeString = viewDoc.Root.Attribute("Type") != null?viewDoc.Root.Attribute("Type").Value : "None";

                        viewTypeString = viewTypeString[0].ToString().ToUpper() + viewTypeString.Substring(1).ToLower();
                        var viewType = (ViewType)Enum.Parse(typeof(ViewType), viewTypeString);

                        // Fields
                        string[] viewFields        = null;
                        var      viewFieldsElement = viewDoc.Descendants("ViewFields").FirstOrDefault();
                        if (viewFieldsElement != null)
                        {
                            viewFields = (from field in viewDoc.Descendants("ViewFields").Descendants("FieldRef") select field.Attribute("Name").Value).ToArray();
                        }

                        // Default view
                        var viewDefault = viewDoc.Root.Attribute("DefaultView") != null && Boolean.Parse(viewDoc.Root.Attribute("DefaultView").Value);

                        // Row limit
                        bool viewPaged       = true;
                        uint viewRowLimit    = 30;
                        var  rowLimitElement = viewDoc.Descendants("RowLimit").FirstOrDefault();
                        if (rowLimitElement != null)
                        {
                            if (rowLimitElement.Attribute("Paged") != null)
                            {
                                viewPaged = bool.Parse(rowLimitElement.Attribute("Paged").Value);
                            }
                            viewRowLimit = uint.Parse(rowLimitElement.Value);
                        }

                        // Query
                        var viewQuery = new StringBuilder();
                        foreach (var queryElement in viewDoc.Descendants("Query").Elements())
                        {
                            viewQuery.Append(queryElement.ToString());
                        }

                        var viewCI = new ViewCreationInformation
                        {
                            ViewFields       = viewFields,
                            RowLimit         = viewRowLimit,
                            Paged            = viewPaged,
                            Title            = viewTitle,
                            Query            = viewQuery.ToString(),
                            ViewTypeKind     = viewType,
                            PersonalView     = false,
                            SetAsDefaultView = viewDefault
                        };

                        createdList.Views.Add(viewCI);
                        createdList.Update();
                        web.Context.ExecuteQueryRetry();
                    }

                    // Removing existing views set the OnQuickLaunch option to false and need to be re-set.
                    if (list.OnQuickLaunch && list.RemoveExistingViews && list.Views.Count > 0)
                    {
                        createdList.RefreshLoad();
                        web.Context.ExecuteQueryRetry();
                        createdList.OnQuickLaunch = list.OnQuickLaunch;
                        createdList.Update();
                        web.Context.ExecuteQueryRetry();
                    }
                }



                #endregion

                #region DataRows

                foreach (var listInfo in createdLists)
                {
                    var listInstance = listInfo.ListInstance;
                    if (listInstance.DataRows != null && listInstance.DataRows.Any())
                    {
                        var list = listInfo.CreatedList;
                        foreach (var dataRow in listInfo.ListInstance.DataRows)
                        {
                            ListItemCreationInformation listitemCI = new ListItemCreationInformation();
                            var listitem = list.AddItem(listitemCI);
                            foreach (var dataValue in dataRow.Values)
                            {
                                listitem[dataValue.Key.ToParsedString()] = dataValue.Value.ToParsedString();
                            }
                            listitem.Update();
                            web.Context.ExecuteQueryRetry(); // TODO: Run in batches?
                        }
                    }
                }

                #endregion
            }
        }
        public void GenerateOAuthCallbackUrlTest()
        {
#if NET45
            Func <string, string, string, HttpContextBase> getHttpContextBase = (url, queryString, baseUrl) =>
            {
                var context  = new Mock <HttpContextBase>();
                var request  = new Mock <HttpRequestBase>();
                var response = new Mock <HttpResponseBase>();

                request.Setup(r => r.Url).Returns(new Uri(url));
                request.Setup(r => r.ApplicationPath).Returns(baseUrl);

                context.Setup(c => c.Request).Returns(request.Object);
                context.Setup(c => c.Response).Returns(response.Object);
                context.Setup(c => c.Response).Returns(response.Object);
                return(context.Object);

                var httpContext     = new HttpContext(new HttpRequest("Senparc", url, queryString), new HttpResponse(null));
                var httpContextBase = new HttpContextWrapper(httpContext);

                return(httpContextBase);
            };
#else
            Func <string, string, string, HttpContext> getHttpContextBase = (url, queryString, baseUrl) =>
            {
                var uri = new Uri(url);

                var scheme = uri.Scheme;
                var path   = uri.LocalPath;

                var httpContext = new DefaultHttpContext();
                httpContext.Request.Path        = path;
                httpContext.Request.Host        = new HostString(uri.Host, uri.Port);
                httpContext.Request.Scheme      = scheme;
                httpContext.Request.QueryString = new QueryString(uri.Query);
                httpContext.Request.PathBase    = baseUrl;
                return(httpContext);
            };
#endif

            string virtualPath = null;//虚拟路径

            {
                var httpContext = getHttpContextBase("https://sdk.weixin.senparc.com/Home/Index", "", virtualPath);
                var callbackUrl = UrlUtility.GenerateOAuthCallbackUrl(httpContext, "/TenpayV3/OAuthCallback");
                Console.WriteLine("\r\n普通 HTTP Url:" + callbackUrl);
                Assert.AreEqual(
                    "https://sdk.weixin.senparc.com/TenpayV3/OAuthCallback?returnUrl=http%3a%2f%2fsdk.weixin.senparc.com%2fHome%2fIndex",
                    callbackUrl, true);
            }


            {
                var httpContext = getHttpContextBase("https://sdk.weixin.senparc.com/Home/Index?a=1&b=2&c=3-1", "a=1&b=2&c=3-1", virtualPath);
                var callbackUrl = UrlUtility.GenerateOAuthCallbackUrl(httpContext, "/TenpayV3/OAuthCallback");
                Console.WriteLine("\r\n带参数 HTTP Url:" + callbackUrl);
                Assert.AreEqual(
                    "https://sdk.weixin.senparc.com/TenpayV3/OAuthCallback?returnUrl=http%3a%2f%2fsdk.weixin.senparc.com%2fHome%2fIndex%3fa%3d1%26b%3d2%26c%3d3-1",
                    callbackUrl, true);
            }


            {
                var httpContext = getHttpContextBase("https://sdk.weixin.senparc.com:8080/Home/Index?a=1&b=2&c=3-1", "a=1&b=2&c=3-1", virtualPath);
                var callbackUrl = UrlUtility.GenerateOAuthCallbackUrl(httpContext, "/TenpayV3/OAuthCallback");
                Console.WriteLine("\r\n带参数、带端口 HTTP Url:" + callbackUrl);
                Assert.AreEqual(
                    "https://sdk.weixin.senparc.com:8080/TenpayV3/OAuthCallback?returnUrl=http%3a%2f%2fsdk.weixin.senparc.com%3a8080%2fHome%2fIndex%3fa%3d1%26b%3d2%26c%3d3-1",
                    callbackUrl, true);
            }

            {
                var httpContext = getHttpContextBase("https://sdk.weixin.senparc.com/Home/Index", "", virtualPath);
                var callbackUrl = UrlUtility.GenerateOAuthCallbackUrl(httpContext, "/TenpayV3/OAuthCallback");
                Console.WriteLine("\r\n普通 HTTPS Url:" + callbackUrl);
                Assert.AreEqual(
                    "https://sdk.weixin.senparc.com/TenpayV3/OAuthCallback?returnUrl=https%3a%2f%2fsdk.weixin.senparc.com%2fHome%2fIndex",
                    callbackUrl, true);
            }

            {
                var httpContext = getHttpContextBase("https://sdk.weixin.senparc.com/Home/Index?a=1&b=2&c=3-1", "a=1&b=2&c=3-1", virtualPath);
                var callbackUrl = UrlUtility.GenerateOAuthCallbackUrl(httpContext, "/TenpayV3/OAuthCallback");
                Console.WriteLine("\r\n带参数 HTTPS Url:" + callbackUrl);
                Assert.AreEqual(
                    "https://sdk.weixin.senparc.com/TenpayV3/OAuthCallback?returnUrl=https%3a%2f%2fsdk.weixin.senparc.com%2fHome%2fIndex%3fa%3d1%26b%3d2%26c%3d3-1",
                    callbackUrl, true);
            }

            {
                var httpContext = getHttpContextBase("https://sdk.weixin.senparc.com:1433/Home/Index?a=1&b=2&c=3-1", "a=1&b=2&c=3-1", virtualPath);
                var callbackUrl = UrlUtility.GenerateOAuthCallbackUrl(httpContext, "/TenpayV3/OAuthCallback");
                Console.WriteLine("\r\n带参数、带端口 HTTPS Url:" + callbackUrl);
                Assert.AreEqual(
                    "https://sdk.weixin.senparc.com:1433/TenpayV3/OAuthCallback?returnUrl=https%3a%2f%2fsdk.weixin.senparc.com%3a1433%2fHome%2fIndex%3fa%3d1%26b%3d2%26c%3d3-1",
                    callbackUrl, true);
            }

            //虚拟路径
            {
                virtualPath = "/VirtualPath";
                var httpContext = getHttpContextBase("https://sdk.weixin.senparc.com:1433/VirtualPath/Home/Index?a=1&b=2&c=3-1", "a=1&b=2&c=3-1", virtualPath);
                //Console.WriteLine("\r\nhttpContext.Request.AbsoluteUri():"+httpContext.Request.AbsoluteUri());
                var callbackUrl = UrlUtility.GenerateOAuthCallbackUrl(httpContext, "/TenpayV3/OAuthCallback");
                Console.WriteLine("\r\n带参数、带端口 HTTPS Url:" + callbackUrl);

#if NET35 || NET40 || NET45
                var expectedUrl = "https://sdk.weixin.senparc.com:1433/VirtualPath/TenpayV3/OAuthCallback?returnUrl=https%3a%2f%2fsdk.weixin.senparc.com%3a1433%2fVirtualPath%2fHome%2fIndex%3fa%3d1%26b%3d2%26c%3d3-1";
#else
                //.NET Standard(.NET Core)下因为模拟会存在偏差(无法自动识别Url中的VirtualPath为特殊的虚拟目录,所以会出现重复),因此以下结果是可以接受的
                var expectedUrl = "https://sdk.weixin.senparc.com:1433/VirtualPath/TenpayV3/OAuthCallback?returnUrl=https%3a%2f%2fsdk.weixin.senparc.com%3a1433%2fVirtualPath%2fVirtualPath%2fHome%2fIndex%3fa%3d1%26b%3d2%26c%3d3-1";
#endif
                Assert.AreEqual(expectedUrl, callbackUrl, true);
            }
        }
示例#13
0
 public override string ToString()
 {
     return($"{Title} ({UrlUtility.GetServerRelativeUrl(Url)})");
 }
        /// <summary>
        /// Ensures that we have context of the source site collection
        /// </summary>
        /// <param name="context">Source site context</param>
        internal void EnsureAssetContextIfRequired(ClientContext context, string sourceUrl)
        {
            // There is two scenarios to check
            //  - If the asset resides on the root site collection
            //  - If the asset resides on another subsite
            //  - If the asset resides on a subsite below this context

            try
            {
                context.Site.EnsureProperties(o => o.ServerRelativeUrl, o => o.Url, o => o.RootWeb.Id);
                context.Web.EnsureProperties(o => o.ServerRelativeUrl, o => o.Id);

                string match = string.Empty;

                // Break the URL into segments and deteremine which URL detects the file in the structure.
                // Use Web IDs to validate content isnt the same on the root

                var fullSiteCollectionUrl = context.Site.Url;
                var relativeSiteCollUrl   = context.Site.ServerRelativeUrl;
                var sourceCtxUrl          = context.Web.GetUrl();

                // Lets break into segments
                var fileName = Path.GetFileName(sourceUrl);

                // Could already be relative
                //var sourceUrlWithOutBaseAddr = sourceUrl.Replace(fullSiteCollectionUrl, "").Replace(relativeSiteCollUrl,"");
                var urlSegments = sourceUrl.Split('/');

                // Need null tests
                var filteredUrlSegments = urlSegments.Where(o => !string.IsNullOrEmpty(o) && o != fileName).Reverse();

                //Assume the last segment is the filename
                //Assume the segment before the last is either a folder or library

                //Url to strip back until detected as subweb
                var remainingUrl = sourceUrl.Replace(fileName, "");     //remove file name

                //Urls to try to determine web
                foreach (var segment in filteredUrlSegments)     //Assume the segment before the last is either a folder or library
                {
                    try
                    {
                        var testUrl = UrlUtility.Combine(fullSiteCollectionUrl.ToLower(), remainingUrl.ToLower().Replace(relativeSiteCollUrl.ToLower(), ""));

                        //No need to recurse this
                        var exists = context.WebExistsFullUrl(testUrl);

                        if (exists)
                        {
                            //winner
                            match = testUrl;
                            break;
                        }
                        else
                        {
                            remainingUrl = remainingUrl.TrimEnd('/').TrimEnd($"{segment}".ToCharArray());
                        }
                    }
                    catch
                    {
                        // Nope not the right web - Swallow
                    }
                }

                // Check if the asset is on the root site collection
                if (match == string.Empty)
                {
                    // Does it contain a relative reference
                    if (sourceUrl.StartsWith("/") && !sourceUrl.ContainsIgnoringCasing(context.Web.GetUrl()))
                    {
                        match = fullSiteCollectionUrl.ToLower();
                    }
                }

                if (match != string.Empty && !match.Equals(context.Web.GetUrl(), StringComparison.InvariantCultureIgnoreCase))
                {
                    _sourceClientContext = context.Clone(match);
                    LogDebug("Source Context Switched", "EsureAssetContextIfRequired");
                }
            }
            catch (Exception ex)
            {
                LogError(LogStrings.Error_CannotGetSiteCollContext, LogStrings.Heading_AssetTransfer, ex);
            }
        }
示例#15
0
        private void ExtractMasterPagesAndPageLayouts(Web web, ProvisioningTemplate template, PnPMonitoredScope scope, ProvisioningTemplateCreationInformation creationInfo)
        {
            web.EnsureProperty(w => w.Url);
            String webApplicationUrl = GetWebApplicationUrl(web.Url);

            if (!String.IsNullOrEmpty(webApplicationUrl))
            {
                // Get the Publishing Feature reference template
                ProvisioningTemplate publishingFeatureTemplate = GetPublishingFeatureBaseTemplate();

                // Get a reference to the root folder of the master page gallery
                var gallery = web.GetCatalog(116);
                web.Context.Load(gallery, g => g.RootFolder);
                web.Context.ExecuteQueryRetry();

                var masterPageGalleryFolder = gallery.RootFolder;

                // Load the files in the master page gallery
                web.Context.Load(masterPageGalleryFolder.Files);
                web.Context.ExecuteQueryRetry();


                var sourceFiles = GetFiles(masterPageGalleryFolder).Where(
                    f => f.Name.EndsWith(".aspx", StringComparison.InvariantCultureIgnoreCase) ||
                    f.Name.EndsWith(".html", StringComparison.InvariantCultureIgnoreCase) ||
                    f.Name.EndsWith(".master", StringComparison.InvariantCultureIgnoreCase));

                /*var sourceFiles = masterPageGalleryFolder.Files.AsEnumerable().Where(
                 *  f => f.Name.EndsWith(".aspx", StringComparison.InvariantCultureIgnoreCase) ||
                 *  f.Name.EndsWith(".html", StringComparison.InvariantCultureIgnoreCase) ||
                 *  f.Name.EndsWith(".master", StringComparison.InvariantCultureIgnoreCase));
                 */

                foreach (var file in sourceFiles)
                {
                    var listItem = file.EnsureProperty(f => f.ListItemAllFields);

                    if (!listItem.ServerObjectIsNull())
                    {
                        listItem.ContentType.EnsureProperties(ct => ct.Id, ct => ct.StringId);

                        // Check if the content type is of type Master Page or Page Layout
                        if (listItem.ContentType.StringId.StartsWith(MASTER_PAGE_CONTENT_TYPE_ID) ||
                            listItem.ContentType.StringId.StartsWith(PAGE_LAYOUT_CONTENT_TYPE_ID) ||
                            listItem.ContentType.StringId.StartsWith(ASP_NET_MASTER_PAGE_CONTENT_TYPE_ID) ||
                            listItem.ContentType.StringId.StartsWith(HTML_PAGE_LAYOUT_CONTENT_TYPE_ID))
                        {
                            // Skip any .ASPX or .MASTER file related to an .HTML designer file
                            if ((file.Name.EndsWith(".aspx", StringComparison.InvariantCultureIgnoreCase) &&
                                 sourceFiles.Any(f => f.Name.Equals(file.Name.ToLower().Replace(".aspx", ".html"),
                                                                    StringComparison.InvariantCultureIgnoreCase))) ||
                                (file.Name.EndsWith(".master", StringComparison.InvariantCultureIgnoreCase) &&
                                 sourceFiles.Any(f => f.Name.Equals(file.Name.ToLower().Replace(".master", ".html"),
                                                                    StringComparison.InvariantCultureIgnoreCase))))
                            {
                                continue;
                            }

                            // If the file is a custom one, and not one native
                            // and coming out from the publishing feature
                            if (creationInfo.IncludeNativePublishingFiles ||
                                !IsPublishingFeatureNativeFile(publishingFeatureTemplate, file.Name))
                            {
                                var fullUri = new Uri(UrlUtility.Combine(webApplicationUrl, file.ServerRelativeUrl));

                                var folderPath = fullUri.Segments.Take(fullUri.Segments.Count() - 1).ToArray().Aggregate((i, x) => i + x).TrimEnd('/');
                                var fileName   = fullUri.Segments[fullUri.Segments.Count() - 1];

                                web.EnsureProperty(w => web.ServerRelativeUrl);
                                file.EnsureProperty(f => f.Level);

                                var containerPath = folderPath.StartsWith(web.ServerRelativeUrl) && web.ServerRelativeUrl != "/"  ? folderPath.Substring(web.ServerRelativeUrl.Length) : folderPath;
                                var container     = HttpUtility.UrlDecode(containerPath).Trim('/').Replace("/", "\\");

                                var publishingFile = new Model.File()
                                {
                                    Folder    = Tokenize(folderPath, web.Url),
                                    Src       = !string.IsNullOrEmpty(container) ? $"{container}\\{HttpUtility.UrlDecode(fileName)}" : HttpUtility.UrlDecode(fileName),
                                    Overwrite = true,
                                    Level     = (Model.FileLevel)Enum.Parse(typeof(Model.FileLevel), file.Level.ToString())
                                };

                                // Add field values to file
                                RetrieveFieldValues(web, file, publishingFile);

                                // Add the file to the template
                                template.Files.Add(publishingFile);

                                // Persist file using connector, if needed
                                if (creationInfo.PersistPublishingFiles)
                                {
                                    PersistFile(web, creationInfo, scope, folderPath, fileName, true);
                                }

                                if (listItem.ContentType.StringId.StartsWith(MASTER_PAGE_CONTENT_TYPE_ID))
                                {
                                    scope.LogWarning($@"The file ""{file.Name}"" is a custom MasterPage. Accordingly to the PnP Guidance (http://aka.ms/o365pnpguidancemasterpages) you should try to avoid using custom MasterPages.");
                                }
                            }
                            else
                            {
                                scope.LogWarning($@"Skipping file ""{file.Name}"" because it is native in the publishing feature.");
                            }
                        }
                    }
                }
            }
        }
示例#16
0
        public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                // Extract the Home Page
                web.EnsureProperties(w => w.RootFolder.WelcomePage, w => w.ServerRelativeUrl, w => w.Url);

                var homepageUrl = web.RootFolder.WelcomePage;
                if (string.IsNullOrEmpty(homepageUrl))
                {
                    homepageUrl = "Default.aspx";
                }
                var welcomePageUrl = UrlUtility.Combine(web.ServerRelativeUrl, homepageUrl);

                var file = web.GetFileByServerRelativeUrl(welcomePageUrl);
                try
                {
                    var listItem = file.EnsureProperty(f => f.ListItemAllFields);
                    if (listItem != null)
                    {
                        if (listItem.FieldValues.ContainsKey("WikiField"))
                        {
                            // Wiki page
                            var fullUri = new Uri(UrlUtility.Combine(web.Url, web.RootFolder.WelcomePage));

                            var folderPath = fullUri.Segments.Take(fullUri.Segments.Count() - 1).ToArray().Aggregate((i, x) => i + x).TrimEnd('/');
                            var fileName   = fullUri.Segments[fullUri.Segments.Count() - 1];

                            var homeFile = web.GetFileByServerRelativeUrl(welcomePageUrl);

                            LimitedWebPartManager limitedWPManager =
                                homeFile.GetLimitedWebPartManager(PersonalizationScope.Shared);

                            web.Context.Load(limitedWPManager);

                            var webParts = web.GetWebParts(welcomePageUrl);

                            var page = new Page()
                            {
                                Layout    = WikiPageLayout.Custom,
                                Overwrite = true,
                                Url       = Tokenize(fullUri.PathAndQuery, web.Url),
                            };
                            var pageContents = listItem.FieldValues["WikiField"].ToString();

                            Regex regexClientIds = new Regex(@"id=\""div_(?<ControlId>(\w|\-)+)");
                            if (regexClientIds.IsMatch(pageContents))
                            {
                                foreach (Match webPartMatch in regexClientIds.Matches(pageContents))
                                {
                                    String serverSideControlId = webPartMatch.Groups["ControlId"].Value;

                                    try
                                    {
                                        String serverSideControlIdToSearchFor = String.Format("g_{0}",
                                                                                              serverSideControlId.Replace("-", "_"));

                                        WebPartDefinition webPart = limitedWPManager.WebParts.GetByControlId(serverSideControlIdToSearchFor);
                                        web.Context.Load(webPart,
                                                         wp => wp.Id,
                                                         wp => wp.WebPart.Title,
                                                         wp => wp.WebPart.ZoneIndex
                                                         );
                                        web.Context.ExecuteQueryRetry();

                                        var webPartxml = TokenizeWebPartXml(web, web.GetWebPartXml(webPart.Id, welcomePageUrl));

                                        page.WebParts.Add(new Model.WebPart()
                                        {
                                            Title    = webPart.WebPart.Title,
                                            Contents = webPartxml,
                                            Order    = (uint)webPart.WebPart.ZoneIndex,
                                            Row      = 1, // By default we will create a onecolumn layout, add the webpart to it, and later replace the wikifield on the page to position the webparts correctly.
                                            Column   = 1  // By default we will create a onecolumn layout, add the webpart to it, and later replace the wikifield on the page to position the webparts correctly.
                                        });

                                        pageContents = Regex.Replace(pageContents, serverSideControlId, string.Format("{{webpartid:{0}}}", webPart.WebPart.Title), RegexOptions.IgnoreCase);
                                    }
                                    catch (ServerException)
                                    {
                                        scope.LogWarning("Found a WebPart ID which is not available on the server-side. ID: {0}", serverSideControlId);
                                    }
                                }
                            }

                            page.Fields.Add("WikiField", pageContents);
                            template.Pages.Add(page);

                            // Set the homepage
                            if (template.WebSettings == null)
                            {
                                template.WebSettings = new WebSettings();
                            }
                            template.WebSettings.WelcomePage = homepageUrl;
                        }
                        else
                        {
                            if (web.Context.HasMinimalServerLibraryVersion(Constants.MINIMUMZONEIDREQUIREDSERVERVERSION))
                            {
                                // Not a wikipage
                                template = GetFileContents(web, template, welcomePageUrl, creationInfo, scope);
                                if (template.WebSettings == null)
                                {
                                    template.WebSettings = new WebSettings();
                                }
                                template.WebSettings.WelcomePage = homepageUrl;
                            }
                            else
                            {
                                WriteWarning(string.Format("Page content export requires a server version that is newer than the current server. Server version is {0}, minimal required is {1}", web.Context.ServerLibraryVersion, Constants.MINIMUMZONEIDREQUIREDSERVERVERSION), ProvisioningMessageType.Warning);
                                scope.LogWarning("Page content export requires a server version that is newer than the current server. Server version is {0}, minimal required is {1}", web.Context.ServerLibraryVersion, Constants.MINIMUMZONEIDREQUIREDSERVERVERSION);
                            }
                        }
                    }
                }
                catch (ServerException ex)
                {
                    if (ex.ServerErrorCode != -2146232832)
                    {
                        throw;
                    }
                    else
                    {
                        if (web.Context.HasMinimalServerLibraryVersion(Constants.MINIMUMZONEIDREQUIREDSERVERVERSION))
                        {
                            // Page does not belong to a list, extract the file as is
                            template = GetFileContents(web, template, welcomePageUrl, creationInfo, scope);
                            if (template.WebSettings == null)
                            {
                                template.WebSettings = new WebSettings();
                            }
                            template.WebSettings.WelcomePage = homepageUrl;
                        }
                        else
                        {
                            WriteWarning(string.Format("Page content export requires a server version that is newer than the current server. Server version is {0}, minimal required is {1}", web.Context.ServerLibraryVersion, Constants.MINIMUMZONEIDREQUIREDSERVERVERSION), ProvisioningMessageType.Warning);
                            scope.LogWarning("Page content export requires a server version that is newer than the current server. Server version is {0}, minimal required is {1}", web.Context.ServerLibraryVersion, Constants.MINIMUMZONEIDREQUIREDSERVERVERSION);
                        }
                    }
                }

                // If a base template is specified then use that one to "cleanup" the generated template model
                if (creationInfo.BaseTemplate != null)
                {
                    template = CleanupEntities(template, creationInfo.BaseTemplate);
                }
            }
            return(template);
        }
示例#17
0
        internal ListItem GetPage(Web web, string listToLoad)
        {
            // Check what we got via the pagepipebind constructor and prep for getting the page
            if (!string.IsNullOrEmpty(this.name))
            {
                if (!this.BlogPage)
                {
                    this.name = ClientSidePageUtilities.EnsureCorrectPageName(this.name);
                }
                this.pageListItem = null;
            }
            else if (this.pageListItem != null)
            {
                if (this.pageListItem != null)
                {
                    if (this.BlogPage)
                    {
                        this.name = this.pageListItem.FieldValues["Title"].ToString();
                    }
                    else
                    {
                        this.name = this.pageListItem.FieldValues["FileLeafRef"].ToString();
                    }
                }
            }

            if (!string.IsNullOrEmpty(this.Library))
            {
                listToLoad = this.Library;
            }

            // Blogs live in a list, not in a library
            if (this.BlogPage && !listToLoad.StartsWith("lists/", StringComparison.InvariantCultureIgnoreCase))
            {
                listToLoad = $"lists/{listToLoad}";
            }

            web.EnsureProperty(w => w.ServerRelativeUrl);
            var listServerRelativeUrl = UrlUtility.Combine(web.ServerRelativeUrl, listToLoad);

            List libraryContainingPage = null;

            if (BaseTransform.GetVersion(web.Context) == SPVersion.SP2010)
            {
                libraryContainingPage = web.GetListByName(listToLoad);
            }
            else
            {
                libraryContainingPage = web.GetList(listServerRelativeUrl);
            }

            if (libraryContainingPage != null)
            {
                CamlQuery query = null;
                if (!string.IsNullOrEmpty(this.name))
                {
                    if (this.BlogPage)
                    {
                        query = new CamlQuery
                        {
                            ViewXml = string.Format(CAMLQueryForBlogByTitle, this.name)
                        };
                    }
                    else
                    {
                        query = new CamlQuery
                        {
                            ViewXml = string.Format(CAMLQueryByExtensionAndName, this.name)
                        };
                    }

                    if (!string.IsNullOrEmpty(this.Folder))
                    {
                        libraryContainingPage.EnsureProperty(p => p.RootFolder);
                        query.FolderServerRelativeUrl = $"{libraryContainingPage.RootFolder.ServerRelativeUrl}/{Folder}";
                    }

                    var page = libraryContainingPage.GetItems(query);
                    web.Context.Load(page);
                    web.Context.ExecuteQueryRetry();

                    if (page.Count >= 1)
                    {
                        // Return the first match
                        return(page[0]);
                    }
                }
            }

            return(null);
        }
示例#18
0
        private async Task <FeedResource <Address> > GetServerAddressesViaGatewayAsync(
            DocumentServiceRequest request,
            string collectionRid,
            IEnumerable <string> partitionKeyRangeIds,
            bool forceRefresh)
        {
            string entryUrl = PathsHelper.GeneratePath(ResourceType.Document, collectionRid, true);

            INameValueCollection addressQuery = new StringKeyValueCollection();

            addressQuery.Add(HttpConstants.QueryStrings.Url, HttpUtility.UrlEncode(entryUrl));

            INameValueCollection headers = new StringKeyValueCollection();

            if (forceRefresh)
            {
                headers.Set(HttpConstants.HttpHeaders.ForceRefresh, bool.TrueString);
            }

            if (request.ForceCollectionRoutingMapRefresh)
            {
                headers.Set(HttpConstants.HttpHeaders.ForceCollectionRoutingMapRefresh, bool.TrueString);
            }

            addressQuery.Add(HttpConstants.QueryStrings.Filter, this.protocolFilter);
            addressQuery.Add(HttpConstants.QueryStrings.PartitionKeyRangeIds, string.Join(",", partitionKeyRangeIds));

            string resourceTypeToSign = PathsHelper.GetResourcePath(ResourceType.Document);

            headers.Set(HttpConstants.HttpHeaders.XDate, DateTime.UtcNow.ToString("r", CultureInfo.InvariantCulture));
            string token = null;

            try
            {
                token = this.tokenProvider.GetUserAuthorizationToken(
                    collectionRid,
                    resourceTypeToSign,
                    HttpConstants.HttpMethods.Get,
                    headers,
                    AuthorizationTokenType.PrimaryMasterKey);
            }
            catch (UnauthorizedException)
            {
            }

            if (token == null && request.IsNameBased)
            {
                // User doesn't have rid based resource token. Maybe he has name based.
                string collectionAltLink = PathsHelper.GetCollectionPath(request.ResourceAddress);
                token = this.tokenProvider.GetUserAuthorizationToken(
                    collectionAltLink,
                    resourceTypeToSign,
                    HttpConstants.HttpMethods.Get,
                    headers,
                    AuthorizationTokenType.PrimaryMasterKey);
            }

            headers.Set(HttpConstants.HttpHeaders.Authorization, token);

            Uri targetEndpoint = UrlUtility.SetQuery(this.addressEndpoint, UrlUtility.CreateQuery(addressQuery));

            string identifier = GatewayAddressCache.LogAddressResolutionStart(request, targetEndpoint);

            using (HttpResponseMessage httpResponseMessage = await this.httpClient.GetAsync(targetEndpoint, headers))
            {
                using (DocumentServiceResponse documentServiceResponse =
                           await ClientExtensions.ParseResponseAsync(httpResponseMessage))
                {
                    GatewayAddressCache.LogAddressResolutionEnd(request, identifier);

                    return(documentServiceResponse.GetResource <FeedResource <Address> >());
                }
            }
        }
示例#19
0
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            Folder targetFolder = null;
            Web    web          = null;

            if (modelHost is ListModelHost)
            {
                targetFolder = (modelHost as ListModelHost).HostList.RootFolder;
                web          = (modelHost as ListModelHost).HostWeb;
            }
            if (modelHost is FolderModelHost)
            {
                targetFolder = (modelHost as FolderModelHost).CurrentListFolder;
                web          = (modelHost as FolderModelHost).HostWeb;
            }

            var definition = model.WithAssertAndCast <WebpartPresenceOnPageDefinition>("model", value => value.RequireNotNull());

            var folder  = targetFolder;
            var allItem = folder.ListItemAllFields;

            var context = folder.Context;

            context.Load(folder, f => f.ServerRelativeUrl);
            context.Load(allItem);

            context.ExecuteQuery();

            var pageName = GetSafeWikiPageFileName(definition.PageFileName);
            var file     = web.GetFileByServerRelativeUrl(UrlUtility.CombineUrl(folder.ServerRelativeUrl, pageName));

            context.Load(file);
            context.ExecuteQueryWithTrace();

            var serverUrl = web.Url;

            if (web.ServerRelativeUrl != "/")
            {
                serverUrl = serverUrl.Replace(web.ServerRelativeUrl, string.Empty);
            }

            var pageUrl = UrlUtility.CombineUrl(new[] {
                serverUrl,
                folder.ServerRelativeUrl,
                pageName
            });

            var client = new WebClient();

            client.UseDefaultCredentials = true;

            if (context.Credentials != null)
            {
                client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
                client.Credentials = context.Credentials;
            }

            var userAgentString = "User-Agent";
            var userAgent       = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36";

            client.Headers.Add(userAgentString, userAgent);

            var pageContent = client.DownloadString(new Uri(pageUrl));

            ValidateHtmlPage(
                file,
                pageUrl,
                pageContent,
                definition);
        }
示例#20
0
        private bool PersistFile(Web web, ProvisioningTemplateCreationInformation creationInfo, PnPMonitoredScope scope, string serverRelativeUrl)
        {
            var success = false;

            if (creationInfo.PersistBrandingFiles)
            {
                if (creationInfo.FileConnector != null)
                {
                    if (UrlUtility.IsIisVirtualDirectory(serverRelativeUrl))
                    {
                        scope.LogWarning("File is not located in the content database. Not retrieving {0}", serverRelativeUrl);
                        return(success);
                    }

                    try
                    {
                        var    file     = web.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(serverRelativeUrl));
                        string fileName = string.Empty;
                        if (serverRelativeUrl.IndexOf("/") > -1)
                        {
                            fileName = serverRelativeUrl.Substring(serverRelativeUrl.LastIndexOf("/") + 1);
                        }
                        else
                        {
                            fileName = serverRelativeUrl;
                        }
                        web.Context.Load(file);
                        web.Context.ExecuteQueryRetry();
                        ClientResult <Stream> stream = file.OpenBinaryStream();
                        web.Context.ExecuteQueryRetry();

                        file.EnsureProperty(f => f.ServerRelativePath);
                        var baseUri    = new Uri(web.Url);
                        var fullUri    = new Uri(baseUri, file.ServerRelativePath.DecodedUrl);
                        var folderPath = Uri.UnescapeDataString(fullUri.Segments.Take(fullUri.Segments.Length - 1).ToArray().Aggregate((i, x) => i + x).TrimEnd('/'));

                        // Configure the filename to use
                        fileName = Uri.UnescapeDataString(fullUri.Segments[fullUri.Segments.Length - 1]);

                        // Build up a site relative container URL...might end up empty as well
                        String container = Uri.UnescapeDataString(folderPath.Replace(web.ServerRelativeUrl, "")).Trim('/').Replace("/", "\\");

                        using (Stream memStream = new MemoryStream())
                        {
                            CopyStream(stream.Value, memStream);
                            memStream.Position = 0;
                            if (!string.IsNullOrEmpty(container))
                            {
                                creationInfo.FileConnector.SaveFileStream(fileName, container, memStream);
                            }
                            else
                            {
                                creationInfo.FileConnector.SaveFileStream(fileName, memStream);
                            }
                        }
                        success = true;
                    }
                    catch (ServerException ex1)
                    {
                        // If we are referring a file from a location outside of the current web or at a location where we cannot retrieve the file an exception is thrown. We swallow this exception.
                        if (ex1.ServerErrorCode != -2147024809)
                        {
                            throw;
                        }
                        else
                        {
                            scope.LogWarning("File is not necessarily located in the current web. Not retrieving {0}", serverRelativeUrl);
                        }
                    }
                }
                else
                {
                    WriteMessage("No connector present to persist footer logo.", ProvisioningMessageType.Error);
                    scope.LogError("No connector present to persist footer logo.");
                }
            }
            else
            {
                success = true;
            }
            return(success);
        }
示例#21
0
        protected override void ExecuteCmdlet()
        {
            if (Url.StartsWith("/"))
            {
                // prefix the url with the current web url
                Url = UrlUtility.Combine(ClientContext.Url, Url);
            }

            var method = new HttpMethod(Method.ToString());

            var httpClient = PnPHttpClient.Instance.GetHttpClient(ClientContext);

            var requestUrl = Url;

            using (HttpRequestMessage request = new HttpRequestMessage(method, requestUrl))
            {
                request.Headers.Add("accept", "application/json;odata=nometadata");

                if (Method == HttpRequestMethod.Merge)
                {
                    method = HttpMethod.Post;
                    request.Headers.Add("X-HTTP-Method", "MERGE");
                }

                if (Method == HttpRequestMethod.Merge || Method == HttpRequestMethod.Delete)
                {
                    request.Headers.Add("IF-MATCH", "*");
                }

                PnPHttpClient.AuthenticateRequestAsync(request, ClientContext).GetAwaiter().GetResult();

                if (Method == HttpRequestMethod.Post)
                {
                    if (string.IsNullOrEmpty(ContentType))
                    {
                        ContentType = "application/json";
                    }
                    var contentString = Content is string?Content.ToString() :
                                            JsonSerializer.Serialize(Content);

                    request.Content = new StringContent(contentString, System.Text.Encoding.UTF8);
                    request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(ContentType);
                }
                HttpResponseMessage response = httpClient.SendAsync(request, new System.Threading.CancellationToken()).Result;

                if (response.IsSuccessStatusCode)
                {
                    var responseString = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                    if (responseString != null)
                    {
                        var jsonElement = JsonSerializer.Deserialize <JsonElement>(responseString);
                        if (jsonElement.TryGetProperty("value", out JsonElement valueProperty))
                        {
                            WriteObject(ConvertToPSObject(valueProperty), true);
                        }
                        else
                        {
                            WriteObject(ConvertToPSObject(jsonElement), true);
                        }
                    }
                }
                else
                {
                    // Something went wrong...
                    throw new Exception(response.Content.ReadAsStringAsync().GetAwaiter().GetResult());
                }
            }
        }
示例#22
0
        private string GetServerRelativeUrl(string url)
        {
            var serverRelativeUrl = SelectedWeb.EnsureProperty(w => w.ServerRelativeUrl);

            return(UrlUtility.Combine(serverRelativeUrl, url));
        }
示例#23
0
        public bool Validate(PnP.Framework.Provisioning.Model.FileCollection sourceFiles, Microsoft.SharePoint.Client.ClientContext ctx)
        {
            int scount = 0;
            int tcount = 0;

            try
            {
                // Check if this is not a noscript site as we're not allowed to write to the web property bag is that one
                bool isNoScriptSite = ctx.Web.IsNoScriptSite();

                foreach (var sf in sourceFiles)
                {
                    scount++;
                    string fileName   = sf.Src;
                    string folderName = sf.Folder;
                    string fileUrl    = UrlUtility.Combine(ctx.Web.ServerRelativeUrl, folderName + "/" + fileName);

                    // Skip the files we skipped to provision (if any)
                    if (ObjectFiles.SkipFile(isNoScriptSite, fileName, folderName))
                    {
                        continue;
                    }

                    var file = ctx.Web.GetFileByServerRelativeUrl(UrlUtility.Combine(ctx.Web.ServerRelativeUrl, folderName + "/" + fileName));
                    ctx.Load(file, f => f.Exists, f => f.Length);
                    ctx.ExecuteQueryRetry();

                    if (file.Exists)
                    {
                        tcount++;

                        #region File - Security
                        if (sf.Security != null)
                        {
                            ctx.Load(file, f => f.ListItemAllFields);
                            ctx.ExecuteQueryRetry();
                            bool isSecurityMatch = ValidateSecurityCSOM(ctx, sf.Security, file.ListItemAllFields);
                            if (!isSecurityMatch)
                            {
                                return(false);
                            }
                        }
                        #endregion

                        #region Overwrite validation
                        if (sf.Overwrite == false)
                        {
                            // lookup the original added file size...should be different from the one we retrieved from SharePoint since we opted to NOT overwrite
                            var files = System.IO.Directory.GetFiles(@".\framework\functional\templates");
                            foreach (var f in files)
                            {
                                if (f.Contains(sf.Src))
                                {
                                    if (new System.IO.FileInfo(f).Length == file.Length)
                                    {
                                        return(false);
                                    }
                                }
                            }
                        }
                        #endregion
                    }
                    else
                    {
                        return(false);
                    }
                }
            }
            catch (Exception ex)
            {
                // Return false if we get an exception
                Console.WriteLine(ex.ToDetailedString(ctx));
                return(false);
            }

            return(true);
        }
示例#24
0
        public ActionResult GenerateModuleInfo()
        {
            ModuleInfo moduleInfo = new ModuleInfo();

            moduleInfo.ModuleName           = ModuleAreaRegistration.ModuleName;
            moduleInfo.Version              = "4.2.1.0";
            moduleInfo.KoobooCMSVersion     = "4.2.1.0";
            moduleInfo.InstallingTemplate   = UrlUtility.Combine("Views", "Shared", "_OnInstalling.cshtml");
            moduleInfo.UninstallingTemplate = UrlUtility.Combine("Views", "Shared", "_OnUninstalling.cshtml");
            moduleInfo.DefaultSettings      = new ModuleSettings()
            {
                ThemeName = "Default",
                Entry     = new Entry()
                {
                    Controller = "News",
                    Action     = "Index",
                    Name       = "NewsList"
                }
            };
            moduleInfo.EntryOptions = new EntryOption[] {
                new EntryOption()
                {
                    Name = "NewsList", Entry = new Entry {
                        Name = "NewsList", Controller = "News", Action = "Index"
                    }
                },
                new EntryOption()
                {
                    Name = "NewsCategories", Entry = new Entry {
                        Name = "NewsList", Controller = "News", Action = "Categories"
                    }
                },
                new EntryOption()
                {
                    Name = "ArticleCategories", Entry = new Entry {
                        Name = "NewsList", Controller = "Article", Action = "Categories"
                    }
                },
                new EntryOption()
                {
                    Name = "ArticleList", Entry = new Entry {
                        Name = "NewsList", Controller = "Article", Action = "List"
                    }
                },
                new EntryOption()
                {
                    Name = "ArticleSearch", Entry = new Entry {
                        Name = "NewsList", Controller = "Article", Action = "Search"
                    }
                },
                new EntryOption()
                {
                    Name = "LastestNews", Entry = new Entry {
                        Name = "NewsList", Controller = "News", Action = "LastestNews", LinkToEntryName = "NewsList"
                    }
                }
            };
            moduleInfo.DefaultSettings.CustomSettings             = new Dictionary <string, string>();
            moduleInfo.DefaultSettings.CustomSettings["Setting1"] = "Value1";
            ModuleInfo.Save(moduleInfo);

            return(Content("The module configuration file has been generated."));
        }
示例#25
0
        protected override void ExecuteCmdlet()
        {
            var serverRelativeWebUrl = SelectedWeb.EnsureProperty(w => w.ServerRelativeUrl);

            if (!ServerRelativePageUrl.ToLowerInvariant().StartsWith(serverRelativeWebUrl.ToLowerInvariant()))
            {
                ServerRelativePageUrl = UrlUtility.Combine(serverRelativeWebUrl, ServerRelativePageUrl);
            }

            Guid id = Guid.Empty;

            if (Identity.Id == Guid.Empty)
            {
                var wp = SelectedWeb.GetWebParts(ServerRelativePageUrl).FirstOrDefault(wps => wps.WebPart.Title == Identity.Title);
                if (wp != null)
                {
                    id = wp.Id;
                }
                else
                {
                    throw new Exception(string.Format("Web Part with title '{0}' cannot be found on page with URL {1}", Identity.Title, ServerRelativePageUrl));
                }
            }
            else
            {
                id = Identity.Id;
            }

            var uri = new Uri(ClientContext.Url);

            var hostUri = uri.Host;
            var webUrl  = string.Format("{0}://{1}{2}", uri.Scheme, uri.Host, SelectedWeb.ServerRelativeUrl);
            var pageUrl = string.Format("{0}://{1}{2}", uri.Scheme, uri.Host, ServerRelativePageUrl);
            var request = (HttpWebRequest)WebRequest.Create(string.Format("{0}/_vti_bin/exportwp.aspx?pageurl={1}&guidstring={2}", webUrl, pageUrl, id.ToString()));

            if (SPOnlineConnection.CurrentConnection.ConnectionType == Enums.ConnectionType.O365)
            {
                var credentials = ClientContext.Credentials as SharePointOnlineCredentials;

                var authCookieValue = credentials.GetAuthenticationCookie(uri);

                Cookie fedAuth = new Cookie()
                {
                    Name     = "SPOIDCRL",
                    Value    = authCookieValue.TrimStart("SPOIDCRL=".ToCharArray()),
                    Path     = "/",
                    Secure   = true,
                    HttpOnly = true,
                    Domain   = uri.Host
                };
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(fedAuth);
            }
            else
            {
                CredentialCache credentialCache = new CredentialCache();
                credentialCache.Add(new Uri(webUrl), "NTLM", ClientContext.Credentials as NetworkCredential);
                request.Credentials = credentialCache;
            }

            var response = request.GetResponse();

            using (Stream stream = response.GetResponseStream())
            {
                StreamReader reader         = new StreamReader(stream, Encoding.UTF8);
                string       responseString = reader.ReadToEnd();
                WriteObject(responseString);
            }
        }
示例#26
0
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                var context = web.Context as ClientContext;

                web.EnsureProperties(w => w.ServerRelativeUrl, w => w.RootFolder.WelcomePage);

                foreach (var page in template.Pages)
                {
                    var url = parser.ParseString(page.Url);

                    if (!url.ToLower().StartsWith(web.ServerRelativeUrl.ToLower()))
                    {
                        url = UrlUtility.Combine(web.ServerRelativeUrl, url);
                    }

                    var exists = true;
                    Microsoft.SharePoint.Client.File file = null;
                    try
                    {
                        file = web.GetFileByServerRelativeUrl(url);
                        web.Context.Load(file);
                        web.Context.ExecuteQuery();
                    }
                    catch (ServerException ex)
                    {
                        if (ex.ServerErrorTypeName == "System.IO.FileNotFoundException")
                        {
                            exists = false;
                        }
                    }
                    if (exists)
                    {
                        if (page.Overwrite)
                        {
                            try
                            {
                                scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Pages_Overwriting_existing_page__0_, url);

                                if (page.WelcomePage && url.Contains(web.RootFolder.WelcomePage))
                                {
                                    web.SetHomePage(string.Empty);
                                }

                                file.DeleteObject();
                                web.Context.ExecuteQueryRetry();
                                web.AddWikiPageByUrl(url);
                                if (page.Layout == WikiPageLayout.Custom)
                                {
                                    web.AddLayoutToWikiPage(WikiPageLayout.OneColumn, url);
                                }
                                else
                                {
                                    web.AddLayoutToWikiPage(page.Layout, url);
                                }
                            }
                            catch (Exception ex)
                            {
                                scope.LogError(CoreResources.Provisioning_ObjectHandlers_Pages_Overwriting_existing_page__0__failed___1_____2_, url, ex.Message, ex.StackTrace);
                            }
                        }
                    }
                    else
                    {
                        try
                        {
                            scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Pages_Creating_new_page__0_, url);

                            web.AddWikiPageByUrl(url);
                            web.AddLayoutToWikiPage(page.Layout, url);
                        }
                        catch (Exception ex)
                        {
                            scope.LogError(CoreResources.Provisioning_ObjectHandlers_Pages_Creating_new_page__0__failed___1_____2_, url, ex.Message, ex.StackTrace);
                        }
                    }

                    if (page.WelcomePage)
                    {
                        web.RootFolder.EnsureProperty(p => p.ServerRelativeUrl);
                        var rootFolderRelativeUrl = url.Substring(web.RootFolder.ServerRelativeUrl.Length);
                        web.SetHomePage(rootFolderRelativeUrl);
                    }

                    if (page.WebParts != null & page.WebParts.Any())
                    {
                        var existingWebParts = web.GetWebParts(url);

                        foreach (var webpart in page.WebParts)
                        {
                            if (existingWebParts.FirstOrDefault(w => w.WebPart.Title == webpart.Title) == null)
                            {
                                WebPartEntity wpEntity = new WebPartEntity();
                                wpEntity.WebPartTitle = webpart.Title;
                                wpEntity.WebPartXml   = parser.ParseString(webpart.Contents.Trim(new[] { '\n', ' ' }));
                                web.AddWebPartToWikiPage(url, wpEntity, (int)webpart.Row, (int)webpart.Column, false);
                            }
                        }
                        var allWebParts = web.GetWebParts(url);
                        foreach (var webpart in allWebParts)
                        {
                            parser.AddToken(new WebPartIdToken(web, webpart.WebPart.Title, webpart.Id));
                        }
                    }

                    file = web.GetFileByServerRelativeUrl(url);
                    file.EnsureProperty(f => f.ListItemAllFields);

                    if (page.Fields.Any())
                    {
                        var item = file.ListItemAllFields;
                        foreach (var fieldValue in page.Fields)
                        {
                            item[fieldValue.Key] = parser.ParseString(fieldValue.Value);
                        }
                        item.Update();
                        web.Context.ExecuteQueryRetry();
                    }
                    if (page.Security != null && page.Security.RoleAssignments.Count != 0)
                    {
                        web.Context.Load(file.ListItemAllFields);
                        web.Context.ExecuteQuery();
                        file.ListItemAllFields.SetSecurity(parser, page.Security);
                    }
                }
            }
            return(parser);
        }
示例#27
0
        private static void SetThemeToWebImplementation(this Web web, Web rootWeb, string themeName)
        {
            // Let's get instance to the composite look gallery
            List themeList = rootWeb.GetCatalog(124);

            rootWeb.Context.Load(themeList);
            rootWeb.Context.ExecuteQuery();

            // Double checking that theme exists
            if (rootWeb.ThemeEntryExists(themeName, themeList))
            {
                CamlQuery query      = new CamlQuery();
                string    camlString = @"
                <View>
                    <Query>                
                        <Where>
                            <Eq>
                                <FieldRef Name='Name' />
                                <Value Type='Text'>{0}</Value>
                            </Eq>
                        </Where>
                     </Query>
                </View>";

                // Let's update the theme name accordingly
                camlString    = string.Format(camlString, themeName);
                query.ViewXml = camlString;
                var found = themeList.GetItems(query);
                rootWeb.Context.Load(found);
                rootWeb.Context.ExecuteQuery();
                if (found.Count > 0)
                {
                    ListItem themeEntry = found[0];
                    //Set the properties for applying custom theme which was jus uplaoded
                    string spColorURL = null;
                    if (themeEntry["ThemeUrl"] != null && themeEntry["ThemeUrl"].ToString().Length > 0)
                    {
                        spColorURL = UrlUtility.MakeRelativeUrl((themeEntry["ThemeUrl"] as FieldUrlValue).Url);
                    }
                    string spFontURL = null;
                    if (themeEntry["FontSchemeUrl"] != null && themeEntry["FontSchemeUrl"].ToString().Length > 0)
                    {
                        spFontURL = UrlUtility.MakeRelativeUrl((themeEntry["FontSchemeUrl"] as FieldUrlValue).Url);
                    }
                    string backGroundImage = null;
                    if (themeEntry["ImageUrl"] != null && themeEntry["ImageUrl"].ToString().Length > 0)
                    {
                        backGroundImage = UrlUtility.MakeRelativeUrl((themeEntry["ImageUrl"] as FieldUrlValue).Url);
                    }

                    // Set theme for demonstration
                    web.ApplyTheme(spColorURL,
                                   spFontURL,
                                   backGroundImage,
                                   false);

                    // Let's also update master page, if needed
                    if (themeEntry["MasterPageUrl"] != null && themeEntry["MasterPageUrl"].ToString().Length > 0)
                    {
                        web.MasterUrl = UrlUtility.MakeRelativeUrl((themeEntry["MasterPageUrl"] as FieldUrlValue).Url);;
                    }

                    web.Context.ExecuteQuery();
                }
            }
        }
示例#28
0
        protected override void ExecuteCmdlet()
        {
            if (ParameterSetName == ParameterSet_ASFILE)
            {
                if (!System.IO.Path.IsPathRooted(Path))
                {
                    Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path);
                }
                if (string.IsNullOrEmpty(NewFileName))
                {
                    FileName = System.IO.Path.GetFileName(Path);
                }
                else
                {
                    FileName = NewFileName;
                }
            }

            var folder  = EnsureFolder();
            var fileUrl = UrlUtility.Combine(folder.ServerRelativeUrl, FileName);

            string targetContentTypeId = null;

            // Check to see if the Content Type exists. If it doesn't we are going to throw an exception and block this transaction right here.
            if (ContentType != null)
            {
                CurrentWeb.EnsureProperty(w => w.ServerRelativeUrl);
                var list = CurrentWeb.GetListByUrl(folder.ServerRelativeUrl.Substring(CurrentWeb.ServerRelativeUrl.TrimEnd('/').Length + 1));
                if (list is null)
                {
                    throw new PSArgumentException("The folder specified does not have a corresponding list", nameof(Folder));
                }
                targetContentTypeId = ContentType?.GetIdOrThrow(nameof(ContentType), list);
            }

            // Check if the file exists
            if (Checkout)
            {
                try
                {
                    var existingFile = CurrentWeb.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(fileUrl));

                    existingFile.EnsureProperty(f => f.Exists);
                    if (existingFile.Exists)
                    {
                        CurrentWeb.CheckOutFile(fileUrl);
                    }
                }
                catch
                { // Swallow exception, file does not exist
                }
            }
            Microsoft.SharePoint.Client.File file;
            if (ParameterSetName == ParameterSet_ASFILE)
            {
                file = folder.UploadFile(FileName, Path, true);
            }
            else
            {
                file = folder.UploadFile(FileName, Stream, true);
            }

            bool updateRequired = false;
            var  item           = file.ListItemAllFields;

            if (Values != null)
            {
                ListItemHelper.SetFieldValues(item, Values, this);
                updateRequired = true;
            }

            if (ContentType != null)
            {
                item["ContentTypeId"] = targetContentTypeId;
                updateRequired        = true;
            }

            if (updateRequired)
            {
                item.UpdateOverwriteVersion();
            }
            if (Checkout)
            {
                CurrentWeb.CheckInFile(fileUrl, CheckinType.MajorCheckIn, CheckInComment);
            }

            if (Publish)
            {
                CurrentWeb.PublishFile(fileUrl, PublishComment);
            }

            if (Approve)
            {
                CurrentWeb.ApproveFile(fileUrl, ApproveComment);
            }

            ClientContext.Load(file);
            try
            {
                ClientContext.ExecuteQueryRetry();
            }
            catch (ServerException)
            {
                // Can happen when uploading a file to a location not residing inside a document library, such as to the _cts folder. Switch to fallback option so that the upload doesn't result in an error.
                ClientContext.Load(file, f => f.Length, f => f.Name, f => f.TimeCreated, f => f.TimeLastModified, f => f.Title);
                ClientContext.ExecuteQueryRetry();
            }
            WriteObject(file);
        }
示例#29
0
        protected override void ExecuteCmdlet()
        {
            if (ParameterSetName == ParameterSet_ASFILE)
            {
                if (!System.IO.Path.IsPathRooted(Path))
                {
                    Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path);
                }
                if (string.IsNullOrEmpty(NewFileName))
                {
                    FileName = System.IO.Path.GetFileName(Path);
                }
                else
                {
                    FileName = NewFileName;
                }
            }

            var folder  = EnsureFolder();
            var fileUrl = UrlUtility.Combine(folder.ServerRelativeUrl, FileName);

            ContentType targetContentType = null;

            // Check to see if the Content Type exists. If it doesn't we are going to throw an exception and block this transaction right here.
            if (ContentType != null)
            {
                try
                {
                    var list = SelectedWeb.GetListByUrl(Folder);

                    if (!string.IsNullOrEmpty(ContentType.Id))
                    {
                        targetContentType = list.GetContentTypeById(ContentType.Id);
                    }
                    else if (!string.IsNullOrEmpty(ContentType.Name))
                    {
                        targetContentType = list.GetContentTypeByName(ContentType.Name);
                    }
                    else if (ContentType.ContentType != null)
                    {
                        targetContentType = ContentType.ContentType;
                    }
                    if (targetContentType == null)
                    {
                        ThrowTerminatingError(new ErrorRecord(new ArgumentException($"Content Type Argument: {ContentType} does not exist in the list: {list.Title}"), "CONTENTTYPEDOESNOTEXIST", ErrorCategory.InvalidArgument, this));
                    }
                }
                catch
                {
                    ThrowTerminatingError(new ErrorRecord(new ArgumentException($"The Folder specified ({folder.ServerRelativeUrl}) does not have a corresponding List, the -ContentType parameter is not valid."), "RELATIVEPATHNOTINLIBRARY", ErrorCategory.InvalidArgument, this));
                }
            }

            // Check if the file exists
            if (Checkout)
            {
                try
                {
#if ONPREMISES
                    var existingFile = SelectedWeb.GetFileByServerRelativeUrl(fileUrl);
#else
                    var existingFile = SelectedWeb.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(fileUrl));
#endif
                    existingFile.EnsureProperty(f => f.Exists);
                    if (existingFile.Exists)
                    {
                        SelectedWeb.CheckOutFile(fileUrl);
                    }
                }
                catch
                { // Swallow exception, file does not exist
                }
            }
            Microsoft.SharePoint.Client.File file;
            if (ParameterSetName == ParameterSet_ASFILE)
            {
                file = folder.UploadFile(FileName, Path, true);
            }
            else
            {
                file = folder.UploadFile(FileName, Stream, true);
            }

            if (Values != null)
            {
                var item = file.ListItemAllFields;

                ListItemHelper.UpdateListItem(item, Values, ListItemUpdateType.UpdateOverwriteVersion,
                                              (warning) =>
                {
                    WriteWarning(warning);
                },
                                              (terminatingErrorMessage, terminatingErrorCode) =>
                {
                    ThrowTerminatingError(new ErrorRecord(new Exception(terminatingErrorMessage), terminatingErrorCode, ErrorCategory.InvalidData, this));
                });
            }
            if (ContentType != null)
            {
                var item = file.ListItemAllFields;
                item["ContentTypeId"] = targetContentType.Id.StringValue;
#if !ONPREMISES
                item.UpdateOverwriteVersion();
#else
                item.Update();
#endif
                ClientContext.ExecuteQueryRetry();
            }

            if (Checkout)
            {
                SelectedWeb.CheckInFile(fileUrl, CheckinType.MajorCheckIn, CheckInComment);
            }


            if (Publish)
            {
                SelectedWeb.PublishFile(fileUrl, PublishComment);
            }

            if (Approve)
            {
                SelectedWeb.ApproveFile(fileUrl, ApproveComment);
            }
            ClientContext.Load(file);
            ClientContext.ExecuteQueryRetry();
            WriteObject(file);
        }
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                web.EnsureProperties(w => w.ServerRelativeUrl);

                foreach (var clientSidePage in template.ClientSidePages)
                {
                    // determine pages library
                    string pagesLibrary = "SitePages";
                    string pageName     = $"{System.IO.Path.GetFileNameWithoutExtension(clientSidePage.PageName)}.aspx";

                    string url = $"{pagesLibrary}/{pageName}";

                    url = UrlUtility.Combine(web.ServerRelativeUrl, url);

                    var exists = true;
                    try
                    {
                        var file = web.GetFileByServerRelativeUrl(url);
                        web.Context.Load(file);
                        web.Context.ExecuteQueryRetry();
                    }
                    catch (ServerException ex)
                    {
                        if (ex.ServerErrorTypeName == "System.IO.FileNotFoundException")
                        {
                            exists = false;
                        }
                    }

                    Pages.ClientSidePage page = null;
                    if (exists)
                    {
                        if (clientSidePage.Overwrite)
                        {
                            // Get the existing page
                            page = web.LoadClientSidePage(pageName);
                            // Clear the page
                            page.ClearPage();
                        }
                        else
                        {
                            scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_ClientSidePages_NoOverWrite, pageName);
                            continue;
                        }
                    }
                    else
                    {
                        // Create new client side page
                        page = web.AddClientSidePage(pageName);
                    }

                    // Load existing available controls
                    var componentsToAdd = page.AvailableClientSideComponents().ToList();

                    // if no section specified then add a default single column section
                    if (!clientSidePage.Sections.Any())
                    {
                        clientSidePage.Sections.Add(new CanvasSection()
                        {
                            Type = CanvasSectionType.OneColumn, Order = 10
                        });
                    }

                    int sectionCount = -1;
                    // Apply the "layout" and content
                    foreach (var section in clientSidePage.Sections)
                    {
                        sectionCount++;
                        switch (section.Type)
                        {
                        case CanvasSectionType.OneColumn:
                            page.AddSection(Pages.CanvasSectionTemplate.OneColumn, section.Order);
                            break;

                        case CanvasSectionType.OneColumnFullWidth:
                            page.AddSection(Pages.CanvasSectionTemplate.OneColumnFullWidth, section.Order);
                            break;

                        case CanvasSectionType.TwoColumn:
                            page.AddSection(Pages.CanvasSectionTemplate.TwoColumn, section.Order);
                            break;

                        case CanvasSectionType.ThreeColumn:
                            page.AddSection(Pages.CanvasSectionTemplate.ThreeColumn, section.Order);
                            break;

                        case CanvasSectionType.TwoColumnLeft:
                            page.AddSection(Pages.CanvasSectionTemplate.TwoColumnLeft, section.Order);
                            break;

                        case CanvasSectionType.TwoColumnRight:
                            page.AddSection(Pages.CanvasSectionTemplate.TwoColumnRight, section.Order);
                            break;

                        default:
                            page.AddSection(Pages.CanvasSectionTemplate.OneColumn, section.Order);
                            break;
                        }

                        // Add controls to the section
                        if (section.Controls.Any())
                        {
                            // Safety measure: reset column order to 1 for columns marked with 0 or lower
                            foreach (var control in section.Controls.Where(p => p.Column <= 0).ToList())
                            {
                                control.Column = 1;
                            }

                            foreach (CanvasControl control in section.Controls)
                            {
                                Pages.ClientSideComponent baseControl = null;

                                // Is it a text control?
                                if (control.Type == WebPartType.Text)
                                {
                                    Pages.ClientSideText textControl = new Pages.ClientSideText();
                                    if (control.ControlProperties.Any())
                                    {
                                        var textProperty = control.ControlProperties.First();
                                        textControl.Text = parser.ParseString(textProperty.Value);
                                        // Reduce column number by 1 due 0 start indexing
                                        page.AddControl(textControl, page.Sections[sectionCount].Columns[control.Column - 1], control.Order);
                                    }
                                }
                                // It is a web part
                                else
                                {
                                    // apply token parsing on the web part properties
                                    control.JsonControlData = parser.ParseString(control.JsonControlData);

                                    // perform processing of web part properties (e.g. include listid property based list title property)
                                    var webPartPostProcessor = CanvasControlPostProcessorFactory.Resolve(control);
                                    webPartPostProcessor.Process(control, page);

                                    // Is a custom developed client side web part (3rd party)
                                    if (control.Type == WebPartType.Custom)
                                    {
                                        if (!string.IsNullOrEmpty(control.CustomWebPartName))
                                        {
                                            baseControl = componentsToAdd.FirstOrDefault(p => p.Name.Equals(control.CustomWebPartName, StringComparison.InvariantCultureIgnoreCase));
                                        }
                                        else if (control.ControlId != Guid.Empty)
                                        {
                                            baseControl = componentsToAdd.FirstOrDefault(p => p.Id.Equals($"{{{control.ControlId.ToString()}}}", StringComparison.CurrentCultureIgnoreCase));
                                        }
                                    }
                                    // Is an OOB client side web part (1st party)
                                    else
                                    {
                                        string webPartName = "";
                                        switch (control.Type)
                                        {
                                        case WebPartType.Image:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.Image);
                                            break;

                                        case WebPartType.BingMap:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.BingMap);
                                            break;

                                        case WebPartType.ContentEmbed:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.ContentEmbed);
                                            break;

                                        case WebPartType.ContentRollup:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.ContentRollup);
                                            break;

                                        case WebPartType.DocumentEmbed:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.DocumentEmbed);
                                            break;

                                        case WebPartType.Events:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.Events);
                                            break;

                                        case WebPartType.GroupCalendar:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.GroupCalendar);
                                            break;

                                        case WebPartType.Hero:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.Hero);
                                            break;

                                        case WebPartType.ImageGallery:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.ImageGallery);
                                            break;

                                        case WebPartType.LinkPreview:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.LinkPreview);
                                            break;

                                        case WebPartType.List:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.List);
                                            break;

                                        case WebPartType.NewsFeed:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.NewsFeed);
                                            break;

                                        case WebPartType.NewsReel:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.NewsReel);
                                            break;

                                        case WebPartType.PageTitle:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.PageTitle);
                                            break;

                                        case WebPartType.People:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.People);
                                            break;

                                        case WebPartType.PowerBIReportEmbed:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.PowerBIReportEmbed);
                                            break;

                                        case WebPartType.QuickChart:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.QuickChart);
                                            break;

                                        case WebPartType.QuickLinks:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.QuickLinks);
                                            break;

                                        case WebPartType.SiteActivity:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.SiteActivity);
                                            break;

                                        case WebPartType.VideoEmbed:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.VideoEmbed);
                                            break;

                                        case WebPartType.YammerEmbed:
                                            webPartName = Pages.ClientSidePage.ClientSideWebPartEnumToName(Pages.DefaultClientSideWebParts.YammerEmbed);
                                            break;
                                        }

                                        baseControl = componentsToAdd.FirstOrDefault(p => p.Name.Equals(webPartName, StringComparison.InvariantCultureIgnoreCase));
                                    }

                                    if (baseControl != null)
                                    {
                                        Pages.ClientSideWebPart myWebPart = new Pages.ClientSideWebPart(baseControl)
                                        {
                                            Order = control.Order
                                        };

                                        // Reduce column number by 1 due 0 start indexing
                                        page.AddControl(myWebPart, page.Sections[sectionCount].Columns[control.Column - 1], control.Order);

                                        // set properties using json string
                                        if (!String.IsNullOrEmpty(control.JsonControlData))
                                        {
                                            myWebPart.PropertiesJson = control.JsonControlData;
                                        }

                                        // set using property collection
                                        if (control.ControlProperties.Any())
                                        {
                                            // grab the "default" properties so we can deduct their types, needed to correctly apply the set properties
                                            var    controlManifest   = JObject.Parse(baseControl.Manifest);
                                            JToken controlProperties = null;
                                            if (controlManifest != null)
                                            {
                                                controlProperties = controlManifest.SelectToken("preconfiguredEntries[0].properties");
                                            }

                                            foreach (var property in control.ControlProperties)
                                            {
                                                Type propertyType = typeof(string);

                                                if (controlProperties != null)
                                                {
                                                    var defaultProperty = controlProperties.SelectToken(property.Key, false);
                                                    if (defaultProperty != null)
                                                    {
                                                        propertyType = Type.GetType($"System.{defaultProperty.Type.ToString()}");

                                                        if (propertyType == null)
                                                        {
                                                            if (defaultProperty.Type.ToString().Equals("integer", StringComparison.InvariantCultureIgnoreCase))
                                                            {
                                                                propertyType = typeof(int);
                                                            }
                                                        }
                                                    }
                                                }

                                                myWebPart.Properties[property.Key] = JToken.FromObject(Convert.ChangeType(parser.ParseString(property.Value), propertyType));
                                            }
                                        }
                                    }
                                    else
                                    {
                                        scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_ClientSidePages_BaseControlNotFound, control.ControlId, control.CustomWebPartName);
                                    }
                                }
                            }
                        }
                    }

                    // Persist the page
                    page.Save(pageName);

                    // Make it a news page if requested
                    if (clientSidePage.PromoteAsNewsArticle)
                    {
                        page.PromoteAsNewsArticle();
                    }
                }
            }
            return(parser);
        }