Field Name | Details |
---|---|
AllowedLicenses |
|
ExpirationDate |
|
NamespacePrefix |
|
Status |
|
UsedLicenses |
|
Use this object to determine the number of licenses allowed and in use for a managed package installed in your organization.
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); } } } } }