This is a common file is used to create 'n' number of site columns in SharePoint site.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Taxonomy;
using Microsoft.SharePoint.Publishing;
namespace SPHelper
{
public class SiteColumn
{
/// <summary>
/// Determine if field exists as a site column in the web site
/// </summary>
/// <param name="web"></param>
/// <param name="internalName"></param>
/// <param name="displayName"></param>
/// <returns></returns>
public static bool IsExist(SPWeb web, string internalName, string displayName)
{
bool isExist = false;
try
{
// check to see if field exist by using passed internal name
if (!string.IsNullOrEmpty(internalName)) { isExist = web.Fields.ContainsField(internalName); }
// now check by field's display name, but only if couldn't already find the field using internal name,
// and the displayname is not null, and the display name is different from the internalname
if (!isExist && !string.IsNullOrEmpty(displayName) && displayName != internalName)
{ isExist = web.Fields.ContainsField(displayName); }
}
catch (Exception ex)
{
Log.WriteError("rthdytkyttdyrdrtjesr4e6esr", ex, "internal name: " + internalName);
}
return isExist;
}
/// <summary>
/// Create a new site column
/// </summary>
/// <param name="web">website to add column to (should bee root site!)</param>
/// <param name="internalName"></param>
/// <param name="displayName"></param>
/// <param name="type"></param>
/// <param name="isRequired"></param>
/// <param name="group"></param>
/// <param name="defaultValue"></param>
/// <param name="description"></param>
/// <param name="isThrowErrorIfFieldAlreadyExists"></param>
/// <returns></returns>
public static SPField CreateSiteColumn(SPWeb web, string internalName, string displayName, string description,
string group, bool isRequired, SPFieldType type, string defaultValue,
bool isHidden, bool isThrowErrorIfFieldAlreadyExists)
{
SPField f = null;
try
{
// init
if (web == null) { throw new Exception("SPWeb passed is null"); }
if (string.IsNullOrEmpty(internalName)) { throw new Exception("Internal Name for new site column cannot be null"); }
if (string.IsNullOrEmpty(group)) { throw new Exception("Custom site column group name is not defined"); }
// determine if field already exists
bool isExist = IsExist(web, internalName, displayName);
if (!isExist)
{
// create field
string fieldName = web.Fields.Add(internalName, type, true);
f = web.Fields[fieldName];
// group
f.Group = group;
// required?
f.Required = isRequired;
// default value
if (!string.IsNullOrEmpty(defaultValue)) { f.DefaultValue = defaultValue; }
// description
if (!string.IsNullOrEmpty(description)) { f.Description = description; }
// public title
if (!string.IsNullOrEmpty(displayName)) { f.Title = displayName; }
// hidden?
if (isHidden) { f.Hidden = isHidden; }
// update
f.Update();
}
else if (isThrowErrorIfFieldAlreadyExists)
{
throw new Exception("Site column: " + internalName + " already exists");
}
}
catch (Exception ex)
{
Log.WriteError("ette6idtyidrtsdrrdy", ex, "field internalName: " + internalName);
f = null;
}
return f;
}
public static SPField CreateTextSiteColumn(SPWeb web, string internalName, string displayName, string description,
string group, bool isRequired, string defaultValue, int? displaySize,
bool isThrowErrorIfFieldAlreadyExists)
{
SPField f = null;
try
{
// call original signature
f = CreateSiteColumn(web, internalName, displayName, description, group, isRequired, SPFieldType.Text,
null, false, isThrowErrorIfFieldAlreadyExists);
if (f != null)
{
// default value
if (!string.IsNullOrEmpty(defaultValue)) { ((SPFieldText)f).DefaultValue = defaultValue; }
// display size
if (displaySize != null) { ((SPFieldText)f).DisplaySize = displaySize.Value.ToString(); }
// update
((SPFieldText)f).Update();
}
}
catch (Exception ex)
{
Log.WriteError("r6eutrddfresr55t", ex, "internal name: " + internalName);
f = null;
}
return f;
}
/// <summary>
/// Create a multiline text box site column
/// </summary>
/// <param name="web"></param>
/// <param name="internalName"></param>
/// <param name="displayName"></param>
/// <param name="description"></param>
/// <param name="group"></param>
/// <param name="isRequired"></param>
/// <param name="defaultValue"></param>
/// <param name="numberOfLines"></param>
/// <param name="displaySize"></param>
/// <param name="isRichText"></param>
/// <param name="isThrowErrorIfFieldAlreadyExists"></param>
/// <returns></returns>
public static SPField CreateMultiLineTextSiteColumn(SPWeb web, string internalName, string displayName, string description,
string group, bool isRequired, string defaultValue, int? numberOfLines, int? displaySize,
bool isRichText, bool isThrowErrorIfFieldAlreadyExists)
{
SPField f = null;
try
{
// call original
f = CreateSiteColumn(web, internalName, displayName, description, group, isRequired, SPFieldType.Note,
defaultValue, false, isThrowErrorIfFieldAlreadyExists);
if (f != null)
{
// display size
if (displaySize != null) { ((SPFieldMultiLineText)f).DisplaySize = displaySize.Value.ToString(); }
// number of lines
if (numberOfLines != null) { ((SPFieldMultiLineText)f).NumberOfLines = numberOfLines.Value; }
// is rich text?
((SPFieldMultiLineText)f).RichText = isRichText;
if (isRichText) { ((SPFieldMultiLineText)f).RichTextMode = SPRichTextMode.FullHtml; }
// update
((SPFieldMultiLineText)f).Update();
}
}
catch (Exception ex)
{
Log.WriteError("56dfdsssetfdcd", ex, "internal name: " + internalName);
f = null;
}
return f;
}
/// <summary>
/// Create a dateTime site column
/// </summary>
/// <param name="web"></param>
/// <param name="internalName"></param>
/// <param name="displayName"></param>
/// <param name="description"></param>
/// <param name="group"></param>
/// <param name="isRequired"></param>
/// <param name="defaultValue"></param>
/// <param name="displayFormat"></param>
/// <param name="isThrowErrorIfFieldAlreadyExists"></param>
/// <returns></returns>
public static SPField CreateDateSiteColumn(SPWeb web, string internalName, string displayName, string description,
string group, bool isRequired, DateTime? defaultValue, SPDateTimeFieldFormatType displayFormat,
bool isThrowErrorIfFieldAlreadyExists)
{
SPField f = null;
try
{
// call original signature
f = CreateSiteColumn(web, internalName, displayName, description, group, isRequired, SPFieldType.DateTime,
null, false, isThrowErrorIfFieldAlreadyExists);
if (f != null)
{
// default value
if (defaultValue != null && defaultValue != DateTime.MinValue)
{
string _defaultValue = defaultValue.Value.ToShortDateString();
if (displayFormat == SPDateTimeFieldFormatType.DateTime)
{
_defaultValue += " " + defaultValue.Value.ToShortTimeString();
}
((SPFieldDateTime)f).DefaultValue = _defaultValue;
}
// display format
((SPFieldDateTime)f).DisplayFormat = displayFormat;
// update
((SPFieldDateTime)f).Update();
}
}
catch (Exception ex)
{
Log.WriteError("et6fhtdfewrer", ex, "internal name: " + internalName);
f = null;
}
return f;
}
public static SPField CreateCurrencySiteColumn(SPWeb web, string internalName, string displayName, string description,
string group, bool isRequired, SPNumberFormatTypes currencyFormat, double? defaultValue, double? minValue,
double? maxValue, int? displaySize, bool isThrowErrorIfFieldAlreadyExists)
{
SPField f = null;
try
{
// init
if (defaultValue != null)
{
if (minValue != null && defaultValue < minValue) { throw new Exception("default value is less than the minimum value"); }
if (maxValue != null && defaultValue > maxValue) { throw new Exception("default value is greater than the maximum value"); }
}
// call original signature
f = CreateSiteColumn(web, internalName, displayName, description, group, isRequired, SPFieldType.Currency,
null, false, isThrowErrorIfFieldAlreadyExists);
if (f != null)
{
// display format
((SPFieldCurrency)f).DisplayFormat = currencyFormat;
// min value
if (minValue != null) { ((SPFieldCurrency)f).MinimumValue = minValue.Value; }
// max value
if (maxValue != null) { ((SPFieldCurrency)f).MaximumValue = maxValue.Value; }
// display size
if (displaySize != null) { ((SPFieldCurrency)f).DisplaySize = displaySize.Value.ToString(); }
// default value
if (defaultValue != null) { ((SPFieldCurrency)f).DefaultValue = defaultValue.Value.ToString(); }
// update
((SPFieldCurrency)f).Update();
}
}
catch (Exception ex)
{
Log.WriteError("euuerrsterres", ex, "internal name: " + internalName);
f = null;
}
return f;
}
/// <summary>
/// Create number site column
/// </summary>
/// <param name="web"></param>
/// <param name="internalName"></param>
/// <param name="displayName"></param>
/// <param name="description"></param>
/// <param name="group"></param>
/// <param name="isRequired"></param>
/// <param name="numberFormat"></param>
/// <param name="defaultValue"></param>
/// <param name="minValue"></param>
/// <param name="maxValue"></param>
/// <param name="displaySize"></param>
/// <param name="isShowAsPercentage"></param>
/// <param name="isThrowErrorIfFieldAlreadyExists"></param>
/// <returns></returns>
public static SPField CreateNumberSiteColumn(SPWeb web, string internalName, string displayName, string description,
string group, bool isRequired, SPNumberFormatTypes numberFormat, double? defaultValue, double? minValue,
double? maxValue, int? displaySize, bool isShowAsPercentage, bool isThrowErrorIfFieldAlreadyExists)
{
SPField f = null;
try
{
// init
if (defaultValue != null)
{
if (minValue != null && defaultValue < minValue) { throw new Exception("default value is less than the minimum value"); }
if (maxValue != null && defaultValue > maxValue) { throw new Exception("default value is greater than the maximum value"); }
}
// call original signature
f = CreateSiteColumn(web, internalName, displayName, description, group, isRequired, SPFieldType.Number,
null, false, isThrowErrorIfFieldAlreadyExists);
if (f != null)
{
// display format
((SPFieldNumber)f).DisplayFormat = numberFormat;
// min value
if (minValue != null) { ((SPFieldNumber)f).MinimumValue = minValue.Value; }
// max value
if (maxValue != null) { ((SPFieldNumber)f).MaximumValue = maxValue.Value; }
// display size
if (displaySize != null) { ((SPFieldNumber)f).DisplaySize = displaySize.Value.ToString(); }
// default value
if (defaultValue != null) { ((SPFieldNumber)f).DefaultValue = defaultValue.Value.ToString(); }
// percent?
((SPFieldNumber)f).ShowAsPercentage = isShowAsPercentage;
// update
((SPFieldNumber)f).Update();
}
}
catch (Exception ex)
{
Log.WriteError("t6uftdfxgdfrddrt", ex, "internal name: " + internalName);
f = null;
}
return f;
}
// BROKEN FOR SOME REASON, GET ERROR: The node to be inserted is from a different document context.
///// <summary>
///// Create a choices site column
///// http://niral.net/blog/create-sharepoint-content-type-programmatically
///// </summary>
///// <param name="web"></param>
///// <param name="internalName"></param>
///// <param name="displayName"></param>
///// <param name="isRequired"></param>
///// <param name="group"></param>
///// <param name="choices"></param>
///// <param name="defaultValue"></param>
///// <param name="description"></param>
///// <param name="isThrowErrorIfFieldAlreadyExists"></param>
///// <returns></returns>
//public static SPField CreateChoiceSiteColumn(SPWeb web, string internalName, string displayName, string description,
// string group, bool isRequired, string[] choices, string defaultValue, bool isThrowErrorIfFieldAlreadyExists)
//{
// SPField f = null;
// try
// {
// // call original
// f = CreateSiteColumn(web, internalName, displayName, description, group, isRequired, SPFieldType.Choice,
// null, false, isThrowErrorIfFieldAlreadyExists);
// // if didn't already exist and no errors
// if (f != null)
// {
// // site column successfully created, now set choice specific properties
// if (choices != null && choices.Length > 0)
// {
// Log.WriteInformation("about to add choices");
// bool isDefaultFound = false;
// int defaultIndex = 0;
// int i = 0;
// foreach (string choice in choices)
// {
// // a.) add choice option
// Log.WriteInformation("about to add choice: " + choice);
// ((SPFieldChoice)f).Choices.Add(choice);
// if (choice == defaultValue)
// {
// // b.) default choice found
// isDefaultFound = true;
// defaultIndex = i;
// }
// i++;
// }
// if (!isDefaultFound)
// {
// if (!string.IsNullOrEmpty(defaultValue)) { throw new Exception("Default value: " + defaultValue + " was not found in array of choices passed"); }
// ((SPFieldChoice)f).DefaultValue = string.Empty;
// }
// // update the site column
// Log.WriteInformation("about to update");
// ((SPFieldChoice)f).Update();
// Log.WriteInformation("successfully updated");
// // set default
// if (isDefaultFound)
// {
// ((SPFieldChoice)f).DefaultValue = defaultIndex.ToString();
// Log.WriteInformation("about to update again after setting the default value to: " + defaultIndex.ToString());
// ((SPFieldChoice)f).Update();
// }
// }
// }
// }
// catch (Exception ex)
// {
// Log.WriteError("rh6tthsGGhdrsrt", ex, "field internalName: " + internalName);
// f = null;
// }
// return f;
//}
/// <summary>
/// Create a lookup site column
/// http://niral.net/blog/create-sharepoint-content-type-programmatically
/// </summary>
/// <param name="web"></param>
/// <param name="internalName"></param>
/// <param name="displayName"></param>
/// <param name="description"></param>
/// <param name="group"></param>
/// <param name="isRequired"></param>
/// <param name="lookupListId">SPList.ID</param>
/// <param name="lookupField"></param>
/// <param name="isThrowErrorIfFieldAlreadyExists"></param>
/// <returns></returns>
public static SPField CreateLookupSiteColumn(SPWeb web, string internalName, string displayName, string description,
string group, bool isRequired, Guid lookupListId, string lookupField, bool isThrowErrorIfFieldAlreadyExists)
{
SPField f = null;
try
{
// init
if (web == null) { throw new Exception("SPWeb passes is null"); }
if (string.IsNullOrEmpty(internalName)) { throw new Exception("Internal name passed is null"); }
if (string.IsNullOrEmpty(displayName)) { displayName = internalName; }
if (lookupListId == null || lookupListId == Guid.Empty) { throw new Exception("Invalid list GUID passed to lookup against"); }
if (string.IsNullOrEmpty(lookupField)) { throw new Exception("Lookup Field passed is null"); }
// determine if site column already exists
if (IsExist(web, internalName, displayName))
{
if (isThrowErrorIfFieldAlreadyExists) { throw new Exception("site column already exists: " + internalName); }
}
else
{
// create lookup site column
string fieldname = web.Fields.AddLookup(displayName, lookupListId, isRequired);
f = web.Fields[fieldname];
if (f == null) { throw new Exception("Failed to create lookup list: " + internalName); }
else
{
// remote lookup field
((SPFieldLookup)f).LookupField = lookupField;
// update
((SPFieldLookup)f).Update();
}
}
}
catch (Exception ex)
{
Log.WriteError("tek7rdthddr", ex, "internal name: " + internalName);
f = null;
}
return f;
}
/// <summary>
/// Create new image field
/// http://blog.beckybertram.com/Lists/Posts/Post.aspx?ID=67
/// </summary>
/// <param name="web"></param>
/// <param name="internalName"></param>
/// <param name="displayName"></param>
/// <param name="group"></param>
/// <returns></returns>
public static Microsoft.SharePoint.Publishing.Fields.ImageField CreateImageSiteColumn(SPWeb web, string internalName,
string displayName, string description, string group, bool isThrowErrorIfFieldAlreadyExists)
{
Microsoft.SharePoint.Publishing.Fields.ImageField f = null;
try
{
// init
if (web == null) { throw new Exception("SPWeb passed is null"); }
if (string.IsNullOrEmpty(internalName)) { throw new Exception("Internal name passed is null"); }
if (string.IsNullOrEmpty(displayName)) { displayName = internalName; }
if (string.IsNullOrEmpty(group)) { throw new Exception("Custom site column group name is not defined"); }
if (IsExist(web, internalName, displayName))
{
if (isThrowErrorIfFieldAlreadyExists) { throw new Exception("Site column already exists: " + internalName); }
}
else
{
f = new Microsoft.SharePoint.Publishing.Fields.ImageField(web.Fields, "Image", displayName);
f.Group = group;
f.StaticName = internalName;
f.Title = displayName;
f.RichText = true;
f.RichTextMode = SPRichTextMode.FullHtml;
web.Fields.Add(f);
}
}
catch (Exception ex)
{
Log.WriteError("5ek7itytdrhdfdf", ex);
f = null;
}
return f;
}
/// <summary>
/// Create new link url field
/// http://blog.beckybertram.com/Lists/Posts/Post.aspx?ID=67
/// </summary>
/// <param name="web"></param>
/// <param name="internalName"></param>
/// <param name="displayName"></param>
/// <param name="group"></param>
/// <returns></returns>
public static Microsoft.SharePoint.Publishing.Fields.LinkField CreateLinkSiteColumn(SPWeb web, string internalName,
string displayName, string description, string group, bool isThrowErrorIfFieldAlreadyExists)
{
Microsoft.SharePoint.Publishing.Fields.LinkField f = null;
try
{
// init
if (web == null) { throw new Exception("SPWeb passed is null"); }
if (string.IsNullOrEmpty(internalName)) { throw new Exception("Internal name passed is null"); }
if (string.IsNullOrEmpty(displayName)) { displayName = internalName; }
if (string.IsNullOrEmpty(group)) { throw new Exception("Custom site column group name is not defined"); }
if (IsExist(web, internalName, displayName))
{
if (isThrowErrorIfFieldAlreadyExists) { throw new Exception("Site column already exists: " + internalName); }
}
else
{
f = new Microsoft.SharePoint.Publishing.Fields.LinkField(web.Fields, "Link", displayName);
f.Group = group;
f.StaticName = internalName;
f.Title = displayName;
//f.RichText = true;
//f.RichTextMode = SPRichTextMode.FullHtml;
web.Fields.Add(f);
}
}
catch (Exception ex)
{
Log.WriteError("76ritfgdfdedrt", ex);
f = null;
}
return f;
}
// NOT WORKING: Simply creates text fields. Why?!?
///// <summary>
///// Create Managed Metadata site columns
///// The first SPField in the collection is the managed metadata column.
///// The second SPField in the collection is the hidden note field that must also be added
///// http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.taxonomy.taxonomyfield.aspx
///// http://social.technet.microsoft.com/Forums/en/sharepoint2010programming/thread/310692d3-49f2-4c0f-b911-735f24b769b3
///// </summary>
///// <param name="web"></param>
///// <param name="internalName"></param>
///// <param name="displayName"></param>
///// <param name="description"></param>
///// <param name="group"></param>
///// <param name="isRequired"></param>
///// <param name="defaultValue"></param>
///// <param name="isAllowMultipleValues">Allow multiple terms to be selected?</param>
///// <param name="isCreateValuesInEditForm">Allowed to create new terms into the termset?</param>
///// <param name="isAllowFillInChoices">Allowed to add keywords? (added to the item, but not to the term store)</param>
///// <param name="termSet"></param>
///// <param name="termTargetTemplate">Relative url that is used to display the term when clicked on</param>
///// <param name="isThrowErrorIfFieldAlreadyExists"></param>
///// <returns></returns>
//public static List<SPField> CreateMetadataSiteColumn(SPWeb web, string internalName, string displayName, string description,
// string group, bool isRequired, string defaultValue, bool isAllowMultipleValues,
// bool isCreateValuesInEditForm, bool isAllowFillInChoices,
// TermSet termSet, string termTargetTemplate, bool isThrowErrorIfFieldAlreadyExists)
//{
// List<SPField> taxonomySiteColumns = null;
// try
// {
// // init
// if (web == null) { throw new Exception("SPWeb passed is null"); }
// if (string.IsNullOrEmpty(internalName)) { throw new Exception("Internal name passed is null"); }
// if (string.IsNullOrEmpty(displayName)) { displayName = internalName; }
// if (string.IsNullOrEmpty(group)) { group = "NEMA"; }
// if (termSet == null) { throw new Exception("TermSet passed is null"); }
// TaxonomyField f = null;
// taxonomySiteColumns = new List<SPField>();
// // exist?
// if (IsExist(web, internalName, displayName))
// {
// if (isThrowErrorIfFieldAlreadyExists) { throw new Exception("Duplicate column already exists: " + internalName); }
// }
// else
// {
// // create field
// f = web.Fields.CreateNewField("TaxonomyFieldTypeMulti", displayName) as TaxonomyField;
// // internal name
// f.StaticName = internalName;
// // description
// if (!string.IsNullOrEmpty(description)) { f.Description = description; }
// // group
// f.Group = group;
// // is required?
// f.Required = isRequired;
// // default value
// if (!string.IsNullOrEmpty(defaultValue)) { f.DefaultValue = defaultValue; }
// // allow multiple values?
// f.AllowMultipleValues = isAllowMultipleValues;
// // is allowed to create new terms in the terms store edit form?
// f.CreateValuesInEditForm = isCreateValuesInEditForm;
// // user allowed to create new terms
// f.Open = isAllowFillInChoices;
// //////////////////////////////////////////////////////
// //////////////////////////////////////////////////////
// // termstore
// //////////////////////////////////////////////////////
// //////////////////////////////////////////////////////
// // anchor term
// // If this is set to a GUID of a term only terms that are descendents of the term can be picked
// f.AnchorId = Guid.Empty;
// // term store id
// f.SspId = termSet.TermStore.Id;
// // term set id
// f.TermSetId = termSet.Id;
// // term target url (relative)
// if (!string.IsNullOrEmpty(termTargetTemplate)) { f.TargetTemplate = termTargetTemplate; }
// // create Note site column to be linked to this site column
// string noteInternalName = Taxonomy.FormatNoteFieldInternalName(internalName);
// SPField noteSiteColumn = null;
// try
// {
// noteSiteColumn = web.Fields.GetField(noteInternalName);
// if (noteSiteColumn != null) { Log.WriteInformation("regwegtwge", "Hidden Note field already exists: " + noteInternalName); }
// }
// catch { }
// if (noteSiteColumn == null)
// {
// // note field doesn't already exist, create it
// noteSiteColumn = CreateSiteColumn(web, noteInternalName, internalName + "_0",
// null, group, false, SPFieldType.Note, null, true, false);
// }
// if (noteSiteColumn == null) { throw new Exception("Failed to find or create an accompanying hidden note field for this metadata column"); }
// // link to notes field
// f.TextField = noteSiteColumn.Id;
// // update
// f.Update();
// // add to collection, the first being the taxonomy field, the 2nd being the note field
// // IMPORTANT: BOTH need to be added to the content type!
// taxonomySiteColumns.Add(f);
// taxonomySiteColumns.Add(noteSiteColumn);
// }
// }
// catch (Exception ex)
// {
// Log.WriteError("6uydrtserrH", ex, "internal name: " + internalName);
// taxonomySiteColumns = null;
// }
// return taxonomySiteColumns;
//}
public static bool DeleteSiteColumn(SPWeb web, string displayName)
{
bool isSuccessful = false;
try
{
// init
if (web == null) { throw new Exception("SPWeb passed is null"); }
if (string.IsNullOrEmpty(displayName)) { throw new Exception("Site Column display name passed is null"); }
// get internal name
string internalName = Field.ConvertDisplayNameToInternalName(displayName);
// get site column object
SPField siteColumnToDelete = web.Fields.GetFieldByInternalName(internalName);
if (displayName == null) { throw new Exception("Failed to find site column using internal name: " + internalName); }
// can't delete these types
if (siteColumnToDelete is TaxonomyField) { throw new Exception("Cannot handle deleting managed metadata fields"); }
if (siteColumnToDelete is SPFieldLookup) { throw new Exception("Cannot handle deleting lookup fields"); }
// delete
siteColumnToDelete.Delete();
isSuccessful = true;
}
catch (Exception ex)
{
Log.WriteError("shrjsfhasert43srth", ex, "display name: " + displayName);
isSuccessful = false;
}
return isSuccessful;
}
}
}