Quite a while back I experienced the following error generated by the Apply-PnPProvisioningTemplate Cmdlet.

Exception has been thrown by the target of an invocation.

Today I received the same error while I tried to apply PnP Templates to a site that I just created.OfficeDev/PnP

Maybe quite a basic mistake to make to create a new site and then change a few more things within the site and then when the PnP tmeplate is applied the ClientContext object is out of date and the above error is generated.

So to create a new site I’m first creating a new site after I checked that the site doesn’t already exist.

newWeb = web.GetWeb(Url);
if (newWeb == null)
{
WebCreationInformation newWebInfo = new Microsoft.SharePoint.Client.WebCreationInformation();
newWebInfo.WebTemplate = provisioningTemplate.BaseSiteTemplate;
newWebInfo.Description = provisioningTemplate.Description;
newWebInfo.Title = Title;
newWebInfo.Url = Url;
newWebInfo.Language = 1033;
newWeb = web.Webs.Add(newWebInfo);
ctx.Load(newWeb, w => w.Title);
ctx.ExecuteQueryRetry();

}

Then a couple of other things are done to the site. with functions/methods that use their own client context (making my above ctx out of sync)

When running the following to apply the template the Exception is thrown:

newWeb.ApplyProvisioningTemplate(provisioningTemplate, provisioningInfo);

To solve this problem I created a new context and create a new web object from this new context:

ClientContext newWebCtx = new ClientContext(ctx.Web.Url + “/” + Url);

newWebCtx.Credentials = new Microsoft.SharePoint.Client.SharePointOnlineCredentials(username, securePassword);
Web newApplyTemplateWWeb = newWebCtx.Web;
newWebCtx.Load(newWebCtx.Web);
newWebCtx.ExecuteQueryRetry();
ProvisioningTemplateApplyingInformation provisioningInfo = new ProvisioningTemplateApplyingInformation();
newWebCtx.Web.ApplyProvisioningTemplate(provisioningTemplate, provisioningInfo);

By Pieter Veenstra

Business Applications and Office Apps & Services Microsoft MVP working as a Microsoft Productivity Principal Consultant at HybrIT Services. You can contact me using contact@veenstra.me.uk.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: