New Batch#100 (10th Nov 2021) - Salesforce Admin + Dev Training (WhatsApp: +91 - 8087988044) :https://t.co/p4F3oeQagK

Saturday, 14 July 2012

Batchable Apex and Schedulable Apex

* It is a powerful new feature to do batch processing on our database records.
* It was released in summer'09.
* It is used to execute large volumes of data unlike ordinary DML and SOQL  statements.
* Tasks that require processing of large data volumes without any active human intervention can take advantage of this feature.
As an example, consider the task of validating addresses in your contacts when you can potentially have millions of contact records.  A batch job would be ideal for this scenario since you can start the batch job, continue to work or even log off while the job continues to execute.
* Batch-apex can execute large volumes of data up to 50 million records.
*To remove custom object records in bulk we need to delete it through data loader, now we can do it with Batch-apex.
*For Mass updating, inserting and other similar scenarios like this can be more conveniently handled with force.com's Batch Apex.
* With Batch Apex, we can now build complex, long-running processes on the platform. This feature is very useful for time to time data cleansing, archiving or data quality improvement operations.
* To use this functionality, you need to implement the Database.Batchable interface.
* 'Database' is a class and 'Batchable' is the interface inside the class.
* This interface demands for three methods to be implemented:
   1. Start()
   2. execute()
   3. finish()
***********
1. Start() Method:
* Start() method is called at the beginning of a batch Apex job. 
* Use this method to collect the records (of objects) to be passed to the "execute" method for processing. 
* The start() method determines the set of records that will be processed by the executeBatch method. We would need to construct a SOQL query and return a QueryLocator object.
return Database.getQueryLocator( 'SELECT Name, MailingAddress FROM Contact');
*QueryLocator can retrieve up to 50 million records at a time. 
*Instead of QueryLocator, we can use 'Iterable' which can process up to 50 thousand records.
* The Apex engine automatically breaks the massive numbers of records we selected into smaller batches and repeatedly calls the "execute" method until all records are processed.
* Start() and finish() methods executes only one time. 
* But execute() method execute many times based on number of batches.


2. execute() Method:
*  It will fetch the records from the start method.
* We can perform all the DML operations here on bulk volumes of data.

3. finish() Method:
* All the post processing operations like sending emails will be done here. 
 *************
Database.BatchableContext:
* It is the interface which holds the run-time information.
**************
Program to give 20% discount on all the books

//To provide 20% discount for all the books
/*BatchApexProcessing b = new BatchApexProcessing();
  Id jobid = Database.executeBatch(b,3);*/
  //Note: If there are any triggers for the object which we are using for the batchApexProcessing, it won't work
//For the below class we are using list, so it can accept upto 50000 records
//Database is the class name and Batchable is the interface name which is inside database class
//To access interface Database.Batchable we have to use
/*
global class BatchApexProcessing implements Database.Batchable<Book__c> {
    global Iterable<Book__c> start(Database.BatchableContext bc){
        List <Book__c> bl = new List <Book__c>();
        bl = [select Id,Name,Author__c,Price__c from Book__c];
        return bl;
    }
    global void execute(Database.BatchableContext bc, LIST<Book__c> bl) {
        for(Book__c b:bl) {
            b.Price__c *= 0.80;
        }      
        update bl;
    }
    global void finish(Database.BatchableContext bc) {
    }
}
*/

//    ********    Using Query Locater    ****************

//For the below class we are using Query Locater, so it can accept upto 50 million records
global class BatchApexProcessing implements Database.Batchable<sObject>,Database.stateful { 
    //database.stateful is used to make data members with new values assigned should reflect
    String myname = 'SRINU';   
    global Database.QueryLocator <Book__c> start(Database.BatchableContext bc) {
        myname = 'SRINIVAS';
        System.Debug('***** My Name in Start *****'+myname);
        List <Book__c> bl = new List <Book__c>();
        String Query = 'select Id,Name,Author__c,Price__c from Book__C';
        return Database.getQueryLocator(Query);
    }
    global void execute(Database.BatchableContext bc, LIST<book__c> bl){
        for(Book__c b:bl) {
            System.Debug('***** My Name in Start *****'+myname);
            b.Price__c *= 0.75;
        }
        update bl;
    }
    global void finish(Database.BatchableContext bc) {
        System.Debug('***** My Name in Start *****'+myname);
    }   
}

 
 ****************************************
http://salesforcesource.blogspot.in/2010/02/utilizing-power-of-batch-apex-and-async.html
http://blogs.developerforce.com/systems-integrator/2009/05/batch-apex-a-powerful-new-functionality-in-summer-09.html
http://blog.ic-2000.com/2011/09/executing-batch-apex-in-sequence/

Web Services

  
* Web Services can convert your applications into Web-applications.
* Web Services are published, found, and used through the Web.
* Web services are typically application programming interfaces (API) or Web APIs that are accessed via Hypertext Transfer Protocol (HTTP) and executed on a remote system hosting the requested services. 
* Web services are application (software) components that run over the internet using XML.
* Web services can be used by other applications. 
How Does it Work?
* The basic Web services platform is XML + HTTP.
*XML provides a language which can be used between different platforms and programming languages and still express complex messages and functions.
*The HTTP protocol is the most used Internet protocol.
*Web services platform elements:
SOAP (Simple Object Access Protocol)
UDDI (Universal Description, Discovery and Integration)
WSDL (Web Services Description Language)

Exposing Apex Methods as Web Services:
 * To expose your Apex methods, use WebService.
* You can expose your Apex methods so that external applications can access your
code and your application.
Note:
* Apex Web services allow an external application to invoke Apex methods through Web services.
   (Nothing but 'call in', external application use our apex methods)
* Apex callouts enable Apex to invoke external web or HTTP services.

WebService Methods:
* Apex class methods can be exposed as custom Force.comWeb services API calls.
* This allows an external application to invoke an Apex web service to perform an action in Salesforce.
*Use the webService keyword to define these methods.
global class MyWebService {
webService static Id makeContact(String lastName, Account a) {
Contact c = new Contact(lastName = 'Weissman', AccountId = a.Id);
insert c;
return c.id;
}
}
*A developer of an external application can integrate with an Apex class containing webService methods by generating a WSDL for the class.
*To generate a WSDL from an Apex class detail page:
1. In the application navigate to Your Name ➤ Setup ➤ Develop ➤ Apex Classes.
2. Click the name of a class that contains webService methods.
3. Click Generate WSDL.
Exposing Data with WebService Methods:
* Invoking a custom webService method always uses System context.
* Apex class methods that are exposed through the API with the webService keyword do not observe object permissions, field-level security, or sharing rules for any records, unless the methods are contained in a class defined using the with sharing keyword.
* Only classes defined using with sharing respect sharing rules for current user.


Friday, 13 July 2012

Relationships

* To avoid redundancy and inconsistency we have to use relationships in sfdc. 
* Redundancy: Repeating records/data in multiple locations is called redundancy.
* Inconsistency: Due to the repetition of the data, if we delete data at one location in other  location the data exists due to that inconsistency will arise.
 In SFDC, we have 5 types of relationships:
1. Self Relationship
2. Look-up Relationship
3. Master Detail Relationship
4. Many to Many Relationship
5. Hierarchical Relationship
 ********
1. Self Relationship:
*It is the relationship between two fields of the same sObject.
* From one field value of the sObject we will derive another field value of the sObject.
* Using Formula data-type we can achieve self relationship. 
2. Look-up Relationship:
* It is the relationship between two sObjects provided one is child which contains link to the parent and another one is parent which contains physical record.
 *If we delete physical record in parent object all the referencing child fields(not entire record) get deleted.
*If the relationship is not mandatory in that case we have to use look-up relationship.
* Up to 25 look-up relationships we can create for single sObject. 
3. Master Detail Relationship:
* It is the relationship between two sObjects provided one is child which contains link to the parent and another one is parent which contains physical record.
*If we delete physical record in parent object all the referencing child records(entire records) also get deleted.
*If the relationship is mandatory in that case we have to use master-detail relationship.
* In master-detail parent object we can create roll-up summary field.
*It is not possible to create master detail relationship if the child object has records in it, if it is empty then only we can create master-detail relationship.
* We can convert master-detail to look-up easily without any restrictions.
* up to 2 master-detail relationships we can create for single sObject.
* a detail record automatically inherits the sharing setting of its parent.
4. Many to Many Relationship:
*If one sObject having two master-detail relationships is called Junction Object.
*For a junction object no need to create tab.
* Junction object can't be on the master side of another master-detail relationship.
*The relationship between two master objects having a common child object i.e. junction object is called many to many relationship.
*many to many relationship form indirectly. 
*We can't create a many to many relationship, If two master-detail relationships on the junction object can't have the same master object.
*To exchange data between two master objects using many to many relationship we have to use related list.
5. Hierarchical Relationship:
* It is the relationship between the users of the organization.
****************
Important points to consider:
* We can convert look-up to master-detail only when all the fields in the look-up relationship populate (fill) with the values.
*If we delete a child sObject and undelete it again then all the master-detail relationships will be converted to look-up relationships.
*It is not possible to delete child sObject if the parent has Roll-up summary field, because parent is using child object information.
*It is not possible to delete parent objects because child sObject using parent sObject information (master-detail parent object).
* If the custom object is on the detail(child) side of the master-detail relationship, it can't be the master side of a different master-detail relationship.
* Standard objects can't be on the detail side of a custom mater-detail relationship.

***************************
Interview Questions:
Q. When to use Look-up and Master-detail relationships?
A.  * If we need to create roll-up summary field and if we need many to many relationship in that case we have to use master-detail relationship.
*For master-detail, relationship is mandatory.
*For look-up, relationship is not mandatory.
*First we have to create look-up then if the master-detail relationship is necessary for that sObject then we have to convert it to master-detail relationship.


Tuesday, 10 July 2012

Governor Limits


Number of SOQL queries: 100

Number of query rows: 50000

Number of SOSL queries: 20

Number of DML statements: 150

Number of DML rows: 10000

Number of script statements: 200000

Maximum heap size: 6000000

Number of callouts: 10
 
Number of Email Invocations: 10
 
Number of fields describes: 100
 
Number of record type describes: 100
 
Number of child relationships describes: 100
 
Number of picklist describes: 100
 
Number of future calls: 10

Sunday, 1 July 2012

Triggers


Triggers:
 A trigger is an apex code that performs validations while performing DML operations. 

* Validations: For filtering the data (To make proper data insert otherwise we will throw an error message through validations). 

* Trigger runs in System Mode by default unless we hand over  to a class decorated as 'with sharing'. 

* By default triggers will run in a batch of 200 records. 200 records for one trigger invocation, even in case of Bulk API.

* SOSL cannot be used in Triggers.

 

*Workflow automates on insert, update.
*Trigger automates on all the DML statements including delete and undelete operations except 
  upsert and merge.
*A workflow can update the fields of the current object.
*Trigger can perform cross object referencing.
*Triggers execute only at run-time.
Bulk Triggers:
*All triggers are bulk triggers by default and can process multiple records at a time.
*Triggers can handle both single record updates and bulk operations.
1.Data import 2.Force.com Bulk API calls 3.Mass Actions 4.Recursive Apex Methods
*A Trigger can works in two modes
1.) Before: works before executing DML statements. (Before saving into model)
2.) After: Works after executing DML statements. (After saving into model but not commit)
What are the Events in Triggers?
* no before undelete event for Triggers
* we should not use upsert and merge for the triggers
Detail Information for Trigger Events 
DML
Before State (Old)
After State (New)
Insert
No
yes
Update
Yes
Yes
Upsert
Never use in Triggers
Never use in Triggers
Delete
Yes
No
Undelete
No
Yes
Merge
Never use in Triggers
Never use in Triggers

*APEX provides Trigger Context Variables, Which holds run-time information used by the trigger.

Trigger Context Variables which generates Boolean values:
Trigger.isBefore
Returns ‘T’ if the triggers is executing in before mode
Trigger.isAfter
Returns ‘T’ if the triggers is executing in after mode
Trigger.isInsert
Returns ‘T’ if the DML operation is in insert mode
Trigger.isUpdate
Returns ‘T’ if the DML operation is in update mode
Trigger.isDelete
Returns ‘T’ if the DML operation is in delete mode
Trigger.isUndelete
Returns ‘T’ if the DML operation is in undelete mode
‘is’ before name represents Boolean types i.e. either ‘T’ or ‘F’

 Trigger Context Variables which works for collection of records:
Trigger.new
Gives collection of records that represents the new state of sObject.
Trigger.old
Gives collection of records that represents the old state of sObject.
Trigger.newMap
A map of Id’s to the new version of sObject records.
Trigger.OldMap
A map of Id’s to the old version of sObject records.
Trigger.Size
Total number of records in a trigger invocation i.e. for both old & new.
Note:
new – Available for insert, update and undelete.
Old - Available for update and delete.
newMap – Available for before update, after insert & after update.


Syntax:
trigger <name> on <sObject name> (<events>) {
}

Examples:
--------------------------

trigger FirstInsert on Student__c (before insert) {
    List<Student__c> s_list = Trigger.new;
    for(Student__c s : s_list) {
        if(s.Name__c == 'Srinu') {
            s.addError('He is not a right candidate.');
        }
    }    
}
trigger FirstUpdate on Student__c (before update) {
    List <Student__c> s_list = Trigger.new;
    for(Student__c s: s_list) {
        if(s.Name__c == 'Vasu') {
            s.addError('He is Good');
        }
    }
}
 trigger Multiple on Student__c (before insert,before update) {
    if(Trigger.isinsert) {//if is is inserting
        List<Student__c> s_list = Trigger.new;
        for(Student__c s:s_list) {
            if(s.Name__c == 'Srinu') {
                s.addError('This is Srinu');
            }
        }
    }    
    if(Trigger.isupdate) {//if it is updating
        List<Student__c> s_list = Trigger.new;
        for(Student__c s:s_list) {
            if(s.Name__c == 'Vasu') {
                s.addError('This is Vasu');
            }
        }  
    }
}
/*
If the same events occur in same block of code(i.e same trigger) then which has recently 
created that trigger will get fire

If same events occur in different triggers then which trigger is the oldest created 
date and time that trigger will get fire 

If there are multiple events in one block of code and diff number of events in another block 
of code but the error conditions are same then recently created trigger error msg only fire
*/ 
 
Triggers and Order of Execution:

*When we save a record with insert/update statement, salesforce performs the following event in order:

Note: Before Salesforce executes these events on the server browser runs the JavaScript validations.

1. Loads the original record form database/ initializes for an insert/update statement.
2. Loads new records field values from the request and overwrites the old values.
3. Executes all the before triggers.
4. Run most system validation steps [Required field have not null value].
5. Saves record to database, but does not do commit yet.
6. Executes all after triggers.
7. Executes assignment rules.
8. Executes auto-response rules.
9. Executes workflow rules.
10. If there are workflow field updates, updates record again.
11. If record updated with workflow field values, fires before and after triggers one more time.
12. Executes escalation rules.
13. If record contains roll-up summary field/ is part of cross-object workflow, performs calculations and updates roll-up summary field in parent record then saves.
14. If parent record updated, grand-parent record contains roll-up summary field, perform calculations and updates roll-up summary field in parent record then saves.
15. Executes criteria based sharing evaluation.
16. Commit all the DML operations to the database.
17. Executes post commit logic, such as send email.
Note: During recursive save, sales force skips step (7) – (14).

Interview Questions:

Q. What operations that don't invoke triggers?
A. Triggers only invoked by the DML operations that are initiated/processed by Java Application server.
 *Examples that operations don't invoke by the triggers:
  1. Cascading delete (Bulk delete).
  2. Cascading updates of child records.
  3. Mass Campaign status changes.
4. Mass division transfers.
5. Mass address updates.
6. Mass approval request transfers.
7. Mass email actions.
8. Modifying custom field data types.
9. Renaming or replacing pick-lists.
10. Managing price books.
11. Changing a user's default division with the transfer division option checked.
12. Changes to the following objects:
     i. Brand Template 
     ii. MassEmail
     iii. Template Folder
13. Update account triggers don't fire before or after a business account record type is changed to person account (or a person account record type is changed to business account.)
Note: 
    Inserts, updates, and deletes on person accounts fire account triggers, not contact triggers.
    Before triggers associated with the following operations are only fired during lead conversion if validation and triggers for lead conversion are enabled in the organization:
14. insert of accounts, contacts, and opportunities.
15. update of accounts and contacts.

Q. Fields that can not be updated by triggers?
A. 1. Task.isclosed 2. Opportunity.amount* 3. Case.isclosed 4. Opportunity.iswon
     5. Solution.isReviewed 6. Contact.activatedDate 7. Opportunity.isclosed
     Note: Above field values set during save operation.
 Q. How to avoid recursive triggers?
 A. Using static Boolean variable we can control recursive triggers.
 Q. Handling Governor limits through triggers?
Scenarios  
* Whenever Opportunity stagename fieldset to 'Closed one', a new record has created in patient object
* Try to access info. form sObj for which don't have permissions for user using trigger

Saturday, 26 May 2012

To perform arithmetic operations (VF)


<apex:page sidebar="false" controller="arthematic">
<!-- We should create form for inserting data into the text fields-->
<apex:form >
<!-- value atrribure in inputtext is used to set and get the values i.e date enterd in inputbox to controller & controller to vf page-->
<b>Enter value1:</b>&nbsp;&nbsp;<apex:inputText value="{!num1}"/><br/><br/>
<b>Enter value2:</b>&nbsp;&nbsp;<apex:inputText value="{!num2}"/><br/><br/>
<!--commandButton is used to create the button-->
<apex:commandButton value="Sum"/>&nbsp;
<!-- outputText to show the output-->
<apex:outputText value="{!sum}"/><br/><br/>
<apex:commandButton value="Diff"/>&nbsp;
<apex:outputText value="{!diff}"/><br/><br/>
<apex:commandButton value="Mul"/>&nbsp;
<apex:outputText value="{!mul}"/><br/><br/>
</apex:form>
</apex:page>




**************
**************

To perform arithmetic operations (APEX)



public class arthematic { 
   
    public Integer num1 { get; set; }

    public Integer num2 { get; set; }
   
    public Integer sum { set; }//If we take inputbox then only we need this, if use outputtext this datamember is not required
   
    public Integer diff { set; }
   
    public Integer mul { set; }
   
    public Integer div { set; }    
  
    public PageReference addition() {
   
        //return null;
        return Page.arthematic;
    }
   
    public arthematic() {
        num1 = num2 = 0;       
    }   
   
   //Addition
    public Integer getSum() {
        //return num1 + num2;       
        return add();
    }   
    public Integer add() {       
        return num1 + num2;
    }
   
    //Subtraction
    public Integer getDiff() {
        //return num1 + num2;       
        return diff();
    }   
    public Integer diff() {       
        return num1 - num2;
    }
   
    //Multiplication
    public Integer getMul() {
        //return num1 + num2;       
        return mul();
    }   
    public Integer mul() {       
        return num1 * num2;
    }
   
    //Division
    public Integer getDiv() {
        //return num1 + num2;       
        return div();
    }   
    public Integer div() {       
        return num1 / num2;
    }/*//<apex:commandButton value="div"/>
//<apex:outputText value="{!div}"/><br></br><br></br>*/ //Getting Exception
   
    }

***********
***********

Labels