Concepts or coding lessons of Salesforce that you can implement easily

Showing posts with label apex. Show all posts
Showing posts with label apex. Show all posts

Schedulable Batch Apex In 3 Easy steps In Salesforce

There are three main steps involved in Schedulable Batch Apex

1. Write a Batch Class
2. Write a Scheduled Apex class which execute the above Batch Class
3. Schedule the Scheduled Apex class from the Developer Console or from UI

So here we go...

Step 1. Write Batch Class

global class BatchApexClassExample implements Database.Batchable<SObject>{
 global Database.QueryLocator start(Database.BatchableContext BC) { 
  String soqlquery = 'SELECT Id, name, phone FROM Account';
  return database.getquerylocator(soqlquery);
 }
 // The batch job executes and operates on one records batch of max 200
 global void execute(Database.BatchableContext BC, List<SObject> scope) { 
   // your logic
   System.debug('In BatchApexClassExample - Execute Method ');
 }
 // The batch job finishes
 global void finish(Database.BatchableContext BC) { 
   System.debug('BatchApexClassExample Batch job completed successfully.');

Step 2. Write a Scheduled Apex which execute the above Batch Class

global with sharing class ScheduleBatchApexClassExample implements Schedulable {
 global void execute(SchedulableContext sc) {
  ID BatchId = Database.executeBatch(new BatchApexClassExample(), 200);
 }
}

Step 3. Schedule the class from the Developer Console or from UI
  •  From UI : Go to Setup -> Apex Classes -> Click on Schedule Apex button
  •  From Developer Console, check below 
 Execute a schedulable Apex class with System.schedule method

 System.schedule('ScheduleBatchApexClassExampleScheduler', '0 0 * * * ?', new ScheduleBatchApexClassExample());

Good job, we are done. 

If you want to see your batch job scheduled then 

  • Go to Setup—>Monitor –> Scheduled Jobs

If you want to Schedule a Class in Every 5 Mins in Salesforce, since this is not possible to do through standard Salesforce User interface.


Yes I have solution for it. Use above small code snippets to do so for every 5 minutes.


Check my next post Run Schedule a Class In Every 5 Mins in Salesforce

Some important things about Schedulable Batch Apex :


Syntax for CRON expression:

Seconds Minutes Hours Day Month Week Year

Year is optional.


Seconds                         :- 0–59
Minutes                         :- 0–59
Hours                         :- 0–23
Day (Day_of_month) :- 1–31
Month                         :- 1–12
Week (Day_of_week)         :- 1–7

Year                             :- null or 1970–2099

The following are some examples of cron expressions:

ExpressionDescription
0 0 13 * * ?Class runs every day at 1 PM.
0 0 22 ? * 6LClass runs the last Friday of every month at 10 PM.
0 0 10 ? * MON-FRIClass runs Monday through Friday at 10 AM.
0 0 20 * * ? 2010Class runs every day at 8 PM during the year 2010.
Apex Scheduler Limits:


  • You can only have maximum 100 scheduled Apex jobs at one time.
  • The maximum number of scheduled Apex executions per a day or 24-hour period is 250,000 or the number of user licenses in your organization multiplied by 200, whichever is greater in number.

Apex Scheduler Notes and Best Practices:


  • Salesforce schedules the apex class for execution at the specified time. Actual execution may be delayed based on salesforce service availability.
  • In Salesforce, Synchronous Web service callouts are not supported from scheduled Apex class. To be able to make callouts, make an asynchronous callout by placing @future(callout=true) annotation in class method and call this method from scheduled Apex class.
  • If any apex jobs scheduled to run during a Salesforce service maintenance downtime, those will be scheduled to run after the service comes online again, when system resources become available.
Enjoy! If you have any questions, comments, please feel free to let me know. As always, please feel free to get in touch me as I would be more than happy to assist you with any of your Salesforce development needs.

Next post: Run Schedule a Class In Every 5 Mins in Salesforce

Run Schedule a Class In Every 5 Mins in Salesforce

You can run apex job every 1-hour using CRON expression by default but you can schedule this job 12 times in one hour at 5 min duration.

If you are not aware of Schedulable Batch Apex then first look Schedulable Batch Apex In 3 Easy steps In Salesforce


Then how to Schedule a Class in Every 5 Mins in Salesforce, since this is not possible to do through the standard Salesforce User interface.

Yes, I have a solution for it. So here is a small code to do so for every 5 minutes.

Example, you have Scheduler class ScheduleBatchApexClassExample which is in my other blog and want to run the schedule a class in every five mins, then use below CRON expression.

How to run follow below process:


Go to your developer console -> Open Execute Anonymous Window -> Copy and Paste Below code and click on execute button

Simply say, Run below CRON expression from your developer console:



System.schedule('Schedule Job Name 1',  '0 00 * * * ?', new ScheduleBatchApexClassExample());
System.schedule('Schedule Job Name 2',  '0 05 * * * ?', new ScheduleBatchApexClassExample());
System.schedule('Schedule Job Name 3',  '0 10 * * * ?', new ScheduleBatchApexClassExample());
System.schedule('Schedule Job Name 4',  '0 15 * * * ?', new ScheduleBatchApexClassExample());
System.schedule('Schedule Job Name 5',  '0 20 * * * ?', new ScheduleBatchApexClassExample());
System.schedule('Schedule Job Name 6',  '0 25 * * * ?', new ScheduleBatchApexClassExample());
System.schedule('Schedule Job Name 7',  '0 30 * * * ?', new ScheduleBatchApexClassExample());
System.schedule('Schedule Job Name 8',  '0 35 * * * ?', new ScheduleBatchApexClassExample());
System.schedule('Schedule Job Name 9',  '0 40 * * * ?', new ScheduleBatchApexClassExample());
System.schedule('Schedule Job Name 10', '0 45 * * * ?', new ScheduleBatchApexClassExample());
System.schedule('Schedule Job Name 11', '0 50 * * * ?', new ScheduleBatchApexClassExample());
System.schedule('Schedule Job Name 12', '0 55 * * * ?', new ScheduleBatchApexClassExample());

After this, if you want To check apex class in scheduled or not then:
Go to -> Setup -> Jobs -> Scheduled Jobs















So Easy !!!

Some important things of System.schedule :


To Run Schedule a Class In Every 5 Mins in Salesforce, you have to use System.schedule method. System.schedule method is used to executes a Apex class. 

System.schedule('ScheduleBatchApexClassExampleScheduler', '0 0 * * * ?', new ScheduleBatchApexClassExample());

If you want to see your batch job scheduled then 
  • Go to Setup—>Monitor –> Scheduled Jobs
Syntax for CRON expression:

Seconds Minutes Hours Day Month Week Year


Year is optional.

The following are some examples of cron expressions:
ExpressionDescription
0 0 13 * * ?Class runs every day at 1 PM.
0 0 22 ? * 6LClass runs the last Friday of every month at 10 PM.
0 0 10 ? * MON-FRIClass runs Monday through Friday at 10 AM.
0 0 20 * * ? 2010Class runs every day at 8 PM during the year 2010.

Enjoy! If you have any questions, comments etc. please feel free to let me know. As always, please feel free to get in touch me as I would be more than happy to assist you with any of your Salesforce development needs.

An Introduction to Visualforce View State in Salesforce

Visualforce pages that contain a form component also contain an encrypted, hidden form field that encapsulates the view state of the page. 

This view state is automatically created, and as its name suggests, it holds the state of the page - state that includes the components, field values and controller state.

The view state size of your Visualforce pages must be under 170 KB. (Prior to Spring 19 release it was 135 KB. for reference: Spring 19 Release Notes).
By reducing your view state size, your pages can load quicker and stall less often.

Serialization is what occurs when binary computer memory is converted into a format that can be transferred to disk or over a network connection. In Salesforce (and most other web-based platforms), this is commonly called the View state in Salesforce. 


When a Visualforce page receives a view state, it "deserializes" the data into an existing object, and acts as the object initialization routine instead of the constructor that is defined for the class. When there is no view state, the constructor is called instead.

How I can see view state:

To see view state, Enable Development mode from your user record.

View State
View State
Best practices to optimize view state:

  • Minimize Number of Forms on a Page :
Assume a page contains two forms - form A and form B. Whichever form the user submits and causes a postback, the view state for the page needs to get transferred. To support this, each form on your page will have its own copy of view state. If the associated view state is large, instead of having multiple forms on a page, have a single form and use <apex:actionRegion> to submit portions of the form. This practice will ensure that only a single copy of the view state is associated with that page.
  • Declare Variables as Transient to Reduce View State :
An instance variable declared as transient is not saved and is not transmitted as part of the view state. If a certain field is needed only for the duration of the page request and does not need to be part of the view state, declare it as transient.
  • Recreate State versus Storing It in View State:
View state should ideally contain only work in progress data. If you can reconstruct the data during postback, via a SOQL query or a web services call, do that instead of storing it in controller data members.
  • Use Custom Objects or Custom Settings to Store Large Quantities of Read-Only Data:
Assume that your controller needs to call a Web service and parse a large response object. Storing it in view state may not even be an option given the size. Marking it as transient would incur the cost of an additional Web service call and parsing it again. In such instances, you could store the parsed response in a custom object and store just the record id to get to the parsed response. Custom settings provide another mechanism to cache data needed by your controller. Accessing custom settings is faster than access to custom objects since custom settings are part of your application's cache and does not require a database query to retrieve the data.
  • Refine Your SOQL to Retrieve Only the Data Needed by the Page:
Only retrieve and store the fields in variable you need and also filter the records to only retrieve records needed by the visual force page.
  • Refactor Your Pages to Make Its View Stateless:
Instead of using <apex:commandLink> or <apex:commandButton> components which need to be inside a <apex:form> component to invoke an action, use an <apex:outputLink> or other non-action method instead and implement the action through an <apex:page> action attribute - where it makes sense.


Enjoy! If you have any questions, comments etc. please feel free to let me know. As always, please feel free to get in touch me as I would be more than happy to assist you with any of your Salesforce development needs.

Actionpoller Tag in Visualforce Page

Action poller is acts as a timer in visual force page. A timer that sends an AJAX request to the Salesforce server according to a time interval that you specified.
The time interval between AJAX update requests is always be in seconds. 
This timer value must be 5 seconds or greater than 5, and if it not specified, then defaults to 60 seconds. 

In this article, I will demonstrate how to use <apex:actionpoller> in visual force page.

Create Visualforce Page -->

<apex:page controller="exampleCon">
    <apex:form>
        <apex:outputText value="This counter is changing, check this: {!count}" id="counter"/>
        <apex:actionPoller action="{!incrementCounter}" reRender="counter" interval="15"/>
    </apex:form>
</apex:page>


Create Apex Controller: -->

public class exampleCon {
    Integer count = 0;

    public PageReference incrementCounter() {
        count++;
        return null;
    }

    public Integer getCount() {
        return count;
    }
}

Note that if an <apex:actionPoller> is ever re-rendered as the result of another action, then this tag resets itself. An <apex:actionPoller> must be within the region where it acts upon. 
For example, to use an <apex:actionPoller> tag with an <apex:actionRegion> tag, the <apex:actionPoller> tag must be within the <apex:actionRegion> tag.

Check below point while using <apex:actionPoller>


  • Action methods used by <apex:actionPoller> tag should be lightweight. It's a best practice to avoid performing error whcih are occured in DML, external service calls, and other resource-intensive operations in action methods called by an <apex:actionPoller> tag . 
  • <apex:actionPoller> tag refreshes the connection regularly, which keeping login sessions alive. A page with <apex:actionPoller> tag on visualforce won't time out due to inactivity.
  • If an <apex:actionPoller> tag is ever re-rendered as the result of another action, then this tag resets itself.
  • Time out can also be specified as an attribute in actionpoller tag. Once the time out point is reached it stops making AJAX callout to the Salesforce server and no more controller method is called.
Below are the attributes supported by actionpoller tag:


Attribute
Description
action
The action () invoked by the timer for a periodic AJAX update request from the page. Use the merge field syntax to reference the action method. For example, action="{!incrementCounter}" references the incrementCounter() method in the controller. If no an action is specified, then the page simply refreshes.
enabled
This is a Boolean value that indicates whether the poller is active or not. If not specified, then this value defaults to true.
id
An identifier that allows the one component to be referenced by other components in the page.
interval
This is the time interval between 2 AJAX update requests, which is in seconds. interval value must be 5 seconds or greater than that, and if this value is not specified, then by defaults Salesforce take is as 60 seconds. Keep in mind that the interval is only the amount of time between the update requests. Once an update request is sent to the server, it enters a server queue and can take additional time to process and display to the client.
oncomplete
The JavaScript function invoked when the result of an AJAX update request completes on the client.
onsubmit
The JavaScript function invoked before an AJAX update request has been sent to the server.
rendered
A Boolean value that indicates whether the component is rendered on the page or not. If this not specified, then this value defaults to true.
reRender
The ID of one or more components that are redrawn when the result of an AJAX update request returns from a server to the client. This value can be a single ID or can be a comma-separated list of IDs, or a merge field expression for a list or collection of IDs.
status
The ID of a related to the component that displays the status of an AJAX update request. 
timeout
The amount of time specified in milliseconds before an AJAX update request should time out.

Enjoy! If you have any questions, comments etc. please feel free to let me know. As always, please feel free to get in touch me as I would be more than happy to assist you with any of your Salesforce development needs.


Main Difference Between ISBLANK And ISNULL in Salesforce

ISBLANK
ISNULL
ISBLANK determines if an expression has a value then returns TRUE if it does not. If an expression contains a value, then this function returns FALSE.
ISNULL determines if an expression is null (blank) then returns TRUE if it is. If the expression contains a value, then this function returns FALSE.
Syntax: ISBLANK(expression)
Syntax: ISNULL(expression)
It checks whether an expression is blank and returns TRUE or FALSE
It checks whether an expression is null and returns TRUE or FALSE
ISBLANK supports text fields.
Text fields are never null, so using ISNULL function with a text field always returns false result.
For Numeric fields, ISBLANK function only returns TRUE if the field has no value and not configured to treat blank fields as 0s.
ISNULL supports Numeric fields.

Note: Instead of using ISNULL, use ISBLANK in new formulas. Both functions have same functionality, but ISBLANK supports text fields. Salesforce will continue to support ISNULL, so you do not need to worry and change any existing formulas.


The below tests does not have any value present in both text and number field including whitespace.
S NO
Formula function
Formula option
Field type
Result
1
ISBLANK()
Treat blank fields as zeroes 
Text
True
2
ISBLANK()
Treat blank fields as blanks
Text
True    
3
ISBLANK()
Treat blank fields as zeroes
Number
False
4
ISBLANK()
Treat blank fields as blanks
Number
True
5
ISNULL()
Treat blank fields as zeroes
Text
False
6
ISNULL()
Treat blank fields as blanks
Text
False
7
ISNULL()
Treat blank fields as zeroes
Number
False
8
ISNULL()
Treat blank fields as blanks
Number
True








From the output, it's clear that both the formula functions are not same and they behave differently for different field types.

ISBLANK:


Description: Determines if an expression has a value and returns TRUE if it does not. If ISBLANK contains a value, then this function returns FALSE.

Use: ISBLANK(expression) and replace the expression with the expression you want to evaluate.

Example:
(IF(ISBLANK(Maint_Amount__c), 0, 1) +
 IF(ISBLANK(Services_Amount__c), 0,1) +
  IF(ISBLANK(Discount_Percent__c), 0, 1) +
   IF(ISBLANK(Amount), 0, 1) +
    IF(ISBLANK(Timeline__c), 0, 1)) / 5

This formula takes a group of fields and calculates what percent of them are being used by your personnel. Above formula field checks five fields to see if they are blank or not. If so, a zero is counted for that field. A "1" is counted for any field that contains a value and this total is divided by five (the number of fields evaluated). Keep in mind that above formula requires you select the Treat blank fields as blanks option under Blank Field Handling while the Advanced Formula subtab is showing.

Below are the Tips for ISBLANK:
  • Instead of using ISNULL, use ISBLANK in new formulas. Both functions have same functionality, but ISBLANK supports text fields. Salesforce will continue to support ISNULL, so you do not need to worry and change any existing formulas.
  • A field contains character the its not empty, blank space, or zero. For example, a field that contains a space inserted with the spacebar is not an empty field.
  • If the field does not have a value, then use the BLANKVALUE function to return a specified string ; use the ISBLANK () function if you only want to check if the field has a value or not.
  • If you use ISBLANK () function with a numeric field, the function only returns TRUE if the field has no value. ISBLANK () function is not configured to treat blank fields as zeroes.
  • If you want to use this function with a picklist datatype, then use ISBLANK(TEXT(<picklist>)) to convert the picklist items into a text value.
ISNULL:


Description: ISNULL determines if an expression is null (blank) then returns TRUE if it is. If the expression contains a value, then this function returns FALSE.

Use: ISNULL(expression) and replace the expression with the expression you want to evaluate.

Example:
(IF(ISNULL(Maint_Amount__c), 0, 1) +
 IF(ISNULL(Services_Amount__c), 0,1) +
  IF(ISNULL(Discount_Percent__c), 0, 1) +
   IF(ISNULL(Amount), 0, 1) +
    IF(ISNULL(Timeline__c), 0, 1)) / 5

Above formula takes a group of fields and calculates what percent of them are being used by your personnel. Above formula field checks 5 fields to see if they are blank. If so, a 0 is counted for that field. 1 is counted for any field that contains a value and the total is divided by 5 (as we are evaluating 5 fields, i.e. the number of fields evaluated). Note that above formula requires you select the Treat blank fields as blanks option under Blank Field Handling while the Advanced Formula subtab is showing.

Validation Rule Example:

AND(ISPICKVAL(StageName, "Closed Won"), ISNULL(Project_Start_Date__c))

This validation rule makes the Project Start Date custom date field conditionally required whenever the stage is "Closed Won"

Below are the Tips for ISNULL:

  • Text fields are never null, so using ISNULL () function with a text field always returns false. For example, the formula field IF(ISNULL(new__c) 1, 0) is always 0 regardless of the value in the New field. For text fields, you must use the ISBLANK function instead of ISNULL.
  • Multi select picklist fields are never null in s-controls which are deprecated, buttons, and email templates, so using ISNULL function with a multi select picklist field in those contexts always returns false.
  • Date & date/time fields which are Empty, then this function always return true when referenced in ISNULL functions.
  • Do not use ISNULL function for date/time fields.
  • Choose Treat blank fields as blanks for your formula when referencing a number field, percent field, or currency field in an ISNULL () function. Choosing Treat blank fields as 0s gives blank fields the value of 0 so none of them will be null.
  • Merge fields can be handled as blanks, which can affect the results of components like s-controls ( which are deprecated ) because they can call ISNULL function.

Enjoy! If you have any questions, comments etc. please feel free to let me know. As always, please feel free to get in touch me as I would be more than happy to assist you with any of your Salesforce development needs.