salesforceapexsfdc-metadata-api

Apex script to uninstall an unmanaged package throws INSUFFICIENT_ACCESS: insufficient access rights error


I'm trying to write a simple script in apex to handle the uninstallation of an unmanaged package. The code is as follows

 public static void uninstallPackage() {    
    String[] fullNames = new String[1];
    fullNames[0] = 'SomePackage';
    System.debug('fullNames -->'+fullNames);
    MetadataService.DeleteResult[] result = createService().deleteMetadata('InstalledPackage',fullNames);
}   
private static  MetadataService.MetadataPort createService() {
    MetadataService.MetadataPort service = new MetadataService.MetadataPort();
    service.SessionHeader = new MetadataService.SessionHeader_element();
    service.SessionHeader.sessionId = UserInfo.getSessionId();
    return service;
}

When I run this script I get the following error 'INSUFFICIENT_ACCESS: insufficient access rights on cross-reference id faultcode=sf:INSUFFICIENT_ACCESS faultactor='

I tried searching for all possible solutions, but all pointed out to have the Modify All permission enabled on the profile that is handling this script, And yes, I am using a sys admin profile to run this script and the permission is enabled.

I tried using a connected app to get the session id , but again that also didn't heal the issue.

Could somebody please help me solve this?


Solution

  • On further study found that the above-said script doesn't work for an unmanaged package. Using the above script we are able to uninstall a managed package. We are supposed to give the namespace of the package as the name parameter As unmanaged package doesn't have a namespace, we will not be able to uninstall an unmanaged package.