protected override void MapProperties(object modelHost, Hashtable fileProperties, ContentPageDefinitionBase definition) { base.MapProperties(modelHost, fileProperties, definition); var typedDefinition = definition.WithAssertAndCast<FilterDisplayTemplateDefinition>("model", value => value.RequireNotNull()); fileProperties[BuiltInInternalFieldNames.ContentTypeId] = "0x0101002039C03B61C64EC4A04F5361F38510660400F643FF79F6BD764F8A469B6F153396EE"; if (!string.IsNullOrEmpty(typedDefinition.CrawlerXSLFileURL)) { var crawlerXSLFileValue = new SPFieldUrlValue { Url = typedDefinition.CrawlerXSLFileURL }; if (!string.IsNullOrEmpty(typedDefinition.CrawlerXSLFileDescription)) crawlerXSLFileValue.Description = typedDefinition.CrawlerXSLFileDescription; fileProperties["CrawlerXSLFile"] = crawlerXSLFileValue.ToString(); } if (!string.IsNullOrEmpty(typedDefinition.CompatibleManagedProperties)) fileProperties["CompatibleManagedProperties"] = typedDefinition.CompatibleManagedProperties; if (typedDefinition.CompatibleSearchDataTypes.Count > 0) { var multiChoiceValue = new SPFieldMultiChoiceValue(); foreach (var value in typedDefinition.CompatibleSearchDataTypes) multiChoiceValue.Add(value); fileProperties["CompatibleSearchDataTypes"] = multiChoiceValue.ToString(); } }
protected override void MapProperties(object modelHost, Hashtable fileProperties, ContentPageDefinitionBase definition) { base.MapProperties(modelHost, fileProperties, definition); var typedTemplateModel = definition.WithAssertAndCast<ItemControlTemplateDefinitionBase>("model", value => value.RequireNotNull()); if (typedTemplateModel.TargetControlTypes.Count > 0) { var multiChoiceValue = new SPFieldMultiChoiceValue(); foreach (var value in typedTemplateModel.TargetControlTypes) multiChoiceValue.Add(value); fileProperties["TargetControlType"] = multiChoiceValue.ToString(); } if (!string.IsNullOrEmpty(typedTemplateModel.PreviewURL)) { var htmlPreviewValue = new SPFieldUrlValue { Url = typedTemplateModel.PreviewURL }; if (!string.IsNullOrEmpty(typedTemplateModel.PreviewDescription)) htmlPreviewValue.Description = typedTemplateModel.PreviewDescription; fileProperties["HtmlDesignPreviewUrl"] = htmlPreviewValue.ToString(); } }
protected override void MapProperties(object modelHost, Hashtable fileProperties, ContentPageDefinitionBase definition) { base.MapProperties(modelHost, fileProperties, definition); var typedDefinition = definition.WithAssertAndCast<JavaScriptDisplayTemplateDefinition>("model", value => value.RequireNotNull()); fileProperties[BuiltInInternalFieldNames.ContentTypeId] = "0x0101002039C03B61C64EC4A04F5361F3851068"; if (!string.IsNullOrEmpty(typedDefinition.Standalone)) fileProperties["DisplayTemplateJSTemplateType"] = typedDefinition.Standalone; if (!string.IsNullOrEmpty(typedDefinition.TargetControlType)) fileProperties["DisplayTemplateJSTargetControlType"] = typedDefinition.TargetControlType; if (!string.IsNullOrEmpty(typedDefinition.TargetListTemplateId)) fileProperties["DisplayTemplateJSTargetListTemplate"] = typedDefinition.TargetListTemplateId; if (!string.IsNullOrEmpty(typedDefinition.TargetScope)) fileProperties["DisplayTemplateJSTargetScope"] = typedDefinition.TargetScope; if (!string.IsNullOrEmpty(typedDefinition.IconUrl)) { var iconValue = new SPFieldUrlValue { Url = typedDefinition.IconUrl }; if (!string.IsNullOrEmpty(typedDefinition.IconDescription)) iconValue.Description = typedDefinition.IconDescription; fileProperties["DisplayTemplateJSIconUrl"] = iconValue.ToString(); } }
protected override void MapProperties(object modelHost, Hashtable fileProperties, ContentPageDefinitionBase definition) { base.MapProperties(modelHost, fileProperties, definition); var typedTemplateModel = definition.WithAssertAndCast <ItemControlTemplateDefinitionBase>("model", value => value.RequireNotNull()); if (typedTemplateModel.TargetControlTypes.Count > 0) { var multiChoiceValue = new SPFieldMultiChoiceValue(); foreach (var value in typedTemplateModel.TargetControlTypes) { multiChoiceValue.Add(value); } fileProperties["TargetControlType"] = multiChoiceValue.ToString(); } if (!string.IsNullOrEmpty(typedTemplateModel.PreviewURL)) { var htmlPreviewValue = new SPFieldUrlValue { Url = typedTemplateModel.PreviewURL }; if (!string.IsNullOrEmpty(typedTemplateModel.PreviewDescription)) { htmlPreviewValue.Description = typedTemplateModel.PreviewDescription; } fileProperties["HtmlDesignPreviewUrl"] = htmlPreviewValue.ToString(); } }
/// <summary> /// Writes a field value as an SPFolder's default column value /// </summary> /// <param name="folder">The folder for which we wish to update a field's default value</param> /// <param name="fieldValueInfo">The field and value information</param> public override void WriteValueToFolderDefault(SPFolder folder, FieldValueInfo fieldValueInfo) { var defaultValue = (UrlValue)fieldValueInfo.Value; MetadataDefaults listMetadataDefaults = new MetadataDefaults(folder.ParentWeb.Lists[folder.ParentListId]); if (defaultValue != null) { var sharePointFieldUrlValue = new SPFieldUrlValue { Url = defaultValue.Url, Description = defaultValue.Description }; this.log.Warn( "WriteValueToFolderDefault - Initializing {0} field (fieldName={1}) with default value \"{2}\"." + " Be aware that folder default values on {0}-type field are not well supported by SharePoint and that this default" + " value will not be editable through your document library's \"List Settings > Column default value settings\" options page.", fieldValueInfo.FieldInfo.FieldType, fieldValueInfo.FieldInfo.InternalName, sharePointFieldUrlValue.ToString()); listMetadataDefaults.SetFieldDefault(folder, fieldValueInfo.FieldInfo.InternalName, sharePointFieldUrlValue.ToString()); } else { listMetadataDefaults.RemoveFieldDefault(folder, fieldValueInfo.FieldInfo.InternalName); } listMetadataDefaults.Update(); }
private static void CreateLinkForItem(string listUrl, string description, string linkUrl) { SPFieldUrlValue val = new SPFieldUrlValue(); val.Description = description; val.Url = linkUrl; string fieldResult = val.ToString(); Dictionary <Guid, object> values = new Dictionary <Guid, object>(); values.Add(new Guid("{c29e077d-f466-4d8e-8bbe-72b66c5f205c}"), fieldResult); // GUID is the URL field GUID it's defined by WSS CreateItemInList(listUrl, values); }
protected override void MapProperties(object modelHost, Hashtable fileProperties, ContentPageDefinitionBase definition) { base.MapProperties(modelHost, fileProperties, definition); var typedTemplateModel = definition.WithAssertAndCast<ControlDisplayTemplateDefinition>("model", value => value.RequireNotNull()); fileProperties[BuiltInInternalFieldNames.ContentTypeId] = "0x0101002039C03B61C64EC4A04F5361F385106601"; if (!string.IsNullOrEmpty(typedTemplateModel.CrawlerXSLFileURL)) { var crawlerXSLFileValue = new SPFieldUrlValue { Url = typedTemplateModel.CrawlerXSLFileURL }; if (!string.IsNullOrEmpty(typedTemplateModel.CrawlerXSLFileDescription)) crawlerXSLFileValue.Description = typedTemplateModel.CrawlerXSLFileDescription; fileProperties["CrawlerXSLFile"] = crawlerXSLFileValue.ToString(); } }
protected override void MapProperties(object modelHost, Hashtable fileProperties, ContentPageDefinitionBase definition) { base.MapProperties(modelHost, fileProperties, definition); var typedDefinition = definition.WithAssertAndCast <JavaScriptDisplayTemplateDefinition>("model", value => value.RequireNotNull()); fileProperties[BuiltInInternalFieldNames.ContentTypeId] = "0x0101002039C03B61C64EC4A04F5361F3851068"; if (!string.IsNullOrEmpty(typedDefinition.Standalone)) { fileProperties["DisplayTemplateJSTemplateType"] = typedDefinition.Standalone; } if (!string.IsNullOrEmpty(typedDefinition.TargetControlType)) { fileProperties["DisplayTemplateJSTargetControlType"] = typedDefinition.TargetControlType; } if (!string.IsNullOrEmpty(typedDefinition.TargetListTemplateId)) { fileProperties["DisplayTemplateJSTargetListTemplate"] = typedDefinition.TargetListTemplateId; } if (!string.IsNullOrEmpty(typedDefinition.TargetScope)) { fileProperties["DisplayTemplateJSTargetScope"] = typedDefinition.TargetScope; } if (!string.IsNullOrEmpty(typedDefinition.IconUrl)) { var iconValue = new SPFieldUrlValue { Url = typedDefinition.IconUrl }; if (!string.IsNullOrEmpty(typedDefinition.IconDescription)) { iconValue.Description = typedDefinition.IconDescription; } fileProperties["DisplayTemplateJSIconUrl"] = iconValue.ToString(); } }
protected override void MapProperties(object modelHost, Hashtable fileProperties, ContentPageDefinitionBase definition) { base.MapProperties(modelHost, fileProperties, definition); var typedTemplateModel = definition.WithAssertAndCast <ControlDisplayTemplateDefinition>("model", value => value.RequireNotNull()); fileProperties[BuiltInInternalFieldNames.ContentTypeId] = "0x0101002039C03B61C64EC4A04F5361F385106601"; if (!string.IsNullOrEmpty(typedTemplateModel.CrawlerXSLFileURL)) { var crawlerXSLFileValue = new SPFieldUrlValue { Url = typedTemplateModel.CrawlerXSLFileURL }; if (!string.IsNullOrEmpty(typedTemplateModel.CrawlerXSLFileDescription)) { crawlerXSLFileValue.Description = typedTemplateModel.CrawlerXSLFileDescription; } fileProperties["CrawlerXSLFile"] = crawlerXSLFileValue.ToString(); } }
protected override void MapProperties(object modelHost, Hashtable fileProperties, ContentPageDefinitionBase definition) { base.MapProperties(modelHost, fileProperties, definition); var typedDefinition = definition.WithAssertAndCast <FilterDisplayTemplateDefinition>("model", value => value.RequireNotNull()); fileProperties[BuiltInInternalFieldNames.ContentTypeId] = "0x0101002039C03B61C64EC4A04F5361F38510660400F643FF79F6BD764F8A469B6F153396EE"; if (!string.IsNullOrEmpty(typedDefinition.CrawlerXSLFileURL)) { var crawlerXSLFileValue = new SPFieldUrlValue { Url = typedDefinition.CrawlerXSLFileURL }; if (!string.IsNullOrEmpty(typedDefinition.CrawlerXSLFileDescription)) { crawlerXSLFileValue.Description = typedDefinition.CrawlerXSLFileDescription; } fileProperties["CrawlerXSLFile"] = crawlerXSLFileValue.ToString(); } if (!string.IsNullOrEmpty(typedDefinition.CompatibleManagedProperties)) { fileProperties["CompatibleManagedProperties"] = typedDefinition.CompatibleManagedProperties; } if (typedDefinition.CompatibleSearchDataTypes.Count > 0) { var multiChoiceValue = new SPFieldMultiChoiceValue(); foreach (var value in typedDefinition.CompatibleSearchDataTypes) { multiChoiceValue.Add(value); } fileProperties["CompatibleSearchDataTypes"] = multiChoiceValue.ToString(); } }
private void DeployPublishingPage(object modelHost, SPList list, SPFolder folder, PublishingPageLayoutDefinition definition) { var web = list.ParentWeb; var targetPage = GetCurrentObject(folder, definition); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = targetPage == null ? null : targetPage.File, ObjectType = typeof(SPFile), ObjectDefinition = definition, ModelHost = modelHost }); if (targetPage == null) { targetPage = CreateObject(modelHost, folder, definition); } InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = targetPage.File, ObjectType = typeof(SPFile), ObjectDefinition = definition, ModelHost = modelHost }); ModuleFileModelHandler.WithSafeFileOperation(list, folder, targetPage.Url, GetSafePageFileName(definition), Encoding.UTF8.GetBytes(definition.Content), definition.NeedOverride, null, afterFile => { var pageItem = afterFile.Properties; if (!string.IsNullOrEmpty(definition.Title)) { pageItem["vti_title"] = definition.Title; } if (!string.IsNullOrEmpty(definition.Description)) { pageItem["MasterPageDescription"] = definition.Description; } pageItem[BuiltInInternalFieldNames.ContentTypeId] = BuiltInPublishingContentTypeId.PageLayout; if (!string.IsNullOrEmpty(definition.PreviewImageUrl)) { var urlValue = TokenReplacementService.ReplaceTokens(new TokenReplacementContext { Value = definition.PreviewImageUrl, Context = web }).Value; var urlFieldValue = new SPFieldUrlValue { Url = urlValue }; if (!string.IsNullOrEmpty(definition.PreviewImageDescription)) { urlFieldValue.Description = definition.PreviewImageDescription; } pageItem["PublishingPreviewImage"] = urlFieldValue.ToString(); } if (!string.IsNullOrEmpty(definition.AssociatedContentTypeId)) { var siteContentType = web.AvailableContentTypes[new SPContentTypeId(definition.AssociatedContentTypeId)]; pageItem["PublishingAssociatedContentType"] = String.Format(";#{0};#{1};#", siteContentType.Name, siteContentType.Id.ToString()); } }); }
/// <summary> /// Fixes the pages page layout url so that it points to the page layout in the container site collections master page gallery. /// </summary> /// <param name="publishingWeb">The target publishing web.</param> /// <param name="pageName">Name of the page.</param> /// <param name="pageLayoutUrl">The page layout URL.</param> /// <param name="searchRegex">The search regex.</param> /// <param name="replaceString">The replace string.</param> /// <param name="fixContact">if set to <c>true</c> [fix contact].</param> /// <param name="test">if set to <c>true</c> [test].</param> public static void FixPages(PublishingWeb publishingWeb, string pageName, string pageLayoutUrl, Regex searchRegex, string replaceString, bool fixContact, bool test) { if (!PublishingWeb.IsPublishingWeb(publishingWeb.Web)) return; PublishingPageCollection pages; int tryCount = 0; while (true) { try { tryCount++; pages = publishingWeb.GetPublishingPages(); break; } catch (InvalidPublishingWebException) { // The following is meant to deal with a timing issue when using this method in conjuction with other commands. When // used independently this should be unnecessary. if (tryCount > 4) throw; Thread.Sleep(10000); SPWeb web = publishingWeb.Web; SPSite site = web.Site; string url = site.MakeFullUrl(web.ServerRelativeUrl); site.Close(); site.Dispose(); web.Close(); web.Dispose(); publishingWeb.Close(); site = new SPSite(url); web = site.OpenWeb(Utilities.GetServerRelUrlFromFullUrl(url)); publishingWeb = PublishingWeb.GetPublishingWeb(web); } } foreach (PublishingPage page in pages) { if (!(string.IsNullOrEmpty(pageName) || page.Name.ToLower() == pageName.ToLower())) continue; if (page.ListItem[FieldId.PageLayout] == null) continue; Logger.Write("Progress: Begin processing {0}.", page.Url); Logger.Write("Progress: Current layout set to {0}.", page.ListItem[FieldId.PageLayout].ToString()); // Can't edit items that are checked out. if (Utilities.IsCheckedOut(page.ListItem) && !Utilities.IsCheckedOutByCurrentUser(page.ListItem)) { Logger.WriteWarning("WARNING: Page is already checked out by another user - skipping."); continue; } SPFieldUrlValue url; if (string.IsNullOrEmpty(pageLayoutUrl)) { if (searchRegex == null) { if (page.ListItem[FieldId.PageLayout] == null || string.IsNullOrEmpty(page.ListItem[FieldId.PageLayout].ToString().Trim())) { Logger.WriteWarning("WARNING: Current page layout is empty - skipping. Use the 'pagelayout' parameter to set a page layout."); continue; } // We didn't get a layout url passed in or a regular expression so try and fix the existing url url = new SPFieldUrlValue(page.ListItem[FieldId.PageLayout].ToString()); if (string.IsNullOrEmpty(url.Url) || url.Url.IndexOf("/_catalogs/") < 0) { Logger.WriteWarning("WARNING: Current page layout does not point to a _catalogs folder or is empty - skipping. Use the 'pagelayout' parameter to set a page layout Layout Url: {0}", url.ToString()); continue; } string newUrl = publishingWeb.Web.Site.ServerRelativeUrl.TrimEnd('/') + url.Url.Substring(url.Url.IndexOf("/_catalogs/")); string newDesc = publishingWeb.Web.Site.MakeFullUrl(newUrl); if (url.Url.ToLowerInvariant() == newUrl.ToLowerInvariant()) { Logger.Write("Progress: Current layout matches new evaluated layout - skipping."); continue; } url.Url = newUrl; url.Description = newDesc; } else { if (page.ListItem[FieldId.PageLayout] == null || string.IsNullOrEmpty(page.ListItem[FieldId.PageLayout].ToString().Trim())) Logger.Write("Progress: Current page layout is empty - skipping. Use the pagelayout parameter to set a page layout."); // A regular expression was passed in so use it to fix the page layout url if we find a match. if (searchRegex.IsMatch((string)page.ListItem[FieldId.PageLayout])) { url = new SPFieldUrlValue(page.ListItem[FieldId.PageLayout].ToString()); string newUrl = searchRegex.Replace((string)page.ListItem[FieldId.PageLayout], replaceString); if (url.ToString().ToLowerInvariant() == newUrl.ToLowerInvariant()) { Logger.Write("Progress: Current layout matches new evaluated layout - skipping."); continue; } url = new SPFieldUrlValue(newUrl); } else { Logger.Write("Progress: Existing page layout url does not match provided regular expression - skipping."); continue; } } } else { // The user passed in an url string so use it. if (pageLayoutUrl.ToLowerInvariant() == (string)page.ListItem[FieldId.PageLayout]) { Logger.Write("Progress: Current layout matches provided layout - skipping."); continue; } url = new SPFieldUrlValue(pageLayoutUrl); } string fileName = url.Url.Substring(url.Url.LastIndexOf('/')); // Make sure that the URLs are server relative instead of absolute. //if (url.Description.ToLowerInvariant().StartsWith("http")) // url.Description = Utilities.GetServerRelUrlFromFullUrl(url.Description) + fileName; //if (url.Url.ToLowerInvariant().StartsWith("http")) // url.Url = Utilities.GetServerRelUrlFromFullUrl(url.Url) + fileName; if (page.ListItem[FieldId.PageLayout] != null && url.ToString().ToLowerInvariant() == page.ListItem[FieldId.PageLayout].ToString().ToLowerInvariant()) continue; // No difference detected so move on. Logger.Write("Progress: Changing layout url from \"{0}\" to \"{1}\"", page.ListItem[FieldId.PageLayout].ToString(), url.ToString()); if (fixContact) { SPUser contact = null; try { contact = page.Contact; } catch (SPException) { } if (contact == null) { Logger.Write("Progress: Page contact ('{0}') does not exist - assigning current user as contact.", page.ListItem[FieldId.Contact].ToString()); page.Contact = publishingWeb.Web.CurrentUser; if (!test) page.ListItem.SystemUpdate(); } } if (test) continue; try { bool publish = false; if (!Utilities.IsCheckedOut(page.ListItem)) { page.CheckOut(); publish = true; } page.ListItem[FieldId.PageLayout] = url; page.ListItem.UpdateOverwriteVersion(); if (publish) { Common.Lists.PublishItems itemPublisher = new Common.Lists.PublishItems(); itemPublisher.PublishListItem(page.ListItem, page.ListItem.ParentList, false, "Automated fix of publishing pages page layout URL.", null, null); } } catch (Exception ex) { Logger.WriteException(new ErrorRecord(ex, null, ErrorCategory.NotSpecified, page)); } } }
/// <summary> /// Gets a friendly string representation of the URL including the friendly name. /// </summary> /// <returns></returns> public override string ToString() { return(_urlValue.ToString()); }
private void ProcessFile(SPListItem item) { DataTable dtErrors = new DataTable(); string uploadedFileName = item.File.Name; string logFileName = "Error_Log_" + item.ID.ToString() + "_" + uploadedFileName; if (uploadedFileName.ToLower().EndsWith("csv")) { try { using (CsvReader csvReader = new CsvReader(item.File.OpenBinaryStream())) { try { item["Status"] = "In Progress"; item.Update(); csvReader.ReadHeaderRecord(); DataSet dsBulkUpload = new DataSet(); int ret = DataExtensions.Fill(dsBulkUpload, csvReader, "BulkUpload"); if (ret > 0) { dtErrors = this.ProcessData(dsBulkUpload, (UploadTypes)Enum.Parse(typeof(UploadTypes), item["LoadType"].ToString(), true)); } string fileContent = string.Empty; string columnContent = string.Empty; for (int i = 0; i < dtErrors.Columns.Count; i++) { fileContent += (fileContent != string.Empty ? "," : string.Empty) + dtErrors.Columns[i].ColumnName; } for (int row = 0; row < dtErrors.Rows.Count; row++) { for (int column = 0; column < dtErrors.Columns.Count; column++) { columnContent += (columnContent != string.Empty ? "," : string.Empty) + dtErrors.Rows[row][column].ToString(); } fileContent += "\n" + columnContent; columnContent = string.Empty; } SPFile file = fldErrorLogs.Files.Add(logFileName, ASCIIEncoding.ASCII.GetBytes ( fileContent)); file.Update(); SPFieldUrlValue urlValue = new SPFieldUrlValue(); urlValue.Description = logFileName; urlValue.Url = file.ServerRelativeUrl ; item["Status"] = "Completed"; item["Url"] = urlValue.ToString(); item.Update(); } catch (Exception ex) { } } } catch (Exception ex) { } } else { } }
public void GetandUpdateItemById(int itemId, string sourceList, string historyList) { string siteUrl = SPContext.Current.Site.Url; SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite spSite = new SPSite(siteUrl)) //找到网站集 { using (SPWeb spWeb = spSite.OpenWeb()) { if (historyList != "") { SPList spList = spWeb.Lists.TryGetList(historyList); if (spList != null) { spList.AllowEveryoneViewItems = true; string sourceUrl = siteUrl + spList.DefaultViewUrl; string[] slistData = getSourceList(sourceList, itemId, sourceUrl); SPQuery qry = new SPQuery(); qry.Query = @" <Where><And><Eq><FieldRef Name='ItemID' /><Value Type='Text'>" + itemId + "</Value></Eq><Eq><FieldRef Name='ListGuid' /><Value Type='Text'>" + slistData[0] + "</Value></Eq></And></Where>"; SPListItemCollection listItems = spList.GetItems(qry); if (listItems.Count > 0) { SPListItem item = listItems[0]; //获取访问次数,并显示 string hitCount = item["访问次数"] != null ? item["访问次数"].ToString() : "0"; viewspan.InnerText = "总访问次数:" + (int.Parse(hitCount) + 1).ToString(); string visittime = item["最后访问时间"] != null ? item["最后访问时间"].ToString() : DateTime.Now.ToString(); viewtimespan.InnerText = "最后访问时间:" + visittime; //更新访问次数历史 spWeb.AllowUnsafeUpdates = true; item["访问次数"] = int.Parse(hitCount) + 1; item["最后访问者"] = GetCurrentAccount(); item["最后访问者IP"] = GetClientIPAddr(); item["最后访问时间"] = DateTime.Now; item.Update(); } else { viewspan.InnerText = "总访问次数:1"; viewtimespan.InnerText = "最后访问时间:" + DateTime.Now.ToString(); spWeb.AllowUnsafeUpdates = true; SPListItem item = spList.AddItem(); item["标题"] = slistData[2]; item["项目ID"] = itemId; item["列表Guid"] = slistData[0]; item["列表名称"] = slistData[1]; item["访问次数"] = 1; item["最后访问者"] = GetCurrentAccount(); item["最后访问者IP"] = GetClientIPAddr(); item["最后访问时间"] = DateTime.Now; var urlField = spList.Fields["项目Url"] as SPFieldUrl; SPFieldUrlValue urlFieldValue = new SPFieldUrlValue() { Description = slistData[2], Url = slistData[3] }; urlField.ValidateParseAndSetValue(item, urlFieldValue.ToString()); item.Update(); } } } } } }); }
private void DeployPublishingPage(object modelHost, SPList list, SPFolder folder, PublishingPageLayoutDefinition definition) { var web = list.ParentWeb; var targetPage = GetCurrentObject(folder, definition); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = targetPage == null ? null : targetPage.File, ObjectType = typeof(SPFile), ObjectDefinition = definition, ModelHost = modelHost }); if (targetPage == null) targetPage = CreateObject(modelHost, folder, definition); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = targetPage.File, ObjectType = typeof(SPFile), ObjectDefinition = definition, ModelHost = modelHost }); ModuleFileModelHandler.WithSafeFileOperation(list, folder, targetPage.Url, GetSafePageFileName(definition), Encoding.UTF8.GetBytes(definition.Content), definition.NeedOverride, null, afterFile => { //var pageItem = afterFile.Properties; var pageItem = afterFile.ListItemAllFields; FieldLookupService.EnsureDefaultValues(pageItem, definition.DefaultValues); if (!string.IsNullOrEmpty(definition.Title)) { //pageItem["vti_title"] = definition.Title; pageItem["Title"] = definition.Title; } // ootb ? pageItem[BuiltInInternalFieldNames.ContentTypeId] = BuiltInPublishingContentTypeId.PageLayout; // custom? if (!string.IsNullOrEmpty(definition.ContentTypeId) || !string.IsNullOrEmpty(definition.ContentTypeName)) { if (!string.IsNullOrEmpty(definition.ContentTypeId)) pageItem["ContentTypeId"] = ContentTypeLookupService.LookupListContentTypeById(list, definition.ContentTypeId); if (!string.IsNullOrEmpty(definition.ContentTypeName)) pageItem["ContentTypeId"] = ContentTypeLookupService.LookupContentTypeByName(list, definition.ContentTypeName); } if (!string.IsNullOrEmpty(definition.Description)) { // did not work pageItem["MasterPageDescription"] = definition.Description; //pageItem.Properties["MasterPageDescription"] = definition.Description; } if (!string.IsNullOrEmpty(definition.PreviewImageUrl)) { var urlValue = TokenReplacementService.ReplaceTokens(new TokenReplacementContext { Value = definition.PreviewImageUrl, Context = web }).Value; var urlFieldValue = new SPFieldUrlValue { Url = urlValue }; if (!string.IsNullOrEmpty(definition.PreviewImageDescription)) urlFieldValue.Description = definition.PreviewImageDescription; pageItem["PublishingPreviewImage"] = urlFieldValue.ToString(); } if (!string.IsNullOrEmpty(definition.AssociatedContentTypeId)) { var siteContentType = web.AvailableContentTypes[new SPContentTypeId(definition.AssociatedContentTypeId)]; pageItem["PublishingAssociatedContentType"] = String.Format(";#{0};#{1};#", siteContentType.Name, siteContentType.Id.ToString()); } FieldLookupService.EnsureValues(pageItem, definition.Values, true); pageItem.Update(); }); }
public override string ToString() { return(m_fieldUrlValue.ToString()); }
public override void SetUrlFieldValue(string fieldName, SPFieldUrlValue value) { this[fieldName] = value.ToString(); }
/// <summary> /// Fixes the pages page layout url so that it points to the page layout in the container site collections master page gallery. /// </summary> /// <param name="publishingWeb">The target publishing web.</param> /// <param name="pageName">Name of the page.</param> /// <param name="pageLayoutUrl">The page layout URL.</param> /// <param name="searchRegex">The search regex.</param> /// <param name="replaceString">The replace string.</param> /// <param name="fixContact">if set to <c>true</c> [fix contact].</param> /// <param name="test">if set to <c>true</c> [test].</param> public static void FixPages(PublishingWeb publishingWeb, string pageName, string pageLayoutUrl, Regex searchRegex, string replaceString, bool fixContact, bool test) { if (!PublishingWeb.IsPublishingWeb(publishingWeb.Web)) { return; } PublishingPageCollection pages; int tryCount = 0; while (true) { try { tryCount++; pages = publishingWeb.GetPublishingPages(); break; } catch (InvalidPublishingWebException) { // The following is meant to deal with a timing issue when using this method in conjuction with other commands. When // used independently this should be unnecessary. if (tryCount > 4) { throw; } Thread.Sleep(10000); SPWeb web = publishingWeb.Web; SPSite site = web.Site; string url = site.MakeFullUrl(web.ServerRelativeUrl); site.Close(); site.Dispose(); web.Close(); web.Dispose(); publishingWeb.Close(); site = new SPSite(url); web = site.OpenWeb(Utilities.GetServerRelUrlFromFullUrl(url)); publishingWeb = PublishingWeb.GetPublishingWeb(web); } } foreach (PublishingPage page in pages) { if (!(string.IsNullOrEmpty(pageName) || page.Name.ToLower() == pageName.ToLower())) { continue; } if (page.ListItem[FieldId.PageLayout] == null) { continue; } Logger.Write("Progress: Begin processing {0}.", page.Url); Logger.Write("Progress: Current layout set to {0}.", page.ListItem[FieldId.PageLayout].ToString()); // Can't edit items that are checked out. if (Utilities.IsCheckedOut(page.ListItem) && !Utilities.IsCheckedOutByCurrentUser(page.ListItem)) { Logger.WriteWarning("WARNING: Page is already checked out by another user - skipping."); continue; } SPFieldUrlValue url; if (string.IsNullOrEmpty(pageLayoutUrl)) { if (searchRegex == null) { if (page.ListItem[FieldId.PageLayout] == null || string.IsNullOrEmpty(page.ListItem[FieldId.PageLayout].ToString().Trim())) { Logger.WriteWarning("WARNING: Current page layout is empty - skipping. Use the 'pagelayout' parameter to set a page layout."); continue; } // We didn't get a layout url passed in or a regular expression so try and fix the existing url url = new SPFieldUrlValue(page.ListItem[FieldId.PageLayout].ToString()); if (string.IsNullOrEmpty(url.Url) || url.Url.IndexOf("/_catalogs/") < 0) { Logger.WriteWarning("WARNING: Current page layout does not point to a _catalogs folder or is empty - skipping. Use the 'pagelayout' parameter to set a page layout Layout Url: {0}", url.ToString()); continue; } string newUrl = publishingWeb.Web.Site.ServerRelativeUrl.TrimEnd('/') + url.Url.Substring(url.Url.IndexOf("/_catalogs/")); string newDesc = publishingWeb.Web.Site.MakeFullUrl(newUrl); if (url.Url.ToLowerInvariant() == newUrl.ToLowerInvariant()) { Logger.Write("Progress: Current layout matches new evaluated layout - skipping."); continue; } url.Url = newUrl; url.Description = newDesc; } else { if (page.ListItem[FieldId.PageLayout] == null || string.IsNullOrEmpty(page.ListItem[FieldId.PageLayout].ToString().Trim())) { Logger.Write("Progress: Current page layout is empty - skipping. Use the pagelayout parameter to set a page layout."); } // A regular expression was passed in so use it to fix the page layout url if we find a match. if (searchRegex.IsMatch((string)page.ListItem[FieldId.PageLayout])) { url = new SPFieldUrlValue(page.ListItem[FieldId.PageLayout].ToString()); string newUrl = searchRegex.Replace((string)page.ListItem[FieldId.PageLayout], replaceString); if (url.ToString().ToLowerInvariant() == newUrl.ToLowerInvariant()) { Logger.Write("Progress: Current layout matches new evaluated layout - skipping."); continue; } url = new SPFieldUrlValue(newUrl); } else { Logger.Write("Progress: Existing page layout url does not match provided regular expression - skipping."); continue; } } } else { // The user passed in an url string so use it. if (pageLayoutUrl.ToLowerInvariant() == (string)page.ListItem[FieldId.PageLayout]) { Logger.Write("Progress: Current layout matches provided layout - skipping."); continue; } url = new SPFieldUrlValue(pageLayoutUrl); } string fileName = url.Url.Substring(url.Url.LastIndexOf('/')); // Make sure that the URLs are server relative instead of absolute. //if (url.Description.ToLowerInvariant().StartsWith("http")) // url.Description = Utilities.GetServerRelUrlFromFullUrl(url.Description) + fileName; //if (url.Url.ToLowerInvariant().StartsWith("http")) // url.Url = Utilities.GetServerRelUrlFromFullUrl(url.Url) + fileName; if (page.ListItem[FieldId.PageLayout] != null && url.ToString().ToLowerInvariant() == page.ListItem[FieldId.PageLayout].ToString().ToLowerInvariant()) { continue; // No difference detected so move on. } Logger.Write("Progress: Changing layout url from \"{0}\" to \"{1}\"", page.ListItem[FieldId.PageLayout].ToString(), url.ToString()); if (fixContact) { SPUser contact = null; try { contact = page.Contact; } catch (SPException) { } if (contact == null) { Logger.Write("Progress: Page contact ('{0}') does not exist - assigning current user as contact.", page.ListItem[FieldId.Contact].ToString()); page.Contact = publishingWeb.Web.CurrentUser; if (!test) { page.ListItem.SystemUpdate(); } } } if (test) { continue; } try { bool publish = false; if (!Utilities.IsCheckedOut(page.ListItem)) { page.CheckOut(); publish = true; } page.ListItem[FieldId.PageLayout] = url; page.ListItem.UpdateOverwriteVersion(); if (publish) { Common.Lists.PublishItems itemPublisher = new Common.Lists.PublishItems(); itemPublisher.PublishListItem(page.ListItem, page.ListItem.ParentList, false, "Automated fix of publishing pages page layout URL.", null, null); } } catch (Exception ex) { Logger.WriteException(new ErrorRecord(ex, null, ErrorCategory.NotSpecified, page)); } } }