static void Main(string[] args)
{
string siteUrl = "http://localhost";
List<string> fieldNames = new List<string>();
Program p = new Program();
using (SPSite site = new SPSite(siteUrl))
{
using (SPWeb web = site.OpenWeb())
{
SPContentType newContentType;
newContentType = p.CreateContentType(web,
"MyFirstContentType",
"Item");
p.CreateSiteColumn(web, "MyColumn",
SPFieldType.Text,
false);
fieldNames.Add("MyColumn");
p.CreateSiteColumn(web, "MyColumn2",
SPFieldType.Text,
false);
fieldNames.Add("MyColumn2");
p.AddFields(web, fieldNames.ToArray(), newContentType);
Console.WriteLine("{0} | {1} | {2}", "Title".PadRight(20),
"Type".PadRight(20),
"Group".PadRight(20));
Console.WriteLine(new string(′-′, 70));
foreach (SPField fld in newContentType.Fields)
{
Console.WriteLine("{0} | {1} | {2}", fld.StaticName.PadRight(20),
fld.TypeDisplayName.PadRight(20),
fld.Group.PadRight(20));
}
}
}
Console.ReadLine();
}
void CreateSiteColumn(SPWeb web, string name, SPFieldType fieldType,
bool isRequired)
{
if (!web.AvailableFields.ContainsField(name))
{
web.Fields.Add(name, fieldType, isRequired);
}
}
void AddFields(SPWeb web, string[] fieldNames, SPContentType contentType)
{
foreach (string fieldname in fieldNames)
{
if (web.Fields.ContainsField(fieldname))
{
SPFieldLink fieldLink = new SPFieldLink(web.Fields[fieldname]);
contentType.FieldLinks.Add(fieldLink);
}
}
//Update should be called to persist these changes
//contentType.Update();
}