About Me

My photo
PLANO, Texas, United States

Wednesday, September 17, 2014

Dashboard

  • Dashboards are graphical representations of reports. 
  • Dashboards can be generated for summary or matrix reports (and not for tabular reports). 
  • Dashboards display data as per the last time the report was run.
  • A dashboard can have up to 20 components.

Dashboard Component Types

  1. Chart
  2. Gauge
  3. Metric
  4. Table
  5. Visualforce Page
  6. Custom S-Control

Data Source of Dashboard

  1. Report
  2. VisualForce Page
The chart in the Dashboard:
  1. Vertical column
  2. Horizontal bar
  3. Line
  4. Donut
  5. Funnel
  6. Pie
Important Points:
  • Dashboard also support automatic refresh and email. The refresh and email can also be scheduled at intervals - daily, weekly, monthly.
  • The folder in which dashboards are stored determines which user has access to running the dashboard. The dashboard data is based upon the reports data. When a user views the drill-down report for a dashboard component. running user's access permissions determine what data is displayed on the drilldown report. Hence it is possible that the data in the drill down report does not match the cumulative dashboard data.
  • Dashboard also support automatic refresh and email. The refresh and email can also be scheduled at intervals - daily, weekly, monthly.
  • Two things that determine access to dashboards: Dashboard Folder & Running User

Report

  • A report returns a set of records that meets certain criteria and displays it in organized rows and columns. Report data can be filtered, grouped, and displayed graphically as a chart. Reports are stored in folders, which control who has access.
  • In reports data displayed is as per running user's security access. Reports can be run on both standard and custom objects provided object must have permission for Report creation. Reports are stored in folders. Users with access to these folders can run the reports.
  • Reports data is always generated in real-time. When a report is saved, reports configuration parameters are stored - but the generated data is not stored.

Types of Report:

  1. Tabular report:  This is the most basic report. It displays just the row of records in a table-like format with grand total. Tabular reports cannot be used for generating dashboards.
  2. Summary report: This is the most commonly type of report. It allows grouping of rows of data. It supports sorting and displaying subtotals. For example in a recruiting app, a summary report could be used to display open positions classified by department name.
  3. Matrix report: Matrix report summarize information in a grid format. Matrix reports allows records to be grouped by both columns and rows.
  4. Joint Report:Use the joined report format to create multiple views of the data contained in a single report. You can add multiple report types to a joined report, create standard and cross-block custom summary formulas, add a chart, and more.
Summary and Matrix reports can be used to generate dashboards.Report display upto 2000 rows of data. Larger reports can be emailed to Excel.

Report Type:

  1. Standard Report Type:
    1. Created when an object is created
    2. Always inner joins
    3. Cannot be modified.
    4. Created when relationships between objects are created 
  2. Custom Report type
    1. Created by Admin or users with “Manager Custom Report types”.
    2. Used to streamline the reporting process.

Use of bucket field in Reports in Salesforce:

  • Bucket field in Reports in Salesforce is used to group values to the name we specify.
  • Bucketing lets you quickly categorize report records without creating a formula or a custom field.
  • When you create a bucket field, you define multiple categories (buckets) used to group report values.
  • Custom reports let the developers define which all fields should be available in a report. Custom report allows user to change field names. Custom reports allow developers to select related fields (upto four levels). The custom reports also allow developers to add sections to group fields. Once a custom report is created it is available in reports tab and user may create reports from it.

Limitations of Salesforce reports:

  • User Interface of Salesforce reports and dashboards is fixed. Salesforce does not support pixel perfect report.
  • Salesforce reports do not support importing data from other sources
  • When displaying objects and their children, Salesforce does not support reporting on objects that do not have any children.
  • If an object has two different related lists, then Salesforce reporting does not support displaying both these related lists together.

Work-around these limitations,:

Salesforce customers have the following three options.
  • Reporting as a service: Data resides on Salesforce. New Reports get generated from same data source
  • BI as a service: Data is moved to a different destination on cloud. Reporting is performed on this new data server.
  • Datawarehousing as a service: Data is exported to the customers server and reports are generated from the server located at the customers locations.
  • Use VF Page for Complex Report

Wednesday, September 10, 2014

ETL Tools

ETL - Extract, Transform, Load: ETL is used to migrate data from one database to another, to form data marts and data warehouses, and also to convert databases from one format or type to another.
  • ETL is short for extract, transform, load, three database functions that are combined into one tool to pull data out of one database and place it into another database.
  • Extract is the process of reading data from a database.
  • Transform is the process of converting the extracted data from its previous form into the form it needs to be in so that it can be placed into another database. Transformation occurs by using rules or lookup tables or by combining the data with other data.
  • Load is the process of writing the data into the target database.
List of the most popular ETL tools:
  • Informatica - Power Center
  • Pervasive - Data Integrator
  • IBM - Websphere DataStage(Formerly known as Ascential DataStage)
  • SAP - BusinessObjects Data Integrator
  • IBM - Cognos Data Manager (Formerly known as Cognos DecisionStream)
  • Microsoft - SQL Server Integration Services
  • Oracle - Data Integrator (Formerly known as Sunopsis Data Conductor)
  • SAS - Data Integration Studio
  • AB Initio
  • Information Builders - Data Migrator
  • Pentaho - Pentaho Data Integration
  • Embarcadero Technologies - DT/Studio
  • IKAN - ETL4ALL
  • IBM - DB2 Warehouse Edition
  • ETL Solutions Ltd. - Transformation Manager
  • Group 1 Software (Sagent) - DataFlow
  • Sybase - Data Integrated Suite ETL
  • Talend - Talend Open Studio
  • Expressor Software - Expressor Semantic Data Integration System
  • Elixir - Elixir Repertoire
  • OpenSys - CloverETL

Tuesday, September 2, 2014

Apex test Class

Unit testing is the software development practice of writing additional code, called unit tests. These tests execute your business logic code with known input parameters and evaluate the output for expected results.

What are the common facts for apex test Classes?

  • isTest Annotation is used to define the Apex Test class.

  • Classes defined with the isTest annotation do not count against your organization limit of 2 MB for all Apex code.

  • Classes annotated with isTest can be declared as private or public otherwise Top-level type must have public or global visibility.

  • At least 75% of your Apex code must be covered by unit tests, and all of those tests must complete successfully.

  • Every trigger must have some test coverage.

  • All classes and triggers must compile successfully.

What are some Best Practices while writing Test Classes?

Whenever we are creating the test class, we must be following below best practices:

  • Though we need 75% code coverage to deploy the class from Sandbox to Production, still test Coverage Target Should not be limited to 75%, we should try to make it 100%.

  • If possible don’t use seeAllData=true, Create your Own Test Data.

  • Create a Common class for Dummy Data for testing, and use it everywhere.

  • If you’re Object’s Schema is not changing frequently, you can create a CSV file of records and load in a static resource. This file will act as Test data for your Test Classes.

  • Use As much as Assertions like System.AssertEquals or System.AssertNotEquals to verify the test result.

  • Use Test.startTest() to reset Governor limits in Test methods and close it with Test.stopTest().

  • End your test class with “_Test”. So that in the Apex Class list view, the Main class and Test class will come together, resulting in easy navigation and time saver.

  • Always test the Batch Capabilities of your code by passing 20 to 100 records.

  • Use the runAs method to test your application in different user contexts.

  • If there is a unique field then use System. currentTimeMillis() method with the name

  • Test Negative scenario in the test class.

What are the methods used for test class?

  1. Test.getStandardPricebookId() - Returns the ID of the standard price book in the organization.

  2. Test.isRunningTest() -Returns true if the currently executing code was called by code contained in a test method, false otherwise. Use this method if you need to run different code depending on whether it was being called from a test.

  3. Test.startTest()-Marks the point in your test code when your test actually begins. Use this method when you are testing governor limits.

  4. Test.stopTest()-Marks the point in your test code when your test ends. Use this method in conjunction with the startTest method.

  5. Test.loadData(Schema.SObjectType, String)-Inserts test records from the specified static resource .csv file and for the specified sObject type, and returns a list of the inserted sObjects.


Apart from the above, there are below methods used in Apex test Class:

  1. System.Assert 

  2. System.AssertEquals

  3. System.AssertNotEquals

  4. System.runAs(User)

What is the difference between System.Assert and System.AssertEquals()?


Basically, both methods are used to prove that code behaves properly.


System.Assert accepts two parameters, one (mandatory) which is the condition to test for, and the other a message (optional) to display should that condition be false.

Syntax:

System.assert(var1 == var2, "The value of var1 is: " +var1 + " and the value of... oh hell I don't care I mean it's just a variable");

System.AssertEquals and System.AssertNotEquals both accepts three parameters; the first two (mandatory) are the variables that will be tested for in/equality and the third (optional) is the message to display if the assert results in false.

Syntax:

System.assertEquals(var1, var2,<Optional Message>);


The advantage of System.AssertEquals over System.Assert is that the AssertEquals method shows the exact error without using the optional parameters. However, in the Assert method, we cannot be able to see the error until unless we will pass some message in the optional parameter.


To understand this, let's take an example, I am creating an Account in below two test classes. In one class, I am using the Assert method and in another class, I am using the assertEquals method.  



Test Class using AssertEquals 


Result 

When we will run the class, the below fail result will come. So, in this case, we don’t know what should be the result. 
How we create a fake response in the Test class?
Apex provides the built-in WebServiceMock interface and the Test.setMock method that you can use to receive fake responses in a test method.

How to write Test method of Controller Extension for StandardController?
Create the Object for which you are writing the Extension and pass the object instance in the ApexPages.StandardController as below: 


How to write Test method of Controller Extension for StandardSetController?


TestSetup Methods


Multiple test methods in the same class often have similar data requirements. Because of this, the Lightning Platform offers a way for you to annotate methods in your test class as @testSetup methods. The platform calls these methods automatically before every individual test method.


@isTest

private class myDataGenerationTests {

   @testSetup

   static void myDataGenerationTests() {

       List<sObject> accounts = Test.loadData(Account.SObjectType, 'Mock_Data');

   }

   @isTest

   static void testLoadAccountsFromStaticResource(){

       Test.startTest();

       List<Account> lstAccount =[Select Id from Account];

       Test.stopTest();

       system.assert(lstAccount.size() == 15, 'expected 15 accounts');

   }

}






Tuesday, August 26, 2014

Data Import/Export Tool in Salesforce

Below are the tools used in salesforce to import and export the data:
  1. Import Wizard
  2. Data Loader 
  3. Data loader.io
  4. Workbench
  5. Export Wizard
  6. Jitterbit Data
Import Wizard:
  • An in-browser wizard.
  • You can import up to 50,000 records into Salesforce from an existing data source.
  • The following objects can be imported using import wizard.
  1. Account
  2. Contact
  3. Lead
  4. Solution
  5. Custom Object
  • Have Option to turn of WorkFlow Rule
  • Can prevent duplicate record
  • You can use only for importing data. Do not allow for export data
Data loader
  • Data Loader is a client application for the bulk import or export of data.
  • Can import more than 50,000 records. 
  • You can achieved below action by data loader:
  1. Insert
  2. Export (Include data from recycle bin)
  3. Export (Exclude data from recycle bin)
  4. Update
  5. Upsert
  6. Delete

Data loader.io
  • Web-based suite of tools
  • Support all the standard things – insert, upsert, update, export and delete of data from production and sandbox Salesforce orgs.
  • No signup or security tokens: simply log in with your Salesforce production or sandbox credentials using OAuth unlike data loader
  • Task history: We keep a 30 day history of all your activity, making it easy to go back in time and see what happened, as well as view archived data of your data exports.
  • Can schedule the task
  • Can send the notification after completing the task
  • Can save directly on specific folder (Dropbox,FTP etc.)

Workbench
  • Web-based suite of tools
  • Can be accessed by https://workbench.developerforce.com/login.php
  • Workbench uses OAuth 2.0 login (meaning single sign-on)
  • Can import, export,delete and update the data
  • Can fetch the meta data
  • Provide REST Explorer
Export Wizard
  • An in-browser wizard that exports data in .zip files that are up to 128 MB.
  • We can schedule it
  • Cannot import the data

Jitterbit Data
  • Jitterbit Data Loader for Salesforce is an installable application for Windows and OS X.
  • Data operations are performed as a combination of modules, where sources, targets, file formats, and operations are created as separate components.
  • Jitterbit’s best feature allows users to schedule operations to run and perform features like a barebones ETL tool
  • Best use: repetitive data operations or light integration


Thursday, August 21, 2014

Contacts to Multiple Accounts

Contacts to Multiple Accounts

  • People often work with more than one company. A business owner might own more than one company or a consultant might work on behalf of multiple organizations. Relate a single contact to multiple accounts so you can easily track the relationships between people and businesses without creating duplicate records.

  • When you use Contacts to Multiple Accounts, each contact still requires a primary account (the account in the Account Name field). The contact and its primary account have a direct relationship. But you can add other accounts to the contact. These secondary account-contact relationships are indirect.



Configuring Security in Salesforce

  1. Object-Level Security (Permission Sets and Profiles):    
  2. Field-Level Security (Permission Sets and Profiles):
  3. Record-Level Security (Sharing):
1st and 2nd is related to Profile and 3rd is related to Role.

OWDs:
Organization-Wide Defaults, or OWDs, are the baseline security you for your Salesforce instance. Organizational Wide Defaults are used to restrict access. You grant access through below other means:

  1. Sharing rules
  2. Role Hierarchy
  3. Sales Teams 
  4. Account teams
  5. Manual sharing

There are four levels of access that can be set:

  1. Public Read/Write/Transfer (only available of Leads and Cases)
  2. Public Read/Write
  3. Public Read/Only
  4. Private


Wednesday, August 20, 2014

Products, Pricebook & PricebookEntry


Products: 

Products are the actual items that you sell on your opportunities and quotes. Products are associated to one or more price books to create price book entries. Products can exist in multiple price books with many different prices. 
For example, you may have a "North India" price book with one set of prices for your products and a "South India" price book with a different set of prices.

Price Books:

A price book is a list of products and their associated prices. Each product and its price is called a price book entry.
Salesforce provides two types of price books—standard and custom.
The standard price book is a master list of all products with their associated default or standard prices. It automatically lists all products and standard prices regardless of the custom price books that also contain them.
A custom price book is a list of products with their custom or list prices, making them ideal for offering different prices to different market segments. Custom price books can contain discounted list prices or list prices that are higher than the standard price.

Price Book Entries:

A price book entry is a price that’s defined for a product and price book.  Salesforce provides two types of price book entries—standard and custom. Standard price book entries represent the default or standard prices for the products and services that are sold.  Custom price book entries represent the custom or list prices for the products and services that are sold.  A custom price book entry can be created in a custom price book only if an active standard price book entry exists for that product or service in the standard price book.           

Notes:
  • The API name of Product is  Product2.
  • The API name of  price books is Pricebook2.
  • The API Name of Price book Entry is PricebookEntry.
  • You can create up to 50 Price Book Entry custom fields.
  • PricebookEntry is a junction object between Pricebook2 and Product2.
  • OpportunityLineItem is a junction object between PricebookEntry and Opportunit.
  • We can write the trigger on Product2 and PriceBook2 but we cannot write the trigger on PricebookEntry2 because it s a junction object and we cannot write trigger on Junction Object.
Create Price Book Entries in Apex Tests:

You can create price book entries for standard and custom price books in Apex tests.
Previously, you couldn’t create price book entries in an Apex test by default unless the test had access to organization data via the @isTest(SeeAllData=true) annotation. With this new support, you can isolate your price book test data from your organization data. Note that custom price books can be created but standard price books cannot.

Support for test price book entries is added for all tests, including tests that use the default data isolation mode (tests that can’t access organization data). 

With this support, you can do the following.
  • Query for the ID of the standard price book in your organization with the Test.getStandardPricebookId() method.
  • Create test price book entries with standard prices by using the standard price book ID that’s returned by Test.getStandardPricebookId().
  • Create test custom price books, which enables you to add price book entries with custom prices.
@isTest
public class PriceBookTest {
    // Utility method that can be called by Apex tests to create     //price book entries.
    static testmethod void addPricebookEntries() {
        // First, set up test price book entries.
        // Insert a test product.
        Product2 prod = new Product2(Name = 'Laptop X200', 
            Family = 'Hardware');
        insert prod;
        
        // Get standard price book ID.
        // This is available irrespective of the state of SeeAllData.
        Id pricebookId = Test.getStandardPricebookId();
        
        // 1. Insert a price book entry for the standard price //book.
        // Standard price book entries require the standard price //book ID we got earlier.
        PricebookEntry standardPrice = new PricebookEntry(
            Pricebook2Id = pricebookId, Product2Id = prod.Id,
            UnitPrice = 10000, IsActive = true);
        insert standardPrice;
        
        // Create a custom price book
        Pricebook2 customPB = new Pricebook2(Name='Custom Pricebook', isActive=true);
        insert customPB;
        
        // 2. Insert a price book entry with a custom price.
        PricebookEntry customPrice = new PricebookEntry(
            Pricebook2Id = customPB.Id, Product2Id = prod.Id,
            UnitPrice = 12000, IsActive = true);
        insert customPrice;
        
        // Next, perform some tests with your test price book //entries.
    }
}





Monday, August 18, 2014

Interfaces in Apex

An interface is like a class in which none of the methods have been implemented—the method signatures are there, but the body of each method is empty. To use an interface, another class must implement it by providing a body for all of the methods contained in the interface.

Interfaces can provide a layer of abstraction to your code. They separate the specific implementation of a method from the declaration for that method. This way you can have different implementations of a method based on your specific application.

In Apex, there are two types of Interface.
  1. User Define Interface (Custom Interface)
  2. System define Interface (Standard Interface)

Use Define Interface

Developer can develop the Interface via apex programming Language and can implement it in the other apex class using implements keyword.

Below is the example of an Interface define by the User:

//Interface with define two method
//Start with prefix I to denote interface
public interface ICountNumber{
    Integer getSum(integer a,integer b);
    Integer getMulti(integer a,integer b);
}

Apex class that implements the above interface:

public class clsCountNumber implements CountNumber
{
    public Integer getSum(Integer a,Integer b)
    {
        return (a+b);
    }
    public Integer getMulti(Integer a,Integer b)
    {
        return (a*b);
    }
}

Systems defined Interface (Standard Interface)

Salesforce provides some standard interface that we can implement In your apex classes. Some of the Standard Interface as below:
  1. Database. Batchable Interface (For Handling bulk records)
  2. System. Schedulableinterface  (For Running apex class at a specific time)
  3. Site.UrlRewriter (Enables rewriting Sites URLs.)
  4. HttpCalloutMock (Enables sending fake responses when testing HTTP callouts.)
  5. WebServiceMock Interface (Enables sending fake responses when testing Web service callouts of a class auto-generated from a WSDL.)
  6. Messaging.InboundEmailHandler interface (To handle an inbound email message.)
There are many other interfaces provided by Salesforce but the above are generally used.


Polymorphisms in Apex

Polymorphisms are generic terms that mean "many shaps". Allows you to use an entity in multiple forms. polymorphisms are achieved by using many different techniques named method overloading, operator overloading, and method overriding.

Overloading vs. Overriding In the apex

In Java we use the “final” keyword to stop overriding by child classes; this applies to both classes and methods, however, in apex, every class or method is final by default. So if you want to make a class/method inheritable we have to declare it either “virtual” or “abstract”. So In Java, we declare “What you can’t extend” and in Apex you declare “What you can extend”.
  1. Overloading happens at compile-time while Overriding happens at runtime.
  2. Overloading is being done in the same class while overriding base and child classes are required Overriding is all about giving a specific implementation to the inherited method of the parent class.
  3. Performance: Overloading gives better performance compared to overriding. The reason is that the binding of overridden methods is being done at runtime.
  4. Private and final methods can be overloaded but they cannot be overridden and in Apex, all methods and classes are final by default. So to override a class or a method we have to use virtual and override keywords.

Overloading

The conditions for method overloading:
  • The number of parameters is different for the methods.
  • The parameter types are different (like changing a parameter that was a float to an int).  
You cannot make overloading:
  • Just changing the return type of the method.  If the return type of the method is the only thing changed, then this will result in a compiler error.  
  • Changing just the name of the method parameters, but not changing the parameter types.  If the name of the method parameter is the only thing changed then this will also result in a compiler error. 
Example of Overloading

public class CalculateNumber
{
     public static Integer Sum(Integer FirstNum,Integer SecondNum)
     {
         return FirstNum+SecondNum;
     }
     public static Integer Sum(Integer FirstNum,Integer SecondNum,
Integer ThridNum)
     {
         return FirstNum+SecondNum+ThridNum;
     }
}


Overriding

Overriding means having two methods with the same method name and arguments (i.e., method signature). One of them is in the Parent class and the other is in the Child class.

Rules for method overriding:
  • The argument list should be exactly the same as that of the overridden method.
  • The return type should be the same or a subtype of the return type declared in the original overridden method in the superclass.
  • A method declared final cannot be overridden. As Apex class and method are final by default so if we want to override any method or class, we need to declare it by virtual keyword.
  • Use override keyword in the child class where you are going to override the method of the parent class.
Example of Overriding

Parent Class-

//Define Virtual keyword otherwise class will be final
public virtual class Parent_Marker
{   
    //Define virtual methods
     public virtual void write()
     {
         system.System.debug('This is in parent class..')
     }
     public virtual double discount()
     {
         return 2.5;
     }
}

Child class-

//Extend write method from Parent
public class Child_Marker extends Parent_Marker
{   
    //Define override methods
     public override void write()
     {
         system.System.debug('This is in child class..')
     }
     
}


Abstract class and methods

  • Only abstract classes can have abstract members.
  • An abstract method cannot provide any implementation means you can only declare the body. You cannot define.
  • An abstract function has to be overridden while a virtual function may be overridden.

Sunday, August 17, 2014

Heap Size

A stack is a place in the computer memory where all the variables that are declared and initialized before runtime are stored. The heap is the section of computer memory where all the variables created or initialized at runtime are stored. On the other hand, the heap is an area of memory used for dynamic memory allocation.

  • When you create objects in Apex code memory is allocated to store the objects. And that memory is allocated from the allocated heap. Think of it as a designated amount of memory you can use up in your Apex request.

  • Heap play an important role when your application runs, Bad code quality can consume the heap size badly and which impact the performance of your application

Apex heap size too large
  • As you know heap is important to allocate the memory at runtime and hence we should be very careful while writing the code and must ensure to take care of heap size. If the heap size is huge, it will surely impact the performance of the application and the application will get slow. 

  • Salesforce enforces an Apex Heap Size Limit of 6MB for synchronous transactions and 12MB for asynchronous transactions.

  • The "Apex heap size too large" error occurs when too much data is being stored in memory during processing. The limit depends on the type of execution (E.g. synchronous vs asynchronous calls) and the current value can be found in the Apex Developer's Guide.

It is important to review your code and follow best practices to ensure that the heap limit does not exceed the maximum. The below example shows the incorrect use of collections. 

The List baseList, the value of SampleMap and the List tempList are pointing to the same memory address. As a result, the heap size doubles with each iteration of the loop.

public class HealsizeExample{

   public static void testHeapSize(){

       String str = 'aaaaa bbbbb ccccc ddddd eeeeee fffff hhhhh jjjjj kkkkk lllll mmmmm';

       List<String> baseList = str.split(' ');

       System.debug('This is baseList :'+baseList);

       System.debug('This is baseList :'+baseList.size());

       List<String> bigList = baseList;

       system.debug('This is bigList :'+bigList);

       System.debug('This is bigList :'+bigList.size());

       Map<integer, List<String>> SampleMap = new Map<integer, List<String>>();

       SampleMap.put(1, bigList);

       system.debug('This is SampleMap :'+SampleMap);

       System.debug('This is SampleMap :'+SampleMap.size());

       for (integer i=0; i<50; i++) {

           List<String> tempList = new List<String>();

           tempList = SampleMap.get(1);

           bigList.addAll(tempList);

       }

       system.debug('FINAL LIST SIZE IS '+bigList.size());

   }

}


Solution-

public class heapCheckSuccess{

 public static void myHeapTest(){

   String tStr = 'aaaaa bbbbb ccccc ddddd eeeeee fffff ggggg 11111 22222 33333 44444';

   List<String> baseList = tStr.split(' ');

   Map<integer, List<String>> Sample = new Map<integer, List<String>>();

   List<String> bigList = baseList;

 

   Sample.put(1, bigList);

   List<string> myList = new list<string>(); //Declare a new list

 

   for (integer i=0; i<50; i++) {

     List<String> tempList = new List<String>();

     tempList = Sample.get(1);

     system.debug('templist: ' + tempList.size());

     system.debug(' bigList: ' + bigList.size());

 

     myList.addall(tempList); //original code is  bigList.addall(tempList);

   }

 

   system.debug('FINAL LIST SIZE OF bigList IS '+ bigList.size());

   system.debug('myList IS '+mylist.size());

 }

}


Best Practices to avoid Heap Size

  1. Use the Transient Keyword

    • Try using the "Transient" keyword with variables in your controllers and extensions. The transient keyword is used to declare instance variables that cannot be saved, and shouldn't be transmitted as part of the view state for a Visualforce page.

  2. Use Limit Methods

  • Use heap limits methods in your Apex code to monitor/manage the heap during execution. 

  • Limits.getHeapSize() - Returns the approximate amount of memory (in bytes) that has been used for the heap in the current context.

  • Limits.getLimitHeapSize() - Returns the total amount of memory (in bytes) that can be used for the heap in the current context.

  1. Fetch only necessary Fields in the SOQL Query

    • If the objects in your collection contain related objects (i.e., Account objects with a number of related Contacts for each) make sure the related objects only contain the fields that are actually needed by your script.

  2. Use SOQL For Loops

    • To avoid heap size limits, developers should always use a SOQL "for" loop to process query results that return many records. SOQL "for" loops retrieve all sObjects in a query and process multiple batches of records through the use of internal calls to query and queryMore.

    • Issue

List accs = [SELECT Id, Name FROM Account];

for(Account a : accs){

  System.debug(a.Name);

}

List accs = [SELECT Id, Name FROM Account];

for(Account a : accs){

  System.debug(a.Name);

}

    • Solution

    • for(Account a : [SELECT Id, Name FROM Account]){

        System.debug(a.Name);

      }

      for(Account a : [SELECT Id, Name FROM Account]){

        System.debug(a.Name);

      }

  1. Switching to Batch Apex increased the heap limit to 12000000 bytes. Also, by setting the scope to 1 only one attachment was processed at a time.

  2. Don't use class-level variables to store a large amount of data.
  3. Run Future Methods with Higher Limits (Pilot)

@future(limits='2xHeap')

 

    public static void myFutureMethod() {

 

    // Your code here

 

    }