private Field EnsureField(ClientRuntimeContext context, Field currentField, FieldCollection fieldCollection, FieldDefinition fieldModel) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "EnsureField()"); if (currentField == null) { TraceService.Verbose((int)LogEventId.ModelProvisionProcessingNewObject, "Current field is NULL. Creating new"); var fieldDef = GetTargetSPFieldXmlDefinition(fieldModel); var addFieldOptions = (AddFieldOptions)(int)fieldModel.AddFieldOptions; var resultField = fieldCollection.AddFieldAsXml(fieldDef, fieldModel.AddToDefaultView, addFieldOptions); if (PreloadProperties(resultField)) { context.ExecuteQueryWithTrace(); } ProcessFieldProperties(resultField, fieldModel); return(resultField); } else { TraceService.Verbose((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing field"); ProcessFieldProperties(currentField, fieldModel); return(currentField); } }
public static TF CreateField <TF>( this FieldCollection fields, FieldType fieldType, Guid fieldId, string name, string displayName, bool required, Action <TF> action = null) where TF : Field { string fieldXml = string.Format( @"<Field ID=""{0}"" Name=""{1}"" StaticName=""{1}"" DisplayName=""{2}"" Type=""{3}"" Overwrite=""TRUE"" SourceID=""http://schemas.microsoft.com/sharepoint/v3"" />", fieldId, name, displayName, fieldType); Field newField = fields.AddFieldAsXml(fieldXml, true, AddFieldOptions.DefaultValue); TF field = fields.Context.CastTo <TF>(newField); field.Required = required; if (action != null) { action(field); } field.Update(); fields.Context.ExecuteQuery(); return(field); }
public static Field Add(this FieldCollection fields, string name, FieldType fieldType, bool addToDefaultView) { return(fields.AddFieldAsXml( $"<Field Name='{name}' DisplayName='{name}' Type='{fieldType}' />", addToDefaultView, AddFieldOptions.DefaultValue)); }
private void CreateField(ShField field, FieldCollection fields) { // code to handle lookup fields. does not work if the list has not been created... if (field.Type == "Lookup" || field.Type == "LookupMulti") { var web = ClientContext.Web; if (!web.IsObjectPropertyInstantiated("Lists")) { ClientContext.Load(web, x => x.Lists); ClientContext.ExecuteQuery(); } var listTitle = field.List; var list = web.Lists.GetByTitle(listTitle); try { ClientContext.Load(list, x => x.Id); ClientContext.ExecuteQuery(); field.List = list.Id.ToString(); } catch (Exception) { Log.Info("Lookup field " + field.DisplayName + " id:" + field.ID + " cannot be created since the list " + listTitle + " has not been created. Please rund content type creation again after setting up the site hierarchy"); return; } } var fieldXml = field.GetFieldAsXml(); Field newField = fields.AddFieldAsXml(fieldXml, true, AddFieldOptions.AddFieldInternalNameHint); ClientContext.Load(newField); ClientContext.ExecuteQuery(); }
public bool AddFields(string listTitle, List <FieldInfo> fields) { List targetList = Web.Lists.GetByTitle(listTitle); FieldCollection collField = targetList.Fields; fields.Sort(); try { for (int i = 0; i < fields.Count; i++) { FieldInfo fieldInfo = fields[i]; string fieldSchema = fieldInfo.Element.ToString(); Field field; if (TryGetField(targetList, fieldInfo.InternalName, out field)) { field.SchemaXml = fieldSchema; } else { field = collField.AddFieldAsXml(fieldSchema, !fieldInfo.Hidden, AddFieldOptions.AddFieldInternalNameHint); } field.Update(); } ExecuteQuery(); } catch (Exception ex) { Log.Error($"{ex.Message}\n{ex.StackTrace}"); return(false); } return(true); }
private Field EnsureField(ClientRuntimeContext context, Field currentField, FieldCollection fieldCollection, FieldDefinition fieldModel) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "EnsureField()"); if (currentField == null) { TraceService.Verbose((int)LogEventId.ModelProvisionProcessingNewObject, "Current field is NULL. Creating new"); var fieldDef = GetTargetSPFieldXmlDefinition(fieldModel); // special handle for taxonomy field // incorectly removed tax field leaves its indexed field // https://github.com/SubPointSolutions/spmeta2/issues/521 HandleIncorectlyDeletedTaxonomyField(fieldModel, fieldCollection); var addFieldOptions = (AddFieldOptions)(int)fieldModel.AddFieldOptions; var resultField = fieldCollection.AddFieldAsXml(fieldDef, fieldModel.AddToDefaultView, addFieldOptions); ProcessFieldProperties(resultField, fieldModel); return(resultField); } else { TraceService.Verbose((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing field"); ProcessFieldProperties(currentField, fieldModel); return(currentField); } }
private Field EnsureField(ClientRuntimeContext context, FieldCollection fieldCollection, FieldDefinition fieldModel) { var currentField = FindExistingField(fieldCollection, fieldModel.InternalName); if (currentField == null) { var fieldDef = string.Format(SiteFieldXmlTemplate, new string[] { fieldModel.Id.ToString("B"), fieldModel.InternalName, fieldModel.Title, fieldModel.Title, fieldModel.InternalName, fieldModel.FieldType, fieldModel.Group }); currentField = fieldCollection.AddFieldAsXml(fieldDef, false, AddFieldOptions.DefaultValue); } currentField.Title = fieldModel.Title; currentField.Description = fieldModel.Description ?? string.Empty; currentField.Group = fieldModel.Group ?? string.Empty; return(currentField); }
/// <summary> /// Create field to web remotely /// </summary> /// <param name="web">Site to be processed - can be root web or sub site</param> /// <param name="id">Guid for the new field.</param> /// <param name="internalName">Internal name of the field</param> /// <param name="fieldType">Field type to be created.</param> /// <param name="displayName">The display name of hte field</param> /// <param name="group">The field group name</param> /// <returns>The newly created field or existing field.</returns> public static Field CreateField(this Web web, Guid id, string internalName, string fieldType, string displayName, string group, string additionalXmlAttributes = "", bool executeQuery = true) { FieldCollection fields = web.Fields; web.Context.Load(fields, fc => fc.Include(f => f.Id, f => f.InternalName)); web.Context.ExecuteQuery(); var field = fields.FirstOrDefault(f => f.Id == id || f.InternalName == internalName); if (field != null) { throw new ArgumentException("id", "Field already exists"); } string newFieldCAML = string.Format(FIELD_XML_FORMAT, fieldType, internalName, displayName, id, group, additionalXmlAttributes); LoggingUtility.LogInformation("New Field as XML: " + newFieldCAML, EventCategory.FieldsAndContentTypes); field = fields.AddFieldAsXml(newFieldCAML, false, AddFieldOptions.AddFieldInternalNameHint); web.Update(); if (executeQuery) { web.Context.ExecuteQuery(); } return(field); }
private static void CreateSiteColumn(ClientContext cc, Web web) { // Add site column to the content type if it's not there... FieldCollection fields = web.Fields; cc.Load(fields); cc.ExecuteQuery(); foreach (var item in fields) { if (item.InternalName == "ContosoString") { return; } } string FieldAsXML = @"<Field ID='{4F34B2ED-9CFF-4900-B091-4C0033F89944}' Name='ContosoString' DisplayName='Contoso String' Type='Text' Hidden='False' Group='Contoso Site Columns' Description='Contoso Text Field' />"; Field fld = fields.AddFieldAsXml(FieldAsXML, true, AddFieldOptions.DefaultValue); cc.Load(fields); cc.Load(fld); cc.ExecuteQuery(); }
private void CreateField(ShField field, FieldCollection fields) { var fieldXml = field.GetFieldAsXml(); Field newField = fields.AddFieldAsXml(fieldXml, true, AddFieldOptions.AddFieldInternalNameHint); ClientContext.Load(newField); ClientContext.ExecuteQuery(); }
public static bool CreateSharepointColumn(String SPSite, String SPListName, String newCol) { bool fError = false; bool fieldExists = false; try { using (ClientContext clientContext = new ClientContext(SPSite)) { // clientcontext.Web.Lists.GetById - This option also can be used to get the list using List GUID // This value is NOT List internal name List targetList = clientContext.Web.Lists.GetByTitle(SPListName); clientContext.Load(targetList); clientContext.Load(targetList.Fields); clientContext.ExecuteQuery(); for (int i = 0; i < targetList.Fields.Count; i++) { if (targetList.Fields[i].Title == newCol) { fieldExists = true; } } } if (!fieldExists) { using (ClientContext clientContext = new ClientContext(SPSite)) { // clientcontext.Web.Lists.GetById - This option also can be used to get the list using List GUID // This value is NOT List internal name List targetList = clientContext.Web.Lists.GetByTitle(SPListName); FieldCollection collField = targetList.Fields; string fieldSchema = "<Field Type='Text' DisplayName='" + newCol + "' Name='" + newCol + "' />"; collField.AddFieldAsXml(fieldSchema, true, AddFieldOptions.AddToDefaultContentType); clientContext.Load(collField); clientContext.ExecuteQuery(); } } //else // this just isn't needed unless debugging //{ // Console.WriteLine("The SharePoint column you're trying to add already exists!"); //} return(!fError); } catch (Exception ex) { Console.WriteLine("Error writing new column {0}. Exception: {1}", newCol, ex); fError = true; return(fError); } }
public static void AddFieldLookup(this FieldCollection flds, string cInternalName, string cDisplayName, string cFieldDescription, string cGroup, string cListName, string cShowField) { try { string strNewField = string.Format("<Field Type='Lookup' DisplayName='{0}' StaticName='{1}' Name='{1}' Group = '{2}' Description='{3}' List='{4}' ShowField='{5}' />", cDisplayName, cInternalName, cGroup, cFieldDescription, cListName, cShowField); flds.AddFieldAsXml(strNewField, true, AddFieldOptions.AddFieldInternalNameHint); flds.Context.ExecuteQuery(); } catch (Exception ex) { throw new Exception(string.Format("Error in extFieldCollection.AddField - {0} - {1}", cDisplayName, ex.Message), ex); } }
public static void AddFieldCurrency(this FieldCollection flds, string cInternalName, string cFieldTitle, string cFieldDescription, string cGroup) { try { cInternalName = GetInternalName(cInternalName, cFieldTitle); string strNewField = string.Format("<Field Type='Currency' DisplayName='{0}' StaticName='{1}' Name='{1}' Group = '{2}' Description='{3}' ><Default>0</Default></Field>", cFieldTitle, cInternalName, cGroup, cFieldDescription); flds.AddFieldAsXml(strNewField, true, AddFieldOptions.AddFieldInternalNameHint); flds.Context.ExecuteQuery(); } catch (Exception ex) { throw new Exception(string.Format("Error in extFieldCollection.AddField - {0} - {1}", cFieldTitle, ex.Message), ex); } }
public static void AddField(this FieldCollection fields, FieldType type, string displayName, string internalName, AddFieldOptions addFieldOptions, bool addToDefaultView, bool?readOnly = null) { var field = new XElement("Field"); field.SetAttributeValue("Type", type); field.SetAttributeValue("DisplayName", displayName); field.SetAttributeValue("Name", internalName); if (readOnly.HasValue) { field.SetAttributeValue("ReadOnly", readOnly); } fields.AddFieldAsXml(field.ToString(), addToDefaultView, addFieldOptions); }
/// <summary> /// Check for Ratings/Likes field and add to ListField if doesn't exists. /// </summary> /// <param name="list">List</param> /// <param name="fieldId">Field Id</param> /// <returns></returns> private static void EnsureField(List list, Guid fieldId) { FieldCollection fields = list.Fields; FieldCollection availableFields = list.ParentWeb.AvailableFields; Field field = availableFields.GetById(fieldId); _library.Context.Load(fields); _library.Context.Load(field, p => p.SchemaXmlWithResourceTokens, p => p.Id, p => p.InternalName, p => p.StaticName); _library.Context.ExecuteQueryRetry(); if (!fields.Any(p => p.Id == fieldId)) { fields.AddFieldAsXml(field.SchemaXmlWithResourceTokens, false, AddFieldOptions.AddFieldInternalNameHint | AddFieldOptions.AddToAllContentTypes); } }
/// <summary> /// Creates sample codes list for demo purposes /// </summary> /// <param name="ctx"></param> /// <param name="web"></param> public void SetupCodesList(ClientContext ctx, Web web) { string newListName = "CodesList"; var spContext = SharePointContextProvider.Current.GetSharePointContext(Context); using (ctx = spContext.CreateUserClientContextForSPHost()) { if (!ctx.Web.ListExists(newListName)) { ctx.Web.AddList(ListTemplateType.GenericList, newListName, false, true); List newlist = ctx.Web.Lists.GetByTitle(newListName); FieldCollection collField = newlist.Fields; // Add url field for links to site assets images collField.AddFieldAsXml("<Field DisplayName='CodesImageUrl' Name='CodesImageUrl' Type='URL' />", true, AddFieldOptions.DefaultValue); ctx.Load(collField); ctx.ExecuteQuery(); // Create sample list items needed for demo purposes only ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); Microsoft.SharePoint.Client.ListItem newXXItem = newlist.AddItem(itemCreateInfo); newXXItem["Title"] = "XX"; newXXItem["CodesImageUrl"] = "/SiteAssets/contosoxx.png"; newXXItem.Update(); itemCreateInfo = new ListItemCreationInformation(); Microsoft.SharePoint.Client.ListItem newYYItem = newlist.AddItem(itemCreateInfo); newYYItem["Title"] = "YY"; newYYItem["CodesImageUrl"] = "/SiteAssets/contosoyy.png"; newYYItem.Update(); itemCreateInfo = new ListItemCreationInformation(); Microsoft.SharePoint.Client.ListItem newZZItem = newlist.AddItem(itemCreateInfo); newZZItem["Title"] = "ZZ"; newZZItem["CodesImageUrl"] = "/SiteAssets/contosoZZ.png"; newZZItem.Update(); // Batch update ctx.ExecuteQuery(); } } }
static void Main(string[] args) { string UserName = "******"; Console.WriteLine("Enter Your Password"); SecureString password = GetPassword(); ClientContext context = new ClientContext("https://acuvatehyd.sharepoint.com/teams/Info"); context.Credentials = new SharePointOnlineCredentials(UserName, password); Web oWebsite = context.Web; //****************List Creation*************************// //ListCreationInformation listCreationInformation = new ListCreationInformation(); //listCreationInformation.Title = "ListViaCsom"; //listCreationInformation.TemplateType = (int)ListTemplateType.Announcements; //List list = oWebsite.Lists.Add(listCreationInformation); //********************************************************// // ***********************adding fields to the list*********************** context.Load(oWebsite); List list = context.Web.Lists.GetByTitle("BackendTest"); string field = "<Field Type='Text' DisplayName = 'Silicon' Name='Silicon'/>"; FieldCollection fields = list.Fields; fields.AddFieldAsXml(field, true, AddFieldOptions.AddToDefaultContentType); //ListItem listItem= list.AddItem() //list.Fields.AddFieldAsXml("<Field Name='Decoy' DisplayName='Decoy' type='text' Required='FALSE'></Field>", true, AddFieldOptions.DefaultValue); //FieldNumber fieldNumber = context.CastTo<FieldNumber>(field); //fieldNumber.MaximumValue = 100; //fieldNumber.MinimumValue = 35; context.ExecuteQuery(); Console.WriteLine("ListCreated Go and check"); Console.ReadLine(); }
/// <summary> /// Create field to web remotely /// </summary> /// <param name="web">Site to be processed - can be root web or sub site</param> /// <param name="fieldAsXml">The XML declaration of SiteColumn definition</param> /// <returns>The newly created field or existing field.</returns> public static Field CreateField(this Web web, string fieldAsXml, bool executeQuery = true) { FieldCollection fields = web.Fields; web.Context.Load(fields); web.Context.ExecuteQuery(); Field field = fields.AddFieldAsXml(fieldAsXml, false, AddFieldOptions.AddFieldInternalNameHint); web.Update(); if (executeQuery) { web.Context.ExecuteQuery(); } return(field); }
private void CreateTaxonomyField(GtField field, FieldCollection fields) { var fieldSchema = field.GetFieldAsXml(); var newField = fields.AddFieldAsXml(fieldSchema, false, AddFieldOptions.AddFieldInternalNameHint); ClientContext.Load(newField); ClientContext.ExecuteQuery(); var termSetId = GetTermSetId(field); var newTaxonomyField = ClientContext.CastTo <TaxonomyField>(newField); newTaxonomyField.SspId = field.SspId; newTaxonomyField.TermSetId = termSetId; newTaxonomyField.TargetTemplate = String.Empty; newTaxonomyField.AnchorId = Guid.Empty; newTaxonomyField.Update(); ClientContext.ExecuteQuery(); }
private void CreateTaxonomyField(ShField field, FieldCollection fields) { Log.Debug("Attempting to create taxonomy field " + field.DisplayName); var fieldSchema = field.GetFieldAsXml(); var newField = fields.AddFieldAsXml(fieldSchema, false, AddFieldOptions.AddFieldInternalNameHint); ClientContext.Load(newField); ClientContext.ExecuteQuery(); var termSetId = GetTermSetId(field); var newTaxonomyField = ClientContext.CastTo <TaxonomyField>(newField); newTaxonomyField.SspId = field.SspId; newTaxonomyField.TermSetId = termSetId; newTaxonomyField.TargetTemplate = String.Empty; newTaxonomyField.AnchorId = Guid.Empty; newTaxonomyField.CreateValuesInEditForm = field.OpenTermSet; newTaxonomyField.Open = field.OpenTermSet; newTaxonomyField.Update(); ClientContext.ExecuteQuery(); }
public static void AddFieldChoice(this FieldCollection flds, string cInternalName, string cFieldTitle, string cFieldDescription, string cGroup, string[] cChoices) { try { cInternalName = GetInternalName(cInternalName, cFieldTitle); string strNewField = string.Format("<Field Type='Choice' DisplayName='{0}' StaticName='{1}' Name='{1}' Description='{2}' Group='{3}' ><CHOICES>", cFieldTitle, cInternalName, cFieldDescription, cGroup); foreach (string item in cChoices) { strNewField += string.Format("<CHOICE>{0}</CHOICE>", item); } strNewField += "</CHOICES></Field>"; flds.AddFieldAsXml(strNewField, true, AddFieldOptions.AddFieldInternalNameHint); flds.Context.ExecuteQuery(); } catch (Exception ex) { throw new Exception(string.Format("Error in extFieldCollection.AddField - {0} - {1}", cFieldTitle, ex.Message), ex); } }
static void Main() { string siteUrl = "http://MyServer/sites/MySiteCollection"; ClientContext clientContext = new ClientContext(siteUrl); Web site = clientContext.Web; List targetList = site.Lists.GetByTitle("Announcements"); FieldCollection collField = targetList.Fields; string fieldSchema = "<Field Type='Text' DisplayName='NewField' Name='NewField' />"; collField.AddFieldAsXml(fieldSchema, true, AddFieldOptions.AddToDefaultContentType); clientContext.Load(collField); clientContext.ExecuteQuery(); Console.WriteLine("NewField added to Announcements list.\n\nThe following fields are available:\n\n"); foreach (Field myField in collField) { Console.WriteLine(myField.Title); } }
private void EnsureRequestList(Web web) { string listName = ConfigurationManager.AppSettings["SiteCollectionRequests_List"]; if (!ListExists(web, listName)) { // Let's create the request list CreateList(web, ListTemplateType.GenericList, listName, false); List list = GetListByTitle(web, listName); web.Context.Load(list.Fields); FieldCollection collField = list.Fields; collField.AddFieldAsXml("<Field Type='Text' DisplayName='SiteUrl' Name='SiteUrl' />", true, AddFieldOptions.AddToDefaultContentType); collField.AddFieldAsXml("<Field Type='Text' DisplayName='Template' Name='Template' />", true, AddFieldOptions.AddToDefaultContentType); collField.AddFieldAsXml("<Field Type='Text' DisplayName='Description' Name='Description' />", true, AddFieldOptions.AddToDefaultContentType); collField.AddFieldAsXml("<Field Type='Text' DisplayName='AdminAccount' Name='AdminAccount' />", true, AddFieldOptions.AddToDefaultContentType); collField.AddFieldAsXml("<Field Type='Text' DisplayName='NotifyEmail' Name='NotifyEmail' />", true, AddFieldOptions.AddToDefaultContentType); collField.AddFieldAsXml("<Field Type='Text' DisplayName='Status' Name='Status' />", true, AddFieldOptions.AddToDefaultContentType); collField.AddFieldAsXml("<Field Type='Text' DisplayName='StatusMessage' Name='StatusMessage' />", true, AddFieldOptions.AddToDefaultContentType); web.Context.Load(collField); web.Context.ExecuteQuery(); } }
public static void CreateSiteColumns(Web web) { ClientContext context = (ClientContext)web.Context; context.Load(web, w => w.ContentTypes); FieldCollection fields = web.Fields; //Create Projects Column (using Term Set) //Create Keywords Column (using Term Set) //Create Lessons Learned Field string lessonTypeSchemaTextField = String.Format("<Field Required='TRUE' Type='Choice' Format='Dropdown' Name = '{0}' StaticName = '{0}' DisplayName='Lesson Type'><Default> Lessons Learned</Default><CHOICES><CHOICE>Lessons Learned</CHOICE><CHOICE>Continuous Improvement</CHOICE></CHOICES></Field>", LESSONTYPEFIELDNAME); fields.AddFieldAsXml(lessonTypeSchemaTextField, true, AddFieldOptions.AddFieldInternalNameHint); //Create Date-Time Field string dateSchemaTextField = String.Format("<Field Required='TRUE' Type='DateTime' Format='DateOnly' Name='{0}' StaticName='{0}' DisplayName='{0}' />", DATEFIELDNAME); fields.AddFieldAsXml(dateSchemaTextField, true, AddFieldOptions.AddFieldInternalNameHint); //Create Innovator Field string innovatorSchemaTextField = String.Format("<Field Required='TRUE' Type='Text' Name='{0}' StaticName='{0}' DisplayName='{0}' />", INNOVATORFIELDNAME); fields.AddFieldAsXml(innovatorSchemaTextField, true, AddFieldOptions.AddFieldInternalNameHint); //Create Issue Field string issueSchemaTextField = String.Format("<Field Required='TRUE' Type='Note' NumLines='6' Name='{0}' StaticName='{0}' DisplayName='{0}' />", ISSUEFIELDNAME); fields.AddFieldAsXml(issueSchemaTextField, true, AddFieldOptions.AddFieldInternalNameHint); //Create Resolution Field string resolutionSchemaTextField = String.Format("<Field Required='TRUE' Type='Note' NumLines='6' Name='{0}' StaticName='{0}' DisplayName='{0}' />", RESOLUTIONFIELDNAME); fields.AddFieldAsXml(resolutionSchemaTextField, true, AddFieldOptions.AddFieldInternalNameHint); //Create Status Field string statusSchemaTextField = String.Format("<Field Required='TRUE' Type='Choice' Format='Dropdown' Name='{0}' StaticName='{0}' DisplayName='{0}'><Default>Draft</Default><CHOICES><CHOICE>Draft</CHOICE><CHOICE>Submit for Review</CHOICE></CHOICES></Field>", STATUSFIELDNAME); fields.AddFieldAsXml(statusSchemaTextField, true, AddFieldOptions.AddFieldInternalNameHint); }
/// <summary> /// フィールド情報を指定して、 /// フィールドを追加します。 /// </summary> /// <param name="this">フィールドコレクション</param> /// <param name="fieldInfo">フィールド情報</param> /// <returns>フィールドを返します。</returns> public static Field AddField(this FieldCollection @this, XmlField fieldInfo) { var field = @this.AddFieldAsXml(fieldInfo.ToString(), false, AddFieldOptions.AddFieldCheckDisplayName); return(field); }
public static Field AddNote(this FieldCollection fields, String displayName, bool addToDefaultView) { return(fields.AddFieldAsXml(String.Format("<Field DisplayName='{0}' Type='{1}' />", displayName, FieldType.Note), addToDefaultView, AddFieldOptions.DefaultValue)); }
private Field EnsureField(ClientRuntimeContext context, Field currentField, FieldCollection fieldCollection, FieldDefinition fieldModel) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "EnsureField()"); if (currentField == null) { TraceService.Verbose((int)LogEventId.ModelProvisionProcessingNewObject, "Current field is NULL. Creating new"); var fieldDef = GetTargetSPFieldXmlDefinition(fieldModel); var addFieldOptions = (AddFieldOptions)(int)fieldModel.AddFieldOptions; var resultField = fieldCollection.AddFieldAsXml(fieldDef, fieldModel.AddToDefaultView, addFieldOptions); if (PreloadProperties(resultField)) { context.ExecuteQueryWithTrace(); } ProcessFieldProperties(resultField, fieldModel); return resultField; } else { TraceService.Verbose((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing field"); ProcessFieldProperties(currentField, fieldModel); return currentField; } }
private Field EnsureField(ClientRuntimeContext context, FieldCollection fieldCollection, FieldDefinition fieldModel) { var currentField = FindExistingField(fieldCollection, fieldModel.InternalName); if (currentField == null) { var fieldDef = string.Format(SiteFieldXmlTemplate, new string[] { fieldModel.Id.ToString("B"), fieldModel.InternalName, fieldModel.Title, fieldModel.Title, fieldModel.InternalName, fieldModel.FieldType, fieldModel.Group }); currentField = fieldCollection.AddFieldAsXml(fieldDef, false, AddFieldOptions.DefaultValue); } currentField.Title = fieldModel.Title; currentField.Description = fieldModel.Description ?? string.Empty; currentField.Group = fieldModel.Group ?? string.Empty; return currentField; }
public override void Provision(bool forceOverwrite, ProvisionLevel level) { if (Field != null && Model != null && Model.Context != null && Model.Context.Context != null) { if (Field.Behavior == ProvisionBehavior.None) { return; } if (level != ProvisionLevel.Default) { //Field.Level = level; } else if (Field.Level == ProvisionLevel.Default) { if (ContentType != null) { level = ContentType.Level; } if (level == ProvisionLevel.Default) { level = List != null && List.Behavior != ProvisionBehavior.None ? ProvisionLevel.List : ProvisionLevel.Web; } } if (Field.Behavior == ProvisionBehavior.Default) { if (level == ProvisionLevel.List) { if (List != null) { Field.Behavior = List.Behavior; } } if (Field.Behavior == ProvisionBehavior.Default && ContentType != null) { Field.Behavior = ContentType.Behavior; } } if (Field.DataType == FieldType.ContentTypeId || Field.DataType == FieldType.Counter || Field.DataType == FieldType.Computed || Field.DataType == FieldType.File) { return; } var context = Model.Context.Context; Web web = context.Web; List list = null; Field field = null; if (List != null && List.Behavior != ProvisionBehavior.None) { if (List.Id != default) { list = context.Web.Lists.GetById(List.Id); } else if (List.Url != null) { list = context.Web.GetList($"{ new Uri(Model.Context.SiteUrl).LocalPath.TrimEnd('/')}/{List.Url.TrimStart('/')}"); } else if (!string.IsNullOrEmpty(List.Title)) { list = context.Web.Lists.GetByTitle(List.Title); } //if (list != null) //{ // context.Load(list); // try // { // context.ExecuteQuery(); // } // catch (Exception ex) // { // list = null; // } //} } FieldCollection fields = null; field = web.AvailableFields.GetByInternalNameOrTitle(Field.Name); fields = web.Fields; context.Load(field); try { context.ExecuteQuery(); } catch (Exception) { field = null; } if (level == ProvisionLevel.List && list != null) { Field existField = list.Fields.GetByInternalNameOrTitle(Field.Name); context.Load(existField); try { context.ExecuteQuery(); } catch (Exception ex) { existField = null; } if (existField != null) { field = existField; } else { field = null; } fields = list.Fields; } if (!forceOverwrite /*&& !Field.Overwrite*/ && Field.Behavior != ProvisionBehavior.Overwrite && field != null) { OnProvisioned?.Invoke(this, field); return; } if (fields != null) { if (Field.DataType == FieldType.Calculated) { string formula = null; string fieldRefs = null; string newFormula = null; if (typeof(CalculatedFieldAttribute).IsAssignableFrom(Field.GetType())) { fieldRefs = (Field as CalculatedFieldAttribute).FieldRefs == null ? null : string.Join("", (Field as CalculatedFieldAttribute).FieldRefs.Select(fieldRef => new Caml.CamlFieldRef() { Name = fieldRef }.ToString())); formula = (Field as CalculatedFieldAttribute).Formula; if (!string.IsNullOrEmpty(fieldRefs) && !string.IsNullOrEmpty(formula)) { if (level == ProvisionLevel.List) { var refFields = new List <Field>(); foreach (string fieldName in (Field as CalculatedFieldAttribute).FieldRefs) { var refField = (level == ProvisionLevel.Web ? web.AvailableFields : fields).GetByInternalNameOrTitle(fieldName); context.Load(refField, f => f.Title, f => f.InternalName, f => f.Id); refFields.Add(refField); } context.ExecuteQuery(); foreach (Field refField in refFields) { newFormula = formula.Replace($"[{refField.InternalName}]", $"[{refField.Title}]"); } } } } if (field == null) { string fieldXml = $"<Field Type='{Field.DataType}' Name='{Field.Name}' StaticName='{Field.Name}' DisplayName='{Field.Title ?? Field.Name}' ResultType='{{2}}'><Formula>{{0}}</Formula><FieldRefs>{{1}}</FieldRefs></Field>"; fieldXml = string.Format(fieldXml, System.Security.SecurityElement.Escape(newFormula), fieldRefs, (Field as CalculatedFieldAttribute).ResultType); field = fields.AddFieldAsXml(fieldXml, true, AddFieldOptions.AddFieldInternalNameHint); } if (Field is CalculatedFieldAttribute) { (Field as CalculatedFieldAttribute).Formula = newFormula; } try { field = ApplyField(field); } finally { if (Field is CalculatedFieldAttribute) { (Field as CalculatedFieldAttribute).Formula = formula; } } OnProvisioning?.Invoke(this, field); } else { if (Field.DataType == FieldType.Lookup) { if (_valueType != null && (typeof(ISpEntityLookup).IsAssignableFrom(_valueType) || typeof(ISpEntityLookupCollection).IsAssignableFrom(_valueType)) || typeof(IListItemEntity).IsAssignableFrom(_valueType)) { bool allowMultipleValues = false; if (typeof(LookupFieldAttribute).IsAssignableFrom(Field.GetType())) { allowMultipleValues = (Field as LookupFieldAttribute).IsMultiple; } if (field == null) { string fieldXml = allowMultipleValues ? $"<Field Type='LookupMulti' Name='{Field.Name}' StaticName='{Field.Name}' DisplayName='{Field.Title ?? Field.Name}' Mult='TRUE' />" : $"<Field Type='{Field.DataType}' Name='{Field.Name}' StaticName='{Field.Name}' DisplayName='{Field.Title ?? Field.Name}' />"; field = fields.AddFieldAsXml(fieldXml, true, AddFieldOptions.AddFieldInternalNameHint); } field = ApplyField(field); OnProvisioning?.Invoke(this, field); } else { field = null; } } else if (Field.DataType == FieldType.User) { bool allowMultipleValues = false; if (typeof(LookupFieldAttribute).IsAssignableFrom(Field.GetType())) { allowMultipleValues = (Field as LookupFieldAttribute).IsMultiple; } if (field == null) { string fieldXml = allowMultipleValues ? $"<Field Type='UserMulti' Name='{Field.Name}' StaticName='{Field.Name}' DisplayName='{Field.Title ?? Field.Name}' Mult='TRUE' />" : $"<Field Type='{Field.DataType}' Name='{Field.Name}' StaticName='{Field.Name}' DisplayName='{Field.Title ?? Field.Name}' />"; field = fields.AddFieldAsXml(fieldXml, true, AddFieldOptions.AddFieldInternalNameHint); } field = ApplyField(field); OnProvisioning?.Invoke(this, field); } else if ((Field.DataType == FieldType.Choice || Field.DataType == FieldType.MultiChoice) && _valueType.IsEnum) { if (field == null) { string fieldXml = $"<Field Type='{Field.DataType}' Name='{Field.Name}' StaticName='{Field.Name}' DisplayName='{Field.Title ?? Field.Name}' />"; field = fields.AddFieldAsXml(fieldXml, true, AddFieldOptions.AddFieldInternalNameHint); } field = ApplyField(field); OnProvisioning?.Invoke(this, field); } else if (Field.DataType == FieldType.Note) { if (field == null) { string fieldXml = $"<Field Type='{Field.DataType}' Name='{Field.Name}' StaticName='{Field.Name}' DisplayName='{Field.Title ?? Field.Name}' RichText='{(Field is NoteFieldAttribute && (Field as NoteFieldAttribute).RichText ? "TRUE" : "FALSE")}' RichTextMode='{(Field is NoteFieldAttribute && (Field as NoteFieldAttribute).RichText ? "FullHtml" : "Compatible")}' IsolateStyles='{(Field is NoteFieldAttribute && (Field as NoteFieldAttribute).RichText ? "TRUE" : "FALSE")}' />"; field = fields.AddFieldAsXml(fieldXml, true, AddFieldOptions.AddFieldInternalNameHint); } field = ApplyField(field); OnProvisioning?.Invoke(this, field); } else { if (field == null) { string fieldXml = $"<Field Type='{Field.DataType}' Name='{Field.Name}' StaticName='{Field.Name}' DisplayName='{Field.Title ?? Field.Name}' />"; field = fields.AddFieldAsXml(fieldXml, true, AddFieldOptions.AddFieldInternalNameHint); } field = ApplyField(field); OnProvisioning?.Invoke(this, field); } } if (field != null) { field.Update(); context.Load(field); context.ExecuteQuery(); OnProvisioned?.Invoke(this, field); } } } }
/// <summary> /// Import new fields to the target SharePoint. /// </summary> /// <exception cref="ElementsMigrationException">if importing of fields fails</exception> private void ImportNewField() { Console.WriteLine("import new fields"); Logger.AddMessage("import new SiteColumns"); FieldCollection sourceFieldCollection = this.GetAllFields(SourceClientContext); FieldCollection targetFieldCollection = this.GetAllFields(TargetClientContext); HashSet <string> targetFieldTitles = targetFieldCollection.GetAllTitles(); foreach (var sourceField in sourceFieldCollection) { if (!targetFieldTitles.Contains(sourceField.Title)) { Logger.AddMessage("import new field = '" + sourceField.Title + "'"); string newField = "<Field DisplayName='" + sourceField.Title + "' Type='" + sourceField.TypeAsString + "' />"; Field targetField = targetFieldCollection.AddFieldAsXml(newField, true, AddFieldOptions.DefaultValue); targetField.Description = sourceField.Description; targetField.Direction = sourceField.Direction; targetField.EnforceUniqueValues = sourceField.EnforceUniqueValues; targetField.FieldTypeKind = sourceField.FieldTypeKind; //// TODO getGroup: targetField.Group = sourceField.Group; targetField.Hidden = sourceField.Hidden; try { targetField.Indexed = sourceField.Indexed; } catch (PropertyOrFieldNotInitializedException) { } try { targetField.ReadOnlyField = sourceField.ReadOnlyField; } catch (PropertyOrFieldNotInitializedException) { } try { targetField.Required = sourceField.Required; } catch (PropertyOrFieldNotInitializedException) { } try { targetField.StaticName = sourceField.StaticName; } catch (PropertyOrFieldNotInitializedException) { } try { targetField.Tag = sourceField.Tag; } catch (PropertyOrFieldNotInitializedException) { } try { targetField.TypeAsString = sourceField.TypeAsString; } catch (PropertyOrFieldNotInitializedException) { } try { targetField.ValidationFormula = sourceField.ValidationFormula; } catch (PropertyOrFieldNotInitializedException) { } try { targetField.ValidationMessage = sourceField.ValidationMessage; } catch (PropertyOrFieldNotInitializedException) { } } else { Console.WriteLine("don't have to import '{0}'", sourceField.Title); Logger.AddMessage("don't have to import '" + sourceField.Title + "'"); } } try { TargetClientContext.ExecuteQuery(); } catch (Exception e) { Console.WriteLine("Exception during importing new Fields.", e); Logger.AddMessage("Exception during importing new Fields. Error = " + e.Message); throw new ElementsMigrationException("Exception during importing new Fields.", e); } }
private Field EnsureField(ClientRuntimeContext context, Field currentField, FieldCollection fieldCollection, FieldDefinition fieldModel) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "EnsureField()"); if (currentField == null) { TraceService.Verbose((int)LogEventId.ModelProvisionProcessingNewObject, "Current field is NULL. Creating new"); var fieldDef = GetTargetSPFieldXmlDefinition(fieldModel); // special handle for taxonomy field // incorectly removed tax field leaves its indexed field // https://github.com/SubPointSolutions/spmeta2/issues/521 HandleIncorectlyDeletedTaxonomyField(fieldModel, fieldCollection); var addFieldOptions = (AddFieldOptions)(int)fieldModel.AddFieldOptions; var resultField = fieldCollection.AddFieldAsXml(fieldDef, fieldModel.AddToDefaultView, addFieldOptions); ProcessFieldProperties(resultField, fieldModel); return resultField; } else { TraceService.Verbose((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing field"); ProcessFieldProperties(currentField, fieldModel); return currentField; } }
private void CreateTaxonomyField(ShField field, FieldCollection fields) { Log.Debug("Attempting to create taxonomy field " + field.DisplayName); var fieldSchema = field.GetFieldAsXml(); var newField = fields.AddFieldAsXml(fieldSchema, false, AddFieldOptions.AddFieldInternalNameHint); ClientContext.Load(newField); ClientContext.ExecuteQuery(); var termSetId = GetTermSetId(field); var newTaxonomyField = ClientContext.CastTo<TaxonomyField>(newField); newTaxonomyField.SspId = field.SspId; newTaxonomyField.TermSetId = termSetId; newTaxonomyField.TargetTemplate = String.Empty; newTaxonomyField.AnchorId = Guid.Empty; newTaxonomyField.CreateValuesInEditForm = field.OpenTermSet; newTaxonomyField.Open = field.OpenTermSet; newTaxonomyField.Update(); ClientContext.ExecuteQuery(); }
private void CreateField(ShField field, FieldCollection fields) { // code to handle lookup fields. does not work if the list has not been created... if (field.Type == "Lookup" || field.Type == "LookupMulti") { var web = ClientContext.Web; if (!web.IsObjectPropertyInstantiated("Lists")) { ClientContext.Load(web, x => x.Lists); ClientContext.ExecuteQuery(); } var listTitle = field.List; var list = web.Lists.GetByTitle(listTitle); try { ClientContext.Load(list, x=>x.Id); ClientContext.ExecuteQuery(); field.List = list.Id.ToString(); } catch (Exception) { Log.Info("Lookup field " + field.DisplayName + " id:" + field.ID + " cannot be created since the list " + listTitle + " has not been created. Please rund content type creation again after setting up the site hierarchy"); return; } } var fieldXml = field.GetFieldAsXml(); Field newField = fields.AddFieldAsXml(fieldXml, true, AddFieldOptions.AddFieldInternalNameHint); ClientContext.Load(newField); ClientContext.ExecuteQuery(); }
/// <summary> /// Add a field to a fieldCollection based on a FieldCreationInformation object /// </summary> /// <param name="fields"></param> /// <param name="info"></param> /// <returns></returns> public static Field Add(this FieldCollection fields, FieldCreationInformation info) { var fieldSchema = info.ToXml(); return(fields.AddFieldAsXml(fieldSchema, info.AddToDefaultView, AddFieldOptions.AddFieldToDefaultView)); }