本文整理汇总了C#中Web.EnsureProperties方法的典型用法代码示例。如果您正苦于以下问题:C# Web.EnsureProperties方法的具体用法?C# Web.EnsureProperties怎么用?C# Web.EnsureProperties使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Web
的用法示例。
在下文中一共展示了Web.EnsureProperties方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Rebase
public void Rebase(Web web)
{
web.EnsureProperties(w => w.ServerRelativeUrl, w => w.Language);
_web = web;
foreach (var token in _tokens)
{
token.ClearCache();
token.Web = web;
}
}
示例2: 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.RootFolder.WelcomePage);
foreach (var page in template.Pages)
{
var url = parser.ParseString(page.Url);
if (!url.ToLower().StartsWith(web.ServerRelativeUrl.ToLower()))
{
url = UrlUtility.Combine(web.ServerRelativeUrl, url);
}
var exists = true;
File file = null;
try
{
file = web.GetFileByServerRelativeUrl(url);
web.Context.Load(file);
web.Context.ExecuteQueryRetry();
}
catch (ServerException ex)
{
if (ex.ServerErrorTypeName == "System.IO.FileNotFoundException")
{
exists = false;
}
}
if (exists)
{
if (page.Overwrite)
{
try
{
scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Pages_Overwriting_existing_page__0_, url);
string welcomePageUrl = string.IsNullOrEmpty(web.RootFolder.WelcomePage) ? "" : UrlUtility.Combine(web.ServerRelativeUrl, web.RootFolder.WelcomePage);
if (!string.IsNullOrEmpty(welcomePageUrl) && url.Equals(welcomePageUrl, StringComparison.InvariantCultureIgnoreCase))
web.SetHomePage(string.Empty);
file.DeleteObject();
web.Context.ExecuteQueryRetry();
this.AddPage(web, url, page, parser);
}
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);
this.AddPage(web, url, page, parser);
}
catch (Exception ex)
{
scope.LogError(CoreResources.Provisioning_ObjectHandlers_Pages_Creating_new_page__0__failed___1_____2_, url, ex.Message, ex.StackTrace);
}
}
if (page.WelcomePage)
{
var rootFolderRelativeUrl = url.Substring(web.ServerRelativeUrl.Length + 1);
web.SetHomePage(rootFolderRelativeUrl);
}
if (page.WebParts != null & page.WebParts.Any())
{
this.AddWebParts(web, page, parser);
}
if (page.Security != null)
{
file = web.GetFileByServerRelativeUrl(url);
web.Context.Load(file.ListItemAllFields);
web.Context.ExecuteQueryRetry();
file.ListItemAllFields.SetSecurity(parser, page.Security);
}
}
}
return parser;
}
示例3: TokenParser
public TokenParser(Web web, ProvisioningTemplate template)
{
web.EnsureProperties(w => w.ServerRelativeUrl, w => w.Language);
_web = web;
_tokens = new List<TokenDefinition>();
_tokens.Add(new SiteCollectionToken(web));
_tokens.Add(new SiteCollectionIdToken(web));
_tokens.Add(new SiteToken(web));
_tokens.Add(new MasterPageCatalogToken(web));
_tokens.Add(new SiteCollectionTermStoreIdToken(web));
_tokens.Add(new KeywordsTermStoreIdToken(web));
_tokens.Add(new ThemeCatalogToken(web));
_tokens.Add(new SiteNameToken(web));
_tokens.Add(new SiteIdToken(web));
_tokens.Add(new AssociatedGroupToken(web, AssociatedGroupToken.AssociatedGroupType.owners));
_tokens.Add(new AssociatedGroupToken(web, AssociatedGroupToken.AssociatedGroupType.members));
_tokens.Add(new AssociatedGroupToken(web, AssociatedGroupToken.AssociatedGroupType.visitors));
_tokens.Add(new GuidToken(web));
_tokens.Add(new DateNowToken(web));
_tokens.Add(new CurrentUserIdToken(web));
_tokens.Add(new CurrentUserLoginNameToken(web));
_tokens.Add(new CurrentUserFullNameToken(web));
_tokens.Add(new AuthenticationRealmToken(web));
// Add lists
web.Context.Load(web.Lists, ls => ls.Include(l => l.Id, l => l.Title, l => l.RootFolder.ServerRelativeUrl));
web.Context.ExecuteQueryRetry();
foreach (var list in web.Lists)
{
_tokens.Add(new ListIdToken(web, list.Title, list.Id));
_tokens.Add(new ListUrlToken(web, list.Title, list.RootFolder.ServerRelativeUrl.Substring(web.ServerRelativeUrl.Length + 1)));
}
if (web.IsSubSite())
{
// Add lists from rootweb
var rootWeb = (web.Context as ClientContext).Site.RootWeb;
rootWeb.EnsureProperty(w => w.ServerRelativeUrl);
rootWeb.Context.Load(rootWeb.Lists, ls => ls.Include(l => l.Id, l => l.Title, l => l.RootFolder.ServerRelativeUrl));
rootWeb.Context.ExecuteQueryRetry();
foreach (var rootList in rootWeb.Lists)
{
// token already there? Skip the list
if (web.Lists.FirstOrDefault(l => l.Title == rootList.Title) == null)
{
_tokens.Add(new ListIdToken(web, rootList.Title, rootList.Id));
_tokens.Add(new ListUrlToken(web, rootList.Title, rootList.RootFolder.ServerRelativeUrl.Substring(rootWeb.ServerRelativeUrl.Length + 1)));
}
}
}
// Add ContentTypes
web.Context.Load(web.AvailableContentTypes, cs => cs.Include(ct => ct.StringId, ct => ct.Name));
web.Context.ExecuteQueryRetry();
foreach (var ct in web.AvailableContentTypes)
{
_tokens.Add(new ContentTypeIdToken(web, ct.Name, ct.StringId));
}
// Add parameters
foreach (var parameter in template.Parameters)
{
_tokens.Add(new ParameterToken(web, parameter.Key, parameter.Value));
}
// Add TermSetIds
TaxonomySession session = TaxonomySession.GetTaxonomySession(web.Context);
var termStores = session.EnsureProperty(s => s.TermStores);
foreach (var ts in termStores)
{
_tokens.Add(new TermStoreIdToken(web, ts.Name, ts.Id));
}
var termStore = session.GetDefaultSiteCollectionTermStore();
web.Context.Load(termStore);
web.Context.ExecuteQueryRetry();
if (!termStore.ServerObjectIsNull.Value)
{
web.Context.Load(termStore.Groups,
g => g.Include(
tg => tg.Name,
tg => tg.TermSets.Include(
ts => ts.Name,
ts => ts.Id)
));
web.Context.ExecuteQueryRetry();
foreach (var termGroup in termStore.Groups)
{
foreach (var termSet in termGroup.TermSets)
{
_tokens.Add(new TermSetIdToken(web, termGroup.Name, termSet.Name, termSet.Id));
}
}
}
_tokens.Add(new SiteCollectionTermGroupIdToken(web));
_tokens.Add(new SiteCollectionTermGroupNameToken(web));
//.........这里部分代码省略.........
示例4: ProvisionObjects
public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
{
using (var scope = new PnPMonitoredScope(this.Name))
{
if (template.Lists.Any())
{
var rootWeb = (web.Context as ClientContext).Site.RootWeb;
web.EnsureProperties(w => w.ServerRelativeUrl);
web.Context.Load(web.Lists, lc => lc.IncludeWithDefaultProperties(l => l.RootFolder.ServerRelativeUrl));
web.Context.ExecuteQueryRetry();
var existingLists = web.Lists.AsEnumerable().ToList();
var serverRelativeUrl = web.ServerRelativeUrl;
var processedLists = new List<ListInfo>();
// Check if this is not a noscript site as we're not allowed to update some properties
bool isNoScriptSite = web.IsNoScriptSite();
#region Lists
foreach (var templateList in template.Lists)
{
// Check for the presence of the references content types and throw an exception if not present or in template
if (templateList.ContentTypesEnabled)
{
var existingCts = web.Context.LoadQuery(web.AvailableContentTypes);
web.Context.ExecuteQueryRetry();
foreach (var ct in templateList.ContentTypeBindings)
{
var found = template.ContentTypes.Any(t => t.Id.ToUpperInvariant() == ct.ContentTypeId.ToUpperInvariant());
if (found == false)
{
found = existingCts.Any(t => t.StringId.ToUpperInvariant() == ct.ContentTypeId.ToUpperInvariant());
}
if (!found)
{
scope.LogError("Referenced content type {0} not available in site or in template", ct.ContentTypeId);
throw new Exception(string.Format("Referenced content type {0} not available in site or in template", ct.ContentTypeId));
}
}
}
// check if the List exists by url or by title
var index = existingLists.FindIndex(x => x.Title.Equals(templateList.Title, StringComparison.OrdinalIgnoreCase) || x.RootFolder.ServerRelativeUrl.Equals(UrlUtility.Combine(serverRelativeUrl, templateList.Url), StringComparison.OrdinalIgnoreCase));
if (index == -1)
{
try
{
scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ListInstances_Creating_list__0_, templateList.Title);
var returnTuple = CreateList(web, templateList, parser, scope, isNoScriptSite);
var createdList = returnTuple.Item1;
parser = returnTuple.Item2;
processedLists.Add(new ListInfo { SiteList = createdList, TemplateList = templateList });
parser.AddToken(new ListIdToken(web, templateList.Title, createdList.Id));
parser.AddToken(new ListUrlToken(web, templateList.Title, createdList.RootFolder.ServerRelativeUrl.Substring(web.ServerRelativeUrl.Length + 1)));
}
catch (Exception ex)
{
scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ListInstances_Creating_list__0__failed___1_____2_, templateList.Title, ex.Message, ex.StackTrace);
throw;
}
}
else
{
try
{
scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ListInstances_Updating_list__0_, templateList.Title);
var existingList = web.Lists[index];
var returnTuple = UpdateList(web, existingList, templateList, parser, scope, isNoScriptSite);
var updatedList = returnTuple.Item1;
parser = returnTuple.Item2;
if (updatedList != null)
{
processedLists.Add(new ListInfo { SiteList = updatedList, TemplateList = templateList });
}
}
catch (Exception ex)
{
scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ListInstances_Updating_list__0__failed___1_____2_, templateList.Title, ex.Message, ex.StackTrace);
throw;
}
}
}
#endregion
#region FieldRefs
foreach (var listInfo in processedLists)
{
if (listInfo.TemplateList.FieldRefs.Any())
{
foreach (var fieldRef in listInfo.TemplateList.FieldRefs)
{
//.........这里部分代码省略.........
示例5: TokenParser
public TokenParser(Web web, ProvisioningTemplate template)
{
web.EnsureProperties(w => w.ServerRelativeUrl);
_web = web;
_tokens = new List<TokenDefinition>();
_tokens.Add(new SiteCollectionToken(web));
_tokens.Add(new SiteToken(web));
_tokens.Add(new MasterPageCatalogToken(web));
_tokens.Add(new SiteCollectionTermStoreIdToken(web));
_tokens.Add(new KeywordsTermStoreIdToken(web));
_tokens.Add(new ThemeCatalogToken(web));
_tokens.Add(new SiteNameToken(web));
_tokens.Add(new SiteIdToken(web));
_tokens.Add(new AssociatedGroupToken(web, AssociatedGroupToken.AssociatedGroupType.owners));
_tokens.Add(new AssociatedGroupToken(web, AssociatedGroupToken.AssociatedGroupType.members));
_tokens.Add(new AssociatedGroupToken(web, AssociatedGroupToken.AssociatedGroupType.visitors));
_tokens.Add(new GuidToken(web));
_tokens.Add(new CurrentUserIdToken(web));
_tokens.Add(new CurrentUserLoginNameToken(web));
_tokens.Add(new CurrentUserFullNameToken(web));
// Add lists
web.Context.Load(web.Lists, ls => ls.Include(l => l.Id, l => l.Title, l => l.RootFolder.ServerRelativeUrl));
web.Context.ExecuteQueryRetry();
foreach (var list in web.Lists)
{
_tokens.Add(new ListIdToken(web, list.Title, list.Id));
_tokens.Add(new ListUrlToken(web, list.Title, list.RootFolder.ServerRelativeUrl.Substring(web.ServerRelativeUrl.Length + 1)));
}
// Add ContentTypes
web.Context.Load(web.ContentTypes, cs => cs.Include(ct => ct.StringId, ct => ct.Name));
web.Context.ExecuteQueryRetry();
foreach (var ct in web.ContentTypes)
{
_tokens.Add(new ContentTypeIdToken(web, ct.Name, ct.StringId));
}
// Add parameters
foreach (var parameter in template.Parameters)
{
_tokens.Add(new ParameterToken(web, parameter.Key, parameter.Value));
}
// Add TermSetIds
TaxonomySession session = TaxonomySession.GetTaxonomySession(web.Context);
var termStore = session.GetDefaultSiteCollectionTermStore();
web.Context.Load(termStore);
web.Context.ExecuteQueryRetry();
if (!termStore.ServerObjectIsNull.Value)
{
web.Context.Load(termStore.Groups,
g => g.Include(
tg => tg.Name,
tg => tg.TermSets.Include(
ts => ts.Name,
ts => ts.Id)
));
web.Context.ExecuteQueryRetry();
foreach (var termGroup in termStore.Groups)
{
foreach (var termSet in termGroup.TermSets)
{
_tokens.Add(new TermSetIdToken(web, termGroup.Name, termSet.Name, termSet.Id));
}
}
}
_tokens.Add(new SiteCollectionTermGroupIdToken(web));
_tokens.Add(new SiteCollectionTermGroupNameToken(web));
var sortedTokens = from t in _tokens
orderby t.GetTokenLength() descending
select t;
_tokens = sortedTokens.ToList();
}
示例6: ExtractObjects
public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
{
using (var scope = new PnPMonitoredScope(this.Name))
{
web.EnsureProperties(w => w.ServerRelativeUrl, w => w.Url);
var serverRelativeUrl = web.ServerRelativeUrl;
// For each list in the site
var lists = web.Lists;
web.Context.Load(lists,
lc => lc.IncludeWithDefaultProperties(
l => l.ContentTypes,
l => l.Views,
l => l.BaseTemplate,
l => l.OnQuickLaunch,
l => l.RootFolder.ServerRelativeUrl,
l => l.Fields.IncludeWithDefaultProperties(
f => f.Id,
f => f.Title,
f => f.Hidden,
f => f.InternalName,
f => f.Required)));
web.Context.ExecuteQueryRetry();
// Let's see if there are workflow subscriptions
Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription[] workflowSubscriptions = null;
try
{
workflowSubscriptions = web.GetWorkflowSubscriptions();
}
catch (ServerException)
{
// If there is no workflow service present in the farm this method will throw an error.
// Swallow the exception
}
// Retrieve all not hidden lists and the Workflow History Lists, just in case there are active workflow subscriptions
var includeWorkflowSubscriptions = workflowSubscriptions != null && workflowSubscriptions.Length > 0;
// var allowedLists = lists.Where(l => !l.Hidden || includeWorkflowSubscriptions && l.BaseTemplate == 140);
foreach (var siteList in lists)
{
ListInstance baseTemplateList = null;
if (creationInfo.BaseTemplate != null)
{
// Check if we need to skip this list...if so let's do it before we gather all the other information for this list...improves performance
var index = creationInfo.BaseTemplate.Lists.FindIndex(f => f.Url.Equals(siteList.RootFolder.ServerRelativeUrl.Substring(serverRelativeUrl.Length + 1)) &&
f.TemplateType.Equals(siteList.BaseTemplate));
if (index != -1)
{
baseTemplateList = creationInfo.BaseTemplate.Lists[index];
if (siteList.Hidden && !(includeWorkflowSubscriptions && siteList.BaseTemplate == 140))
{
continue;
}
}
}
var contentTypeFields = new List<FieldRef>();
var list = new ListInstance
{
Description = siteList.Description,
EnableVersioning = siteList.EnableVersioning,
TemplateType = siteList.BaseTemplate,
Title = siteList.Title,
Hidden = siteList.Hidden,
EnableFolderCreation = siteList.EnableFolderCreation,
DocumentTemplate = Tokenize(siteList.DocumentTemplateUrl, web.Url),
ContentTypesEnabled = siteList.ContentTypesEnabled,
Url = siteList.RootFolder.ServerRelativeUrl.Substring(serverRelativeUrl.Length).TrimStart('/'),
TemplateFeatureID = siteList.TemplateFeatureId,
EnableAttachments = siteList.EnableAttachments,
OnQuickLaunch = siteList.OnQuickLaunch,
MaxVersionLimit =
siteList.IsObjectPropertyInstantiated("MajorVersionLimit") ? siteList.MajorVersionLimit : 0,
EnableMinorVersions = siteList.EnableMinorVersions,
MinorVersionLimit =
siteList.IsObjectPropertyInstantiated("MajorWithMinorVersionsLimit")
? siteList.MajorWithMinorVersionsLimit
: 0
};
list = ExtractContentTypes(web, siteList, contentTypeFields, list);
list = ExtractViews(siteList, list);
list = ExtractFields(web, siteList, contentTypeFields, list, lists);
list.Security = siteList.GetSecurity();
var logCTWarning = false;
if (baseTemplateList != null)
{
if (!baseTemplateList.Equals(list))
{
scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ListInstances_Adding_list___0_____1_, list.Title, list.Url);
template.Lists.Add(list);
//.........这里部分代码省略.........
示例7: 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.RootFolder.WelcomePage);
foreach (var page in template.Pages)
{
var url = parser.ParseString(page.Url);
if (!url.ToLower().StartsWith(web.ServerRelativeUrl.ToLower()))
{
url = UrlUtility.Combine(web.ServerRelativeUrl, url);
}
var exists = true;
Microsoft.SharePoint.Client.File file = null;
try
{
file = web.GetFileByServerRelativeUrl(url);
web.Context.Load(file);
web.Context.ExecuteQuery();
}
catch (ServerException ex)
{
if (ex.ServerErrorTypeName == "System.IO.FileNotFoundException")
{
exists = false;
}
}
if (exists)
{
if (page.Overwrite)
{
try
{
scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Pages_Overwriting_existing_page__0_, url);
if (page.WelcomePage && url.Contains(web.RootFolder.WelcomePage))
web.SetHomePage(string.Empty);
file.DeleteObject();
web.Context.ExecuteQueryRetry();
web.AddWikiPageByUrl(url);
if (page.Layout == WikiPageLayout.Custom)
{
web.AddLayoutToWikiPage(WikiPageLayout.OneColumn, url);
}
else {
web.AddLayoutToWikiPage(page.Layout, url);
}
}
catch (Exception ex)
{
scope.LogError(CoreResources.Provisioning_ObjectHandlers_Pages_Overwriting_existing_page__0__failed___1_____2_, url, ex.Message, ex.StackTrace);
}
}
}
else
{
try
{
scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Pages_Creating_new_page__0_, url);
web.AddWikiPageByUrl(url);
web.AddLayoutToWikiPage(page.Layout, url);
}
catch (Exception ex)
{
scope.LogError(CoreResources.Provisioning_ObjectHandlers_Pages_Creating_new_page__0__failed___1_____2_, url, ex.Message, ex.StackTrace);
}
}
if (page.WelcomePage)
{
web.RootFolder.EnsureProperty(p => p.ServerRelativeUrl);
var rootFolderRelativeUrl = url.Substring(web.RootFolder.ServerRelativeUrl.Length);
web.SetHomePage(rootFolderRelativeUrl);
}
if (page.WebParts != null & page.WebParts.Any())
{
var existingWebParts = web.GetWebParts(url);
foreach (var webpart in page.WebParts)
{
if (existingWebParts.FirstOrDefault(w => w.WebPart.Title == webpart.Title) == null)
{
WebPartEntity wpEntity = new WebPartEntity();
wpEntity.WebPartTitle = webpart.Title;
wpEntity.WebPartXml = parser.ParseString(webpart.Contents.Trim(new[] { '\n', ' ' }));
web.AddWebPartToWikiPage(url, wpEntity, (int)webpart.Row, (int)webpart.Column, false);
}
}
var allWebParts = web.GetWebParts(url);
foreach (var webpart in allWebParts)
{
parser.AddToken(new WebPartIdToken(web, webpart.WebPart.Title, webpart.Id));
//.........这里部分代码省略.........
示例8: ExtractObjects
public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
{
if (template.Workflows == null)
{
template.Workflows = new Workflows();
}
using (var scope = new PnPMonitoredScope(this.Name))
{
if (creationInfo.FileConnector == null)
{
scope.LogWarning("Cannot export Workflow definitions without a FileConnector.");
}
else
{
// Pre-load useful properties
web.EnsureProperties(w => w.Id, w => w.ServerRelativeUrl, w => w.Url);
// Retrieve all the lists and libraries
var lists = web.Lists;
web.Context.Load(lists);
web.Context.ExecuteQueryRetry();
// Retrieve the workflow definitions (including unpublished ones)
Microsoft.SharePoint.Client.WorkflowServices.WorkflowDefinition[] definitions = null;
try
{
definitions = web.GetWorkflowDefinitions(false);
}
catch (ServerException)
{
// If there is no workflow service present in the farm this method will throw an error.
// Swallow the exception
}
if (definitions != null)
{
template.Workflows.WorkflowDefinitions.AddRange(
from d in definitions.AsEnumerable()
select new Model.WorkflowDefinition(d.Properties.TokenizeWorkflowDefinitionProperties(lists))
{
AssociationUrl = d.AssociationUrl,
Description = d.Description,
DisplayName = d.DisplayName,
DraftVersion = d.DraftVersion,
FormField = d.FormField,
Id = d.Id,
InitiationUrl = d.InitiationUrl,
Published = d.Published,
RequiresAssociationForm = d.RequiresAssociationForm,
RequiresInitiationForm = d.RequiresInitiationForm,
RestrictToScope = (!String.IsNullOrEmpty(d.RestrictToScope) && Guid.Parse(d.RestrictToScope) != web.Id) ? WorkflowExtension.TokenizeListIdProperty(d.RestrictToScope, lists) : null,
RestrictToType = !String.IsNullOrEmpty(d.RestrictToType) ? d.RestrictToType : "Universal",
XamlPath = d.Xaml.SaveXamlToFile(d.Id, creationInfo.FileConnector, lists),
}
);
foreach (var d in definitions.AsEnumerable())
{
if (d.RequiresInitiationForm)
{
PersistWorkflowForm(web, template, creationInfo, scope, d.InitiationUrl);
}
if (d.RequiresAssociationForm)
{
PersistWorkflowForm(web, template, creationInfo, scope, d.AssociationUrl);
}
}
}
// Retrieve the workflow subscriptions
Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription[] subscriptions = null;
try
{
subscriptions = web.GetWorkflowSubscriptions();
}
catch (ServerException)
{
// If there is no workflow service present in the farm this method will throw an error.
// Swallow the exception
}
if (subscriptions != null)
{
#if ONPREMISES
template.Workflows.WorkflowSubscriptions.AddRange(
from s in subscriptions.AsEnumerable()
select new Model.WorkflowSubscription(s.PropertyDefinitions.TokenizeWorkflowSubscriptionProperties(lists))
{
DefinitionId = s.DefinitionId,
Enabled = s.Enabled,
EventSourceId = s.EventSourceId != web.Id ? String.Format("{{listid:{0}}}", lists.First(l => l.Id == s.EventSourceId).Title) : null,
EventTypes = s.EventTypes.ToList(),
ManualStartBypassesActivationLimit = s.ManualStartBypassesActivationLimit,
Name = s.Name,
ListId = s.EventSourceId != web.Id ? String.Format("{{listid:{0}}}", lists.First(l => l.Id == s.EventSourceId).Title) : null,
StatusFieldName = s.StatusFieldName,
}
//.........这里部分代码省略.........
示例9: ExtractObjects
public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
{
using (var scope = new PnPMonitoredScope(this.Name))
{
// Load object if not there
#if !CLIENTSDKV15
web.EnsureProperties(w => w.Url, w => w.MasterUrl, w => w.AlternateCssUrl, w => w.SiteLogoUrl);
#else
web.EnsureProperties(w => w.Url, w => w.MasterUrl);
#endif
// Information coming from the site
template.ComposedLook.MasterPage = Tokenize(web.MasterUrl, web.Url);
#if !CLIENTSDKV15
template.ComposedLook.AlternateCSS = Tokenize(web.AlternateCssUrl, web.Url);
template.ComposedLook.SiteLogo = Tokenize(web.SiteLogoUrl, web.Url);
#else
template.ComposedLook.AlternateCSS = null;
template.ComposedLook.SiteLogo = null;
#endif
scope.LogInfo(CoreResources.Provisioning_ObjectHandlers_ComposedLooks_ExtractObjects_Retrieving_current_composed_look);
Site site = (web.Context as ClientContext).Site;
if (!site.IsObjectPropertyInstantiated("Url"))
{
web.Context.Load(site);
web.Context.ExecuteQueryRetry();
}
SharePointConnector spConnector = new SharePointConnector(web.Context, web.Url, "dummy");
// to get files from theme catalog we need a connector linked to the root site
SharePointConnector spConnectorRoot;
if (!site.Url.Equals(web.Url, StringComparison.InvariantCultureIgnoreCase))
{
spConnectorRoot = new SharePointConnector(web.Context.Clone(site.Url), site.Url, "dummy");
}
else
{
spConnectorRoot = spConnector;
}
// Check if we have composed look info in the property bag, if so, use that, otherwise try to detect the current composed look
if (web.PropertyBagContainsKey("_PnP_ProvisioningTemplateComposedLookInfo"))
{
scope.LogInfo(CoreResources.Provisioning_ObjectHandlers_ComposedLooks_ExtractObjects_Using_ComposedLookInfoFromPropertyBag);
try
{
var composedLook = JsonConvert.DeserializeObject<ComposedLook>(web.GetPropertyBagValueString("_PnP_ProvisioningTemplateComposedLookInfo", ""));
if (composedLook.Name == null || composedLook.BackgroundFile == null || composedLook.FontFile == null || composedLook.MasterPage == null || composedLook.SiteLogo == null)
{
scope.LogError(CoreResources.Provisioning_ObjectHandlers_ComposedLooks_ExtractObjects_ComposedLookInfoFailedToDeserialize);
throw new JsonSerializationException();
}
template.ComposedLook = composedLook;
if (creationInfo != null && creationInfo.PersistComposedLookFiles && creationInfo.FileConnector != null)
{
scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ComposedLooks_ExtractObjects_Creating_SharePointConnector);
// Let's create a SharePoint connector since our files anyhow are in SharePoint at this moment
// Download the theme/branding specific files
#if !CLIENTSDKV15
DownLoadFile(spConnector, spConnectorRoot, creationInfo.FileConnector, web.Url, web.AlternateCssUrl, scope);
DownLoadFile(spConnector, spConnectorRoot, creationInfo.FileConnector, web.Url, web.SiteLogoUrl, scope);
#endif
TokenParser parser = new TokenParser(web, template);
DownLoadFile(spConnector, spConnectorRoot, creationInfo.FileConnector, web.Url, parser.ParseString(composedLook.BackgroundFile), scope);
DownLoadFile(spConnector, spConnectorRoot, creationInfo.FileConnector, web.Url, parser.ParseString(composedLook.ColorFile), scope);
DownLoadFile(spConnector, spConnectorRoot, creationInfo.FileConnector, web.Url, parser.ParseString(composedLook.FontFile), scope);
}
// Create file entries for the custom theme files
if (!string.IsNullOrEmpty(template.ComposedLook.BackgroundFile))
{
template.Files.Add(GetComposedLookFile(template.ComposedLook.BackgroundFile));
}
if (!string.IsNullOrEmpty(template.ComposedLook.ColorFile))
{
template.Files.Add(GetComposedLookFile(template.ComposedLook.ColorFile));
}
if (!string.IsNullOrEmpty(template.ComposedLook.FontFile))
{
template.Files.Add(GetComposedLookFile(template.ComposedLook.FontFile));
}
if (!string.IsNullOrEmpty(template.ComposedLook.SiteLogo))
{
template.Files.Add(GetComposedLookFile(template.ComposedLook.SiteLogo));
}
}
catch (JsonSerializationException)
{
// cannot deserialize the object, fall back to composed look detection
template = DetectComposedLook(web, template, creationInfo, scope, spConnector, spConnectorRoot);
}
//.........这里部分代码省略.........
示例10: TokenParser
public TokenParser(Web web, ProvisioningTemplate template)
{
web.EnsureProperties(w => w.ServerRelativeUrl, w => w.Language);
_web = web;
_tokens = new List<TokenDefinition>();
_tokens.Add(new SiteCollectionToken(web));
_tokens.Add(new SiteToken(web));
_tokens.Add(new MasterPageCatalogToken(web));
_tokens.Add(new SiteCollectionTermStoreIdToken(web));
_tokens.Add(new KeywordsTermStoreIdToken(web));
_tokens.Add(new ThemeCatalogToken(web));
_tokens.Add(new SiteNameToken(web));
_tokens.Add(new SiteIdToken(web));
_tokens.Add(new AssociatedGroupToken(web, AssociatedGroupToken.AssociatedGroupType.owners));
_tokens.Add(new AssociatedGroupToken(web, AssociatedGroupToken.AssociatedGroupType.members));
_tokens.Add(new AssociatedGroupToken(web, AssociatedGroupToken.AssociatedGroupType.visitors));
_tokens.Add(new GuidToken(web));
_tokens.Add(new CurrentUserIdToken(web));
_tokens.Add(new CurrentUserLoginNameToken(web));
_tokens.Add(new CurrentUserFullNameToken(web));
// Add lists
web.Context.Load(web.Lists, ls => ls.Include(l => l.Id, l => l.Title, l => l.RootFolder.ServerRelativeUrl));
web.Context.ExecuteQueryRetry();
foreach (var list in web.Lists)
{
_tokens.Add(new ListIdToken(web, list.Title, list.Id));
_tokens.Add(new ListUrlToken(web, list.Title, list.RootFolder.ServerRelativeUrl.Substring(web.ServerRelativeUrl.Length + 1)));
}
// Add ContentTypes
web.Context.Load(web.ContentTypes, cs => cs.Include(ct => ct.StringId, ct => ct.Name));
web.Context.ExecuteQueryRetry();
foreach (var ct in web.ContentTypes)
{
_tokens.Add(new ContentTypeIdToken(web, ct.Name, ct.StringId));
}
// Add parameters
foreach (var parameter in template.Parameters)
{
_tokens.Add(new ParameterToken(web, parameter.Key, parameter.Value));
}
// Add TermSetIds
TaxonomySession session = TaxonomySession.GetTaxonomySession(web.Context);
var termStore = session.GetDefaultSiteCollectionTermStore();
web.Context.Load(termStore);
web.Context.ExecuteQueryRetry();
if (!termStore.ServerObjectIsNull.Value)
{
web.Context.Load(termStore.Groups,
g => g.Include(
tg => tg.Name,
tg => tg.TermSets.Include(
ts => ts.Name,
ts => ts.Id)
));
web.Context.ExecuteQueryRetry();
foreach (var termGroup in termStore.Groups)
{
foreach (var termSet in termGroup.TermSets)
{
_tokens.Add(new TermSetIdToken(web, termGroup.Name, termSet.Name, termSet.Id));
}
}
}
_tokens.Add(new SiteCollectionTermGroupIdToken(web));
_tokens.Add(new SiteCollectionTermGroupNameToken(web));
// Handle resources
if (template.Localizations.Any())
{
// Read all resource keys in a list
List<Tuple<string, uint, string>> resourceEntries = new List<Tuple<string, uint, string>>();
foreach (var localizationEntry in template.Localizations)
{
var filePath = localizationEntry.ResourceFile;
using (var stream = template.Connector.GetFileStream(filePath))
{
if (stream != null)
{
using (ResXResourceReader resxReader = new ResXResourceReader(stream))
{
foreach (DictionaryEntry entry in resxReader)
{
resourceEntries.Add(new Tuple<string, uint, string>(entry.Key.ToString(), (uint)localizationEntry.LCID, entry.Value.ToString()));
}
}
}
}
}
var uniqueKeys = resourceEntries.Select(k => k.Item1).Distinct();
foreach (var key in uniqueKeys)
{
//.........这里部分代码省略.........
示例11: ExtractObjects
public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
{
using (var scope = new PnPMonitoredScope(this.Name))
{
web.EnsureProperties(
#if !ONPREMISES
w => w.NoCrawl,
w => w.RequestAccessEmail,
#endif
//w => w.Title,
//w => w.Description,
w => w.MasterUrl,
w => w.CustomMasterUrl,
w => w.SiteLogoUrl,
w => w.RootFolder,
w => w.AlternateCssUrl,
w => w.Url);
var webSettings = new WebSettings();
#if !ONPREMISES
webSettings.NoCrawl = web.NoCrawl;
webSettings.RequestAccessEmail = web.RequestAccessEmail;
#endif
// We're not extracting Title and Description
//webSettings.Title = Tokenize(web.Title, web.Url);
//webSettings.Description = Tokenize(web.Description, web.Url);
webSettings.MasterPageUrl = Tokenize(web.MasterUrl, web.Url);
webSettings.CustomMasterPageUrl = Tokenize(web.CustomMasterUrl, web.Url);
webSettings.SiteLogo = Tokenize(web.SiteLogoUrl, web.Url);
// Notice. No tokenization needed for the welcome page, it's always relative for the site
webSettings.WelcomePage = web.RootFolder.WelcomePage;
webSettings.AlternateCSS = Tokenize(web.AlternateCssUrl, web.Url);
template.WebSettings = webSettings;
if (creationInfo.PersistBrandingFiles)
{
if (!string.IsNullOrEmpty(web.MasterUrl))
{
var masterUrl = web.MasterUrl.ToLower();
if (!masterUrl.EndsWith("default.master") && !masterUrl.EndsWith("custom.master") && !masterUrl.EndsWith("v4.master") && !masterUrl.EndsWith("seattle.master") && !masterUrl.EndsWith("oslo.master"))
{
if (PersistFile(web, creationInfo, scope, web.MasterUrl))
{
template.Files.Add(GetTemplateFile(web, web.MasterUrl));
}
}
}
if (!string.IsNullOrEmpty(web.CustomMasterUrl))
{
var customMasterUrl = web.CustomMasterUrl.ToLower();
if (!customMasterUrl.EndsWith("default.master") && !customMasterUrl.EndsWith("custom.master") && !customMasterUrl.EndsWith("v4.master") && !customMasterUrl.EndsWith("seattle.master") && !customMasterUrl.EndsWith("oslo.master"))
{
if (PersistFile(web, creationInfo, scope, web.CustomMasterUrl))
{
template.Files.Add(GetTemplateFile(web, web.CustomMasterUrl));
}
}
}
if (!string.IsNullOrEmpty(web.SiteLogoUrl))
{
if (PersistFile(web, creationInfo, scope, web.SiteLogoUrl))
{
template.Files.Add(GetTemplateFile(web, web.SiteLogoUrl));
}
}
if (!string.IsNullOrEmpty(web.AlternateCssUrl))
{
if (PersistFile(web, creationInfo, scope, web.AlternateCssUrl))
{
template.Files.Add(GetTemplateFile(web, web.AlternateCssUrl));
}
}
}
var files = template.Files.Distinct().ToList();
template.Files.Clear();
template.Files.AddRange(files);
}
return template;
}
示例12: ExtractObjects
public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
{
using (var scope = new PnPMonitoredScope(this.Name))
{
web.EnsureProperties(w => w.ServerRelativeUrl, w => w.Url);
var serverRelativeUrl = web.ServerRelativeUrl;
// For each list in the site
var lists = web.Lists;
web.Context.Load(lists,
lc => lc.IncludeWithDefaultProperties(
l => l.ContentTypes,
l => l.Views,
l => l.BaseTemplate,
l => l.OnQuickLaunch,
l => l.RootFolder.ServerRelativeUrl,
l => l.Fields.IncludeWithDefaultProperties(
f => f.Id,
f => f.Title,
f => f.Hidden,
f => f.InternalName,
f => f.Required)));
web.Context.ExecuteQueryRetry();
// Let's see if there are workflow subscriptions
Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription[] workflowSubscriptions = null;
try
{
workflowSubscriptions = web.GetWorkflowSubscriptions();
}
catch (ServerException)
{
// If there is no workflow service present in the farm this method will throw an error.
// Swallow the exception
}
// Retrieve all not hidden lists and the Workflow History Lists, just in case there are active workflow subscriptions
foreach (var siteList in lists.AsEnumerable().Where(l => (l.Hidden == false || ((workflowSubscriptions != null && workflowSubscriptions.Length > 0) && l.BaseTemplate == 140))))
{
ListInstance baseTemplateList = null;
if (creationInfo.BaseTemplate != null)
{
// Check if we need to skip this list...if so let's do it before we gather all the other information for this list...improves performance
var index = creationInfo.BaseTemplate.Lists.FindIndex(f => f.Url.Equals(siteList.RootFolder.ServerRelativeUrl.Substring(serverRelativeUrl.Length + 1)) &&
f.TemplateType.Equals(siteList.BaseTemplate));
if (index != -1)
{
baseTemplateList = creationInfo.BaseTemplate.Lists[index];
}
}
var contentTypeFields = new List<FieldRef>();
var list = new ListInstance
{
Description = siteList.Description,
EnableVersioning = siteList.EnableVersioning,
TemplateType = siteList.BaseTemplate,
Title = siteList.Title,
Hidden = siteList.Hidden,
EnableFolderCreation = siteList.EnableFolderCreation,
DocumentTemplate = Tokenize(siteList.DocumentTemplateUrl, web.Url),
ContentTypesEnabled = siteList.ContentTypesEnabled,
Url = siteList.RootFolder.ServerRelativeUrl.Substring(serverRelativeUrl.Length).TrimStart('/'),
TemplateFeatureID = siteList.TemplateFeatureId,
EnableAttachments = siteList.EnableAttachments,
OnQuickLaunch = siteList.OnQuickLaunch,
MaxVersionLimit =
siteList.IsObjectPropertyInstantiated("MajorVersionLimit") ? siteList.MajorVersionLimit : 0,
EnableMinorVersions = siteList.EnableMinorVersions,
MinorVersionLimit =
siteList.IsObjectPropertyInstantiated("MajorWithMinorVersionsLimit")
? siteList.MajorWithMinorVersionsLimit
: 0
};
var count = 0;
foreach (var ct in siteList.ContentTypes)
{
web.Context.Load(ct, c => c.Parent);
web.Context.ExecuteQueryRetry();
list.ContentTypeBindings.Add(new ContentTypeBinding
{
ContentTypeId = ct.Parent != null ? ct.Parent.StringId : ct.StringId,
Default = count == 0
});
//if (ct.Parent != null)
//{
// //Add the parent to the list of content types
// if (!BuiltInContentTypeId.Contains(ct.Parent.StringId))
// {
// list.ContentTypeBindings.Add(new ContentTypeBinding { ContentTypeId = ct.Parent.StringId, Default = count == 0 });
// }
//}
//else
//{
//.........这里部分代码省略.........
示例13: ProvisionObjects
public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
{
using (var scope = new PnPMonitoredScope(this.Name))
{
// Check if this is not a noscript site as we're not allowed to write to the web property bag is that one
bool isNoScriptSite = web.IsNoScriptSite();
var context = web.Context as ClientContext;
web.EnsureProperties(w => w.ServerRelativeUrl, w => w.Url);
// Build on the fly the list of additional files coming from the Directories
var directoryFiles = new List<Model.File>();
foreach (var directory in template.Directories)
{
var metadataProperties = directory.GetMetadataProperties();
directoryFiles.AddRange(directory.GetDirectoryFiles(metadataProperties));
}
foreach (var file in template.Files.Union(directoryFiles))
{
var folderName = parser.ParseString(file.Folder);
if (folderName.ToLower().StartsWith((web.ServerRelativeUrl.ToLower())))
{
folderName = folderName.Substring(web.ServerRelativeUrl.Length);
}
if (SkipFile(isNoScriptSite, file.Src, folderName))
{
// add log message
scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_Files_SkipFileUpload, file.Src, folderName);
continue;
}
var folder = web.EnsureFolderPath(folderName);
var checkedOut = false;
var targetFile = folder.GetFile(template.Connector.GetFilenamePart(file.Src));
if (targetFile != null)
{
if (file.Overwrite)
{
scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Files_Uploading_and_overwriting_existing_file__0_, file.Src);
checkedOut = CheckOutIfNeeded(web, targetFile);
using (var stream = GetFileStream(template, file))
{
targetFile = UploadFile(template, file, folder, stream);
}
}
else
{
checkedOut = CheckOutIfNeeded(web, targetFile);
}
}
else
{
using (var stream = GetFileStream(template, file))
{
scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Files_Uploading_file__0_, file.Src);
targetFile = UploadFile(template, file, folder, stream);
}
checkedOut = CheckOutIfNeeded(web, targetFile);
}
if (targetFile != null)
{
if (file.Properties != null && file.Properties.Any())
{
Dictionary<string, string> transformedProperties = file.Properties.ToDictionary(property => property.Key, property => parser.ParseString(property.Value));
SetFileProperties(targetFile, transformedProperties, false);
}
#if !SP2013
bool webPartsNeedLocalization = false;
#endif
if (file.WebParts != null && file.WebParts.Any())
{
targetFile.EnsureProperties(f => f.ServerRelativeUrl);
var existingWebParts = web.GetWebParts(targetFile.ServerRelativeUrl).ToList();
foreach (var webPart in file.WebParts)
{
// check if the webpart is already set on the page
if (existingWebParts.FirstOrDefault(w => w.WebPart.Title == parser.ParseString(webPart.Title)) == null)
{
scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Files_Adding_webpart___0___to_page, webPart.Title);
var wpEntity = new WebPartEntity();
wpEntity.WebPartTitle = parser.ParseString(webPart.Title);
wpEntity.WebPartXml = parser.ParseString(webPart.Contents).Trim(new[] { '\n', ' ' });
wpEntity.WebPartZone = webPart.Zone;
wpEntity.WebPartIndex = (int)webPart.Order;
var wpd = web.AddWebPartToWebPartPage(targetFile.ServerRelativeUrl, wpEntity);
#if !SP2013
if (webPart.Title.ContainsResourceToken())
{
//.........这里部分代码省略.........
示例14: 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.RootFolder.WelcomePage);
// Check if this is not a noscript site as we're not allowed to update some properties
bool isNoScriptSite = web.IsNoScriptSite();
foreach (var page in template.Pages)
{
var url = parser.ParseString(page.Url);
if (!url.ToLower().StartsWith(web.ServerRelativeUrl.ToLower()))
{
url = UrlUtility.Combine(web.ServerRelativeUrl, url);
}
var exists = true;
Microsoft.SharePoint.Client.File file = null;
try
{
file = web.GetFileByServerRelativeUrl(url);
web.Context.Load(file);
web.Context.ExecuteQueryRetry();
}
catch (ServerException ex)
{
if (ex.ServerErrorTypeName == "System.IO.FileNotFoundException")
{
exists = false;
}
}
if (exists)
{
if (page.Overwrite)
{
try
{
scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Pages_Overwriting_existing_page__0_, url);
if (page.WelcomePage && url.Contains(web.RootFolder.WelcomePage))
web.SetHomePage(string.Empty);
file.DeleteObject();
web.Context.ExecuteQueryRetry();
web.AddWikiPageByUrl(url);
if (page.Layout == WikiPageLayout.Custom)
{
web.AddLayoutToWikiPage(WikiPageLayout.OneColumn, url);
}
else
{
web.AddLayoutToWikiPage(page.Layout, url);
}
}
catch (Exception ex)
{
scope.LogError(CoreResources.Provisioning_ObjectHandlers_Pages_Overwriting_existing_page__0__failed___1_____2_, url, ex.Message, ex.StackTrace);
}
}
}
else
{
try
{
scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Pages_Creating_new_page__0_, url);
web.AddWikiPageByUrl(url);
if (page.Layout == WikiPageLayout.Custom)
{
web.AddLayoutToWikiPage(WikiPageLayout.OneColumn, url);
}
else
{
web.AddLayoutToWikiPage(page.Layout, url);
}
}
catch (Exception ex)
{
scope.LogError(CoreResources.Provisioning_ObjectHandlers_Pages_Creating_new_page__0__failed___1_____2_, url, ex.Message, ex.StackTrace);
}
}
if (page.WelcomePage)
{
web.RootFolder.EnsureProperty(p => p.ServerRelativeUrl);
var rootFolderRelativeUrl = url.Substring(web.RootFolder.ServerRelativeUrl.Length);
web.SetHomePage(rootFolderRelativeUrl);
}
#if !SP2013
bool webPartsNeedLocalization = false;
#endif
if (page.WebParts != null & page.WebParts.Any())
{
if (!isNoScriptSite)
{
//.........这里部分代码省略.........
示例15: ExtractObjects
public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
{
using (var scope = new PnPMonitoredScope(this.Name))
{
// Extract the Home Page
web.EnsureProperties(w => w.RootFolder.WelcomePage, w => w.ServerRelativeUrl, w => w.Url);
var homepageUrl = web.RootFolder.WelcomePage;
if (string.IsNullOrEmpty(homepageUrl))
{
homepageUrl = "Default.aspx";
}
var welcomePageUrl = UrlUtility.Combine(web.ServerRelativeUrl, homepageUrl);
var file = web.GetFileByServerRelativeUrl(welcomePageUrl);
try
{
var listItem = file.EnsureProperty(f => f.ListItemAllFields);
if (listItem != null)
{
if (listItem.FieldValues.ContainsKey("WikiField"))
{
// Wiki page
var fullUri = new Uri(UrlUtility.Combine(web.Url, web.RootFolder.WelcomePage));
var folderPath = fullUri.Segments.Take(fullUri.Segments.Count() - 1).ToArray().Aggregate((i, x) => i + x).TrimEnd('/');
var fileName = fullUri.Segments[fullUri.Segments.Count() - 1];
var homeFile = web.GetFileByServerRelativeUrl(welcomePageUrl);
LimitedWebPartManager limitedWPManager =
homeFile.GetLimitedWebPartManager(PersonalizationScope.Shared);
web.Context.Load(limitedWPManager);
var webParts = web.GetWebParts(welcomePageUrl);
var page = new Page()
{
Layout = WikiPageLayout.Custom,
Overwrite = true,
Url = Tokenize(fullUri.PathAndQuery, web.Url),
};
var pageContents = listItem.FieldValues["WikiField"].ToString();
Regex regexClientIds = new Regex(@"id=\""div_(?<ControlId>(\w|\-)+)");
if (regexClientIds.IsMatch(pageContents))
{
foreach (Match webPartMatch in regexClientIds.Matches(pageContents))
{
String serverSideControlId = webPartMatch.Groups["ControlId"].Value;
try
{
String serverSideControlIdToSearchFor = String.Format("g_{0}",
serverSideControlId.Replace("-", "_"));
WebPartDefinition webPart = limitedWPManager.WebParts.GetByControlId(serverSideControlIdToSearchFor);
web.Context.Load(webPart,
wp => wp.Id,
wp => wp.WebPart.Title,
wp => wp.WebPart.ZoneIndex
);
web.Context.ExecuteQueryRetry();
var webPartxml = TokenizeWebPartXml(web, web.GetWebPartXml(webPart.Id, welcomePageUrl));
page.WebParts.Add(new Model.WebPart()
{
Title = webPart.WebPart.Title,
Contents = webPartxml,
Order = (uint)webPart.WebPart.ZoneIndex,
Row = 1, // By default we will create a onecolumn layout, add the webpart to it, and later replace the wikifield on the page to position the webparts correctly.
Column = 1 // By default we will create a onecolumn layout, add the webpart to it, and later replace the wikifield on the page to position the webparts correctly.
});
pageContents = Regex.Replace(pageContents, serverSideControlId, string.Format("{{webpartid:{0}}}", webPart.WebPart.Title), RegexOptions.IgnoreCase);
}
catch (ServerException)
{
scope.LogWarning("Found a WebPart ID which is not available on the server-side. ID: {0}", serverSideControlId);
}
}
}
page.Fields.Add("WikiField", pageContents);
template.Pages.Add(page);
// Set the homepage
if (template.WebSettings == null)
{
template.WebSettings = new WebSettings();
}
template.WebSettings.WelcomePage = homepageUrl;
}
else
{
if (web.Context.HasMinimalServerLibraryVersion(Constants.MINIMUMZONEIDREQUIREDSERVERVERSION))
{
//.........这里部分代码省略.........