Office 365 Dev Tip - Retrieve all tenant-level WebTemplates in your Office 365 tenant using CSOM

Here’s another simple and quick tip for Office 365 dev (with SharePoint Online).

In this post I’ll simply show how you can easily get the Tenant-level Web Templates and information about then. In recent weeks, this topic has been cause of many discussions I’ve had with people who have been asking about Office 365 and CSOM. Since I think it’ll be easier to just show once here instead of replying uniquely to those e-mails, let’s just get to the code and see how you can do this.

Pre-requisites

In order to run the code in the snippet you should already have:

Office 365 dev – code Snippet

Here’s a simple code snippet which will get your tenant-level WebTemplates.

using (ClientContext context = new ClientContext("https://yourdomain-admin.sharepoint.com"))
{
    // Create a new Microsoft.Online.SharePoint.TenantAdministration Tenant object and reference the client context of your Admin site
    Tenant tenant = new Tenant(context);
    tenant.Context.Load(tenant);
    tenant.Context.ExecuteQueryRetry();

    // Reference the Office 365 PnP Core library and use the tenant.GetWebTemplates() extension method if you want. Easy as pie!
    var webTemplates = tenant.GetWebTemplates(1033, 15);

    /*
    Note: 
    The reason for this extension method is simply to avoid having to call context.Load() and context.ExecuteQuery() manually.
    Using the extension from the PnP, it will essentially just run this code for you under the hood: 
    
    var templates = tenant.GetSPOTenantWebTemplates(lcid, compatibilityLevel);
    tenant.Context.Load(templates);
    tenant.Context.ExecuteQueryRetry();
    return templates;
    Seeing that, you may understand why I want to use the PnP extension-method to keep my (visible) code cleaner.
    */

    // That's really all there's to it - we now have our Web Templates. Do with them as you please.
    foreach (var webTemplate in webTemplates)
    {
        // TODO: Add your code logic here to work with the template code.
        Debug.WriteLine("TEMPLATE: " + webTemplate.Name);
    }
}

Here’s a list of all the properties available in the WebTemplate class:

public int CompatibilityLevel { get; }
public string Description { get; }
public string DisplayCategory { get; }
public uint Lcid { get; }
public string Name { get; }
public string Title { get; }
public override string TypeId { get; }

Enjoy :-)