Represents a license for an installed managed
package.
This object is available in API version 31.0 and later.
Fields
| Field Name | Details |
|---|---|
| AllowedLicenses |
|
| ExpirationDate |
|
| IsAvailableForIntegrations |
|
| IsProvisioned |
|
| NamespacePrefix |
|
| Status |
|
| UsedLicenses |
|
Usage
Use this object to determine the number of licenses allowed and in use for a managed package installed in your organization.
The following example demonstrates the use of the API to manage licenses for
a package. The example defines an Apex class that does the following.
- Retrieves the PackageLicense record for the specified package (identified by its namespace prefix).
- Defines a function that returns a list of all users with the specified profile.
- Creates a UserPackageLicense record for each user with that profile, which has the effect of assigning a license for the package to all users with that profile.
- Returns an error message if the number of users exceeds the number of available licenses.
public class AssignPackageLicense { static String PACKAGE_NAMESPACE_PREFIX = 'acme_101'; static String PROFILE_ID = '00exx000000jz1SAAQ'; public static String exceptionText {get; set;} public AssignPackageLicense() { exceptionText = 'Initialized'; } static List<User> getUsersWithProfile(){ String userQuery = 'SELECT Id FROM User WHERE ProfileId = :PROFILE_ID'; List<User> matchingUsers = new List<User>(); matchingUsers = [SELECT Id FROM User WHERE ProfileId = :PROFILE_ID]; return matchingUsers; } public static void assignLicenseByProfile() { //find the PackageLicense Id PackageLicense pl = [SELECT Id, NamespacePrefix, AllowedLicenses, UsedLicenses, ExpirationDate,Status FROM PackageLicense WHERE NamespacePrefix = :PACKAGE_NAMESPACE_PREFIX]; System.assert(pl != null, 'PackageLicense cannot be null.'); List<User> usersToAssignLicenses = getUsersWithProfile(); List<UserPackageLicense> firstUPLs = new List<UserPackageLicense>(); //create a new UserPackageLicense record for each user with the specified profile for (Integer i = 0; i< usersToAssignLicenses.size(); i++){ UserPackageLicense upl = new UserPackageLicense(); upl.PackageLicenseId = pl.Id; upl.UserId = usersToAssignLicenses[i].Id; firstUPLs.add(upl); } try { //bulk insert insert(firstUPLs); } catch(DmlException e) { for (Integer i = 0; i < e.getNumDml(); i++) { // process exception here System.debug(e.getDmlMessage(i)); String status = e.getDmlStatusCode(i); System.debug(status + ' ' + e.getDmlMessage(i)); if(status.equals('LICENSE_LIMIT_EXCEEDED')){ exceptionText = 'You tried to assign more licenses than available. ' +' You tried to create '+ firstUPLs.size()+' licenses but only have ' + (pl.AllowedLicenses - pl.UsedLicenses) + ' licenses free.'; System.debug(exceptionText); } } } } }