private SPContentType EnsureContentTypeExists(ref SPWeb web) { SPContentType cType = null; try { cType = web.ContentTypes[ContentTypeId]; } catch { /* expected: not found */ } if (cType == null) { int ctCounter = 0; string ctId = ContentTypeId.ToString(); string ctName = Name; while (web.AvailableContentTypes[new SPContentTypeId(ctId)] != null && ctCounter < 100) { ctCounter++; ctId = ContentTypeId.ToString() + ctCounter.ToString("00"); ctName = string.Concat(Name, ParentSchema.ContentTypeNameSchemaSeparator, ctCounter); } SPContentType.ValidateName(ctName); cType = new SPContentType(new SPContentTypeId(ctId), web.ContentTypes, ctName); cType.Group = ParentSchema.GroupName; cType.ReadOnly = false; web.ContentTypes.Add(cType); //myContentType.Update(); } return(cType); }
//public static DefinitionBase OnCreating(this DefinitionBase model, Action<ListDefinition, SPList> action) //{ // model.RegisterModelUpdatingEvent(action); // return model; //} //public static DefinitionBase OnCreated(this DefinitionBase model, Action<ListDefinition, SPList> action) //{ // model.RegisterModelUpdatedEvent(action); // return model; //} #endregion #region add content type public static ModelNode AddContentTypeLink(this ModelNode model, ContentTypeId contentTypeId) { return(ContentTypeLinkDefinitionSyntax.AddContentTypeLink(model, new ContentTypeLinkDefinition { ContentTypeId = contentTypeId.ToString() })); }
public static void Add(this DocumentSetTemplate documentSet, ListItem documentItem, string documentSetName, string folder, ContentTypeId docId, bool majorVersionOnly) { Trace.TraceInformation($"Adding: {documentItem.File.Name} to {documentSetName}, Document Folder: {folder}"); var ctx = documentSet.Context; Uri webUrl = new Uri(ctx.Url); DocumentStream ds = new DocumentStream((ClientContext)ctx, documentItem); MemoryStream documentStream; if (majorVersionOnly) documentStream = ds.MajorVersion; else documentStream = ds.LatestVersion; //Use a place holder to workaround filesize limitation with the DefaultDocuments API. //Place holder is inserted via the API, and then overwritten later. if (documentStream != null) { string placeholderPage = "Placeholder"; MemoryStream repo = new MemoryStream(Encoding.UTF8.GetBytes(placeholderPage)); documentSet.DefaultDocuments.Add(folder + ds.FileName, docId, repo.ToArray()); documentSet.Update(true); ctx.ExecuteQuery(); repo.Close(); Trace.TraceInformation("- Placeholder created"); UploadFile((ClientContext)ctx, webUrl.AbsolutePath + "/_cts/" + documentSetName, documentStream, documentItem.File.Name); } }
public static ModelNode AddContentTypeLink(this ModelNode model, ContentTypeId contentTypeId) { return ContentTypeLinkDefinitionSyntax.AddContentTypeLink(model, new ContentTypeLinkDefinition { ContentTypeId = contentTypeId.ToString() }); }
public ImportedContentType ResolveContentType(ContentTypeId id) { if (this.ContentTypesById.ContainsKey(id.StringValue)) { return(this.ContentTypesById[id.StringValue]); } return(null); }
public ImportedContentType(ContentTypeImporter importer, ContentType type, ContentTypeId parentId) { this.Importer = importer; this.Id = type.Id; this.Name = type.Name; this.Type = type; this.Fields = new Dictionary <string, ImportedContentTypeField>(); if (parentId.StringValue == this.Id.StringValue) { parentId = null; } this.ParentId = parentId; }
/// <summary> /// Gets and sets default content type of the list. /// </summary> /// <param name="requestObject">RequestObject object</param> /// <param name="clientContext">ClientContext object</param> /// <param name="url">SourceURL of the OneDrive document</param> /// <param name="contentTypeId">Content Type Id</param> /// <param name="operationType">Operation type specifies either get or set Content type operation</param> /// <param name="documentLibraryName">Name of the document library</param> /// <returns>Returns Content Type Id</returns> internal static string GetContentTypeList(RequestObject requestObject, ClientContext clientContext, string url, string contentTypeId, int operationType, string documentLibraryName) { try { using (clientContext = ServiceUtility.GetClientContext(requestObject.SPAppToken, new Uri(url.Split(Convert.ToChar(ConstantStrings.DOLLAR, CultureInfo.InvariantCulture))[0]), requestObject.RefreshToken)) { List docLib = clientContext.Web.Lists.GetByTitle(documentLibraryName); clientContext.Load(docLib); clientContext.ExecuteQuery(); Microsoft.SharePoint.Client.Folder folder = docLib.RootFolder; IList <ContentTypeId> list = new List <ContentTypeId>(); clientContext.Load(folder, item => item.ContentTypeOrder, item => item.UniqueContentTypeOrder); clientContext.ExecuteQuery(); list = folder.ContentTypeOrder; ServiceConstantStrings.OperationTypes type = (ServiceConstantStrings.OperationTypes)operationType; switch (type) { case ServiceConstantStrings.OperationTypes.Update: contentTypeId = list[0].StringValue; break; case ServiceConstantStrings.OperationTypes.Checkout: int iterator = 0, index = 0; for (iterator = 0; iterator < list.Count; iterator++) { if (list[iterator].StringValue == contentTypeId) { index = iterator; break; } } ContentTypeId currentContentTypeID = list[index]; list.RemoveAt(index); list.Insert(0, currentContentTypeID); folder.UniqueContentTypeOrder = list; folder.Update(); clientContext.ExecuteQuery(); break; } } } catch (Exception exception) { Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName); } return(contentTypeId); }
/// <summary> /// Sets the default content type based on user selection for the new matter that is getting created /// </summary> /// <param name="clientContext">SP client context</param> /// <param name="list">Name of the list</param> /// <param name="requestObject">Request Object</param> /// <param name="client">Client Object</param> /// <param name="matter">Matter Object</param> private void SetDefaultContentType(ClientContext clientContext, List list, Client client, Matter matter) { int contentCount = 0, contentSwap = 0; try { ContentTypeCollection currentContentTypeOrder = list.ContentTypes; clientContext.Load(currentContentTypeOrder); clientContext.ExecuteQuery(); IList <ContentTypeId> updatedContentTypeOrder = new List <ContentTypeId>(); foreach (ContentType contentType in currentContentTypeOrder) { if (0 == string.Compare(contentType.Name, matter.DefaultContentType, StringComparison.OrdinalIgnoreCase)) { contentSwap = contentCount; } if (0 != string.Compare(contentType.Name, contentTypesConfig.HiddenContentType, StringComparison.OrdinalIgnoreCase)) { updatedContentTypeOrder.Add(contentType.Id); contentCount++; } } if (updatedContentTypeOrder.Count > contentSwap) { ContentTypeId documentContentType = updatedContentTypeOrder[0]; updatedContentTypeOrder[0] = updatedContentTypeOrder[contentSwap]; updatedContentTypeOrder.RemoveAt(contentSwap); updatedContentTypeOrder.Add(documentContentType); } list.RootFolder.UniqueContentTypeOrder = updatedContentTypeOrder; list.RootFolder.Update(); list.Update(); clientContext.ExecuteQuery(); } catch (Exception exception) { customLogger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, logTables.SPOLogTable); throw; } }
public static File UploadFile(this Folder folder, string filePath, ContentTypeId contentTypeId, bool overwriteIfExists = true, bool useWebDav = true) { if (filePath == null) { throw new ArgumentNullException("filePath"); } if (string.IsNullOrWhiteSpace(filePath)) { throw new ArgumentException("File path is required.", "filePath"); } var fileName = System.IO.Path.GetFileName(filePath); using (var fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open)) { var additionalProperties = new Dictionary <string, string>(); if (contentTypeId != null) { additionalProperties["ContentTypeId"] = contentTypeId.StringValue; } return(UploadFile(folder, fileName, fs, additionalProperties: additionalProperties, replaceContent: overwriteIfExists, checkHashBeforeUpload: true, level: FileLevel.Published, useWebDav: useWebDav)); } }
/// <summary> /// Sets default content type for user's OneDrive. /// </summary> /// <param name="clientContext">SP client context</param> /// <param name="list">Name of the list</param> /// <param name="defaultContentType">Default content type to be set</param> /// <returns>Content type Id of default content type</returns> internal static string SetOneDriveDefaultContentType(ClientContext clientContext, List list, string defaultContentType) { string defaultContentTypeId = string.Empty; try { ContentTypeCollection currentContentTypeOrder = list.ContentTypes; clientContext.Load(currentContentTypeOrder); clientContext.ExecuteQuery(); IList <ContentTypeId> updatedContentTypeOrder = new List <ContentTypeId>(); int count = 0, swap = 0; foreach (ContentType contentType in currentContentTypeOrder) { if (contentType.Name.Equals(defaultContentType)) { defaultContentTypeId = contentType.StringId; swap = count; } if (!contentType.Name.Equals(ConstantStrings.OneDriveFolderContentType)) { updatedContentTypeOrder.Add(contentType.Id); count++; } } ContentTypeId documentContentType = updatedContentTypeOrder[0]; updatedContentTypeOrder[0] = updatedContentTypeOrder[swap]; updatedContentTypeOrder[swap] = documentContentType; list.RootFolder.UniqueContentTypeOrder = updatedContentTypeOrder; list.RootFolder.Update(); list.Update(); clientContext.ExecuteQuery(); } catch (Exception exception) { defaultContentTypeId = ConstantStrings.FALSE; Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName); } return(defaultContentTypeId); }
/// <summary> /// Sets the default content type /// </summary> /// <param name="clientContext">Client context</param> /// <param name="list">List object</param> /// <param name="defaultContentType">Default content type</param> internal static void SetDefaultContentType(ClientContext clientContext, List list, string defaultContentType) { ContentTypeCollection currentContentTypeOrder = list.ContentTypes; clientContext.Load(currentContentTypeOrder); clientContext.ExecuteQuery(); IList <ContentTypeId> updatedContentTypeOrder = new List <ContentTypeId>(); int contentCount = 0, contentSwap = 0; foreach (ContentType contentType in currentContentTypeOrder) { if (contentType.Name.Equals(defaultContentType)) { contentSwap = contentCount; } if (!contentType.Name.Equals("Folder")) { updatedContentTypeOrder.Add(contentType.Id); contentCount++; } } if (updatedContentTypeOrder.Count > contentSwap) { ContentTypeId documentContentType = updatedContentTypeOrder[0]; updatedContentTypeOrder[0] = updatedContentTypeOrder[contentSwap]; updatedContentTypeOrder.RemoveAt(contentSwap); updatedContentTypeOrder.Add(documentContentType); } list.RootFolder.UniqueContentTypeOrder = updatedContentTypeOrder; list.RootFolder.Update(); list.Update(); clientContext.ExecuteQuery(); }
/// <summary> /// Creates a new document set as a child of an existing folder, with the specified content type ID. /// </summary> /// <param name="folder"></param> /// <param name="documentSetName"></param> /// <param name="contentTypeId">Content type of the document set</param> /// <returns>The created Folder representing the document set, so that additional operations (such as setting properties) can be done.</returns> /// <remarks> /// <example> /// var setContentType = list.BestMatchContentTypeId(BuiltInContentTypeId.DocumentSet); /// var set1 = list.RootFolder.CreateDocumentSet("Set 1", setContentType); /// </example> /// </remarks> public static Folder CreateDocumentSet(this Folder folder, string documentSetName, ContentTypeId contentTypeId) { if (folder == null) { throw new ArgumentNullException("folder"); } if (documentSetName == null) { throw new ArgumentNullException("documentSetName"); } if (contentTypeId == null) { throw new ArgumentNullException("contentTypeId"); } // TODO: Check for any other illegal characters in SharePoint if (documentSetName.Contains('/') || documentSetName.Contains('\\')) { throw new ArgumentException("The argument must be a single document set name and cannot contain path characters.", "documentSetName"); } LoggingUtility.Internal.TraceInformation(1, CoreResources.FieldAndContentTypeExtensions_CreateDocumentSet, documentSetName); var result = DocumentSet.DocumentSet.Create(folder.Context, folder, documentSetName, contentTypeId); folder.Context.ExecuteQuery(); var fullUri = new Uri(result.Value); var serverRelativeUrl = fullUri.AbsolutePath; var documentSetFolder = folder.Folders.GetByUrl(serverRelativeUrl); return documentSetFolder; }
/// <summary> /// Uploads a file to the specified folder, with an optional content type. /// </summary> /// <param name="folder">Folder to upload file to.</param> /// <param name="fileName">Name of the file to upload</param> /// <param name="stream">Stream containing the contents of the file</param> /// <param name="contentTypeId">Content type; if null (default) the default content type will be used.</param> /// <param name="overwriteIfExists">true (default) to overwite existing files</param> /// <param name="useWebDav">true (default) to save the binary directly (via webdav); false to use file creation</param> /// <returns>The uploaded File, so that additional operations (such as setting properties) can be done.</returns> public static File UploadFile(this Folder folder, string fileName, Stream stream, ContentTypeId contentTypeId, bool overwriteIfExists = true, bool useWebDav = true) { var additionalProperties = new Dictionary<string, string>(); if (contentTypeId != null) { additionalProperties["ContentTypeId"] = contentTypeId.StringValue; } return UploadFile(folder, fileName, stream, additionalProperties: additionalProperties, replaceContent: overwriteIfExists, checkHashBeforeUpload: true, level: FileLevel.Published, useWebDav: useWebDav); }
/// <summary> /// Uploads a file to the specified folder, with an optional content type. /// </summary> /// <param name="folder">Folder to upload file to.</param> /// <param name="filePath">Location of the file to be uploaded.</param> /// <param name="contentTypeId">Content type; if null (default) the default content type will be used.</param> /// <param name="overwriteIfExists">true (default) to overwite existing files</param> /// <param name="useWebDav">true (default) to save the binary directly (via webdav); false to use file creation</param> /// <returns>The uploaded File, so that additional operations (such as setting properties) can be done.</returns> public static File UploadFile(this Folder folder, string filePath, ContentTypeId contentTypeId, bool overwriteIfExists = true, bool useWebDav = true) { if (filePath == null) { throw new ArgumentNullException("filePath"); } if (string.IsNullOrWhiteSpace(filePath)) { throw new ArgumentException("File path is required.", "filePath"); } var fileName = System.IO.Path.GetFileName(filePath); using (var fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open)) { var additionalProperties = new Dictionary<string, string>(); if (contentTypeId != null) { additionalProperties["ContentTypeId"] = contentTypeId.StringValue; } return UploadFile(folder, fileName, fs, additionalProperties: additionalProperties, replaceContent: overwriteIfExists, checkHashBeforeUpload: true, level: FileLevel.Published, useWebDav: useWebDav); } }
public SPOContentTypePipeBind(ContentTypeId contentTypeId) { _contentTypeId = contentTypeId.StringValue; }
/// <summary> /// Creates a token for the specified list title and list content type id /// </summary> /// <param name="listTitle">Title for the list</param> /// <param name="id">Content type id of the list content type</param> /// <returns>List content type token. Example: "{listContentTypeId:My List,0x0101}"</returns> public static string CreateToken(string listTitle, ContentTypeId id) { return($"{{{tokenPrefix}:{Regex.Escape(listTitle)},{Regex.Escape(id.GetParentIdValue())}}}"); }
public ContentTypePipeBind(ContentTypeId contentTypeId) { _idOrName = contentTypeId?.StringValue ?? throw new ArgumentNullException(nameof(contentTypeId)); }
protected ContentType ResolveContentType(ContentTypeId id) { return(this.ContentTypeImporter.ResolveContentType(id)?.Type); }
/// <summary> /// Uploads a file to the specified folder, with an optional content type. /// </summary> /// <param name="folder">Folder to upload file to.</param> /// <param name="filePath">Location of the file to be uploaded.</param> /// <param name="contentTypeId">Optional content type; if null (default) the default content type will be used.</param> /// <param name="overwriteIfExists">true (default) to overwite existing files</param> /// <param name="useWebDav">true (default) to save the binary directly (via webdav); false to use file creation</param> /// <returns>The uploaded File, so that additional operations (such as setting properties) can be done.</returns> public static File UploadFile(this Folder folder, string filePath, ContentTypeId contentTypeId = null, bool overwriteIfExists = true, bool useWebDav = true) { if (filePath == null) { throw new ArgumentNullException("filePath"); } if (string.IsNullOrWhiteSpace(filePath)) { throw new ArgumentException("File path is required.", "filePath"); } var fileName = System.IO.Path.GetFileName(filePath); LoggingUtility.Internal.TraceInformation((int)EventId.UploadFile, CoreResources.FileFolderExtensions_UploadFile, fileName, filePath); File file = null; if (useWebDav) { if (!folder.IsObjectPropertyInstantiated("ServerRelativeUrl")) { folder.Context.Load(folder, f => f.ServerRelativeUrl); folder.Context.ExecuteQuery(); } var serverRelativeUrl = UrlUtility.Combine(folder.ServerRelativeUrl, fileName); using (var uploadContext = new ClientContext(folder.Context.Url) { Credentials = folder.Context.Credentials }) { using (var fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open)) { LoggingUtility.Internal.TraceVerbose("Save binary direct (via webdav) to '{0}'", serverRelativeUrl); File.SaveBinaryDirect(uploadContext, serverRelativeUrl, fs, overwriteIfExists); folder.Context.ExecuteQuery(); } } file = folder.Files.GetByUrl(serverRelativeUrl); } else { using (var fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open)) { FileCreationInformation fileCreation = new FileCreationInformation(); fileCreation.ContentStream = fs; fileCreation.Url = fileName; fileCreation.Overwrite = overwriteIfExists; LoggingUtility.Internal.TraceVerbose("Creating file info with Url '{0}'", fileCreation.Url); file = folder.Files.Add(fileCreation); folder.Context.ExecuteQuery(); } } if (contentTypeId != null) { LoggingUtility.Internal.TraceVerbose("Setting content type to '{0}'", contentTypeId.StringValue); file.ListItemAllFields["ContentTypeId"] = contentTypeId.StringValue; file.ListItemAllFields.Update(); } return file; }
public static File UploadFile(this Folder folder, string fileName, Stream stream, ContentTypeId contentTypeId, bool overwriteIfExists = true, bool useWebDav = true) { var additionalProperties = new Dictionary <string, string>(); if (contentTypeId != null) { additionalProperties["ContentTypeId"] = contentTypeId.StringValue; } return(UploadFile(folder, fileName, stream, additionalProperties: additionalProperties, replaceContent: overwriteIfExists, checkHashBeforeUpload: true, level: FileLevel.Published, useWebDav: useWebDav)); }
public SPOContentTypePipeBind(ContentTypeId contentTypeId) { _contentTypeId = contentTypeId.StringValue; }
public ListContentTypeIdToken(Web web, string listTitle, string contentTypeName, ContentTypeId contentTypeId) : base(web, $"{{listcontenttypeid:{Regex.Escape(listTitle)},{Regex.Escape(contentTypeName)}}}") { _contentTypeId = contentTypeId.StringValue; }
/// <summary> /// Uploads a file to the specified folder, with an optional content type. /// </summary> /// <param name="folder">Folder to upload file to.</param> /// <param name="filePath">Location of the file to be uploaded.</param> /// <param name="contentTypeId">Optional content type; if null (default) the default content type will be used.</param> /// <param name="overwriteIfExists">true (default) to overwite existing files</param> /// <param name="useWebDav">true (default) to save the binary directly (via webdav); false to use file creation</param> /// <returns>The uploaded File, so that additional operations (such as setting properties) can be done.</returns> public static File UploadFile(this Folder folder, string filePath, ContentTypeId contentTypeId = null, bool overwriteIfExists = true, bool useWebDav = true) { if (filePath == null) { throw new ArgumentNullException("filePath"); } if (string.IsNullOrWhiteSpace(filePath)) { throw new ArgumentException("File path is required.", "filePath"); } var fileName = System.IO.Path.GetFileName(filePath); LoggingUtility.Internal.TraceInformation((int)EventId.UploadFile, CoreResources.FileFolderExtensions_UploadFile, fileName, filePath); File file = null; if (useWebDav) { if (!folder.IsObjectPropertyInstantiated("ServerRelativeUrl")) { folder.Context.Load(folder, f => f.ServerRelativeUrl); folder.Context.ExecuteQuery(); } var serverRelativeUrl = UrlUtility.Combine(folder.ServerRelativeUrl, fileName); using (var uploadContext = new ClientContext(folder.Context.Url) { Credentials = folder.Context.Credentials }) { using (var fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open)) { LoggingUtility.Internal.TraceVerbose("Save binary direct (via webdav) to '{0}'", serverRelativeUrl); File.SaveBinaryDirect(uploadContext, serverRelativeUrl, fs, overwriteIfExists); folder.Context.ExecuteQuery(); } } file = folder.Files.GetByUrl(serverRelativeUrl); } else { using (var fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open)) { FileCreationInformation fileCreation = new FileCreationInformation(); fileCreation.ContentStream = fs; fileCreation.Url = fileName; fileCreation.Overwrite = overwriteIfExists; LoggingUtility.Internal.TraceVerbose("Creating file info with Url '{0}'", fileCreation.Url); file = folder.Files.Add(fileCreation); folder.Context.ExecuteQuery(); } } if (contentTypeId != null) { LoggingUtility.Internal.TraceVerbose("Setting content type to '{0}'", contentTypeId.StringValue); file.ListItemAllFields["ContentTypeId"] = contentTypeId.StringValue; file.ListItemAllFields.Update(); } return(file); }
/// <summary> /// Creates a new document set as a child of an existing folder, with the specified content type ID. /// </summary> /// <param name="folder"></param> /// <param name="documentSetName"></param> /// <param name="contentTypeId">Content type of the document set</param> /// <returns>The created Folder representing the document set, so that additional operations (such as setting properties) can be done.</returns> /// <remarks> /// <example> /// var setContentType = list.BestMatchContentTypeId(BuiltInContentTypeId.DocumentSet); /// var set1 = list.RootFolder.CreateDocumentSet("Set 1", setContentType); /// </example> /// </remarks> public static Folder CreateDocumentSet(this Folder folder, string documentSetName, ContentTypeId contentTypeId) { if (folder == null) { throw new ArgumentNullException("folder"); } if (documentSetName == null) { throw new ArgumentNullException("documentSetName"); } if (contentTypeId == null) { throw new ArgumentNullException("contentTypeId"); } if (documentSetName.ContainsInvalidUrlChars()) { throw new ArgumentException(CoreResources.FileFolderExtensions_CreateDocumentSet_The_argument_must_be_a_single_document_set_name_and_cannot_contain_path_characters_, "documentSetName"); } Log.Info(Constants.LOGGING_SOURCE, CoreResources.FieldAndContentTypeExtensions_CreateDocumentSet, documentSetName); var result = DocumentSet.DocumentSet.Create(folder.Context, folder, documentSetName, contentTypeId); folder.Context.ExecuteQueryRetry(); var fullUri = new Uri(result.Value); var serverRelativeUrl = fullUri.AbsolutePath; var documentSetFolder = folder.Folders.GetByUrl(serverRelativeUrl); return documentSetFolder; }
/// <summary> /// Creates a new document set as a child of an existing folder, with the specified content type ID. /// </summary> /// <param name="folder"></param> /// <param name="documentSetName"></param> /// <param name="contentTypeId">Content type of the document set</param> /// <returns>The created Folder representing the document set, so that additional operations (such as setting properties) can be done.</returns> /// <remarks> /// <example> /// var setContentType = list.BestMatchContentTypeId(BuiltInContentTypeId.DocumentSet); /// var set1 = list.RootFolder.CreateDocumentSet("Set 1", setContentType); /// </example> /// </remarks> public static Folder CreateDocumentSet(this Folder folder, string documentSetName, ContentTypeId contentTypeId) { if (folder == null) { throw new ArgumentNullException("folder"); } if (documentSetName == null) { throw new ArgumentNullException("documentSetName"); } if (contentTypeId == null) { throw new ArgumentNullException("contentTypeId"); } // TODO: Check for any other illegal characters in SharePoint if (documentSetName.Contains('/') || documentSetName.Contains('\\')) { throw new ArgumentException(CoreResources.FileFolderExtensions_CreateDocumentSet_The_argument_must_be_a_single_document_set_name_and_cannot_contain_path_characters_, "documentSetName"); } Log.Info(Constants.LOGGING_SOURCE, CoreResources.FieldAndContentTypeExtensions_CreateDocumentSet, documentSetName); var result = DocumentSet.DocumentSet.Create(folder.Context, folder, documentSetName, contentTypeId); folder.Context.ExecuteQueryRetry(); var fullUri = new Uri(result.Value); var serverRelativeUrl = fullUri.AbsolutePath; var documentSetFolder = folder.Folders.GetByUrl(serverRelativeUrl); return(documentSetFolder); }
private static void CreateView(Web web, View view, Microsoft.SharePoint.Client.ViewCollection existingViews, List createdList) { try { //have to maintain raw displayNameElement for displayNameElement.Value.ContainsResourceToken() at Line 717 var viewElementRaw = XElement.Parse(view.ListViewXml); //var displayNameElement = viewElementRaw.Attribute("DisplayName"); var displayNameElement = "XluoTest"; if (displayNameElement == null) { throw new ApplicationException("Invalid View element, missing a valid value for the attribute DisplayName."); } //for all other functions need Parsed SchemaXML var viewElement = XElement.Parse(view.ListViewXml); //WriteSubProgress($"Views for list {createdList.Title}", displayNameElement.Value, currentViewIndex, total); //monitoredScope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ListInstances_Creating_view__0_, displayNameElement.Value); //get from resource file var viewTitle = displayNameElement; //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); // Fix the calendar recurrence if (viewType == ViewType.Calendar) { viewType = ViewType.Calendar | ViewType.Recurrence; } // 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 && bool.Parse(viewElement.Attribute("DefaultView").Value); // Hidden view var hidden = viewElement.Attribute("Hidden") != null && bool.Parse(viewElement.Attribute("Hidden").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); } #if !SP2013 && !SP2016 //BaseViewID int BaseViewID = 1; var baseviewIDElement = viewElementRaw.Attribute("BaseViewID"); if (baseviewIDElement != null) { BaseViewID = int.Parse(baseviewIDElement.Value); } #endif // Query var viewQuery = new StringBuilder(); foreach (var queryElement in viewElement.Descendants("Query").Elements()) { viewQuery.Append(queryElement.ToString()); } var viewCI = new ViewCreationInformation { #if !SP2013 && !SP2016 baseViewId = BaseViewID, #endif 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 = urlAttribute.Value; } var reader = viewElement.CreateReader(); reader.MoveToContent(); var viewInnerXml = reader.ReadInnerXml(); var createdView = createdList.Views.Add(viewCI); createdView.ListViewXml = viewInnerXml; if (hidden) { createdView.Hidden = hidden; } createdView.Update(); #if SP2013 || SP2016 createdView.EnsureProperties(v => v.Scope, v => v.JSLink, v => v.Title, v => v.Aggregations, v => v.MobileView, v => v.MobileDefaultView, v => v.ViewData); #else createdView.EnsureProperties(v => v.Scope, v => v.JSLink, v => v.Title, v => v.Aggregations, v => v.MobileView, v => v.MobileDefaultView, v => v.ViewData, v => v.CustomFormatter); #endif web.Context.ExecuteQueryRetry(); if (urlHasValue) { //restore original title createdView.Title = viewTitle; createdView.Update(); } // ContentTypeID var contentTypeID = (string)viewElement.Attribute("ContentTypeID"); 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; } else { childContentTypeId = createdList.ContentTypes.BestMatch(contentTypeID); } if (childContentTypeId != null) { createdView.ContentTypeId = childContentTypeId; createdView.Update(); } } // Default for content type bool parsedDefaultViewForContentType; var defaultViewForContentType = (string)viewElement.Attribute("DefaultViewForContentType"); if (!string.IsNullOrEmpty(defaultViewForContentType) && bool.TryParse(defaultViewForContentType, out parsedDefaultViewForContentType)) { createdView.DefaultViewForContentType = parsedDefaultViewForContentType; createdView.Update(); } // Scope var scope = (string)viewElement.Attribute("Scope"); var parsedScope = ViewScope.DefaultValue; if (!string.IsNullOrEmpty(scope) && Enum.TryParse <ViewScope>(scope, out parsedScope)) { createdView.Scope = parsedScope; createdView.Update(); } // MobileView var mobileView = viewElement.Attribute("MobileView") != null && bool.Parse(viewElement.Attribute("MobileView").Value); if (mobileView) { createdView.MobileView = mobileView; createdView.Update(); } // MobileDefaultView var mobileDefaultView = viewElement.Attribute("MobileDefaultView") != null && bool.Parse(viewElement.Attribute("MobileDefaultView").Value); if (mobileDefaultView) { createdView.MobileDefaultView = mobileDefaultView; createdView.Update(); } // Aggregations var aggregationsElement = viewElement.Descendants("Aggregations").FirstOrDefault(); if (aggregationsElement != null && aggregationsElement.HasElements) { var fieldRefString = ""; foreach (var fieldRef in aggregationsElement.Descendants("FieldRef")) { fieldRefString += fieldRef.ToString(); } if (createdView.Aggregations != fieldRefString) { createdView.Aggregations = fieldRefString; createdView.Update(); } } // JSLink var jslinkElement = viewElement.Descendants("JSLink").FirstOrDefault(); if (jslinkElement != null) { var jslink = jslinkElement.Value; if (createdView.JSLink != jslink) { createdView.JSLink = jslink; createdView.Update(); // Only push the JSLink value to the web part as it contains a / indicating it's a custom one. So we're not pushing the OOB ones like clienttemplates.js or hierarchytaskslist.js // but do push custom ones down to th web part (e.g. ~sitecollection/Style Library/JSLink-Samples/ConfidentialDocuments.js) if (jslink.Contains("/")) { createdView.EnsureProperty(v => v.ServerRelativeUrl); createdList.SetJSLinkCustomizations(createdView.ServerRelativeUrl, jslink); } } } #if !ONPREMISES || SP2019 // CustomFormatter var customFormatterElement = viewElement.Descendants("CustomFormatter").FirstOrDefault(); if (customFormatterElement != null) { var customFormatter = customFormatterElement.Value; customFormatter = customFormatter.Replace("&", "&"); if (createdView.CustomFormatter != customFormatter) { createdView.CustomFormatter = customFormatter; createdView.Update(); } } #endif // View Data var viewDataElement = viewElement.Descendants("ViewData").FirstOrDefault(); if (viewDataElement != null && viewDataElement.HasElements) { var fieldRefString = ""; foreach (var fieldRef in viewDataElement.Descendants("FieldRef")) { fieldRefString += fieldRef.ToString(); } if (createdView.ViewData != fieldRefString) { createdView.ViewData = fieldRefString; createdView.Update(); } } createdList.Update(); web.Context.ExecuteQueryRetry(); // Add ListViewId token parser createdView.EnsureProperty(v => v.Id); //parser.AddToken(new ListViewIdToken(web, createdList.Title, createdView.Title, createdView.Id)); #if !SP2013 // Localize view title //if (displayNameElement.Value.ContainsResourceToken()) { //createdView.LocalizeView(web, displayNameElement.Value, parser, monitoredScope); } #endif } catch (Exception ex) { //monitoredScope.LogError(CoreResources.Provisioning_ObjectHandlers_ListInstances_Creating_view_failed___0_____1_, ex.Message, ex.StackTrace); throw; } }
private string RenderEditor() { StringBuilder stringBuilder = new StringBuilder(); if (EnableHtmlModeEditing) { ICustomEditorPlugin plugin = PluginManager.GetSingleton <ICustomEditorPlugin>(); String name = new StringBuilder("EditorWrapper-").Append(plugin.EditorName).ToString(); if (!Page.ClientScript.IsStartupScriptRegistered(GetType(), name)) { Page.ClientScript.RegisterStartupScript(GetType(), name, ""); foreach (ICentralizedFile file in plugin.Files) { stringBuilder.Append("<script type=\"text/javascript\" src='").Append(PublicApi.Html.EncodeAttribute(file.GetDownloadUrl())).Append("'></script>").AppendLine(); } } if (!Page.ClientScript.IsStartupScriptRegistered(GetType(), ClientID)) { HttpContext context = HttpContext.Current; String uploaderId = Guid.NewGuid().ToString(); PageContext pageContext = PublicApi.Url.CurrentContext; if (pageContext == null) { pageContext = PublicApi.Url.ParsePageContext(System.Web.HttpContext.Current.Request.Url.ToString()); } var authCookie = context.Request.Cookies["AuthorizationCookie"]; string authValue = string.Empty; if (authCookie != null) { authValue = authCookie.Value; } string callbackUrl = plugin.GetCallbackUrl(uploaderId, ClientID, pageContext.ApplicationTypeId.GetValueOrDefault(), pageContext.ContainerTypeId.GetValueOrDefault(), ContentTypeId.GetValueOrDefault(), authValue, pageContext.ContextItems.GetAllContextItems()); Telligent.Evolution.Urls.Routing.IContextItem group = pageContext.ContextItems.GetAllContextItems().FirstOrDefault <Telligent.Evolution.Urls.Routing.IContextItem>(g => g.TypeName == "Group"); bool sourceButton = true; if (group != null) { sourceButton = PublicApi.Permissions.Get(PermissionRegistrar.CustomEditorSourceButton, PublicApi.Users.AccessingUser.Id.Value, group.ContentId.GetValueOrDefault(), pageContext.ContainerTypeId.Value).IsAllowed; } stringBuilder.Append("<script type=\"text/javascript\">jQuery.fourroads.customEditor.Attach('").Append(ClientID).Append("','"); stringBuilder.Append(callbackUrl); stringBuilder.Append("','").Append(callbackUrl).Append("&delete=true',").Append(SupportFileUpload.ToString().ToLower()).Append(",").Append(sourceButton.ToString().ToLower()).Append(")").Append("</script>"); } } return(stringBuilder.ToString()); }
/// <summary> /// Creates a new document set as a child of an existing folder, with the specified content type ID. /// </summary> /// <param name="folder"></param> /// <param name="documentSetName"></param> /// <param name="contentTypeId">Content type of the document set</param> /// <returns>The created Folder representing the document set, so that additional operations (such as setting properties) can be done.</returns> /// <remarks> /// <example> /// var setContentType = list.BestMatchContentTypeId(BuiltInContentTypeId.DocumentSet); /// var set1 = list.RootFolder.CreateDocumentSet("Set 1", setContentType); /// </example> /// </remarks> public static Folder CreateDocumentSet(this Folder folder, string documentSetName, ContentTypeId contentTypeId) { if (folder == null) { throw new ArgumentNullException("folder"); } if (documentSetName == null) { throw new ArgumentNullException("documentSetName"); } if (contentTypeId == null) { throw new ArgumentNullException("contentTypeId"); } // TODO: Check for any other illegal characters in SharePoint if (documentSetName.Contains('/') || documentSetName.Contains('\\')) { throw new ArgumentException("The argument must be a single document set name and cannot contain path characters.", "documentSetName"); } LoggingUtility.Internal.TraceInformation(1, CoreResources.FieldAndContentTypeExtensions_CreateDocumentSet, documentSetName); var result = DocumentSet.DocumentSet.Create(folder.Context, folder, documentSetName, contentTypeId); folder.Context.ExecuteQueryRetry(); var fullUri = new Uri(result.Value); var serverRelativeUrl = fullUri.AbsolutePath; var documentSetFolder = folder.Folders.GetByUrl(serverRelativeUrl); return(documentSetFolder); }
public static void Add(this DocumentSetTemplate documentSet, ListItem documentItem, string documentSetName, string folder, ContentTypeId docId, bool majorVersionOnly) { Trace.TraceInformation($"Adding: {documentItem.File.Name} to {documentSetName}, Document Folder: {folder}"); var ctx = documentSet.Context; Uri webUrl = new Uri(ctx.Url); DocumentStream ds = new DocumentStream((ClientContext)ctx, documentItem); MemoryStream documentStream; if (majorVersionOnly) { documentStream = ds.MajorVersion; } else { documentStream = ds.LatestVersion; } //Use a place holder to workaround filesize limitation with the DefaultDocuments API. //Place holder is inserted via the API, and then overwritten later. if (documentStream != null) { string placeholderPage = "Placeholder"; MemoryStream repo = new MemoryStream(Encoding.UTF8.GetBytes(placeholderPage)); documentSet.DefaultDocuments.Add(folder + ds.FileName, docId, repo.ToArray()); documentSet.Update(true); ctx.ExecuteQuery(); repo.Close(); Trace.TraceInformation("- Placeholder created"); UploadFile((ClientContext)ctx, webUrl.AbsolutePath + "/_cts/" + documentSetName, documentStream, documentItem.File.Name); } }