public void UpdateFieldToContentType(ContentType targetContentType, Field targetField, string fieldName) { //if (UtilApp.IsExist(Context, fieldName, Basic_CSOM.Enums.TypeSharepointEnum.SiteColumn)) //{ // return; //} Context.Load(targetContentType, x => x.FieldLinks.Include(item => item.Name)); Context.ExecuteQuery(); // Update content type FieldLinkCreationInformation fldLink = new FieldLinkCreationInformation(); fldLink.Field = targetField; // If uou set this to "true", the column getting added to the content type will be added as "required" field fldLink.Field.Required = false; // If you set this to "true", the column getting added to the content type will be added as "hidden" field fldLink.Field.Hidden = false; if (targetContentType.FieldLinks.FirstOrDefault(x => x.Name.Equals(fieldName)) == null) { targetContentType.FieldLinks.Add(fldLink); } targetContentType.Update(false); Context.Load(targetContentType); Context.ExecuteQuery(); }
static void Main(string[] args) { string webSPOUrl = "https://psrsolutions1.sharepoint.com/sites/Dev/"; string userName = "******"; Console.WriteLine("Password:"******"Site Pages"); context.Load(list); var fieldSchemaXml = @"<Field ID='{7f759147-c861-4cd6-a11f-5aa3037d9634}' Type='UserMulti' List='UserInfo' Name='_ModernAudienceTargetUserField' StaticName='_ModernAudienceTargetUserField' DisplayName='Audience' Required='FALSE' SourceID='{e533a454-bc7a-4e33-954c-f7c9c17244ef}' ColName='int2' RowOrdinal='0' ShowField='ImnName' ShowInDisplayForm='TRUE' ShowInListSettings='FALSE' UserSelectionMode = 'GroupsOnly' UserSelectionScope = '0' Mult = 'TRUE' Sortable = 'FALSE' Version = '1' /> "; var field = list.Fields.AddFieldAsXml(fieldSchemaXml, true, AddFieldOptions.AddFieldInternalNameHint); context.ExecuteQuery(); // Get the content type from list var ContentTypeColl = list.ContentTypes; context.Load(ContentTypeColl); context.ExecuteQuery(); foreach (var contentType in ContentTypeColl) { Console.WriteLine(contentType.Name); var ColumnColl = list.Fields; context.Load(ColumnColl); context.ExecuteQuery(); var ColumnName = "Audience"; var Column = ColumnColl.Where(c => c.Title == ColumnName).FirstOrDefault(); if (Column != null) { //Check if column already added to the content type var FieldCollection = contentType.Fields; context.Load(FieldCollection); context.ExecuteQuery(); var Field = FieldCollection.Where(f => f.Title == ColumnName).FirstOrDefault(); if (Field == null && !(contentType.Sealed)) { //Add Field to content type var FieldLink = new FieldLinkCreationInformation(); FieldLink.Field = Column; contentType.FieldLinks.Add(FieldLink); contentType.Update(false); context.ExecuteQuery(); } } } } } catch (Exception ex) { Console.WriteLine("Error is : " + ex.Message); } }
private static void BindFieldsToContentType(Web web, string contentTypeId, IEnumerable <Field> fields) { var contentType = web.GetContentTypeById(contentTypeId); var descriptionField = web.Fields.GetByInternalNameOrTitle(FIELD_DESCRIPTION); web.Context.Load(web.Fields); web.Context.Load(descriptionField); web.Context.Load(contentType.FieldLinks); web.Context.ExecuteQuery(); // add the description field ((List <Field>)fields).Insert(0, descriptionField); // add any fields which have not be included var missingFields = fields.Except(from f in fields join fl in contentType.FieldLinks on f.StaticName equals fl.Name select f).ToList(); foreach (var field in missingFields) { var fieldLinkCreationInfo = new FieldLinkCreationInformation() { Field = field }; contentType.FieldLinks.Add(fieldLinkCreationInfo); } contentType.Update(false); contentType.Context.ExecuteQuery(); }
public override void Create() { if (TargetContentType == null) { throw new Exception("Cần cung cấp content type"); } Field targetField = GetField(); if (targetField == null) { throw new Exception($"Field {InternalName} không tồn tại."); } FieldLinkCreationInformation fldLink = new FieldLinkCreationInformation { Field = targetField }; fldLink.Field.Required = false; fldLink.Field.Hidden = false; TargetContentType.FieldLinks.Add(fldLink); TargetContentType.Update(false); _context.ExecuteQuery(); }
static void CreateExpenseContentTypes() { ctypeExpense = CreateContentType("Expense Item", "0x01"); ctypeExpense.Update(true); clientContext.Load(ctypeExpense.FieldLinks); clientContext.ExecuteQuery(); FieldLinkCreationInformation fldLinkExpenseCategory = new FieldLinkCreationInformation(); fldLinkExpenseCategory.Field = fldExpenseCategory; ctypeExpense.FieldLinks.Add(fldLinkExpenseCategory); ctypeExpense.Update(true); // add site columns FieldLinkCreationInformation fldLinkExpenseDate = new FieldLinkCreationInformation(); fldLinkExpenseDate.Field = fldExpenseDate; ctypeExpense.FieldLinks.Add(fldLinkExpenseDate); ctypeExpense.Update(true); // add site columns FieldLinkCreationInformation fldLinkExpenseAmount = new FieldLinkCreationInformation(); fldLinkExpenseAmount.Field = fldExpenseAmount; ctypeExpense.FieldLinks.Add(fldLinkExpenseAmount); ctypeExpense.Update(true); clientContext.ExecuteQuery(); ctypeExpenseBudgetItem = CreateContentType("Expense Budget Item", "0x01"); ctypeExpenseBudgetItem.Update(true); clientContext.Load(ctypeExpenseBudgetItem.FieldLinks); clientContext.ExecuteQuery(); FieldLinkCreationInformation fldLinkExpenseBudgetCategory = new FieldLinkCreationInformation(); fldLinkExpenseBudgetCategory.Field = fldExpenseCategory; ctypeExpenseBudgetItem.FieldLinks.Add(fldLinkExpenseBudgetCategory); ctypeExpenseBudgetItem.Update(true); FieldLinkCreationInformation fldLinkExpenseBudgetYear = new FieldLinkCreationInformation(); fldLinkExpenseBudgetYear.Field = fldExpenseBudgetYear; ctypeExpenseBudgetItem.FieldLinks.Add(fldLinkExpenseBudgetYear); ctypeExpenseBudgetItem.Update(true); FieldLinkCreationInformation fldLinkExpenseBudgetQuarter = new FieldLinkCreationInformation(); fldLinkExpenseBudgetQuarter.Field = fldExpenseBudgetQuarter; ctypeExpenseBudgetItem.FieldLinks.Add(fldLinkExpenseBudgetQuarter); ctypeExpenseBudgetItem.Update(true); FieldLinkCreationInformation fldLinkExpenseBudgetAmount = new FieldLinkCreationInformation(); fldLinkExpenseBudgetAmount.Field = fldExpenseBudgetAmount; ctypeExpenseBudgetItem.FieldLinks.Add(fldLinkExpenseBudgetAmount); ctypeExpenseBudgetItem.Update(true); clientContext.ExecuteQuery(); }
/// <summary> /// Method to add columns to Content Type /// </summary> /// <param name="web">Object of site</param> /// <param name="siteColumns">List of site columns</param> /// <param name="finalObj">Content type to which columns are to be added</param> /// <returns>Success or Failure</returns> private static bool AddColumnsToContentType(Web web, List <string> siteColumns, ContentType finalObj) { try { FieldCollection fieldCol = web.Fields; foreach (string columns in siteColumns) { bool isColumnExists = (null != finalObj.Fields.Where(field => field.Title.Equals(columns, StringComparison.OrdinalIgnoreCase)).FirstOrDefault()) ? true : false; if (!isColumnExists) { Field customDoc = fieldCol.GetByTitle(columns); FieldLinkCreationInformation fieldCreationInformation = new FieldLinkCreationInformation(); fieldCreationInformation.Field = customDoc; finalObj.FieldLinks.Add(fieldCreationInformation); } } finalObj.Update(true); return(true); } catch (Exception exception) { ErrorLogger.LogErrorToTextFile(errorFilePath, "Message: " + exception.Message + "\nStacktrace: " + exception.StackTrace); return(false); } }
static void CreateWingtipContentTypes() { ctypeProduct = CreateContentType("Product", "0x01"); // add site columns FieldLinkCreationInformation fieldLinkProductCode = new FieldLinkCreationInformation(); fieldLinkProductCode.Field = fieldProductCode; ctypeProduct.FieldLinks.Add(fieldLinkProductCode); ctypeProduct.Update(true); FieldLinkCreationInformation fieldLinkProductListPrice = new FieldLinkCreationInformation(); fieldLinkProductListPrice.Field = fieldProductListPrice; ctypeProduct.FieldLinks.Add(fieldLinkProductListPrice); ctypeProduct.Update(true); FieldLinkCreationInformation fieldLinkProductCategory = new FieldLinkCreationInformation(); fieldLinkProductCategory.Field = fieldProductCategory; ctypeProduct.FieldLinks.Add(fieldLinkProductCategory); ctypeProduct.Update(true); FieldLinkCreationInformation fieldLinkProductColor = new FieldLinkCreationInformation(); fieldLinkProductColor.Field = fieldProductColor; ctypeProduct.FieldLinks.Add(fieldLinkProductColor); ctypeProduct.Update(true); FieldLinkCreationInformation fieldLinkMinimumAge = new FieldLinkCreationInformation(); fieldLinkMinimumAge.Field = fieldMinimumAge; ctypeProduct.FieldLinks.Add(fieldLinkMinimumAge); ctypeProduct.Update(true); FieldLinkCreationInformation fieldLinkMaximumAge = new FieldLinkCreationInformation(); fieldLinkMaximumAge.Field = fieldMaximumAge; ctypeProduct.FieldLinks.Add(fieldLinkMaximumAge); ctypeProduct.Update(true); clientContext.ExecuteQuery(); Console.WriteLine("Create Product Proposal content type"); ctypeProductProposal = CreateContentType("Product Proposal", "0x0101"); clientContext.Load(ctypeProductProposal); clientContext.ExecuteQuery(); Console.WriteLine("Create Product Proposal folder in _cts folder"); ListItemCreationInformation folder = new ListItemCreationInformation(); site.RootFolder.Folders.Add("_cts/Product Proposal"); clientContext.ExecuteQuery(); Console.WriteLine("Update doc template file for content type"); FileCreationInformation newFile = new FileCreationInformation(); newFile.Content = System.IO.File.ReadAllBytes(studentFolder + @"Modules\DocumentLibraries\Lab\DocumentTemplates\WingtipProductProposal.dotx"); newFile.Url = @"_cts/Product Proposal/WingtipProductProposal.dotx"; newFile.Overwrite = true; Microsoft.SharePoint.Client.File uploadFile = site.RootFolder.Files.Add(newFile); clientContext.Load(uploadFile); clientContext.ExecuteQuery(); Console.WriteLine("Assign doc template url to content type"); ctypeProductProposal.DocumentTemplate = siteUrl + @"/_cts/Product Proposal/WingtipProductProposal.dotx"; ctypeProductProposal.Update(true); clientContext.ExecuteQuery(); }
public void AddFieldToContentType(string contentTypeName, string[] fields) { // Get all the content types from current site ContentTypeCollection collection = _context.Site.RootWeb.ContentTypes; _context.Load(collection); _context.ExecuteQuery(); ContentType contentType = (from c in collection where c.Name == contentTypeName select c).FirstOrDefault(); foreach (var item in fields) { if (item.Contains("Leader") || item.Contains("Members")) { continue; } Field targetField = _context.Web.AvailableFields.GetByInternalNameOrTitle(item); FieldLinkCreationInformation fldLink = new FieldLinkCreationInformation { Field = targetField }; fldLink.Field.Required = false; fldLink.Field.Hidden = false; contentType.FieldLinks.Add(fldLink); contentType.Update(false); } }
private void AddOrUpdateFieldOfContentType(ShContentType configContentType, FieldCollection webFields, string fieldName, ContentType contentType) { // Need to load content type fields every iteration because fields are added to the collection Field webField = webFields.GetByInternalNameOrTitle(fieldName); FieldLinkCollection contentTypeFields = contentType.FieldLinks; ClientContext.Load(contentTypeFields); ClientContext.Load(webField); ClientContext.ExecuteQuery(); var fieldLink = contentTypeFields.FirstOrDefault(existingFieldName => existingFieldName.Name == fieldName); if (fieldLink == null) { var link = new FieldLinkCreationInformation { Field = webField }; fieldLink = contentType.FieldLinks.Add(link); } fieldLink.Required = configContentType.RequiredFields.Contains(fieldName); fieldLink.Hidden = configContentType.HiddenFields.Contains(fieldName); contentType.Update(true); ClientContext.ExecuteQuery(); }
static void CreateProductContentType() { Console.WriteLine("Creating Product content type..."); ctypeProduct = CreateContentType("Product", "0x01"); // add site columns FieldLinkCreationInformation fieldLinkProductCode = new FieldLinkCreationInformation(); fieldLinkProductCode.Field = fieldProductCode; ctypeProduct.FieldLinks.Add(fieldLinkProductCode); ctypeProduct.Update(true); FieldLinkCreationInformation fieldLinkProductDescription = new FieldLinkCreationInformation(); fieldLinkProductDescription.Field = fieldProductDescription; ctypeProduct.FieldLinks.Add(fieldLinkProductDescription); ctypeProduct.Update(true); FieldLinkCreationInformation fieldLinkProductListPrice = new FieldLinkCreationInformation(); fieldLinkProductListPrice.Field = fieldProductListPrice; ctypeProduct.FieldLinks.Add(fieldLinkProductListPrice); ctypeProduct.Update(true); FieldLinkCreationInformation fieldLinkProductColor = new FieldLinkCreationInformation(); fieldLinkProductColor.Field = fieldProductColor; ctypeProduct.FieldLinks.Add(fieldLinkProductColor); ctypeProduct.Update(true); FieldLinkCreationInformation fieldLinkMinimumAge = new FieldLinkCreationInformation(); fieldLinkMinimumAge.Field = fieldMinimumAge; ctypeProduct.FieldLinks.Add(fieldLinkMinimumAge); ctypeProduct.Update(true); FieldLinkCreationInformation fieldLinkMaximumAge = new FieldLinkCreationInformation(); fieldLinkMaximumAge.Field = fieldMaximumAge; ctypeProduct.FieldLinks.Add(fieldLinkMaximumAge); ctypeProduct.Update(true); FieldLinkCreationInformation fieldLinkProductImageUrl = new FieldLinkCreationInformation(); fieldLinkProductImageUrl.Field = fieldProductImageUrl; ctypeProduct.FieldLinks.Add(fieldLinkProductImageUrl); ctypeProduct.Update(true); clientContext.ExecuteQuery(); }
private void AddSiteColumnsToContentType(ShContentType configContentType) { Log.Debug("Attempting to add fields to content type " + configContentType.DisplayName); Web web = ClientContext.Web; ContentTypeCollection contentTypes = web.ContentTypes; ClientContext.Load(contentTypes); ClientContext.ExecuteQuery(); ContentType contentType = contentTypes.GetById(configContentType.ID); FieldCollection webFields = web.Fields; ClientContext.Load(contentType); ClientContext.Load(webFields); ClientContext.ExecuteQuery(); foreach (var fieldName in configContentType.Fields) { // Need to load content type fields every iteration because fields are added to the collection Field webField = webFields.GetByInternalNameOrTitle(fieldName); FieldLinkCollection contentTypeFields = contentType.FieldLinks; ClientContext.Load(contentTypeFields); ClientContext.Load(webField); ClientContext.ExecuteQuery(); var fieldLink = contentTypeFields.FirstOrDefault(existingFieldName => existingFieldName.Name == fieldName); if (fieldLink == null) { var link = new FieldLinkCreationInformation { Field = webField }; fieldLink = contentType.FieldLinks.Add(link); } fieldLink.Required = configContentType.RequiredFields.Contains(fieldName); if (configContentType.HiddenFields.Contains(fieldName)) { fieldLink.Hidden = true; fieldLink.Required = false; //var hiddenField = contentType.Fields.FirstOrDefault(ct => ct.InternalName == fieldName); //if (hiddenField != null) //{ // hiddenField.Required = false; // hiddenField.Update(); //} } contentType.Update(true); ClientContext.ExecuteQuery(); } }
private static void AddFieldToContentType(ClientContext clientContext, Web oWeb, string columnName, string contentTypeName) { Field fieldName = oWeb.Fields.GetByInternalNameOrTitle(columnName); string contentTypeID = GetContentTypeIdByName(clientContext, contentTypeName); ContentType oContentType = oWeb.ContentTypes.GetById(contentTypeID); FieldLinkCreationInformation fdCI = new FieldLinkCreationInformation(); fdCI.Field = fieldName; oContentType.FieldLinks.Add(fdCI); oContentType.Update(true); clientContext.ExecuteQuery(); Console.WriteLine(columnName + " Site Column has been Added to " + contentTypeName + " Content Type"); }
private void BindFieldsToContentType(ClientContext clientContext, Web web, string contentTypeId) { ContentType ct = web.ContentTypes.GetById(contentTypeId); clientContext.Load(ct); List <string> fields = GetDemoFieldIds(); foreach (string str in fields) { FieldLinkCreationInformation fieldLink = new FieldLinkCreationInformation(); var field = web.Fields.GetById(new Guid(str)); fieldLink.Field = field; ct.FieldLinks.Add(fieldLink); } ct.Update(true); clientContext.ExecuteQuery(); }
private static void AddFieldToContentType(ContentType contentType, Field field, bool required, bool hidden) { if (!contentType.IsPropertyAvailable("Id")) { web.Context.Load(contentType, ct => ct.Id); web.Context.ExecuteQuery(); } if (!field.IsPropertyAvailable("Id")) { web.Context.Load(field, f => f.Id); web.Context.ExecuteQuery(); } // Get the field if already exists in content type, else add field to content type // This will help to customize (required or hidden) any pre-existing field, also to handle existing field of Parent Content type web.Context.Load(contentType.FieldLinks); web.Context.ExecuteQuery(); FieldLink flink = contentType.FieldLinks.FirstOrDefault(fld => fld.Id == field.Id); if (flink == null) { FieldLinkCreationInformation fldInfo = new FieldLinkCreationInformation(); fldInfo.Field = field; contentType.FieldLinks.Add(fldInfo); contentType.Update(true); web.Context.ExecuteQuery(); flink = contentType.FieldLinks.GetById(field.Id); } if (required || hidden) { // Update FieldLink flink.Required = required; flink.Hidden = hidden; contentType.Update(true); web.Context.ExecuteQuery(); } }
static void Main(string[] args) { string userName = "******"; Console.WriteLine("Enter your password."); SecureString password = getpassword(); using (var ctx = new ClientContext("https://sites.bms.com/sites/miketest")) { ctx.Credentials = new SharePointOnlineCredentials(userName, password); Web subsite = ctx.Web; ctx.Load(subsite); ctx.ExecuteQuery(); List userlist = subsite.Lists.GetByTitle("Clinical"); ctx.Load(subsite); ctx.ExecuteQuery(); ContentType ct = userlist.ContentTypes.GetById("0x010047A9C2CCA715F64E96F1FCA3603F845A"); ctx.Load(ct); ctx.ExecuteQuery(); Field column = userlist.Fields.GetByInternalNameOrTitle("console4"); ctx.Load(column); ctx.ExecuteQuery(); Console.WriteLine("Title: " + subsite.Title + "; URL: " + subsite.Url + "; column: " + column.InternalName); Console.ReadLine(); FieldLinkCollection addcolumntoct = ct.FieldLinks; ctx.Load(addcolumntoct); ctx.ExecuteQuery(); foreach (var item in addcolumntoct) { if (item.Name == "console4") { return; } } FieldLinkCreationInformation link = new FieldLinkCreationInformation(); link.Field = column; addcolumntoct.Add(link); ct.Update(false); ctx.ExecuteQuery(); } }
/// <summary> /// Add columns to content type. /// </summary> /// <param name="web">Object of site</param> /// <param name="siteColumns">List of site columns</param> /// <param name="finalObj">Content type to which columns are to be added</param> internal static void AddColumnsToContentType(Microsoft.SharePoint.Client.Web web, List <string> siteColumns, ContentType finalObj) { try { FieldCollection fieldCol = web.Fields; foreach (string columns in siteColumns) { Field customDoc = (from fld in fieldCol where fld.Title == columns && fld.TypeAsString == ServiceConstantStrings.OneDriveSiteColumnType select fld).FirstOrDefault(); FieldLinkCreationInformation fieldLinkCreationInfo = new FieldLinkCreationInformation(); fieldLinkCreationInfo.Field = customDoc; finalObj.FieldLinks.Add(fieldLinkCreationInfo); } finalObj.Update(true); } catch (Exception exception) { Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName); } }
private void AddFieldLinks(FieldCollection fieldCollection, bool isList, params string[] fieldsToAdd) { List <SPOField> fields = new List <SPOField>(); if (fieldsToAdd == null) { return; } var ctx = SPOSiteContext.CurrentSiteContext.Context; foreach (string fieldName in fieldsToAdd) { SPOField existingField = SPOField.GetField(ctx, fieldCollection, fieldName); if (existingField == null) { throw new ArgumentOutOfRangeException("Unable to locate field " + fieldName + "."); } else { fields.Add(existingField); } } if (fields.Count == 0) { return; } foreach (SPOField field in fields) { FieldLinkCreationInformation flci = new FieldLinkCreationInformation(); flci.Field = field.Field; this.ContentType.FieldLinks.Add(flci); } if (fields.Count > 0) { this.ContentType.Update(!isList); ctx.ExecuteQuery(); } }
/// <summary> /// /// </summary> /// <param name="web"></param> /// <param name="contentType"></param> /// <param name="field"></param> /// <param name="required"></param> /// <param name="hidden"></param> public static void AddFieldToContentType(this Web web, ContentType contentType, Field field, bool required = false, bool hidden = false) { FieldLinkCreationInformation fldInfo = new FieldLinkCreationInformation(); fldInfo.Field = field; contentType.FieldLinks.Add(fldInfo); contentType.Update(true); web.Context.ExecuteQuery(); web.Context.Load(field); web.Context.ExecuteQuery(); if (required || hidden) { //Update FieldLink FieldLink flink = contentType.FieldLinks.GetById(field.Id); flink.Required = required; flink.Hidden = hidden; contentType.Update(true); web.Context.ExecuteQuery(); } }
private static void AddSiteColumnToContentType(ClientContext cc, Web web) { ContentTypeCollection contentTypes = web.ContentTypes; cc.Load(contentTypes); cc.ExecuteQuery(); ContentType myContentType = contentTypes.GetById("0x0101009189AB5D3D2647B580F011DA2F356FB2"); cc.Load(myContentType); cc.ExecuteQuery(); FieldCollection fields = web.Fields; Field fld = fields.GetByInternalNameOrTitle("ContosoString"); cc.Load(fields); cc.Load(fld); cc.ExecuteQuery(); FieldLinkCollection refFields = myContentType.FieldLinks; cc.Load(refFields); cc.ExecuteQuery(); foreach (var item in refFields) { if (item.Name == "ContosoString") { return; } } // ref does nt FieldLinkCreationInformation link = new FieldLinkCreationInformation(); link.Field = fld; myContentType.FieldLinks.Add(link); myContentType.Update(true); cc.ExecuteQuery(); }
private ContentType CreateDocumentSetContentType(ClientContext clientContext, string contentTypeName, List <Field> fields) { ContentType ret = null; Web web = clientContext.Web; clientContext.Load(web, w => w.ContentTypes, w => w.Fields); clientContext.ExecuteQuery(); //Get default document set content type. ContentType ctDocumentSet = web.ContentTypes.FirstOrDefault(ct => ct.Name.IndexOf("document set", StringComparison.CurrentCultureIgnoreCase) != -1); ret = web.ContentTypes.FirstOrDefault(ct => ct.Name == contentTypeName); if (ret == null) { ContentTypeCreationInformation ctNewInfo = new ContentTypeCreationInformation(); ctNewInfo.Name = CONTENTTYPENAME; ctNewInfo.Description = CONTENTTYPENAME; ctNewInfo.Group = CONTENTTYPEGROUP; ctNewInfo.ParentContentType = ctDocumentSet; ret = web.ContentTypes.Add(ctNewInfo); } clientContext.Load(ret, ct => ct.FieldLinks, ct => ct.Id); clientContext.ExecuteQuery(); foreach (Field field in fields) { FieldLink flAuthor = ret.FieldLinks.FirstOrDefault(link => link.Name == field.InternalName); if (flAuthor == null) { FieldLinkCreationInformation fNewInfo = new FieldLinkCreationInformation(); fNewInfo.Field = field; ret.FieldLinks.Add(fNewInfo); ret.Update(true); clientContext.Load(ret, ct => ct.FieldLinks); clientContext.ExecuteQuery(); } } return(ret); }
private void AddSiteColumnsToContentType(GtContentType configContentType) { Web web = ClientContext.Web; ContentTypeCollection contentTypes = web.ContentTypes; ClientContext.Load(contentTypes); ClientContext.ExecuteQuery(); ContentType contentType = contentTypes.GetById(configContentType.ID); FieldCollection fields = web.Fields; ClientContext.Load(contentType); ClientContext.Load(fields); ClientContext.ExecuteQuery(); foreach (var fieldName in configContentType.Fields) { // Need to load content type fields every iteration because fields are added to the collection Field webField = fields.GetByInternalNameOrTitle(fieldName); FieldLinkCollection contentTypeFields = contentType.FieldLinks; ClientContext.Load(contentTypeFields); ClientContext.Load(webField); ClientContext.ExecuteQuery(); var fieldLink = contentTypeFields.FirstOrDefault(existingFieldName => existingFieldName.Name == fieldName); if (fieldLink == null) { var link = new FieldLinkCreationInformation { Field = webField }; fieldLink = contentType.FieldLinks.Add(link); } fieldLink.Required = configContentType.RequiredFields.Contains(fieldName); fieldLink.Hidden = configContentType.HiddenFields.Contains(fieldName); contentType.Update(true); ClientContext.ExecuteQuery(); } }
public static void AddExistingSiteColumnToContentType() { var clientContext = Helper.GetClientContext(); Web oWeb = clientContext.Web; Field age = oWeb.Fields.GetByInternalNameOrTitle("Age_SC"); Field sessionName = oWeb.Fields.GetByInternalNameOrTitle("SessionName_SC"); Field sessionPresenter = oWeb.Fields.GetByInternalNameOrTitle("SessionPresenter_SC"); string contentTypeID = GetContentTypeIDByName("Content Type Created By CSOM_WithRef"); ContentType contentTypeCreatedByCSOM_WithRef = oWeb.ContentTypes.GetById(contentTypeID); FieldLinkCreationInformation dd = new FieldLinkCreationInformation(); dd.Field = age; dd.Field = sessionName; dd.Field = sessionPresenter; contentTypeCreatedByCSOM_WithRef.FieldLinks.Add(dd); contentTypeCreatedByCSOM_WithRef.Update(true); clientContext.ExecuteQuery(); }
private void BindFieldsToContentType(Web web, string contentTypeId, IEnumerable <Field> fields) { var contentType = web.GetContentTypeById(contentTypeId); web.Context.Load(web.Fields); web.Context.Load(contentType.FieldLinks); web.Context.ExecuteQuery(); var missingFields = fields.Except(from f in fields join fl in contentType.FieldLinks on f.StaticName equals fl.Name select f); foreach (var field in missingFields) { var fieldLinkCreationInfo = new FieldLinkCreationInformation() { Field = field }; contentType.FieldLinks.Add(fieldLinkCreationInfo); } contentType.Update(false); contentType.Context.ExecuteQuery(); }
static void CreateProductContentType() { Console.WriteLine("Creating Product content type..."); ctypeProduct = CreateContentType("Product", "0x01"); // add site columns FieldLinkCreationInformation fieldLinkProductCode = new FieldLinkCreationInformation(); fieldLinkProductCode.Field = fieldProductCode; ctypeProduct.FieldLinks.Add(fieldLinkProductCode); ctypeProduct.Update(true); FieldLinkCreationInformation fieldLinkProductDescription = new FieldLinkCreationInformation(); fieldLinkProductDescription.Field = fieldProductDescription; ctypeProduct.FieldLinks.Add(fieldLinkProductDescription); ctypeProduct.Update(true); FieldLinkCreationInformation fieldLinkProductListPrice = new FieldLinkCreationInformation(); fieldLinkProductListPrice.Field = fieldProductListPrice; ctypeProduct.FieldLinks.Add(fieldLinkProductListPrice); ctypeProduct.Update(true); FieldLinkCreationInformation fieldLinkProductColor = new FieldLinkCreationInformation(); fieldLinkProductColor.Field = fieldProductColor; ctypeProduct.FieldLinks.Add(fieldLinkProductColor); ctypeProduct.Update(true); FieldLinkCreationInformation fieldLinkMinimumAge = new FieldLinkCreationInformation(); fieldLinkMinimumAge.Field = fieldMinimumAge; ctypeProduct.FieldLinks.Add(fieldLinkMinimumAge); ctypeProduct.Update(true); FieldLinkCreationInformation fieldLinkMaximumAge = new FieldLinkCreationInformation(); fieldLinkMaximumAge.Field = fieldMaximumAge; ctypeProduct.FieldLinks.Add(fieldLinkMaximumAge); ctypeProduct.Update(true); clientContext.ExecuteQuery(); }
private void LoadSiteColumn(ContentType targetContentType) { if (Fields != null && Fields.Count > 0) { foreach (var targetField in Fields) { if (targetField.CurrentField != null) { FieldLinkCreationInformation fldLink = new FieldLinkCreationInformation(); fldLink.Field = targetField.CurrentField; // If uou set this to "true", the column getting added to the content type will be added as "required" field fldLink.Field.Required = false; // If you set this to "true", the column getting added to the content type will be added as "hidden" field fldLink.Field.Hidden = false; targetContentType.FieldLinks.Add(fldLink); targetContentType.Update(false); context.ExecuteQuery(); } } } }
private void BindFieldsToContentType(ClientContext clientContext, Web web, string contentTypeId) { ContentType ct = web.ContentTypes.GetById(contentTypeId); clientContext.Load(ct); List<string> fields = GetDemoFieldIds(); foreach (string str in fields) { FieldLinkCreationInformation fieldLink = new FieldLinkCreationInformation(); var field = web.Fields.GetById(new Guid(str)); fieldLink.Field = field; ct.FieldLinks.Add(fieldLink); } ct.Update(true); clientContext.ExecuteQuery(); }
private void AddOrUpdateFieldOfContentType(ShContentType configContentType, FieldCollection webFields, string fieldName, ContentType contentType) { // Need to load content type fields every iteration because fields are added to the collection Field webField = webFields.GetByInternalNameOrTitle(fieldName); FieldLinkCollection contentTypeFields = contentType.FieldLinks; ClientContext.Load(contentTypeFields); ClientContext.Load(webField); ClientContext.ExecuteQuery(); var fieldLink = contentTypeFields.FirstOrDefault(existingFieldName => existingFieldName.Name == fieldName); if (fieldLink == null) { var link = new FieldLinkCreationInformation {Field = webField}; fieldLink = contentType.FieldLinks.Add(link); } fieldLink.Required = configContentType.RequiredFields.Contains(fieldName); fieldLink.Hidden = configContentType.HiddenFields.Contains(fieldName); contentType.Update(true); ClientContext.ExecuteQuery(); }
/// <summary> /// /// </summary> /// <param name="web"></param> /// <param name="contentType"></param> /// <param name="field"></param> /// <param name="required"></param> /// <param name="hidden"></param> public static void AddFieldToContentType(this Web web, ContentType contentType, Field field, bool required = false, bool hidden = false) { FieldLinkCreationInformation fldInfo = new FieldLinkCreationInformation(); fldInfo.Field = field; contentType.FieldLinks.Add(fldInfo); contentType.Update(true); web.Context.ExecuteQuery(); web.Context.Load(field); web.Context.ExecuteQuery(); if (required || hidden) { //Update FieldLink FieldLink flink = contentType.FieldLinks.GetById(field.Id); flink.Required = required; flink.Hidden = hidden; contentType.Update(true); web.Context.ExecuteQuery(); } }
protected override void ProcessRecord() { base.ProcessRecord(); var ctx = base.Context; Web web = ctx.Site.OpenWeb(Web.Read()); SPOContentType newContentType = null; SPOContentType parentContentType = ParentContentType.Read(web); if (parentContentType == null) { throw new ArgumentException("Unable to locate the specified parent content type."); } SPOContentType existingContentType = SPOContentType.GetContentType(ctx, web.AvailableContentTypes, Name); if (existingContentType != null) { WriteWarning("The content type \"" + Name + "\" already exists within the Site."); WriteObject(existingContentType); return; } List <SPOField> fields = new List <SPOField>(); if (FieldsToAdd != null) { foreach (string fieldName in FieldsToAdd) { SPOField existingField = SPOField.GetField(ctx, web.AvailableFields, fieldName); if (existingField == null) { WriteError(new ErrorRecord(new ArgumentOutOfRangeException("Unable to locate field " + fieldName + ". Content Type will not be created."), null, ErrorCategory.InvalidData, web.AvailableFields)); } else { fields.Add(existingField); } } if (fields.Count != FieldsToAdd.Length) { return; } } var ctli = new ContentTypeCreationInformation(); ctli.Description = Description; ctli.Group = Group; ctli.Name = Name; ctli.ParentContentType = parentContentType.ContentType; ContentType ct = web.ContentTypes.Add(ctli); ctx.ExecuteQuery(); SPOContentType.LoadContentType(ctx, ct); newContentType = new SPOContentType(ct); foreach (SPOField field in fields) { FieldLinkCreationInformation flci = new FieldLinkCreationInformation(); flci.Field = field.Field; newContentType.ContentType.FieldLinks.Add(flci); } if (fields.Count > 0) { newContentType.ContentType.Update(true); ctx.ExecuteQuery(); } WriteObject(newContentType); }
private void BindFieldsToContentType(Web web, string contentTypeId, IEnumerable<Field> fields) { var contentType = web.GetContentTypeById(contentTypeId); web.Context.Load(web.Fields); web.Context.Load(contentType.FieldLinks); web.Context.ExecuteQuery(); var missingFields = fields.Except(from f in fields join fl in contentType.FieldLinks on f.StaticName equals fl.Name select f); foreach (var field in missingFields) { var fieldLinkCreationInfo = new FieldLinkCreationInformation() { Field = field }; contentType.FieldLinks.Add(fieldLinkCreationInfo); } contentType.Update(false); contentType.Context.ExecuteQuery(); }
private void AddFields() { //Add the fields to each content type foreach (var creatorkey in Creators.Keys) { if (_createdContentTypes.Contains(creatorkey)) { OnNotify(ProvisioningNotificationLevels.Verbose, "Processing fields for content type " + creatorkey); var creator = Creators[creatorkey]; if (creator.Fields != null) { var fieldsToAdd = new List <string>(creator.Fields); foreach (var fl in creator.ContentType.FieldLinks) { if (fieldsToAdd.Contains(fl.Name)) { //Hack attempt to force update of lists with this type fl.Required = fl.Required; fieldsToAdd.Remove(fl.Name); } //HACK: SharePoint's event type and calendar list are shit! if (fl.Name == "EventDate" && fieldsToAdd.Contains("StartDate")) { fieldsToAdd.Remove("StartDate"); } if (fl.Name == "Description" && fieldsToAdd.Contains("Comments")) { fieldsToAdd.Remove("Comments"); } } foreach (var fieldKey in fieldsToAdd) { var info = new FieldLinkCreationInformation { Field = _siteFields[fieldKey] }; creator.ContentType.FieldLinks.Add(info); } //Must save at this point to be able to remove undesired fields as the next step creator.ContentType.Name = creatorkey; creator.ContentType.Update(true); _ctx.ExecuteQueryRetry(); if (creator.RemoveFields != null && creator.RemoveFields.Count > 0) { //Refresh the FieldLinks because some nay have been added _ctx.Load(creator.ContentType, c => c.Name, c => c.FieldLinks); _ctx.ExecuteQueryRetry(); foreach (var fieldToRemove in creator.RemoveFields) { foreach (var fl in creator.ContentType.FieldLinks) { if (fl.Name == fieldToRemove) { fl.DeleteObject(); break; } } } } if (creator.OrderedFields != null && creator.OrderedFields.Count > 0) { var reorder = creator.OrderedFields.ToArray(); creator.ContentType.FieldLinks.Reorder(reorder); } creator.ContentType.Update(true); } } _ctx.ExecuteQueryRetry(); } }
//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(); } }
static void ExtendProductContentType() { Console.WriteLine(); Console.WriteLine("Extending Product content type with ProductImageUrl site column"); clientContext.Load(site.ContentTypes); clientContext.ExecuteQuery(); ContentType ctypeProduct = site.ContentTypes.Where(cType => cType.Name.Equals("Product")).First(); clientContext.Load(ctypeProduct); clientContext.ExecuteQuery(); try { FieldLinkCreationInformation fieldLinkProductImageUrl = new FieldLinkCreationInformation(); fieldLinkProductImageUrl.Field = fieldProductImageUrl; ctypeProduct.FieldLinks.Add(fieldLinkProductImageUrl); ctypeProduct.Update(true); clientContext.ExecuteQuery(); } catch { } clientContext.Load(listProducts.DefaultView); clientContext.Load(listProducts.DefaultView.ViewFields); clientContext.ExecuteQuery(); listProducts.DefaultView.ViewFields.Add("ProductImageUrl"); listProducts.DefaultView.Update(); listProducts.Update(); clientContext.ExecuteQuery(); }
protected override void ProcessRecord() { base.ProcessRecord(); var ctx = base.Context; Web web = ctx.Site.OpenWeb(Web.Read()); SPOContentType newContentType = null; SPOContentType parentContentType = ParentContentType.Read(web); if (parentContentType == null) { throw new ArgumentException("Unable to locate the specified parent content type."); } SPOContentType existingContentType = SPOContentType.GetContentType(ctx, web.AvailableContentTypes, Name); if (existingContentType != null) { WriteWarning("The content type \"" + Name + "\" already exists within the Site."); WriteObject(existingContentType); return; } List<SPOField> fields = new List<SPOField>(); if (FieldsToAdd != null) { foreach (string fieldName in FieldsToAdd) { SPOField existingField = SPOField.GetField(ctx, web.AvailableFields, fieldName); if (existingField == null) WriteError(new ErrorRecord(new ArgumentOutOfRangeException("Unable to locate field " + fieldName + ". Content Type will not be created."), null, ErrorCategory.InvalidData, web.AvailableFields)); else fields.Add(existingField); } if (fields.Count != FieldsToAdd.Length) return; } var ctli = new ContentTypeCreationInformation(); ctli.Description = Description; ctli.Group = Group; ctli.Name = Name; ctli.ParentContentType = parentContentType.ContentType; ContentType ct = web.ContentTypes.Add(ctli); ctx.ExecuteQuery(); SPOContentType.LoadContentType(ctx, ct); newContentType = new SPOContentType(ct); foreach (SPOField field in fields) { FieldLinkCreationInformation flci = new FieldLinkCreationInformation(); flci.Field = field.Field; newContentType.ContentType.FieldLinks.Add(flci); } if (fields.Count > 0) { newContentType.ContentType.Update(true); ctx.ExecuteQuery(); } WriteObject(newContentType); }
protected void CSOMButton_Click(object sender, EventArgs e) { var spContext = SharePointContextProvider.Current.GetSharePointContext(Context); using (var clientContext = spContext.CreateUserClientContextForSPHost()) { Web web = clientContext.Web; // Create Content Type on host web ContentTypeCreationInformation newCt = new ContentTypeCreationInformation(); newCt.Name = "CSOM Item"; newCt.Id = "0x010078874F9C61114245806D6F09BC0362F8"; newCt.Group = "A Lab"; ContentType myContentType = web.ContentTypes.Add(newCt); FieldCollection fields = web.Fields; clientContext.Load(fields); clientContext.ExecuteQuery(); // Add field to content type Field field = fields.GetByInternalNameOrTitle("Categories"); FieldLinkCreationInformation link = new FieldLinkCreationInformation(); link.Field = field; myContentType.FieldLinks.Add(link); myContentType.Update(true); clientContext.ExecuteQuery(); // Create list on host web var list = web.Lists.Add(new ListCreationInformation { Title = "CSOM", Url = "lists/csom", TemplateType = (int)ListTemplateType.GenericList }); clientContext.Load(list); clientContext.ExecuteQuery(); // Add Content Type to list list.ContentTypesEnabled = true; list.Update(); list.ContentTypes.AddExistingContentType(myContentType); clientContext.ExecuteQuery(); // Add a view to list var view = list.Views.Add(new ViewCreationInformation { Title = "New View", ViewTypeKind = ViewType.Html, RowLimit = 10, ViewFields = new[] { "Title", "Categories" }, SetAsDefaultView = true, Paged = false }); clientContext.Load(view); clientContext.ExecuteQuery(); // Set a property bag value var properties = clientContext.Web.AllProperties; clientContext.Load(properties); clientContext.ExecuteQuery(); properties["ourwebkey"] = Guid.NewGuid().ToString(); clientContext.Web.Update(); clientContext.ExecuteQuery(); // Make property bag value searchable // TBD } }
/// <summary> /// Add columns to content type. /// </summary> /// <param name="web">Object of site</param> /// <param name="siteColumns">List of site columns</param> /// <param name="finalObj">Content type to which columns are to be added</param> internal static void AddColumnsToContentType(Microsoft.SharePoint.Client.Web web, List<string> siteColumns, ContentType finalObj) { try { FieldCollection fieldCol = web.Fields; foreach (string columns in siteColumns) { Field customDoc = (from fld in fieldCol where fld.Title == columns && fld.TypeAsString == ServiceConstantStrings.OneDriveSiteColumnType select fld).FirstOrDefault(); FieldLinkCreationInformation fieldLinkCreationInfo = new FieldLinkCreationInformation(); fieldLinkCreationInfo.Field = customDoc; finalObj.FieldLinks.Add(fieldLinkCreationInfo); } finalObj.Update(true); } catch (Exception exception) { Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName); } }
/// <summary> /// Provision a list to the specified web using the list definition /// </summary> /// <param name="web">Client Context web</param> /// <param name="listDef">Hydrated list definition from JSON or Object</param> /// <param name="loggerVerbose">TODO: convert to static logger</param> /// <param name="loggerWarning">TODO: convert to static logger</param> /// <param name="loggerError">TODO: convert to static logger</param> /// <param name="SiteGroups">Collection of provisioned SharePoint group for field definitions</param> /// <param name="JsonFilePath">(OPTIONAL) file path to JSON folder</param> public static void CreateListFromDefinition(this Web web, SPListDefinition listDef, Action <string, string[]> loggerVerbose, Action <string, string[]> loggerWarning, Action <Exception, string, string[]> loggerError, List <SPGroupDefinitionModel> SiteGroups = null, string JsonFilePath = null) { var webContext = web.Context; var siteColumns = new List <SPFieldDefinitionModel>(); var afterProvisionChanges = false; // Content Type var listName = listDef.ListName; var listDescription = listDef.ListDescription; // check to see if Picture library named Photos already exists ListCollection allLists = web.Lists; IEnumerable <List> foundLists = webContext.LoadQuery(allLists.Where(list => list.Title == listName) .Include(arl => arl.Title, arl => arl.Id, arl => arl.ContentTypes, ol => ol.RootFolder, ol => ol.EnableVersioning, ol => ol.EnableFolderCreation, ol => ol.ContentTypesEnabled)); webContext.ExecuteQueryRetry(); List listToProvision = foundLists.FirstOrDefault(); if (listToProvision == null) { ListCreationInformation listToProvisionInfo = listDef.ToCreationObject(); listToProvision = web.Lists.Add(listToProvisionInfo); webContext.Load(listToProvision, arl => arl.Title, arl => arl.Id, arl => arl.ContentTypes, ol => ol.RootFolder, ol => ol.EnableVersioning, ol => ol.EnableFolderCreation, ol => ol.ContentTypesEnabled); webContext.ExecuteQuery(); } if (listDef.Versioning && !listToProvision.EnableVersioning) { afterProvisionChanges = true; listToProvision.EnableVersioning = true; if (listDef.ListTemplate == ListTemplateType.DocumentLibrary) { listToProvision.EnableMinorVersions = true; } } if (listDef.ContentTypeEnabled && !listToProvision.ContentTypesEnabled) { afterProvisionChanges = true; listToProvision.ContentTypesEnabled = true; } if (listDef.EnableFolderCreation && !listToProvision.EnableFolderCreation) { afterProvisionChanges = true; listToProvision.EnableFolderCreation = true; } if (afterProvisionChanges) { listToProvision.Update(); webContext.Load(listToProvision); webContext.ExecuteQueryRetry(); } webContext.Load(listToProvision, arl => arl.Title, arl => arl.Id, arl => arl.ContentTypes, ol => ol.RootFolder, ol => ol.EnableVersioning, ol => ol.EnableFolderCreation, ol => ol.ContentTypesEnabled); webContext.ExecuteQuery(); if (listDef.ContentTypeEnabled && listDef.HasContentTypes) { foreach (var contentDef in listDef.ContentTypes) { if (!listToProvision.ContentTypeExistsByName(contentDef.Name)) { var ctypeInfo = contentDef.ToCreationObject(); var accessContentType = listToProvision.ContentTypes.Add(ctypeInfo); listToProvision.Update(); webContext.Load(accessContentType, tycp => tycp.Id, tycp => tycp.Name); webContext.ExecuteQueryRetry(); if (contentDef.DefaultContentType) { listToProvision.SetDefaultContentTypeToList(accessContentType); } } } } // Site Columns foreach (var fieldDef in listDef.FieldDefinitions) { var column = listToProvision.CreateListColumn(fieldDef, loggerVerbose, loggerWarning, SiteGroups, JsonFilePath); if (column == null) { loggerWarning("Failed to create column {0}.", new string[] { fieldDef.InternalName }); } else { siteColumns.Add(new SPFieldDefinitionModel() { InternalName = column.InternalName, DisplayName = column.Title, FieldGuid = column.Id }); } } if (listDef.ContentTypeEnabled && listDef.HasContentTypes) { foreach (var contentDef in listDef.ContentTypes) { var contentTypeName = contentDef.Name; var accessContentTypes = listToProvision.ContentTypes; IEnumerable <ContentType> allContentTypes = webContext.LoadQuery(accessContentTypes.Where(f => f.Name == contentTypeName).Include(tcyp => tcyp.Id, tcyp => tcyp.Name)); webContext.ExecuteQueryRetry(); if (allContentTypes != null) { var accessContentType = allContentTypes.FirstOrDefault(); foreach (var fieldInternalName in contentDef.FieldLinkRefs) { var column = siteColumns.FirstOrDefault(f => f.InternalName == fieldInternalName); if (column != null) { var fieldLinks = accessContentType.FieldLinks; webContext.Load(fieldLinks, cf => cf.Include(inc => inc.Id, inc => inc.Name)); webContext.ExecuteQueryRetry(); var convertedInternalName = column.DisplayNameMasked; if (!fieldLinks.Any(a => a.Name == column.InternalName || a.Name == convertedInternalName)) { loggerVerbose("Content Type {0} Adding Field {1}", new string[] { contentTypeName, column.InternalName }); var siteColumn = listToProvision.GetFieldById <Field>(column.FieldGuid); webContext.ExecuteQueryRetry(); var flink = new FieldLinkCreationInformation(); flink.Field = siteColumn; var flinkstub = accessContentType.FieldLinks.Add(flink); //if(fieldDef.Required) flinkstub.Required = fieldDef.Required; accessContentType.Update(false); webContext.ExecuteQueryRetry(); } } else { loggerWarning("Failed to create column {0}.", new string[] { fieldInternalName }); } } } } } // Views if (listDef.Views != null && listDef.Views.Count() > 0) { ViewCollection views = listToProvision.Views; webContext.Load(views, f => f.Include(inc => inc.Id, inc => inc.Hidden, inc => inc.Title, inc => inc.DefaultView)); webContext.ExecuteQueryRetry(); foreach (var viewDef in listDef.Views) { try { if (views.Any(v => v.Title.Equals(viewDef.Title, StringComparison.CurrentCultureIgnoreCase))) { loggerVerbose("View {0} found in list {1}", new string[] { viewDef.Title, listName }); continue; } var view = listToProvision.CreateView(viewDef.InternalName, viewDef.ViewCamlType, viewDef.FieldRefName, viewDef.RowLimit, viewDef.DefaultView, viewDef.QueryXml, viewDef.PersonalView, viewDef.PagedView); webContext.Load(view, v => v.Title, v => v.Id, v => v.ServerRelativeUrl); webContext.ExecuteQueryRetry(); view.Title = viewDef.Title; if (viewDef.HasJsLink) { view.JSLink = viewDef.JsLink; } view.Update(); webContext.ExecuteQueryRetry(); } catch (Exception ex) { loggerError(ex, "Failed to create view {0} with XML:{1}", new string[] { viewDef.Title, viewDef.QueryXml }); } } } // List Data upload if (listDef.ListItems != null && listDef.ListItems.Count() > 0) { foreach (var listItem in listDef.ListItems) { // Process the record into the notification email list var itemCreateInfo = new ListItemCreationInformation(); var newSPListItem = listToProvision.AddItem(itemCreateInfo); newSPListItem["Title"] = listItem.Title; foreach (var listItemData in listItem.ColumnValues) { newSPListItem[listItemData.FieldName] = listItemData.FieldValue; } newSPListItem.Update(); webContext.ExecuteQueryRetry(); } } }
/// <summary> /// Process the request /// </summary> public override void ExecuteCmdlet() { base.ExecuteCmdlet(); // Initialize logging instance with Powershell logger ITraceLogger logger = new DefaultUsageLogger(LogVerbose, LogWarning, LogError); // SharePoint URI for XML parsing XNamespace ns = "http://schemas.microsoft.com/sharepoint/"; // Definition file to operate on SiteProvisionerModel siteDefinition = null; try { // Retreive JSON Provisioner file and deserialize it var filePath = new System.IO.FileInfo(this.ProvisionerFilePath); var filePathJSON = System.IO.File.ReadAllText(filePath.FullName); siteDefinition = JsonConvert.DeserializeObject <SiteProvisionerModel>(filePathJSON); } catch (Exception ex) { logger.LogError(ex, "Failed to parse {0} Exception {1}", ProvisionerFilePath, ex.Message); return; } if (ValidateJson) { logger.LogInformation("The file {0} is valid.", ProvisionerFilePath); return; } var provisionerChoices = siteDefinition.FieldChoices; // Load the Context var contextWeb = this.ClientContext.Web; this.ClientContext.Load(contextWeb, ctxw => ctxw.ServerRelativeUrl, ctxw => ctxw.Id, ctxw => ctxw.Fields.Include(inc => inc.InternalName, inc => inc.JSLink, inc => inc.Title, inc => inc.Id)); // All Site Columns var siteFields = this.ClientContext.LoadQuery(ClientContext.Web.AvailableFields .Include(inc => inc.InternalName, inc => inc.JSLink, inc => inc.Title, inc => inc.Id)); // pull Site Groups var groupQuery = this.ClientContext.LoadQuery(contextWeb.SiteGroups .Include(group => group.Id, group => group.Title, group => group.Description, group => group.AllowRequestToJoinLeave, group => group.AllowMembersEditMembership, group => group.AutoAcceptRequestToJoinLeave, group => group.OnlyAllowMembersViewMembership, group => group.RequestToJoinLeaveEmailSetting)); var contentTypes = this.ClientContext.LoadQuery(contextWeb.ContentTypes .Include( ict => ict.Id, ict => ict.Group, ict => ict.Description, ict => ict.Name, ict => ict.Hidden, ict => ict.JSLink, ict => ict.FieldLinks, ict => ict.Fields)); var collists = contextWeb.Lists; var lists = this.ClientContext.LoadQuery(collists .Include( linc => linc.Title, linc => linc.Id, linc => linc.Description, linc => linc.Hidden, linc => linc.OnQuickLaunch, linc => linc.BaseTemplate, linc => linc.ContentTypesEnabled, linc => linc.AllowContentTypes, linc => linc.EnableFolderCreation, linc => linc.IsApplicationList, linc => linc.IsCatalog, linc => linc.IsSiteAssetsLibrary, linc => linc.IsPrivate, linc => linc.IsSystemList, linc => linc.Views, linc => linc.Fields .Include( lft => lft.Id, lft => lft.AutoIndexed, lft => lft.CanBeDeleted, lft => lft.DefaultFormula, lft => lft.DefaultValue, lft => lft.Group, lft => lft.Description, lft => lft.EnforceUniqueValues, lft => lft.FieldTypeKind, lft => lft.Filterable, lft => lft.Hidden, lft => lft.Indexed, lft => lft.InternalName, lft => lft.JSLink, lft => lft.NoCrawl, lft => lft.ReadOnlyField, lft => lft.Required, lft => lft.SchemaXml, lft => lft.Scope, lft => lft.Title ), linc => linc.ContentTypes .Include( ict => ict.Id, ict => ict.Group, ict => ict.Description, ict => ict.Name, ict => ict.Hidden, ict => ict.JSLink, ict => ict.FieldLinks, ict => ict.Fields)).Where(w => !w.IsSystemList && !w.IsSiteAssetsLibrary)); this.ClientContext.ExecuteQueryRetry(); // creates groups contextWeb.Context.Load(contextWeb, hw => hw.CurrentUser); contextWeb.Context.ExecuteQueryRetry(); if (ProvisionGroups) { if (siteDefinition.Groups != null && siteDefinition.Groups.Any()) { logger.LogInformation("Group collection will be provisioned for {0} groups", siteDefinition.Groups.Count()); foreach (var groupDef in siteDefinition.Groups) { if (groupQuery.Any(g => g.Title.Equals(groupDef.Title, StringComparison.CurrentCultureIgnoreCase))) { var group = groupQuery.FirstOrDefault(g => g.Title.Equals(groupDef.Title, StringComparison.CurrentCultureIgnoreCase)); SiteGroups.Add(new SPGroupDefinitionModel() { Id = group.Id, Title = group.Title }); } else { var newgroup = contextWeb.GetOrCreateSiteGroups(groupDef); SiteGroups.Add(new SPGroupDefinitionModel() { Id = newgroup.Id, Title = newgroup.Title }); } } } } else { // we aren't going to examine the JSON to provision groups, pull from current SharePoint instance SiteGroups.AddRange(groupQuery.Select(gq => new SPGroupDefinitionModel() { Id = gq.Id, Title = gq.Title })); } // provision columns // Site Columns if (siteDefinition.FieldDefinitions != null && siteDefinition.FieldDefinitions.Any()) { logger.LogInformation("Field definitions will be provisioned for {0} fields", siteDefinition.FieldDefinitions.Count()); foreach (var fieldDef in siteDefinition.FieldDefinitions) { var column = contextWeb.CreateColumn(fieldDef, logger, SiteGroups, siteDefinition.FieldChoices); if (column == null) { logger.LogWarning("Failed to create column {0}.", fieldDef.InternalName); } else { SiteColumns.Add(new SPFieldDefinitionModel() { InternalName = column.InternalName, Title = column.Title, FieldGuid = column.Id }); } } } // provision content types if (siteDefinition.ContentTypes != null && siteDefinition.ContentTypes.Any()) { logger.LogInformation("Content types will be provisioned for {0} ctypes", siteDefinition.ContentTypes.Count()); foreach (var contentDef in siteDefinition.ContentTypes) { var contentTypeName = contentDef.Name; var contentTypeId = contentDef.ContentTypeId; if (!contextWeb.ContentTypeExistsByName(contentTypeName) && !contextWeb.ContentTypeExistsById(contentTypeId)) { logger.LogInformation("Provisioning content type {0}", contentTypeName); contextWeb.CreateContentType(contentTypeName, contentTypeId, (string.IsNullOrEmpty(contentDef.ContentTypeGroup) ? "CustomColumn" : contentDef.ContentTypeGroup)); } var provisionedContentType = contextWeb.GetContentTypeByName(contentTypeName, true); if (provisionedContentType != null) { logger.LogInformation("Found content type {0} and is read only {1}", contentTypeName, provisionedContentType.ReadOnly); if (!provisionedContentType.ReadOnly) { foreach (var fieldDef in contentDef.FieldLinks) { // Check if FieldLink exists in the Content Type if (!contextWeb.FieldExistsByNameInContentType(contentTypeName, fieldDef.Name)) { // Check if FieldLInk column is in the collection of FieldDefinition var siteColumn = siteDefinition.FieldDefinitions.FirstOrDefault(f => f.InternalName == fieldDef.Name); if (siteColumn != null && !contextWeb.FieldExistsByNameInContentType(contentTypeName, siteColumn.DisplayNameMasked)) { var column = this.SiteColumns.FirstOrDefault(f => f.InternalName == fieldDef.Name); if (column == null) { logger.LogWarning("Column {0} was not added to the collection", fieldDef.Name); } else { contextWeb.AddFieldToContentTypeByName(contentTypeName, column.FieldGuid, siteColumn.Required); } } } } } } } } // provision lists var listtoprocess = siteDefinition.Lists.OrderBy(w => w.ProvisionOrder).ToList(); listtoprocess.ForEach(listDef => { // Content Type var listName = listDef.ListName; var listDescription = listDef.ListDescription; // provision the list definition var siteList = contextWeb.CreateListFromDefinition(listDef, provisionerChoices); if (listDef.ContentTypeEnabled && listDef.HasContentTypes) { if (listDef.ContentTypes != null && listDef.ContentTypes.Any()) { logger.LogInformation("List {0} => Content types will be provisioned for {1} ctypes", listDef.ListName, listDef.ContentTypes.Count()); foreach (var contentDef in listDef.ContentTypes) { var contentTypeName = contentDef.Name; ContentType accessContentType = null; if (!contextWeb.ContentTypeExistsByName(listName, contentTypeName)) { if (siteDefinition.ContentTypes != null && siteDefinition.ContentTypes.Any(ct => ct.Name == contentTypeName)) { contextWeb.AddContentTypeToListByName(listName, contentTypeName, true); accessContentType = siteList.GetContentTypeByName(contentTypeName); } else { var ctypeInfo = contentDef.ToCreationObject(); accessContentType = siteList.ContentTypes.Add(ctypeInfo); siteList.Update(); siteList.Context.Load(accessContentType, tycp => tycp.Id, tycp => tycp.Name); siteList.Context.ExecuteQueryRetry(); } if (contentDef.DefaultContentType) { siteList.SetDefaultContentType(accessContentType.Id); } } } } } // Existing columns var internalNamesForList = listDef.FieldDefinitions.Select(s => s.InternalName).ToArray(); var internalNamesFoundInList = new List <string>(); try { var existingListColumns = siteList.GetFields(internalNamesForList); foreach (var column in existingListColumns) { ListColumns.Add(new SPFieldDefinitionModel() { InternalName = column.InternalName, Title = column.Title, FieldGuid = column.Id }); internalNamesFoundInList.Add(column.InternalName); } } catch (Exception ex) { logger.LogError(ex, "List {0} => failed to query columns by internal names {1}", listDef.ListName, ex.Message); } // List Columns var nonExistingListColumns = listDef.FieldDefinitions.Where(fd => !internalNamesFoundInList.Any(inf => fd.InternalName.Equals(inf, StringComparison.InvariantCultureIgnoreCase))); foreach (var fieldDef in nonExistingListColumns) { if (fieldDef.FromBaseType == true && fieldDef.SourceID.IndexOf(ns.NamespaceName, StringComparison.CurrentCultureIgnoreCase) > -1) { // OOTB Column var hostsitecolumn = siteFields.FirstOrDefault(fd => fd.InternalName == fieldDef.InternalName); if (hostsitecolumn != null && !siteList.FieldExistsByName(hostsitecolumn.InternalName)) { var column = siteList.Fields.Add(hostsitecolumn); siteList.Update(); siteList.Context.Load(column, cctx => cctx.Id, cctx => cctx.InternalName); siteList.Context.ExecuteQueryRetry(); } var sourceListColumns = siteList.GetFields(fieldDef.InternalName); foreach (var column in sourceListColumns) { ListColumns.Add(new SPFieldDefinitionModel() { InternalName = column.InternalName, Title = column.Title, FieldGuid = column.Id }); } } else if (fieldDef.FieldTypeKind == FieldType.Invalid && fieldDef.FieldTypeKindText.IndexOf("TaxonomyFieldType", StringComparison.InvariantCultureIgnoreCase) > -1) { // Taxonomy Column var hostsitecolumn = siteFields.FirstOrDefault(fd => fd.InternalName == fieldDef.InternalName); if (hostsitecolumn != null && !siteList.FieldExistsByName(hostsitecolumn.InternalName)) { var column = siteList.Fields.Add(hostsitecolumn); siteList.Update(); siteList.Context.Load(column, cctx => cctx.Id, cctx => cctx.InternalName); siteList.Context.ExecuteQueryRetry(); } var sourceListColumns = siteList.GetFields(fieldDef.InternalName); foreach (var column in sourceListColumns) { ListColumns.Add(new SPFieldDefinitionModel() { InternalName = column.InternalName, Title = column.Title, FieldGuid = column.Id }); } } else { var column = siteList.CreateListColumn(fieldDef, logger, SiteGroups, provisionerChoices); if (column == null) { logger.LogWarning("Failed to create column {0}.", fieldDef.InternalName); } else { ListColumns.Add(new SPFieldDefinitionModel() { InternalName = column.InternalName, Title = column.Title, FieldGuid = column.Id }); } } } // Where content types are enabled // Add the provisioned site columns or list columns to the content type if (listDef.ContentTypeEnabled && listDef.HasContentTypes) { foreach (var contentDef in listDef.ContentTypes) { var contentTypeName = contentDef.Name; var accessContentTypes = siteList.ContentTypes; IEnumerable <ContentType> allContentTypes = contextWeb.Context.LoadQuery(accessContentTypes.Where(f => f.Name == contentTypeName).Include(tcyp => tcyp.Id, tcyp => tcyp.Name)); contextWeb.Context.ExecuteQueryRetry(); if (allContentTypes != null) { var accessContentType = allContentTypes.FirstOrDefault(); foreach (var fieldInternalName in contentDef.FieldLinks) { var column = ListColumns.FirstOrDefault(f => f.InternalName == fieldInternalName.Name); if (column == null) { logger.LogWarning("List {0} => Failed to associate field link {1}.", listDef.ListName, fieldInternalName.Name); continue; } var fieldLinks = accessContentType.FieldLinks; contextWeb.Context.Load(fieldLinks, cf => cf.Include(inc => inc.Id, inc => inc.Name)); contextWeb.Context.ExecuteQueryRetry(); var convertedInternalName = column.DisplayNameMasked; if (!fieldLinks.Any(a => a.Name == column.InternalName || a.Name == convertedInternalName)) { logger.LogInformation("List {0} => Content Type {1} Adding Field {2}", listDef.ListName, contentTypeName, column.InternalName); var siteColumn = siteList.GetFieldById <Field>(column.FieldGuid); contextWeb.Context.ExecuteQueryRetry(); var flink = new FieldLinkCreationInformation { Field = siteColumn }; var flinkstub = accessContentType.FieldLinks.Add(flink); //if(fieldDef.Required) flinkstub.Required = fieldDef.Required; accessContentType.Update(false); contextWeb.Context.ExecuteQueryRetry(); } } } } } // Views if (listDef.Views != null && listDef.Views.Any()) { ViewCollection views = siteList.Views; contextWeb.Context.Load(views, f => f.Include(inc => inc.Id, inc => inc.Hidden, inc => inc.Title, inc => inc.DefaultView)); contextWeb.Context.ExecuteQueryRetry(); foreach (var modelView in listDef.Views) { try { var updatecaml = false; View view = null; if (views.Any(v => v.Title.Equals(modelView.Title, StringComparison.CurrentCultureIgnoreCase))) { logger.LogInformation("List {0} => View {1} found in list", listName, modelView.Title); view = views.FirstOrDefault(v => v.Title.Equals(modelView.Title, StringComparison.CurrentCultureIgnoreCase)); updatecaml = true; } else { logger.LogInformation("List {0} => Creating View {0} in list", listName, modelView.Title); view = siteList.CreateView(modelView.CalculatedInternalName, modelView.ViewCamlType, modelView.FieldRefName.ToArray(), modelView.RowLimit, modelView.DefaultView, modelView.ViewQuery, modelView.PersonalView, modelView.Paged); } // grab the view properties from the object view.EnsureProperties( mview => mview.Title, mview => mview.Scope, mview => mview.AggregationsStatus, mview => mview.Aggregations, mview => mview.DefaultView, mview => mview.Hidden, mview => mview.Toolbar, mview => mview.JSLink, mview => mview.ViewFields, vctx => vctx.ViewQuery ); if (modelView.FieldRefName != null && modelView.FieldRefName.Any()) { var currentFields = view.ViewFields; currentFields.RemoveAll(); modelView.FieldRefName.ToList().ForEach(vField => { currentFields.Add(vField.Trim()); }); } if (!string.IsNullOrEmpty(modelView.Aggregations)) { view.Aggregations = modelView.Aggregations; view.AggregationsStatus = modelView.AggregationsStatus; } if (modelView.Hidden.HasValue && modelView.Hidden == true) { view.Hidden = modelView.Hidden.Value; } if (modelView.ToolBarType.HasValue) { view.Toolbar = string.Format("<Toolbar Type=\"{0}\"/>", modelView.ToolBarType.ToString()); } if (updatecaml) { view.DefaultView = modelView.DefaultView; view.RowLimit = modelView.RowLimit; view.ViewQuery = modelView.ViewQuery; } if (modelView.HasJsLink && modelView.JsLink.IndexOf("clienttemplates.js") == -1) { view.JSLink = modelView.JsLink; } view.Scope = modelView.Scope; view.Title = modelView.Title; view.Update(); contextWeb.Context.Load(view, v => v.Title, v => v.Id, v => v.ServerRelativeUrl); contextWeb.Context.ExecuteQueryRetry(); } catch (Exception ex) { logger.LogError(ex, "List {0} => Failed to create view {1} with XML:{2}", listDef.ListName, modelView.Title, modelView.ViewQuery); } } } }); }
private static void AddSiteColumnToContentType(ClientContext cc, Web web) { ContentTypeCollection contentTypes = web.ContentTypes; cc.Load(contentTypes); cc.ExecuteQuery(); ContentType myContentType = contentTypes.GetById("0x0101009189AB5D3D2647B580F011DA2F356FB2"); cc.Load(myContentType); cc.ExecuteQuery(); FieldCollection fields = web.Fields; Field fld = fields.GetByInternalNameOrTitle("ContosoString"); cc.Load(fields); cc.Load(fld); cc.ExecuteQuery(); FieldLinkCollection refFields = myContentType.FieldLinks; cc.Load(refFields); cc.ExecuteQuery(); foreach (var item in refFields) { if (item.Name == "ContosoString") return; } // ref does nt FieldLinkCreationInformation link = new FieldLinkCreationInformation(); link.Field = fld; myContentType.FieldLinks.Add(link); myContentType.Update(true); cc.ExecuteQuery(); }
private void AddFieldLinks(FieldCollection fieldCollection, bool isList, params string[] fieldsToAdd) { List<SPOField> fields = new List<SPOField>(); if (fieldsToAdd == null) return; var ctx = SPOSiteContext.CurrentSiteContext.Context; foreach (string fieldName in fieldsToAdd) { SPOField existingField = SPOField.GetField(ctx, fieldCollection, fieldName); if (existingField == null) throw new ArgumentOutOfRangeException("Unable to locate field " + fieldName + "."); else fields.Add(existingField); } if (fields.Count == 0) return; foreach (SPOField field in fields) { FieldLinkCreationInformation flci = new FieldLinkCreationInformation(); flci.Field = field.Field; this.ContentType.FieldLinks.Add(flci); } if (fields.Count > 0) { this.ContentType.Update(!isList); ctx.ExecuteQuery(); } }
/// <summary> /// Method to add columns to Content Type /// </summary> /// <param name="web">Object of site</param> /// <param name="siteColumns">List of site columns</param> /// <param name="finalObj">Content type to which columns are to be added</param> /// <returns>Success or Failure</returns> private static bool AddColumnsToContentType(Web web, List<string> siteColumns, ContentType finalObj) { try { FieldCollection fieldCol = web.Fields; foreach (string columns in siteColumns) { bool isColumnExists = (null != finalObj.Fields.Where(field => field.Title.Equals(columns, StringComparison.OrdinalIgnoreCase)).FirstOrDefault()) ? true : false; if (!isColumnExists) { Field customDoc = fieldCol.GetByTitle(columns); FieldLinkCreationInformation fieldCreationInformation = new FieldLinkCreationInformation(); fieldCreationInformation.Field = customDoc; finalObj.FieldLinks.Add(fieldCreationInformation); } } finalObj.Update(true); return true; } catch (Exception exception) { ErrorLogger.LogErrorToTextFile(errorFilePath, "Message: " + exception.Message + "\nStacktrace: " + exception.StackTrace); return false; } }
//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(); } }
private ContentType CreateDocumentSetContentType(ClientContext clientContext, string contentTypeName, List<Field> fields) { ContentType ret = null; Web web = clientContext.Web; clientContext.Load(web, w => w.ContentTypes, w => w.Fields); clientContext.ExecuteQuery(); //Get default document set content type. ContentType ctDocumentSet = web.ContentTypes.FirstOrDefault(ct => ct.Name.IndexOf("document set", StringComparison.CurrentCultureIgnoreCase) != -1); ret = web.ContentTypes.FirstOrDefault(ct => ct.Name == contentTypeName); if (ret == null) { ContentTypeCreationInformation ctNewInfo = new ContentTypeCreationInformation(); ctNewInfo.Name = CONTENTTYPENAME; ctNewInfo.Description = CONTENTTYPENAME; ctNewInfo.Group = CONTENTTYPEGROUP; ctNewInfo.ParentContentType = ctDocumentSet; ret = web.ContentTypes.Add(ctNewInfo); } clientContext.Load(ret, ct => ct.FieldLinks, ct => ct.Id); clientContext.ExecuteQuery(); foreach (Field field in fields) { FieldLink flAuthor = ret.FieldLinks.FirstOrDefault(link => link.Name == field.InternalName); if (flAuthor == null) { FieldLinkCreationInformation fNewInfo = new FieldLinkCreationInformation(); fNewInfo.Field = field; ret.FieldLinks.Add(fNewInfo); ret.Update(true); clientContext.Load(ret, ct => ct.FieldLinks); clientContext.ExecuteQuery(); } } return ret; }
public ContentTypeImporter(ImportContext importContext, String documentLibraryName, bool clearFirst) : base("content types", importContext) { this.Log.Info(string.Format("Mapping the object types to content types and columns to the site and the library [{0}]...", documentLibraryName)); // TODO: Make these two configurable this.TypeGroup = TYPE_GROUP; this.FieldGroup = FIELD_GROUP; using (ObjectPool <SharePointSession> .Ref sessionRef = this.ImportContext.SessionFactory.GetSession()) { SharePointSession session = sessionRef.Target; ClientContext clientContext = session.ClientContext; List documentLibrary = clientContext.Web.Lists.GetByTitle(documentLibraryName); if (clearFirst) { try { Log.Warn("Cleaning out document library content types..."); CleanContentTypes(sessionRef.Target, documentLibrary.ContentTypes); Log.Warn("Cleaning out document library fields..."); CleanFields(sessionRef.Target, documentLibrary.Fields); Log.Warn("Cleaning out site content types..."); CleanContentTypes(sessionRef.Target, clientContext.Web.ContentTypes); Log.Warn("Cleaning out site fields..."); CleanFields(sessionRef.Target, clientContext.Web.Fields); Log.Warn("Fields and content types cleared!"); } catch (Exception e) { Log.Warn("Tried to remove the existing content types, but failed", e); } } ContentTypeCollection contentTypeCollection = clientContext.Web.ContentTypes; clientContext.Load(contentTypeCollection, c => c.Include(t => t.Id, t => t.Name, t => t.Group, t => t.Parent, t => t.FieldLinks)); clientContext.Load(documentLibrary.ContentTypes, c => c.Include(t => t.Id, t => t.Name, t => t.Parent)); clientContext.Load(clientContext.Web, w => w.Fields, w => w.AvailableFields); session.ExecuteQuery(); // First we gather up whatever's already there Dictionary <string, ImportedContentType> siteContentTypes = new Dictionary <string, ImportedContentType>(); Dictionary <string, ImportedContentType> libraryContentTypes = new Dictionary <string, ImportedContentType>(); Dictionary <string, ImportedContentType> contentTypesById = new Dictionary <string, ImportedContentType>(); Dictionary <string, ContentType> allTypes = new Dictionary <string, ContentType>(); foreach (ContentType type in contentTypeCollection) { ImportedContentType ct = new ImportedContentType(this, type); siteContentTypes[type.Name] = ct; contentTypesById[type.Id.StringValue] = ct; } Dictionary <string, Field> existingFields = new Dictionary <string, Field>(); foreach (Field f in clientContext.Web.Fields) { existingFields[f.StaticName] = f; } HashSet <string> documentLibraryTypes = new HashSet <string>(); foreach (ContentType ct in documentLibrary.ContentTypes) { documentLibraryTypes.Add(ct.Name); ImportedContentType ict = new ImportedContentType(this, ct); libraryContentTypes[ct.Name] = ict; contentTypesById[ct.Id.StringValue] = ict; } // Now we go over the XML declarations HashSet <string> newTypes = new HashSet <string>(); XElement types = XElement.Load(this.ImportContext.LoadIndex("types")); XNamespace ns = types.GetDefaultNamespace(); foreach (XElement type in types.Elements(ns + "type")) { string typeName = (string)type.Element(ns + "name"); ImportedContentType finalType = null; HashSet <string> linkNames = new HashSet <string>(); bool skipInherited = true; bool patchFields = false; bool versionableType = false; bool containerType = false; if (siteContentTypes.ContainsKey(typeName)) { finalType = siteContentTypes[typeName]; foreach (FieldLink link in finalType.Type.FieldLinks) { linkNames.Add(link.Name); } if (typeName == "dm_sysobject" || typeName == "dm_folder") { patchFields = true; versionableType = (typeName == "dm_sysobject"); containerType = (typeName == "dm_folder"); } } else { // New type...create it ImportedContentType superType = null; XElement superTypeElement = type.Element(ns + "superType"); if ((superTypeElement != null) && (typeName != "dm_folder")) { string stName = (string)superTypeElement; if (siteContentTypes.ContainsKey(stName)) { superType = siteContentTypes[stName]; } } if (superType == null) { switch (typeName) { case "dm_sysobject": superType = siteContentTypes["Document"]; // skipInherited = false; patchFields = true; versionableType = true; break; case "dm_folder": superType = siteContentTypes["Folder"]; // skipInherited = false; patchFields = true; containerType = true; break; default: // This isn't a type we're intereseted in, so we skip it continue; } } Log.Info(string.Format("Creating content type {0} (descended from [{1}]])", typeName, superType.Name)); ContentTypeCreationInformation ctInfo = new ContentTypeCreationInformation(); ctInfo.Description = string.Format("Documentum Type {0}", typeName); ctInfo.Name = typeName; ctInfo.ParentContentType = (superType != null ? superType.Type : null); ctInfo.Group = this.TypeGroup; ContentType contentTypeObj = contentTypeCollection.Add(ctInfo); clientContext.Load(contentTypeObj, t => t.Id); session.ExecuteQuery(); finalType = new ImportedContentType(this, contentTypeObj, superType.Id); siteContentTypes[typeName] = finalType; contentTypesById[finalType.Id.StringValue] = finalType; } // Now we link the type to its fields, as needed int updateCount = 0; XElement attributeContainer = type.Element(ns + "attributes"); if (patchFields) { XElement versionAtt = new XElement(ns + "attribute"); versionAtt.SetAttributeValue("length", "32"); versionAtt.SetAttributeValue("repeating", "false"); versionAtt.SetAttributeValue("inherited", "false"); versionAtt.SetAttributeValue("sourceName", "version"); versionAtt.SetAttributeValue("name", "cmf:version"); versionAtt.SetAttributeValue("dataType", "STRING"); attributeContainer.AddFirst(versionAtt); versionAtt = new XElement(ns + "attribute"); versionAtt.SetAttributeValue("length", "400"); versionAtt.SetAttributeValue("repeating", "false"); versionAtt.SetAttributeValue("inherited", "false"); versionAtt.SetAttributeValue("sourceName", "title"); versionAtt.SetAttributeValue("name", "cmis:description"); versionAtt.SetAttributeValue("dataType", "STRING"); attributeContainer.AddFirst(versionAtt); versionAtt = new XElement(ns + "attribute"); versionAtt.SetAttributeValue("length", "128"); versionAtt.SetAttributeValue("repeating", "false"); versionAtt.SetAttributeValue("inherited", "false"); versionAtt.SetAttributeValue("sourceName", "author_name"); versionAtt.SetAttributeValue("name", "shpt:authorName"); versionAtt.SetAttributeValue("dataType", "STRING"); attributeContainer.AddFirst(versionAtt); versionAtt = new XElement(ns + "attribute"); versionAtt.SetAttributeValue("length", "0"); versionAtt.SetAttributeValue("repeating", "false"); versionAtt.SetAttributeValue("inherited", "false"); versionAtt.SetAttributeValue("sourceName", "author"); versionAtt.SetAttributeValue("name", "shpt:author"); versionAtt.SetAttributeValue("dataType", "USER"); attributeContainer.AddFirst(versionAtt); versionAtt = new XElement(ns + "attribute"); versionAtt.SetAttributeValue("length", "128"); versionAtt.SetAttributeValue("repeating", "false"); versionAtt.SetAttributeValue("inherited", "false"); versionAtt.SetAttributeValue("sourceName", "editor_name"); versionAtt.SetAttributeValue("name", "shpt:editorName"); versionAtt.SetAttributeValue("dataType", "STRING"); attributeContainer.AddFirst(versionAtt); versionAtt = new XElement(ns + "attribute"); versionAtt.SetAttributeValue("length", "0"); versionAtt.SetAttributeValue("repeating", "false"); versionAtt.SetAttributeValue("inherited", "false"); versionAtt.SetAttributeValue("sourceName", "editor"); versionAtt.SetAttributeValue("name", "shpt:editor"); versionAtt.SetAttributeValue("dataType", "USER"); attributeContainer.AddFirst(versionAtt); versionAtt = new XElement(ns + "attribute"); versionAtt.SetAttributeValue("length", "16"); versionAtt.SetAttributeValue("repeating", "false"); versionAtt.SetAttributeValue("inherited", "false"); versionAtt.SetAttributeValue("sourceName", "object_id"); versionAtt.SetAttributeValue("name", "cmis:objectId"); versionAtt.SetAttributeValue("dataType", "STRING"); attributeContainer.AddFirst(versionAtt); versionAtt = new XElement(ns + "attribute"); versionAtt.SetAttributeValue("length", "256"); versionAtt.SetAttributeValue("repeating", "false"); versionAtt.SetAttributeValue("inherited", "false"); versionAtt.SetAttributeValue("sourceName", "location"); versionAtt.SetAttributeValue("name", "cmf:location"); versionAtt.SetAttributeValue("dataType", "STRING"); attributeContainer.AddFirst(versionAtt); versionAtt = new XElement(ns + "attribute"); versionAtt.SetAttributeValue("length", "256"); versionAtt.SetAttributeValue("repeating", "false"); versionAtt.SetAttributeValue("inherited", "false"); versionAtt.SetAttributeValue("sourceName", "path"); versionAtt.SetAttributeValue("name", "cmis:path"); versionAtt.SetAttributeValue("dataType", "STRING"); attributeContainer.AddFirst(versionAtt); versionAtt = new XElement(ns + "attribute"); versionAtt.SetAttributeValue("length", "256"); versionAtt.SetAttributeValue("repeating", "false"); versionAtt.SetAttributeValue("inherited", "false"); versionAtt.SetAttributeValue("sourceName", "name"); versionAtt.SetAttributeValue("name", "cmis:name"); versionAtt.SetAttributeValue("dataType", "STRING"); attributeContainer.AddFirst(versionAtt); versionAtt = new XElement(ns + "attribute"); versionAtt.SetAttributeValue("length", "1024"); versionAtt.SetAttributeValue("repeating", "true"); versionAtt.SetAttributeValue("inherited", "false"); versionAtt.SetAttributeValue("sourceName", "keywords"); versionAtt.SetAttributeValue("name", "dctm:keywords"); versionAtt.SetAttributeValue("dataType", "STRING"); attributeContainer.AddFirst(versionAtt); versionAtt = new XElement(ns + "attribute"); versionAtt.SetAttributeValue("length", "16"); versionAtt.SetAttributeValue("repeating", "false"); versionAtt.SetAttributeValue("inherited", "false"); versionAtt.SetAttributeValue("sourceName", "acl_id"); versionAtt.SetAttributeValue("name", "dctm:acl_id"); versionAtt.SetAttributeValue("dataType", "STRING"); attributeContainer.AddFirst(versionAtt); if (versionableType) { versionAtt = new XElement(ns + "attribute"); versionAtt.SetAttributeValue("length", "16"); versionAtt.SetAttributeValue("repeating", "false"); versionAtt.SetAttributeValue("inherited", "false"); versionAtt.SetAttributeValue("sourceName", "history_id"); versionAtt.SetAttributeValue("name", "cmis:versionSeriesId"); versionAtt.SetAttributeValue("dataType", "STRING"); attributeContainer.AddFirst(versionAtt); versionAtt = new XElement(ns + "attribute"); versionAtt.SetAttributeValue("length", "16"); versionAtt.SetAttributeValue("repeating", "false"); versionAtt.SetAttributeValue("inherited", "false"); versionAtt.SetAttributeValue("sourceName", "antecedent_id"); versionAtt.SetAttributeValue("name", "cmf:version_antecedent_id"); versionAtt.SetAttributeValue("dataType", "STRING"); attributeContainer.AddFirst(versionAtt); versionAtt = new XElement(ns + "attribute"); versionAtt.SetAttributeValue("length", "0"); versionAtt.SetAttributeValue("repeating", "false"); versionAtt.SetAttributeValue("inherited", "false"); versionAtt.SetAttributeValue("sourceName", "current"); versionAtt.SetAttributeValue("name", "cmis:isLatestVersion"); versionAtt.SetAttributeValue("dataType", "BOOLEAN"); attributeContainer.AddFirst(versionAtt); } } foreach (XElement att in attributeContainer.Elements(ns + "attribute")) { // The attribute is either not inherited or its inheritance is ignored, so add it to the content type's declaration string attName = att.Attribute("name").Value; string attSourceName = att.Attribute("sourceName").Value; string finalName = string.Format("dctm_{0}", attSourceName); // Special case for folder attributes inherited from dm_sysobject bool inherited = XmlConvert.ToBoolean(att.Attribute("inherited").Value) && (typeName != "dm_folder"); bool repeating = XmlConvert.ToBoolean(att.Attribute("repeating").Value); // If this is an inherited attribute, we won't add it because we're not interested in it if (inherited && skipInherited) { continue; } ImportedContentTypeField finalField = null; if (linkNames.Contains(finalName) || (inherited && skipInherited)) { // Existing or inherited link... finalField = new ImportedContentTypeField(existingFields[finalName], attName, finalName, attSourceName, repeating); } else { FieldLinkCreationInformation fieldLink = new FieldLinkCreationInformation(); if (existingFields.ContainsKey(finalName)) { finalField = new ImportedContentTypeField(existingFields[finalName], attName, finalName, attSourceName, repeating); fieldLink.Field = finalField.Field; } else { Log.Info(string.Format("Creating field {0} (first declared by {1})", finalName, typeName)); FieldType attType = Tools.DecodeFieldType(att.Attribute("dataType").Value); if (repeating) { // Default repeating fields to strings, since they'll be concatenated attType = FieldType.Note; } int length = XmlConvert.ToInt32(att.Attribute("length").Value); if (length > 255) { attType = FieldType.Note; } Guid guid = Guid.NewGuid(); string fieldXml = string.Format("<Field DisplayName='{0}' Name='{1}' ID='{2}' Group='{3}' Type='{4}' />", finalName, finalName, guid.ToString(), this.FieldGroup, attType); fieldLink.Field = clientContext.Web.Fields.AddFieldAsXml(fieldXml, false, AddFieldOptions.AddFieldInternalNameHint); clientContext.Load(fieldLink.Field, f => f.Id, f => f.FieldTypeKind, f => f.StaticName, f => f.Group); existingFields[finalName] = fieldLink.Field; finalField = new ImportedContentTypeField(existingFields[finalName], attName, finalName, attSourceName, repeating); } finalType.Type.FieldLinks.Add(fieldLink); linkNames.Add(finalName); updateCount++; } finalType.AddField(finalField); } if (updateCount > 0) { finalType.Type.Update(true); session.ExecuteQuery(); } newTypes.Add(typeName); } // Now, make sure this type exists in the document library List <ContentType> newContentTypes = new List <ContentType>(); foreach (string typeName in newTypes) { if (!documentLibraryTypes.Contains(typeName)) { ContentType ct = documentLibrary.ContentTypes.AddExistingContentType(siteContentTypes[typeName].Type); newContentTypes.Add(ct); clientContext.Load(ct); clientContext.Load(ct, c => c.Parent); } } if (newContentTypes.Count > 0) { session.ExecuteQuery(); foreach (ContentType ct in newContentTypes) { ImportedContentType newCt = new ImportedContentType(this, ct); contentTypesById[ct.Id.StringValue] = newCt; libraryContentTypes[ct.Name] = newCt; } } this.SiteContentTypes = siteContentTypes; this.LibraryContentTypes = libraryContentTypes; this.ContentTypesById = contentTypesById; } }
private static void BindFieldsToContentType(Web web, string contentTypeId, IEnumerable<Field> fields) { var contentType = web.GetContentTypeById(contentTypeId); var descriptionField = web.Fields.GetByInternalNameOrTitle(FIELD_DESCRIPTION); web.Context.Load(web.Fields); web.Context.Load(descriptionField); web.Context.Load(contentType.FieldLinks); web.Context.ExecuteQuery(); // add the description field ((List<Field>)fields).Insert(0, descriptionField); // add any fields which have not be included var missingFields = fields.Except(from f in fields join fl in contentType.FieldLinks on f.StaticName equals fl.Name select f).ToList(); foreach (var field in missingFields) { var fieldLinkCreationInfo = new FieldLinkCreationInformation() { Field = field }; contentType.FieldLinks.Add(fieldLinkCreationInfo); } contentType.Update(false); contentType.Context.ExecuteQuery(); }