本文整理汇总了C#中OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers.TokenParser.ParseString方法的典型用法代码示例。如果您正苦于以下问题:C# TokenParser.ParseString方法的具体用法?C# TokenParser.ParseString怎么用?C# TokenParser.ParseString使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers.TokenParser
的用法示例。
在下文中一共展示了TokenParser.ParseString方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ProvisionObjects
public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
{
using (var scope = new PnPMonitoredScope(this.Name))
{
if (template.ComposedLook != null &&
!template.ComposedLook.Equals(ComposedLook.Empty))
{
bool executeQueryNeeded = false;
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.ParseString(template.ComposedLook.ColorFile);
}
string backgroundFile = null;
if (!string.IsNullOrEmpty(template.ComposedLook.BackgroundFile))
{
backgroundFile = parser.ParseString(template.ComposedLook.BackgroundFile);
}
string fontFile = null;
if (!string.IsNullOrEmpty(template.ComposedLook.FontFile))
{
fontFile = parser.ParseString(template.ComposedLook.FontFile);
}
string masterUrl = null;
if (template.WebSettings != null && !string.IsNullOrEmpty(template.WebSettings.MasterPageUrl))
{
masterUrl = parser.ParseString(template.WebSettings.MasterPageUrl);
}
web.CreateComposedLookByUrl(template.ComposedLook.Name, colorFile, fontFile, backgroundFile, masterUrl);
web.SetComposedLookByUrl(template.ComposedLook.Name, colorFile, fontFile, backgroundFile, masterUrl);
var composedLookJson = JsonConvert.SerializeObject(template.ComposedLook);
web.SetPropertyBagValue("_PnP_ProvisioningTemplateComposedLookInfo", composedLookJson);
}
// Persist composed look info in property bag
}
}
return parser;
}
示例2: AddExtendedTokens
public TokenParser AddExtendedTokens(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
{
using (var scope = new PnPMonitoredScope(this.Name))
{
var context = web.Context as ClientContext;
foreach (var provider in template.Providers)
{
if (provider.Enabled)
{
try
{
if (!string.IsNullOrEmpty(provider.Configuration))
{
provider.Configuration = parser.ParseString(provider.Configuration);
}
scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ExtensibilityProviders_Calling_tokenprovider_extensibility_callout__0_, provider.Assembly);
var _providedTokens = _extManager.ExecuteTokenProviderCallOut(context, provider, template);
if (_providedTokens != null)
{
foreach (var token in _providedTokens)
{
parser.AddToken(token);
}
}
}
catch (Exception ex)
{
scope.LogError(CoreResources.Provisioning_ObjectHandlers_ExtensibilityProviders_tokenprovider_callout_failed___0_____1_, ex.Message, ex.StackTrace);
throw;
}
}
}
return parser;
}
}
示例3: ProvisionObjects
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;
foreach (var handler in template.ExtensibilityHandlers
.Union(template.Providers)
.Union(applyingInformation.ExtensibilityHandlers))
{
if (handler.Enabled)
{
try
{
if (!string.IsNullOrEmpty(handler.Configuration))
{
//replace tokens in configuration data
handler.Configuration = parser.ParseString(handler.Configuration);
}
scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ExtensibilityProviders_Calling_extensibility_callout__0_, handler.Assembly);
_extManager.ExecuteExtensibilityProvisionCallOut(context, handler, template, applyingInformation, parser, scope);
}
catch (Exception ex)
{
scope.LogError(CoreResources.Provisioning_ObjectHandlers_ExtensibilityProviders_callout_failed___0_____1_, ex.Message, ex.StackTrace);
throw;
}
}
}
}
return parser;
}
示例4: ParseTests
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");
}
}
示例5: ProvisionObjects
public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
{
using (var scope = new PnPMonitoredScope(this.Name))
{
// 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())
{
scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Fields_Context_web_is_subweb__skipping_site_columns);
return parser;
}
var existingFields = web.Fields;
web.Context.Load(existingFields, fs => fs.Include(f => f.Id));
web.Context.ExecuteQueryRetry();
var existingFieldIds = existingFields.AsEnumerable<SPField>().Select(l => l.Id).ToList();
var fields = template.SiteFields;
foreach (var field in fields)
{
XElement templateFieldElement = XElement.Parse(parser.ParseString(field.SchemaXml, "~sitecollection", "~site"));
var fieldId = templateFieldElement.Attribute("ID").Value;
if (!existingFieldIds.Contains(Guid.Parse(fieldId)))
{
try
{
scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Fields_Adding_field__0__to_site, fieldId);
CreateField(web, templateFieldElement, scope, parser, field.SchemaXml);
}
catch (Exception ex)
{
scope.LogError(CoreResources.Provisioning_ObjectHandlers_Fields_Adding_field__0__failed___1_____2_, fieldId, ex.Message, ex.StackTrace);
throw;
}
}
else
try
{
scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Fields_Updating_field__0__in_site, fieldId);
UpdateField(web, fieldId, templateFieldElement, scope, parser, field.SchemaXml);
}
catch (Exception ex)
{
scope.LogError(CoreResources.Provisioning_ObjectHandlers_Fields_Updating_field__0__failed___1_____2_, fieldId, ex.Message, ex.StackTrace);
throw;
}
}
}
return parser;
}
示例6: CreateView
private void CreateView(Web web, View view, Microsoft.SharePoint.Client.ViewCollection existingViews, List createdList, PnPMonitoredScope monitoredScope, TokenParser parser)
{
try
{
var viewElement = XElement.Parse(view.SchemaXml);
var displayNameElement = viewElement.Attribute("DisplayName");
if (displayNameElement == null)
{
throw new ApplicationException("Invalid View element, missing a valid value for the attribute DisplayName.");
}
var viewTitle = parser.ParseString(displayNameElement.Value);
monitoredScope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ListInstances_Creating_view__0_, displayNameElement.Value);
var existingView = existingViews.FirstOrDefault(v => v.Title == viewTitle);
if (existingView != null)
{
existingView.DeleteObject();
web.Context.ExecuteQueryRetry();
}
// Type
var viewTypeString = viewElement.Attribute("Type") != null ? viewElement.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 = viewElement.Descendants("ViewFields").FirstOrDefault();
if (viewFieldsElement != null)
{
viewFields = (from field in viewElement.Descendants("ViewFields").Descendants("FieldRef") select field.Attribute("Name").Value).ToArray();
}
// Default view
var viewDefault = viewElement.Attribute("DefaultView") != null && Boolean.Parse(viewElement.Attribute("DefaultView").Value);
// Row limit
var viewPaged = true;
uint viewRowLimit = 30;
var rowLimitElement = viewElement.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 viewElement.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,
};
// Allow to specify a custom view url. View url is taken from title, so we first set title to the view url value we need,
// create the view and then set title back to the original value
var urlAttribute = viewElement.Attribute("Url");
var urlHasValue = urlAttribute != null && !string.IsNullOrEmpty(urlAttribute.Value);
if (urlHasValue)
{
//set Title to be equal to url (in order to generate desired url)
viewCI.Title = Path.GetFileNameWithoutExtension(urlAttribute.Value);
}
var createdView = createdList.Views.Add(viewCI);
web.Context.Load(createdView, v => v.Scope, v => v.JSLink, v => v.Title);
web.Context.ExecuteQueryRetry();
if (urlHasValue)
{
//restore original title
createdView.Title = viewTitle;
createdView.Update();
}
// ContentTypeID
var contentTypeID = viewElement.Attribute("ContentTypeID") != null ? viewElement.Attribute("ContentTypeID").Value : null;
if (!string.IsNullOrEmpty(contentTypeID) && (contentTypeID != BuiltInContentTypeId.System))
{
ContentTypeId childContentTypeId = null;
if (contentTypeID == BuiltInContentTypeId.RootOfList)
{
var childContentType = web.GetContentTypeById(contentTypeID);
childContentTypeId = childContentType != null ? childContentType.Id : null;
//.........这里部分代码省略.........
示例7: ProvisionObjects
public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
{
using (var scope = new PnPMonitoredScope(CoreResources.Provisioning_ObjectHandlers_Pages))
{
var context = web.Context as ClientContext;
if (!web.IsPropertyAvailable("ServerRelativeUrl"))
{
context.Load(web, w => w.ServerRelativeUrl);
context.ExecuteQueryRetry();
}
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);
file.DeleteObject();
web.Context.ExecuteQueryRetry();
web.AddWikiPageByUrl(url);
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)
{
if (!web.IsPropertyAvailable("RootFolder"))
{
web.Context.Load(web.RootFolder);
web.Context.ExecuteQueryRetry();
}
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);
}
}
}
}
}
//.........这里部分代码省略.........
示例8: UpdateField
private void UpdateField(ClientObject web, ListInfo listInfo, Guid fieldId, XElement templateFieldElement, Field existingField, PnPMonitoredScope scope, TokenParser parser)
{
web.Context.Load(existingField, f => f.SchemaXml);
web.Context.ExecuteQueryRetry();
var existingFieldElement = XElement.Parse(existingField.SchemaXml);
var equalityComparer = new XNodeEqualityComparer();
// Is field different in template?
if (equalityComparer.GetHashCode(existingFieldElement) != equalityComparer.GetHashCode(templateFieldElement))
{
// Is existing field of the same type?
if (existingFieldElement.Attribute("Type").Value == templateFieldElement.Attribute("Type").Value)
{
templateFieldElement = PrepareField(templateFieldElement);
foreach (var attribute in templateFieldElement.Attributes())
{
if (existingFieldElement.Attribute(attribute.Name) != null)
{
existingFieldElement.Attribute(attribute.Name).Value = attribute.Value;
}
else
{
existingFieldElement.Add(attribute);
}
}
foreach (var element in templateFieldElement.Elements())
{
if (existingFieldElement.Element(element.Name) != null)
{
existingFieldElement.Element(element.Name).Remove();
}
existingFieldElement.Add(element);
}
if (existingFieldElement.Attribute("Version") != null)
{
existingFieldElement.Attributes("Version").Remove();
}
existingField.SchemaXml = parser.ParseString(existingFieldElement.ToString(), "~sitecollection", "~site");
existingField.UpdateAndPushChanges(true);
web.Context.ExecuteQueryRetry();
}
else
{
var fieldName = existingFieldElement.Attribute("Name") != null ? existingFieldElement.Attribute("Name").Value : existingFieldElement.Attribute("StaticName").Value;
scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_ListInstances_Field__0____1___exists_in_list__2____3___but_is_of_different_type__Skipping_field_, fieldName, fieldId, listInfo.TemplateList.Title, listInfo.SiteList.Id);
WriteWarning(string.Format(CoreResources.Provisioning_ObjectHandlers_ListInstances_Field__0____1___exists_in_list__2____3___but_is_of_different_type__Skipping_field_, fieldName, fieldId, listInfo.TemplateList.Title, listInfo.SiteList.Id), ProvisioningMessageType.Warning);
}
}
}
示例9: ProvisionObjects
public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
{
using (var scope = new PnPMonitoredScope(this.Name))
{
// Get a reference to infrastructural services
var servicesManager = new WorkflowServicesManager(web.Context, web);
var deploymentService = servicesManager.GetWorkflowDeploymentService();
var subscriptionService = servicesManager.GetWorkflowSubscriptionService();
// Provision Workflow Definitions
foreach (var definition in template.Workflows.WorkflowDefinitions)
{
// Load the Workflow Definition XAML
Stream xamlStream = template.Connector.GetFileStream(definition.XamlPath);
System.Xml.Linq.XElement xaml = System.Xml.Linq.XElement.Load(xamlStream);
// Create the WorkflowDefinition instance
Microsoft.SharePoint.Client.WorkflowServices.WorkflowDefinition workflowDefinition =
new Microsoft.SharePoint.Client.WorkflowServices.WorkflowDefinition(web.Context)
{
AssociationUrl = definition.AssociationUrl,
Description = definition.Description,
DisplayName = definition.DisplayName,
FormField = definition.FormField,
DraftVersion = definition.DraftVersion,
Id = definition.Id,
InitiationUrl = definition.InitiationUrl,
RequiresAssociationForm = definition.RequiresAssociationForm,
RequiresInitiationForm = definition.RequiresInitiationForm,
RestrictToScope = parser.ParseString(definition.RestrictToScope),
RestrictToType = definition.RestrictToType != "Universal" ? definition.RestrictToType : null,
Xaml = xaml.ToString(),
};
//foreach (var p in definition.Properties)
//{
// workflowDefinition.SetProperty(p.Key, parser.ParseString(p.Value));
//}
// Save the Workflow Definition
var definitionId = deploymentService.SaveDefinition(workflowDefinition);
web.Context.Load(workflowDefinition);
web.Context.ExecuteQueryRetry();
// Let's publish the Workflow Definition, if needed
if (definition.Published)
{
deploymentService.PublishDefinition(definitionId.Value);
}
}
foreach (var subscription in template.Workflows.WorkflowSubscriptions)
{
#if CLIENTSDKV15
// Create the WorkflowDefinition instance
Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription workflowSubscription =
new Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription(web.Context)
{
DefinitionId = subscription.DefinitionId,
Enabled = subscription.Enabled,
EventSourceId = (!String.IsNullOrEmpty(subscription.EventSourceId)) ? Guid.Parse(parser.ParseString(subscription.EventSourceId)) : web.Id,
EventTypes = subscription.EventTypes,
ManualStartBypassesActivationLimit = subscription.ManualStartBypassesActivationLimit,
Name = subscription.Name,
StatusFieldName = subscription.StatusFieldName,
};
#else
// Create the WorkflowDefinition instance
Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription workflowSubscription =
new Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription(web.Context)
{
DefinitionId = subscription.DefinitionId,
Enabled = subscription.Enabled,
EventSourceId = (!String.IsNullOrEmpty(subscription.EventSourceId)) ? Guid.Parse(parser.ParseString(subscription.EventSourceId)) : web.Id,
EventTypes = subscription.EventTypes,
ManualStartBypassesActivationLimit = subscription.ManualStartBypassesActivationLimit,
Name = subscription.Name,
ParentContentTypeId = subscription.ParentContentTypeId,
StatusFieldName = subscription.StatusFieldName,
};
#endif
foreach (var p in subscription.PropertyDefinitions
.Where(d => d.Key == "TaskListId" || d.Key == "HistoryListId"))
{
workflowSubscription.SetProperty(p.Key, parser.ParseString(p.Value));
}
if (!String.IsNullOrEmpty(subscription.ListId))
{
// It is a List Workflow
Guid targetListId = Guid.Parse(parser.ParseString(subscription.ListId));
subscriptionService.PublishSubscriptionForList(workflowSubscription, targetListId);
}
else
{
// It is a Site Workflow
subscriptionService.PublishSubscription(workflowSubscription);
}
web.Context.ExecuteQueryRetry();
}
//.........这里部分代码省略.........
示例10: CreateFolderInList
private void CreateFolderInList(Microsoft.SharePoint.Client.Folder parentFolder, Model.Folder folder, TokenParser parser, PnPMonitoredScope scope)
{
// Determine the folder name, parsing any token
String targetFolderName = parser.ParseString(folder.Name);
// Check if the folder already exists
if (parentFolder.FolderExists(targetFolderName))
{
// Log a warning if the folder already exists
String warningFolderAlreadyExists = String.Format(CoreResources.Provisioning_ObjectHandlers_ListInstances_FolderAlreadyExists, targetFolderName, parentFolder.ServerRelativeUrl);
scope.LogWarning(warningFolderAlreadyExists);
WriteWarning(warningFolderAlreadyExists, ProvisioningMessageType.Warning);
}
// Create it or get a reference to it
var currentFolder = parentFolder.EnsureFolder(targetFolderName);
if (currentFolder != null)
{
// Handle any child-folder
if (folder.Folders != null && folder.Folders.Count > 0)
{
foreach (var childFolder in folder.Folders)
{
CreateFolderInList(currentFolder, childFolder, parser, scope);
}
}
// Handle current folder security
if (folder.Security != null && folder.Security.RoleAssignments.Count != 0)
{
var currentFolderItem = currentFolder.ListItemAllFields;
parentFolder.Context.Load(currentFolderItem);
parentFolder.Context.ExecuteQueryRetry();
currentFolderItem.SetSecurity(parser, folder.Security);
}
}
}
示例11: CreateField
private static Field CreateField(XElement fieldElement, ListInfo listInfo, TokenParser parser, string originalFieldXml, ClientRuntimeContext context, PnPMonitoredScope scope)
{
Field field = null;
fieldElement = PrepareField(fieldElement);
var fieldXml = parser.ParseString(fieldElement.ToString(), "~sitecollection", "~site");
if (IsFieldXmlValid(parser.ParseString(originalFieldXml), parser, context))
{
field = listInfo.SiteList.Fields.AddFieldAsXml(fieldXml, false, AddFieldOptions.AddFieldInternalNameHint);
listInfo.SiteList.Context.Load(field);
listInfo.SiteList.Context.ExecuteQueryRetry();
bool isDirty = false;
#if !SP2013
if (originalFieldXml.ContainsResourceToken())
{
var originalFieldElement = XElement.Parse(originalFieldXml);
var nameAttributeValue = originalFieldElement.Attribute("DisplayName") != null ? originalFieldElement.Attribute("DisplayName").Value : "";
if (nameAttributeValue.ContainsResourceToken())
{
if (field.TitleResource.SetUserResourceValue(nameAttributeValue, parser))
{
isDirty = true;
}
}
var descriptionAttributeValue = originalFieldElement.Attribute("Description") != null ? originalFieldElement.Attribute("Description").Value : "";
if (descriptionAttributeValue.ContainsResourceToken())
{
if (field.DescriptionResource.SetUserResourceValue(descriptionAttributeValue, parser))
{
isDirty = true;
}
}
}
#endif
if (isDirty)
{
field.Update();
listInfo.SiteList.Context.ExecuteQueryRetry();
}
}
else
{
// The field Xml was found invalid
var tokenString = parser.GetLeftOverTokens(originalFieldXml).Aggregate(String.Empty, (acc, i) => acc + " " + i);
scope.LogError("The field was found invalid: {0}", tokenString);
throw new Exception(string.Format("The field was found invalid: {0}", tokenString));
}
return field;
}
示例12: UpdateList
private Tuple<List, TokenParser> UpdateList(Web web, List existingList, ListInstance templateList, TokenParser parser, PnPMonitoredScope scope, bool isNoScriptSite = false)
{
web.Context.Load(existingList,
l => l.Title,
l => l.Description,
l => l.OnQuickLaunch,
l => l.Hidden,
l => l.ContentTypesEnabled,
l => l.EnableAttachments,
l => l.EnableVersioning,
l => l.EnableFolderCreation,
l => l.EnableModeration,
l => l.EnableMinorVersions,
l => l.ForceCheckout,
l => l.DraftVersionVisibility,
l => l.Views,
l => l.DocumentTemplateUrl,
l => l.RootFolder,
l => l.BaseType,
l => l.BaseTemplate
#if !SP2013
, l => l.MajorWithMinorVersionsLimit
, l => l.MajorVersionLimit
#endif
);
web.Context.ExecuteQueryRetry();
if (existingList.BaseTemplate == templateList.TemplateType)
{
var isDirty = false;
if (parser.ParseString(templateList.Title) != existingList.Title)
{
var oldTitle = existingList.Title;
existingList.Title = parser.ParseString(templateList.Title);
if (!oldTitle.Equals(existingList.Title, StringComparison.OrdinalIgnoreCase))
{
parser.AddToken(new ListIdToken(web, existingList.Title, existingList.Id));
parser.AddToken(new ListUrlToken(web, existingList.Title, existingList.RootFolder.ServerRelativeUrl.Substring(web.ServerRelativeUrl.Length + 1)));
}
isDirty = true;
}
if (!string.IsNullOrEmpty(templateList.DocumentTemplate))
{
if (existingList.DocumentTemplateUrl != parser.ParseString(templateList.DocumentTemplate))
{
existingList.DocumentTemplateUrl = parser.ParseString(templateList.DocumentTemplate);
isDirty = true;
}
}
if (!string.IsNullOrEmpty(templateList.Description) && templateList.Description != existingList.Description)
{
existingList.Description = templateList.Description;
isDirty = true;
}
if (templateList.Hidden != existingList.Hidden)
{
existingList.Hidden = templateList.Hidden;
isDirty = true;
}
if (templateList.OnQuickLaunch != existingList.OnQuickLaunch)
{
existingList.OnQuickLaunch = templateList.OnQuickLaunch;
isDirty = true;
}
if (existingList.BaseTemplate != (int)ListTemplateType.Survey &&
templateList.ContentTypesEnabled != existingList.ContentTypesEnabled)
{
existingList.ContentTypesEnabled = templateList.ContentTypesEnabled;
isDirty = true;
}
if (existingList.BaseTemplate != (int)ListTemplateType.Survey &&
existingList.BaseTemplate != (int)ListTemplateType.DocumentLibrary &&
existingList.BaseTemplate != (int)ListTemplateType.PictureLibrary)
{
// https://msdn.microsoft.com/EN-US/library/microsoft.sharepoint.splist.enableattachments.aspx
// The EnableAttachments property does not apply to any list that has a base type of Survey, DocumentLibrary or PictureLibrary.
// If you set this property to true for either type of list, it throws an SPException.
if (templateList.EnableAttachments != existingList.EnableAttachments)
{
existingList.EnableAttachments = templateList.EnableAttachments;
isDirty = true;
}
}
if (existingList.BaseTemplate != (int)ListTemplateType.DiscussionBoard)
{
if (templateList.EnableFolderCreation != existingList.EnableFolderCreation)
{
existingList.EnableFolderCreation = templateList.EnableFolderCreation;
isDirty = true;
}
}
#if !SP2013
if (templateList.Title.ContainsResourceToken())
{
if (existingList.TitleResource.SetUserResourceValue(templateList.Title, parser))
{
isDirty = true;
}
}
#endif
//.........这里部分代码省略.........
示例13: ProvisionObjects
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.Url);
foreach (PublishingPage page in template.Publishing.PublishingPages)
{
string parsedFileName = parser.ParseString(page.FileName);
string parsedFullFileName = parser.ParseString(page.FullFileName);
Microsoft.SharePoint.Client.Publishing.PublishingPage existingPage =
web.GetPublishingPage(parsedFileName + ".aspx");
if (!web.IsPropertyAvailable("RootFolder"))
{
web.Context.Load(web.RootFolder);
web.Context.ExecuteQueryRetry();
}
if (existingPage != null && existingPage.ServerObjectIsNull.Value == false)
{
if (!page.Overwrite)
{
scope.LogDebug(
CoreResources.Provisioning_ObjectHandlers_PublishingPages_Skipping_As_Overwrite_false,
parsedFileName);
continue;
}
if (page.WelcomePage && web.RootFolder.WelcomePage.Contains(parsedFullFileName))
{
//set the welcome page to a Temp page to allow page deletion
web.RootFolder.WelcomePage = "home.aspx";
web.RootFolder.Update();
web.Update();
context.ExecuteQueryRetry();
}
existingPage.ListItem.DeleteObject();
context.ExecuteQuery();
}
web.AddPublishingPage(
parsedFileName,
page.Layout,
parser.ParseString(page.Title)
);
Microsoft.SharePoint.Client.Publishing.PublishingPage publishingPage =
web.GetPublishingPage(parsedFullFileName);
Microsoft.SharePoint.Client.File pageFile = publishingPage.ListItem.File;
pageFile.CheckOut();
if (page.Properties != null && page.Properties.Count > 0)
{
context.Load(pageFile, p => p.Name, p => p.CheckOutType);
context.ExecuteQueryRetry();
var parsedProperties = page.Properties.ToDictionary(p => p.Key, p => parser.ParseString(p.Value));
pageFile.SetFileProperties(parsedProperties, false);
}
if (page.WebParts != null && page.WebParts.Count > 0)
{
Microsoft.SharePoint.Client.WebParts.LimitedWebPartManager mgr =
pageFile.GetLimitedWebPartManager(
Microsoft.SharePoint.Client.WebParts.PersonalizationScope.Shared);
context.Load(mgr);
context.ExecuteQueryRetry();
AddWebPartsToPublishingPage(page, context, mgr, parser);
}
List pagesLibrary = publishingPage.ListItem.ParentList;
context.Load(pagesLibrary);
context.ExecuteQueryRetry();
ListItem pageItem = publishingPage.ListItem;
web.Context.Load(pageItem, p => p.File.CheckOutType);
web.Context.ExecuteQueryRetry();
if (pageItem.File.CheckOutType != CheckOutType.None)
{
pageItem.File.CheckIn(String.Empty, CheckinType.MajorCheckIn);
}
if (page.Publish && pagesLibrary.EnableMinorVersions)
{
pageItem.File.Publish(String.Empty);
if (pagesLibrary.EnableModeration)
{
pageItem.File.Approve(String.Empty);
}
}
if (page.WelcomePage)
{
SetWelcomePage(web, pageFile);
}
//.........这里部分代码省略.........
示例14: AddWebPartsToPublishingPage
private static void AddWebPartsToPublishingPage(PublishingPage page, ClientContext ctx, Microsoft.SharePoint.Client.WebParts.LimitedWebPartManager mgr, TokenParser parser)
{
foreach (var wp in page.WebParts)
{
string wpContentsTokenResolved = parser.ParseString(wp.Contents).Replace("<property name=\"JSLink\" type=\"string\">" + ctx.Site.ServerRelativeUrl,"<property name=\"JSLink\" type=\"string\">~sitecollection");
Microsoft.SharePoint.Client.WebParts.WebPart webPart = mgr.ImportWebPart(wpContentsTokenResolved).WebPart;
Microsoft.SharePoint.Client.WebParts.WebPartDefinition definition = mgr.AddWebPart(
webPart,
wp.Zone,
(int)wp.Order
);
var webPartProperties = definition.WebPart.Properties;
ctx.Load(definition.WebPart);
ctx.Load(webPartProperties);
ctx.ExecuteQuery();
if (wp.IsListViewWebPart)
{
AddListViewWebpart(ctx, wp, definition, webPartProperties, parser);
}
}
}
示例15: AddListViewWebpart
private static void AddListViewWebpart(
ClientContext ctx,
PublishingPageWebPart wp,
Microsoft.SharePoint.Client.WebParts.WebPartDefinition definition,
PropertyValues webPartProperties,
TokenParser parser)
{
string defaultViewDisplayName = parser.ParseString(wp.DefaultViewDisplayName);
if (!String.IsNullOrEmpty(defaultViewDisplayName))
{
string listUrl = webPartProperties.FieldValues["ListUrl"].ToString();
ctx.Load(definition, d => d.Id); // Id of the hidden view which gets automatically created
ctx.ExecuteQuery();
Guid viewId = definition.Id;
List list = ctx.Web.GetListByUrl(listUrl);
Microsoft.SharePoint.Client.View viewCreatedFromWebpart = list.Views.GetById(viewId);
ctx.Load(viewCreatedFromWebpart);
Microsoft.SharePoint.Client.View viewCreatedFromList = list.Views.GetByTitle(defaultViewDisplayName);
ctx.Load(
viewCreatedFromList,
v => v.ViewFields,
v => v.ListViewXml,
v => v.ViewQuery,
v => v.ViewData,
v => v.ViewJoins,
v => v.ViewProjectedFields,
v => v.Paged,
v => v.RowLimit);
ctx.ExecuteQuery();
//need to copy the same View definition to the new View added by the Webpart manager
viewCreatedFromWebpart.ViewQuery = viewCreatedFromList.ViewQuery;
viewCreatedFromWebpart.ViewData = viewCreatedFromList.ViewData;
viewCreatedFromWebpart.ViewJoins = viewCreatedFromList.ViewJoins;
viewCreatedFromWebpart.ViewProjectedFields = viewCreatedFromList.ViewProjectedFields;
viewCreatedFromWebpart.Paged = viewCreatedFromList.Paged;
viewCreatedFromWebpart.RowLimit = viewCreatedFromList.RowLimit;
viewCreatedFromWebpart.ViewFields.RemoveAll();
foreach (var field in viewCreatedFromList.ViewFields)
{
viewCreatedFromWebpart.ViewFields.Add(field);
}
if (webPartProperties.FieldValues.ContainsKey("JSLink") && webPartProperties.FieldValues["JSLink"] != null)
{
viewCreatedFromWebpart.JSLink = webPartProperties.FieldValues["JSLink"].ToString();
}
viewCreatedFromWebpart.Update();
ctx.ExecuteQuery();
}
}