I am trying to create a new list from an existing list template using CSOM in a SharePoint Online environment.
Here is my code:
using (ClientContext ctx = new ClientContext(WebURL))
{
ctx.Credentials = new SharePointOnlineCredentials(UserName, Password);
var web = ctx.Web;
var templates = web.ListTemplates;
ctx.Load(web, s => s.ListTemplates);
ctx.ExecuteQuery();
var archiveTemplate = templates.GetByName(ArchiveTemplate);
ListCreationInformation lic = new ListCreationInformation();
lic.Title = "New List";
lic.TemplateFeatureId = archiveTemplate.FeatureId;
lic.TemplateType = archiveTemplate.ListTemplateTypeKind;
web.Lists.Add(lic);
ctx.ExecuteQuery();
}
This results in the following exception
Microsoft.SharePoint.Client.PropertyOrFieldNotInitializedException was unhandled HResult=-2146233079 Message=The property or field 'FeatureId' has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested. Source=Microsoft.SharePoint.Client.Runtime StackTrace: bei Microsoft.SharePoint.Client.ClientObject.CheckUninitializedProperty(String propName) bei Microsoft.SharePoint.Client.ListTemplate.get_FeatureId()
I tried to load the properties explicitly by doing the following:
ctx.Load(archiveTemplate, at => at.FeatureId);
ctx.ExecuteQuery();
This results in the following exception: Microsoft.SharePoint.Client.ServerException was unhandled HResult=-2146233088 Message=Value does not fall within the expected range. Source=Microsoft.SharePoint.Client.Runtime
What am I doing wrong? Thanks for your help!
After further investigation, it seems as if I need to use the following code to retrieve my custom list template:
var templates = ctx.Site.GetCustomListTemplates(web);
ctx.Load(templates);
ctx.ExecuteQuery();
var template = templates.First(t => t.Name == ArchiveTemplate);
The problem then is that I cannot provide this template within the ListCreationInformation used to add a new list.