Salesforce: Dynamically Create Apex Class and Apex Test Class using Tooling API


//Creating the Apex Class JSON Body
String classMethod = 'public String DynamicClassMethod (string methodName) { return methodName; }';
String classBody = 'Public Class DynamicClass { ';
classBody += classMethod + '}';

//Creating the Apex Test Class JSON Body
String testClassBody = '@isTest private Class DynamicClassTest { ';
String methodParameter = 'testName'; 
String testClassMethodInstance = ' DynamicClass DynamicClassInstance = new DynamicClass(); ';
testClassMethodInstance += ' DynamicClass.DynamicClassMethod( \''+methodParameter+'\');';
testClassBody += testClassMethodInstance + '}';

String sessionId = UserInfo.getSessionID();
String endpointURL = URL.getSalesforceBaseUrl().toExternalForm();
HttpResponse httpResponseBody;
String jsonBody;

//Check whether class already created or not?
List<ApexClass> apexClasssList = [SELECT id FROM ApexClass WHERE Name = 'DynamicClass']; 
//If Class already created then update the existing class
if(apexClasssList.size()>0) { 
 //During one session we get one key. IF we want to ge the id multiple times in the same session then we need to pass the different values in the name key value
 jsonBody = '{"Name":"'+crypto.getRandomLong()+'"}';   
 httpResponseBody = makeHttpRequest(endpointURL+'/services/data/v44.0/tooling/sobjects/MetadataContainer/','Bearer ' + sessionId,jsonBody);

 Id metadataContainerId = (String)((Map<String,Object>)JSON.deserializeuntyped(httpResponseBody.getBody())).get('id');

 jsonBody = '{"MetadataContainerId" : "'+metadataContainerId+'", "ContentEntityId" : "'+apexClasssList[0].id+'", "Body": "'+classbody+'"}';
 httpResponseBody = makeHttpRequest(endpointURL+'/services/data/v44.0/tooling/sobjects/ApexClassMember/','Bearer ' + sessionId,jsonBody); 

 jsonBody = '{"MetadataContainerId" : "'+metadataContainerId+'", "isCheckOnly": "false"}';
 httpResponseBody = makeHttpRequest(endpointURL+'/services/data/v44.0/tooling/sobjects/ContainerAsyncRequest/','Bearer ' + sessionId,jsonBody); 
} else { //If Class not exist then create the new class
 jsonBody = '{ "Name" : "DynamicClass", "Body" : "'+classBody+'" }';
 httpResponseBody = makeHttpRequest(endpointURL+'/services/data/v44.0/sobjects/ApexClass','OAuth ' + sessionId,jsonBody); 
} 


//Check whether apex Test class already created or not?
List<ApexClass> apexTestClasssList = [SELECT id FROM ApexClass WHERE Name = 'DynamicClassTest']; 
//If Class already created then update the existing class
if(apexTestClasssList.size()>0) {      
    //During one session we get one key. IF we want to ge the id multiple times in the same session then we need to pass the different values in the name key value
 jsonBody = '{"Name":"'+crypto.getRandomLong()+'"}';
    httpResponseBody = makeHttpRequest(endpointURL+'/services/data/v44.0/tooling/sobjects/MetadataContainer/','Bearer ' + sessionId,jsonBody);
   
    Id metadataContainerId = (String)((Map<String,Object>)JSON.deserializeuntyped(httpResponseBody.getBody())).get('id');

    jsonBody = '{"MetadataContainerId" : "'+metadataContainerId+'", "ContentEntityId" : "'+apexTestClasssList[0].id+'", "Body": "'+testClassBody+'"}';
 httpResponseBody = makeHttpRequest(endpointURL+'/services/data/v44.0/tooling/sobjects/ApexClassMember/','Bearer ' + sessionId,jsonBody); 

    jsonBody = '{"MetadataContainerId" : "'+metadataContainerId+'", "isCheckOnly": "false"}';
 httpResponseBody = makeHttpRequest(endpointURL+'/services/data/v44.0/tooling/sobjects/ContainerAsyncRequest/','Bearer ' + sessionId,jsonBody); 
} else {  //If Class not exist then create the new class
 jsonBody = '{ "Name" : "DynamicClassTest", "Body" : "'+testClassBody+'" }';
 httpResponseBody = makeHttpRequest(endpointURL+'/services/data/v44.0/sobjects/ApexClass','OAuth ' + sessionId,jsonBody); 
} 
public HttpResponse makeHttpRequest(String endPoint, String sessionId, String jsonBody){
   HttpRequest httpRequestCall = new HttpRequest();
   httpRequestCall.setEndpoint(endPoint);        
   httpRequestCall.setMethod('POST');
   httpRequestCall.setHeader('Content-Type', 'application/json');
   httpRequestCall.setHeader('Authorization', sessionId);
   httpRequestCall.setBody(jsonBody);
   Http http = new Http();
   return http.send(httpRequestCall);
}    
 


    

Comments

Popular posts from this blog

Transaction Security Policy In Salesforce

Salesforce Data Cloud

Add/Remove Content in the VF Page using JS