'Exception has been thrown by the target of an invocation' during export of webpart for user subsite

Yuvraj Patil 361 Reputation points
2022-08-26T14:56:49.75+00:00

I have one subsite under a user site, which have one wiki page(at least 2,3 versions) with multiple web parts in it.
(To create sub site under subsite:

  1. Go to user site "https://<tenantname>-my.sharepoint.com/personal/<useremailfirstpart>_<tenantname>_onmicrosoft_com"
    for ex. https://bd4-my.sharepoint.com/personal/PaleD_bd4_onmicrosoft_com/Documents/Forms/All.aspx
    user email: PaleD@onmicrosoft.com
  2. Go to site contents from setting option(if not visible view in classic mode)
  3. From site content new option we can create sub site using normal flow.)

Create a wiki page add a web part and publish it. then open page in edit mode and add web part republish again. do this again so file will have 3 versions.

Now when we try to export the web part using below code we get error "Exception has been thrown by the target of an invocation".

// main site url:"https://<tenant>.sharepoint.com/sites/TestSite06";  
// sub site url:"https://<tenant>.sharepoint.com/sites/TestSite06/SubSite01";  
  
var siteCollectionUrl = "https://<tenant>.sharepoint.com/sites/TestSite06"; // Main site  
  
using (ClientContext clientcontext = new ClientContext(siteCollectionUrl))  
{	  
	clientcontext.Credentials = new SharePointOnlineCredentials("username", "password with secure string");  
  
	Web site = clientcontext.Site.OpenWebById(new Guid("f507b7e6-eaee-407d-b56c-05e0aeb2a994")); // open web with subsite id  
	List list = site.Lists.GetById(new Guid("98ef5374-0168-4e33-9a96-56ec0b1c3e44")); // Get site pages using ID from subsite  
	var listItem = list.GetItemByUniqueId(new Guid("1a439e3d-73a6-4ba3-8ea7-b77963aa07b2")); // Get wiki page with Webparts using ID  
	clientcontext.Load(listItem);  
	clientcontext.Load(listItem.File);  
	clientcontext.ExecuteQuery();  
  
	Dictionary<string, string> backupWebparts = new Dictionary<string, string>();  
  
	//Load webparts if any  
	LimitedWebPartManager webPartManager = listItem.File.GetLimitedWebPartManager(PersonalizationScope.Shared);  
	clientcontext.Load(webPartManager.WebParts, wpd => wpd.Include(wp => wp.Id, wp => wp.ZoneId, wp => wp.WebPart));  
  
	clientcontext.ExecuteQuery();  
  
	//Check is webparts instanciated properly and it contains web parts  
	if (null != webPartManager && webPartManager.IsObjectPropertyInstantiated(nameof(webPartManager.WebParts))  
		&& webPartManager.WebParts.AreItemsAvailable && webPartManager.WebParts.Count > 0)  
	{  
		var file = listItem.File;  
  
		foreach (var webPartDef in webPartManager.WebParts)  
		{  
			bool changedExportMode = false;  
			var exportMode = webPartDef.WebPart.ExportMode;  
  
			//Change export mode to all if it is none, as none mode does not allow webpart to export its xml  
			if (webPartDef.WebPart.ExportMode == WebPartExportMode.None)  
			{  
				//when we are changing the export mode, automatically it is checking in file with minor version  
				//to stop creating minor version check in of file, check out the file before doing changes and perform undocheckout after changes  
				//which will not create any minor version check in  
				file.CheckOut();  
  
				webPartDef.OpenWebPart();  
				webPartDef.WebPart.ExportMode = WebPartExportMode.All;  
				webPartDef.SaveWebPartChanges();  
  
				changedExportMode = true;  
			}  
  
			//Getting web part xml  
			var webpartXMLRes = webPartManager.ExportWebPart(webPartDef.Id);  
  
			//Resetting the export mode of webpart to its original value                              
			if (changedExportMode)  
			{  
				//Setting original export mode so that original value should get backed up  
				webPartDef.WebPart.ExportMode = exportMode;  
  
				//discard the checkout as we have checked out earlier  
				file.UndoCheckOut();  
			}  
  
			clientcontext.ExecuteQuery();  
  
			//Adding webpart into backup, after resetting export mode to its original value  
			backupWebparts.Add(webPartDef.Id.ToString(), webpartXMLRes.Value);  
		}  
	}  
  
}  

Please someone help. Thanks in advance !

@RaytheonXie_MSFT
@Tong Zhang_MSFT

SharePoint Server
SharePoint Server
A family of Microsoft on-premises document management and storage systems.
2,297 questions
SharePoint
SharePoint
A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.
10,274 questions
SharePoint Development
SharePoint Development
SharePoint: A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.Development: The process of researching, productizing, and refining new or existing technologies.
2,807 questions
SharePoint Server Development
SharePoint Server Development
SharePoint Server: A family of Microsoft on-premises document management and storage systems.Development: The process of researching, productizing, and refining new or existing technologies.
1,597 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Tong Zhang_MSFT 9,141 Reputation points
    2022-09-01T07:19:04.07+00:00

    Hi @Yuvraj Patil ,

    Based on the code you provided, I cannot reproduce your problem, in my test, there is an error in this sentence : var webPartDef=webPartManager.WebParts[0]; . As a workaround, I recommend you can refer to the following code to export SharePoint Webpart using CSOM:

    var limitedWebPartManager = file.GetLimitedWebPartManager(PersonalizationScope.Shared);  
                var webPartDefinitons = limitedWebPartManager.WebParts;  
                clientcontext.Load(webPartDefinitons);  
                clientcontext.ExecuteQuery();  
                foreach (var webpartDefintion in webPartDefinitons)  
                {  
                    try  
                    {  
                        var webPartId = webpartDefintion.Id;  
                        var webPartXML = limitedWebPartManager.ExportWebPart(webPartId);  
                        clientcontext.ExecuteQuery();  
                        clientcontext.Load(webpartDefintion, def => def.ZoneId, def => def.Id);  
                        clientcontext.ExecuteQuery();  
      
                    }  
                    catch (Exception exception)  
                    {  
                        Console.WriteLine(exception);  
                    }  
                }  
    

    More information for reference: Export SharePoint Webpart using csom

    Hope it can help you. Thanks for your understanding.

    Note: Microsoft is providing this information as a convenience to you. The sites are not controlled by Microsoft. Microsoft cannot make any representations regarding the quality, safety, or suitability of any software or information found there. Please make sure that you completely understand the risk before retrieving any suggestions from the above link.


    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.