Salesforce
// Get Object Type from Id
Id sampleid = '0684N00000AWcZp'; System.debug('object is '+ sampleid.getsobjecttype());
// Check if you are running in Test
if ( Test.isRunningTest() )
// Check to see if you are running in sandbox
public static Boolean runningInASandbox() {
return [SELECT Id, IsSandbox FROM Organization LIMIT 1].IsSandbox;
}
// Iterate through all of the values on the Object (Limit 10)
for (integer i = 2 ; i < 11 ; i++){
String ICD10pos = String.valueOf(i).leftPad(2,'0');
String ICD10Field = 'ICD10_' + ICD10pos + '__c';
Object myCIObj = myEpisode.get(ICD10Field);
if (myCIObj != null) {
String myCIKey = String.valueOf(myCIObj);
String myCIValue = icd10Map.get(Id.valueOf(myCIKey)).Name;
//System.debug('TESTING: ' + ICD10Field + ' - ' + myCIKey + ' - ' + myCIValue);
EDI_837_Claim_Information__c myCI = new EDI_837_Claim_Information__c(
Information_Type__c = 'ABF',
Information_Code__c = myCIValue.replaceAll('[^A-Za-z0-9_]', '')
);
eClaim.myClaimInformation.add(myCI);
}
}
// Iterate CPTs
if (!myPC.EDI_837_Service_Lines__r.IsEmpty()) {
for (EDI_837_Claim_Service_Line__c sl : myPC.EDI_837_Service_Lines__r) {
String CPT = sl.SL_Procedure_Code__c;
if (sl.SL_Procedure_Code_Modifier__c != null) {
if (CPTSet.contains(CPT)) CPTSet.remove(CPT);
CPT = CPT + '(' + sl.SL_Procedure_Code_Modifier__c + ')';
}
CPTSet.add(CPT);
//ClaimSL += sl.SL_Procedure_Code__c + '\n';
}
}
String ClaimSL = String.join(new List<String>(CPTSet), '\n');
//Map of List
Contact[] temp;
Map<Id, Contact[]> contacts = new map<Id, Contact[]>();
for(Contact record: [SELECT AccountId FROM Contact]) {
if((temp = contacts.get(record.AccountId)) == null) {
contacts.put(record.AccountId, temp = new Contact[0]);
}
temp.add(record);
}
// Email
public class SendMail {
public String status = 'Complete';
public String msg = '';
public void AddMessage(String m) {
msg += m;
}
public void Send() {
//sending to salesforce user
//will NOT count against limit because we are using 'setTargetObjectId'
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setTargetObjectId(UserInfo.getUserId());
mail.setSubject('Electronic Provider Claim, Status: ' + status);
mail.setPlainTextBody(msg);
//when sending mail to users, you have to set this switch to false
mail.setSaveAsActivity(false);
// Send the email you have created.
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}
SendMail mail = new SendMail();
mail.AddMessage('This is a Debug Statement.\n');
mail.AddMessage('This is a Error Statement.\n'); //e.getMessage()
mail.Send();
-- Allow users to view all accounts but only edit specific account record types
-- Roles (Only needed for hierachy)
1. Create a Role for Account Managers under Office Head
1.1 Restrict access to Opportunities and Cases to records owned
-- Profiles
2. Clone Profile
2.1 Configure tab settings for objects access
2.2 Configure record type settings for access
2.3 Deselect unneeded Admin Permissions
2.4 Deselect unneeded General User Permissions
2.5 Deselect unneeded Standard Object Permissions (min permissions - Accts with Read/Create only)
2.6 Deselect unneeded Custom Object Permissions
-- Permission Sets
3. Create permission set
3.1 Edit Object settings for accounts to add edit permission for specific record type
-- Grant Login Access
4. Select <Name> -> My Settings
4.1 Enter Login in Quick Find
4.2 Select Grant Account Login Access for Sys Admin for specific time period.
LIST<Episode__c> eps = [Select ID, DOS__C, Original_DOS__C FROM Episode__c WHERE Original_DOS__c= null];
for (Episode__c e : eps) {
e.Original_DOS__c = e.DOS__c;
}
update eps;
----
claimHandling_Dev myClaim = new claimHandling_Dev('a1161000004RVzq');
Id rVal = EClaim.makeOutBound837('ZirMed', '0016100000P8b73');
System.Debug ('`ID: ' + rVal);
----
Set <String> tmpList = new Set <String>();
tmpList.add('test 1');
tmpList.add('test 2');
tmpList.add('test 1');
System.debug(tmpList);
String tmpString = ''+tmpList;
System.debug(tmpString);
String joinedString = String.join(new List<String>(tmpList), '\n');
System.debug(joinedString);
----
String hour = String.valueOf(Datetime.now().hour());
String min = String.valueOf(Datetime.now().minute() + 10);
String ss = String.valueOf(Datetime.now().second());
//parse to cron expression
String nextFireTime = ss + ' ' + min + ' ' + hour + ' * * ?';
OutputSchedule_187 s = new OutputSchedule_187();
System.schedule('Job Started At ' + String.valueOf(Datetime.now()), nextFireTime, s);
----
Blob key = Crypto.generateAesKey(128);
Blob data = Blob.valueOf('Data to be encrypted');
Blob encrypted = Crypto.encryptWithManagedIV('AES128', key, data);
Blob decrypted = Crypto.decryptWithManagedIV('AES128', key, encrypted);
String decryptedString = decrypted.toString();
System.assertEquals('Data to be encrypted', decryptedString);
----------
Blob targetBlob = Blob.valueOf('ExampleMD5String');
Blob hash = Crypto.generateDigest('MD5', targetBlob);
------
Blob key = Crypto.generateAesKey(128);
Blob data = Blob.valueOf('Data to be encrypted');
Blob encrypted = Crypto.encryptWithManagedIV('AES128', key, data);
Blob hash = Crypto.generateDigest('MD5', data);
System.debug('Encrypted: ' + EncodingUtil.base64Encode(encrypted));
System.debug('Hash: ' + EncodingUtil.base64Encode(hash));
Blob decrypted = Crypto.decryptWithManagedIV('AES128', key, encrypted);
String decryptedString = decrypted.toString();
System.assertEquals('Data to be encrypted', decryptedString);
global class InvalidateEmails implements SandboxPostCopy {
global void runApexClass(SandboxContext context) {
System.debug(context.organizationId());
System.debug(context.sandboxId());
System.debug(context.sandboxName());
run();
}
static Map < String, Map < String, Object >> objectConditionals = new Map < String, Map < String, Object >> {
'Lead' => new Map < String,
Object > {
'isConverted' => false
}
};
global static void run() {
// Map from SObject to List of Email Fields
Map < String, List < String >> soEmailFieldMap = findEmaiLFields();
// Invalidate Email fields found on SObjects
processEmailFields(soEmailFieldMap);
}
private static Map < String, List < String >> findEmaiLFields() {
Map < String, List < String >> soEmailFieldMap = new Map < String, List < String >> ();
// Iterate over all SObjects
for (SObjectType soType: Schema.getGlobalDescribe().values()) {
DescribeSObjectResult soDescribe = soType.getDescribe();
// Skip objects we cannot query or update
if (!soDescribe.isQueryable() || !soDescribe.isUpdateable()) continue;
String objectTypeName = soDescribe.getName();
// Iterate over all fields found on a given SObject
for (SObjectField soField: soDescribe.fields.getMap().values()) {
DescribeFieldResult field = soField.getDescribe();
// Skip non Email type fields
if (field.getType() != Schema.DisplayType.EMAIL) continue;
// Skip emails that cannot be filtered on
if (!field.isFilterable()) continue;
// Collect all Email fields found
if (soEmailFieldMap.containsKey(objectTypeName)) {
soEmailFieldMap.get(objectTypeName).add(field.getName());
} else {
soEmailFieldMap.put(objectTypeName, new List < String > {
field.getName()
});
}
}
}
return soEmailFieldMap;
}
private static void processEmailFields(Map < String, List < String >> soEmailFieldMap) {
// Iterate over the SObject to Email Fields collection
for (String objectName: soEmailFieldMap.keySet()) {
// Get any specified conditionals
Map < String, Object > conditionals = new Map < String, Object > ();
if (objectConditionals.containsKey(objectName)) conditionals = objectConditionals.get(objectName);
// Build a list of all fields that need to be queried
List < String > emailFields = soEmailFieldMap.get(objectName);
List < String > fieldList = new List < String > ();
fieldList.addAll(emaiLFields);
fieldList.addAll(conditionals.keySet());
// Generate a SOQL query to get records with non null emails
String soql = getSOQL(objectName, fieldList);
System.debug(soql);
List < SObject > records = new List < SObject > ();
// Iterate over queried SObject records
for (SObject record: Database.query(soql)) {
// Skip records that do not match specified conditons
if (!checkConditions(record, conditionals)) continue;
// Iterate over Email fields found on SObject and invalidate values
for (String field: emailFields) {
String email = (String) record.get(field);
if (String.isEmpty(email)) continue;
record.put(field, email.replaceAll('\\W', '_') + '@disabled.diabled');
}
records.add(record);
}
System.debug(JSON.serializePretty(records));
update records;
}
}
private static boolean checkConditions(SObject record, Map < String, Object > conditionals) {
for (String field: conditionals.keySet()) {
Object value = record.get(field);
Object condition = conditionals.get(field);
if (value != condition) return false;
}
return true;
}
global static String getSOQL(String objectTypeName, List < String > fieldList) {
List < String > conditionals = new List < String > ();
for (String field: fieldList) conditionals.add(field + ' != null');
String soql = 'SELECT {!fieldList} FROM {!objectTypeName} WHERE {!conditionals}';
return soql
.replace('{!fieldList}', String.join(fieldList, ','))
.replace('{!objectTypeName}', objectTypeName)
.replace('{!conditionals}', String.join(conditionals, ' OR '));
}
}
-- 21543
<complexType name="ListViewRecord">
<sequence>
<element name="columns" type="tns:ListViewRecordColumn" minOccurs="1" maxOccurs="unbounded"/>
</sequence>
<xsd:attribute name="tmp" type="xsd:string"></xsd:attribute>
</complexType>
ZirMed2SF.exe regen a1161000004S8urAAC
https://cs91.salesforce.com/apexdebug/traceDownload.apexp?id=07L2F00000Dcq3PUAR
// Find and Delete User Logs
SELECT Id, StartTime, LogUser.Name, LogLength, Location FROM ApexLog
// Find Logs of Code Failures
SELECT Id, Status, Request, Application, Operation
FROM ApexLog
WHERE Status != 'Success'
AND Location = 'SystemLog'
ORDER By StartTime DESC
LIMIT 10
// Find Recently Updated Triggers/Classes for Deployment
SELECT Id,Name,LastModifiedDate FROM ApexClass ORDER BY LastModifiedDate DESC NULLS LAST
SELECT Id,Name,LastModifiedDate FROM ApexTrigger ORDER BY LastModifiedDate DESC NULLS LAST
SELECT Id,EntityDefinition.DeveloperName,DeveloperName,RelationshipLabel,LastModifiedDate FROM CustomField ORDER BY LastModifiedDate DESC NULLS LAST
public class CustomException extends Exception {
public static string CUSTOMSUBSTRING = 'FIELD_CUSTOM_VALIDATION_EXCEPTION';
public static string ENDSINBRACKET = ': []' ;
// Removes extraneous stuff from the exception message and returns it
public static string CleanMessage(Exception ex) {
string msg = ex.getMessage().Trim() ; // Remove whitespace from front/back
if (msg.contains(CUSTOMSUBSTRING)) msg = msg.substring(msg.indexOf(CUSTOMSUBSTRING) + 2 + CUSTOMSUBSTRING.length()) ;
if (msg.endsWith(ENDSINBRACKET)) msg = msg.removeEnd(ENDSINBRACKET) ;
return msg;
}
public static void LogException(Exception e){
try{
String QueryLimit = '1. SOQL Queries used / SOQL Queries allowed: ' + Limits.getQueries() + '/' + Limits.getLimitQueries();
String DMLimit = '2. Number of records queried so far / Number allowed: ' + Limits.getDmlRows() + '/' + Limits.getLimitDmlRows();
String DMLStat = '3. Number of DML statements used so far / Number allowed: ' + Limits.getDmlStatements() + '/' + Limits.getLimitDmlStatements();
String CPUT = '4. Amount of CPU time (in ms) used so far / CPU usage time (in ms) allowed: ' + Limits.getCpuTime() + '/' + Limits.getLimitCpuTime();
//Create exception record
CustomException__c exc = new CustomException__c();
exc.Gov_Limit_Tracking_in_Executed_Code_Cont__c = String.format('{0}\n{1}\n{2}\n{3}',new List{QueryLimit, DMLimit,DMLStat,CPUT});
exc.Error_Message__c = e.getMessage();
exc.Exception_Type__c = e.getTypeName();
exc.Line_Number__c = e.getLineNumber();
exc.Stack_Trace__c = e.getStackTraceString();
database.insert(exc);
} catch (Exception exc) {
}
} //end method
}
throw new CustomException ('Unable to find Patient Claim: ' + myClaimId);
// First Line in Trigger return without executing if disabled
if (TriggerControl.IsDisabled('Trigger Name')) return;
public class TriggerControl {
/**************************************************************************
* IsDisabled (string triggerName)IsDisabled
* Returns TRUE if the specified Trigger is disabled, FALSE otherwise.
**************************************************************************/
public static Boolean IsDisabled (string triggerName) {
Boolean enabled = true;
TriggerControl__c tAll = TriggerControl__c.getValues('ALL');
TriggerControl__c tt = TriggerControl__c.getValues(triggerName);
enabled &= (tall==null) ? true : tAll.Enabled__c;
enabled &= (tt==null)? true : tt.Enabled__c;
enabled &= (AdditionalTriggerControl.containskey(triggerName)) ? AdditionalTriggerControl.get(triggerName) : true;
if (!enabled) System.debug('`Skipping Trigger: ' + triggerName + ', it is disabled.');
if (enabled) System.debug('`Start Trigger: ' + triggerName);
return !enabled ;
}
public static MAP<string,boolean> AdditionalTriggerControl = new MAP<string,boolean>();
/**************************************************************************
* EnableTrigger (triggerName, Boolean enable)
* Only for the current connection - disable (or enable) the specified trigger
**************************************************************************/
public static void EnableTrigger (string triggerName, Boolean enable) {
AdditionalTriggerControl.put (triggerName, enable) ;
}
/**************************************************************************
* EnableAllTriggers (Boolean enable)
* this method can be used to disable (or enable) all triggers.
* Pass FALSE to Disable, TRUE to Enable
**************************************************************************/
public static void EnableAllTriggers (Boolean enable) {
TriggerControl__c tAll = TriggerControl__c.getValues('ALL');
if (tAll == null) {
tAll = new TriggerControl__c (Name = 'ALL', Enabled__c = enable) ;
}
tAll.Enabled__c = enable;
upsert tAll;
}
}
/* In Order to Parse JSON Response in Apex one must use JSONParse Class
*
* 1. Initiate JSONParser as parser
* 2. Pass res.getBody() or JSON body as parameter to Json.CreateParser()
* 3. And parser.nextToken() is responsible for getting next Token/node of JSON body
*/
JSONParser parser = JSON.createParser(res.getBody());
while (parser.nextToken() != null) {
if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
String fieldName = parser.getText();
parser.nextToken();
if (fieldName == 'ContactId') {
//accesstoken = parser.getText();
system.debug('contactId Text() => ' + parser.getText());
} else if (fieldName == 'CompanyName') {
//expiresIn = parser.getIntegerValue();
system.debug('COmpany Text() => ' + parser.getText());
} else if (fieldName == 'Country') {
//expiresIn = parser.getIntegerValue();
system.debug('COmpany Text() => ' + parser.getText());
} else if (fieldName == 'LastName') {
//expiresIn = parser.getIntegerValue();
system.debug('COmpany Text() => ' + parser.getText());
} else if (fieldName == 'City') {
//expiresIn = parser.getIntegerValue();
system.debug('COmpany Text() => ' + parser.getText());
} else if (fieldName == 'State') {
//expiresIn = parser.getIntegerValue();
system.debug('COmpany Text() => ' + parser.getText());
} else if (fieldName == 'FirstName') {
//expiresIn = parser.getIntegerValue();
system.debug('COmpany Text() => ' + parser.getText());
}
}
}
// Top-level (outer) class must be public or global Usually public.
// Must be global if they contain a Web Service.
Global Class LogHandling {
Public String ApexClass;
Public String ApexMethod;
Public Datetime LogStartDt = System.now();
Public Datetime LogEndDt;
Public String LogHeader = '';
Public String LogDetail = '';
Public String LogTrailer = '';
Public Boolean IsDebug = FALSE;
Public Id UserId = UserInfo.getUserId();
/*
* Log Contructor
*/
Public LogHandling() {
Exception_Log__c Info = New Exception_Log__c();
Info.Exception_Type__c = 'LoggingLevel.Info';
}
/*
* Initialize Log and Start Logging
*/
Public void StartLogging(String cls, String method){
ApexClass = cls;
ApexMethod = method;
LogStartDt = System.now();
LogHeader = 'User Name: ' + UserInfo.getUserName() + ' \n' + 'User Email: ' + UserInfo.getUserEmail() + ' \n';
LogHeader = LogHeader + 'Apex Class: ' + cls + ' \n' + 'Apex Method: ' + method + ' \n';
LogHeader = LogHeader + 'Start Logging: ' + System.now().format() + ' \n';
}
/*
* Stop Logging and Capture Limits
*/
Public void StopLogging(){
String QueryLimit = '1. SOQL Queries used / SOQL Queries allowed: ' + Limits.getQueries() + '/' + Limits.getLimitQueries();
String DMLimit = '2. Number of records queried so far / Number allowed: ' + Limits.getDmlRows() + '/' + Limits.getLimitDmlRows();
String DMLStat = '3. Number of DML statements used so far / Number allowed: ' + Limits.getDmlStatements() + '/' + Limits.getLimitDmlStatements();
String CPUT = '4. Amount of CPU time (ms) used so far / CPU usage time allowed: ' + Limits.getCpuTime() + '/' + Limits.getLimitCpuTime();
LogEndDt = System.now();
//LogTrailer = 'Stopped Logging: ' + LogEndDt.format() + ' \n ';
LogTrailer = String.format('\n{0}\n{1}\n{2}\n{3}',new List<String>{QueryLimit,DMLimit,DMLStat,CPUT});
//System.debug(LoggingLevel.Error, new DmlException().getStackTraceString());
}
/*
* Add Information/Debug Log Entry
*/
Public void LogInfo(String NewLogEntry){
LogDetail = LogDetail + System.now() + ' - [INFO] ' + NewLogEntry +'\n';
System.Debug(LOGGINGLEVEL.INFO, NewLogEntry);
}
Public void LogInfo(Integer LineNumber, String NewLogEntry){
LogDetail = LogDetail + System.now() + ' - [' + LineNumber + '] ' + NewLogEntry +'\n';
System.Debug(LOGGINGLEVEL.DEBUG, NewLogEntry);
}
Public void SaveInfo(){
StopLogging();
Exception_Log__c Info = New Exception_Log__c();
Info.Exception_Type__c = 'LoggingLevel.Info';
Info.Governor_Limits__c = LogTrailer;
Info.Stack_Trace__c = ApexClass + ':' + ApexMethod;
try {
database.insert(Info);
} catch (Exception e) {
LogException(e);
}
String Log = LogHeader + '\n' + LogDetail + '\n' + LogTrailer + '\n' + 'Stopped Logging: ' + LogEndDt.format() + ' \n ';
// Attachment Custom Debug Log
try {
Attachment logfile = new Attachment(ParentId = Info.Id, Body=Blob.valueOf(Log),Name='DebugLogger '+System.now());
database.insert(logfile);
} catch (Exception e) {
}
try{
} catch (Exception ex) {
LogException(ex);
}
}
/*
* Add Exception Log Entry
*/
Public void LogException(Exception e){
StopLogging();
Exception_Log__c exl = new Exception_Log__c ();
//exl.Governor_Limits__c = LogTrailer;
exl.Error_Message__c = e.getMessage();
exl.Exception_Type__c = e.getTypeName();
exl.Line_Number__c = e.getLineNumber();
exl.Stack_Trace__c = e.getStackTraceString();
List<String> ExceptionData = New List<String>();
ExceptionData.add(ApexClass); // 0
ExceptionData.add(ApexMethod); // 1
ExceptionData.add(LogHeader); // 2
ExceptionData.add(LogDetail); // 3
ExceptionData.add(LogTrailer); // 4
ExceptionData.add(exl.Error_Message__c); // 5
ExceptionData.add(exl.Exception_Type__c); // 6
ExceptionData.add(exl.Line_Number__c.format()); // 7
ExceptionData.add(exl.Stack_Trace__c); // 8
LogExceptionFuture(ExceptionData);
}
@future(callout=true)
Public Static void LogExceptionFuture(List<String> ExceptionData){
Id UserId = UserInfo.getUserId();
ApexLog SysLog = [
SELECT Id, Status, Request, Application, Operation
FROM ApexLog
WHERE Status != 'Success'
AND LogUserId = :UserId
AND Location = 'SystemLog'
ORDER By StartTime DESC
LIMIT 1];
Blob SysLogDetail;
try {
If (SysLog != null) SysLogDetail = GetSystemLog(SysLog.Id);
} catch (Exception e) {
System.Debug(e.getMessage());
}
String Log = ExceptionData.get(2) + '\n' + ExceptionData.get(3) + '\n' + ExceptionData.get(4) +'\n' + 'Stopped Logging: ' + System.now().format() + ' \n ';
Exception_Log__c exl = new Exception_Log__c ();
//exl.Gov_Limit_Tracking_in_Executed_Code_Cont__c = ExceptionData.get(4);
exl.Governor_Limits__c = ExceptionData.get(4);
exl.Error_Message__c = ExceptionData.get(5);
exl.Exception_Type__c = ExceptionData.get(6);
exl.Line_Number__c = Decimal.valueOf(ExceptionData.get(7));
exl.Stack_Trace__c = ExceptionData.get(8);
database.insert(exl);
// Attachment Custom Debug Log
try {
Attachment logfile = new Attachment(ParentId = exl.Id, Body=Blob.valueOf(Log),Name='DebugLog '+System.now()+'.txt');
database.insert(logfile);
} catch (Exception e) {
}
// Attach System Log
try {
Attachment sysfile = new Attachment(ParentId = exl.Id, Body=SysLogDetail,Name='SysLog '+System.now()+'.txt');
database.insert(sysfile);
} catch (Exception e) {
}
}
/*
* Get System Log
*/
Public Static Blob GetSystemLog(String LogId){
String endpoint = URL.getSalesforceBaseUrl().toExternalForm()+'/services/data/v45.0/sobjects/ApexLog/'+ LogId +'/Body';
String method = 'GET';
HttpRequest req = new HttpRequest();
req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID());
req.setHeader('Content-Type', 'text/plain');
req.setEndpoint(endpoint);
req.setMethod(method);
Http h = new Http();
HttpResponse res = h.send(req);
return res.getBodyAsBlob();
}
/*
* Get Current APEX Class Name
*/
global static String getClassName()
{
String line = new DmlException().getStackTraceString().substringAfter('\n');
if (line.startsWith('Class.'))
line = line.substringAfter('Class.');
return line.substringBefore(':').substringBeforeLast('.');
}
/*
* Get Current Apex Method Name
*/
global static String getMethodName()
{
String line = new DmlException().getStackTraceString().substringAfter('\n');
return line.substringBefore(':').substringAfterLast('.');
}
/*
* Get Line Number
*/
Public Static Integer GetLineNumber() {
try {
Integer x = 0 / 0;
} catch(Exception e) {
String line2 = e.getStackTraceString().split('\n')[1];
Pattern patt = Pattern.compile('([a-z0-9_.]+): line (\\d+)');
Matcher match = patt.matcher(line2);
match.find();
Return Integer.valueOf(match.group(2));
}
Return null;
//return new DmlException().getLineNumber();
}
}
Global Class ExceptionHandling {
Public Static void Log(Exception e){
System.Debug(LOGGINGLEVEL.ERROR,e.getMessage());
}
Public Static void Log(String m, Exception e){
System.Debug(LOGGINGLEVEL.ERROR,m + e.getMessage());
}
Public Static void LogAndSave(Exception e){
Log(e);
SaveException(e);
}
Public Static void LogAndSave(String m, Exception e){
Log(m,e);
SaveException(e);
}
Public Static void LogAndThrow(Exception e){
Log(e);
SaveException(e);
Throw e;
}
Public Static void LogAndThrow(String m, Exception e){
Log(m,e);
SaveException(e);
Throw e;
}
/*************************************************************
* Parse Exception before Saving
*/
Public Static void SaveException(Exception e){
List<String> LimitsData = New List<String>();
String QueryLimit = '1. SOQL Queries used / SOQL Queries allowed: ' + Limits.getQueries() + '/' + Limits.getLimitQueries();
String DMLimit = '2. Number of records queried so far / Number allowed: ' + Limits.getDmlRows() + '/' + Limits.getLimitDmlRows();
String DMLStat = '3. Number of DML statements used so far / Number allowed: ' + Limits.getDmlStatements() + '/' + Limits.getLimitDmlStatements();
String CPUT = '4. CPU time (in ms) used so far / CPU usage time allowed: ' + Limits.getCpuTime() + '/' + Limits.getLimitCpuTime();
String HeapLimit = '5. Heap Size (in bytes) / Heap Size allowed: ' + Limits.getHeapSize() + '/' + Limits.getLimitHeapSize();
String FutureLimit = '6. Future Calls used / Future Calls allowed: ' + Limits.getFutureCalls() + '/' + Limits.getLimitFutureCalls();
String QueueLimit = '7. Queueable Jobs used / Queueable Jobs allowed: ' + Limits.getQueueableJobs() + '/' + Limits.getLimitQueueableJobs();
String FindLimit = '8. SOSL Queries used / SOSL Queries allowed: ' + Limits.getSoslQueries() + '/' + Limits.getLimitSoslQueries();
LimitsData.add(QueryLimit); // 0
LimitsData.add(DMLimit); // 1
LimitsData.add(DMLStat); // 2
LimitsData.add(CPUT); // 3
LimitsData.add(HeapLimit); // 4
LimitsData.add(FutureLimit); // 5
LimitsData.add(QueueLimit); // 6
LimitsData.add(FindLimit); // 7
String DMLErrors = '';
if (e.getTypeName().Contains('DmlException')) {
Integer numErrors = e.getNumDml();
DMLErrors = 'DML Error Count = ' + numErrors + ' \n';
for(Integer i=0;i<numErrors;i++) {
DMLErrors = DMLErrors + 'Field Name: ' + e.getDmlFieldNames(i) + ' Error Message: ' + e.getDmlMessage(i) + ' \n';
}
}
List<String> ExceptionData = New List<String>();
ExceptionData.add(e.getTypeName()); // 0
ExceptionData.add(e.getLineNumber().format()); // 1
ExceptionData.add(e.getMessage()); // 2
ExceptionData.add(e.getStackTraceString()); // 3
ExceptionData.add(DMLErrors); // 4
ExceptionData.add(getClassName(e)); // 5
ExceptionData.add(getMethodName(e)); // 6
try{
if ( !System.isFuture() && !System.isBatch() && Limits.getFutureCalls() < Limits.getLimitFutureCalls() ) {
SaveExceptionFuture(ExceptionData, LimitsData);
} else {
SaveExceptionNow(ExceptionData, LimitsData);
}
} catch (Exception ex) {
System.Debug('Exception Logging Failed! ' + ex.getMessage());
}
} //end method
/*************************************************************
* Save Exception Immediately (Instead of a Future Call)
*/
Public Static void SaveExceptionNow(List<String> ExceptionData, List<String> LimitsData){
Exception_Log__c exl = new Exception_Log__c ();
exl.Exception_Type__c = ExceptionData.get(0);
exl.Line_Number__c = Decimal.valueOf(ExceptionData.get(1));
exl.Error_Message__c = ExceptionData.get(2);
exl.Stack_Trace__c = ExceptionData.get(3);
exl.DML_Errors__c = ExceptionData.get(4);
exl.Apex_Class__c = ExceptionData.get(5);
exl.Apex_Method__c = ExceptionData.get(6);
exl.Governor_Limits__c = String.format('{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}',LimitsData);
exl.Log_Type__c = 'Exception';
try {
Database.Insert(exl);
} catch (Exception ex) {
System.Debug('Exception Logging Failed! ' + ex.getMessage());
}
} //end method
/*************************************************************
* Save Exception as a Future Call
*/
@future(callout=true)
Public Static void SaveExceptionFuture(List<String> ExceptionData, List<String> LimitsData){
Exception_Log__c exl = new Exception_Log__c ();
Id UserId = UserInfo.getUserId();
Blob SysLogDetail;
String SysLogError = '\n';
try {
ApexLog SysLog = [
SELECT Id, Status, Request, Application, Operation
FROM ApexLog
WHERE Status != 'Success'
AND LogUserId = :UserId
AND Location = 'SystemLog'
ORDER By StartTime DESC
LIMIT 1];
If (SysLog != null) {
SysLogDetail = GetSystemLog(SysLog.Id);
exl.Apex_Operation__c = SysLog.Operation;
exl.Apex_Request__c = SysLog.Request;
}
} catch (Exception e) {
System.Debug(e.getMessage());
SysLogError = e.getMessage() + '\n';
}
exl.Exception_Type__c = ExceptionData.get(0);
exl.Line_Number__c = Decimal.valueOf(ExceptionData.get(1));
exl.Error_Message__c = ExceptionData.get(2) + SysLogError;
exl.Stack_Trace__c = ExceptionData.get(3);
exl.DML_Errors__c = ExceptionData.get(4);
exl.Apex_Class__c = ExceptionData.get(5);
exl.Apex_Method__c = ExceptionData.get(6);
exl.Governor_Limits__c = String.format('{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}',LimitsData);
exl.Log_Type__c = 'Exception';
try {
Database.Insert(exl);
Attachment sysfile = new Attachment(ParentId = exl.Id, Body=SysLogDetail,Name='SysLog '+System.now()+'.txt');
if (SysLogDetail != null) Database.Insert(sysfile);
} catch (Exception ex) {
System.Debug('Exception Logging Failed! ' + ex.getMessage());
}
} //end method
/*************************************************************
* Get System Log
*/
Public Static Blob GetSystemLog(String LogId){
// https://cs91.salesforce.com/apexdebug/traceDownload.apexp?id=07L2F00000Dcq3PUAR
String endpoint = URL.getSalesforceBaseUrl().toExternalForm()+'/services/data/v45.0/sobjects/ApexLog/'+ LogId +'/Body';
String method = 'GET';
HttpRequest req = new HttpRequest();
req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID());
req.setHeader('Content-Type', 'text/plain');
req.setEndpoint(endpoint);
req.setMethod(method);
Http h = new Http();
HttpResponse res = h.send(req);
return res.getBodyAsBlob();
} //end method
/*************************************************************
* Get Apex Class Name
*/
global static String getClassName(Exception e) {
String line = e.getStackTraceString();
//String line = e.getStackTraceString().substringAfter('\n'); // Gets the Second line in the Trace
if (line.startsWith('Class.'))
line = line.substringAfter('Class.');
return line.substringBefore(':').substringBeforeLast('.');
} //end method
/*************************************************************
* Get Apex Method Name
*/
global static String getMethodName(Exception e) {
String line = e.getStackTraceString();
//String line = e.getStackTraceString().substringAfter('\n'); // Gets the Second line in the Trace
return line.substringBefore(':').substringAfterLast('.');
} //end method
} //end class
public class Randomizer {
//returns a random Integer
public static Integer getRandomNumber(Integer size){
Double d = math.random() * size;
return d.intValue();
}
//returns either true or false randomly
public static Boolean getRandomBoolean(){
if(math.mod(getRandomNumber(10),2) == 0){
return true;
}
else{
return false;
}
}
//Get's a random value from a list of strings
public static String getRandomString(List<String> strings){
List<Double> ranks = new List<Double>();
Map<Double,String> rankMap = new Map<Double,String>();
for(String s : strings){
Boolean isDup = true;
Double rank;
While(isDup){
Double x = getRandomNumber(100000);
if(!rankMap.containsKey(x)){
rank = x;
isDup = false;
}
}
ranks.add(rank);
rankMap.put(rank,s);
}
ranks.sort();
return rankMap.get(ranks.get(0));
}
//Returns a random picklist value
public static string getRandomPickListValue(Sobject s_object, String field_name, Boolean allow_blank){
List<String> Strings = new List<String>();
if(allow_blank){
String b = '';
Strings.add(b);
}
Schema.sObjectType sobject_type = s_object.getSObjectType();
Schema.DescribeSObjectResult sobject_describe = sobject_type.getDescribe();
Map<String, Schema.SObjectField> field_map = sobject_describe.fields.getMap();
List<Schema.PicklistEntry> pick_list_values = field_map.get(field_name).getDescribe().getPickListValues();
for (Schema.PicklistEntry a : pick_list_values) {
Strings.add(a.getValue());
}
return getRandomString(Strings);
}
//returns a map of all picklists and multiselect picklists for a givien object
//the keyset is the field name using proper case
public static Map<String,List<String>> getPicVals(sObject s_object){
Map<String,List<String>> valueMap = new Map<String,List<String>>();
Schema.sObjectType sobject_type = s_object.getSObjectType();
Schema.DescribeSObjectResult r = sobject_type.getDescribe();
Map<String, Schema.SObjectField> field_map = r.fields.getMap();
for(String s : field_map.keyset()){
List<String> strings = new List<String>();
Schema.DescribeFieldResult F = field_map.get(s).getDescribe();
if(f.GetType() == Schema.DisplayType.Picklist || f.GetType() == Schema.DisplayType.MultiPicklist){
List<Schema.PicklistEntry> pick_list_values = field_map.get(s).getDescribe().getPickListValues();
for (Schema.PicklistEntry a : pick_list_values) {
strings.add(a.getValue());
}
valueMap.put(String.valueOf(field_map.get(s)),strings);
}
}
return valueMap;
}
//Returns Lorem Ipsum placeholder text.
public static String getPlaceholderText(Integer length){
String firstSentence = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. ';
List<String> sentenceList = new List<String>();
sentenceList.add('Vivamus nec lacus eget massa cursus pulvinar. ');
sentenceList.add('Morbi vel odio eget nunc auctor posuere eget eget ante. ');
sentenceList.add('Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. ');
sentenceList.add('Pellentesque lacus eros. ');
sentenceList.add('Sed suscipit tristique varius. ');
sentenceList.add('Mauris ultricies, nibh eu fermentum accumsan, justo quam pulvinar tellus, sed tempor quam eros sit amet ante. ');
sentenceList.add('Duis mi libero, cursus nec facilisis ut, commodo eget nunc. ');
sentenceList.add('Nulla eros augue, iaculis sed volutpat et, sagittis quis sem. ');
sentenceList.add('Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nulla placerat accumsan vulputate. ');
sentenceList.add('Fusce placerat tellus eget tellus faucibus a gravida sapien fermentum. ');
String s = firstSentence;
while (s.length() < length+1){
s += getRandomString(sentenceList);
}
s = s.trim();
while (s.length() >= length-1){
s = s.substring(0,s.length()-1).trim();
}
s = s.substring(0,s.length()-1).trim();
s += '.';
return s;
}
static testMethod void testRandomizer() {
test.startTest();
Integer testInt = getRandomNumber(10);
Boolean testBool = getRandomBoolean();
List<String> testStringList = new List<String>();
testStringList.add('one');
testStringList.add('two');
testStringList.add('three');
String testString = getRandomString(testStringList);
String testString2 = getRandomPickListValue(new Account(), 'Industry', true);
String testString3 = getRandomPickListValue(new Account(), 'Industry', false);
Map<String,List<String>> testMap = getPicVals(new Account());
test.stopTest();
String testString4 = getPlaceholderText(300);
}
}
SFDCRandomizerClass.txt
Displaying SFDCRandomizerClass.txt.
http://www.salesforcefast.com/p/utility-class.html
Great stuff!
=================================================================================
// Object: util
// Author: John Westenhaver
// Comments: Utility code
// =================================================================================
global without sharing class util
{
// ==============================================================================
// RECORD TYPES
// ==============================================================================
// Get the ID for a Record Type, given its Name. Note
// that this is NOT the Developer Name but rather the Name.
global static ID getRecordTypeId(String objType, String name)
{
SObject obj;
Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objType);
if (targetType != null)
{
obj = targetType.newSObject();
Schema.DescribeSObjectResult d = obj.getSObjectType().getDescribe();
if (d != null)
{
map<string, schema.recordtypeinfo=””> rtMap = d.getRecordTypeInfosByName();
if (rtMap != null)
{
Schema.RecordTypeInfo rtInfo = rtMap.get(name);
if (rtInfo != null)
{
return rtInfo.getRecordTypeId();
}
}
}
}
return null;
}
// Testing this is tricky because what if there aren’t any
// record types in the database yet? We will look for any
// existing record type and use that instead.
private static testMethod void testRt()
{
list types =
[SELECT Id, Name, SObjectType FROM RecordType LIMIT 1];
if (types.size() == 1)
{
ID rtId = getRecordTypeId(types[0].SobjectType, types[0].Name);
system.assert(rtId != null && String.valueOf(rtId).length() == 18);
rtId = getRecordTypeId(‘ABC’, ‘DEF’);
system.assert(rtId == null);
}
}
// ==============================================================================
// VISUALFORCE
// ==============================================================================
// Get a list of picklist values from an existing object field.
global static list getPicklistValues(SObject obj, String fld)
{
list options = new list();
// Get the object type of the SObject.
Schema.sObjectType objType = obj.getSObjectType();
// Describe the SObject using its object type.
Schema.DescribeSObjectResult objDescribe = objType.getDescribe();
// Get a map of fields for the SObject
map<string, schema.sobjectfield=””> fieldMap = objDescribe.fields.getMap();
// Get the list of picklist values for this field.
list values =
fieldMap.get(fld).getDescribe().getPickListValues();
// Add these values to the selectoption list.
for (Schema.PicklistEntry a : values)
{
options.add(new SelectOption(a.getLabel(), a.getValue()));
}
return options;
}
private static testMethod void testVf()
{
// The standard Account object’s standard Industry field is a picklist.
// Required fields or validation rules on the Account object will cause
// this to fail.
list testOptions =
getPicklistValues(new Account(Name = ‘Test’), ‘Industry’);
system.assert(testOptions.size() > 0);
}
// ==============================================================================
// STRINGS
// ==============================================================================
// Implement toString() methods for simple variables.
global static String toString(Integer val) { return val.format(); }
global static String toString(Decimal val) { return val.toPlainString(); }
global static String toString(Double val) { return val.format(); }
global static String toString(Long val) { return val.format(); }
global static String toString(Date val) { return val.format(); }
global static String toString(Date val, String fmt)
{
Datetime tmp = Datetime.newInstance(val.year(), val.month(), val.day());
return tmp.format(fmt);
}
global static String toString(Datetime val) { return val.format(); }
global static String toString(Datetime val, String fmt) { return val.format(fmt); }
global static String toString(Time val) { return String.valueOf(val); }
global static String toString(Time val, String fmt)
{
Datetime tmp = Datetime.newInstance(1970, 1, 1, val.hour(), val.minute(), val.second());
return tmp.format(fmt);
}
global static String toString(Boolean val) { if (val) return ‘true’; else return ‘false’; }
private static testMethod void testToString()
{
system.assertEquals(‘12,345’, toString(Integer.valueOf(12345)));
system.assertEquals(‘1.2345’, toString(Decimal.valueOf(‘1.2345’)));
system.assertEquals(‘1.234’, toString(Double.valueOf(‘1.2345’)));
system.assertEquals(‘1,234,567,890’, toString(Long.valueOf(‘1234567890’)));
system.assertEquals(‘1/1/1970’, toString(Date.newInstance(1970, 1, 1)));
system.assertEquals(‘January 1, 1970’,
toString(Date.newInstance(1970, 1, 1), ‘MMMM d, yyyy’));
system.assertEquals(‘January 1, 1970’,
toString(Datetime.newInstance(1970, 1, 1, 0, 0, 0), ‘MMMM d, yyyy’));
system.assertEquals(‘1/1/1970 12:00 AM’,
toString(Datetime.newInstance(1970, 1, 1, 0, 0, 0)));
system.assertEquals(’00:00:00.000Z’, toString(Time.newInstance(0, 0, 0, 0)));
system.assertEquals(’12:00′, toString(Time.newInstance(0, 0, 0, 0), ‘hh:mm’));
system.assertEquals(‘true’, toString(true));
system.assertEquals(‘false’, toString(false));
}
global static final String RANDOM_CHARS =
‘ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789’;
global static final String ALPHA_CHARS =
‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’;
global static final String PUNCTUATION_CHARS =
‘`~!@#$%^&*()_+-={}[]:”;\'<>?,\\./\”‘;
global static final String RANDOM_ALPHA = ’25’;
global static final String RANDOM_ALL = ’35’;
// Generate random strings.
global static String getRandomAlphaString(Integer len)
{ return getRandomString(len, RANDOM_ALPHA); }
global static String getRandomString(Integer len)
{ return getRandomString(len, RANDOM_ALL); }
global static String getRandomString(Integer len, String mode)
{
String retVal = ”;
if (len != null && len >= 1)
{
Integer chars = 0;
Integer random;
do
{
random = Math.round(Math.random() * Integer.valueOf(mode));
retVal += RANDOM_CHARS.substring(random, random + 1);
chars++;
} while (chars < len);
}
return retVal;
}
// Is this string alpha?
global static Boolean isAlpha(String val)
{
Integer len = val.length();
for (Integer i = 0; i < len; i++)
{
if (!ALPHA_CHARS.contains(val.substring(i, i + 1)))
{
return false;
}
}
return true;
}
// Is this string alphanumeric?
global static Boolean isAlphaNumeric(String val)
{
Integer len = val.length();
for (Integer i = 0; i < len; i++)
{
if (!RANDOM_CHARS.contains(val.substring(i, i + 1)))
{
return false;
}
}
return true;
}
// Does this string contain punctuation?
global static Boolean hasPunctuation(String val)
{
Integer len = val.length();
for (Integer i = 0; i < len; i++)
{
if (PUNCTUATION_CHARS.contains(val.substring(i, i + 1)))
{
return true;
}
}
return false;
}
// Is this string null? empty?
global static Boolean isNull(String val)
{
return (val == null ? true : false);
}
global static Boolean isBlank(String val)
{
return ((val == null || val == ”) ? true : false);
}
// Does this string have whitespace within it?
global static Boolean hasWhitespace(String val)
{
return (val.contains(‘ ‘) ||
val.contains(‘\n’) ||
val.contains(‘\t’) ||
val.contains(‘\f’) ||
val.contains(‘\r’));
}
global static Boolean hasCrlf(String val)
{
return (val.contains(‘\n’) || val.contains(‘\r’));
}
// Create shortcuts for substring().
global static String left(String val, Integer len)
{
String retVal = val;
if (len <= val.length())
{
retVal = val.substring(0, len);
}
return retVal;
}
global static String right(String val, Integer len)
{
String retVal = ”;
retVal = val.substring(val.length() – len);
return retVal;
}
// Remove the final delimiter from a string.
global static String stripFinal(String val, String delim)
{
String retVal = ”;
if (val.endsWith(delim))
{
retVal = left(val, val.length() – delim.length());
}
return retVal;
}
// Join together an array of Strings delimited as specified.
global static String joinList(String[] lst, String delim)
{
String retVal = ”;
Boolean firstOne = true;
for (String s : lst)
{
if (s != null)
{
if (firstOne)
{
firstOne = false;
}
else
{
retVal += delim;
}
retVal += s;
}
}
return retVal;
}
private static testMethod void testStrings()
{
system.assertEquals(true, isAlpha(‘ABC’));
system.assertEquals(false, isAlpha(‘___’));
system.assertEquals(true, isAlphaNumeric(‘ABC123’));
system.assertEquals(false, isAlphaNumeric(‘______’));
system.assertEquals(true, isNull(null));
system.assertEquals(false, isNull(”));
system.assertEquals(true, isBlank(”));
system.assertEquals(false, isBlank(‘_’));
system.assertEquals(true, hasWhitespace(‘ ‘));
system.assertEquals(false, hasWhitespace(‘_’));
system.assertEquals(true, hasCrlf(‘\n’));
system.assertEquals(false, hasCrlf(‘_’));
system.assertEquals(true, hasPunctuation(‘#$%’));
system.assertEquals(false, hasPunctuation(‘ABC’));
system.assertEquals(6, getRandomAlphaString(6).length());
system.assertEquals(6, getRandomString(6).length());
system.assertEquals(6, getRandomString(6, RANDOM_ALPHA).length());
system.assertEquals(‘ABC’, left(‘ABCDEF’, 3));
system.assertEquals(‘DEF’, right(‘ABCDEF’, 3));
system.assertEquals(‘1,2,3’, stripFinal(‘1,2,3,’, ‘,’));
String[] lst = new String[] { ‘1’, ‘2’, ‘3’ };
system.assertEquals(‘1,2,3’, joinList(lst, ‘,’));
}
// ==============================================================================
// DATES, TIMES & DATETIMES
// ==============================================================================
// Get date portion of datetime.
global static Date getDate(Datetime dt)
{
return Date.newInstance(dt.year(), dt.month(), dt.day());
}
// Get datetime from date.
global static Datetime getDatetime(Date d)
{
return Datetime.newInstance(d, Time.newInstance(0, 0, 0, 0));
}
// Get the date of the end of the month.
// toStartOfMonth() gives us the beginning of the month.
global static Date getEndofMonth()
{
return system.today().addMonths(1).toStartOfMonth().addDays(-1);
}
global static Date getEndofMonth(Date d)
{
return d.addMonths(1).toStartOfMonth().addDays(-1);
}
// Get the first day of the next month as a date.
global static Date getBeginNextMonth()
{
return system.today().addMonths(1).toStartofMonth();
}
global static Date getBeginNextMonth(Date d)
{
return d.addMonths(1).toStartofMonth();
}
// Get the date of the end of the week.
// toStartOfWeek() gives us the beginning of the week.
global static Date getEndofWeek()
{
return system.today().addDays(7).toStartOfWeek().addDays(-1);
}
global static Date getEndofWeek(Date d)
{
return d.addDays(7).toStartOfWeek().addDays(-1);
}
// Given a time string in the format HH:MM, in 24-hour format,
// return that as a time.
global static Time getTime(String s)
{
if (s.length() == 5)
{
Integer hours = Integer.valueOf(s.substring(0, 2));
Integer minutes = Integer.valueOf(s.substring(3, 5));
Time t = Time.newInstance(hours, minutes, 0, 0);
return t;
}
return null;
}
// Given a datetime, return the time component.
global static Time getTime(Datetime dt)
{
String t = dt.format(‘hh:mm’);
return getTime(t);
}
// Given a time component, return that as a time string.
global static String getTime(Time t)
{
String retval = ”;
Integer hours = t.hour();
Integer minutes = t.minute();
String h = ‘0’ + hours.format();
String m = ‘0’ + minutes.format();
retVal = (h.substring(h.length()-2, h.length()) +
‘:’ + m.substring(m.length()-2, m.length())).substring(0, 5);
return retVal;
}
// Given two times or datetimes, determine the number of seconds between them.
global static Long getSecondsBetween(Time t1, Time t2)
{
Datetime dt1 = Datetime.newInstance(system.today(), t1);
Datetime dt2 = Datetime.newInstance(system.today(), t2);
Long secondsBetween = dt2.getTime() – dt1.getTime();
return Math.abs(secondsBetween / 1000L);
}
global static Long getSecondsBetween(Datetime dt1, Datetime dt2)
{
Long secondsBetween = dt2.getTime() – dt1.getTime();
return Math.abs(secondsBetween / 1000L);
}
// Given the number of seconds between two date/times,
// calculate the number of minutes. Fractional minutes are dropped.
global static Long getMinutesBetween(Datetime dt1, Datetime dt2)
{
return (getSecondsBetween(dt1, dt2) / 60L);
}
// Calculate the number of hours. Fractional hours are dropped.
global static Long getHoursBetween(Datetime dt1, Datetime dt2)
{
return (getSecondsBetween(dt1, dt2) / 3600L);
}
// Adjust this list to match your locale and business rules.
global static list dows =
new String[]{ ‘Su’, ‘Mo’, ‘Tu’, ‘We’, ‘Th’, ‘Fr’, ‘Sa’ };
global static Integer getDow(Date d)
{
Integer dow = -1;
if (d != null)
{
String day = Datetime.newInstance(d,
Time.newInstance(0, 0, 0, 0)).format(‘E’).substring(0, 2);
for (Integer i = 0; i < 7; i++)
{
if (day == dows[i])
{
dow = i;
break;
}
}
}
return dow;
}
// Get the name of the day of the week.
global static String getDowName(Date d)
{
return Datetime.newInstance(d,
Time.newInstance(0, 0, 0, 0)).format(‘EEEE’);
}
private static testMethod void testDates()
{
Date testDate = Date.newInstance(1970, 1, 1);
Datetime testDatetime = Datetime.newInstance(1970, 1, 1, 0, 0, 0);
Datetime testDatetime2 = testDatetime.addHours(1);
Time testTime = Time.newInstance(0, 0, 0, 0);
Time testTime2 = testTime.addHours(1);
system.assertEquals(testDate, getDate(testDatetime));
system.assertEquals(testDatetime, getDatetime(testDate));
system.assertEquals(testDate.addMonths(1).toStartOfMonth().addDays(-1),
getEndofMonth(testDate));
system.assertEquals(system.today().addMonths(1).toStartOfMonth().addDays(-1),
getEndofMonth());
system.assertEquals(testDate.addMonths(1).toStartOfMonth(),
getBeginNextMonth(testDate));
system.assertEquals(system.today().addMonths(1).toStartOfMonth(),
getBeginNextMonth());
system.assertEquals(testDate.addDays(7).toStartOfWeek().addDays(-1),
getEndofWeek(testDate));
system.assertEquals(system.today().addDays(7).toStartOfWeek().addDays(-1),
getEndofWeek());
system.assertEquals(’00:00′, getTime(testTime));
system.assertEquals(null, getTime(‘X’));
system.assertEquals(testTime, getTime(’00:00′));
system.assertEquals(’12:00′, getTime(getTime(testDatetime)));
system.assertEquals(3600, getSecondsBetween(testTime, testTime2));
system.assertEquals(3600, getSecondsBetween(testDatetime, testDatetime2));
system.assertEquals(60, getMinutesBetween(testDatetime, testDatetime2));
system.assertEquals(1, getHoursBetween(testDatetime, testDatetime2));
system.assertEquals(4, getDow(testDate));
// This is locale-specific, obviously.
system.assertEquals(‘Thursday’, getDowName(testDate));
}
// ==============================================================================
// ERROR-HANDLING
// ==============================================================================
// Declare custom exceptions.
global class customException extends Exception {}
global class badArgumentException extends Exception {}
global class nullArgumentException extends Exception {}
// If you have a team of developers working on a project,
// you may have to wade through an ocean of debug messages.
// This handy method lets you find your debug messages quickly.
global static String showDebug(String lbl, String dbg)
{
String s = ‘FROM ‘ + userInfo.getUserName() + ‘: ‘ + lbl + ‘=’ + dbg;
system.debug(s);
return s;
}
// As a matter of course, we automatically write all of these
// messages to the debug log.
global static String showConfirm(String conf)
{
showDebug(‘CONFIRM’, conf);
ApexPages.Message msg =
new ApexPages.Message(ApexPages.Severity.Confirm, conf);
ApexPages.addMessage(msg);
return conf;
}
global static String showInfo(String info)
{
showDebug(‘INFO’, info);
ApexPages.Message msg =
new ApexPages.Message(ApexPages.Severity.Info, info);
ApexPages.addMessage(msg);
return info;
}
global static String showWarning(String warn)
{
showDebug(‘WARNING’, warn);
ApexPages.Message msg =
new ApexPages.Message(ApexPages.Severity.Warning, warn);
ApexPages.addMessage(msg);
return warn;
}
global static String showError(String err)
{
showDebug(‘ERROR’, err);
ApexPages.Message msg =
new ApexPages.Message(ApexPages.Severity.Error, err);
ApexPages.addMessage(msg);
return err;
}
// Strip the error message and line number from the exception and
// show it to the user. This is an easy way to handle unhandled exceptions.
global static String showError(Exception ex)
{
return showError(ex, ”);
}
global static String showError(Exception ex, String err)
{
String errMsg =
(err == null || err == ” ? ” : err + ‘: ‘) +
ex.getMessage() + ‘ at line ‘ +
ex.getLineNumber().format();
showDebug(‘FATAL’, errMsg);
ApexPages.Message msg =
new ApexPages.Message(ApexPages.Severity.Error, errMsg);
ApexPages.addMessage(msg);
return errMsg;
}
private static testMethod void testDebug()
{
system.assertEquals(‘FROM ‘ + userInfo.getUserName() + ‘: var=val’,
showDebug(‘var’, ‘val’));
system.assertEquals(‘Confirm’, showInfo(‘Confirm’));
system.assertEquals(‘Info’, showInfo(‘Info’));
system.assertEquals(‘Warning’, showWarning(‘Warning’));
system.assertEquals(‘Error’, showError(‘Error’));
system.assertEquals(‘Error at line’,
showError(new customException(‘Error’)).substring(0, 14).trim());
system.assertEquals(‘Test: Error at line’,
showError(new customException(‘Error’), ‘Test’).substring(0, 19).trim());
}
// ==============================================================================
// SYSTEM & METADATA
// ==============================================================================
// What edition is this?
global static String getOrgEdition()
{
list orgs =
[SELECT Id, OrganizationType FROM Organization LIMIT 1];
// This HAS to exist.
return orgs[0].OrganizationType;
}
// Returns a dynamic SOQL statement for any object,
// including only creatable fields. Used for cloning.
global static String getCreateableFieldsSoql(String obj)
{
return getCreateableFieldsSoql(obj, ”);
}
global static String getCreateableFieldsSoql(String obj, String whereClause)
{
String sql = ”;
String fieldString = ”;
list fieldList = new list();
// Get a map of field names for this object type.
Map<string, schema.sobjectfield=””> fieldMap =
Schema.getGlobalDescribe().get(obj.toLowerCase()).getDescribe().fields.getMap();
if (fieldMap != null)
{
// Loop through all fields.
for (Schema.SObjectField f : fieldMap.values())
{
// Describe each field.
Schema.DescribeFieldResult fd = f.getDescribe();
// Is this field is createable? If so, we can clone it.
if (fd.isCreateable())
{
// This is the API name.
fieldList.add(fd.getName());
}
}
}
// Sort and assemble field list.
if (!fieldList.isEmpty())
{
fieldList.sort();
for (string s : fieldList)
{
fieldString += s + ‘, ‘;
}
}
// Strip terminal comma.
if (fieldString.endsWith(‘, ‘))
fieldString = fieldString.substring(0, fieldString.lastIndexOf(‘,’));
// Assemble SQL statement.
sql = ‘SELECT ‘ + fieldString + ‘ FROM ‘ + obj;
// Append WHERE clause if present; if ORDER BY or LIMIT are needed,
// append them to WHERE clause when calling this method.
if (whereClause != null && whereClause != ”) sql += ‘ WHERE ‘ + whereClause;
return sql;
}
// Returns a dynamic SOQL statement for any object,
// including all accessible fields: SELECT * FROM [object].
global static String getAccessibleFieldsSoql(String obj)
{ return getAccessibleFieldsSoql(obj, ”); }
global static String getAccessibleFieldsSoql(String obj, String whereClause)
{
String sql = ”;
String fieldString = ”;
list fieldList = new list();
// Get a map of field names for this object type.
Map<string, schema.sobjectfield=””> fieldMap =
Schema.getGlobalDescribe().get(obj.toLowerCase()).getDescribe().fields.getMap();
if (fieldMap != null)
{
// Loop through all fields.
for (Schema.SObjectField f : fieldMap.values())
{
// Describe each field.
Schema.DescribeFieldResult fd = f.getDescribe();
// Is this field is queryable? If so, we can query it.
if (fd.isAccessible())
{
// This is the API name.
fieldList.add(fd.getName());
}
}
}
// Sort and assemble field list.
if (!fieldList.isEmpty())
{
fieldList.sort();
for (string s : fieldList)
{
fieldString += s + ‘, ‘;
}
}
// Strip terminal comma.
if (fieldString.endsWith(‘, ‘))
fieldString = fieldString.substring(0, fieldString.lastIndexOf(‘,’));
// Assemble SQL statement.
sql = ‘SELECT ‘ + fieldString + ‘ FROM ‘ + obj;
// Append WHERE clause if present; if ORDER BY or LIMIT are needed,
// append them to WHERE clause when calling this method.
if (whereClause != null && whereClause != ”) sql += ‘ WHERE ‘ + whereClause;
return sql;
}
global static final String API_LABEL = ‘API Requests, Last 24 Hours’;
// Get maximum number of API requests available.
global static Integer getApiMax()
{
// Get the current organization ID.
Organization org = [SELECT Id FROM Organization LIMIT 1];
// Get the actual contents of the page associated with that organization ID.
PageReference pr = new PageReference(‘/’ + String.valueOf(org.Id));
pr.setRedirect(false);
String result = ”;
// You can’t use getContent() in a test method.
if (Test.isRunningTest())
{
result = Blob.valueOf(API_LABEL + ‘ 12,345 (45,678 max)’).toString();
}
else
{
result = pr.getContent().toString();
}
if (result != null)
{
// Find the label for API requests.
Integer startIndex = result.indexOf(API_LABEL, 1) + (Test.isRunningTest() ? 29 : 52);
startIndex = result.IndexOf(‘(‘, startIndex) + 1;
// Find the first space afterward; this is the max API requests.
Integer endIndex = result.indexOf(‘ ‘, startIndex);
result = result.substring(startIndex, endIndex);
// Clean up the result.
result = result.replaceAll(‘\\(‘, ”);
result = result.replaceAll(‘ ‘, ”);
result = result.replaceAll(‘,’, ”);
}
return Integer.valueOf(result);
}
// Get current number of API requests used right now.
global static Integer getApiCurrent()
{
// Get the current organization ID.
Organization org = [SELECT Id FROM Organization LIMIT 1];
// Get the actual contents of the page associated with that organization ID.
PageReference pr = new PageReference(‘/’ + String.valueOf(org.Id));
pr.setRedirect(false);
String result = ”;
if (Test.isRunningTest())
{
result = Blob.valueOf(API_LABEL + ‘ 12,345 (45,678 max)’).toString();
}
else
{
result = pr.getContent().toString();
}
if (result != null)
{
// Find the label for API requests.
Integer startIndex = result.indexOf(API_LABEL, 1) + (Test.isRunningTest() ? 29 : 52);
// Find the first space afterward; this is the current API requests.
Integer endIndex = result.indexOf(‘ ‘, startIndex);
result = result.substring(startIndex, endIndex);
// Clean up the result.
result = result.replaceAll(‘ ‘, ”);
result = result.replaceAll(‘,’, ”);
}
return Integer.valueOf(result);
}
// Get available number of API requests available right now.
global static Integer getApiLeft()
{
return getApiMax() – getApiCurrent();
}
// Is this a sandbox org?
global static Boolean isSandbox()
{
// By offering a polymorphic variation on this,
// we can improve our test coverage.
return isSandbox(URL.getSalesforceBaseUrl().getHost());
}
global static Boolean isSandbox(String host)
{
// Get the subdomain.
String server = host.substring(0, host.indexOf(‘.’));
// tapp0 is a unique “non-cs” server so check it now.
if (server == ‘tapp0’) return true;
// If server is ‘cs’ followed by a number it’s a sandbox.
if (server.length() > 2)
{
if (server.substring(0, 2) == ‘cs’)
{
return true;
}
}
// If we made it here it’s a production box.
return false;
}
private static testMethod void testSystem()
{
system.assert(getOrgEdition() != null);
system.assert(getCreateableFieldsSoql(‘Account’) != null);
system.assert(getCreateableFieldsSoql(‘Account’, ‘LIMIT 1’) != null);
system.assert(getAccessibleFieldsSoql(‘Account’) != null);
system.assert(getAccessibleFieldsSoql(‘Account’, ‘LIMIT 1’) != null);
system.assertEquals(45678, getApiMax());
system.assertEquals(12345, getApiCurrent());
system.assertEquals(33333, getApiLeft());
system.assert(getOrgEdition() != null);
system.assertEquals(true, isSandbox(‘tapp0.salesforce.com’));
system.assertEquals(true, isSandbox(‘cs1.salesforce.com’));
system.assertEquals(false, isSandbox(‘na1.salesforce.com’));
}
}
public virtual class TriggerHandler {
// SObject type of trigger; set this in the constructor
// of the implementing class
protected SObjectType otype = null;
protected List<EventLog__c> errorList = new List<EventLog__c>();
public void run() {
setup();
try {
// trigger logic goes in here, via calls to
//beforeInsert, afterUpdate and so forth
} catch ( Exception e ) {
log(
String.valueOf( otype ) + ' : uncaught',
'0',
JSON.serialize( trigger.new ),
Event_Error_Message__c = e.getMessage() + '\n'
+ e.getStackTraceString()
) );
} finally {
finish();
}
}
protected void log( String eventType, String eventRecordId,
String eventMessage, String eventDetails
) {
errorList.add( new EventLog__c(
Event_Type__c = eventType,
Event_ID__c = eventRecordId,
Event_Details__c = eventDetails,
Event_Error_Message__c = eventMessage
) );
}
protected void finish() {
if ( !errorList.isEmpty() ) {
Database.insert( errorList, false );
}
}
}
// 1. Create an Apex Class using Tooling API:
public void createApexClass()
{
String json ='{ &quot;Name&quot; : &quot;Mydemoclass1&quot;, &quot;Body&quot; : &quot;public class Mydemoclass1{ public Void sayHello(){ string name= \'HI MEHUL\'; system.debug(\'***Name: \'+name);} }&quot; }';
//HTTP Request
HttpRequest req = buildHttpRequest(URL.getSalesforceBaseUrl().toExternalForm()+'/services/data/v36.0/tooling/sobjects/ApexClass/','POST');
req.setBody(json);
//HTTP Response
HttpResponse res = buildHttpResponse(req);
System.Debug('**** ApexClass Response: ' + res.getBody());
}
// 2. Update an Apex Class using Tooling API:
public JsonTest createMetadataContainer(){
// Request
HttpRequest containerRequest = buildHttpRequest(URL.getSalesforceBaseUrl().toExternalForm()+'/services/data/v36.0/tooling/sobjects/MetadataContainer/', 'POST');
containerRequest.setBody('{&quot;Name&quot;:&quot;TestContainer0&quot;}');
// Response
HttpResponse containerResponse = buildHttpResponse(containerRequest);
System.Debug('**** Metadata Container Response: ' + containerResponse.getBody());
return (JsonTest)JSON.Deserialize(containerResponse.getBody(), JsonTest.class);
}
public void createApexClassMember(){
//Request
HttpRequest apexClassRequest = buildHttpRequest(URL.getSalesforceBaseUrl().toExternalForm()+'/services/data/v36.0/tooling/sobjects/ApexClassMember/', 'POST');
apexClassRequest.setBody('{&quot;ContentEntityId&quot;: &quot;'+aid+'&quot;, &quot;MetadataContainerId&quot;: &quot;'+ containerResponse.id +'&quot;, &quot;Body&quot; : &quot;' + PassUpdatedClassBody + '&quot;}');
}
//Response
HttpResponse apexClassResponse = buildHttpResponse(apexClassRequest);
System.Debug('**** ApexClassMember Response: ' + apexClassResponse.getBody());
}
public void createContainerAsyncRequest(){
//Request
HttpRequest containerAsyncRequest = buildHttpRequest(URL.getSalesforceBaseUrl().toExternalForm()+'/services/data/v36.0/tooling/sobjects/ContainerAsyncRequest/', 'POST');
containerAsyncRequest.setBody('{&quot;IsCheckOnly&quot;: false, &quot;MetadataContainerId&quot;: &quot;'+ containerResponse.id +'&quot;}');
//Response
HttpResponse containerAsyncResponse = buildHttpResponse(containerAsyncRequest);
System.Debug('**** ContainerAsync Response: ' + containerAsyncResponse.getBody());
containerAsyncJson = (JsonTest)JSON.Deserialize(containerAsyncResponse.getBody(), JsonTest.class);
}
// 3. Delete an Apex Class using Tooling API:
public void createApexClass()
{
String ids = '01p65770006Ll4tAXO';
//HTTP Request
HttpRequest req = buildHttpRequest(URL.getSalesforceBaseUrl().toExternalForm()+'/services/data/v36.0/tooling/sobjects/ApexClass/'+ids,'DELETE');
//HTTP Response
HttpResponse res = buildHttpResponse(req);
System.Debug('**** ApexClass Response: ' + res.getBody());
}
// Goto Setup > Administer > Security Controls > Remote Site Settings.
// Click on ‘New Remote Site’ Button and provide Remote Site Name.
public class MyStack {
private List<sObject> al;
public MyStack() {
al = new List<sObject>();
}
public void push(sObject item) {
al.add(item);
}
public sObject pop() {
if (!isEmpty())
return al.remove(size()-1);
else
return null;
}
public boolean isEmpty() {
return (al.size() == 0);
}
public sObject peek() {
if (!isEmpty())
return al.get(size()-1);
else
null;
}
public int size() {
return al.size();
}
}
Savepoint sp = Database.setSavepoint();
Boolean errors = false;
Account[] accts = someList;
Contact[] conts = someOtherList;
Opportunity[] opps = yetAnotherList;
Database.SaveResult acctsRes = Database.insert(accts, false);
for(Integer i=0; i<acctsRes.size(); i++){
if(!acctsRes[i].isSuccess()){
errors = true;
//handle errors
}
}
Database.SaveResult contsRes = Database.insert(conts, false);
for(Integer i=0; i<contsRes.size(); i++){
if(!contsRes[i].isSuccess()){
errors = true;
//handle errors
}
}
Database.SaveResult oppsRes = Database.update(opps, false);
for(Integer i=0; i<oppsRes.size(); i++){
if(!oppsRes[i].isSuccess()){
errors = true;
//handle errors
}
}
if(errors){
Database.rollback(sp);
}
If you need something like the sleep() function, one way to do it is to make a call to a http service which will sleep a requested amount of time. This is fairly simple to do, and there are existing publicly available services for it, for example the one at http://1.cuzillion.com/bin/resource.cgi.
First you have to Configure a new Remote Site in SalesForce (Security Controls -> Remote Site Settings), name it however you want but make sure the Remote Site URL matches the above URL, and that the "Active" checkbox is checked.
After that, you can define your method in code like so:
public static void sleep(Integer sleepSeconds) {
Long startTS = System.currentTimeMillis();
HttpRequest req = new HttpRequest();
req.setEndpoint('http://1.cuzillion.com/bin/resource.cgi?sleep=' + sleepSeconds);
req.setMethod('GET');
Http http = new Http();
HTTPResponse res = http.send(req);
Long duration = System.currentTimeMillis() - startTS;
System.debug('Duration: ' + duration + 'ms');
}
Running it yields:
sleep(1);
-> 08:46:57.242 (1242588000)|USER_DEBUG|[10]|DEBUG|Duration: 1202ms