/// <summary> /// Returns content type associated with the list. /// </summary> /// <param name="list">List object</param> /// <param name="clientContext">Client Context object</param> /// <returns>Content type object</returns> internal static ContentType GetContentType(List list, ClientContext clientContext) { ContentType targetDocumentSetContentType = null; ContentTypeCollection listContentTypes = null; try { listContentTypes = list.ContentTypes; clientContext.Load( listContentTypes, types => types.Include( type => type.Id, type => type.Name, type => type.Parent)); var result = clientContext.LoadQuery(listContentTypes.Where(c => c.Name == ConstantStrings.OneDriveDocumentContentType)); clientContext.ExecuteQuery(); targetDocumentSetContentType = result.FirstOrDefault(); } catch (Exception exception) { Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName); } return(targetDocumentSetContentType); }
/// <summary> /// Return content type by name /// </summary> /// <param name="list"></param> /// <param name="contentTypeName"></param> /// <returns>Conten type object or null if was not found</returns> public static ContentType GetContentTypeByName(this List list, string contentTypeName) { ContentTypeCollection ctCol = list.ContentTypes; IEnumerable <ContentType> results = list.Context.LoadQuery <ContentType>(ctCol.Where(item => item.Name == contentTypeName)); list.Context.ExecuteQuery(); return(results.FirstOrDefault()); }
public static List <ContentTypeId> GetGroupContentTypeIdsByGroupName(this ContentTypeCollection value, string name) { var context = value.Context; context.Load(value); context.ExecuteQuery(); return(value.Where(ct => ct.Group == name).Select(ct => ct.Id).ToList()); }
/// <summary> /// Searches for the content type with the closest match to the value of the specified content type ID. /// If the search finds two matches, the shorter ID is returned. /// </summary> /// <param name="contentTypes">Content type collection to search</param> /// <param name="contentTypeId">Complete ID for the content type to search</param> /// <returns>Content type Id object or null if was not found</returns> public static ContentTypeId BestMatch(this ContentTypeCollection contentTypes, string contentTypeId) { var res = contentTypes.Where(c => c.Id.StringValue.StartsWith(contentTypeId)).OrderBy(c => c.Id.StringValue.Length).FirstOrDefault(); if (res != null) { return(res.Id); } return(null); }
/// <summary> /// Gets a ContentType object based on a Content Type Name /// </summary> /// <param name="context"></param> /// <param name="list"></param> /// <param name="contentType"></param> /// <returns></returns> private ContentType GetContentType(ClientContext context, List list, string contentType) { ContentTypeCollection listContentTypes = list.ContentTypes; context.Load(listContentTypes, types => types.Include(type => type.Id, type => type.Name, type => type.Parent)); var result = context.LoadQuery(listContentTypes.Where(c => c.Name == contentType)); context.ExecuteQuery(); ContentType ct = result.FirstOrDefault(); return(ct); }
public static Folder CreateFolder(ClientContext cc, List list, string sitecontent, string documentSetName, JObject fields) { try { ContentTypeCollection listContentTypes = list.ContentTypes; cc.Load(listContentTypes, types => types.Include(type => type.Id, type => type.Name, type => type.Parent)); //var result = cc.LoadQuery(listContentTypes.Where(c => c.Name == "document set 2")); string SiteContentName = sitecontent; var result = cc.LoadQuery(listContentTypes.Where(c => c.Name == SiteContentName)); cc.ExecuteQuery(); ContentType targetDocumentSetContentType = result.FirstOrDefault(); ListItemCreationInformation newItemInfo = new ListItemCreationInformation(); newItemInfo.UnderlyingObjectType = FileSystemObjectType.Folder; //newItemInfo.LeafName = "Document Set Kien2"; newItemInfo.LeafName = documentSetName; //newItemInfo.FolderUrl = list.RootFolder.ServerRelativeUrl.ToString(); ListItem newListItem = list.AddItem(newItemInfo); newListItem["ContentTypeId"] = targetDocumentSetContentType.Id.ToString(); foreach (KeyValuePair <string, JToken> field in fields) { JObject fieldObj = field.Value as JObject; if (fieldObj["type"].ToString().Equals("User")) { var user = FieldUserValue.FromUser(fieldObj["label"].ToString()); newListItem[field.Key] = user; } else { newListItem[field.Key] = fieldObj["label"].ToString(); } } newListItem.SystemUpdate(); list.Update(); cc.ExecuteQuery(); //Folder folder = GetFolder(cc, list, documentSetName); Folder folder = newListItem.Folder; return(folder); } catch (Exception ex) { Console.WriteLine("Unable to create document set"); Console.WriteLine(ex); throw; } }
private static void DeleteDefaultContentTypeFromList(ClientContext clientContext, Web web, List list) { //Delete default content type ContentTypeCollection collection = list.ContentTypes; clientContext.Load(collection); clientContext.ExecuteQuery(); string contentTypeID = collection.Where(c => c.Name == "Item").FirstOrDefault().StringId; ContentType ct = list.ContentTypes.GetById(contentTypeID); ct.DeleteObject(); clientContext.ExecuteQuery(); }
/// <summary> /// Does content type exists in the web /// </summary> /// <param name="web"></param> /// <param name="contentTypeName"></param> /// <returns></returns> public static bool ContentTypeExistsByName(this Web web, string contentTypeName) { ContentTypeCollection ctCol = web.ContentTypes; IEnumerable <ContentType> results = web.Context.LoadQuery <ContentType>(ctCol.Where(item => item.Name == contentTypeName)); web.Context.ExecuteQuery(); ContentType ct = results.FirstOrDefault(); if (ct != null) { return(true); } return(false); }
private static ContentType GetContentType(ClientContext ctx, List docs, string contentType) { ContentTypeCollection listContentTypes = docs.ContentTypes; ctx.Load(listContentTypes, types => types.Include(type => type.Id, type => type.Name, type => type.Parent)); var result = ctx.LoadQuery(listContentTypes.Where(c => c.Name == contentType)); ctx.ExecuteQuery(); ContentType targetDocumentSetContentType = result.FirstOrDefault(); return(targetDocumentSetContentType); }
private static string GetContentType(Web web, List list, string contentType) { ContentTypeCollection collection = list.ContentTypes; web.Context.Load(collection); web.Context.ExecuteQuery(); var ct = collection.Where(c => c.Name == contentType).FirstOrDefault(); string contentTypeID = ""; if (ct != null) { contentTypeID = ct.StringId; } return(contentTypeID); }
private ContentType GetContentType(List list, string contentType) { ContentTypeCollection contentTypes = list.ContentTypes; _clientContext.Load(contentTypes, types => types.Include (type => type.Id, type => type.Name, type => type.Parent)); var result = _clientContext.LoadQuery(contentTypes.Where(c => c.Name == contentType)); _clientContext.ExecuteQuery(); ContentType targetDocumentSetContentType = result.FirstOrDefault(); return(targetDocumentSetContentType); }
/// <summary> /// Does cotnent type exist in list /// </summary> /// <param name="list"></param> /// <param name="contentTypeName"></param> /// <returns></returns> public static bool ContentTypeExistsByName(this List list, string contentTypeName) { if (!list.ContentTypesEnabled) { return(false); } ContentTypeCollection ctCol = list.ContentTypes; IEnumerable <ContentType> results = list.Context.LoadQuery <ContentType>(ctCol.Where(item => item.Name == contentTypeName)); list.Context.ExecuteQuery(); if (results.FirstOrDefault() != null) { return(true); } return(false); }
public static Folder CreateFolder(ClientContext cc, List list, string sitecontent, string documentSetName) { try { ContentTypeCollection listContentTypes = list.ContentTypes; cc.Load(listContentTypes, types => types.Include(type => type.Id, type => type.Name, type => type.Parent)); //var result = cc.LoadQuery(listContentTypes.Where(c => c.Name == "document set 2")); string SiteContentName = sitecontent; var result = cc.LoadQuery(listContentTypes.Where(c => c.Name == SiteContentName)); cc.ExecuteQuery(); ContentType targetDocumentSetContentType = result.FirstOrDefault(); ListItemCreationInformation newItemInfo = new ListItemCreationInformation(); newItemInfo.UnderlyingObjectType = FileSystemObjectType.Folder; //newItemInfo.LeafName = "Document Set Kien2"; newItemInfo.LeafName = documentSetName; //newItemInfo.FolderUrl = list.RootFolder.ServerRelativeUrl.ToString(); ListItem newListItem = list.AddItem(newItemInfo); newListItem["ContentTypeId"] = targetDocumentSetContentType.Id.ToString(); newListItem.Update(); Folder folder = newListItem.Folder; return(folder); } catch (Exception ex) { Console.WriteLine("Unable to create document set"); Console.WriteLine(ex); throw; } }
/// <summary> /// Removes a content type from a list/library by name /// </summary> /// <param name="list">The list</param> /// <param name="contentTypeName">The content type name to remove from the list</param> /// <exception cref="System.ArgumentException">Thrown when a arguement is null or <see cref="String.Empty"/></exception> public static void RemoveContentTypeByName(this List list, string contentTypeName) { if (string.IsNullOrEmpty(contentTypeName)) { var message = string.Format(Constants.EXCEPTION_MSG_INVALID_ARG, "contentTypeName"); throw new ArgumentNullException("contentTypeName", message); } ContentTypeCollection _cts = list.ContentTypes; list.Context.Load(_cts); IEnumerable <ContentType> _results = list.Context.LoadQuery <ContentType>(_cts.Where(item => item.Name == contentTypeName)); list.Context.ExecuteQuery(); ContentType _ct = _results.FirstOrDefault(); if (_ct != null) { _ct.DeleteObject(); list.Update(); list.Context.ExecuteQuery(); } }
public static void CreateContentType(ClientContext context, ContentType parentContentType, string contentName, string description, string contentGroup, List <Field> fields) { //// Get the content type collection for the website ContentTypeCollection contentTypeColl = context.Web.ContentTypes; ContentType contentType = contentTypeColl.Where(a => a.Name == contentName).FirstOrDefault(); if (contentType == null) { //// Specifies properties that are used as parameters to initialize a new content type. ContentTypeCreationInformation contentTypeCreation = new ContentTypeCreationInformation(); contentTypeCreation.Name = contentName; contentTypeCreation.Description = contentName; contentTypeCreation.Group = contentGroup; contentTypeCreation.ParentContentType = parentContentType; //// Add the new content type to the collection contentType = contentTypeColl.Add(contentTypeCreation); } var siteFields = context.Web.Fields; context.Load(siteFields); context.Load(contentType); context.Load(contentType.Fields); context.ExecuteQuery(); var existingSiteFields = siteFields.ToList(); foreach (var field in fields) { var siteField = field; if (!contentType.Fields.Where(a => a.InternalName == field.InternalName).Any()) { var fieldSchema = XDocument.Parse(field.SchemaXml); string internalName = CreateUnqiueName(existingSiteFields, fieldSchema.Root.Attribute("StaticName").Value); string typeName = fieldSchema.Root.Attribute("Type").Value; string displayName = fieldSchema.Root.Attribute("DisplayName").Value; string required = fieldSchema.Root.Attribute("Required") != null?fieldSchema.Root.Attribute("Required").Value : ""; string enforceUniqueValues = fieldSchema.Root.Attribute("EnforceUniqueValues") != null?fieldSchema.Root.Attribute("EnforceUniqueValues").Value : ""; string showField = fieldSchema.Root.Attribute("ShowField") != null?fieldSchema.Root.Attribute("ShowField").Value : ""; string unlimitedLengthInDocumentLibrary = fieldSchema.Root.Attribute("UnlimitedLengthInDocumentLibrary") != null?fieldSchema.Root.Attribute("UnlimitedLengthInDocumentLibrary").Value : ""; string relationshipDeleteBehavior = fieldSchema.Root.Attribute("RelationshipDeleteBehavior") != null?fieldSchema.Root.Attribute("RelationshipDeleteBehavior").Value : ""; string staticName = internalName; string name = internalName; string sourceId = fieldSchema.Root.Attribute("SourceID") != null?fieldSchema.Root.Attribute("SourceID").Value : ""; string list = fieldSchema.Root.Attribute("List") != null?fieldSchema.Root.Attribute("List").Value : ""; var test = existingSiteFields.Where(a => a.InternalName.ToLower() == "email1").FirstOrDefault(); if (!existingSiteFields.Where(a => a.InternalName == field.InternalName).Any()) { siteField = CreateSiteColumn(context, typeName, displayName, required, enforceUniqueValues, showField, unlimitedLengthInDocumentLibrary, relationshipDeleteBehavior, staticName, name, sourceId, list); } contentType.FieldLinks.Add(new FieldLinkCreationInformation() { Field = siteField }); contentType.Update(true); context.Load(contentType); context.Load(contentType.FieldLinks); context.ExecuteQuery(); } } }
public static Folder CreateFolder(ClientContext cc, List list, string sitecontent, string documentSetName, IDictionary <string, string> inputFields, List <Metadata> fields) { try { ContentTypeCollection listContentTypes = list.ContentTypes; cc.Load(listContentTypes, types => types.Include(type => type.Id, type => type.Name, type => type.Parent)); //var result = cc.LoadQuery(listContentTypes.Where(c => c.Name == "document set 2")); string SiteContentName = sitecontent; var result = cc.LoadQuery(listContentTypes.Where(c => c.Name == SiteContentName)); cc.ExecuteQuery(); ContentType targetDocumentSetContentType = result.FirstOrDefault(); ListItemCreationInformation newItemInfo = new ListItemCreationInformation(); newItemInfo.UnderlyingObjectType = FileSystemObjectType.Folder; //newItemInfo.LeafName = "Document Set Kien2"; newItemInfo.LeafName = documentSetName; //newItemInfo.FolderUrl = list.RootFolder.ServerRelativeUrl.ToString(); DateTime dtMin = new DateTime(1900, 1, 1); Regex regex = new Regex(@"~t.*"); ListItem newListItem = list.AddItem(newItemInfo); newListItem["ContentTypeId"] = targetDocumentSetContentType.Id.ToString(); newListItem.Update(); foreach (KeyValuePair <string, string> inputField in inputFields) { if (inputField.Value == null || inputField.Value == "" || inputField.Key.Equals("Modified")) { continue; } string fieldValue = inputField.Value; Match match = regex.Match(fieldValue); Metadata field = fields.Find(x => x.InternalName.Equals(inputField.Key)); if (field.TypeAsString.Equals("User")) { int uid = SharePointHelper.GetUserId(cc, fieldValue); newListItem[inputField.Key] = new FieldUserValue { LookupId = uid }; } //endre hard koding else if (inputField.Key.Equals("Modified_x0020_By") || inputField.Key.Equals("Created_x0020_By") || inputField.Key.Equals("Dokumentansvarlig")) { StringBuilder sb = new StringBuilder("i:0#.f|membership|"); sb.Append(fieldValue); newListItem[inputField.Key] = sb; } else if (match.Success) { fieldValue = fieldValue.Replace("~t", ""); if (DateTime.TryParse(fieldValue, out DateTime dt)) { if (dtMin <= dt) { newListItem[inputField.Key] = dt; } else { continue; } } } else { newListItem[inputField.Key] = fieldValue; } newListItem.Update(); } Folder folder = newListItem.Folder; return(folder); } catch (Exception ex) { Console.WriteLine("Unable to create document set"); Console.WriteLine(ex); throw; } }
//Deploy the Host Web Support Cases List private void CreateHostWebSupportCasesList(ClientContext clientContext) { ListCollection listCollection = clientContext.Web.Lists; clientContext.Load(listCollection, lists => lists.Include(list => list.Title) .Where(list => list.Title == "Support Cases")); clientContext.ExecuteQuery(); if (listCollection.Count == 0) { List surveylist = Util.CreateList(clientContext, (int)ListTemplateType.GenericList, "Support Cases", "Lists/SupportCases", QuickLaunchOptions.On); ContentTypeCollection ff = clientContext.Web.ContentTypes; clientContext.Load(ff); clientContext.ExecuteQuery(); bool bexist = false; foreach (ContentType ctype in ff) { if (ctype.StringId == Util.SupportCaseCtyeId) { bexist = true; surveylist.ContentTypes.AddExistingContentType(ctype); clientContext.ExecuteQuery(); break; } } if (!bexist) { //Create content type for Support Cases list ContentType ctype = Util.CreateContentType(clientContext, Util.SupportCaseCtypeName, "FTC_TO_AM", Util.SupportCaseCtyeId); //Create Files List <string> fieldsList = new List <string>(); fieldsList.Add("<Field Type='Text' DisplayName='Status' Name='FTCAM_Status' Group='FTC_TO_AM' ></Field>"); fieldsList.Add("<Field Type='Text' DisplayName='CSR' Name='FTCAM_CSR' Group='FTC_TO_AM'></Field>"); fieldsList.Add("<Field Type='Text' DisplayName='Customer ID' Name='FTCAM_CustomerID' Group='FTC_TO_AM'></Field>"); //Bind Field to ctype foreach (string str in fieldsList) { Field field = clientContext.Web.Fields.AddFieldAsXml(str, true, AddFieldOptions.DefaultValue); clientContext.ExecuteQuery(); FieldLinkCreationInformation fieldLink = new FieldLinkCreationInformation(); fieldLink.Field = field; ctype.FieldLinks.Add(fieldLink); ctype.Update(true); clientContext.ExecuteQuery(); } surveylist.ContentTypes.AddExistingContentType(ctype); clientContext.ExecuteQuery(); } //Delete the item content type ContentTypeCollection ctycollection = surveylist.ContentTypes; clientContext.Load(ctycollection); clientContext.ExecuteQuery(); ContentType defualtitemcty = ctycollection.Where(c => c.Name == "Item").FirstOrDefault(); defualtitemcty.DeleteObject(); clientContext.ExecuteQuery(); } }
public static Folder CreateDocumentSetWithTaxonomy(ClientContext cc, List list, string sitecontent, string documentSetName, IDictionary <string, string> inputFields, List <Metadata> fields, IDictionary <string, string> taxonomy) { try { ContentTypeCollection listContentTypes = list.ContentTypes; cc.Load(listContentTypes, types => types.Include(type => type.Id, type => type.Name, type => type.Parent)); //var result = cc.LoadQuery(listContentTypes.Where(c => c.Name == "document set 2")); //string SiteContentName = sitecontent; var result = cc.LoadQuery(listContentTypes.Where(c => c.Name == sitecontent)); cc.ExecuteQuery(); ContentType targetDocumentSetContentType = result.FirstOrDefault(); ListItemCreationInformation newItemInfo = new ListItemCreationInformation(); newItemInfo.UnderlyingObjectType = FileSystemObjectType.Folder; newItemInfo.LeafName = documentSetName; ListItem newListItem = list.AddItem(newItemInfo); newListItem["ContentTypeId"] = targetDocumentSetContentType.Id.ToString(); newListItem.Update(); cc.ExecuteQuery(); var clientRuntimeContext = newListItem.Context; for (int i = 0; i < taxonomy.Count; i++) { var inputField = taxonomy.ElementAt(i); var fieldValue = inputField.Value; var field = list.Fields.GetByInternalNameOrTitle(inputField.Key); cc.Load(field); cc.ExecuteQuery(); var taxKeywordField = clientRuntimeContext.CastTo <TaxonomyField>(field); Guid _id = taxKeywordField.TermSetId; string _termID = TermHelper.GetTermIdByName(cc, fieldValue, _id); TaxonomyFieldValue termValue = new TaxonomyFieldValue() { Label = fieldValue.ToString(), TermGuid = _termID, }; taxKeywordField.SetFieldValueByValue(newListItem, termValue); taxKeywordField.Update(); newListItem.Update(); } DateTime dtMin = new DateTime(1900, 1, 1); Regex regex = new Regex(@"~t.*"); foreach (KeyValuePair <string, string> inputField in inputFields) { if (inputField.Value == null || inputField.Value == "" || inputField.Key.Equals("Modified")) { continue; } string fieldValue = inputField.Value; Match match = regex.Match(fieldValue); Metadata field = fields.Find(x => x.InternalName.Equals(inputField.Key)); if (field.TypeAsString.Equals("User")) { int uid = SharePointHelper.GetUserId(cc, fieldValue); newListItem[inputField.Key] = new FieldUserValue { LookupId = uid }; } //endre hard koding else if (inputField.Key.Equals("Modified_x0020_By") || inputField.Key.Equals("Created_x0020_By") || inputField.Key.Equals("Dokumentansvarlig")) { StringBuilder sb = new StringBuilder("i:0#.f|membership|"); sb.Append(fieldValue); newListItem[inputField.Key] = sb; } else if (match.Success) { fieldValue = fieldValue.Replace("~t", ""); if (DateTime.TryParse(fieldValue, out DateTime dt)) { if (dtMin <= dt) { newListItem[inputField.Key] = dt; } else { continue; } } } else { newListItem[inputField.Key] = fieldValue; } newListItem.Update(); } Folder folder = newListItem.Folder; return(folder); } catch (Exception ex) { Console.WriteLine("Unable to create document set"); Console.WriteLine(ex); throw; } }
public static void RemoveContentType(this List list, string contentTypeName) { ContentTypeCollection _cts = list.ContentTypes; list.Context.Load(_cts); IEnumerable <ContentType> _results = list.Context.LoadQuery <ContentType>(_cts.Where(item => item.Name == contentTypeName)); list.Context.ExecuteQuery(); ContentType _ct = _results.FirstOrDefault(); if (_ct != null) { _ct.DeleteObject(); list.Update(); list.Context.ExecuteQuery(); } }
public bool AddNewFolder(string listUrl, string listName, string docSetContentTypeName, string newDocSetName) { bool res = false; try { string siteUrl = SLMConstant.Ecm.SiteUrl; //http://ecm/dept/public string domain = SLMConstant.Ecm.Domain; string userName = SLMConstant.Ecm.Username; string password = SLMConstant.Ecm.Password; //log.Info("Connect ECM"); using (ClientContext clientContext = new ToEcm.ClientContext(siteUrl) { Credentials = new NetworkCredential(userName, password, domain) }) { // get the web Web web = clientContext.Web; List list = clientContext.Web.Lists.GetByTitle(listName); clientContext.Load(clientContext.Site); // load the folder Folder f = web.GetFolderByServerRelativeUrl(listUrl + newDocSetName); log.Info(listUrl + newDocSetName); clientContext.Load(f); bool alreadyExists = false; // check if the folder exists try { log.Info("Before clientContext.ExecuteQuery()"); clientContext.ExecuteQuery(); log.Info("After clientContext.ExecuteQuery()"); alreadyExists = true; res = true; } catch (Exception ee) { //ถ้าเข้า catch แสดงว่า ไม่พบ folder ที่โหลดเข้ามา log.Error("Error Check Folder : " + ee.Message); } // create folder if (!alreadyExists) { log.Info("Create Folder: Start"); // folder doesn't exists so create it ContentTypeCollection listContentTypes = list.ContentTypes; clientContext.Load(listContentTypes, types => types.Include (type => type.Id, type => type.Name, type => type.Parent)); var result = clientContext.LoadQuery(listContentTypes.Where (c => c.Name == docSetContentTypeName)); clientContext.ExecuteQuery(); ContentType targetDocumentSetContentType = result.FirstOrDefault(); // create the item ListItemCreationInformation newItemInfo = new ListItemCreationInformation(); newItemInfo.UnderlyingObjectType = FileSystemObjectType.Folder; newItemInfo.LeafName = newDocSetName; Microsoft.SharePoint.Client.ListItem newListItem = list.AddItem(newItemInfo); // set title and content type newListItem["ContentTypeId"] = targetDocumentSetContentType.Id.ToString(); newListItem["Title"] = newDocSetName; newListItem.Update(); res = true; // execute it clientContext.Load(list); clientContext.ExecuteQuery(); log.Info("Create Folder: Finished"); } } } catch (Exception ex) { log.Error("Error AddNewFolder : " + ex.Message); throw ex; } return(res); }