How to get Salesforce.com certification exam schedules?

Use the below link to get Salesforce.com certification exam schedules

http://certification.salesforce.com/schedules


Cheers!

How to find from which Email To Case service the case was generated in Salesforce?

From EmailMessage object we can find from which Email to Case's Email Address, the case is generated. We can also write a trigger on EmailMessage object to update this value on the case record for reference.

On Demand Email to Cases in my Organization:



Sample Query:

SELECT ToAddress FROM EmailMessage WHERE Incoming = True

ToAddress is used to refer the Email Address in Email To Case and Incoming refers that it is a incoming email to our organization.


How to create a report for Cases from email to case in Salesforce?

To create a report for Cases from email to case in Salesforce, create a report with Cases with Emails report type.


Cheers!!!

How to restrict email domain or email addresses in On Demand Email to Case in Salesforce?

Accept Email From is used to restrict email domain in On Demand Email to Case in Salesforce.


Cheers!!!

How to enable Email Notification check box in case?

To enable Email Notification Check box by default, go to the Case object page layout, click edit, select "Layout Properties" and check "Select by Default" check box in "Email Notification Check box".


How to enable Lead Assignment Checkbox by default?

To enable Lead Assignment Check box by default, go to the Lead object page layout, click edit, select "Layout Properties" and check "Select by Default" check box in "Lead Assignment Check box".



Cheers!!!

How to enable Case Assignment Checkbox by default?

To enable Case Assignment Check box by default, go to the Case object page layout, click edit, select "Layout Properties" and check "Select by Default" check box in "Case Assignment Check box".


How to get selected records from list view in Salesforce?

Visualforce page:

<apex:page standardController="Member__c" extensions="MemberExt" recordSetVar="Member">
    <apex:pageBlock >
        <apex:pageBlockTable value="{!memList}" var="M">
            <apex:column value="{!M.Name}"/>
            <apex:column value="{!M.Age__c}"/>
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:page>

Apex Controller:

public class MemberExt {
    public List<Member__c> memList {get;set;}
    private ApexPages.StandardSetController standardController;
    private Set<Id> memIds = new Set<Id>();

    public MemberExt(ApexPages.StandardSetController standardController){
        this.standardController = standardController;
        memList = new List<Member__c>();
        for (Member__c mem : (List<Member__c>)standardController.getSelected()){ 
            memIds.add(mem.Id);
        }
        memList = [SELECT Name, Age__c FROM Member__c WHERE ID IN: memIds];
    }
}

Custom Button:


Output:



Validation Error: value is not valid error in Salesforce

This error may be due to assigning Set data type variable to <apex:selectOptions/>.

The workaround for this is, assign the Set data type values to List data type variable and assign it to the <apex:selectOptions/>.

Sample Controller:


Set<SelectOption> optionsSet = new Set<SelectOption>();
List<SelectOption> optionsList = new List<SelectOption>();


for(){
        optionsSet.add(........, '...........');
}
optionsList.addAll(optionsSet);

Sample VF Page:

<apex:SelectList>
        <apex:selectOptions values="{!optionsList}"/>
</apex:SelectList>

Cheers!!!

Happy Coding!!!

How to remove last character from a String in Apex?

Sample Code:

String str = 'Approved/Rejected/';
str = str.removeEnd('/');
system.debug('Value is ' + str);

Output:




Cheers!!!

How assign assignment rule to Lead using apex?

Sample Code:

Lead led = new Lead();

Database.DMLOptions dmo = new Database.DMLOptions();
dmo.assignmentRuleHeader.useDefaultRule = true;
led.setOptions(dmo);

insert led;

this is applicable even when you update the Lead.

How assign assignment rule to Case using apex?

Sample Code:

Case cas = new Case();

Database.DMLOptions dmo = new Database.DMLOptions();
dmo.assignmentRuleHeader.useDefaultRule = true;
cas.setOptions(dmo);

insert cas;

this is applicable even when you update the case.

How to get recordTypeId using record type name?

Sample Code:

        String strObject = 'Account';
        String rtName = 'Marketing';

        Schema.DescribeSObjectResult d = getDescribSObject(strObject);        
        Map<String,Schema.RecordTypeInfo> rtMapByName = d.getRecordTypeInfosByName();
        Schema.RecordTypeInfo rtByName = rtMapByName.get(rtName);
        Id recTypeId = rtByName.getRecordTypeId();


        public static Schema.DescribeSObjectResult getDescribSObject(String strObject) {
            Schema.DescribeSObjectResult d;
            if(strObject.equals('Account')) {
                        d = Schema.SObjectType.Account;
                }
        }

(Or)

Id devRecordTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('Advisors').getRecordTypeId();

Cheers!!!

How to get default value in a picklist in Salesforce?

When we insert a record using Apex, the default values of picklist fields will not be populated until DML operation is done on the record. It will be empty/blank. So, make sure that we use the below sample code for populating default values of picklist fields. It doesn't count against SOQL limits, since we are getting it using schema description.

Sample Code:

String defaultVal;
Schema.DescribeFieldResult F = Account.Active__c.getDescribe();
List <Schema.PicklistEntry> pickVals = F.getPicklistValues();        
for (Schema.PicklistEntry pv: pickVals) {
    if (pv.isDefaultValue()) {
        defaultVal = pv.getValue();
    }    
}
system.debug('Default value is' + defaultVal);


Outputs:

Cheers!!!

Trigger to find total Opportunity amount in Account

Sample Trigger:

trigger Opportunity_AIUD on Opportunity (after insert, after update, after delete) {
    Map<Id, List<Opportunity>> acctIdOpptyListMap = new Map<Id, List<Opportunity>>();
    Set<Id> acctIds = new Set<Id>();
    List<Opportunity> opptyList = new List<Opportunity>();
    if(trigger.isUpdate || trigger.isInsert){
        for(Opportunity oppty : trigger.New){
            if(oppty.AccountId != null){
                acctIds.add(oppty.AccountId);
            }
        }    
    }
    if(trigger.isDelete){
        for(Opportunity oppty : trigger.old){
            if(oppty.AccountId != null){
                acctIds.add(oppty.AccountId);
            }
        }    
    }
    if(acctIds.size() > 0){
        opptyList = [SELECT Amount, AccountId FROM Opportunity WHERE AccountId IN : acctIds];
        for(Opportunity oppty : opptyList){
            if(!acctIdOpptyListMap.containsKey(oppty.AccountId)){
                acctIdOpptyListMap.put(oppty.AccountId, new List<Opportunity>());
            }
            acctIdOpptyListMap.get(oppty.AccountId).add(oppty); 
        }   
        List<Account> acctList = new List<Account>();
        acctList = [SELECT Total_Opportunity_Amount__c FROM Account WHERE Id IN: acctIds];
        for(Account acct : acctList){
            List<Opportunity> tempOpptyList = new List<Opportunity>();
            tempOpptyList = acctIdOpptyListMap.get(acct.Id);
            Double totalOpptyAmount = 0;
            for(Opportunity oppty : tempOpptyList){
                if(oppty.Amount != null){
                    totalOpptyAmount += oppty.Amount;
                }
            }
            acct.Total_Opportunity_Amount__c = totalOpptyAmount;
        }
        update acctList;
    }
}

Quote to Cash

Quote shows us the proposed prices for products and services.

Quote-to-Cash is a process which has the below steps
  • Pricing
  • Quote creation for a prospect or customer, and negotiation
  • Contract and order management
  • Invoicing
  • Payment receipt
These steps are followed from quote creation to revenue generation.

Cheers!!!

Sample JAVA program to insert record using REST API

Sample Program:


package packageForREST;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;

import org.json.JSONException;
import org.json.JSONObject;

public class SampleInsert {
/* --------- Login Credentials ---------- */
private static String userName;
private static String password;

private static String OAUTH_ENDPOINT = "/services/oauth2/token";
private static String REST_ENDPOINT = "/services/data";

String baseUri;

Header oauthHeader;

Header prettyPrintHeader = new BasicHeader("X-PrettyPrint", "1");

/* Id of inserted Employee */
private static String employeeId;

private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

/* Main Method */
public static void main(String[] args) {
new SampleInsert();
}

/* Constructor */
public SampleInsert() {
getLoginCredentials();
this.oauth2Login();
this.insertEmployee();
}

/* Authentication using oauth2 */
public HttpResponse oauth2Login() {
System.out.println("Logging in... Kindly Wait...");
OAuth2Response oauth2Response = null;
HttpResponse response = null;
UserCredentials userCredentials = new UserCredentials();
String loginHostUri = "https://" + 
userCredentials.loginInstanceDomain + OAUTH_ENDPOINT;

try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(loginHostUri);
StringBuffer requestBodyText = new StringBuffer("grant_type=password");
requestBodyText.append("&username=");
requestBodyText.append(userCredentials.userName);
requestBodyText.append("&password=");
requestBodyText.append(userCredentials.password);
requestBodyText.append("&client_id=");
requestBodyText.append(userCredentials.consumerKey);
requestBodyText.append("&client_secret=");
requestBodyText.append(userCredentials.consumerSecret);
StringEntity requestBody = new StringEntity(requestBodyText.toString());
requestBody.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(requestBody);
httpPost.addHeader(prettyPrintHeader);

response = httpClient.execute(httpPost);
 
if (  response.getStatusLine().getStatusCode() == 200 ) {
String response_string = EntityUtils.toString(response.getEntity());
try {
JSONObject json = new JSONObject(response_string);
oauth2Response = new OAuth2Response(json);
System.out.println("JSON returned by response: +\n" + json.toString(1));
} catch (JSONException je) {
je.printStackTrace();
}  
baseUri = oauth2Response.instance_url + REST_ENDPOINT + "/v" + userCredentials.apiVersion +".0";
oauthHeader = new BasicHeader("Authorization", "OAuth " + oauth2Response.access_token);
System.out.println("\nSuccessfully logged in to instance: " + baseUri);
} else {
System.out.println("An error has occured. Http status: " + response.getStatusLine().getStatusCode());
System.out.println(getBody(response.getEntity().getContent()));
System.exit(-1);
}
} catch (UnsupportedEncodingException uee) {
uee.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (NullPointerException npe) {
npe.printStackTrace();
}
return response;
}

/* Method to insert Employee */
public void insertEmployee() {
String uri = baseUri + "/sobjects/Employee__c/";
try {
String name;
String age;
JSONObject employee = new JSONObject();
name = getUserInput("Enter the name: ");
age = getUserInput("Enter the age: ");
employee.put("Employee_Name__c", name);
employee.put("Age__c", age);
System.out.println("\nEmployee record to be inserted:\n" + employee.toString(1));

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(uri);
httpPost.addHeader(oauthHeader);
httpPost.addHeader(prettyPrintHeader);
StringEntity body = new StringEntity(employee.toString(1));
body.setContentType("application/json");
httpPost.setEntity(body);

HttpResponse response = httpClient.execute(httpPost);

int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 201) {
String response_string = EntityUtils.toString(response.getEntity());
JSONObject json = new JSONObject(response_string);
employeeId = json.getString("id");
System.out.println("New Employee id from response: " + employeeId);      
} else {
System.out.println("Insertion unsuccessful. Status code returned is " + statusCode);
}
} catch (JSONException e) {
System.out.println("Issue creating JSON or processing results");
e.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (NullPointerException npe) {
npe.printStackTrace();
}
}

static class OAuth2Response {
String id;
String issued_at;
String instance_url;
String signature;
String access_token;

public OAuth2Response() {
}
public OAuth2Response(JSONObject json) {
try {
id =json.getString("id");
issued_at = json.getString("issued_at");
instance_url = json.getString("instance_url");
signature = json.getString("signature");
access_token = json.getString("access_token");

} catch (JSONException e) {
e.printStackTrace();
}
}
}

/* Class to hold user credentials */
class UserCredentials {
String loginInstanceDomain = "na1.salesforce.com";
String apiVersion = "22";
String userName = SampleInsert.userName;
String password = SampleInsert.password;
String consumerKey = "3MVG99OxTyEMCQ3hvhY_jCIAcS5.TwlxLkUPavrSugAtRMxYIW5Woi.ujyRUbQRWqDPG_JLRVWVcKHqTIp9EL";
String consumerSecret = "4820902082354189113";
String grantType = "password";
}

private String getBody(InputStream inputStream) {
String result = "";
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(inputStream)
);
String inputLine;
while ( (inputLine = in.readLine() ) != null ) {
result += inputLine;
result += "\n";
}
in.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return result;
}

/* Method to get user input */
private String getUserInput(String prompt) {
String result = "";
try {
System.out.print(prompt);
result = reader.readLine();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return result;
}

/* Method to get login credentials */
private void getLoginCredentials() {
userName = getUserInput("Enter the username: ");
password = getUserInput("Enter the password: ");
}

}

Sample JAVA program to Query records using REST API

Sample Program:


package packageForREST;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

public class QueryUsingREST {
/* --------- Login Credentials ---------- */
private static String userName;
private static String password;

private static String OAUTH_ENDPOINT = "/services/oauth2/token";
private static String REST_ENDPOINT = "/services/data";
String queryStr;
String baseUri;
Header oauthHeader;
Header prettyPrintHeader = new BasicHeader("X-PrettyPrint", "1");

private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

public static void main(String[] args) {
new QueryUsingREST();
}

/* Constructor */
public QueryUsingREST() {
getLoginCredentials();
this.oauth2Login();
this.retrieveRecords();
}

/* Authentication using oauth2 */
public HttpResponse oauth2Login() {
System.out.println("Logging in... Kindly Wait...");
OAuth2Response oauth2Response = null;
HttpResponse response = null;
UserCredentials userCredentials = new UserCredentials();
String loginHostUri = "https://" + 
userCredentials.loginInstanceDomain + OAUTH_ENDPOINT;

try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(loginHostUri);
StringBuffer requestBodyText = new StringBuffer("grant_type=password");
requestBodyText.append("&username=");
requestBodyText.append(userCredentials.userName);
requestBodyText.append("&password=");
requestBodyText.append(userCredentials.password);
requestBodyText.append("&client_id=");
requestBodyText.append(userCredentials.consumerKey);
requestBodyText.append("&client_secret=");
requestBodyText.append(userCredentials.consumerSecret);
StringEntity requestBody = new StringEntity(requestBodyText.toString());
requestBody.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(requestBody);
httpPost.addHeader(prettyPrintHeader);

response = httpClient.execute(httpPost);
 
if (  response.getStatusLine().getStatusCode() == 200 ) {
String response_string = EntityUtils.toString(response.getEntity());
try {
JSONObject json = new JSONObject(response_string);
oauth2Response = new OAuth2Response(json);
System.out.println("JSON returned by response: +\n" + json.toString(1));
} catch (JSONException je) {
je.printStackTrace();
}  
baseUri = oauth2Response.instance_url + REST_ENDPOINT + "/v" + userCredentials.apiVersion +".0";
oauthHeader = new BasicHeader("Authorization", "OAuth " + oauth2Response.access_token);
System.out.println("\nSuccessfully logged in to instance: " + baseUri);
} else {
System.out.println("An error has occured. Http status: " + response.getStatusLine().getStatusCode());
System.out.println(getBody(response.getEntity().getContent()));
System.exit(-1);
}
} catch (UnsupportedEncodingException uee) {
uee.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (NullPointerException npe) {
npe.printStackTrace();
}
return response;
}

/* Method to retrieve records */
public void retrieveRecords() {
System.out.println("\nQuerying Example\n");
try {
queryStr = getUserInput("Enter the query: ");
System.out.println("\nThe query is " + queryStr);
HttpClient httpClient = new DefaultHttpClient();
String uri = baseUri + queryStr;
System.out.println("\nQuery URL: " + uri + "\n");
HttpGet httpGet = new HttpGet(uri);
httpGet.addHeader(oauthHeader);
httpGet.addHeader(prettyPrintHeader);

HttpResponse response = httpClient.execute(httpGet);

int statusCode = response.getStatusLine().getStatusCode();
System.out.println("\nStatus code returned is " + statusCode + "\n\n");
if (statusCode == 200) {
String response_string = EntityUtils.toString(response.getEntity());
try {
JSONObject json = new JSONObject(response_string);
System.out.println("Id\t\t\t\tName");
for(Integer i = 0; i < json.length() - 1; i++){
System.out.print(json.getJSONArray("records").getJSONObject(i).getString("Id") + "\t\t");
System.out.print(json.getJSONArray("records").getJSONObject(i).getString("Name") + "\n");
}
System.out.println("\nEnd of the execution");
} catch (JSONException je) {
je.printStackTrace();
}          
} else {
System.out.println("Query was unsuccessful. Status code returned is " + statusCode);
}
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (NullPointerException npe) {
npe.printStackTrace();
}
}

/* Class to hold values returned by the OAuth request. */
static class OAuth2Response {
String id;
String issued_at;
String instance_url;
String signature;
String access_token;

public OAuth2Response() {
}
public OAuth2Response(JSONObject json) {
try {
id =json.getString("id");
issued_at = json.getString("issued_at");
instance_url = json.getString("instance_url");
signature = json.getString("signature");
access_token = json.getString("access_token");

} catch (JSONException e) {
e.printStackTrace();
}
}
}

/* Class to store user login credentials */
class UserCredentials {
String loginInstanceDomain = "na1.salesforce.com";
String apiVersion = "22";
String userName = QueryUsingREST.userName;
String password = QueryUsingREST.password;
String consumerKey = "3MVG99OxTyEMCQ3hvhY_jCIAcS5.TwlxLkUPavrSugAtRMxYIW5Woi.ujyRUbQRWqDPG_JLRVWVcKHqTIp9EL";
String consumerSecret = "4820902082354189113";
String grantType = "password";
}

private String getBody(InputStream inputStream) {
String result = "";
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(inputStream)
);
String inputLine;
while ( (inputLine = in.readLine() ) != null ) {
result += inputLine;
result += "\n";
}
in.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return result;
}

/* Method to get login credentials */
private void getLoginCredentials() {
userName = getUserInput("Enter the username: ");
password = getUserInput("Enter the password: ");
}

/* Method to get user input */
private String getUserInput(String prompt) {
String result = "";
try {
System.out.print(prompt);
result = reader.readLine();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return result;
}
}

Sample Input for Query:
/query?q=SELECT+id+,+name+FROM+Account+limit+2

Static keyword in programming

Static variable is a variable that has been allocated statically. Static variable lifetime extends across the entire run of the program.

Things to remember while using Static keyword
  1. Static methods can be called only with the class name not with the class object instance.
  2. Static variable values lifetime is until the end of the execution. 
Cheers!!!

Difference between SOAP and REST APIs

SOAP API
REST API
Simple Object Access Protocol
Representational State Transfer
It is based on standard XML format
It is based on URI
It works with WSDL
It works with GET, POST, PUT, DELETE
Works over with HTTP, HTTPS, SMTP, XMPP
Works over with HTTP and HTTPS

Cheers!!!

Interaction Log layout in Salesforce

Use the interaction log to write notes in call logs while using a Salesforce console application. A call log is an activity record that automatically generates when you use a SoftPhone; it tracks the phone number, caller, date, time, and duration of the call. You can view call logs in the Activity History related list of any record associated with the call.

Cheers!

Chat settings in Salesforce

Chat window:


To enable or disable chat settings in Salesforce, follow the below steps

1. Go to Customize --> Chatter --> Chat Settings.


2. Enable or disable to view or hide.


Calendar in Salesforce


Visualforce Components in Salesforce

Similar to the way functions work in a programming language, custom Visualforce components allow you to encapsulate common design patterns and then reuse those patterns in one or more Visualforce pages.

1. Go to Setup --> Build --> Develop -->  Components.


2. Click "New" button.


Sample Visualforce component



Code Used inside the Visualforce Component:

<apex:component >
    <apex:attribute name="height" required="true" type="integer" description="Height for the table"/>
    
    <table height="{!height}" border="2">
        <tr><td><h1>Infallible Techie</h1></td></tr>
    </table>
</apex:component>

3. Create a Visualforce page to use the Visualforce Component.

Visualforce page:

<apex:page>
    <c:CompanyTitle height="30"></c:CompanyTitle>
</apex:page>

Output:




Cheers!!!

Simple action status in Salesforce

Sample Code:

<apex:page controller="Sample">
<apex:actionstatus id="counterStatus">
    <apex:facet name="start">
        <div class="waitingSearchDiv" id="el_loading" style="background-color: #fbfbfb; height:100%;opacity:0.65;width:100%;">
            <div class="waitingHolder" style="top: 100px; width: 91px;">
            <img class="waitingImage" src="/img/loading.gif" title="Please Wait..." />
            <span class="waitingDescription">Loading...</span>
            </div>
        </div>
    </apex:facet>
</apex:actionstatus>
<apex:form id="frm">
    <apex:commandButton value="Test" status="counterStatus" reRender="frm"/>
</apex:form>
</apex:page>

Output:



How to avoid CPU time exceeded exception in Salesforce?

1. Avoid nested loop. Make use of Map data type instead of nested loop.

2. Make use of future methods.

3. Try to use Aggregate SOQL.

Check the below link for more information

https://help.salesforce.com/articleView?id=000232681&language=en_US&type=1

Cheers!

How to debug workflow rules in Salesforce?

1. Go to Setup --> Monitor --> Log --> Debug logs.

2. Click "New" button and add your name to get the debug logs.

3. Create or update the record to meet the workflow criteria.

4. Open the log and view its workflow log.


(or)

Go to developer console and open the log.