I'm adding a custom content type and then setting it as default content type for a custom content type. I has followed the instruction on the internet. When I execute the code, my custom content type has been added but it hasn't been set as default content type (No error, exception when running). Here is my code:
List list = web.Lists.GetByTitle(lname);
list.ContentTypesEnabled = true;
list.ContentTypes.AddExistingContentType(contentType);
var ctypes = list.ContentTypes;
context.Load(ctypes);
context.ExecuteQuery();
var ids = new List<ContentTypeId>();
foreach(var content in ctypes)
{
ids.Add(GetByName(ctypes, content.Name).Id);
}
ids.Reverse();
list.RootFolder.UniqueContentTypeOrder = ids;
list.RootFolder.Update();
list.Update();
context.Load(list.RootFolder, r => r.UniqueContentTypeOrder);
Console.WriteLine("Content-type Added!");
The function GetByName above I use to get the ContentType by name:
public static ContentType GetByName(ContentTypeCollection cts, string name)
{
var ctx = cts.Context;
ctx.Load(cts);
ctx.ExecuteQuery();
return Enumerable.FirstOrDefault(cts, ct => ct.Name == name);
}
So, where did I get it wrong? How can I solve it?
Try to set default content type for list using code below.
List aeList = context.Web.Lists.GetByTitle(lname);
var currentCtOrder = aeList.ContentTypes;
context.Load(currentCtOrder, coll => coll.Include(
ct => ct.Name,
ct => ct.Id));
context.ExecuteQuery();
IList<ContentTypeId> reverseOrder = (from ct in currentCtOrder where ct.Name.Equals("CustomContentTypeName", StringComparison.OrdinalIgnoreCase) select ct.Id).ToList();
aeList.RootFolder.UniqueContentTypeOrder = reverseOrder;
aeList.RootFolder.Update();
aeList.Update();
context.ExecuteQuery();