Running batch Apex Example

Batch Apex Example:




Here I am providing simple example to understnd how to run batch apex programatically. Below is the simple apex class which implements Database.Batchable interface.

global class batchAccountUpdate implements Database.Batchable<sObject> {
global Database.QueryLocator start(Database.BatchableContext BC) {
String query = ‘SELECT Id,Name FROM Account’;
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<Account> scope) {
for(Account a : scope)
{
a.Name = a.Name + ‘******’;
}
update scope;
}
global void finish(Database.BatchableContext BC) {
}
}

Now, I want to run this batch apex class. To run the apex job, you have to call “database.executeBatch” method. open developer console and execute belwo line of code.

batchAccountUpdate bc = new batchAccountUpdate();
database.executeBatch(bc);

After executing above code, related job will run. To see/monitor Batch apex jobs go to setup->jobs->Apex Jobs. here you will see status of Batch apex jobs like submitted date, Job Type, Status, Total Batches, Bathes processed, failures, submitted by, Completion date, Apex Class & Apex Job ID. And also you can abort the jobs which are in proccessing.




If you want to run apex job after click on button on visualforce page, then create a page & impliment above login in controller & call that method after clciking on button in a visualforce page.





Database.executeBatch-To Run apex job

Database.executeBatch: How to invoke batch apex job?/How to execute apex job programatically?




There are two Database class methods avilable to execute/invoke batch apex job. Those are:

1. executeBatch(batchClassObject) : This method submits a batch apex job for execution corresponding to the specified class.
2. executeBatch(batchClassObject, scope) : Submits a batch Apex job for execution using the the specified class and scope.Here scope specifies Number of records to be passed into the execute method for batch processing.




Above two methods are static methods of database class. The class name which we are passing  to the executeBatch () method should be object of the class which has implemented from Database.batchable interface.

Order of execution of batch apex job:
1. Creates an object for the class which has implemented by using Database.Batchable interface.
2. Pass the object which you have created in first step as a parameter to the Database.executeBatch method. When this method calls it will add apex job to the queue.
3. Once resource is available in the queue automatically start() method will invoked & it will collect all the records.
4. The records that are fetched from the start method are divided into small group based on the size we mentioned in the executeBatch method & execute the operation specified in execute method.
If you don’t specify size of the batch in executeBatch method(), 200 is the default size.

 




What is Batch Apex?

Batch Apex in salesforce




– What is Batch Apex? It allows you to define a job that can be divided into manageable chunks, where each chunk can be proceed separately.
– For example, if you want to make an field update of all records in any object which is having more number of records, then governor limits restricts us to process that operation. Because, In a single transaction we can only process 10,000 records.
– In batch apex, it will fetch all records which you want perform the field update and divide them into list of 200 records & every 200 records operation is performed separately.

What is Batchable Interface? To use Batch Apex, you must implement “Database.Batchable”. This interface has three methods. those are:
1. Start
2. execute
3. Finish

Start method is automatically called at the beginning of the apex job. This method will collect record or objects on which the operation should be performed. These record are divided into subtasks & passes those to execute method.

Execute Method performs operation which we want to perform on the records fetched from start method.

Finish method executes after all batches are processed. Use this method to send confirmation email notifications.

To understand this see the below class. Belwo program updates Account name in the account object with “*****” aftet the account name.

global class batchAccountUpdate implements Database.Batchable<sObject> {
global Database.QueryLocator start(Database.BatchableContext BC) {
String query = ‘SELECT Id,Name FROM Account’;
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<Account> scope) {
for(Account a : scope)
{
a.Name = a.Name + ‘******’;
}
update scope;
}
global void finish(Database.BatchableContext BC) {
}
}





Inbound Email Service in Salesforce

What is Inbound Email Service?




Inbound Email Service : When we get email from external system to salesforce, the apex class will process the emails, attachements & perform requested operation. To perform this you have to write apex class by implement the “Messaging.InboundEmailHandler” interface. And also there are some pre defined classes under Messaging name sapce to implement this. Below are the pre defined classes.

1. InboundEmail
2. InboundEmail.Header
3. InboundEmail.BinaryAttachment
4. InboundEmail.TextAttachment
5. InboundEmailResult
6. InboundEnvelope




See the below example program to handle the inbound email. Below example program creates a new account when salesforce org recieves an email.

Apex Class:

global class CreateAccountEmailServiceExample implements Messaging.InboundEmailHandler {
global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email,Messaging.InboundEnvelope envelop){
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
String accname = email.fromName;
String accdes = email.plainTextBody;
String accIndus = email.Subject;
Account ac = new Account(Name = accname, description = accdes, Industry = accIndus);
insert ac;
return null;
}
}

What is Email Sevice? Email Sevice is an automated process that use apex classes to process the contents, headers, attachements of Inbound email. We can associate each email service with one or more salesforce generated email addresses to which users can send messages for processing.

How to configure Email Service? Below are the steps to create email service.

1. Setup -> Develop -> Email Services Click on New Email Service button
2. Fill the required details like Email Service Name, APexClass and check Active check box & click on SaveandNewEmailAddress. See the below image for reference.

Email Service

3. Again fill required details and click on save. You will see one auto generated email address. Copy this & send an email to this. Salesforce will receive that email and create a new account based on the logic of the above code.





sending email with attached document by using Apex

Sending email – sending document as attachment




What is Document? Document object in salesforce represents afile that user has uploaded. Now this example helps you to understand sending documents as attachment.

How to create a document?

1. Login to Salesforce -> click all tabs (+) and click on Documents tab.

2. Click on new button & enter required fields and upload document and save. See below image for reference.

Sending Email

To send document as attachment write a query to get the id of the document and pass this id in “setDocumentAttachments(ID[])” this method. This is the method in SingleEmailMessage class.

Query:
Document doc = [SELECT Id,Name FROM Document WHERE Name = ‘DocName’];

See below example to send document as attachment.

ApexClass:

public class SendingDocasattachmentExample{
public pagereference sendDocAttach()
{
Document doc = [SELECT Id,Name FROM Document WHERE Name = ‘Sample’];
Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage();
semail.setDocumentAttachments(new ID[]{doc.id});
semail.setSubject(‘Sending Document as attachemnt example’);
String[] sendTo = new String[]{‘XXXXXXXX@gmail.com’};
semail.setToAddresses(sendTo);
semail.setPlainTextBody(‘Please find the attached document details’);
Messaging.sendEmail(new Messaging.SingleEmailMessage[]{semail});
return null;
}
}

“Documentattachment” ApexPage:

<apex:page controller="SendingDocasattachmentExample">
<apex:form >
<apex:commandButton value="Send Doc" action="{!sendDocAttach}"/>
</apex:form>  
</apex:page>

Click on Send Doc button, you will get email to address you have mentioned in above apex class.





Sending Email attachment – EmailFileAttachment

Sending Email attachment by using Apex




How to send email attachment by using Apex? By using EmailFileAttachment class we can send attachment. We can use this SingleEMailMesSage to send attachments. Below are the methods in EmailFileAttachment class.
– setBody(Blob) : To set the attachment.
– setContentType(String) : To set content type of the attachment.
– setFileName(String) : To set the attachment file name.
– setInline(Boolean) : Used to specify content description.

See the below example to understand EmailFileAttachment:




bookdetails vf page:
I am sending below visualforce page as an attachment.
<apex:page standardController=”Books__c” renderAs=”pdf”>
<apex:pageBlock >
<apex:pageBlockSection columns=”1″>
<apex:outputField Value=”{!Books__c.Name}”/>
<apex:outputField Value=”{!Books__c.Title__c}”/>
<apex:outputField Value=”{!Books__c.price__c}”/>
<apex:outputField Value=”{!Books__c.Publisher__c}”/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:page>

attachmentExample: This controller is having logic to send attachment in an email.

public class attachmentExample{
Books__c book;
public attachmentExample()
{
book = [select id,name from Books__c where Id = :ApexPages.currentPage().getParameters().get(‘id’)];
}
public pagereference sendAttach()
{
Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage();
Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
PageReference pref = page.bookdetails;
pref.getParameters().put(‘id’,(String)book.id);
pref.setRedirect(true);
Blob b = pref.getContent();
attach.setFileName(‘BookDetails.pdf’);
attach.setBody(b);
semail.setSubject(‘Book details’);
String[] sendTo = new String[]{‘XXXXXXXXX@gmail.com’};
semail.setToAddresses(sendTo);
semail.setPlainTextBody(‘Please find the attached book details’);
semail.setFileAttachments(new Messaging.EmailFileAttachment[]{attach});
Messaging.sendEmail(new Messaging.SingleEmailMessage[]{semail});
return null;
}
}




How to test sending email attachment? To test this, create detail button to execute above logic in object & add that button in detail page.




sending emails – SingleEmailMessage

Sending emails by using SingleEmailMessage




Sending emails: By using Single email message we can send emails. SingleEmailMessage class contains methods for sending emails. SingleEmailMessage contains below methods.
1. setBccAddresses(String[])
2. setCcAddresses(String[])
3. setCharset(String)
4. setDocumentAttachments(ID[])
5. setFileAttachments(EmailFileAttachment[])
6. setHtmlBody(String)
7. setInReplyTo(String)
8. setPlainTextBody(String)
9. setOrgWideEmailAddressId(ID)
10. setReferences(String)
11. setSubject(String)
12. setTargetObjectId(ID)
13. setToAddresses(String[])
14. setWhatId(ID)

Example Apex Class: Below class is a simple apex program to understand single email message. I  have created vf page with button. & when we click on that button that calls sending emails method in below class. Try this for sending emails

public class singleEmailExample
{
public PageReference sendingEmail()
{
Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage();
String[] sendingTo = new String[]{‘XXXXXXXXXXXXXX@gmail.com’};
semail.setToAddresses(sendingTo);
String[] sendingToBccAdd = new String[]{‘XXXXXXXXX@gmail.com’};
semail.setBccAddresses(sendingToBccAdd);
String[] sendingTocAdd = new String[]{‘XXXXXXXXXXX@gmail.com’};
semail.setCcAddresses(sendingTocAdd);
semail.setSubject(‘Single Email message Example’);
semail.setPlainTextBody(‘Hello!!!!!!!!!!This is a test email to test single email message program’);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {semail});
return null;
}
}

Apex Page:

<apex:page controller="singleEmailExample">
  <apex:form >
  <apex:commandButton value="SendEmail" action="{!sendingEmail}"/>
  </apex:form>
</apex:page>