Wednesday, October 19, 2016

Visualforce Component for Record Status Progress Bar

Sometimes we have to display current status of record through progress bar on record detail page. For example user can directly see the status of current opportunity or case by looking into detail page of record.




For this purpose we generally create a VF page and embed it in record page layout.

I have created a generic visualforce component which can be used to display record status bar. We just have to pass the object API name and field API name to component and it will generate status bar for you.

Upload below image image in static resource and name it as "progressbar".


Just create a new VF page and include this component in it. Below is code for visualforce Component and visualforce component Controller.


Suppose we need to display progress bar for opportunity stage, then use below code.

<apex:page standardController="Opportunity">
<c:StatusProgressBar objectAPIName="Opportunity"  fieldAPIName="stagename"/>
</apex:page>

Note:
  • You need to specify the objectAPIName and fieldAPIName for which you want to display progress bar.
  • Add this VF page to page layout to display progress bar.

Opportunity Record Detail Page



Now suppose you want to display progress bar for case record then create a VF page and use below code:

<apex:page standardController="Case">
<c:StatusProgressBar objectAPIName="Case" fieldAPIName="Status"/>
</apex:page>

Here we are displaying the progress bar for status field present in case. You can display status bar for any picklist field (standard or custom).



Friday, October 14, 2016

Batch Apex Job Progress Bar

We can display the progress of Batch Apex job on UI to user. Apex allows you to query the job status by query AsyncApexJob  object and getting all details about running job like status, JobItemsProcessed, NumberOfErrors, TotalJobItems etc. By using apex, we can manipulate the result and display the progress bar for batch job.

Suppose you already have Apex Batch class written. Here for example "RecordTypeAccessFinder" is batch class is already present.

Below is VF page and Apex class Code:



Monday, October 3, 2016

Asynchronous Apex- Apex Scheduler, Batch Apex & Future Methods Implementation Tricks

Salesforce provide different options to run asynchronous jobs which can run in background whenever salesforce resources will be available.

Apex Scheduler is one of the options through which you can schedule a job to run after certain interval of time or to run at particular time everyday, every week, every month etc.

Batch Apex allows you to process large volume of data. Normal apex class will hit governor limits if we process large volume of data. Batch Apex split the records in different batched and you will get new governor limits for each batch.

Future methods runs asynchronously which can be used to perform some operation in background. When you are executing particular code and you want to perform some other operation and don't want to wait for it to get completed, then you can use future method to perform that operation and you can continue executing your code. You can consider that future methods starts new thread or execution.

Now we are going to cover different scenarios related to future methods and apex schedulers and batch apex.


  • Is it possible to call future method from apex scheduler or not?
         Yes

Below is sample code which I tested for this scenario. After scheduling the scheduler, I checked the debug logs and it was displaying logs for future handler  and debug statement present in future method was present in logs.

//Scheduled Apex 
public class DemoScheduler1 implements Schedulable{
    public void execute(SchedulableContext sc){
        system.debug('*******Going to call future method ');
        DemoAsynchronousTest.futureMethodCallFromScheduler();
    }
}
//apex class containing future method
public class DemoAsynchronousTest{
    @future
    public static void futureMethodCallFromScheduler(){
        system.debug('******futureMethodCallFromScheduler get called');
    }
    
}

  • Is it possible to do Synchronous Web service callouts from scheduled apex?
          No.

Synchronous Web service callouts are not supported from scheduled Apex. To be able to make callouts, make an asynchronous callout by placing the callout in a method annotated with @future(callout=true) and call this method from scheduled Apex. However, if your scheduled Apex executes a batch job, callouts are supported from the batch class.

  • Can we call scheduler from future method?
Yes

  • Can we call future method from batch apex (from execute method)?
No

  • Is there is any way through which we can call future method from batch apex?
As we know that a webservice can be called from batch class and webservice can call @future method. So in your batch class call webservice and which can call your @future method.         
Also you can call future method from finish method in batch class.

  • What all different things which we need to consider while using future methods?
  1. Methods with the future annotation cannot be used in Visualforce controllers in either getMethodName or setMethodName methods, nor in the constructor.
  2. You cannot call a method annotated with future from a method that also has the future annotation. Nor can you call a trigger from an annotated method that calls another annotated method.
  3. Future methods cannot be called from batch class.

  • Can we modify the scheduler class or classes referenced by this scheduler class if any scheduled job is pending?
          No

If there are one or more active scheduled jobs for an Apex class, you cannot update the class or any classes referenced by this class through the Salesforce user interface. However, you can enable deployments to update the class with active scheduled jobs by using the Metadata API.

  • What we can do if we have to deploy the scheduler class or classes referenced by this scheduler class if any scheduled job is pending for that scheduler class in target org?
By default, changes to Apex code that have Apex jobs pending or in progress can’t be deployed. To deploy these changes, do one of the following.
  • Cancel Apex jobs before deploying changes to Apex code. Reschedule the jobs after the              deployment.
  • Enable deployments with Apex jobs in the Salesforce user interface in the Deployment Settings page.



          

Tuesday, September 13, 2016

Dynamic Apex in Salesforce

You can fetch all sobject and their field information in apex by using describe methods. Apex gives 2 data types for sobject and field information.
  1. Token: A lightweight, serializable reference to an sObject or a field that is validated at compile time.
  2. Describe Result: It contains all the describe information about sobject and fields. Describe result objects are not serializable, and are validated at runtime.
It is easy to move from a token to its describe result, and vice versa. Both sObject and field tokens have the method getDescribe which returns the describe result for that token.
On the describe result, the getSObjectType and getSObjectField methods return the tokens for sObject and field, respectively.

Finding All object in Organization

Schema getGlobalDescribe method returns a map that represents the relationship between all sObject names (keys) to sObject tokens (values).
For example:
Map<String, Schema.SObjectType> schemaMapOfOrg = Schema.getGlobalDescribe();
The map has the following characteristics:
  • It is dynamic, that is, it is generated at runtime on the sObjects currently available for the organization, based on permissions.
  • The sObject names are case insensitive. 
  • The keys use namespaces as required. The keys reflect whether the sObject is a custom object.
Creating sObjects Dynamically

If we need to create contact record dynamically, then use below code:
String typeName='Contact';
Schema.SObjectType objToken = Schema.getGlobalDescribe().get(typeName);
sobject son= objToken.newSObject();
son.put('firstname','Execute1');
son.put('LastName','Kumar');
son.put('Email','sunil.kumar2@in.gmail.com');
insert son;

Apex code to find all sobject and their fields

Apex code to generate SOQL to fetch all fields of an object

Monday, September 12, 2016

RecordTypeId using Describe & SOQL

RecordTypeId of an object can be determined by using 2 different options:

For example we will find out the recordtypeId of "Renewal" recordtype of opportunity.

By Using Describe:
Id renewalRecordTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('Renewal').getRecordTypeId();
Advantage: Saves on SOQL limits but uses a describe call.

By using SOQL:
Id renewalRecordTypeId =[select id from recordType where  sobjectType='Opportunity' AND DeveloperName='Renewal'].Id;
Advantage of SOQL: If in future, someone change the name of recordtype, the code will work as it refers developername.

Sunday, August 28, 2016

HighCharts in Visualforce Page

We can use interactive charts provided by HighCharts in Visualforce page. Here I am going to display line chart using highCharts.

For example, we will display the count of opportunity group by stage.

Download  js files from below mentioned URL and store it in static resource:

  • https://code.highcharts.com/highcharts.js
  • https://code.highcharts.com/modules/exporting.js
  • https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js

Create VF page "HighChartDemo" and apex class "HighChartDemoController". Below is VF page and apex class code:



Chart Snapshot:




HighCharts gives option to download chart in PNG, JPEG, PDF and SVG vector image.

Tuesday, June 14, 2016

Data Load through Command line Interface in Salesforce


Purpose: To insert, extract and then delete Accounts records from Salesforce.

Steps to, install data loader.

1.       Download Apex data loader. Navigate to Set up->Administration Set up->Data management->Data Loader. Click on Download Data Loader link.
2.       Install apex data loader setup.  C:\Program Files (x86)\salesforce.com\Apex Data Loader 23.0 will be default location while installing.

Below are the steps in order to achieve our requirement:

1. Create a folder and name it as “data Loader Demo” in E drive.
2. Generate Key File.
Open Command Prompt (Go to run-type cmd press enter), change directory to bin:
cd Program Files (x86)\salesforce.com\Apex Data Loader 23.0\bin>   press enter
Now type :
Encrypt   –g  randomtext


key will be generated, copy the key in notepad and save it as keyToEncrypt.txt in data Loader Demo folder. Note the path of this Key.txt file. In our case path is E:\Data Loader Demo\keyToEncrypt.txt

3. Encrypt Password and security token.
In command prompt, type
Encrypt   –e password+securitytoken  “ path of key.txt file”
For example:
Encrypt  –e  xxxxxx129k19YRftloxFbgBMkb6NZsNK  “E:\Data Loader Demo\keyToEncrypt.txt"



Save the encrypted password for later use.
In our case generated password is:
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx6c75bb5c73f60175181c7aa5d1441aee65c

4. Create 4 new  folders as Mapping files, Log files, extracted Accounts and Account data      folder in Data Loader demo folder


Create mapping files for insert and delete from Apex Data Loader GUI and copy paste in Mapping files folder


Create insertAccounts.csv file in Account data folder which will be inserted into salesforce.


Log files folder will be used to store success and error files.

5. Copy config.properties from below mentioned directory:
C:\Program Files (x86)\salesforce.com\Apex Data Loader 23.0\conf


Paste this file in “Data Loader Demo” folder.

Also copy process-conf.xml file from below mention directory to “Data Loader Demo folder”
C:\Program Files (x86)\salesforce.com\Apex Data Loader 23.0\samples\conf


Data Loader Demo folder:


6. Now edit process-conf.xml file in notepad:


7. Create Batch file to do the operation in bin folder.

Create a new text file with following content:

call process "E:\Data Loader Demo" accountInsert
call process "E:\Data Loader Demo" csvAccountExtractProcess
call process "E:\Data Loader Demo" AccountDeleteProcess


Save the file as autorundataloadcommandlineinterface.bat and store it in bin folder
Path : C:\Program Files (x86)\salesforce.com\Apex Data Loader 23.0\bin
     

8. Run the batch.
Open cmd, change the directory to bin “C:\Program Files (x86)\salesforce.com\Apex Data Loader 23.0\bin” and type autorundataloadcommandlineinterface.bat, and press enter



OR you can double click on bat file to execute the process.

Now check your log files and extracted Accounts folder to see success and error files and extracted account file.


Steps to schedule the data upload process or to start execution of bat file

1. Control Panel->System and Security->Administrative Tools->task scheduler->create basic task->







Browse > C:\Program Files (x86)\salesforce.com\Apex Data Loader 23.0\bin \autorundataloadcommandlineinterface.bat file and click next


            Click on finish.