Monday, February 11, 2013

SharePoint Content Deployment Error - Cannot open file .webpart

I was getting this error “Cannot open file myOldWebpart.webpart” during SharePoint 2010 content deployment job run. The webpart it was given is one of the old webparts I used some time ago but renamed later. So I was wondering whether there are any references left for this old webpart in the content database.

Therefore I used following SQL query to discover any location references for the myOldWebpart.webpart file in content database.

USE  [My-Content-DB]
SELECT DirName, LeafName
FROM [dbo].[AllDocs]
WHERE LeafName = 'myOldWebpart.webpart'

Query result showed that there is a reference in the Web Part Gallery (_catalogs/wp). Since it was the only reference, removing myOldWebpart.webpart file from the webpart gallery fixed my error.

Note:
To prevent such issue happening, it is recommended to write code in the FeatureDeactivating event handler to delete all the webpart template files that were created during feature activation.

Here is a sample code to enumerate through the Web Part Gallery looking for the first part of the webpart file name to delete.

/// <summary>
/// Occurs when a Feature is deactivated.
/// </summary>
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
    SPSite site = properties.Feature.Parent as SPSite;
    SPWeb web = site.RootWeb;

    List<SPFile> filesToDelete = new List<SPFile>();
    SPList webpartGallery = web.Lists["Web Part Gallery"];

    foreach (SPListItem webpartFile in webpartGallery.Items)
    {
        if (webpartFile.File.Name.Contains("myWebpart"))
        {
            filesToDelete.Add(webpartFile.File);
        }
    }

    // Delete .webpart files
    foreach (SPFile file in filesToDelete)
    {
        file.Delete();
    }           
}

However above method will not help if we uninstall the solution package without deactivating the feature. In that case we have to check .webpart file in the Web Part Gallery and have to delete it manually.

No comments: