I have a requirement to always use the internal field name for columns in custom Visual Studio projects. I want to use the internal string value of the field name consistently and have the following two methods defined.
An example of how and when I need to use the internal field name is as follows:
properties.ListItem["My Field Name"] = "";
In place of "My Field Name" I always want to use the internal field name. In lots of instances site collection owners will rename fields from "MyOriginalInternalFieldName" to "My Field Name", for example. The code above still needs to work.
Are the below methods the best way to always use the internal field name string value?
(NOTE: I found them here: http://apicollection.wikia.com/wiki/Get_And_Set_Value_By_Field_Internal_Name )
public object GetValueInternalName(SPListItem item, string fieldInternalName)
{
if (item == null)
throw new ArgumentNullException("item");
if (item.Fields.ContainsField(fieldInternalName))
{
SPField field = item.Fields.GetFieldByInternalName(fieldInternalName);
if (item[field.Id] != null || string.IsNullOrEmpty(field.DefaultValue))
return item[field.Id];
else if (field.FieldValueType == typeof(Boolean))
return bool.Parse((field.DefaultValue == "0") ? bool.FalseString : bool.TrueString);
else
return Convert.ChangeType((field.DefaultValueTyped != null) ? field.DefaultValueTyped : field.DefaultValue, field.FieldValueType);
}
return null;
}
public void SetValueInternalName(SPListItem item, string fieldInternalName, object value)
{
SPField field = item.Fields.GetFieldByInternalName(fieldInternalName);
if (value is DateTime && (DateTime)value == DateTime.MinValue)
item[field.Id] = null;
else
item[field.Id] = value;
}
Is there a way I could include a custom "utilities" class that I could reuse across projects so that I don't have to put these two methods in multiple times into the classes where I need to use them?