public static void CreateContentType(ClientContext ctx, string contentTypeName, string categoryFieldName) { //ctx.Web.ContentTypeExistsByName ContentTypeCollection contentTypes = ctx.Web.ContentTypes; ctx.Load(contentTypes); ctx.ExecuteQuery(); if (ctx.Web.ContentTypeExistsByName(contentTypeName)) { return; } // Create a Content Type Information object. ContentTypeCreationInformation newCt = new ContentTypeCreationInformation(); // Set the name for the content type. newCt.Name = contentTypeName; //Site Page - 0x0101009D1CB255DA76424F860D91F20E6C4118 newCt.ParentContentType = ctx.Web.ContentTypes.GetById("0x0101009D1CB255DA76424F860D91F20E6C4118"); // Set content type to be available from specific group. newCt.Group = "LB Content Types"; // Create the content type. Microsoft.SharePoint.Client.ContentType myContentType = contentTypes.Add(newCt); FieldLinkCollection fieldsCollection = myContentType.FieldLinks; ctx.Load(fieldsCollection); ctx.ExecuteQuery(); FieldCollection fields = ctx.Site.RootWeb.Fields; ctx.Load(fields); ctx.ExecuteQuery(); //Field f = ctx.Site.RootWeb.Fields.GetFieldByInternalName(categoryFieldName); fieldsCollection.Add(new FieldLinkCreationInformation { //Field = ctx.Site.RootWeb.Fields.GetFieldByInternalName(categoryFieldName) Field = fields.GetFieldByInternalName(categoryFieldName) }); myContentType.Update(true); ctx.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(); } }