public void CanProvisionObjects() { var template = new ProvisioningTemplate(); FileSystemConnector connector = new FileSystemConnector(resourceFolder,""); template.Connector = connector; template.Files.Add(new Core.Framework.Provisioning.Model.File() { Overwrite = true, Src = fileName, Folder = folder }); using (var ctx = TestCommon.CreateClientContext()) { var parser = new TokenParser(ctx.Web, template); new ObjectFiles().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); if (!ctx.Web.IsPropertyAvailable("ServerRelativeUrl")) { ctx.Load(ctx.Web, w => w.ServerRelativeUrl); ctx.ExecuteQueryRetry(); } var file = ctx.Web.GetFileByServerRelativeUrl( UrlUtility.Combine(ctx.Web.ServerRelativeUrl, UrlUtility.Combine(folder, fileName))); ctx.Load(file, f => f.Exists); ctx.ExecuteQueryRetry(); Assert.IsTrue(file.Exists); } }
public void CanProvisionObjects() { var template = new ProvisioningTemplate(); var contentType = new ContentType() { Id = "0x010100503B9E20E5455344BFAC2292DC6FE805", Name = "Test Content Type", Group = "PnP", Description = "Test Description", Overwrite = true, Hidden = false }; contentType.FieldRefs.Add(new FieldRef() { Id = BuiltInFieldId.Category, DisplayName = "Test Category", }); template.ContentTypes.Add(contentType); using (var ctx = TestCommon.CreateClientContext()) { TokenParser parser = new TokenParser(ctx.Web, template); new ObjectContentType().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); var ct = ctx.Web.GetContentTypeByName("Test Content Type"); Assert.IsNotNull(ct); } }
public static void SetSecurity(this SecurableObject securable, TokenParser parser, ObjectSecurity security) { //using (var scope = new PnPMonitoredScope("Set Security")) //{ var context = securable.Context as ClientContext; var groups = context.LoadQuery(context.Web.SiteGroups.Include(g => g.LoginName)); var webRoleDefinitions = context.LoadQuery(context.Web.RoleDefinitions); context.ExecuteQueryRetry(); securable.BreakRoleInheritance(security.CopyRoleAssignments, security.ClearSubscopes); foreach (var roleAssignment in security.RoleAssignments) { Principal principal = groups.FirstOrDefault(g => g.LoginName == parser.ParseString(roleAssignment.Principal)); if (principal == null) { principal = context.Web.EnsureUser(roleAssignment.Principal); } var roleDefinitionBindingCollection = new RoleDefinitionBindingCollection(context); var roleDefinition = webRoleDefinitions.FirstOrDefault(r => r.Name == roleAssignment.RoleDefinition); if (roleDefinition != null) { roleDefinitionBindingCollection.Add(roleDefinition); } securable.RoleAssignments.Add(principal, roleDefinitionBindingCollection); } context.ExecuteQueryRetry(); //} }
public override void ProvisionObjects(Web web, ProvisioningTemplate template) { // if this is a sub site then we're not provisioning fields. Technically this can be done but it's not a recommended practice if (web.IsSubSite()) { return; } var parser = new TokenParser(web); var existingFields = web.Fields; web.Context.Load(existingFields, fs => fs.Include(f => f.Id)); web.Context.ExecuteQueryRetry(); var existingFieldIds = existingFields.Select(l => l.Id).ToList(); var fields = template.SiteFields; foreach (var field in fields) { XDocument document = XDocument.Parse(field.SchemaXml); var fieldId = document.Root.Attribute("ID").Value; if (!existingFieldIds.Contains(Guid.Parse(fieldId))) { var fieldXml = parser.Parse(field.SchemaXml); web.Fields.AddFieldAsXml(fieldXml, false, AddFieldOptions.DefaultValue); web.Context.ExecuteQueryRetry(); } } }
public void CanProvisionObjects() { var template = new ProvisioningTemplate(); foreach (var user in admins) { template.Security.AdditionalMembers.Add(new User() { Name = user.LoginName}); } using (var ctx = TestCommon.CreateClientContext()) { var parser = new TokenParser(ctx.Web, template); new ObjectSiteSecurity().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); var memberGroup = ctx.Web.AssociatedMemberGroup; ctx.Load(memberGroup, g => g.Users); ctx.ExecuteQueryRetry(); foreach (var user in admins) { var existingUser = memberGroup.Users.GetByLoginName(user.LoginName); ctx.Load(existingUser); ctx.ExecuteQueryRetry(); Assert.IsNotNull(existingUser); } } }
public override void ProvisionObjects(Web web, ProvisioningTemplate template) { TokenParser parser = new TokenParser(web); var context = web.Context as ClientContext; if (!web.IsPropertyAvailable("ServerRelativeUrl")) { context.Load(web, w => w.ServerRelativeUrl); context.ExecuteQueryRetry(); } foreach (var file in template.Files) { var folderName = parser.Parse(file.Folder); if (folderName.ToLower().StartsWith((web.ServerRelativeUrl.ToLower()))) { folderName = folderName.Substring(web.ServerRelativeUrl.Length); } var folder = web.EnsureFolderPath(folderName); using (var stream = template.Connector.GetFileStream(file.Src)) { folder.UploadFile(file.Src, stream, true); } } }
/// <summary> /// Add a rule for converting a regex pattern to a token /// Order in which this is provided is important, with more specific /// rules needing to be provided before more general ones. /// /// Returns self to allow for chaining. /// </summary> /// <param name="pattern">Regex pattern that needs to be matched</param> /// <param name="rule">Function that generates a token based on the input</param> /// <returns></returns> public Lexer AddRule(string pattern, TokenParser rule) { _ruleDictionary.Add("^" + pattern, rule); // for chaining return this; }
private static void LocalizeParts(Web web, TokenParser parser, string url, WebPartCollection webParts, PnPMonitoredScope scope) { if (CanUseAcceptLanguageHeaderForLocalization(web)) { var context = web.Context; var allParts = web.GetWebParts(parser.ParseString(url)).ToList(); foreach (var webPart in webParts) { #if !SP2016 var partOnPage = allParts.FirstOrDefault(w => w.ZoneId == webPart.Zone && w.WebPart.ZoneIndex == webPart.Order); #else var partOnPage = allParts.FirstOrDefault(w => w.WebPart.ZoneIndex == webPart.Order); #endif if (webPart.Title.ContainsResourceToken() && partOnPage != null) { var resourceValues = parser.GetResourceTokenResourceValues(webPart.Title); foreach (var resourceValue in resourceValues) { // Save property with correct locale on the request to make it stick // http://sadomovalex.blogspot.no/2015/09/localize-web-part-titles-via-client.html context.PendingRequest.RequestExecutor.WebRequest.Headers["Accept-Language"] = resourceValue.Item1; partOnPage.WebPart.Properties["Title"] = resourceValue.Item2; partOnPage.SaveWebPartChanges(); context.ExecuteQueryRetry(); } } } context.PendingRequest.RequestExecutor.WebRequest.Headers.Remove("Accept-Language"); } else { // warning scope.LogWarning(CoreResources.Provisioning_Extensions_WebPartLocalization_Skip); } }
public void DoesNotParseTagsWhichStartsWithNonLetters() { const string html = "<1head x>"; List<Token> tokens = new TokenParser().Parse(html).ToList(); Token single = tokens.Single(); Assert.Equal(TokenType.Text, single.Type); Assert.Equal("<1head x>", single.Value); }
public void DoesNotParseAsCommentLtWithSingleMinus() { const string html = "<!- head x=y z-->"; IEnumerable<Token> tokens = new TokenParser().Parse(html); Token token = tokens.First(); Assert.Equal(TokenType.Text, token.Type); Assert.Equal("<!- head x=y z-->", token.Value); }
private void ProvisionCustomActionImplementation(object parent, List<CustomAction> customActions) { TokenParser parser = null; Web web = null; Site site = null; if (parent is Site) { site = parent as Site; parser = new TokenParser(site.RootWeb); } else { web = parent as Web; parser = new TokenParser(web); } foreach (var customAction in customActions) { var caExists = false; if (site != null) { caExists = site.CustomActionExists(customAction.Name); } else { caExists = web.CustomActionExists(customAction.Name); } if (!caExists) { var customActionEntity = new CustomActionEntity(); customActionEntity.CommandUIExtension = customAction.CommandUIExtension; customActionEntity.Description = customAction.Description; customActionEntity.Group = customAction.Group; customActionEntity.ImageUrl = parser.Parse(customAction.ImageUrl); customActionEntity.Location = customAction.Location; customActionEntity.Name = customAction.Name; customActionEntity.RegistrationId = customAction.RegistrationId; customActionEntity.RegistrationType = customAction.RegistrationType; customActionEntity.Remove = customAction.Remove; customActionEntity.Rights = customAction.Rights; customActionEntity.ScriptBlock = customAction.ScriptBlock; customActionEntity.ScriptSrc = parser.Parse(customAction.ScriptSrc); customActionEntity.Sequence = customAction.Sequence; customActionEntity.Title = customAction.Title; customActionEntity.Url = parser.Parse(customAction.Url); if (site != null) { site.AddCustomAction(customActionEntity); } else { web.AddCustomAction(customActionEntity); } } } }
public void ScriptCDataParsedCorrectly() { const string html = "<script>//<br></script>"; var tokens = new TokenParser().Parse(html).ToList(); Assert.Equal(TokenType.OpenTag, tokens[0].Type); Assert.Equal("script", tokens[0].Value); Assert.Equal(TokenType.Text, tokens[1].Type); Assert.Equal("//<br>", tokens[1].Value); Assert.Equal(TokenType.CloseTag, tokens[2].Type); Assert.Equal("script", tokens[2].Value); }
public void ParseAttributeDoubleQuotedValueWithLtInside() { const string html = "<head x=\"y<z\">"; List<Token> tokens = new TokenParser().Parse(html).ToList(); Assert.Equal("head", tokens.First().Value); Token attrName = tokens[1]; Assert.Equal(TokenType.AttributeName, attrName.Type); Assert.Equal("x", attrName.Value); Token attrValue = tokens[2]; Assert.Equal(TokenType.AttributeValue, attrValue.Type); Assert.Equal("y<z", attrValue.Value); }
public List<ModelWebPart> Retrieve(string pageUrl, TokenParser parser) { if (parser == null) { parser = new TokenParser(this.Web, new Model.ProvisioningTemplate()); } var xml = Web.GetWebPartsXml(pageUrl); var pageContent = Web.GetPageContent(pageUrl); var result = new List<ModelWebPart>(); if (string.IsNullOrEmpty(xml)) return result; var maches = GetWebPartXmlReqex.Matches(xml); var webPartDefinitions = this.GetWebPartDefinitionsWithServiceCall(pageUrl); foreach (var match in maches) { var webPartXml = match.ToString(); var zone = this.GetZone(webPartXml); var wpId = this.GetWebPartId(webPartXml); var definition = webPartDefinitions.FirstOrDefault(d => d.Id == wpId); var webPart = definition.WebPart; webPartXml = this.WrapToV3Format(webPartXml); var pcLower = pageContent.ToLower(); //TODO: refactor getting webpartId2 make separate method, probably use regex or another approach var contentBoxIndex = pcLower.IndexOf("<div id=\"contentbox\""); var indexOfIdStartIndex = contentBoxIndex != -1 ? pcLower.IndexOf(wpId.ToString().ToLower(), contentBoxIndex) : -1; var indexOfId = indexOfIdStartIndex != -1 ? pcLower.IndexOf("webpartid2", indexOfIdStartIndex) : -1; var wpExportId = definition.Id; var wpControlId = GetWebPartControlId(webPartXml); if (indexOfId != -1 && string.IsNullOrEmpty(wpControlId)) { var wpId2 = pageContent.Substring(indexOfId + "webpartid2=\"".Length, 36); wpExportId = Guid.Parse(wpId2); } webPartXml = this.SetWebPartIdToXml(wpExportId, webPartXml); webPartXml = this.TokenizeWebPartXml(webPartXml, parser); var entity = new ModelWebPart { Contents = webPartXml, Order = (uint)webPart.ZoneIndex, Zone = zone, Title = webPart.Title }; result.Add(entity); } return result; }
public static IEnumerable<string> Tokenize(this string content) { var searchString = content.Trim(); if (searchString.Length == 0) return new string[0]; var parser = new TokenParser(); content.ToCharArray().Each(parser.Read); // Gotta force the parser to know it's done parser.Read('\n'); return parser.Tokens; }
public string Tokenize(string xml, TokenParser parser) { XElement webPartXml = XElement.Parse(xml); var nodes = webPartXml.Nodes(); foreach (var node in nodes) { var element = node as XElement; if (!SkipTokenization(element.Name.LocalName)) { element.Value = parser.TokenizeString(element.Value); } } return webPartXml.ToString(); }
public void CanProvisionObjects() { var template = new ProvisioningTemplate(); template.SiteFields.Add(new Core.Framework.Provisioning.Model.Field() { SchemaXml = ElementSchema }); using (var ctx = TestCommon.CreateClientContext()) { var parser = new TokenParser(ctx.Web, template); new ObjectField().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); var f = ctx.Web.GetFieldById<FieldText>(fieldId); Assert.IsNotNull(f); Assert.IsInstanceOfType(f, typeof(FieldText)); } }
public static bool SetUserResourceValue(this UserResource userResource, string tokenValue, TokenParser parser) { bool isDirty = false; if (userResource != null && !String.IsNullOrEmpty(tokenValue)) { var resourceValues = parser.GetResourceTokenResourceValues(tokenValue); foreach (var resourceValue in resourceValues) { userResource.SetValueForUICulture(resourceValue.Item1, resourceValue.Item2); isDirty = true; } } return isDirty; }
public void CanProvisionObjects() { var template = new ProvisioningTemplate(); template.Features.WebFeatures.Add( new OfficeDevPnP.Core.Framework.Provisioning.Model.Feature() { Id = featureId, Deactivate = true}); using (var ctx = TestCommon.CreateClientContext()) { var parser = new TokenParser(ctx.Web, template); new ObjectFeatures().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); var f = ctx.Web.IsFeatureActive(featureId); Assert.IsFalse(f); } }
public string Tokenize(string xml, TokenParser parser) { XElement webPartXml = XElement.Parse(xml); var webPartProperties = webPartXml.Descendants().FirstOrDefault(n => n.Name.LocalName.Equals("properties", StringComparison.InvariantCultureIgnoreCase)); var nodes = webPartProperties.Nodes(); foreach (var node in nodes) { var element = node as XElement; if (!SkipTokenization(element.Name.LocalName)) { element.Value = parser.TokenizeString(element.Value); } } return webPartXml.ToString(); }
public void CanProvisionObjects() { var template = new ProvisioningTemplate(); var ca = new Core.Framework.Provisioning.Model.CustomAction(); ca.Name = "Test Custom Action"; ca.Location = "ScriptLink"; ca.ScriptBlock = "alert('Hello PnP!');"; template.CustomActions.SiteCustomActions.Add(ca); using (var ctx = TestCommon.CreateClientContext()) { var parser = new TokenParser(ctx.Web, template); new ObjectCustomActions().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); Assert.IsTrue(ctx.Site.CustomActionExists("Test Custom Action")); } }
public void ParseTests() { using (var ctx = TestCommon.CreateClientContext()) { ctx.Load(ctx.Web, w => w.ServerRelativeUrl); ctx.Load(ctx.Site, s => s.ServerRelativeUrl); var masterCatalog = ctx.Web.GetCatalog((int)ListTemplateType.MasterPageCatalog); ctx.Load(masterCatalog, m => m.RootFolder.ServerRelativeUrl); var themesCatalog = ctx.Web.GetCatalog((int)ListTemplateType.ThemeCatalog); ctx.Load(themesCatalog, t => t.RootFolder.ServerRelativeUrl); ctx.ExecuteQueryRetry(); ProvisioningTemplate template = new ProvisioningTemplate(); template.Parameters.Add("test", "test"); var parser = new TokenParser(ctx.Web, template); var site1 = parser.ParseString("~siTE/test"); var site2 = parser.ParseString("{site}/test"); var sitecol1 = parser.ParseString("~siteCOLLECTION/test"); var sitecol2 = parser.ParseString("{sitecollection}/test"); var masterUrl1 = parser.ParseString("~masterpagecatalog/test"); var masterUrl2 = parser.ParseString("{masterpagecatalog}/test"); var themeUrl1 = parser.ParseString("~themecatalog/test"); var themeUrl2 = parser.ParseString("{themecatalog}/test"); var parameterTest1 = parser.ParseString("abc{parameter:TEST}/test"); var parameterTest2 = parser.ParseString("abc{$test}/test"); Assert.IsTrue(site1 == string.Format("{0}/test", ctx.Web.ServerRelativeUrl)); Assert.IsTrue(site2 == string.Format("{0}/test", ctx.Web.ServerRelativeUrl)); Assert.IsTrue(sitecol1 == string.Format("{0}/test", ctx.Site.ServerRelativeUrl)); Assert.IsTrue(sitecol2 == string.Format("{0}/test", ctx.Site.ServerRelativeUrl)); Assert.IsTrue(masterUrl1 == string.Format("{0}/test", masterCatalog.RootFolder.ServerRelativeUrl)); Assert.IsTrue(masterUrl2 == string.Format("{0}/test", masterCatalog.RootFolder.ServerRelativeUrl)); Assert.IsTrue(themeUrl1 == string.Format("{0}/test", themesCatalog.RootFolder.ServerRelativeUrl)); Assert.IsTrue(themeUrl2 == string.Format("{0}/test", themesCatalog.RootFolder.ServerRelativeUrl)); Assert.IsTrue(parameterTest1 == "abctest/test"); Assert.IsTrue(parameterTest2 == "abctest/test"); } }
public Model.File GetFile(string pageUrl, TokenParser parser, bool ignoreDefault) { Model.File file = null; if (pageUrl.StartsWith(Web.ServerRelativeUrl, StringComparison.OrdinalIgnoreCase)) { var provider = new WebPartsModelProvider(Web); var webPartsModels = provider.Retrieve(pageUrl, parser); var needToOverride = this.NeedToOverrideFile(Web, pageUrl); if ( !ignoreDefault || needToOverride || (1 != webPartsModels.Count) || !WebPartsModelProvider.IsWebPartDefault(webPartsModels[0])) { var folderPath = this.GetFolderPath(pageUrl); var localFilePath = this.GetFilePath(pageUrl); file = new Model.File(localFilePath, folderPath, needToOverride, webPartsModels, null); } } return file; }
public static ObjectSecurity GetSecurity(this SecurableObject securable, TokenParser parser) { ObjectSecurity security = null; using (var scope = new PnPMonitoredScope("Get Security")) { var context = securable.Context as ClientContext; context.Load(securable, sec => sec.HasUniqueRoleAssignments); var roleAssignments = context.LoadQuery(securable.RoleAssignments.Include( r => r.Member.LoginName, r => r.RoleDefinitionBindings.Include( rdb => rdb.Name, rdb => rdb.RoleTypeKind ))); context.ExecuteQueryRetry(); if (securable.HasUniqueRoleAssignments) { security = new ObjectSecurity(); foreach (var roleAssignment in roleAssignments) { if (roleAssignment.Member.LoginName != "Excel Services Viewers") { foreach (var roleDefinition in roleAssignment.RoleDefinitionBindings) { if (roleDefinition.RoleTypeKind != RoleType.Guest) { security.RoleAssignments.Add(new Model.RoleAssignment() { Principal = parser.TokenizePrincipalLogin(roleAssignment.Member.LoginName), RoleDefinition = roleDefinition.Name }); } } } } } } return security; }
internal static void LocalizeView(this Microsoft.SharePoint.Client.View view, Web web, string token, TokenParser parser, PnPMonitoredScope scope) { if (CanUseAcceptLanguageHeaderForLocalization(web)) { var context = web.Context; var resourceValues = parser.GetResourceTokenResourceValues(token); foreach (var resourceValue in resourceValues) { // Save property with correct locale on the request to make it stick // http://sadomovalex.blogspot.no/2015/09/localize-web-part-titles-via-client.html context.PendingRequest.RequestExecutor.WebRequest.Headers["Accept-Language"] = resourceValue.Item1; view.Title = resourceValue.Item2; view.Update(); context.ExecuteQueryRetry(); } } else { // warning scope.LogWarning(CoreResources.Provisioning_Extensions_ViewLocalization_Skip); } }
public void CanProvisionObjects() { var template = new ProvisioningTemplate(); var listInstance = new Core.Framework.Provisioning.Model.ListInstance(); listInstance.Url = string.Format("lists/{0}", listName); listInstance.Title = listName; listInstance.TemplateType = (int) ListTemplateType.GenericList; Dictionary<string, string> dataValues = new Dictionary<string, string>(); dataValues.Add("Title","Test"); DataRow dataRow = new DataRow(dataValues); listInstance.DataRows.Add(dataRow); template.Lists.Add(listInstance); using (var ctx = TestCommon.CreateClientContext()) { var parser = new TokenParser(ctx.Web, template); // Create the List parser = new ObjectListInstance().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); // Load DataRows new ObjectListInstanceDataRows().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); var list = ctx.Web.GetListByUrl(listInstance.Url); Assert.IsNotNull(list); var items = list.GetItems(CamlQuery.CreateAllItemsQuery()); ctx.Load(items, itms => itms.Include(item => item["Title"])); ctx.ExecuteQueryRetry(); Assert.IsTrue(items.Count == 1); Assert.IsTrue(items[0]["Title"].ToString() == "Test"); } }
public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation) { using (var scope = new PnPMonitoredScope(this.Name)) { if (template.Navigation != null) { if (!WebSupportsProvisionNavigation(web, template)) { scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Navigation_Context_web_is_not_publishing); return(parser); } // Check if this is not a noscript site as navigation features are not supported bool isNoScriptSite = web.IsNoScriptSite(); // Retrieve the current web navigation settings var navigationSettings = new WebNavigationSettings(web.Context, web); web.Context.Load(navigationSettings, ns => ns.CurrentNavigation, ns => ns.GlobalNavigation); web.Context.ExecuteQueryRetry(); navigationSettings.AddNewPagesToNavigation = template.Navigation.AddNewPagesToNavigation; navigationSettings.CreateFriendlyUrlsForNewPages = template.Navigation.CreateFriendlyUrlsForNewPages; if (!isNoScriptSite) { navigationSettings.Update(TaxonomySession.GetTaxonomySession(web.Context)); web.Context.ExecuteQueryRetry(); } if (template.Navigation.GlobalNavigation != null) { switch (template.Navigation.GlobalNavigation.NavigationType) { case GlobalNavigationType.Inherit: navigationSettings.GlobalNavigation.Source = StandardNavigationSource.InheritFromParentWeb; web.Navigation.UseShared = true; break; case GlobalNavigationType.Managed: if (template.Navigation.GlobalNavigation.ManagedNavigation == null) { throw new ApplicationException(CoreResources.Provisioning_ObjectHandlers_Navigation_missing_global_managed_navigation); } navigationSettings.GlobalNavigation.Source = StandardNavigationSource.TaxonomyProvider; navigationSettings.GlobalNavigation.TermStoreId = Guid.Parse(parser.ParseString(template.Navigation.GlobalNavigation.ManagedNavigation.TermStoreId)); navigationSettings.GlobalNavigation.TermSetId = Guid.Parse(parser.ParseString(template.Navigation.GlobalNavigation.ManagedNavigation.TermSetId)); web.Navigation.UseShared = false; break; case GlobalNavigationType.Structural: default: if (template.Navigation.GlobalNavigation.StructuralNavigation == null) { throw new ApplicationException(CoreResources.Provisioning_ObjectHandlers_Navigation_missing_global_structural_navigation); } navigationSettings.GlobalNavigation.Source = StandardNavigationSource.PortalProvider; web.Navigation.UseShared = false; break; } if (!isNoScriptSite) { navigationSettings.Update(TaxonomySession.GetTaxonomySession(web.Context)); web.Context.ExecuteQueryRetry(); } // Need to set navigation nodes after update navigation settings if (template.Navigation.GlobalNavigation.NavigationType == GlobalNavigationType.Structural) { ProvisionGlobalStructuralNavigation(web, template.Navigation.GlobalNavigation.StructuralNavigation, parser, applyingInformation.ClearNavigation, scope); } } if (template.Navigation.CurrentNavigation != null) { switch (template.Navigation.CurrentNavigation.NavigationType) { case CurrentNavigationType.Inherit: navigationSettings.CurrentNavigation.Source = StandardNavigationSource.InheritFromParentWeb; break; case CurrentNavigationType.Managed: if (template.Navigation.CurrentNavigation.ManagedNavigation == null) { throw new ApplicationException(CoreResources.Provisioning_ObjectHandlers_Navigation_missing_current_managed_navigation); } navigationSettings.CurrentNavigation.Source = StandardNavigationSource.TaxonomyProvider; navigationSettings.CurrentNavigation.TermStoreId = Guid.Parse(parser.ParseString(template.Navigation.CurrentNavigation.ManagedNavigation.TermStoreId)); navigationSettings.CurrentNavigation.TermSetId = Guid.Parse(parser.ParseString(template.Navigation.CurrentNavigation.ManagedNavigation.TermSetId)); break; case CurrentNavigationType.StructuralLocal: if (!isNoScriptSite) { web.SetPropertyBagValue(NavigationShowSiblings, "false"); } if (template.Navigation.CurrentNavigation.StructuralNavigation == null) { throw new ApplicationException(CoreResources.Provisioning_ObjectHandlers_Navigation_missing_current_structural_navigation); } navigationSettings.CurrentNavigation.Source = StandardNavigationSource.PortalProvider; break; case CurrentNavigationType.Structural: default: if (!isNoScriptSite) { web.SetPropertyBagValue(NavigationShowSiblings, "true"); } if (template.Navigation.CurrentNavigation.StructuralNavigation == null) { throw new ApplicationException(CoreResources.Provisioning_ObjectHandlers_Navigation_missing_current_structural_navigation); } navigationSettings.CurrentNavigation.Source = StandardNavigationSource.PortalProvider; break; } if (!isNoScriptSite) { navigationSettings.Update(TaxonomySession.GetTaxonomySession(web.Context)); web.Context.ExecuteQueryRetry(); } // Need to set navigation nodes after update navigation settings if (template.Navigation.CurrentNavigation.NavigationType == CurrentNavigationType.Structural || template.Navigation.CurrentNavigation.NavigationType == CurrentNavigationType.StructuralLocal) { ProvisionCurrentStructuralNavigation(web, template.Navigation.CurrentNavigation.StructuralNavigation, parser, applyingInformation.ClearNavigation, scope); } } if (template.Navigation.SearchNavigation != null) { var structuralNavigation = new StructuralNavigation(); structuralNavigation.NavigationNodes.AddRange(template.Navigation.SearchNavigation.NavigationNodes); structuralNavigation.RemoveExistingNodes = template.Navigation.SearchNavigation.RemoveExistingNodes; ProvisionSearchNavigation(web, structuralNavigation, parser, applyingInformation.ClearNavigation, scope); } } } return(parser); }
private void ProvisionStructuralNavigation(Web web, StructuralNavigation structuralNavigation, TokenParser parser, Enums.NavigationType navigationType, bool clearNavigation, PnPMonitoredScope scope) { // Determine the target structural navigation //var navigationType = currentNavigation ? // Enums.NavigationType.QuickLaunch : // Enums.NavigationType.TopNavigationBar; if (structuralNavigation != null) { // Remove existing nodes, if requested if (structuralNavigation.RemoveExistingNodes || clearNavigation) { if (!structuralNavigation.RemoveExistingNodes && !ClearWarningShown) { WriteMessage("You chose to override the template value RemoveExistingNodes=\"false\" by specifying ClearNavigation", ProvisioningMessageType.Warning); ClearWarningShown = true; } web.DeleteAllNavigationNodes(navigationType); } // Provision root level nodes, and children recursively if (structuralNavigation.NavigationNodes.Any()) { ProvisionStructuralNavigationNodes( web, parser, navigationType, structuralNavigation.NavigationNodes, scope ); } } }
private void ProvisionCurrentStructuralNavigation(Web web, StructuralNavigation structuralNavigation, TokenParser parser, bool clearNavigation, PnPMonitoredScope scope) { ProvisionStructuralNavigation(web, structuralNavigation, parser, Enums.NavigationType.QuickLaunch, clearNavigation, scope); }
internal static List <ReusedTerm> ProcessGroup(ClientContext context, TaxonomySession session, TermStore termStore, Model.TermGroup modelTermGroup, TermGroup siteCollectionTermGroup, TokenParser parser, PnPMonitoredScope scope) { List <ReusedTerm> reusedTerms = new List <ReusedTerm>(); SiteCollectionTermGroupNameToken siteCollectionTermGroupNameToken = new SiteCollectionTermGroupNameToken(context.Web); #region Group var newGroup = false; var modelGroupName = parser.ParseString(modelTermGroup.Name); var normalizedGroupName = TaxonomyItem.NormalizeName(context, modelGroupName); context.ExecuteQueryRetry(); TermGroup group = termStore.Groups.FirstOrDefault( g => g.Id == modelTermGroup.Id || g.Name == normalizedGroupName.Value); if (group == null) { var parsedDescription = parser.ParseString(modelTermGroup.Description); if (modelTermGroup.Name == "Site Collection" || modelGroupName == siteCollectionTermGroupNameToken.GetReplaceValue() || modelTermGroup.SiteCollectionTermGroup) { var site = context.Site; group = termStore.GetSiteCollectionGroup(site, true); context.Load(group, g => g.Name, g => g.Id, g => g.TermSets.Include( tset => tset.Name, tset => tset.Id)); context.ExecuteQueryRetry(); } else { group = termStore.Groups.FirstOrDefault(g => g.Name == normalizedGroupName.Value); if (group == null) { if (modelTermGroup.Id == Guid.Empty) { modelTermGroup.Id = Guid.NewGuid(); } group = termStore.CreateGroup(modelGroupName, modelTermGroup.Id); group.Description = parsedDescription; // Handle TermGroup Contributors, if any if (modelTermGroup.Contributors != null && modelTermGroup.Contributors.Count > 0) { foreach (var c in modelTermGroup.Contributors) { group.AddContributor(c.Name); } } // Handle TermGroup Managers, if any if (modelTermGroup.Managers != null && modelTermGroup.Managers.Count > 0) { foreach (var m in modelTermGroup.Managers) { group.AddGroupManager(m.Name); } } termStore.CommitAll(); context.Load(group); context.Load(termStore); context.ExecuteQueryRetry(); newGroup = true; } } } #endregion session.UpdateCache(); session.Context.ExecuteQueryRetry(); #region TermSets foreach (var modelTermSet in modelTermGroup.TermSets) { TermSet set = null; var newTermSet = false; var normalizedTermSetName = TaxonomyItem.NormalizeName(context, parser.ParseString(modelTermSet.Name)); context.ExecuteQueryRetry(); if (!newGroup) { set = group.TermSets.FirstOrDefault( ts => ts.Id == modelTermSet.Id || ts.Name == normalizedTermSetName.Value); } if (set == null) { if (modelTermSet.Id == Guid.Empty) { modelTermSet.Id = Guid.NewGuid(); } else { if (CheckIfTermSetIdIsUnique(termStore, modelTermSet.Id) == false) { throw new Exception($"Termset ID {modelTermSet.Id} is already present in termstore"); } } var termSetLanguage = modelTermSet.Language.HasValue ? modelTermSet.Language.Value : termStore.DefaultLanguage; set = group.CreateTermSet(normalizedTermSetName.Value, modelTermSet.Id, termSetLanguage); parser.AddToken(new TermSetIdToken(context.Web, group.Name, normalizedTermSetName.Value, modelTermSet.Id)); if (siteCollectionTermGroup != null && !siteCollectionTermGroup.ServerObjectIsNull.Value) { if (group.Name == siteCollectionTermGroup.Name) { parser.AddToken((new SiteCollectionTermSetIdToken(context.Web, normalizedTermSetName.Value, modelTermSet.Id))); } } newTermSet = true; if (!string.IsNullOrEmpty(modelTermSet.Description)) { set.Description = parser.ParseString(modelTermSet.Description); } set.IsOpenForTermCreation = modelTermSet.IsOpenForTermCreation; set.IsAvailableForTagging = modelTermSet.IsAvailableForTagging; foreach (var property in modelTermSet.Properties) { set.SetCustomProperty(property.Key, parser.ParseString(property.Value)); } if (modelTermSet.Owner != null) { set.Owner = parser.ParseString(modelTermSet.Owner); } termStore.CommitAll(); context.Load(set); context.ExecuteQueryRetry(); } context.Load(set, s => s.Terms.Include(t => t.Id, t => t.Name)); context.ExecuteQueryRetry(); var terms = set.Terms; foreach (var modelTerm in modelTermSet.Terms) { if (!newTermSet) { if (terms.Any()) { var term = terms.FirstOrDefault(t => t.Id == modelTerm.Id); if (term == null) { var normalizedTermName = TaxonomyItem.NormalizeName(context, parser.ParseString(modelTerm.Name)); context.ExecuteQueryRetry(); term = terms.FirstOrDefault(t => t.Name == normalizedTermName.Value); if (term == null) { var returnTuple = CreateTerm(context, modelTerm, set, termStore, parser, scope); if (returnTuple != null) { modelTerm.Id = returnTuple.Item1; parser = returnTuple.Item2; } reusedTerms.AddRange(returnTuple.Item3); } else { // todo: add handling for reused term? modelTerm.Id = term.Id; } } else { // todo: add handling for reused term? modelTerm.Id = term.Id; } if (term != null) { CheckChildTerms(context, modelTerm, term, termStore, parser, scope); } } else { var returnTuple = CreateTerm(context, modelTerm, set, termStore, parser, scope); if (returnTuple != null) { modelTerm.Id = returnTuple.Item1; parser = returnTuple.Item2; } reusedTerms.AddRange(returnTuple.Item3); } } else { var returnTuple = CreateTerm(context, modelTerm, set, termStore, parser, scope); if (returnTuple != null) { modelTerm.Id = returnTuple.Item1; parser = returnTuple.Item2; } reusedTerms.AddRange(returnTuple.Item3); } } // do we need custom sorting? if (modelTermSet.Terms.Any(t => t.CustomSortOrder > 0)) { var sortedTerms = modelTermSet.Terms.OrderBy(t => t.CustomSortOrder); var customSortString = sortedTerms.Aggregate(string.Empty, (a, i) => a + i.Id.ToString() + ":"); customSortString = customSortString.TrimEnd(new[] { ':' }); set.CustomSortOrder = customSortString; termStore.CommitAll(); context.ExecuteQueryRetry(); } } #endregion return(reusedTerms); }
private void ProvisionStructuralNavigationNodes(Web web, TokenParser parser, Enums.NavigationType navigationType, Model.NavigationNodeCollection nodes, PnPMonitoredScope scope, string parentNodeTitle = null, string l1ParentNodeTitle = null) { foreach (var node in nodes) { try { string fileUrl = ReplaceFileUniqueToken(web, parser.ParseString(node.Url)); var navNode = web.AddNavigationNode( parser.ParseString(node.Title), new Uri(fileUrl, UriKind.RelativeOrAbsolute), parser.ParseString(parentNodeTitle), navigationType, node.IsExternal, l1ParentNodeTitle: l1ParentNodeTitle ); if (node.Title.ContainsResourceToken()) { navNode.LocalizeNavigationNode(web, node.Title, parser, scope); } } catch (ServerException ex) { // If the SharePoint link doesn't exist, provision it as external link // when we provision as external link, the server side URL validation won't kick-in // This handles the "no such file or url found" error WriteMessage(String.Format(CoreResources.Provisioning_ObjectHandlers_Navigation_Link_Provisioning_Failed_Retry, node.Title), ProvisioningMessageType.Warning); if (ex.ServerErrorCode == -2130247147) { try { string fileUrl = ReplaceFileUniqueToken(web, parser.ParseString(node.Url)); var navNode = web.AddNavigationNode( parser.ParseString(node.Title), new Uri(fileUrl, UriKind.RelativeOrAbsolute), parser.ParseString(parentNodeTitle), navigationType, true, l1ParentNodeTitle: l1ParentNodeTitle ); } catch (Exception innerEx) { WriteMessage(String.Format(CoreResources.Provisioning_ObjectHandlers_Navigation_Link_Provisioning_Failed, innerEx.Message), ProvisioningMessageType.Warning); } } else { WriteMessage(String.Format(CoreResources.Provisioning_ObjectHandlers_Navigation_Link_Provisioning_Failed, ex.Message), ProvisioningMessageType.Warning); } } ProvisionStructuralNavigationNodes( web, parser, navigationType, node.NavigationNodes, scope, parser.ParseString(node.Title), parentNodeTitle ); } }
/// <summary> /// Creates child terms for the current model term if any exist /// </summary> /// <param name="context"></param> /// <param name="modelTerm"></param> /// <param name="term"></param> /// <param name="termStore"></param> /// <param name="parser"></param> /// <param name="scope"></param> /// <returns>Updated parser object</returns> private static TokenParser CreateChildTerms(ClientContext context, Model.Term modelTerm, Term term, TermStore termStore, TokenParser parser, PnPMonitoredScope scope) { if (modelTerm.Terms.Any()) { foreach (var modelTermTerm in modelTerm.Terms) { context.Load(term.Terms); context.ExecuteQueryRetry(); var termTerms = term.Terms; if (termTerms.Any()) { var termTerm = termTerms.FirstOrDefault(t => t.Id == modelTermTerm.Id); if (termTerm == null) { termTerm = termTerms.FirstOrDefault(t => t.Name == modelTermTerm.Name); if (termTerm == null) { var returnTuple = CreateTerm(context, modelTermTerm, term, termStore, parser, scope); if (returnTuple != null) { modelTermTerm.Id = returnTuple.Item1; parser = returnTuple.Item2; } } else { modelTermTerm.Id = termTerm.Id; } } else { modelTermTerm.Id = termTerm.Id; } } else { var returnTuple = CreateTerm(context, modelTermTerm, term, termStore, parser, scope); if (returnTuple != null) { modelTermTerm.Id = returnTuple.Item1; parser = returnTuple.Item2; } } } if (modelTerm.Terms.Any(t => t.CustomSortOrder > 0)) { var sortedTerms = modelTerm.Terms.OrderBy(t => t.CustomSortOrder); var customSortString = sortedTerms.Aggregate(string.Empty, (a, i) => a + i.Id.ToString() + ":"); customSortString = customSortString.TrimEnd(new[] { ':' }); term.CustomSortOrder = customSortString; termStore.CommitAll(); } } return(parser); }
internal static Tuple <Guid, TokenParser, List <ReusedTerm> > CreateTerm(ClientContext context, Model.Term modelTerm, TaxonomyItem parent, TermStore termStore, TokenParser parser, PnPMonitoredScope scope) { var reusedTerms = new List <ReusedTerm>(); // If the term is a re-used term and the term is not a source term, skip for now and create later if (modelTerm.IsReused && !modelTerm.IsSourceTerm) { reusedTerms.Add(new ReusedTerm() { ModelTerm = modelTerm, Parent = parent, TermStore = termStore }); return(Tuple.Create(modelTerm.Id, parser, reusedTerms)); } // Create new term Term term; if (modelTerm.Id == Guid.Empty) { modelTerm.Id = Guid.NewGuid(); } else { if (CheckIfTermIdIsUnique(termStore, modelTerm.Id) == false) { throw new Exception($"Term ID {modelTerm.Id} is already present in termstore"); } } if (parent is Term) { term = ((Term)parent).CreateTerm(parser.ParseString(modelTerm.Name), modelTerm.Language != null && modelTerm.Language != 0 ? modelTerm.Language.Value : termStore.DefaultLanguage, modelTerm.Id); } else { term = ((TermSet)parent).CreateTerm(parser.ParseString(modelTerm.Name), modelTerm.Language != null && modelTerm.Language != 0 ? modelTerm.Language.Value : termStore.DefaultLanguage, modelTerm.Id); } if (!string.IsNullOrEmpty(modelTerm.Description)) { term.SetDescription(parser.ParseString(modelTerm.Description), modelTerm.Language != null && modelTerm.Language != 0 ? modelTerm.Language.Value : termStore.DefaultLanguage); } if (!string.IsNullOrEmpty(modelTerm.Owner)) { term.Owner = modelTerm.Owner; } term.IsAvailableForTagging = modelTerm.IsAvailableForTagging; if (modelTerm.Properties.Any() || modelTerm.Labels.Any() || modelTerm.LocalProperties.Any()) { if (modelTerm.Labels.Any()) { CreateTermLabels(modelTerm, termStore, parser, scope, term); } if (modelTerm.Properties.Any()) { SetTermCustomProperties(modelTerm, parser, term); } if (modelTerm.LocalProperties.Any()) { SetTermLocalCustomProperties(modelTerm, parser, term); } } termStore.CommitAll(); context.Load(term); context.ExecuteQueryRetry(); // Deprecate term if needed if (modelTerm.IsDeprecated != term.IsDeprecated) { term.Deprecate(modelTerm.IsDeprecated); context.ExecuteQueryRetry(); } parser = CreateChildTerms(context, modelTerm, term, termStore, parser, scope); return(Tuple.Create(modelTerm.Id, parser, reusedTerms)); }
public static void RunInterpeted(string name, IReadOnlyList <IAssembly <InterpetedAssemblyBacking> > dependencies, string toRun) { var module = new TokenParser().Parse <IAssembly <InterpetedAssemblyBacking>, InterpetedAssemblyBacking>(toRun, dependencies, name); Interpeter.Run(module.Is1OrThrow()); }
public virtual bool ValidateObjectXML(string source, string target, List <string> properties, TokenParser tokenParser = null, Dictionary <string, string[]> parsedProperties = null) { XElement sourceXml = XElement.Parse(source); XElement targetXml = XElement.Parse(target); if (tokenParser != null && parsedProperties != null) { // Run token parser over provided list of properties foreach (var property in properties) { if (sourceXml.Attribute(property) != null) { string[] parserExceptions; parsedProperties.TryGetValue(property, out parserExceptions); sourceXml.Attribute(property).Value = tokenParser.ParseString(sourceXml.Attribute(property).Value, parserExceptions); if (targetXml.Attribute(property) != null) { targetXml.Attribute(property).Value = tokenParser.ParseString(targetXml.Attribute(property).Value, parserExceptions); } } } } // call virtual override method, consuming validators can add fixed validation logic if needed OverrideXmlData(sourceXml, targetXml); // call event handler, validator instances can add additional validation behaviour if needed, including forcing an IsEqual ValidateXmlEventArgs e = null; if (ValidateXmlEvent != null) { e = new ValidateXmlEventArgs(sourceXml, targetXml); ValidateXmlEvent(this, e); } if (e != null && e.IsEqual) { // Do nothing since we've declared equality in the event handler } else { // Not using XNode.DeepEquals anymore since it requires that the attributes in both XML's are ordered the same //var equalNodes = XNode.DeepEquals(sourceXml, targetXml); var equalNodes = XmlComparer.AreEqual(sourceXml, targetXml); if (!equalNodes.Success) { Console.WriteLine(string.Format("Source XML:{0}", sourceXml.ToString())); Console.WriteLine(string.Format("Target XML:{0}", targetXml.ToString())); return(false); } } return(true); }
public bool Validate(TermGroupCollection sourceCollection, TermGroupCollection targetCollection, TokenParser tokenParser) { // Convert object collections to XML List <SerializedTermGroupInstance> sourceTermGroups = new List <SerializedTermGroupInstance>(); List <SerializedTermGroupInstance> targetTermGroups = new List <SerializedTermGroupInstance>(); foreach (TermGroup termGroup in sourceCollection) { ProvisioningTemplate pt = new ProvisioningTemplate(); pt.TermGroups.Add(termGroup); sourceTermGroups.Add(new SerializedTermGroupInstance() { SchemaXml = ExtractElementXml(pt) }); } foreach (TermGroup termGroup in targetCollection) { ProvisioningTemplate pt = new ProvisioningTemplate(); pt.TermGroups.Add(termGroup); targetTermGroups.Add(new SerializedTermGroupInstance() { SchemaXml = ExtractElementXml(pt) }); } // Use XML validation logic to compare source and target Dictionary <string, string[]> parserSettings = new Dictionary <string, string[]> { { "SchemaXml", null } }; bool isTermGroupsMatch = ValidateObjectsXML(sourceTermGroups, targetTermGroups, "SchemaXml", new List <string> { "Name" }, tokenParser, parserSettings); Console.WriteLine("-- Term group validation " + isTermGroupsMatch); return(isTermGroupsMatch); }
public void Provision(ClientContext ctx, ProvisioningTemplate template, ProvisioningTemplateApplyingInformation applyingInformation, TokenParser tokenParser, PnPMonitoredScope scope, string configurationData) { if (!string.IsNullOrEmpty(configurationData)) { // Get the current web var web = ctx.Web; // Read configuration data from the template var configuration = XDocument.Parse(configurationData); var ns = configuration.Root.GetDefaultNamespace(); var libraries = configuration.Descendants(ns + "Library"); foreach (var library in libraries) { var libraryTitle = library.Attribute("Title").Value; //Get the library List list = ctx.Web.Lists.GetByTitle(libraryTitle); if (list != null) { var items = library.Descendants(ns + "Default"); foreach (var item in items) { // Get configuration infos var fieldName = item.Attribute("InternalName").Value; var fieldValue = item.Attribute("Value").Value; var folder = item.Attribute("Folder").Value; // Get the field var field = list.Fields.GetByInternalNameOrTitle(fieldName); ctx.Load(field, f => f.InternalName, f => f.TypeAsString); ctx.ExecuteQueryRetry(); if (field != null) { IDefaultColumnValue defaultColumnValue = null; if (field.TypeAsString == "Text") { var values = string.Join(";", fieldValue); defaultColumnValue = new DefaultColumnTextValue() { FieldInternalName = field.InternalName, FolderRelativePath = folder, Text = values }; } else { var terms = new List <Microsoft.SharePoint.Client.Taxonomy.Term>(); var values = fieldValue.Split(';'); foreach (var termString in values) { var term = ctx.Site.GetTaxonomyItemByPath(termString); if (term != null) { terms.Add(term as Microsoft.SharePoint.Client.Taxonomy.Term); } } if (terms.Any()) { defaultColumnValue = new DefaultColumnTermValue() { FieldInternalName = field.InternalName, FolderRelativePath = folder, }; terms.ForEach(t => ((DefaultColumnTermValue)defaultColumnValue).Terms.Add(t)); } } if (defaultColumnValue != null) { list.SetDefaultColumnValues(new List <IDefaultColumnValue>() { defaultColumnValue }); } } } } } } }
public virtual bool ValidateObjects <T>(T sourceElement, T targetElement, List <string> properties, TokenParser tokenParser = null, Dictionary <string, string[]> parsedProperties = null) where T : class { IEnumerable sElements = (IEnumerable)sourceElement; IEnumerable tElements = (IEnumerable)targetElement; string key = properties[0]; int sourceCount = 0; int targetCount = 0; foreach (object sElem in sElements) { sourceCount++; string sourceKey = sElem.GetType().GetProperty(key).GetValue(sElem).ToString(); if (tokenParser != null && parsedProperties != null) { if (parsedProperties.ContainsKey(key)) { string[] parserExceptions; parsedProperties.TryGetValue(key, out parserExceptions); sourceKey = tokenParser.ParseString(Convert.ToString(sourceKey), parserExceptions); } } foreach (object tElem in tElements) { string targetKey = tElem.GetType().GetProperty(key).GetValue(tElem).ToString(); if (sourceKey.Equals(targetKey)) { targetCount++; //compare objects foreach (string property in properties) { string sourceProperty = sElem.GetType().GetProperty(property).GetValue(sElem).ToString(); if (tokenParser != null && parsedProperties != null) { if (parsedProperties.ContainsKey(property)) { string[] parserExceptions; parsedProperties.TryGetValue(key, out parserExceptions); sourceProperty = tokenParser.ParseString(Convert.ToString(sourceProperty), parserExceptions); } } string targetProperty = tElem.GetType().GetProperty(property).GetValue(tElem).ToString(); ValidateEventArgs e = null; if (ValidateEvent != null) { e = new ValidateEventArgs(property, sourceProperty, targetProperty, sElem, tElem); ValidateEvent(this, e); } if (e != null && e.IsEqual) { // Do nothing since we've declared equality in the event handler } else { if (!sourceProperty.Equals(targetProperty)) { return(false); } } } break; } } } return(sourceCount == targetCount); }
public static bool ValidateCustomActions(CustomActionCollection source, CustomActionCollection target, TokenParser tokenParser, Web web = null) { int sCount = 0; int tCount = 0; if (web != null && web.IsNoScriptSite()) { Console.WriteLine("Skipping validation of custom actions due to noscript site."); return(true); } foreach (CustomAction srcSCA in source) { //Only count the enabled ones if (srcSCA.Enabled && !srcSCA.Remove) { // ensure token in source are parsed before comparing with target srcSCA.Title = tokenParser.ParseString(srcSCA.Title); srcSCA.ImageUrl = tokenParser.ParseString(srcSCA.ImageUrl); srcSCA.ScriptBlock = tokenParser.ParseString(srcSCA.ScriptBlock); srcSCA.ScriptSrc = tokenParser.ParseString(srcSCA.ScriptSrc, "~site", "~sitecollection"); srcSCA.Title = tokenParser.ParseString(srcSCA.Title); srcSCA.Url = tokenParser.ParseString(srcSCA.Url); if (srcSCA.CommandUIExtension != null) { srcSCA.CommandUIExtension = XElement.Parse(tokenParser.ParseString(srcSCA.CommandUIExtension.ToString())); } sCount++; foreach (CustomAction tgtSCA in target) { if (tgtSCA.CommandUIExtension != null) { // Drop the namespace attribute before comparing (xmlns="http://schemas.microsoft.com/sharepoint"). // SharePoint injects this namespace when we extract a custom action that has a commandUIExtension tgtSCA.CommandUIExtension = RemoveAllNamespaces(tgtSCA.CommandUIExtension); } // Use our custom action "Equals" implementation if (srcSCA.Equals(tgtSCA)) { tCount++; break; } else { Console.WriteLine("{0} is not matching", tgtSCA.Name); } } } } if (sCount != tCount) { return(false); } // cross check that enabled false custom actions do not exist anymore foreach (CustomAction srcSCA in source) { if (!srcSCA.Enabled || srcSCA.Remove) { var ca = target.Where(w => w.Name == srcSCA.Name).FirstOrDefault(); if (ca != null) { return(false); } } } return(true); }
public static bool Validate(CustomActions sourceCustomActions, CustomActions targetCustomActions, TokenParser tokenParser, Web web) { if (web.IsNoScriptSite()) { Console.WriteLine("Skipping validation of custom actions due to noscript site."); return(true); } Console.WriteLine("Custom Action validation started..."); bool isSiteCustomActionsMatch = false; bool isWebCustomActionsMatch = false; if (sourceCustomActions.SiteCustomActions.Count > 0) { isSiteCustomActionsMatch = ValidateCustomActions(sourceCustomActions.SiteCustomActions, targetCustomActions.SiteCustomActions, tokenParser, web); Console.WriteLine("Site Custom Actions validation " + isSiteCustomActionsMatch); } if (sourceCustomActions.WebCustomActions.Count > 0) { isWebCustomActionsMatch = ValidateCustomActions(sourceCustomActions.WebCustomActions, targetCustomActions.WebCustomActions, tokenParser, web); Console.WriteLine("Web Custom Actions validation " + isWebCustomActionsMatch); } if (!isSiteCustomActionsMatch || !isWebCustomActionsMatch) { return(false); } else { return(true); } }
internal static void LocalizeWebParts(this File file, Web web, TokenParser parser, Microsoft.SharePoint.Client.File targetFile, PnPMonitoredScope scope) { var url = targetFile.ServerRelativeUrl; var webParts = file.WebParts; LocalizeParts(web, parser, url, webParts, scope); }
public virtual bool ValidateObjectsXML <T>(IEnumerable <T> sElements, IEnumerable <T> tElements, string XmlPropertyName, List <string> properties, TokenParser tokenParser = null, Dictionary <string, string[]> parsedProperties = null) where T : class { string key = properties[0]; int sourceCount = 0; int targetCount = 0; foreach (var sElem in sElements) { sourceCount++; string sourceXmlString = sElem.GetType().GetProperty(XmlPropertyName).GetValue(sElem).ToString(); if (tokenParser != null && parsedProperties != null) { if (parsedProperties.ContainsKey(XmlPropertyName)) { string[] parserExceptions; parsedProperties.TryGetValue(XmlPropertyName, out parserExceptions); sourceXmlString = tokenParser.ParseString(Convert.ToString(sourceXmlString), parserExceptions); } } XElement sourceXml = XElement.Parse(sourceXmlString); string sourceKeyValue = sourceXml.Attribute(key).Value; foreach (var tElem in tElements) { string targetXmlString = tElem.GetType().GetProperty(XmlPropertyName).GetValue(tElem).ToString(); if (tokenParser != null && parsedProperties != null) { if (parsedProperties.ContainsKey(XmlPropertyName)) { string[] parserExceptions; parsedProperties.TryGetValue(XmlPropertyName, out parserExceptions); targetXmlString = tokenParser.ParseString(Convert.ToString(targetXmlString), parserExceptions); } } XElement targetXml = XElement.Parse(targetXmlString); string targetKeyValue = targetXml.Attribute(key).Value; if (sourceKeyValue.Equals(targetKeyValue, StringComparison.InvariantCultureIgnoreCase)) { targetCount++; // compare XML's // call virtual override method, consuming validators can add fixed validation logic if needed OverrideXmlData(sourceXml, targetXml); // call event handler, validator instances can add additional validation behaviour if needed, including forcing an IsEqual ValidateXmlEventArgs e = null; if (ValidateXmlEvent != null) { e = new ValidateXmlEventArgs(sourceXml, targetXml); ValidateXmlEvent(this, e); } if (e != null && e.IsEqual) { // Do nothing since we've declared equality in the event handler } else { // Not using XNode.DeepEquals anymore since it requires that the attributes in both XML's are ordered the same //var equalNodes = XNode.DeepEquals(sourceXml, targetXml); var equalNodes = XmlComparer.AreEqual(sourceXml, targetXml); if (!equalNodes.Success) { Console.WriteLine(string.Format("Source XML:{0}", sourceXml.ToString())); Console.WriteLine(string.Format("Target XML:{0}", targetXml.ToString())); return(false); } } break; } } } return(sourceCount == targetCount); }
private void RefineTemplate(ClientContext context, ProvisioningTemplate template, ProvisioningTemplateApplyingInformation ptai, string type = "NotSet", string docIdPrefix = "") { try { switch (type?.ToUpper()) { case "PRE": template.Files.RemoveAll(x => true); template.Navigation = null; break; case "POST": template.Lists.RemoveAll(x => true); template.SiteFields.RemoveAll(x => true); template.ContentTypes.RemoveAll(x => true); break; case "INIT": template.Files.RemoveAll(x => true); template.Lists.RemoveAll(x => true); template.Navigation = null; break; case "LISTS": template.Files.RemoveAll(x => true); template.Navigation = null; break; case "FILES": template.Lists.RemoveAll(x => true); template.Navigation = null; break; case "NAVIGATION": template.Files.RemoveAll(x => true); template.Lists.RemoveAll(x => true); break; } var web = context.Web; if (!string.IsNullOrEmpty(docIdPrefix)) { SetDocumentId(context, web, docIdPrefix); } var isSubSite = web.IsSubSite(); if (isSubSite) { var tokenParser = new TokenParser(web, template); if (template.SiteFields.Any()) { var columnProvisionManager = new SiteColumnProvisionManager(); columnProvisionManager.Provision(web, template, tokenParser, ptai); } if (template.ContentTypes.Any()) { var contentTypeProvisionManager = new ContentTypeProvisionManager(); contentTypeProvisionManager.Provision(web, template, tokenParser, ptai); } template.Files.RemoveAll( f => f.Src.EndsWith(".master", StringComparison.InvariantCultureIgnoreCase)); } var pageLib = context.Web.GetPagesLibrary(); if (template.Files.Any()) { foreach (var file in template.Files) { if (file.Src.EndsWith(".aspx")) { file.Src = $"{pageLib.Title}\\{file.Src}"; } } } } catch (Exception ex) { throw ex; } }
public TokenizedContentPackValueProvider(string rawString, TokenParser tokenParser) { this._parts = tokenParser.ParseRawValue(rawString).ToArray(); }
private static void CreateTermLabels(Model.Term modelTerm, TermStore termStore, TokenParser parser, PnPMonitoredScope scope, Term term) { foreach (var label in modelTerm.Labels) { if (((label.IsDefaultForLanguage && label.Language != termStore.DefaultLanguage) || label.IsDefaultForLanguage == false) && termStore.Languages.Contains(label.Language)) { term.CreateLabel(parser.ParseString(label.Value), label.Language, label.IsDefaultForLanguage); } else { scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_TermGroups_Skipping_label__0___label_is_to_set_to_default_for_language__1__while_the_default_termstore_language_is_also__1_, label.Value, label.Language); } } }
private bool Validatelocalization(List <Localization> sElements, List <Localization> tElements, TokenParser sParser, TokenParser tParser) { bool isValid = false; int sCount = 0; int tCount = 0; foreach (var sElement in sElements) { var sTokenValue1 = sElement.Title; var sTokenValue2 = sElement.Description; string sKey = sElement.Key; bool isProp1ContainsRes = sTokenValue1.ContainsResourceToken(); bool isProp2ContainsRes = sTokenValue2.ContainsResourceToken(); if (isProp1ContainsRes || isProp2ContainsRes) { sCount++; foreach (var tElement in tElements) { var tKey = tElement.Key; if (sKey.ToLower() == tKey.ToLower()) { if (isProp1ContainsRes) { if (!ValidateResourceEntries(sParser, tParser, sTokenValue1, tElement.Title)) { return(false); } } if (isProp2ContainsRes) { if (!ValidateResourceEntries(sParser, tParser, sTokenValue2, tElement.Description)) { return(false); } } if (sElement.Fields != null) // validate if list contains fields { if (!ValidateSiteFields(sElement.Fields, tElement.Fields, sParser, tParser)) { return(false); } } tCount++; break; } } } } if (sCount == tCount) { isValid = true; } return(isValid); }
public override void ProvisionObjects(Web web, ProvisioningTemplate template) { if (template.ComposedLook != null && !template.ComposedLook.Equals(ComposedLook.Empty)) { bool executeQueryNeeded = false; TokenParser parser = new TokenParser(web); // Apply alternate CSS if (!string.IsNullOrEmpty(template.ComposedLook.AlternateCSS)) { var alternateCssUrl = parser.Parse(template.ComposedLook.AlternateCSS); web.AlternateCssUrl = alternateCssUrl; web.Update(); executeQueryNeeded = true; } // Apply Site logo if (!string.IsNullOrEmpty(template.ComposedLook.SiteLogo)) { var siteLogoUrl = parser.Parse(template.ComposedLook.SiteLogo); web.SiteLogoUrl = siteLogoUrl; web.Update(); executeQueryNeeded = true; } if (executeQueryNeeded) { web.Context.ExecuteQueryRetry(); } if (String.IsNullOrEmpty(template.ComposedLook.ColorFile) && String.IsNullOrEmpty(template.ComposedLook.FontFile) && String.IsNullOrEmpty(template.ComposedLook.BackgroundFile)) { // Apply OOB theme web.SetComposedLookByUrl(template.ComposedLook.Name); } else { // Apply custom theme string colorFile = null; if (!string.IsNullOrEmpty(template.ComposedLook.ColorFile)) { colorFile = parser.Parse(template.ComposedLook.ColorFile); } string backgroundFile = null; if (!string.IsNullOrEmpty(template.ComposedLook.BackgroundFile)) { backgroundFile = parser.Parse(template.ComposedLook.BackgroundFile); } string fontFile = null; if (!string.IsNullOrEmpty(template.ComposedLook.FontFile)) { fontFile = parser.Parse(template.ComposedLook.FontFile); } string masterUrl = null; if (!string.IsNullOrEmpty(template.ComposedLook.MasterPage)) { masterUrl = parser.Parse(template.ComposedLook.MasterPage); } web.CreateComposedLookByUrl(template.ComposedLook.Name, colorFile, fontFile, backgroundFile, masterUrl); web.SetComposedLookByUrl(template.ComposedLook.Name, colorFile, fontFile, backgroundFile, masterUrl); } } }
private bool ValidateCustomActions(CustomActions srcCustomActions, CustomActions targetCustomActions, TokenParser sParser, TokenParser tParser, bool rootSite) { List <Localization> sCustomActions = LoadCustomActions(srcCustomActions, rootSite); List <Localization> tCustomActions = LoadCustomActions(targetCustomActions, rootSite); if (sCustomActions.Count > 0) { if (!Validatelocalization(sCustomActions, tCustomActions, sParser, tParser)) { return(false); } } return(true); }
public static void SetSecurity(this SecurableObject securable, TokenParser parser, ObjectSecurity security) { // If there's no role assignments we're returning if (security.RoleAssignments.Count == 0) { return; } var context = securable.Context as ClientContext; var groups = context.LoadQuery(context.Web.SiteGroups.Include(g => g.LoginName)); var webRoleDefinitions = context.LoadQuery(context.Web.RoleDefinitions); var securableRoleAssignments = context.LoadQuery(securable.RoleAssignments); context.ExecuteQueryRetry(); securable.BreakRoleInheritance(security.CopyRoleAssignments, security.ClearSubscopes); foreach (var roleAssignment in security.RoleAssignments) { if (!roleAssignment.Remove) { var roleAssignmentPrincipal = parser.ParseString(roleAssignment.Principal); Principal principal = groups.FirstOrDefault(g => g.LoginName == roleAssignmentPrincipal); if (principal == null) { principal = context.Web.EnsureUser(roleAssignmentPrincipal); } if (principal != null) { var roleDefinitionBindingCollection = new RoleDefinitionBindingCollection(context); var roleAssignmentRoleDefinition = parser.ParseString(roleAssignment.RoleDefinition); var roleDefinition = webRoleDefinitions.FirstOrDefault(r => r.Name == roleAssignmentRoleDefinition); if (roleDefinition != null) { roleDefinitionBindingCollection.Add(roleDefinition); securable.RoleAssignments.Add(principal, roleDefinitionBindingCollection); } } } else { var roleAssignmentPrincipal = parser.ParseString(roleAssignment.Principal); Principal principal = groups.FirstOrDefault(g => g.LoginName == roleAssignmentPrincipal); if (principal == null) { principal = context.Web.EnsureUser(roleAssignmentPrincipal); principal.EnsureProperty(p => p.Id); } if (principal != null) { var assignmentsForPrincipal = securableRoleAssignments.Where(t => t.PrincipalId == principal.Id); foreach (var assignmentForPrincipal in assignmentsForPrincipal) { var binding = assignmentForPrincipal.EnsureProperty(r => r.RoleDefinitionBindings).FirstOrDefault(b => b.Name == roleAssignment.RoleDefinition); if (binding != null) { assignmentForPrincipal.DeleteObject(); context.ExecuteQueryRetry(); break; } } } } } context.ExecuteQueryRetry(); }
public bool Validate(ProvisioningTemplate ptSource, ProvisioningTemplate ptTarget, TokenParser sParser, TokenParser tParser, Web web) { bool isValid = false; #region SiteFields if (ptTarget.SiteFields.Count > 0) { isValid = ValidateSiteFields(ptSource.SiteFields, ptTarget.SiteFields, sParser, tParser); if (!isValid) { return(false); } } #endregion #region ContentTypes if (ptTarget.ContentTypes.Count > 0) { isValid = ValidateContentTypes(ptSource.ContentTypes, ptTarget.ContentTypes, sParser, tParser); if (!isValid) { return(false); } } #endregion #region ListInstances isValid = ValidateListInstances(ptSource.Lists, ptTarget.Lists, sParser, tParser); if (!isValid) { return(false); } #endregion #region ListViews if (CanUseAcceptLanguageHeaderForLocalization(web)) { isValid = ValidateListView(ptSource, sParser); if (!isValid) { return(false); } } #endregion #region WebParts if (!isNoScriptSite && CanUseAcceptLanguageHeaderForLocalization(web)) { isValid = ValidateWebPartOnPages(ptSource, sParser); if (!isValid) { return(false); } } #endregion #region Navigation if (!isNoScriptSite && CanUseAcceptLanguageHeaderForLocalization(web)) { isValid = ValidateStructuralNavigation(ptSource, sParser); if (!isValid) { return(false); } } #endregion #region Custom Action if (!isNoScriptSite) { isValid = ValidateCustomActions(ptSource.CustomActions, ptTarget.CustomActions, sParser, tParser, ptTarget.SiteFields.Count > 0); if (!isValid) { return(false); } } #endregion return(isValid); }
public PublishingPageModelProvider(string homePageUrl, Web web, TokenParser parser) : base(homePageUrl, web, parser) { }
public bool ValidateListInstances(ListInstanceCollection sElements, ListInstanceCollection tElements, TokenParser sParser, TokenParser tParser) { List <Localization> sColl = LoadListInstances(sElements); List <Localization> tColl = LoadListInstances(tElements); if (sColl.Count > 0) { if (!Validatelocalization(sColl, tColl, sParser, tParser)) { return(false); } } return(true); }
private void ProvisionSearchNavigation(Web web, StructuralNavigation structuralNavigation, TokenParser parser, bool clearNavigation, PnPMonitoredScope scope) { if (structuralNavigation != null) { if (structuralNavigation.RemoveExistingNodes || clearNavigation) { if (!structuralNavigation.RemoveExistingNodes && !ClearWarningShown) { WriteMessage("You chose to override the template value RemoveExistingNodes=\"false\" by specifying ClearNavigation", ProvisioningMessageType.Warning); ClearWarningShown = true; } web.DeleteAllNavigationNodes(Enums.NavigationType.SearchNav); } if (structuralNavigation.NavigationNodes.Any()) { var searchNav = web.LoadSearchNavigation(); foreach (var node in structuralNavigation.NavigationNodes) { var navNode = searchNav.Add(new NavigationNodeCreationInformation() { Title = parser.ParseString(node.Title), IsExternal = node.IsExternal, Url = parser.ParseString(node.Url), }); if (node.Title.ContainsResourceToken()) { navNode.LocalizeNavigationNode(web, node.Title, parser, scope); } web.Context.ExecuteQueryRetry(); } } } ProvisionStructuralNavigation(web, structuralNavigation, parser, Enums.NavigationType.SearchNav, clearNavigation, scope); }
public bool ValidateContentTypes(PnP.Framework.Provisioning.Model.ContentTypeCollection sElements, PnP.Framework.Provisioning.Model.ContentTypeCollection tElements, TokenParser sParser, TokenParser tParser) { List <Localization> sColl = LoadContentTypes(sElements); List <Localization> tColl = LoadContentTypes(tElements); if (sColl.Count > 0) { if (!Validatelocalization(sColl, tColl, sParser, tParser)) { return(false); } } return(true); }
private void ProvisionGlobalStructuralNavigation(Web web, StructuralNavigation structuralNavigation, TokenParser parser, bool clearNavigation, PnPMonitoredScope scope) { ProvisionStructuralNavigation(web, structuralNavigation, parser, Enums.NavigationType.TopNavigationBar, clearNavigation, scope); }
private static TokenParser CheckChildTerms(ClientContext context, Model.Term modelTerm, Term parentTerm, TermStore termStore, TokenParser parser, PnPMonitoredScope scope) { if (modelTerm.Terms.Any()) { parentTerm.Context.Load(parentTerm, s => s.Terms.Include(t => t.Id, t => t.Name)); parentTerm.Context.ExecuteQueryRetry(); var terms = parentTerm.Terms; foreach (var childTerm in modelTerm.Terms) { if (terms.Any()) { var term = terms.FirstOrDefault(t => t.Id == childTerm.Id); if (term == null) { var normalizedTermName = TaxonomyItem.NormalizeName(context, childTerm.Name); context.ExecuteQueryRetry(); term = terms.FirstOrDefault(t => t.Name == normalizedTermName.Value); if (term == null) { var returnTuple = CreateTerm(context, childTerm, parentTerm, termStore, parser, scope); if (returnTuple != null) { childTerm.Id = returnTuple.Item1; parser = returnTuple.Item2; } } else { childTerm.Id = term.Id; } } else { childTerm.Id = term.Id; } if (term != null) { parser = CheckChildTerms(context, childTerm, term, termStore, parser, scope); } } else { var returnTuple = CreateTerm(context, childTerm, parentTerm, termStore, parser, scope); if (returnTuple != null) { childTerm.Id = returnTuple.Item1; parser = returnTuple.Item2; } } } } return(parser); }
internal static void LocalizeWebParts(this Page page, Web web, TokenParser parser, PnPMonitoredScope scope) { var url = page.Url; var webParts = page.WebParts; LocalizeParts(web, parser, url, webParts, scope); }
/// <summary> /// Attempts to reuse the model term. If the term does not yet exists it will return /// false for the first part of the the return tuple. this will notify the system /// that the term should be created instead of re-used. /// </summary> /// <param name="context"></param> /// <param name="modelTerm"></param> /// <param name="parent"></param> /// <param name="termStore"></param> /// <param name="parser"></param> /// <param name="scope"></param> /// <returns></returns> internal static TryReuseTermResult TryReuseTerm(ClientContext context, Model.Term modelTerm, TaxonomyItem parent, TermStore termStore, TokenParser parser, PnPMonitoredScope scope) { if (!modelTerm.IsReused) { return new TryReuseTermResult() { Success = false, UpdatedParser = parser } } ; if (modelTerm.Id == Guid.Empty) { return new TryReuseTermResult() { Success = false, UpdatedParser = parser } } ; // Since we're reusing terms ensure the previous terms are committed termStore.CommitAll(); context.ExecuteQueryRetry(); // Try to retrieve a matching term from the website also marked from re-use. var taxonomySession = TaxonomySession.GetTaxonomySession(context); context.Load(taxonomySession); context.ExecuteQueryRetry(); if (taxonomySession.ServerObjectIsNull()) { return(new TryReuseTermResult() { Success = false, UpdatedParser = parser }); } var freshTermStore = taxonomySession.GetDefaultKeywordsTermStore(); Term preExistingTerm = freshTermStore.GetTerm(modelTerm.Id); try { context.Load(preExistingTerm); context.ExecuteQueryRetry(); if (preExistingTerm.ServerObjectIsNull()) { preExistingTerm = null; } } catch (Exception) { preExistingTerm = null; } // If the matching term is not found, return false... we can't re-use just yet if (preExistingTerm == null) { return(new TryReuseTermResult() { Success = false, UpdatedParser = parser }); } // if the matching term is found re-use, create child terms, and return true else { // Reuse term Term createdTerm = null; if (parent is TermSet) { createdTerm = ((TermSet)parent).ReuseTerm(preExistingTerm, false); } else if (parent is Term) { createdTerm = ((Term)parent).ReuseTerm(preExistingTerm, false); } if (modelTerm.IsSourceTerm) { preExistingTerm.ReassignSourceTerm(createdTerm); } // Set labels and shared properties just in case we're on the source term if (modelTerm.IsSourceTerm) { if (modelTerm.Labels.Any()) { CreateTermLabels(modelTerm, termStore, parser, scope, createdTerm); } if (modelTerm.Properties.Any()) { SetTermCustomProperties(modelTerm, parser, createdTerm); } } if (modelTerm.LocalProperties.Any()) { SetTermLocalCustomProperties(modelTerm, parser, createdTerm); } termStore.CommitAll(); context.Load(createdTerm); context.ExecuteQueryRetry(); // Create any child terms parser = CreateChildTerms(context, modelTerm, createdTerm, termStore, parser, scope); // Return true, because our TryReuseTerm attempt succeeded! return(new TryReuseTermResult() { Success = true, UpdatedParser = parser }); } }
public void CanProvisionObjects() { var template = new ProvisioningTemplate(); var propbagEntry = new Core.Framework.Provisioning.Model.PropertyBagEntry(); propbagEntry.Key = key; propbagEntry.Value = "Unit Test"; template.PropertyBagEntries.Add(propbagEntry); using (var ctx = TestCommon.CreateClientContext()) { var parser = new TokenParser(ctx.Web, template); parser = new ObjectPropertyBagEntry().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); var value = ctx.Web.GetPropertyBagValueString(key, "default"); Assert.IsTrue(value == "Unit Test"); // Create same entry, but don't overwrite. template = new ProvisioningTemplate(); var propbagEntry2 = new PropertyBagEntry(); propbagEntry2.Key = key; propbagEntry2.Value = "Unit Test 2"; propbagEntry2.Overwrite = false; template.PropertyBagEntries.Add(propbagEntry2); parser = new ObjectPropertyBagEntry().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); value = ctx.Web.GetPropertyBagValueString(key, "default"); Assert.IsTrue(value == "Unit Test"); // Create same entry, but overwrite template = new ProvisioningTemplate(); var propbagEntry3 = new PropertyBagEntry(); propbagEntry3.Key = key; propbagEntry3.Value = "Unit Test 3"; propbagEntry3.Overwrite = true; template.PropertyBagEntries.Add(propbagEntry3); parser = new ObjectPropertyBagEntry().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); value = ctx.Web.GetPropertyBagValueString(key, "default"); Assert.IsTrue(value == "Unit Test 3"); // Create entry with system key. We don't specify to overwrite system keys, so the key should not be created. template = new ProvisioningTemplate(); var propbagEntry4 = new PropertyBagEntry(); propbagEntry4.Key = systemKey; propbagEntry4.Value = "Unit Test System Key"; propbagEntry4.Overwrite = true; template.PropertyBagEntries.Add(propbagEntry4); parser = new ObjectPropertyBagEntry().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation()); value = ctx.Web.GetPropertyBagValueString(systemKey, "default"); Assert.IsTrue(value == "default"); // Create entry with system key. We _do_ specify to overwrite system keys, so the key should be created. template = new ProvisioningTemplate(); var propbagEntry5 = new PropertyBagEntry(); propbagEntry5.Key = systemKey; propbagEntry5.Value = "Unit Test System Key 5"; propbagEntry5.Overwrite = true; template.PropertyBagEntries.Add(propbagEntry5); parser = new ObjectPropertyBagEntry().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation() { OverwriteSystemPropertyBagValues = true }); value = ctx.Web.GetPropertyBagValueString(systemKey, "default"); Assert.IsTrue(value == "Unit Test System Key 5"); // Create entry with system key. We _do not_ specify to overwrite system keys, so the key should not be created. template = new ProvisioningTemplate(); var propbagEntry6 = new PropertyBagEntry(); propbagEntry6.Key = systemKey; propbagEntry6.Value = "Unit Test System Key 6"; propbagEntry6.Overwrite = true; template.PropertyBagEntries.Add(propbagEntry6); parser = new ObjectPropertyBagEntry().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation() { OverwriteSystemPropertyBagValues = false }); value = ctx.Web.GetPropertyBagValueString(systemKey, "default"); Assert.IsFalse(value == "Unit Test System Key 6"); } }
private void RefineTemplate(ClientContext context, ProvisioningTemplate template, ProvisioningTemplateApplyingInformation ptai, ApplyRambollTemplateRequest request) { try { string type = request.ApplyComponent ?? "NotSet"; ptai.HandlersToProcess = Handlers.All; switch (type?.ToUpper()) { /*case "PRE": * template.Files.RemoveAll(x => true); * template.Navigation = null; * break; * case "POST": * template.Lists.RemoveAll(x => true); * template.SiteFields.RemoveAll(x => true); * template.ContentTypes.RemoveAll(x => true); * break; * case "INIT": * template.Files.RemoveAll(x => true); * template.Lists.RemoveAll(x => true); * template.Navigation = null; * break; * case "LISTS": * template.Files.RemoveAll(x => true); * template.Navigation = null; * break; * case "FILES": * template.Lists.RemoveAll(x => true); * template.Navigation = null; * break; * case "NAVIGATION": * template.Files.RemoveAll(x => true); * template.Lists.RemoveAll(x => true); * break;*/ case "PRE": ptai.HandlersToProcess = Handlers.All & ~Handlers.Files & ~Handlers.Navigation; break; case "POST": ptai.HandlersToProcess = Handlers.All & ~Handlers.Lists & ~Handlers.Fields & ~Handlers.ContentTypes; break; case "INIT": ptai.HandlersToProcess = Handlers.All & ~Handlers.PropertyBagEntries & ~Handlers.Features & ~Handlers.Files & ~Handlers.Lists & ~Handlers.Navigation; break; case "PROPERTYBAGENTRIES": ptai.HandlersToProcess = Handlers.All & ~Handlers.Features & ~Handlers.Files & ~Handlers.Lists & ~Handlers.Navigation; break; case "FEATURES": ptai.HandlersToProcess = Handlers.All & ~Handlers.PropertyBagEntries & ~Handlers.Files & ~Handlers.Lists & ~Handlers.Navigation; break; case "LISTS": ptai.HandlersToProcess = Handlers.All & ~Handlers.PropertyBagEntries & ~Handlers.Features & ~Handlers.Files & ~Handlers.Navigation; break; case "FILES": ptai.HandlersToProcess = Handlers.All & ~Handlers.PropertyBagEntries & ~Handlers.Features & ~Handlers.Lists & ~Handlers.Navigation; break; case "NAVIGATION": ptai.HandlersToProcess = Handlers.All & ~Handlers.PropertyBagEntries & ~Handlers.Features & ~Handlers.Files & ~Handlers.Lists; break; } var web = context.Web; if (type?.ToUpper() == "PROPERTYBAGENTRIES") { string docIdPrefix = ""; docIdPrefix = GetMetadataValue(new Guid(request.WebId), "Project number")?.ToString(); if (!string.IsNullOrEmpty(docIdPrefix)) { SetDocumentId(context, web, docIdPrefix); } } else if (type?.ToUpper() == "FILES") { var defaultPage = "default.aspx"; var siteUri = new Uri(request.SiteUrl); string tenantUrl = $"{siteUri.Scheme}://{siteUri.Host}"; if (!siteUri.IsDefaultPort) { tenantUrl = $"{tenantUrl}:{siteUri.Port}"; } context.Load(context.Web, w => w.CurrentUser); context.ExecuteQueryRetry(); var loginName = context.Web?.CurrentUser?.LoginName; //?.Split('|').LastOrDefault(); foreach (var file in template.Files) { if (file.Src.Equals(defaultPage, StringComparison.InvariantCultureIgnoreCase)) { string projectName = ""; projectName = GetMetadataValue(new Guid(request.WebId), "Project name")?.ToString(); file.Properties["Title"] = projectName; } if (file.Properties.ContainsKey("_dlc_DocIdUrl")) { var docIdUrl = file.Properties["_dlc_DocIdUrl"]; if (!string.IsNullOrEmpty(docIdUrl)) { file.Properties["_dlc_DocIdUrl"] = docIdUrl.Replace("{tenant}", tenantUrl); } } if (!string.IsNullOrEmpty(loginName)) { if (file.Properties.ContainsKey("PublishingContact")) { file.Properties["PublishingContact"] = loginName; } else { file.Properties.Add("PublishingContact", loginName); } } } } var isSubSite = web.IsSubSite(); if (isSubSite) { var tokenParser = new TokenParser(web, template); if (template.SiteFields.Any()) { var columnProvisionManager = new SiteColumnProvisionManager(); columnProvisionManager.Provision(web, template, tokenParser, ptai); } if (template.ContentTypes.Any()) { var contentTypeProvisionManager = new ContentTypeProvisionManager(); contentTypeProvisionManager.Provision(web, template, tokenParser, ptai); } template.Files.RemoveAll( f => f.Src.EndsWith(".master", StringComparison.InvariantCultureIgnoreCase)); } var pageLib = context.Web.GetPagesLibrary(); if (template.Files.Any()) { foreach (var file in template.Files) { if (file.Src.EndsWith(".aspx")) { file.Src = $"{pageLib.Title}\\{file.Src}"; } } } } catch (Exception ex) { throw ex; } }