About Me

My photo
PLANO, Texas, United States

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

 

    }