Inbound email services in salesforce

Lets see how we can use them and demo an example for same. We can receive a email in salesforce and use the information contained in that email i.e access that information in apex and act accordingly on that information.

Lets define a problem and work on it.
Requirement: Create a account record, record should be automatically created when a user sends an email(email will contain all the fields information)

Step 1: create a global class that can receive that email as below

global class InbEmailHandlerClass implements Messaging.InboundEmailHandler {
 global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
        Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
        String emailBody = EncodingUtil.urldecode(email.plaintextbody,'utf-8');
       string[] emaildata = emailbody.split(',');
       Account cobj = new Account(); emaildata[0];
       cobj.Accountnumber = emaildata[1];
       cobj.Industry = emaildata[2];
       insert cobj;
       result.success = true;
       return result;

Step 2: You need email address to receive the email. Go to set up -> develop -> email services -> new email services.
 In new email services fill following fields
 1. name: any name you wish
 2. apex class: above class that you created
 3. Active: checked
 4.Click save.
 5. On detail email services record related list create new email address.Fill in the accept from email addresses as per your wish.
    This will be your email address to which the emails should be sent.

Step 3. Send an email from your chosen address to your salesforce email address you saved in step 2
      email format: Remember as per our class you should send field values coma separated and in proper order. That is as an example;
      Email body: testaccountname,1234,Banking
Once a email is sent, your account record would be created(If there are no other validations)

passing parameters in action function

We can pass parameters to controller method that is being called using action function. For this we can use attribute "param" in visualforce.

Following is an example to demonstrate the parameter passing using param in action function. Clicking the checkbox calls the controller method using action function, first name and last name are passed to the controller using param attribute.

Visualforce Page

<apex:page controller="passparam">
  <apex:pageblock id="pgblck">
   First name : <apex:inputtext id="fn" value="{!firstname}">
   Last Name :<apex:inputtext id="ln" value="{!lastname}"> 

 Click this to See full name :  <apex:inputcheckbox onclick="calculate('{!$Component.fn}','{!$Component.ln}')">

Full Name:    <apex:outputtext value="{!fullname}"></apex:outputtext> 
<apex:actionfunction action="{!calpercentage}" name="calAF" rerender="pgblck">
<apex:param assignto="{!firstname}" name="param1" value="">
<apex:param assignto="{!lastname}" name="param" value="">
  function calculate(frst,lst){
  var Fname = document.getElementById(frst).value;
 var Lname = document.getElementById(lst).value;
   var res = confirm('Do you want to calculate?');
   if(res == true)
      calAF(Fname,Lname );

Apex Class

Public class passparam{
Public string firstname{get;set;}
Public string lastname{get;set;}
Public string fullname{get;set;}
 Public void calpercentage(){
  fullname = firstname +' '+lastname;

select all checkbox in visualforce using action function

Here is an example that demonstrates select all checkbox column using action function. Though the response is slower, at times we may need to use this depending on requirement.

Visualforce Page ]]> Apex Class

Batch apex scheduling in apex - batch apex job run for every 15 minutes or 30 minutes

We can schedule a batch apex using declarative way/OOTB, for this we need to write the schedule class that calls the batch apex class. Using declarative way we can schedule the class either weekly or monthly basis.

In weekly, we can have it run every day or any selected day of week. For a particular day we can specify a preferred time at which the class run. So, using declarative way we can have a highest frequency of 1 time per day not more than that. That is it does not support to run the class more number of times per day. Say, you want the class to run every 1 hour, or every 30 mins, then you cannot do it using declarative way. To do this, we can use system.schedule method and call the scheduler class. 

System.schedule takes 3 parameters as below :

system.schedule('jobname',timeperiod,scheduler class name)

jobname: you can give any name to your job
timeperiod: specify the time frequency with which the job should run
scheduler class name: scheduler class that calls your batch apex class.

timeperiod should be specified in below format:
Seconds Minutes Hours Day_of_month Month Day_of_week optional_year

For example, to run every 30 mins the expression would be : 0 30 * * * ?

here '*' means every time against the specified parameter, every hour, every day of month, every day of week and '?' means no specific value. Thus, this expression means every 30 minutes. So, the system.schedule('testname',0 30 * * * ?,schedulerclass()); would call the schedulerclass every 30 minutes when the statement executes.

You can visit salesforce documentation to know more on system.schedule parameters.

Lets write a simple batch apex class, its scheduler class and then, execute system.schedule method to run that batch apex every 30 minutes.

Batch Apex Class:
Scheduler class along with method that will Can scheduler class every 30 minutes:
Now, we have to just execute the "SchedulerMethod" once, this will keep on calling the batch apex every 30 minutes. We can use developer console to execute this method. Just execute below statement to call the method: ScheduleBatchApexDemo.SchedulerMethod();

You can monitor the batch apex being called every 30 minutes from: set up--> monitoring jobs

Importing selected salesforce org components in IDE or Eclipse swiftly

IDE/Ecipse is a preferred tool that we all use for coding purpose, when the codes are of short length we prefer UI for coding but when we have very lengthy codes IDE/Eclipse is a best option. It also allows us to search in the entire ORG if any object or field is being referenced in any class, trigger or workflow etc(This is something which is very difficult to do manually from UI in the org).

Many times we require only certain components of the org in IDE/Eclipse, and its only fair to get those components rather then all the components of the org. At times entire org could be so huge that its almost impossible to get the entire org in time. IDE allows us to get the selected components from the org. A faster way to get only selected components is by modifying the package.xml. Here we have to just put the component members (that we wish) in the package.xml file and save it, components will get downloaded very swiftly in this way.

Follow this steps to get only selected components in IDE:

1. Create new project in IDE, fill in all the details (username,password, security token) and click finish.

2. From the "choose initial components" window choose 'none' and click finish, this will instantly create the project.

3. Right click on project and select workoffline

4. Now open the package.xml file, modify its content to include whichever components you wish to download in IDE

With none components selected your package.xml will look like following:

<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="">

Now suppose you wish to include trigger,classes and page members then you need to include those members as below

<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="">

4. Press cntrl+s to save the package.xml file

5. Right click on project and select work online, your new components will now be populated in your project. If it does not populate the components, try to refresh from server, or close the IDE and reopen and then refresh from server.

Difference between Database DML statements and simple DML statements

Article 1** Article 2** Article 3** Article 4** Article 5** Article 6** Article 7** Article 8** Article 9 ** Article 10

Let us see what is the difference between the two types of dml statements that we come across in apex. 
To understand this we will consider dml being applied on collection(List). Let us see 'insert' dml as an example. When we execute the below two statements, how do they differ from each other?

1. Insert accList;

2. Database.insert(accList,false);

**accList is a list of account records.

First let's see simple insert- when we do simple insert on that list it will either insert all of the account records in the list or none will be inserted. That is, there will be either total success or total failure. You cannot have partial success, partial failure in case of simple insert. If any of the record in the list fails due to any validation or any other thing, then none of the records in that list will be inserted. Records will be inserted only if all of the records are good to get inserted(i.e pass all sorts of validations)

Database.insert on the other hand can give you partial success. To get partial success we will have to pass a parameter "opt_allOrNone" as 'false' separated by the list name. If this parameter is set to true then it functions like simple insert. So if the parameter is false, then all the records passing validations will be inserted and others will be restricted.

We can track the errors that are encountered, using saveresult object as shown in the below code snippet,

List<database.saveresult>  accResultList = database.insert(accList,false);
for(database.saveresult res:accResultList){
  database.error e = esr.getErrors()[0];
system.debug('error is *******'+e.getmessage());

Let us summarise on the points discussed above,
Simple Insert
1. Can insert either all the records or no records at all. Partial success is not possible.

1. Partial success is possible in this case.

1. Operates same like simple insert dml i.e no partial success possible.

Data Loader, if you have observed works on the principle of database methods with "opt_allOrNone" flag set as 'false', hence we get partial success even if any of the record fail.

** all of the points discussed above for insert also apply for other DML: update,upsert,delete.
Article 1** Article 2** Article 3** Article 4** Article 5** Article 6** Article 7** Article 8** Article 9 ** Article 10