6

I am looking at the documentation for adding a contenttype via code using Sharepoint CSOM. The example uses a hardcoded ID.

foreach (var item in contentTypes)
{
   if (item.StringId == "0x0101009189AB5D3D2647B580F011DA2F356FB2")
   return;
}

// Create a Content Type Information object.
ContentTypeCreationInformation newCt = new ContentTypeCreationInformation();
// Set the name for the content type.
newCt.Name = "Contoso Document";
// Inherit from oob document - 0x0101 and assign. 
newCt.Id = "0x0101009189AB5D3D2647B580F011DA2F356FB2";
// Set content type to be available from specific group.
newCt.Group = "Contoso Content Types";
// Create the content type.
ContentType myContentType = contentTypes.Add(newCt);
cc.ExecuteQuery();

What is this ID? Where does it come from? Can we generate it? We need to add multiple contenttypes.

8

A valid content type Id can be constructed using one of the following ways

  1. Parent content type ID + two hexadecimal values (the two hexadecimal values cannot be "00")
  2. Parent content type ID + "00" + hexadecimal GUID

Refer in detail about content type ids.

If you do not want to take up this pain of constructing the Content Type Ids by yourself, then you can have SharePoint generate the ID for you.

Use this code. SharePoint will generate Id by itself.

Web rootWeb = clientContext.Site.RootWeb;

// create by reference
var itemContentTypes = clientContext.LoadQuery(rootWeb.ContentTypes.Where(ct => ct.Name == "Item"));  
clientContext.ExecuteQuery();

var itemContentType = itemContentTypes.FirstOrDefault();

if (itemContentType != null) {  
    rootWeb.ContentTypes.Add(new ContentTypeCreationInformation {
        Name = "Your Content Type Name",
        Group = "Your Group Name",
        ParentContentType = itemContentType
    });
    clientContext.ExecuteQuery();
}
else {  
    throw new InvalidOperationException("Item Content Type not found");
}

Refer Programmatically creating Site Columns and Content Types

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.