Wednesday 28 December 2016

SFDC Interview Questions and Answers with examples

SFDC Interview Questions:


What is difference between salesforce.com and force.com
 
The biggest difference between Salesforce.com and Force.com lies in the concept on which both are based.
Force.com is based on the concept of Platform as a Service or commonly known as PAAS  whereas Salesforce.com is based on the concept of Application as a Service.
So, we can say Salesforce.com is an application build by Salesforce on force.com platform and has been made available to people for use at per month per license pricing.
As a rule of thumb: Force.com platform license is three times cheaper than the Salesforce.com license but takes three times of effort and time to build any functionality which is billed in Salesforce.com application.
Force.com is the platform because of which SFDC says sky is the limit for developing any application. Create customize, and integrate enterprise applications as a service and without software. There are numerous examples of the same on AppExchange where people have Built Contract Management, HR systems, Social CRM etc.


What is the difference between sales cloud & service cloud?

"Sales Cloud" refers to the "sales" module in salesforce.com. It includes Leads, Accounts, Contacts, Contracts, Opportunities, Products, Pricebooks, Quotes, and Campaigns (limits apply). It includes features such as Web-to-lead to support online lead capture, with auto-response rules. It is designed to be a start-to-end setup for the entire sales process; you use this to help generate revenue.
"Service Cloud" refers to the "service" (as in "customer service") module in salesforce.com. It includes Accounts, Contacts, Cases, and Solutions. It also encompasses features such as the Public Knowledge Base, Web-to-case, Call Center, and the Self-Service Portal, as well as customer service automation (e.g. escalation rules, assignment rules). It is designed to allow you to support past, current, and future clients' requests for assistance with a product, service, billing, etcetera; you use this to help make people happy.


What are the differences between Roles and Profiles?

Profiles controls users object and field level access permission, without profile user can’t be defined. Profile specifies the apps and tabs that appear when he / she logs in.

Roles control users Record level access permission through role hierarchy and sharing rules.

To remember : Roles control Records.

·         Profile manages the Salesforce.com License, Tabs Settings, Record types, Page layouts, General Settings, Administrator Settings etc.; Role hierarchy does not do any of these things
·         Profile is Mandatory, Role is not

What are Web services?

A Web service is the mechanism by which two applications that run on different platforms, that were written in different languages, and that are geographically remote from each other, can exchange data using the Internet. Web services makes data exchange between two such applications as straightforward as the way that two processes can exchange data on a single computer.

The key difference is the actual data that is sent and received—Web services use XML instead of HTML.

What is Visual Force?

It is powerful framework. With visual force, you can create just about any type of browser-based user interface you can imagine.

The visual force framework includes a tag-based markup language, similar to HTML.

What is SOAP?

A protocol that defines a uniform way of passing XML-encoded data. SOAP Stands for Simple Object Access Protocol.

What is a Time Trigger?

A setting that defines when time-dependent workflow actions should fire.
 
How many types of the relationship fields available in Salesforce?
 
·         Master Detail
Master Detail relationship is the Parent child relationship. In which Master represents Parent and detail represents Child. If Parent is deleted then Child also gets deleted. Rollup summary fields can only be created on Master records which will calculate the SUM, AVG, and MIN of the Child records.
·         Lookup
Look up relationship is something like “has-a” (Containership) relationship.
Where one record has reference to other records. When one record is deleted then there is no impact on other records.
Only 2 M-D relationship per object. Overcome the limit of 2 M-D by creating Lookup and make the lookup field mandatory.
25 lookup relationship per object
·         Many to Many (Junction Object)
Junction objects are used to create many to many relationships between objects. If you take the Recruiting application example, you can see that a Position can be linked to many Candidates, and a Candidate can apply for different Positions. To create this data model you need a third object "Job Application" that links the two?

So you'd create a lookup field for both Position and Candidate object on the "Job Application" object. This will establish many to many relationships between Position and Candidate via the "Job Application" object known as the junction object.
  • Hierarchical
A special lookup relationship available for only the user object. It lets users use a lookup field to associate one user with another that does not directly or indirectly refer to itself. For example, you can create a custom hierarchical relationship field to store each user's direct manager

When are record types used? 

Record Types are used in the following two cases: 
  • To assign the different Page layouts to different users based on their profiles
  • To enable different sets of Standard/Custom Picklist values for two different users using the same page layout.
 
In How many ways we can invoke the Apex class?
  1. Visual force page
  2. Trigger
  3. Web Services
  4. Email Services
Can we create Master Detail relationship on existing records?

No. As discussed above, first we have to create the lookup relationship then populate the value on all existing record and then convert it.
 
What is the Standard salesforce.com execution order?
  1.  Old record loaded from database (or initialized for new inserts)
  2.  New record values overwrite old values
  3.  System Validation Rules
  4.  All Apex “before” triggers
  5.  Custom Validation Rules
  6.  Record saved to database (but not committed)
  7.  Record reloaded from database
  8.  All Apex “after” triggers
  9.  Assignment rules
  10.  Auto-response rules
  11.  Workflow rules
  12.  Escalation rules
  13.  Parent Rollup Summary Formula value updated (if present)
  14.  Database commit
  15.  Post-commit logic (sending email)
 What is the salesforce.com workflow process?
 
Many of the tasks you normally assign, the emails you regularly send, and other record updates are part of your organization's standard processes. Instead of doing this work manually, have salesforce do it automatically by configuring workflow.
Workflow is available in: Enterprise, Unlimited, and Developer Editions
Workflow is the automation of the following types of actions based on your organization's processes:

* Tasks - Assign a new task to a user, role, or record owner.
* Email Alerts - Send an email to one or more recipients you specify.
* Field Updates - Update the value of a field on a record.
* Outbound Messages - Send a secure configurable API message (in XML format) to a designated listener. In outbound message contains end point URL.


What is Roll up summary field in Salesforce?
 
Roll up summary field in salesforce calculates the Count, Sum, Min or Max of particular field of any child record. Thus, we can say that Roll up summary field can only be created on Master object.
 
Which type of report can be used for dashboard components?

Summary and matrix report.
 
What is analytic Snapshot in salesforce?

Analytic snapshot capture and store the data at pre decided intervals. It captures data from report and saves in custom object as per schedule. It only supports tabular and summary report as a source report. It does not support matrix report. The field type in target object must be same as source report object field.
 
Explain difference in COUNT() and COUNT(fieldname) in SOQL.
 
COUNT()
  • COUNT() must be the only element in the SELECT list.
  • You can use COUNT() with a LIMIT clause.
  • You can’t use COUNT() with an ORDER BY clause. Use COUNT(fieldName) instead.
  • You can’t use COUNT() with a GROUP BY clause for API version 19.0 and later. Use COUNT(fieldName) instead.
COUNT(fieldName)
  • You can use COUNT(fieldName) with an ORDER BY clause.
  • You can use COUNT(fieldName) with a GROUP BY clause for API version 19.0 and later.
 
Which SOQL statement can be used to get all records even from recycle bin or Archived Activities?

We will need “ALL Rows” clause of SOQL.
Sample: SELECT COUNT() FROM Contact WHERE AccountId = a.Id ALL ROWS

 
 What is difference between public and global class in Apex?

 Public class can be accessed within application or namespace. This is not exactly like    Public modifier in Java.
  • Global class visible everywhere, any application or namespace. Web Service must be declared as Global and which can be accessed inside JavaScript also. It is like public modifier in Java.
How can you call Apex class using Javascript ? Give Example.
Global class myClass
{
            WebService static Id makeContact(String lastName,Account a)
{
            Contact c=new Contact(LastName =lastName,AccountId=a.Id);
            return c.Id;
}
}

We can execute above method from javascript like :
var account = sforce.sObject("Account");
var id = sforce.apex.execute("myClass“ , "makeContact",
{lastName:"Smith", a:account});
 
·         To call a webService method with no parameters, use {} as the third parameter for sforce.apex.execute .
·         Also, you can use the following line to display a popup window with debugging information:
sforce.debug.trace=true;

 

Difference between WhoID and WhatID.

WhatID
WhoId
Refers to object.
Refers to people.
Example: Account Id, Opportunity Id.
Example: Lead Id, Contact Id.

Difference between the multiple messaging options in Visual force?

<apex:message> is used to display an error on only a very specific field /Component. It is used to allow the developer to place field specific errors in a specific location.
<apex:messages> is similar to <apex:message>, but it displays all of the errors. These errors are displayed as a list with no styling.
<apex:pageMessage> is used to display a single custom message using the Salesforce formatting. You can specify the severity (which will control the display of the message box) and the strength (which will control the size of the box).
<apex:pageMessages> is used to display all of the messages on a page. It will display Salesforce generated messages as well as custom messages added to the ApexPages class.

What is Dynamic SOQL
 
Dynamic SOQL refers to the creation of a SOQL string at runtime with Apex code. Dynamic SOQL enables you to create more flexible applications.

To create a dynamic SOQL query at runtime, use the database query method, in one of the following ways:

Return a single sObject when the query returns a single record:

sObject S = Database.query(string_limit_1);


Return a list of sObjects when the query returns more than a single record:

List<sObject> L = Database.query(string);

 

Difference between Standard Controller​s and Standard List Controller​s  

The standard controller is auto generated by SF for all objects.Standard controller encapsulates just a single Sobject (e.g. Account, Opportunity).
Custom controllers are written by you and do what your code tells them to do.
Standard list controller contains a list of records (one or more), and has additional functions to facilitate paging (moving between pages) and updating a number of records at once.

What is meant by Standard Controller & Controller?

In standard controller we can refer Standard and custom objects.

In Controller we can refer Apex class.
Examples of Standard Controller,Standard List  Controller,Controller and extension.
For a page with a single record, accessing standard data and behavior of your object you would use standard controller:
<apex:page standardController="Account"...> ... </apex:page>

If you want a page with many records, using standard list view, and list actions you could use standard list controller:
<apex:page standardController="Account" recordsetVar="accountsList"...> ... </apex:page>

If you want to use completely custom functionality and don't really need most of the standard object behaviors, custom controller is a good option, but bear in mind, any standard actions you want to use will have to be implemented in your custom class. A page with a custom controller would use the following attribute:
<apex:page controller="MyApexClass"...> ... </apex:page>

But bear in mind, you yourself can instantiate ApexPages.StandardController to use its features and functionality. I often use the pattern below to instantiate standard controller to get access to its methods:
Public with sharing class MyApexClass
{
private ApexPages.StandardController ctrl;
public Account acct {get;set;}
public MyApexClass()
{
try
{
acct = [select Name from Account where Id = : ApexPages.currentPage().getParameters().get('id')];
}
catch (QueryException e)
{
acct = new Account();
}
ctrl = new ApexPages.StandardController(acct);
}
Public PageReference save ()
{
//here I can put additional functionality or just leave it as-is.
return ctrl.save();
}
}
If I want to add to the functionality of any controller, I can then use an extension. Extensions work with either standard or custom controllers. Standard controller with custom extension, for me, is the most common construct I use for Visualforce that will operate inside my org. I get all the power of the standard controller, but all the flexibility of Apex. The syntax for an extension with a standard controller page would be as follows:
<apex:page standardController="account" extensions="MyExtClass"...> ... </apex:page>
The extension class is then required to implement a constructor that accepts the type of the controller. You will then typically want to get a handle to the standard controller instance that is floating around, and the sObject instance that it represents. So for a standard controller page:

public with sharing class MyExtClass {
  private ApexPages.StandardController ctrl;
  public Account acct {get;set;}
  public MyExtClass(ApexPages.StandardController controllerParam){
      ctrl = controllerParam;
      acct = (Account) ctrl.getRecord();
  }
  public PageReference customsave(){
    //here I override my standard save functionality before I return the save call.
    return ctrl.save();
  }
}
With a custom controller and extension, you can probably extrapolate from the above, but just to close the loop.
<apex:page controller="MyApexClass" extensions="MyExtClass"...> ... </apex:page>
Again, the extension class implements a constructor that accepts the type of the controller, only now it is my custom class. From there, apart from getting a local handle to your custom controller instance, there isn't a pattern, per-se, but the local handle allows you to interact directly with your custom controller, in whatever way necessary, of course. :
public with sharing class MyExtClass {
  private MyApexClass ctrl;
  public MyExtClass(MyApexClass controllerParam){
      ctrl = controllerParam;
  }
}


What is meant by Rendered, Render As & Re-render attribute in VF?

Rendered is used decide whether to display or hide the VF elements.
<apex:inputField value="{obj.Filed_C}"  Rendered="{!val == true}"/>


Render As is render a VF page as PDF or some other

Eg: <apex:page controller="mmm" renderAs="pdf">

ReRender is to ReRender(ie.,Reload) some fields, or sections  after some operation/change. For this you need to assign id to field, sections.

Eg:
<apex:actionRegion >
     <apex:inputField value="{!xxxx}"  >
                        <apex:actionSupport event="onchange" rerender="yrs,yrss,yrsss,nodays,nohours,nominutes" action="{!xxx}" >
                            <apex:param name="Para" value="{!rowNum}" assignTo="{!IndexValue}" />                         
                        </apex:actionSupport>
                    </apex:inputField>
                </apex:actionRegion>
</apex:inputFiel>

yrs,yrss,yrsss,nodays,nohours,nominutes  are the id's of field and sections

What is Grant Access Using Hierarchies?

Say there are three roles
  • Role A
    • Role B
      • Role C
Role A is higher in hierarchy, Role B is in middle and Role C is lower in hierarchy
If the Role A user through Manual Sharing or Sharing Rules, shares the record to Role C user who is in lower hierarchy, then the Role B user who is above in hierarchy to Role C user can see the records, if we enable Grant Access Using Hierarchies at sharing settings else Role B user cannot see the record.
Beyond setting the organization-wide sharing defaults for each object, you can specify whether users have access to the data owned by or shared with their subordinates in the hierarchy. For example, the role hierarchy automatically grants record access to users above the record owner in the hierarchy. By default, the Grant Access Using Hierarchies option is enabled for all objects, and it can only be changed for custom objects.

What is OWD?

OWD is the default access level on records for any object in sales force.
For custom objects we can see below access levels -
1.Private
2.Public Read only
3.Public Read/Write

Private: only owner and above hierarchy users can have Read/Write access and below hierarchy users don't have any access.
Public Read only: only owner and above hierarchy users can have Read/Write access and below hierarchy users can have only Read Only.
Public Read/Write: Irrespective of role hierarchy everyone can have Read/Write permissions on the records.


Can you tell difference between Profile, OWD or a Sharing Rule?

Profile: Profile is used for object level access. It is used to provide CURD (Create, Update, Read and Delete) permission.

OWD: OWD is used for record level access for all the users across Organization. It is used to provide Public Read Only, Public Read/Write, Private, Public Read/Write/Transfer(Lead and Case Objects alone).

Sharing Rule: Sharing Rules is used to extend Role Hierarchy.


How to get site URL from apex

The following example creates a link to a Salesforce record. The full URL is created by concatenating the Salesforce base URL with the record ID.

Account acct = [SELECT Id FROM Account WHERE Name = 'Acme' LIMIT 1];

String fullRecordURL = URL.getSalesforceBaseUrl().toExternalForm() + '/' + acct.Id;

How many Types of Dashboards
There are five type of dashboards

Chart
Used for comparisons
Table
Good for showing top five, bottom five lists.
Gauge
Used to show progress towards a goal
Metric
Shows a single number
VisualForce page
used to pull data from other sources


What is difference between Trigger and Workflow?

Workflow
Workflow is automated process that fired an action based on Evaluation criteria and rule criteria.
We can access a workflow across the object.
We cannot perform DML operation on workflow
We cannot query from database

Trigger
Trigger is a piece of code that executes before or after a record is inserted or updated.
We can access the trigger across the object and related to that objects
We can use 20 DML operations in one trigger.
We can use 20 SOQL’s from data base in one trigger.

What is Difference between SOQL and SOSL?

SOQL(Salesforce Object Query Language)
Using SOQL we can Search only on one object at a time.
We can query on all fields of any datatype
We can use SOQL in Triggers and classes.
We can perform DML operation on query results.

SOSL (Salesforce object Search Language)
Using SOSL we can search on many objects at a time.
We can query only on fields whose data type is text, phone and Email.
We can use in classes but not in Triggers.
We cannot perform DML operation on search result

How many records can be retrieved by List data type if the page attribute in readonly?

10,000.

What is visual force view state?

Visual force that contain a form component also contains a hidden, encrypted form field that encapsulate the view state of the page. This view state is automatically created and it holds the state of the page – state includes the component, field values and controller state.

What is Custom Components?

Similar to the way you can encapsulate a piece of code in a method and then reuse that method several times in a program, you can encapsulate a common design pattern in a custom component and then reuse that component several times in one or more Visualforce pages.
<apex:page standardController="Account">
   This is my <i>page</i>. <br/>
   <c:myComponent/>
</apex:page>
It results in the following output:
This is my page.
This is my custom component.

What is the difference between profiles and permission sets?
Grant additional access to one or more users without changing their profile or reassigning profiles.
You have one profile assigned to 20 different users.
Now suppose you want give some extra permission to one of user. You have two options here.
a) To change Profile permissions : By this way those extra permissions will received by every user who is having that profile

b) Second way is to create a permission set having those extra permission. You need to assign this permission set to particular user by navigating to User detail page. In this way, you don’t have to worry about other users, as only specific user is getting those extra permissions.

You can assign permission set as many users you want.

The difference between Profile and Permission Sets is Profiles are used to restrict from something where Permission Set allows user to get extra permissions.

Difference between action function and action support.

Action function:  Invoke/call the controller method from java script using AJAX and we can use action function from different places on visual force page.
Its easy to call a controller method for most of the attributes using action="{!Yourmethode_Name}", but what if you were to call the controller method from java script? solution is action function.
Controller Class
Global Class Actfunc
{
            Public string str {set;get;}
            Public string ctrlmethod()
            {
                        Str=”I am called by the action function”;
                        Return null;
}
}

VF Page

<apex:page Controller=”Actfunc” >
<apex:form>
<apex:actionfunction name =”nameofactfunc”action={!crtlmethod} rerender=”optxtid”>
<apex:pageBlock>
<apex:outputLabel value=”Welcome,Click on Chkbox to call act fun” for=”cbid”>
<apex:checkbox id=”cbid” onClick=”chbox”>

</apex:pageBlock>
<apex:outputText value={!str} id=”optxtid”>
</apex:form>
<Script>
Function chbox()
{
            Nameofactfunc();
}
</script>
</apex:page>

Action support: Invoke the controller method using AJAX when even occurs on page like onMouseOver, onClick, ect… and we can use action support for particular single apex component.

What is batch Apex in salesforce?

The typical use of batch apex is when you want to do a bulk job, but if you do it in a regular apex you’re bound to hit the governor limits. Batch Classes process the set of records you pass to it in batches of maximum 200 per batch.

Advantages of using Batch Apex?
·        
            Higher Governor Limits
·         can be used to process in batches
·         can be scheduled to run at different time. (Read more)
·         Work around to other governor limits e.g. Send More than 10 E-mails.
Area
Normal Context
Batch Context
SOQL queries
100 SOQL per cycle
200 SOQL per cycle
records retrieved by SOQL queries
50,000
50,000,000 (getQueryLocator)
executed code statements
200,000
1,000,000 (Winter '14)
Heap size
6 MB
12 MB

Sample Code: Batch Class

global class ExampleBatchClass implements Database.Batchable<sObject>
            global ExampleBatchClass()
{
                // Batch Constructor
            }   
            // Start Method
            global Database.QueryLocator start(Database.BatchableContext BC)
{
                        return Database.getQueryLocator(query);
             }  
            // Execute Logic
            global void execute(Database.BatchableContext BC, List<sObject>scope)
{
                        // Logic to be Executed batch wise
             } 
            global void finish(Database.BatchableContext BC)
{
                        // Logic to be Executed at finish
             }
 }

Call the batch class

ExampleBatchClass b = new ExampleBatchClass();
//Parameters of ExecuteBatch(context,BatchSize)
database.executebatch(b,10);


Calling Batch class under Schedule Class:

Global Class ScheduleClass implements Schedulable
{
            Global Void execute(SchedulableContext sc)
{
            ExampleBatchClass ebc= new ExampleBatchClass();
            Database.executebatch(ebc,10);
}
}


now use the following system.schedule method for above class
open system log (click Your Name | Setup) and execute the below mentioned method so it will get scheduled.

ScheduleClass m = new ScheduleClass(); 
 String s = '1 30 1 10 2 ?'; 
 system.schedule('Job Name', s, m);


here string
s is in following pattern:
seconds, minutes, hours, dayofMonth, month, dayofWeek, year(optional)
Values for expression:
Name
Values
Special Characters
Seconds
0–59
None
Minutes
0–59
None
Hours
0–23
, - * /
Day_of_month
1–31
, - * ? / L W
Month
1–12
, - * /
Day_of_week
1–7
, - * ? / L #
optional_year
null or 1970–2099
, - * /



The special characters are defined as follows:
Special Character Description
, Delimits values. For example, use JAN, MAR, APR to specify more than one month.

- Specifies a range. For example, use JAN-MAR to specify more than one month.

* Specifies all values. For example, if Month is specified as *, the job is scheduled for every month.

? Specifies no specific value. This is only available for Day_of_month and Day_of_week, and is generally used when specifying a value for one and not the other.

/ Specifies increments. The number before the slash specifies when the intervals should begin, and the number after the slash is the interval amount. For example, if you specify 1/5 for Day_of_month, the Apex class runs every fifth day of the month, starting on the first of the month.

L Specifies the end of a range (last). This is only available for Day_of_month and Day_of_week. When used with Day of month, L always means the last day of the month, such as January 31, February 28 for leap years, and so on. When used with Day_of_week by itself, it always means 7 or SAT. When used with a Day_of_week value, it means the last of that type of day in the month. For example, if you specify 2L, you are specifying the last Monday of the month. Do not use a range of values with L as the results may be unexpected.

W Specifies the nearest weekday (Monday-Friday) of the given day. This is only available for Day_of_month. For example, if you specify 20W, and the 20th is a Saturday, the class runs on the 19th. If you specify 1W, and the first is a Saturday, the class does not run in the previous month, but on the third, which is the following Monday. Tip: Use the L and W together to specify the last weekday of the month.

# Specifies the nth day of the month, in the format weekday#day_of_month. This is only available for Day_of_week. The number before the # specifies weekday (SUN-SAT). The number after the # specifies the day of the month. For example, specifying 2#2 means the class runs on the second Monday of every month.

What is Annotation?

Apex supports the following annotations:
  • @Deprecated
  • @Future
  • @IsTest
  • @ReadOnly
  • @RemoteAction

Apex REST annotations:
·         @RestResource
·         @HttpDelete
·         @HttpGet
·         @HttpPatch
·         @HttpPost
·         @HttpPut

@Deprecated:
Use the deprecated annotation to identify methods, classes, exceptions, enums, interfaces, or variables that can no longer be referenced in subsequent releases of the managed package in which they reside. This is useful when you are refactoring code in managed packages as the requirements evolve. New subscribers cannot see the deprecated elements, while the elements continue to function for existing subscribers and API integrations.
Note the following rules when deprecating Apex identifiers:
·         Unmanaged packages cannot contain code that uses the deprecated keyword.
·         When an Apex item is deprecated, all global access modifiers that reference the deprecated identifier must also be deprecated. Any global method that uses the deprecated type in its signature, either in an input argument or the method return type, must also be deprecated. A deprecated item, such as a method or a class, can still be referenced internally by the package developer.
§  webService methods and variables cannot be deprecated.
§  You can deprecate an enum but you cannot deprecate individual enum values.
§  You can deprecate an interface but you cannot deprecate individual methods in an interface.
§  You can deprecate an abstract class but you cannot deprecate individual abstract methods in an abstract class.
§  You cannot remove the deprecated annotation to undeprecate something in Apex after you have released a package version where that item in Apex is deprecated.
@Future:
Use the future annotation to identify methods that are executed asynchronously. When you specify future, the method executes when Salesforce has available resources.
For example, you can use the future annotation when making an asynchronous Web service callout to an external service. Without the annotation, the Web service callout is made from the same thread that is executing the Apex code, and no additional processing can occur until the callout is complete (synchronous processing).
Methods with the future annotation must be static methods, and can only return a void type.

@Istest:
Use the isTest annotation to define classes or individual methods that only contain code used for testing your application. This is test annotation is similar to creating methods declared as testMethod.

@ReadOnly:
The @ReadOnly annotation allows you to perform unrestricted queries against the Force.com database. All other limits still apply. It's important to note that this annotation, while removing the limit of the number of returned rows for a request, blocks you from performing the following operations within the request: DML operations, calls to System.schedule, calls to methods annotated with @future, and sending emails.
The @ReadOnly annotation is available for Web services and the Schedulable interface. To use the @ReadOnly annotation, the top level request must be in the schedule execution or the Web service invocation. For example, if a Visualforce page calls a Web service that contains the @ReadOnly annotation, the request fails because Visualforce is the top level request, not the Web service.

@RemoteAction:
The RemoteAction annotation provides support for Apex methods used in Visualforce to be called via JavaScript. This process is often referred to as JavaScript remoting.

@RestResource:
The @RestResource annotation is used at the class level and enables you to expose an Apex class as a REST resource.
These are some considerations when using this annotation:
·         The URL mapping is relative to https://instance.salesforce.com/services/apexrest/.
·         A wildcard character (*) may be used.
§  The URL mapping is case-sensitive. A URL mapping for my_url will only match a REST resource containing my_url and not My_Url.
§  To use this annotation, your Apex class must be defined as global.

@HTTPDelete:
The @HttpDelete annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method is called when an HTTP DELETE request is sent, and deletes the specified resource.

@HTTPGet:
The @HttpGet annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method is called when an HTTP GET request is sent, and returns the specified resource.
These are some considerations when using this annotation:
·         To use this annotation, your Apex method must be defined as global static.
·         Methods annotated with @HttpGet are also called if the HTTP request uses the HEAD request method.

@HTTPPatch:
The @HttpPatch annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method is called when an HTTP PATCH request is sent, and updates the specified resource.
To use this annotation, your Apex method must be defined as global static.

@HTTPPost:
The @HttpPost annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method is called when an HTTP POST request is sent, and creates a new resource.To use this annotation, your Apex method must be defined as global static.

@HTTPPut:
The @HttpPut annotation is used at the method level and enables you to expose an Apex method as a REST resource. This method is called when an HTTP PUT request is sent, and creates or updates the specified resource.
To use this annotation, your Apex method must be defined as global static.
 
What is Vlookup?
Suppose that you are creating Employee(a custom object) records in the SF org. Now since Employees are very important records, you do not want the users to create duplicate Employee again and again. For example, say one User already created an Employee Record with name - Arpita Bose. Now, an another User who does not know about this tries to create an another Employee record with the same name - Arpita Bose. and hence there is a potential duplication. This should not be allowed.

So you have two options now:
1.    Add a Validation Rule on the Employee which checks whether there are any existing Employee records with the same name if so stop the User from saving it. Here comes the role of VLOOKUP.
2.    Create an Apex Trigger(before Insert, before Update) which runs a SOQL query to get all the Employee records in the Org with same name as of the one thats getting created now. If the number of records is 1 then stop the User from creating the Employee using an addError method. This will require considerable development effort.
Now, since we are interested in VLOOKUP lets see as of how we can do the same. Create a Validation Rule as below:
(4) Name = VLOOKUP(
(1) $ObjectType.Employee__c.Fields.Name ,
(2) $ObjectType.Employee__c.Fields.Name ,
(3) Name)

The SFDC Document define VLOOKUP as follows:
VLOOKUP(field_to_returnfield_on_lookup_objectlookup_value)
 
Searches an object for a record where the specified field matches the specified lookup_value. If a match is found, returns another specified field value.
Points to Remember:
1.    VLOOKUP only available on Custom Objects.
2.    VLOOKUP only available in Validation Rules.
3.    VLOOKUP can only be done on the Name fields.
4.    The field_to_return must be an auto number, roll-up summary, lookup relationship, master-detail relationship, checkbox, date, date/time, email, number, percent, phone, picklist, text,
 text area, or URL field type.
5.    The field_on_lookup_object must be the Record Name field on a custom object.
6.    The field_on_lookup_object and lookup_value must be the same data type.

What is Package? Difference between Managed and Un Managed Package.
A package is a container for something as small as an individual component or as large as a set of related apps. After creating a package, you can distribute it to other Salesforce users and organizations, including those outside your company.
Packages come in two forms—unmanaged and managed:
Unmanaged packages
Unmanaged packages are typically used to distribute open-source projects or application templates to provide developers with the basic building blocks for an application. Once the components are installed from an unmanaged package, the components can be edited in the organization they are installed in. The developer who created and uploaded the unmanaged package has no control over the installed components, and can't change or upgrade them. Unmanaged packages should not be used to migrate components from a sandbox to production organization. Instead, use Change Sets.
Managed packages
Managed packages are typically used by Salesforce partners to distribute and sell applications to customers. These packages must be created from a Developer Edition organization. Using the AppExchange and the License Management Application (LMA), developers can sell and manage user-based licenses to the app. Managed packages are also fully upgradeable. To ensure seamless upgrades, certain destructive changes, like removing objects or fields, cannot be performed.
Managed packages also offer the following benefits:
§ Intellectual property protection for Apex
§ Built-in versioning support for API accessible components
§ The ability to branch and patch a previous version
§ The ability to seamlessly push patch updates to subscribers
§ Unique naming of all components to ensure conflict-free installs
The following definitions illustrate these concepts:
Unmanaged and Managed Packages
Components
A component is one constituent part of a package. It defines an item, such as a custom object or a custom field. You can combine components in a package to produce powerful features or applications. In an unmanaged package, components are not upgradeable. In a managed package, some components can be upgraded while others can’t.
Attributes
An attribute is a field on a component, such as the name of an email template or the Allow Reports checkbox on a custom object. On a non-upgradeable component in either an unmanaged or managed package, attributes are editable by both the developer (the one who created the package) and the subscriber (the one who installed the package). On an upgradeable component in a managed package, some attributes can be edited by the developer, some can be edited by the subscriber, and some are locked, meaning they can’t be edited by either the developer or subscriber.
What is the difference between External ID and Unique ID?

External ID

This is a field that usually references an ID from another (external) system. For instance, if the customer has an Oracle Financials system that they will be linking with salesforce.com, it may be easier for them to be able to refer to the Oracle ID of account records from within salesforce. So they would create an external ID in salesforce.com and they would load the Oracle ID into that field for each account. They can then refer to that ID field, rather than the salesforce.com id.
Additionally, if you have an external ID field, the field becomes searchable in the sidebar search. You also can use the upsert API call with the extenal ID to refer to records.

You can have multiple records with the same external ID (though it is not reccomended, as it will defeat the purpose of the external id).

External ID(index) can be created on text, number and email

Unique ID field

This is a setting for the field that will prevent you from using the same value in multiple records for the unique field. So if I create a 5 character text field and make it unique, and I create a record with the value "12345" I will not be able to create another record with that same value in the unique field. If I try to do so, I will get an error saying that the value is already in use.

Often, External Ids are set with the unique property so that the IDs will be unique to each record.

What are the types of email templates available in salesforce.com?

1. Text
2. HTML with Letter Head
3. Custom HTML
4. Visual force

Difference between "Trigger.New" and "Trigger.old".

Trigger.new : Returns a list of the new versions of the sObject records. Note that this sObject list is only available in insert and update triggers, and the records can only be modified in before triggers.

 Trigger.old : Returns a list of the old versions of the sObject records. Note that this sObject list is only available in update and delete triggers.

What is difference between Trigger.new and Trigger.newMap?
Trigger.new returns a list, which are ordered, and
Trigger.newMap returns a map - which are unordered. We cannot use in before Insert

 
What is the difference between database.insert and insert ?
If we use the DML statement (insert), then in bulk operation if error occurs, the execution will stop .and Apex code throws an error which can be handled in try catch block.

If DML database methods (Database.insert) used, then if error occurs the remaining records will be inserted / updated means partial DML operation will be done.

Example
If there is 100 records, 99 are correct and 1is bad record,

In DML statement (insert) 100 records are failed,
In Database.Insert 99 records are inserted, one record is failed.

What is Static Resource?
Static resources allow you to upload content that you can reference in a Visualforce page, including archives (such as .zip and .jar files), images, stylesheets, JavaScript, and other files.
Using a static resource is preferable to uploading a file to the Documents tab because:
·         You can package a collection of related files into a directory hierarchy and upload that hierarchy as a .zip or .jar archive.
·         You can reference a static resource by name in page markup by using the $Resource global variable instead of hard coding document IDs.
To create a static resource:
·         From Setup, click Develop | Static Resources.
·         Click New Static Resource.
·         Enter the text In the Name text box
·         Next to the File text box, click Browse to navigate to a local copy of the resource that you want to upload.A single static resource can be up to 5 MB in size, and an organization can have up to 250 MB of static resources, total.
·         Set the Cache Control
·         Save
Referencing a static resource in visual force markup:
To reference a stand-alone file, use $Resource.<resource_name> as a merge field, where <resource_name> is the name you specified when you uploaded the resource
<apex:image url= “{!$Resource.TestImage}” Width=”50” height =”60”/>
Or
<apex:IncludeScript value=”{!$Resource.myjavascriptfile}” />
To reference a file in an archive, use the URLFOR function. Specify the static resource name that you provided when you uploaded the archive with the first parameter, and the path to the desired file within the archive with the second. 
<apex:image url =”{!URLFOR($Resource.testZip,’images/bluehills.jpg’)}” width=”50” height =”60”/>
Or
<apex:includescript value=”{URLFOR($Resource.libraryJS,`/base/subdir/file.js`)}” />

How to run trigger in asynchronously?
 If you use @FUTURE annotation trigger run asynchronously.

Give Sample Code Snippet of Apex that that will show that how Parent and Child record can be inserted in Single Statement ?
Ans : It can be done with help of External Id.

Date dt = Date.today().addDays(7);

2
Opportunity newOpportunity = new Opportunity(Name = 'shivasoft', StageName ='Prospecting', CloseDate = dt);

3


4
/*

5
Create the parent reference. Used only for foreign key reference and doesn't contain any other fields. If we provide any other value it will give following error

6


7
System.DmlException: Insert failed. First exception on row 1; first error: INVALID_FIELD, More than 1 field provided in an external foreign key reference in entity: Account: []

8
*/

9


10
Account accountReference = new Account(MyExtID__c = 'SHIVA1234567');

11
newOpportunity.Account = accountReference;

12


13
// Create the Account object to insert.  Same as above but has Name field.  Used for the insert.

14
Account parentAccount = new Account(Name = 'Shiva', MyExtID__c = 'SHIVA1234567');

15


16
Database.SaveResult[]

17
    results = Database.insert(new SObject[] {  parentAccount, newOpportunity });


156. What are few Considerations about Trigger ?
·         upsert triggers fire both before and after insert or before and after update triggers as appropriate.
·         merge triggers fire both before and after delete triggers for the losing records and before update triggers for the winning record only.
·         Triggers that execute after a record has been undeleted only work with specific objects.
·         Field history is not recorded until the end of a trigger. If you query field history in a trigger, you will not see any history for the current transaction.
·         You can only use the webService keyword in a trigger when it is in a method defined as asynchronous; that is, when the method is defined with the @future keyword.
·         A trigger invoked by an insert, delete, or update of a recurring event or recurring taskresults in a runtime error when the trigger is called in bulk from the Force.com API.
·         Merge trigger doesn’t fire there own trigger instead they fire delete and update of loosing and winning records respectively.
 
Explain Considerations for Static keyword in Apex.
 
·         Apex classes cannot be static.
·         Static allowed only in outer class.
·         Static variables not transferred as a part of View State.
·         Static variables and static block runs in order in which they are written in class.
·         Static variables are static only in scope of request.
 
Explain few considerations for @Future annotation in Apex.
Method must be static
  • Cannot return anything ( Only Void )
  • To test @future methods, you should use startTest and stopTest to make it synchronous inside Test class.
  • Parameter to @future method can only be primitive or collection of primitive data type.
  • Cannot be used inside VF in Constructor, Set or Get methods.
  • @future method cannot call other @future method.
What is Wrapper class ?

A wrapper or container class is a class, data structure, or an abstract data type whose instances are a collections of other objects.It is a custom object defined by Salesforce developer where he defines the properties of the wrapper class. Within Apex & Visualforce this can be extremely helpful to achieve many business scenarios within the Salesforce CRM software.
Use of Wrapper Class within Salesforce:
Many times in the community boards, people have asked the questions on how they can display a table of records with a check box and then process only the records that are selected. You can do it using this below step by step instructions. You can use wrapper class to display records from multiple records within a single table based around the business needs.
A wrapper class is a custom object defined by programmer wherein he defines the wrapper class properties. Consider a custom object in salesforce, what do you have in it? fields right? different fields of different data types. Similarly wrapper class is a custom class which has different data types or properties as per requirement. We can wrap different objects types or any other types in a wrapper class.
Here is an example if you want to display account data in the table along with a checkbox on the right side of the table (checkbox with every row). You can bind an account checkbox field to this right column but below is an example for demonstrating wrapper with a custom checkbox column.
Follow these simple steps within your Salesforce CRM:
Step 1 –
Go to setup→Develop→PagesàNew
Step 2-
In the label and name box, type “WrapperClass”
Step 3 -
In editor paste this code:
In the Visualforce page code section, paste the following:
<apex:page controller=”wrapperClass” sidebar=”false” showHeader=”false”>
<apex:form>
<apex:pageMessages />
<apex:pageBlock title=”Edit Information in Account” mode=”edit”>
<apex:pageBlockSection>
<apex:pageBlockSectionItem>
<apex:commandButton value=”Change Type” action=”{!Changetype}” reRender=”theTable”/>
<apex:inputField value=”{!anacc.type}”/>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
<apex:pageBlockTable value=”{!accwrap}” var=”a” id=”theTable”>
<apex:columnheaderValue=”All accounts name”>
<apex:inputCheckbox value=”{!a.selected}”/>
<apex:actionSupport event=”onclick” action=”{!getselected}” reRender=”other_block”/>&nbsp;
<apex:outputField value=”{!a.acc.name}”/>
</apex:column>
<apex:columnheaderValue=”Owner name”>
<apex:outputField value=”{!a.acc.Ownerid}”/>
</apex:column>
<apex:columnheaderValue=”Type”>
<apex:outputField value=”{!a.acc.Type}”/>
</apex:column>
<apex:columnheaderValue=”Last modify “>
<apex:outputField value=”{!a.acc.Website}”/>
</apex:column>
<apex:columnheaderValue=”Last modify “>
<apex:outputField value=”{!a.acc.Price__c}”/>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>
In the controller code section, paste the following:
public class wrapperClass {
public String accinp { get; set; }
public list<account>accs = new list<account>();
public list<accountwrapper>accwrap{get; set;}
public list<account>selectedaccount{get; set;}
public account anacc{get; set;}
public void Changetype(){
for(account ac:selectedaccount){
ac.type=anacc.type;
}
if(anacc.Price__c<400){
update selectedaccount;
}else{
apexpages.addmessage(new apexpages.message(apexpages.severity.error,’This is only applicable for Price less than 400…..’));
}
}
publicwrapperClass(){
accwrap=new list<accountwrapper>();
anacc= new account();
accs= [select name, Ownerid, Website, Type,Price__c from account where website!= null order by createddatedesc limit 100];
accountWrapperObject();
}
public void accountWrapperObject(){
for(account a:accs){
accountwrapper aw = new accountwrapper(a);
accwrap.add(aw);
}
}
public void getselected(){
selectedaccount = new list<account>();
selectedaccount.clear();
for(accountwrapperawrap:accwrap)
if(awrap.selected==true){
selectedaccount.add(awrap.acc);
}
}
public class accountwrapper{
public account acc{get; set;}
public boolean selected{get; set;}
public accountWrapper(account a){
acc=a;
selected= false;
}
}
}
“Save” this code
Step 4 -
Open page on Preview panelbar:

What is DML Exception ?

getDmlFieldNames:Returns the names of the field or fields that caused the error described by the ith failed row.
getDmlFields:Schema.sObjectField []          Returns the field token or tokens for the field or fields that caused the error described by the ith failed row. For more information on field tokens, see Dynamic Apex.
getDmlId: String Returns the ID of the failed record that caused the error described by the ith failed row.
getDmlIndex:Returns the original row position of the ith failed row.
getDmlMessage:StringReturns the user message for the ith failed row.
getDmlStatusCode   :String  Deprecated. Use getDmlType instead. Returns the Apex failure code for the ith failed row.
getDmlType: System. Status Code Returns the value of the System.StatusCode enum. For example:
getNumDml   :IntegerReturns the number of failed rows for DML exceptions.
API Name
What It’s For
When to Use It
Protocol
Data Format
Communication
REST API
Accessing objects in your organization using REST.
You want to leverage the REST architecture to integrate with your organization. No WSDL requirement. Well-suited for browser-based applications, mobile apps, and highly-interactive social applications.
REST
JSON, XML
Synchronous
SOAP API
Integrating your organization’s data with other applications using SOAP.
You have pre-existing middleware services that need to work with WSDLs and XML data.
SOAP/
WSDL
XML
Synchronous
Chatter REST API
Displaying Salesforcedata, especially in mobile apps. Work with Chatterfeeds, users, groups, and followers; work withSalesforce Files and Files Connect; work with recommendations, topics, notifications, Data.com, and other Salesforce features .
You want to integrateSalesforce into a mobile app, intranet site, or third-party Web application.
REST
JSON, XML
Synchronous (photos are processed asynchronously)
Bulk API
Loading or deleting large numbers of records.
You have over a million records to process and speed is a requirement.
REST
CSV, XML
Asynchronous
Metadata API
Managing customizations in your organization and building tools that can manage the metadata model, not the data itself.
You want to migrate changes, such as custom object definitions and page layouts, from asandbox to your production environment.
SOAP/
WSDL
XML
Asynchronous
Streaming API
Providing a stream of data reflecting data changes in your organization.
You need near real-time notifications of when records are created or updated.
Bayeux
JSON
Asynchronous (stream of data)
Apex REST API
Building your own REST API in Apex. ExposesApex classes as RESTful Web services.
You need to build custom JSON responses or you want to expose custom functionality that you implemented in Apex.
REST
JSON, XML, Custom
Synchronous
Apex SOAP API
Creating custom SOAP Web services in Apex. Exposes Apex classes as SOAP Web services.
You need to build custom XML responses or you want to expose custom functionality that you implemented in Apex .
SOAP/
WSDL
XML
Synchronous
Tooling API
Building custom development tools forForce.com applications.
You want to add functionality to your existing development and integration tools or you want to build specialized development tools for a specific application or service.
REST and SOAP
JSON, XML, Custom
Asynchronous
What API are there in salesforce?
 
Note: To use the APIs,  api should enabled.
 
·         REST API - Access objects in your organization using REST. Its advantages include ease of integration and development, and it’s an excellent choice of technology for use with mobile applications and Web projects.
·         SOAP API - Integrate your organization’s data with other applications using SOAP. You can use SOAP API to create, retrieve, update, or delete records. You can also use SOAP API to perform searches and much more. Use SOAP API in any language that supports Web services.
·         Tooling API - Build custom development tools for Force.com applications. You want to add functionality to your existing development and integration tools or you want to build specialized development tools for a specific application or service.
·         Chatter REST API - Access Chatter feeds and social data such as users, groups, followers, and files using REST.
·         Bulk API - Load or delete large numbers of records.
·         Metadata API - Manage customizations in your org and build tools that manage the metadata model (not the data, itself).
·         Streaming API - Provide a stream of data reflecting data changes in your organization.
·         Apex REST API - Build your own REST API in Apex. This API exposes Apex classes as REST full Web services.
·         Apex SOAP API - Create custom SOAP Web services in Apex. This API exposes Apex classes as SOAP Web services.
·         Data.com API - Data.com provides 100% complete, high quality data, updated in real-time in the cloud, and with comprehensive coverage worldwide.
 

How many records we can display on page for a report?

We can display up to 2000 records on a page. If more records are there to display we cannot see those through user interface. If you export the records to a excel sheet then you can export up to to 50000 records.

What are the types of Reports?

  1. Tabular (Displays records just like a table)
  2. Summary (we can summarize the information based on certain fields)
  3. Matrix (we can summarize the information in two dimensional manner, both rows and columns)
  4. Join (we can summarize information in different blocks on the same object and the related objects)

How many blocks we can create for join reports?

5 Blocks.

How many maximum groupings we can do for summary, matrix and join reports?

3 groupings

What is bucketing in reports?

It is used to group values to the name we specify.

What is the purpose of @TestVisible?

Sometimes in test classes we need to access a variable from Apex Class, if it is private we cannot access for that we will replace private with public. for this reason we are compromising the security. To avoid this before the private variables in apex class we can include @TestVisible so that even though variable is private we can access from the test class.

What is the purpose of Test.isRunningTest()?

Sometimes we cannot satisfy certain if conditions for the apex classes, in those situations on those if conditions we can add Test.isRunningTest separated with or condition. Example: if(condition || Test.isRunningTest())

There is a code in a method of your controller that a test class should not invoke. How would you ensure that the test execution never executes this piece of code? Provide a sample code snippet.
 
Use Test.isRunningTest to wrap that piece of code.

What are the assert statements?

To compare Actual value and Expected value we use assert statements.
Types of assert statements
  1. system.assertEquals(val1,val2): If both val1 and val2 are same then test class run successfully otherwise test class will fail.
  2. system.assertNotEquals(val1,val2): If both val1 and val2 are not same then test class run successfully otherwise test class will fail.
  3. system.assertEquals(val1> val2): If the condition satisfied then test class run successfully otherwise test class will fail.

What is the purpose of Test.startTest() and Test.stopTest()?

Test.startTest() and Test.stopTest() maintains fresh set of governor limits. Assume that you are consuming 99 SOQL queries outside of Test.startTest() and Test.stopTest() then if you include any SOQL inside of Test.startTest() and Test.stopTest() count will start from 1.
Per testMethod we can use Test.startTest() and Test.stopTest() only for one time.
To execute asynchronous methods synchronously we can call those methods from inside of Test.startTest() and Test.stopTest().

What are the Assignment rules?

On lead and case objects we can create the Assignment rules. Whenever any record is submitted for lead/case if specified condition in the Assignment rule satisfied based on that we can decide the owner of the case/lead. Note: While submitting case/lead we should check for 'Assign using active assignment rule' checkbox which will display under Optional section.

What are Auto-Response Rules?

On lead and case objects we can create the Auto-Response Rules. Whenever any record is submitted for lead/case if specified condition in the Auto-Response Rules satisfied based on that we can decide the email format which should send as auto response.

What are the Escalation rules?

On case object we can create Escalation rule. Based on the priority we can send escalation mails.

 What is the purpose of seeAllData?

By default test class cannot recognize the existing data in the database.
if you mention @isTest(seeAllData = true) then test class can recognize the existing data in the database.
See the below examples -
  • From a List Custom Settings we cannot fetch the existing data without seeAllData = true in test class.
  • Suppose you have a custom object called 'CustomObject__c' and it contains many records, we cannot fetch the existing data without seeAllData = true in test class.
Note: It is not recommended to use seeAllData = true for a test class. Based on the existing data in database code coverage will impact.

What is the difference between 15 digit and 18 digit id in Salesforce?

  • In Salesforce, whenever user create any component (Object, field, tab etc...) or record then salesforce will generate an unique id with which user can identify the record or component.
  • After creating the record, in the URL user can see the id of the record which is of 15 digits length.
  • Through user interface user always see 15 digit id which is Cases-Sensitive.
  • If the user query the existing records from the database through API (Either from Query Tool or from a program), it will always return 18 digit id which is Case-Insensitive.
  • Last 3 digits of the 18 digit represents checksum of the capitalization of 15 digit id.
  • Based on the first 3 digits user can identify the object of the record.
  • All the records belongs to same object will contain same first 3 digits.
Provide a sample snippet to implement the following scenario - there are two DML operations in a method and you want to revert all the changes committed by DML1 in case DML2 fails(the DMLS are fairly independent but you want to ensure that all changes are reverted if the second DML fails)
    Need to use Database.savepoint before DML1. Need to wrap DML2 in a try catch , and once DML2 fails , need to use database.rollback to revert it back to the point before DML1.
 
Sample:

Savepoint sp = Database.setSavepoint();;

Account a = new Account();
a.Name='1';

a.AccountNumber = '2';
insert a;

Contact c = new Contact(Account = a.Id);
try
{
    insert c;
}
catch(Exception e)
{
    Database.RollBack(sp);
}

In this example, if any error occurs while inserting the Contact 'c', then the entire transaction will be rolled back to savepoint sp ( as specified in the catch section by Database.rollback method).

Note the following:
  • If you set more than one savepoint, then roll back to a savepoint that is not the last savepoint you generated, the later savepoint variables become invalid. For example, if you generated savepoint SP1 first, savepoint SP2 after that, and then you rolled back to SP1, the variable SP2 would no longer be valid. You will receive a runtime error if you try to use it.
  • References to savepoints cannot cross trigger invocations, because each trigger invocation is a new execution context. If you declare a savepoint as a static variable then try to use it across trigger contexts you will receive a runtime error.
  • Each savepoint you set counts against the governor limit for DML statements.
List the trigger contexts in which Trigger.Old is not available while writing an Apex Trigger.
 
Trigger.old is not available in before insert, after insert.
 
Write a simple trigger that will mark a "Brought back from Recycle Bin" checkbox flag on the Account object to true whenever an account has been brought back from the recycle bin.
 
trigger Supply_Trigger on Supply__c (after undelete)
{
 List<Supply__c>supList = new List<Supply__c>();
 if(Trigger.isUndelete)
 {
  for(Supply__c sup : Trigger.new)
  {
   supList.add(new Supply__c(isUndeleted__c = true, Id = sup.Id));
  }
  update supList;
 }
}
 
Write a SOQL Query that you will have to write in your controller to ensure that the record in context (take example of an Account) cannot be updated by any other user till your transaction is completed.

Select Id from Account where ID = :acc.Id FOR UPDATE

Throw some light on the following exception and a few work-arounds of solving it -"Maximum view state size limit (135KB) exceeded. Actual view state size for this page was 1,287.984KB"

https://developer.salesforce.com/page/An_Introduction_to_Visualforce_View_State
https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_best_practices_performance.html

Which interface would you implement in your wrapper class if you desire to sort the columns of the wrapper on the button click from the UI?

Comparable Interface

Write a SOQL query on Contact object which would return all the records (ones that are deleted and are in the recycle bin as well)

SELECT COUNT() FROM Contact WHERE AccountId = a.Id ALL ROWS

Write a single SOQL query to return the cases of whose Priority is "High" for the account whose Name starts with "A"

Select Id,Casenumber from Case where Priority = 'High' and Account.Name Like 'A%'

Provide a sample code snippet to stop trigger recursion

Boolean isFirstTime = false;
if(isFirstTime == false)
{
 isFirstTime = true;
// call trigger method
}

Write a test class for the following controller : (we can check for his best practices in test classes - seeAllData annotation, start and stop test, asserts, System.runAs)

public with sharing class ColorPicker
{
 public Boolean isBlue;
 public ColorPicker()
 {
 isBlue = false;
 }
}
public Boolean isBlueColor(String s)
{
 if(s == 'Blue')
 {
  isBlue = true;
 }
 return isBlue;                          
 }
}

Explain when you would chose "Master Detail" relationship over "Lookup" while creating a relationship field.
You have to configure a validation rule on an object to ensure that it does not fire for a particular configured profile. What is the best way of achieving this?


Need to use hierarchical custom settings.
Need to create a hierarchical custom setting (Suppress_Validation__c) with checkbox field.
Need to make this checkbox true only for the profiles for which we do not want the validation to be fired.
Then, need to add a condition in the validation rule as 'if(Suppress_Validation__c == false)'.

What happens when the criteria of a time-based workflow rule is met but the time when the workflow action has to fire is set to the past?

a. The job is not queued
b. The job is queued but never executed
c. The job is queued and is executed immediately when an executor becomes available

What are Standard Business Objects?
  • Campaigns: A Campaign is any marketing project that you want to plan, manage, and track in Salesforce.
  • Leads: A Lead is any person, organization or company that may be interested in your products. Sometimes Leads are referred to as Prospects or Suspects. Leads are not yet customers.
  • Accounts: An Account is an organization, individual or company involved with your business such as customers, competitors and partners that you wish to track in Salesforce.
  • Contacts: A Contact is any individual or influencer associated with an account that you want to track in Salesforce.
  • Opportunities: An Opportunity is any potential revenue-generating event (“sales deal” ) that you want to track in Salesforce.
  • Cases: A case is a detailed description of a customer’s feedback, problem or question.
  • Solutions: A solution is a detailed description of a customer issue and the resolution of that issue. The collection of your organization’s solutions is sometimes referred to as the solution knowledge base.
  • Forecasts: A forecast is your best estimate of how much revenue you can generate in a quarter.
  • Documents
  • Reports: Reports are summaries and analyses of your data, which you can display or print.
  • Dashboards: Dashboards give you a real-time snapshot of corporate metrics and key performance indicators. A dashboard is a group of different charts (or components) that graphically display your custom report data.
  • Calendar and Task: Activities are both tasks and scheduled calendar events. You can define and track activities for many different objects, including campaigns, accounts, contacts, and leads.
  • Products: Products are the individual items that you sell on your opportunities. (Please note that Products are available in EE/UE and Developer and in PE for an additional fee.)

Single Sign On Steps:

Salesforce provides different options to configure Single Sign On. This includes 

Ø  Federated Authentication using SAML

Ø  Delegated Authentication

Ø  OpenID Connect

There are two main concepts in SSO that you need to be aware of. 

Ø  The concept of IdP/SP

Ø  The concept of IdP initiated login and SP initiated login. 

1.       IdP/SP: IdP stands for Identity Provider and SP stands for Service Provider. When logging on, IdP is the system that authenticates user by validating his username and password and then subsequently all other applications trust IdP and allow user to access the application if the IdP asserts that the user is a valid user. In such cases, IdP is the system that stores user’s login name and password. You can configure different systems as IdP, for example Microsoft Active Directory, Oracle Internet Directory, Google, Salesforce etc.

2.      IdP initiated Login and SP initiated Login: When a user needs to access the application, he/she can initiate the access in two different ways. User can logon to IdP and then from there, click on links to access other systems (i.e. SP). This is called IdP initiated login. Or otherwise, the user can go directly to an SP application to access the application. In this case, SP will redirect the user to IdP login page where user will provide his or her username and password, IdP will authenticate the user and pass the control back to SP asserting whether user is authenticated or not. SP will then allow user to access the application.

With Salesforce, you can configure Salesforce both ways – as an IdP or as a SP. There are different possible combinations in setting up SSO with Salesforce.

Microsoft Active Directory as IdP and Salesforce as SP

In the first scenario, you will be setting up a Microsoft Active Directory on Amazon Web Services (AWS) as Identify Provider and then use this to allow users to logon to Salesforce. Salesfoce in this scenario will play the role of Service Provider. Don’t worry if you do not know how to setup Microsoft AD and AWS. With this step-by-step guide with screenshots, you just need to follow the instructions. This step-by-step guide includes how to

·         Configure Windows 2008 Server on AWS

·         Install Microsoft Active Directory

·         Install Microsoft ADFS 2.0

·         Create self-signed certificate in IIS

·         Configure Microsoft ADFS 2.0

·         Export Self-Signed Certificate

·         Retrieve ADFS 2.0 Details for Salesforce Configuration

·         Configure My Domain in Salesforce

·         Enable SSO in Salesforce

·         Add Salesforce as Trusted Relying Party in ADFS

·         Configure AD User for Single Sign On in Salesforce

·         Test SSO

·         Use Just-In-Time (JIT) Provisioning

·         Debug SSO Issues

What is a web-lead?
Capturing a lead from a website and routing it into lead object in Sales Force is called wed-lead (web to lead).

 

What is Sales process? 

Campaign à Lead à Account, Contact, Opportunity 

After campaigning, manually we need to convert into Lead and then automatically system will create Account, Contact, and Opportunity.

Even we can create Web-to-Lead, else we can create Email-to-Case and Web-to-Case and then convert to Lead. 

After Campaigning, we can create lead into three ways one Web-to-Lead, Case-to Lead in this case we can create Case through Email-to-Case or Web-to-Case and manually also. Once we create Lead, system can automatically create Account, Contact, and Opportunity or we can can create just Account or Contact too. 

Campaigns: A campaign is an outbound marketing project that you want to plan, manage, and track within Salesforce. It can be a direct mail program, seminar, print advertisement, email, or other type of marketing initiative. You can organize campaigns into hierarchies for easy analysis of related marketing tactics. 

There are three general ways of doing so:
·         Manual entry – Yes, it’s true. Leads are entered manually sometimes. It doesn’t happen often but there are certain scenarios – such as when reps collect business cards at a networking event – where it is possible. When doing so, it is critical to look for the lead first or use a duplicate preventer like DupeCatcher to make sure you don’t have multiple entries of the same lead.

·         Web leads – This is a very common method in today’s marketing world, with many leads coming in through a form or a landing page on your website. Again, it would be wise to use a third-party web entry application to make sure you don’t have duplicates in your Salesforce system.

With web leads, you can take the data to the next level by creating an Activity for the user’s download history, creating Custom Objects to see a user’s page-view sequence or create topic-interest strings to specific fields. Be warned: this type of web page logic requires code to push the data properly into Salesforce, unless you use a high-quality Marketing Automation System to handle it for you.
·         Spreadsheet / list imports – Many marketing teams will buy huge lists of names that they can then send their marketing efforts to, importing those .csv files into Salesforce. This is an extremely common way to market today. Parse the individual entries to correct spelling errors, formatting issues and dirty data. Make sure that all the data is normalized and match your system’s pick-list values. Remove all duplicates, and change the column headers to fit with your Salesforce instance’s template. 
·         Through Case – Even through case also we can get Lead information. It is rarely happens.
 

What are Custom Settings?
Custom settings are special types of custom objects whose data is cached.

Custom Settings:
·         Can be accessed repeatedly without hitting governor limits

·         Can be accessed programmatically using built-in getter methods in apex code.
There are two types of custom settings
List: store static data such as abbreviations, codes, configuration settings and so on.
Hierarchy: store settings that may change on a per-user, per-profile, or organization wide default.

What are Groups?
Queue and groups are both are same, which will hold group of users, but in working environment as per the requirement we need to decide which will use in proper way.

For Example in Call Centre. There are many Customer Care Executive in a call center and many customers call at a time and one executive can talk to one customer at one time, so other customer’s calls are kept in queues. In this scenario we have to go with Queue
                      
Suppose you need to Share some of the information in your organization among some users, in this we can define Group, then we can share information or we assign some work to group.

What are some Best Practices while writing Test Classes?
  • Very important and first, “Test Coverage Target Should not be limited to 75%”. It is not about coverage, it is about testing complete functionality.
  • If possible don’t use seeAllData=true, Create your Own Test Data.
  • @testSetup is a new annotation, any record created in this method will be available to all test methods of that class. Using @testSetup method will improve test execution performance by creating test records only once for that class
  • If you’re Object’s Schema is not changing frequently, you can create CSV file of records and load in static resource. This file will act as Test data for your Test Classes.
  • Use As much as Assertions like System.AssertEquals or System.AssertNotEquals
  • Use Test.startTest() to reset Governor limits in Test methods
  • If you are doing any Asynchronous operation in code, then don’t forget to call Test.stopTest () to make sure that operation is completed.
  • Use System.runAs () method to enforce OWD and Profile related testing’s. This is very important from Security point of View.
  • Always try to pass null values in every methods. This is the area where most of program fails, unknowingly.
  • Always test Batch Capabilities of your code by passing 20 to 100 records.
  • Use Test.isRunningTest () in your code to identify that context of class is Test or not. You can use this condition with OR (||) to allow test classes to enter inside code bock. It is very handy while testing for WebService, we can generate fake response easily.
  • @TestVisible annotation can be used to access private members and methods inside Test Class. Now we don’t need to compromise with access specifiers for sake of code coverage.
  • End your test class with “_Test”. So that in Apex Class list view, Main class and Test class will come together, resulting easy navigation and time saver.