2

I am applying a temporary fix to some CSOM code whilst a more permanent fix is given to me hence I want to create the equivalent of

 ctx.Web.Lists.GetByTitle("Contoso Documents").ContentTypes.GetByName("Contoso Sales Document")

or even

   ctx.Web.ContentTypes.GetByName("Contoso Sales Document")    

has anyone implemented this or do traverse all the content types in a ContentTypeCollection and try to match the title string

6

How to retrieve Content Type by name using CSOM (implemented as extension method):

public static class ContentTypeExtensions
{
    public static ContentType GetByName(this ContentTypeCollection cts, string name)
    {
        var ctx = cts.Context;
        ctx.Load(cts);
        ctx.ExecuteQuery();
        return Enumerable.FirstOrDefault(cts, ct => ct.Name == name);
    }
}

Examples:

using (var ctx = new ClientContext(url))
{ 
     //1. get site level content type
     var siteContentType = ctx.Site.RootWeb.ContentTypes.GetByName("Document Set");

     //2. get web level content type
     var webContentType = ctx.Web.ContentTypes.GetByName(webContentTypeName);


     //3. get list level content type
     var listContentType = ctx.Web.Lists.GetByTitle(listTitle).ContentTypes.GetByName(listContentTypeName);

}
  • Thanks very much - I will to create this extension method. Out of interest why aren't you needed to reference an SPWeb object. – westerdaled Sep 17 '14 at 16:25
  • That could be a potential performance bottleneck as the while collection is fetched from the server. Reconsidering getting content type by ID might work much better. – avishnyakov Nov 17 '14 at 1:23
  • Indeed it could affect the performance since all content types are retrieved from the server – Vadim Gremyachev Nov 17 '14 at 7:29
  • In case it's tripping up anyone else: be aware of the difference between Web.ContentTypes (msdn.microsoft.com/en-us/library/office/…) and Web.AvailableContentTypes (msdn.microsoft.com/en-us/library/office/…). – nsturdivant Jul 17 '15 at 16:03

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.