Tuesday 11 October 2016

How to create or generate a csv file in apex code Salesforce (Generate Setup Audit Trail records as CSV file)

Here is the sample code to create or generate a CSV file using apex code. The below code will query all SetupAuditTrail object records and stored the generated CSV file in document object folder. 

Usually Setup Audit Log in salesforce will provide only last six month of data. But when we need a specific range of logs, then we have to go for a custom logic. 

The below query will provide specific date range of Audit logs,

  1. SELECT CreatedDate, CreatedBy.Username, Display, Section, Action, DelegateUser FROM SetupAuditTrail WHERE CreatedDate >= 2016-09-10T00:00:00Z AND CreatedDate <= 2016-10-01T00:00:00Z ORDER BY CreatedDate DESC

Sample Batch Code

  1. global class SetupAuditTrailBatch implements Database.Batchable<sObject>, Database.Stateful {
  2.    
  3.     global String csvColumnHeader;
  4.     global List<String> csvRowValues = new List<String>();
  5.    
  6.     global Database.QueryLocator start(Database.BatchableContext BC){
  7.         //Query all SetupAuditTrail records.
  8.         String query = 'SELECT CreatedDate, CreatedBy.Username, Display, Section, Action, DelegateUser, CreatedById, CreatedBy.Name FROM SetupAuditTrail ORDER BY CreatedDate DESC';
  9.         return Database.getQueryLocator(query);
  10.     }
  11.    
  12.     global void execute(Database.BatchableContext BC, List<sObject> scope){
  13.         //Process retrieved SetupAuditTrail records and format field values.
  14.         for(SetupAuditTrail currSetupAudit : (List<SetupAuditTrail>) scope){
  15.             String formattedDate = currSetupAudit.CreatedDate.format('M/d/yyyy h:mm:ss a z');
  16.             String userName = currSetupAudit.CreatedBy.Username != null ? currSetupAudit.CreatedBy.Username : '';
  17.             String displayVal = currSetupAudit.Display != null ? String.valueOf(currSetupAudit.Display).escapeCsv() : '';
  18.             String sectionVal = currSetupAudit.Section != null ? currSetupAudit.Section : '';
  19.             String delegateUser = currSetupAudit.DelegateUser != null ? currSetupAudit.DelegateUser : '';
  20.            
  21.             String rowStr = formattedDate + ',' + userName + ',' + displayVal + ',' + sectionVal + ','+ delegateUser;
  22.             csvRowValues.add(rowStr);
  23.         }
  24.     }
  25.    
  26.     global void finish(Database.BatchableContext BC){
  27.         List<Folder> folders = [SELECT Id, Name FROM Folder WHERE Name = 'Setup Audit Trail Logs'];
  28.        
  29.         if(!folders.isEmpty()){
  30.             String documentName = 'SetupAuditTrailLog-'+ Datetime.now().format('MMM') + Datetime.now().year();
  31.             csvColumnHeader = 'Date, User, Action, Section, Delegate User\n';
  32.             String csvFile = csvColumnHeader + String.join(csvRowValues,'\n');
  33.            
  34.             // Insert the generated CSV file in Document object under "Setup Audit Trail Logs".
  35.             Document doc = new Document(Name = documentName, Body = Blob.valueOf(csvFile), FolderId = folders[0].Id, Type = 'csv', ContentType='application/vnd.ms-excel');
  36.             insert doc;
  37.         }
  38.     }
  39. }


References:


Supported calls:
query(), retrieve()

Note:
Aggregate queries aren’t supported on this object. For example, SELECT count() FROM SetupAuditTrail works but SELECT count(Id) FROM SetupAuditTrail fails.

11 comments:

  1. very informative blog and useful article thank you for sharing with us , keep posting learn more aboutsalesforce training,salesforce online training

    ReplyDelete
  2. HI,I implemented this logic to create a csv file based on LastModifiedDate.It did generate the file correctly with all values.Today when I ran the batch it is creating a csv bt does not have any values.I queried and there are 3 records based on the soql.I am posting my code below,any help is highly appreciated since I need to get it up and running soon.
    global class BatchGenerateUpdatedMeterFile implements Database.Batchable, Database.Stateful
    {
    global String csvColumnHeader;
    global List csvRowValues = new List();

    global Database.QueryLocator start(Database.BatchableContext BC)
    {
    //Query all modified meter records

    Date dt = date.today();
    System.debug(dt);
    String query = 'SELECT Id,Name,parcel__r.Name, Module_Number__c,Meter_Install_Date__c from sm1e__smEquipment__c WHERE LastModifiedDate = Today';
    return Database.getQueryLocator(query);

    }


    global void execute(Database.BatchableContext BC ,List scope)
    {
    //Process retrieved records and format field values.
    for(sm1e__smEquipment__c currentList : (List) scope){

    String parcelName = currentList.parcel__r.Name;
    System.debug(parcelName);
    String moduleNumber = currentList.Module_Number__c;
    Date meterInstallDate = currentList.Meter_Install_Date__c;
    String meternumber = currentList.Name;


    String rowStr = meternumber + ',' + parcelName + ',' + moduleNumber ;
    csvRowValues.add(rowStr);

    }


    }

    global void finish(Database.BatchableContext BC)
    {
    List folders = [SELECT Id, Name FROM Folder WHERE Name = 'BeaconExportFolder'];

    if(!folders.isEmpty()){
    String documentName = 'MeterDataExportFile-'+Datetime.now().format('dd/MM/yyyy');
    csvColumnHeader = 'MeterNumber , Address ,ModuleNumber ,InstallDate \n';
    String csvFile = csvColumnHeader + String.join(csvRowValues,'\n');

    //Insert the genertaed CSV file in Document object under 'BeaconExportFolder'

    Document doc = new Document(Name = documentName, Body = Blob.valueOf(csvFile),FolderId = folders[0].id,
    Type = 'csv', ContentType ='application/vnd.ms-excel');
    insert doc;
    System.debug('File inserted');
    }


    }
    }

    ReplyDelete
  3. I figured it out.The batch apex was taking time to complete.

    ReplyDelete
  4. Very good points you wrote here..Great stuff...I think you've made some truly interesting points.Keep up the good work. Free TikTok Fans

    ReplyDelete
  5. Thanks for sharing this great information on Oracle APEX. Actually I was looking for the same information on internet for Oracle Apex Interview Questions and Answers and came across your blog. I am impressed by the information that you have on this blog. It shows how well you understand this subject, you can learn more about Oracle PPM Cloud by attending Oracle APEX Training.

    ReplyDelete
  6. This was exactly what I needed. The Database.Stateful in the class header is a must. If it is not there, csvRowValues loses scope in the finish routine and will be blank. Only took me 1 hour to find that missing piece in my code. Thanks again for posting this.

    ReplyDelete
  7. I was looking for similar type of example, its a very good once. Thanks a lot.

    ReplyDelete
  8. Hello Everyone,

    Welcome to the future! Financing made easy with Prof. Mrs. DOROTHY LOAN INVESTMENTS

    Have you been looking for financing options for your new business plans, Are you seeking for a loan to expand your existing business, Do you find yourself in a bit of trouble with unpaid bills and you don’t know which way to go or where to turn to? Have you been turned down by your banks? MRS. DOROTHY LOAN INVESTMENTS says YES when your banks say NO. Contact us as we offer financial services at a low and affordable interest rate of 2% for long and short term loans. Interested applicants should contact us for further loan acquisition procedures via profdorothyinvestments@gmail.com

    Services rendered include:

    *Refinancing Loans
    * Car Loan
    *Truck Loans
    * Home Loan
    * Mortgage Loan
    * Debt Consolidation Loan
    * Business Loan [secure and unsecured]
    * Personal Loan [secure and unsecured]
    * Students Loan and so many others.

    For more info; Contact us via Email: profdorothyinvestments@gmail.com

    With Prof. Mrs. DOROTHY LOAN INVESTMENTS. you can say goodbye to all your financial crisis and difficulties as we are certified, trustworthy, reliable, efficient, fast and dynamic

    ReplyDelete
  9. Nice and good article. It is very useful for me to learn and understand easily. Thanks for sharing.
    CPQ Salesforce Training
    Salesforce CPQ Course

    ReplyDelete
  10. Salesforce Service Cloud is about ensuring that businesses provide exceptional customer service. It's like having a virtual customer care team on hand 24 hours a day, seven days a week. Salesforce Service Cloud Implementation can be a challenging yet rewarding experience, but it is important to streamline their customer service operations, improve their agent productivity, and ultimately enhance their overall customer experience.

    With Salesforce Service Cloud Implementation, you can easily assist your businesses to leverage the power of Salesforce to achieve your business goals. Request a free consultation with an AblyPro expert to learn how Salesforce Service Cloud may help your company improve customer service and drive higher retention rates!

    ReplyDelete

Activities: Assign Tasks to a Queue Salesforce Lightning

Salesforce announced to assign Tasks to a Queue beginning from Spring'20 release. How does it work? In Setup, enter Queues in th...