Wednesday 16 January 2019

Batch Apex

1. What are transaction limits in apex?
Total number of SOQL queries issued1 - 100
Total number of records retrieved by SOQL queries - 50,000
Total number of records retrieved by Database.getQueryLocator - 10,000
Total number of records retrieved by a single SOSL query - 2,000
Total number of DML statements issued2 - 150
Total number of records processed as a result of DML statements, Approval.process, or database.emptyRecycleBin - 10000
Total number of callouts (HTTP requests or Web services calls) in a transaction - 100
Maximum cumulative timeout for all callouts (HTTP requests or Web services calls) in a transaction - 120
Maximum number of methods with the future annotation allowed per Apex invocation - 50
Maximum number of Apex jobs added to the queue with System.enqueueJob - 50
Total number of sendEmail methods allowed - 10
Maximum execution time for each Apex transaction - 10 minimum
Maximum number of push notification method calls allowed per Apex transaction - 10
Maximum number of push notifications that can be sent in each push notification method call - 2000


4. What is Database.Batchable interface?
To use batch Apex, write an Apex class that implements the Salesforce-provided interface Database.Batchable and then invoke the class programmatically.
To monitor or stop the execution of the batch Apex job, from Setup, enter Apex Jobs in the Quick Find box, then select Apex Jobs.

5. Define the methods in Batchable interface?
Start()
Execute()
Finish()

6. What is purpose of Start method in batch apex?
Used to collect the records or objects to be passed to the interface method execute for processing.
This method is called once at the beginning of a Batch Apex job and returns either a Database.
Most of the time a QueryLocator does the trick with a simple SOQL query to generate the scope of objects in the batch job.
But if you need to do something crazy like loop through the results of an API call or pre-process records before being passed to the execute method, you might want to check out the Custom Iterators link in the Resources section.

7. What is the Database.QueryLocator ?
With the QueryLocator object, the governor limit for the total number of records retrieved by SOQL queries is bypassed and you can query up to 50 million records.
However, with an Iterable, the governor limit for the total number of records retrieved by SOQL queries is still enforced.
QueryLocator object or an Iterable that contains the records or objects passed to the job.

9. How to define the custom Iterable?
The iterator method must be declared as global or public. It creates a reference to the iterator that you can then use to traverse the data structure.
In the following example a custom iterator iterates through a collection:
global class CustomIterable
   implements Iterator<Account>{

   List<Account> accs {get; set;}
   Integer i {get; set;}

   public CustomIterable(){
       accs =
       [SELECT Id, Name,
       NumberOfEmployees
       FROM Account
       WHERE Name = 'false'];
       i = 0;
   } 

   global boolean hasNext(){
       if(i >= accs.size()) {
           return false;
       } else {
           return true;
       }
   }   

   global Account next(){
       // 8 is an arbitrary
       // constant in this example
       // that represents the
       // maximum size of the list.
       if(i == 8){return null;}
       i++;
       return accs[i-1];
   }
}

global class example implements iterable<Account>{
   global Iterator<Account> Iterator(){
      return new CustomIterable();
   }
}

global class batchClass implements Database.batchable<Account>{
   global Iterable<Account> start(Database.batchableContext info){
       return new example();
   }   
   global void execute(Database.batchableContext info, List<Account> scope){
       List<Account> accsToUpdate = new List<Account>();
       for(Account a : scope){
           a.Name = 'true';
           a.NumberOfEmployees = 69;
           accsToUpdate.add(a);
       }
       update accsToUpdate;
   }   
   global void finish(Database.batchableContext info){   
   }
}

10. What is the use of execute method?
Used to collect the records or objects to be passed to the interface method execute for processing.
This method is called once at the beginning of a Batch Apex job and returns either a Database.QueryLocator object or an Iterable that contains the records or objects passed to the job.

11. How many times execute method is called?
For the execute method, it depends on you.

12. What is scope-of execute method?
Do DML Actions

13. Can we call callouts from batch apex?
global class BatchSync implements Database.Batchable<sObject>,   Database.AllowsCallouts {

 public String query = 'Select ID, Name from Account';
 global Database.QueryLocator start(Database.BatchableContext BC) {
    return Database.getQueryLocator(query);
 }

     global void execute(Database.BatchableContext BC, List<Account> records) {       
        String endpoint;       

        for ( integer i = 0; i< records.size(); i++ ){
         try {                 
          HttpRequest req = new HttpRequest();
          HttpResponse res = new HttpResponse();
          Http http = new Http();
          // Set values to Params

          endpoint = 'Your endpoint';

          req.setHeader('Authorization', header);
          req.setHeader('Content-Type', 'application/json');
          req.setEndpoint(endpoint);
          req.setMethod('POST');
          req.setBody('Information you wanna send');
          req.setCompressed(true); // This is imp according to SF, but please check if
                                 // the webservice accepts the info. Mine did not :P
                                 // Had to set it to false

          if (!Test.isRunningTest()) {     
            res = http.send(req);
            String sJson = res.getBody();
            System.debug('Str:' + res.getBody());
          }           
          // now do what u want to with response.             
          }
          catch (Exception e) {       
            System.debug('Error:' + e.getMessage() + 'LN:' + e.getLineNumber() );         
          }
       }
    } 

    global void finish(Database.BatchableContext BC){   
    }
}

14. Can we call another batch apex from batch apex?
Batch 1:
global class Batch1 implements Database.Batchable<Sobject>{

    //Method to get the data to be proceesed 
    global database.Querylocator Start(Database.BatchableContext bc){
        String query = 'Select Id, Name From Account Limit 1000';
        return Database.getQueryLocator(query);
    }


    //Method to execute the batch
    global void execute(Database.BatchableContext bc, Sobject[] scope){
        for(Sobject s : scope){
        Account a = (Account)s;
            // TO DO
            // add your logic
        }
    }

    //Method to be called after the excute
    global void finish(Database.BatchableContext bc){
        //Add your start code for the other batch job here
        Database.executeBatch(new Batch2());
    }
}

Batch 2:
global class Batch2 implements Database.Batchable<Sobject>{

    //Method to get the data to be proceesed 
    global database.Querylocator start(Database.BatchableContext bc){
        string query = 'Select Id, Name From Contact Limit 1000';
        return Database.getQueryLocator(query);
    }


    //Method to execute the batch
    global void execute(Database.BatchableContext bc, Sobject[] scope){
        for(Sobject s : scope){
        Contact c = (Contact)s;
            // TO DO
            // add your logic
        }
    }

    //Method to be called after the excute
    global void finish(Database.BatchableContext bc){

    }
}
15. How many callouts we can call in batch apex?
The upper limit now is 100 callouts ,which means if you have one callout in your execute method you can keep batch size as 100.
Say you have two callouts then your batch size can be 50 .

16. If you get Callouts Governing limits error how do you rectify?
Too many SOQL queries: 101
Since Apex runs on a multi-tenant platform, the Apex runtime engine strictly enforces limits to ensure code doesn't monopolize shared resources.
Avoid SOQL queries that are inside FOR loops.
Follow the key coding principals for Apex Code in our Developer's Guide.

17. Batch is synchronous or Asynchronous operations?
Asynchronous:
In a Asynchronous call, the thread will not wait until it completes its tasks before proceeding to next. Instead it proceeds to next leaving it run in separate thread. In a Asynchronous call, the code runs in multiple threads which helps to do many tasks as background jobs.
Example:
Batch
@future Annotation

Synchronous:
In a Synchronous call, the thread will wait until it completes its tasks before proceeding to next. In a Synchronous call, the code runs in single thread.
Example:
Trigger
Controller Extension
Custom Controller

21. What is the maximum size of the batch and minimum size of the batch?
Minimum size for Batch Apex in Salesforce is 1.
Maximum size for Batch Apex in Salesforce is 2000.

24. HOW to track the details of the current running Batch using BatchableContext?
Integer enqueuedJobs = [SELECT COUNT() FROM AsyncApexJob WHERE JobType='BatchApex' AND Status IN ('Processing','Preparing','Queued')] ;

if(enqueuedJobs >= 5){
    throw new TooManyBatchApexJobsException();
}

Visualforce - Part 2

1.What are expressions used in pages  to bind in controllers?
Using methods we can bind.
Getter:Will return value from controller to vf page
Setter:Will pass value from vf page to controller
Action:Will redirect to another page.

2.What is the purpose of controllers?
Controllers provide the data and actions that are available to a Visualforce page.

3.Which objects have associated standard controllers?
All standard and custom objects that can be accessed via the API have associated controllers

4.What is included with each standard controller?
Data: the fields for the associated object record that are API accessible, including the related records (5 up/1 down).  Actions: save, delete, view, edit, cancel.

5. When do you need to go beyond a standard controller and code custom Apex?
If you need data beyond the limits of what is available in the standard controller or actions that go beyond the provided standard actions.

6.Compare and contrast custom controllers and controller extensions.  How are they the same?  How are they different?
Both allow for custom code to be used, allowing for custom data sets and custom actions.  Extensions leverage the existing data and actions within a standard or custom controller.
Custom controllers must contain all data and actions that need to be executed by the page. 
Extensions that extend standard controller allow for the pages which use those extensions to be used in custom buttons, standard button overrides, and over declarative features.

7.What identifies a controller as being an extension?
The controller must declare a constructor which takes another controller explicitly. 
For example: public myControllerExtension(ApexPages.StandardController stdController) {this.acct = (Account)stdController.getRecord();  }

8.Why are properties helpful in controllers?
Properties can automatically create standard getters and setters while still allowing for their customizations. 
They save you from both writing the tedious code and reading the clutter when reviewing code.

9.In what order do methods fire within a controller?
The only rule is that setters fire before action methods.  Aside from that, there is no guaranteed order.

10.What are some Apex classes that are commonly used within controllers?
StandardController, SelectOption, PageReference, Message, etc.

11.How are wizard controllers different from other controllers?
The two main issues is that they must handle multiple pages and they must maintain the state across those pages.

12.What are the effects of using the transient key word?
The transient key word prevents the data from being saved into the view state.  This should be used for very temporary variables.

13.When is a component controller required for custom components?
A component controller is required when business logic is required to decide how to render the component.

14.What kind of content can be included in a Visualforce page?
Any content that can be rendered in a browser (HTML, JavaScript, etc.).

15.What do {!expressions} refer to when used in Visualforce components?
Expressions refer to either data or actions that are made available to the page from the controller

16.What are the ways that Visualpages can be incorporated into the rest of your user interface?
Basically, via links, buttons, tabs, and inline frames.

17.Is it always necessary to know Apex to create Visualforce pages?  When does it become necessary?
No, it is not always necessary.  You can use standard controllers and VF component tags to accomplish quite a bit.
Apex becomes necessary when you need either a custom set of data or custom actions to be available from the page.

18.What are attributes?  What is the syntax for including them?
Attributes are modifiers to the main tag that belong after the tag name in the start tag.  The syntax is attributeName=“attributeValue”

19.What are three types of bindings used in Visualforce?  What does each refer to?
Data bindings refer to the data set in the controller.
Action bindings refer to action methods in the controller.
Component bindings refer to other Visualforce components

20.What is the main difference between using dataTable vs. pageBlockTable tags?
PageBlock: For default salesforce standard format.
dataTable:To design customformats

21.Which tag is used with both radio buttons and picklists to create the selectable values?
<Apex:selectoption> tag

22.How many controllers can a page have?  Where is the controller for a page assigned?
One main controller (of course, it could have extensions or custom components could have controllers, etc.).  The controller is assigned in the <apex:page> tag.

23.There are a series of layout components that all help recreate the traditional Salesforce page layout style very easily.  What name do they share?
pageBlock.

24.Which tags should be used to automatically bring in the Salesforce label and default widget for a field?
pageblock

25.What are static resources?
Static resources are a new type of storage in Salesforce specifically designed for use in Visualforce pages. 
They are ways to store images, flash files, stylesheets, and other web resources on the Salesforce servers that can be cached for better page performance.

26.What are some examples of JavaScript Events?
Onmouseover, onclieck etc.

27.What is AJAX typically used for in Visualforce
AJAX is primarily used for partial page updates in Visualforce.  In s-controls, the AJAX toolkit was the soap (XML over HTTP) client that gave you access to the force.com Web Services API.

28.What is the purpose of <script> tags?
Script tags allow you to create JavaScript (or other types) functions that can be used within your pages

29.What are the different AJAX action tags?  What does each do?
actionStatus: used to display start and stop statuses of AJAX requests.
actionSupport: used to call a second component when an event happens to the first component.
actionPoller: similar to actionSupport, but the event is based on a timer instead of a user action.
actionFunction: provides support for invoking a controller action from JavaScript code using an AJAX request by defining a new JavaScript function.
actionRegion: used to demarcate which parts of the page the server should reprocess.

30.   How can you create partial page refreshes?
Basically, you need to define the section of the page that is going to refresh (typically with a panel of sorts), and then define the event that will cause the refresh. 
The method changes depending on if the area being refreshed is the same as the one handling the event. 
It also depends on if you are just processing something on the server, or if you need the UI to change.

31.Which tag is used with both radio buttons and picklists to create the selectable values?
<apex:selectOption>

32.What is the purpose of creating attributes on components? 
By allowing the component to take parameters via an attribute, you can make the component more flexible and reusable

33.What are the Global Key words?
We have global keywords like component,User,url,current page etc., to access various values from components on page, from user object or from url or from current page fields.
To access value from each source, we have different global keywords. One such keyword is explained in above question(!$component)
Various global keywords are:
i.                     URL
ii.                   USER
iii.                  PROFILE
iv.                 Resource
v.                   Component
vi.                 Current page
vii.                Page reference etc.

34.How can you access visualforce components values into a JavaScript?
Using Component global variable, we can access visualforce components in javascript. Let us suppose, we want to use id of an apex field with id=”afield”.
So, we can use the {!$Component.afield} syntax to use properties of the field in javascript.
Let us suppose, we want to store the field’s value in java script, then we can use like below:
<script>
Var a =’ document.getElementById('{!$component.afield}').value’;
</script>


35.What are the Gov Limits in Salesforce.com?
Because Apex runs in a multitenant environment, the Apex runtime engine strictly enforces a number of limits to ensure that
runaway scripts do not monopolize shared resources. These limits, or governors, track and enforce the statistics outlined in the following table.
If a script ever exceeds a limit, the associated governor issues a runtime exception that cannot be handled.
Governor limits can be extended from release to release.


Visualforce - Part 1

1) What is View state in Visual force ?
To maintain state in a Visualforce page, the Lightning Platform platform includes the state of components, field values, and controller state in a hidden form element.
This encrypted string is the view state and has a limit of 135 KB. Large view states require longer processing times for each request, including serializing and deserializing, and encryption and decryption.
Reducing your view state size causes your pages to load quicker and stall less often.
Use the View State tab in the development mode footer to monitor view state performance, and take the following actions.
Use the transient keyword in your Apex controllers for variables that aren’t essential for maintaining state and aren’t necessary during page refreshes.
If you notice that a large percentage of your view state comes from objects used in controllers or controller extensions, consider refining your SOQL calls to return only data that's relevant to the Visualforce page.
If your view state is affected by a large component tree, try reducing the number of components your page depends on.
Use filters and pagination to reduce data requiring state.
Declare instance variables with a transient keyword when the variable is only useful for the current request. The view state includes all non-transient members in the controller and extension, as well as objects reachable from these non-transient members. Decide if some data can be read-only and use the <apex:outputText> component instead of <apex:inputField>.
Set the Development Mode and Show View State in Development Mode permissions set to see the View State tab in the development mode footer. The tab displays the distribution of view state. Make sure you know the view state size of each page, and test with large data volumes to determine if issues might occur after deployment.
Use JavaScript remoting. Unlike the <apex:actionFunction> component, JavaScript Remoting does not require a form component. This technique doesn’t reduce the overall view state of a page, but your page generally performs better without the need to transmit, serialize, and deserialize the view state. The tradeoff is the loss of the re-render attribute and the additional JavaScript code to handle callbacks.

2) Which api used to design Visual force page?
Metadata Api


3) What is difference between insert and include?
Apex:Insert
A template component that declares a named area that must be defined by an <apex:define> component in another Visualforce page.
Use this component with the <apex:composition> and <apex:define> components to share data between multiple pages.
Apex:include
A component that inserts a second Visualforce page into the current page. The entire page subtree is injected into the Visualforce DOM at the point of reference and the scope of the included page is maintained.

4) What is the difference between controller and extension ?
Custom Controller:
It is an Apex class that implements all of the logic for a page without leveraging a standard controller.
You can use only one Apex class.
You can Use custom controllers when you want your Visualforce page to run entirely in system mode, which does not enforce the permissions and field-level security of the current user.

Extension:
A controller extension is any Apex class containing a constructor that takes a single argument of type ApexPages.
It provides additional functionality to a controller – either a standard controller or a custom controller.
You can use multiple Apex classes separated by comma.
Use controller extensions when:You want to leverage the built-in functionality of a standard controller but override one or more actions, such as edit, view, save, or delete.
You want to add new actions.You want to build a Visualforce page that respects user permissions.
Although a controller extension class executes in system mode, if a controller extension extends a standard controller, the logic from the standard controller does not execute in system mode.
Instead, it executes in user mode, in which permissions, field-level security, and sharing rules of the current user apply.

5) What is the use Static Resource in Visual force?
The way you reference a static resource in Visualforce markup depends on whether you want to reference a stand-alone file, or whether you want to reference a file that is contained in an archive (such as a .zip or .jar file):
To reference a stand-alone file, use $Resource.<resource_name> as a merge field, where <resource_name> is the name

7) How do you refer to current page id
 public CurrentRecordIdDemoController(ApexPages.StandardController controller) {
        currentRecordId  = ApexPages.CurrentPage().getparameters().get('id');
        acc = [select id ,name, AccountNumber, Type, Industry from Account where id =: currentRecordId ];
        parameterValue = ApexPages.CurrentPage().getparameters().get('nameParam');
    }
}

8) What are custom components?
Yes

Trigger

1. What is trigger?
Apex can be invoked by using triggers.
Apex triggers enable you to perform custom actions before or after changes to Salesforce records, such as insertions, updates, or deletions.

2. What are different types of Triggers in sfdc?
A trigger is Apex code that executes before or after the following types of operations:
insert.
update.
delete.
merge.
upsert.
undelete

3. What are Trigger Context variable? 
Variable Usage
isExecuting Returns true if the current context for the Apex code is a trigger, not a Visualforce page, a Web service, or an executeanonymous() API call.
isInsert :         Returns true if this trigger was fired due to an insert operation, from the Salesforce user interface, Apex, or the API.
isUpdate : Returns true if this trigger was fired due to an update operation, from the Salesforce user interface, Apex, or the API.
isDelete :       Returns true if this trigger was fired due to a delete operation, from the Salesforce user interface, Apex, or the API.
isBefore  :      Returns true if this trigger was fired before any record was saved.
isAfter : Returns true if this trigger was fired after all records were saved.
isUndelete : Returns true if this trigger was fired after a record is recovered from the Recycle Bin (that is, after an undelete operation from the Salesforce user interface, Apex, or the API.)
new : Returns a list of the new versions of the sObject records.
This sObject list is only available in insert, update, and undelete triggers, and the records can only be modified in before triggers.
newMap : A map of IDs to the new versions of the sObject records.
This map is only available in before update, after insert, after update, and after undelete triggers.
old : Returns a list of the old versions of the sObject records.
This sObject list is only available in update and delete triggers.
oldMap : A map of IDs to the old versions of the sObject records.
This map is only available in update and delete triggers.
size : The total number of records in a trigger invocation, both old and new.

4. What is the difference between Trigger. New and :Trigger.NewMap
newMap A map of IDs to the new versions of the sObject records.
This map is only available in before update, after insert, after update, and after undelete triggers.
new Returns a list of the new versions of the sObject records.
This sObject list is only available in insert, update, and undelete triggers, and the records can only be modified in before triggers.

5. Can we call the Batchapex from the trigger?
1.As Daniel has said, you can only have five batch job running so calling batch from a trigger is almost certainly not a good idea.
These answers are somewhat valid, but since you can query the state of a running batch you can ensure that your batch is a singleton
2. @future is also possible

A batch apex can be called from a class as well as from trigger code.
In your Trigger code something like below :-
// BatchClass is the name of batchclass
BatchClass bh = new BatchClass();
Database.executeBacth(bh);

6. What are the problems you have encountered when calling batch apex from the trigger.
future method call that performs more processing on the same record(s).
The issue is that this entire process becomes recursive in nature and you receive the error "System.AsyncException: Future method cannot be called from a future method.

7. Can we call the callouts from triggers?
yes we can. It is same as usual class method calling from trigger.
The only difference being the method should always be asynchronous with @future

8. What are the problems that you encountered while calling apex callouts in triggers.
 Too many Future calls".

7. What is the recursive triggers?
Recursion occurs in trigger if your trigger has a same DML statement and the same dml condition is used in trigger firing condition on the same object(on which trigger has been written)

8. What is bulkifying triggers?
By default every trigger is a bulk trigger which is used to process the multiple records at a time as a batch. For each batch of 200 records.

9. What is the use of future methods in triggers?
Using @Future annotation we can convert the Trigger into a Asynchrinous Class and we can use a Callout method.

10. What is the order of executing the trigger apex?
1. Executes all before triggers.
2. Validation rules.
3. Executes all after triggers.
4. Executes assignment rules.
5. Executes auto-response rules.
6. Executes workflow rules.
7. If there are workflow field updates, updates the record again.
8. If the record was updated with workflow field updates, fires before and after triggers one more time. Custom validation rules are not run again.
9. Executes escalation rules.
10. If the record contains a roll-up summary field or is part of a cross-object workflow, performs calculations and updates the roll-up summary field in the parent record. Parent record goes through save procedure.
11. If the parent record is updated, and a grand-parent record contains a roll-up summary field or is part of a cross-object workflow, performs calculations and updates the roll-up summary field in the parent record. Grand-parent record goes through save procedure.
12. Executes Criteria Based Sharing evaluation.
13. Commits all DML operations to the database.
14. Executes post-commit logic. Ex: Sending email.

11. What is trigger handler?

Trigger:
Trigger:

    trigger AccountTrigger on Account(before insert, before update) 
    {
        AccountTriggerHandler handler = new  AccountTriggerHandler();
       
        handler.updateUser(Trigger.new);  // Call method for update account field.

    }
Trigger Handler
    public class AccountTriggerHandler
    {
           public void updateUser(List<Account> accList)
           {
                  Set<Id> masterIds = new Set<Id>();
                 
                  for(Account accObj : accList)
                  {
                    if(accObj.Master__c != null)
                       masterIds.add(accObj.Master__c);
                  }
           
                    Map<Id,Master__c> masterMap = new Map<Id,Master__c>([Select Id, test_user1__c from Master__c where Id IN : masterIds]);
                   
                   
                  for(Account acct : accList)
                  {
           
                    if(masterMap.containsKey(acct.Master__c))
                    {
                       Master__c masterObj = masterMap.get(acct.Master__c);
                 
                        if(acct.test_user1__c == null)
               
                           acct.test_user1__c = masterObj.test_user1__c;
                    }
                  }
           }
    }

12. How do you avoid-recursive triggers?
Use a static variable in an Apex class to avoid an infinite loop.
Static variables are local to the context of a Web request.

13. HOW many triggers we can define on a object?
We can write more than one trigger But it is not recommended .
Best practice is One trigger On One object.

14. How many time workflow filed update will be called in triggers?
If the record was updated with workflow field updates, fires before and after triggers one more time (and only one more time).
Note:The before and after triggers fire one more time only if something needs to be updated.
If the fields have already been set to a value, the triggers are not fired again.

Tuesday 15 January 2019

SFDC Top interview Questions

Difference between Workflow and Trigger
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.

Wrapper Class :
Answer:-A Wrapper class is a class whose instances are collection of other objects. It is used to display different objects on a Visual Force page in same table.

Difference between SOSL & SOQL:
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 calsses but not in Triggers.
We cannot perform DML operation on search result

Difference between insert() & Database.insert()
Using insert method we can insert the records but if any error occurs in any record system will throw an error insertion fail and none of the records are inserted.
If we want to execute partially success of bulk insert operation we will use database .insert.

Static Resource:
Using Static Resources we can upload images, zip files, jar files, java script and CSS files that can be referred in a visual force page.
The maximum size of Static Resources for an organization is 250mB.

Java Script using static resource in visualforce page
Using Static Resources we can upload images, zip files, jar files, java script and CSS files that can be referred in a visual force page.
The maximum size of Static Resources for an organization is 250mB.

Ways to share the record
Role Hierarchy:
If we add a user to a role, the user is above in the role hierarchy will have read access. Setup -> manage users -> roles -> setup roles -> click on ‘add role’ -> provide name and save.

OWD:
Defines the base line setting for the organization. Defines the level of access to the user can see the other user’s record OWD can be Private, Public Read Only, Public Read and Write. Setup -> Security Controls -> sharing settings -> Click on ‘Edit’

Manual Sharing:
Manual Sharing is sharing a single record to single user or group of users. We can see this button detail page of the record and this is visible only when OWD setting is private.
Criteria Based Sharing rules: If we want to share records based on condition like share records to group of users Whose criteria are country is India. Setup -> security controls -> sharing settings -> select the object and provide name and Conditions and save

Apex sharing:
Share object is available for every object(For Account object share object is AccountShare ). If we want to share the records using apex we have to create a record to the share object.

To made fields required:
1. While creation of field
2. Validation rules
3. Page Layout level

Role vs Profile
Role is Record level access and it is not mandatory for all users.
Profile is object level and field level access and it is mandatory for all users.

Maximum size of the PDF generated on visualforce attribute renderAs:
15 MB

How many controller can be used in VF page:
Salesforce come under SAAS so, we can use one controller and as many extension controllers.

Difference between ActionSupport & ActionFunction
Action function: Invoke the controller method from java script using AJAX and we can use action function from different places on visual force 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.

How many ways we can call apex class
1. Visual force page
2. Web Service
3. Triggers
4. Email services

Transfer Records in profile
If user have only Read access on particular record but he wants to change the owner name of that record, then in profile level Transfer Record enables he can able to change the owner.

Report Types
4 Types of report in Salesforce
Tabular Reports: We can only displays the grand total in the table form.
Summary Reports: It is a detail form of report in which the grouping done based on Columns.
Matrix Reports: It is a detail form of report in which the grouping done based on both Rows and Columns.
Joined Reports: We can join the two or more reports in the single report displayed in the form of blocks.

Dashboard
Dashboard is a pictorial representation of report. We can add up to 20 reports in single dashboard.

Organization Wide Defaults:
Below are the different OWD values Private
If the OWD for an object is set to private, then only the owner, and users above that role in role hierarchy, can view, edit and report on those records
Public Read Only
If the OWD for an object is set to Public Read Only, then all users can view and report on records but they cannot edit them. Only the record owner and the users above that role in the role hierarchy can edit the records
Public Read/Write
If the OWD for an object is set to Public Read/Write, then all users can view, edit and report on all records. But only owner of the record can delete the records.
Public Read/Write/Trfer
This is available only for Case and Lead objects If the OWD for an object is set to Public Read/Write/Trfer then, all users can view, edit, trfer and report on all the records but only owner of the record can delete the records
Public Full Access
This is available only for Campaign object. If the OWD for Campaigns are set Public Full Access then, all users can view, edit, delete and report on all records. No Access, View Only or Use
This is available only for Price Book object. If the OWD for Price Book is set Use then, all users can access the Price Book information and as well as using the Price Book configuration for Opportunities with Products. If the OWD for Price Book is set View Only then, all users can access the Price Book information but not to use that Price Book detail in Opportunities with Products If the OWD for Price Book is set No Access then, it restricts users from accessing information for Price Book and Prices. Controlled By Parent
If the OWD for any object is set as Controlled By Parent, then user can perform an action on the record based on whether they can do the same on the parent record associated with it

Grant Access Using Hierarchy
In Sharing settings, OWD settings, we have a check box Grant Access Using Hierarchies (for both standard and custom objects).
If this check box is checked then it will give automatic access to the user’s data to other users in higher role of salesforce CRM Role Hierarchy.
If this check box is not checked then, only record owner and users granted access by OWD can gain the access.

Difference between Export & Export All in data loader
Export enables user to export all the records for a particular object excluding the records in the recycle bin or soft deleted records.
Export All enables user to export all the records for a particular object including the records in the recycle bin or soft deleted records.

Wednesday 9 January 2019

Questions

What are available portals in Salesforce?
Three types of portals are available in salesforce.com

Customer Portal.
Partner Portal.
Self Service Portal
Customer Portal : It enables us to utilize the capabilities of the Web as the ideal channel to deliver superior self-service.
Partner Portal : It allows partner users to login to Salesforce via a separate website than our non-partner users.
Self Service Portal : Customers will able to search organization knowledge using this portal.

What is the Profile? Name some Standard profile available in Salesforce?
It is similar to setting and permissions in Salesforce to perform the different functions which are defined by users. It is another way to manage to particular records.

Two types of Profile

Standard profile : Profiles created by force.com
Custom profile : Profiles created by the user.
Salesforce standard profiles are

Standard user.
Solution manager.
Marketing user.
Read only.
System administrator

How to delete or freeze users in sales force.com?
Deleting a user is not possible in sales force.com but we can deactivate the user by freezing.
Setup  Administer  Manage users  users  freeze.

Mention the ways to store files, documents, and images in salesforce.com?
We can store files, documents, and images in sales force.com in 5 types

 Attachments.
Documents.
Google drive.
Libraries.
Chatter Files

Give one-word answers to following questions. a. In visual Force page how many field dependencies used? b. Two users can have the same profile in Salesforce? c. Which fields can’t be added as a custom index? d. Can we edit a formula field value in a record? e. Can we use sharing rules to restrict data access?
a.10 field dependencies
b. Yes
c. Formula field
d. No
e. No

How to set the Login hours and Login IP ranges to the users in Salesforce ?
Login hours- If Login hours set in an organization, then it restricts to log in before or after login hours.
Setup | Administration | Manage users | Profiles.
Login IP – It helps to restrict the unauthorized IP addresses login attempt.
Setup | Administration setup | Manage users | Profiles.

List out the characteristics and functions of Roll-up summary field?
Characteristics of Roll-up summary field

It can be created for Master-detail Relationship but can’t create for Look-up Relationship.
Auto numbers are not available here.
We can’t change field type in the roll-up summary field.
It derives data from child object.
The functions of Roll-up summary fields are

Count.
Sum.
Min.
Max

What are the different kinds of reports in Salesforce?
The different kind of reports in sales force is
Tabular Report : It is similar to spreadsheet and this report is the simplest and fastest way to see the data. Tabular reports are best to creating the lists of record.
Summary Report : It is similar to tabular report, but allows users to group rows of data, view subtotals, and create charts.
Matrix Report : It is similar to the summary report, but it allows users to group and summarize data by both rows and columns.
Joined Report : Joined reports let we create multiple report blocks that provide different views of our data and each blocks act as a sub-report.

Define dynamic dashboards? Can we schedule dynamic dashboards?
Dynamic dashboards help us to display the set of metrics in an organization. It is created to provide security settings for dashboards at salesforce.com
Two setting options in dashboards

Run as specified user.
Run as Logged-in User

What are the limitations of Time-dependent workflow?
Limitations of Time-dependent workflow

Time triggers doesn’t support minutes or seconds.
Time triggers cannot reference when Formula fields that include related-object merge fields.
We can’t add or remove the time triggers if
Workflow rule is active.
Workflow rule included in a package

How many ways to call the Apex class?
Four ways to call the Apex class.

Visual page.
Web service.
Triggers.
Email services

How to insert multiple records at a time?
public class insert50
{
public void p1()
{
List lstExample = new List();
Example_c objTest;
objTest = new Example_c(name=’Example1’,city_c=’City1’);
lstTesting.add(objTest);
objTest = new Example_c(name=’Example2’,city_c=’City2’);
lstTesting.add(objTest);
objTest = new Example_c(name=’Example3’,city_c=’City3’);
lstTesting.add(objTest);
insert lstTesting
}
}


When we use the data loader?
We are using the data loader when

We need to load more than 50 thousand records and lesser than 50 thousand.
We need to load into an object that is not yet supported by web-based importing.
We want to be able to save multiple mapping files for future use.
We want to export our data for backup purposes.
We want to prevent duplicates by uploading the records.

Thursday 3 January 2019

SFDC Interview Questions:


Links
https://www.shellblack.com/administration/owds/
https://www.simplilearn.com/top-salesforce-interview-questions-and-answers-article
sfdcfaq.blogspot.com/2013/04/what-is-case.html
https://www.forcetalks.com/salesforce-topic/how-to-display-names-of-contact-amp-opportunity-related-to-an-account-in-a-visualforce-page/
https://www.salesforcetutorial.com/how-to-use-system-runas/


Use the with sharing keywords when declaring a class to enforce the sharing rules that apply to the current user.

Use the without sharing keywords when declaring a class to ensure that the sharing rules for the current user are not enforced

Sales Cloud vs Service Cloud

Difference between Sales Cloud and Service Cloud :

Sales Cloud Implements Sales and Marketing for business development while Service cloud implements Salesforce Knowledge.
Sales Cloud is a great solution for small and mid-sized sales groups that want to rapidly increase revenue and cost effectively deploy Salesforce While Service Cloud provides Customer Support to the Clients and giving you the platform to provide a better customer experience for your clients.
Sales Cloud gives you the ability to open Cases and relate them to Accounts, Contacts; etc.
While The Service Cloud is a super set of Sales Cloud, meaning you get everything that is in Sales Cloud PLUS some other features.
When we develop product in force.com for sales then it comes in Sales Cloud Ex: – Account, Contacts, and Lead.
While when we want to provide some facility and also provides support to the clients then it comes in Service Cloud. Ex: – create cases is the example of Service Cloud in which client write his problem into cases instead of call.

what is the difference between profiles and roles?
https://www.shellblack.com/administration/owds/
Profile - to restrict object level
Role - i to open up the user level access
what are web services? why we need to go for them?

REST Service - @RestResource(urlMapping='/Account/*')
Annotation Action Details
@HttpGet Read Reads or retrieves records.
@HttpPost Create Creates records.
@HttpDelete Delete Deletes records.
@HttpPut Upsert Typically used to update existing records or create records.
@HttpPatch Update Typically used to update fields in existing records.

SOAP Service
WSDL file

What is WSDL?

Enterprise WSDL
1. The Enterprise WSDL is strongly typed.
2. The Enterprise WSDL is tied (bound) to a specific configuration of Salesforce (ie. a specific organization's Salesforce configuration).
3. The Enterprise WSDL changes if modifications (e.g custom fields or custom objects) are made to an organization's Salesforce configuration.

For the reasons outlined above, the Enterprise WSDL is intended primarily for Customers.

Partner WSDL
1. The Partner WSDL is loosely typed.
2. The Partner WSDL can be used to reflect against/interrogate any configuration of Salesforce (ie. any organization's Salesforce configuration).
3. The Partner WSDL is static, and hence does not change if modifications are made to an organization's Salesforce configuration.

For the reasons outlined above, the Partner WSDL is intended primarily for Partners.

Download a WSDL file when logged into Salesforce

1. Click Setup | Develop | API
2. Click the link to download the appropriate WSDL.
3. Save the file locally, giving the file a ".wsdl" extension.
What is SOAP?
SOAP is defined as an XML-based protocol.
It is known for designing and developing web services as well as enabling communication between applications developed on different platforms using various programming languages over the Internet.
It is both platform and language independent.


How you will make a class available to others for extension? (Inheritance concept)
The class has to be either abstract or virtual in order to extend it.
A class that extends another class inherits all the methods and properties of the extended class.
In addition, the extending class can override the existing virtual methods by using the override keyword in the method definition.
Overriding a virtual method allows you to provide a different implementation for an existing method.
This means that the behavior of a particular method is different based on the object you’re calling it on. This is referred to as polymorphism.
A class extends another class using the extends keyword in the class definition. A class can only extend one other class, but it can implement more than one interface.
This example shows how the YellowMarker class extends the Marker class. To run the inheritance examples in this section, first create the Marker class.
public virtual class Marker {
public virtual void write() {
System.debug('Writing some text.');
}

public virtual Double discount() {
return .05;
}
}
// Extension for the Marker class
public class YellowMarker extends Marker {
public override void write() {
System.debug('Writing some text using the yellow marker.');
}


In the process of creating a new record, how you will check, whether user has entered email or not in the email field of Account object?
Validation Rule (ISBLANK(Email__c)) or Trigger with before event.
trigger CheckName on Account (before insert)
{
List<account> a1=[Select id from account where account.name=:trigger.new[0].name];
if(a1.size()>0)
{
trigger.new[0].name.addError('Account Name already Exist');
}

}

How you will write a javascript function that display an alert on the screen?
<apex:page>
       <apex:form>
         <apex:selectList value="{!selectedItem}" onchange="callMethod()">
           <apex:selectOption value="{!itemList}"
         </apex:selectList>
       <apex:actionfunction name="callMethod" action="{!controllerMethod}" oncomplete="showAlert({!returnValue })"/>
      <apex:form>
  <script>
function showAlert(t) {
  if(t) {
alert('Correct');
  } else {
alert('No value entered !');
  }
}
  </script>
</apex:page>

Whatis the value of “renderas” attribute to display o/p in the form of Excel Sheet?
<apex:page contentType="application/vnd.ms-excel#report.xls" >

How you will get the javascript function into Visualforce page?
1. You can then use the functions defined within that JavaScript file within your page using <script> tags.
When using JavaScript within an expression, you need to escape quotes using a backslash (\). For example,
onclick="{!IF(false, 'javascript_call(\"js_string_parameter\")', 'else case')}"

2. The best method for including JavaScript in a Visualforce page is placing the JavaScript in a static resource, then calling it from there. For example,
<apex:includeScript value="{!$Resource.MyJavascriptFile}"/>

Can we create a dashboard using Visual-force page? and what all the components we use here?
Visualforce pages can be used as dashboard components. A dashboard shows data from source reports as visual components, which can be charts, gauges, tables, metrics, or Visualforce pages.
The components provide a snapshot of key metrics and performance indicators for your organization. Each dashboard can have up to 20 components.
Visualforce pages that use the Standard Controller can’t be used in dashboards.
To be included in a dashboard, a Visualforce page must have either no controller, use a custom controller, or reference a page bound to the StandardSetController Class.
If a Visualforce page does not meet these requirements, it does not appear as an option in the dashboard component Visualforce Page drop-down list.
<apex:page standardController="Case" recordSetvar="cases">
    <apex:pageBlock>
        <apex:form id="theForm">
            <apex:panelGrid columns="2">
                <apex:outputLabel value="View:"/>
<apex:selectList value="{!filterId}" size="1">
<apex:actionSupport event="onchange" rerender="list"/>
<apex:selectOptions value="{!listviewoptions}"/>
</apex:selectList>
</apex:panelGrid>
<apex:pageBlockSection>
<apex:dataList var="c" value="{!cases}" id="list">
{!c.subject}
</apex:dataList>
</apex:pageBlockSection>
</apex:form>
</apex:pageBlock>
</apex:page>

What are web tabs?
Custom Web tabs display any external Web-based application or Web page in a Salesforce tab. You can design Web tabs to include the sidebar or span across the entire page without the sidebar.
Custom tabs display custom object data or other web content embedded in the application.

How you will add an attachment from VF page? tell me the component names to achieve this functionality?
This example illustrates the way to upload a file and attach it against any record using Visualforce. The file that you upload using this will be available in the "Notes & Attachments" related list for the record.

Click here if you are looking to upload a file into "Documents".

Step 1: Create an Apex class named "attachmentsample" . Paste the code below.


public class attachmentsample {

public attachmentsample(ApexPages.StandardController controller) {

}
Public Attachment myfile;
Public Attachment getmyfile()
{
myfile = new Attachment();
return myfile;
}
 
Public Pagereference Savedoc()
{
String accid = System.currentPagereference().getParameters().get('id');

Attachment a = new Attachment(parentId = accid, name=myfile.name, body = myfile.body);

/* insert the attachment */
insert a;
return NULL;


}

Step 2:

Create a Visualforce page named "attachment" and paste the code below.


<apex:page standardController="Account" extensions="attachmentsample">

<apex:form >
  <apex:sectionHeader title="Upload a Attachment into Salesforce"/>
  <apex:pageblock >
  <apex:pageblocksection columns="1">
  <apex:inputfile value="{!myfile.body}" filename="{!myfile.Name}" />
  <apex:commandbutton value="Save" action="{!Savedoc}"/>
  </apex:pageblocksection>
  </apex:pageblock> 
</apex:form>

</apex:page>

Quick Test:
If you do not wish to do Step3 and 4 do this. Paste the following URL in your browser
http://yoursalesforceinstance.com/apex/attachment?id=0017000000eiDgy

ID should be a Valid Account Id of your instance.

Step 3:
Create a custom button (Detail Page button) on Account and select the new Visualforce page that you created as the source.

Step4:
Add the button created in Step3 to the Account Page layout.

You can test this by navigating to any account and clicking on the button that you created in Step3.
You may test

What is Dynamic Approval process?
https://www.salesforcetutorial.com/dynamic-approval-process-salesforce/

Flow of execution in validations, triggers & workflows?
1. The original record is loaded from the database (or initialized for an insert statement)
2. The new record field values are loaded from the request and overwrite the old values
3. All before triggers execute
4. System validation occurs, such as verifying that all required fields have a non-null value, and running any user-defined validation rules
5. The record is saved to the database, but not yet committed
6. All after triggers execute
7. Assignment rules execute
8. Auto-response rules execute
9. Workflow rules execute
10. If there are workflow field updates, the record is updated again
11. If the record was updated with workflow field updates, before and after triggers fire one more time (and only one more time)
12. Escalation rules execute
13. All DML operations are committed to the database
14. Post-commit logic executes, such as sending email

Difference between Trigger.new & 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.

Trigger events? & context variables?
Variable Usage
isExecuting Returns true if the current context for the Apex code is a trigger, not a Visualforce page, a Web service, or an executeanonymous() API call.
isInsert Returns true if this trigger was fired due to an insert operation, from the Salesforce user interface, Apex, or the API.
isUpdate Returns true if this trigger was fired due to an update operation, from the Salesforce user interface, Apex, or the API.
isDelete Returns true if this trigger was fired due to a delete operation, from the Salesforce user interface, Apex, or the API.
isBefore Returns true if this trigger was fired before any record was saved.
isAfter Returns true if this trigger was fired after all records were saved.
isUndelete Returns true if this trigger was fired after a record is recovered from the Recycle Bin (that is, after an undelete operation from the Salesforce user interface, Apex, or the API.)
new Returns a list of the new versions of the sObject records.
This sObject list is only available in insert, update, and undelete triggers, and the records can only be modified in before triggers.

newMap A map of IDs to the new versions of the sObject records.
This map is only available in before update, after insert, after update, and after undelete triggers.

old Returns a list of the old versions of the sObject records.
This sObject list is only available in update and delete triggers.

oldMap A map of IDs to the old versions of the sObject records.
This map is only available in update and delete triggers.

size The total number of records in a trigger invocation, both old and new.

Batch Apex?
Start
Execute
Finish

Will one workflow effects another workflow?
Yes If one workflow field update one field and there is another workflow which gets trigger (provided that on field update "Re-evaluate Workflow Rules after Field Change" is checked).
Check here for more details :
Field Updates That Re-evaluate Workflow Rules

Syntax for upsert & undelete trigger & Purpose undelete?
trigger AccountTrigger on Account( after insert, after update, before insert, before update)
{

    AccountTriggerHandler handler = new AccountTriggerHandler(Trigger.isExecuting, Trigger.size);
   
    if( Trigger.isInsert )
    {
        if(Trigger.isBefore)
        {
            handler.OnBeforeInsert(trigger.New);
        }
        else
        {
            handler.OnAfterInsert(trigger.New);
        }
    }
    else if ( Trigger.isUpdate )
    {
        if(Trigger.isBefore)
        {
            handler.OnBeforeUpdate(trigger.New ,trigger.Old,Trigger.NewMap,Trigger.OldMap);
        }
        else
        {
            handler.OnAfterUpdate(trigger.New ,trigger.Old,Trigger.NewMap,Trigger.OldMap);
        }
    }
}
public with sharing class AccountTriggerHandler
{
    private boolean m_isExecuting = false;
    private integer BatchSize = 0;
    public static boolean IsFromBachJob ;
    public static boolean isFromUploadAPI=false;
   
    public AccountTriggerHandler(boolean isExecuting, integer size)
    {
        m_isExecuting = isExecuting;
        BatchSize = size;
    }
           

    public void OnBeforeInsert(List<Account> newAccount)
    {
        system.debug('Account Trigger On Before Insert');
    }
    public void OnAfterInsert(List<Account> newAccount)
    {
        system.debug('Account Trigger On After Insert');
    }
    public void OnAfterUpdate( List<Account> newAccount, List<Account> oldAccount, Map<ID, Account> newAccountMap , Map<ID, Account> oldAccountMap )
    {
        system.debug('Account Trigger On After Update ');
        AccountActions.updateContact (newAccount);
    }
    public void OnBeforeUpdate( List<Account> newAccount, List<Account> oldAccount, Map<ID, Account> newAccountMap , Map<ID, Account> oldAccountMap )
    {
        system.debug('Account Trigger On Before Update ');
    }

    @future
    public static void OnAfterUpdateAsync(Set<ID> newAccountIDs)
    {

    }     
    public boolean IsTriggerContext
    {
        get{ return m_isExecuting;}
    }
   
    public boolean IsVisualforcePageContext
    {
        get{ return !IsTriggerContext;}
    }
   
    public boolean IsWebServiceContext
    {
        get{ return !IsTriggerContext;}
    }
   
    public boolean IsExecuteAnonymousContext
    {
        get{ return !IsTriggerContext;}
    }
}
Case management?
If we want to upload data through DataLoader, what the changes to be done?
-------------------------------------------------------------------------------------------------------------------------------------------

We have 3 objects Account, Contact, Opportunity. In a VF page, we need to display the names of contact & Opportunity which are related to Account.
<apex:page controller=”AccountRelatedContactsOpportunities”>
<apex:form>
<apex:pageBlock title=”Contacts List” id=”contacts_list”>
<apex:pageBlockTable value=”{! contacts }” var=”ct”>
<apex:column value=”{! ct.FirstName }”/>
<apex:column value=”{! ct.LastName }”/>
<apex:column value=”{! ct.Title }”/>
<apex:column value=”{! ct.Email }”/>
</apex:pageBlockTable>
</apex:pageBlock>
<apex:pageBlock title=”Opportunity List” id=”opportunity_list”>
<apex:pageBlockTable value=”{! opportunities }” var=”ot”>
<apex:column value=”{! ot.Name }”/>
<apex:column value=”{! ot.CloseDate }”/>
<apex:column value=”{! ot.StageName }”/>
<apex:column value=”{! ot.Amount }”/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>

public class AccountRelatedContactsOpportunities {

public List<Contact> getContacts() {
List<Contact> conresults = [Select Id, FirstName, LastName,Title,Email from Contact where accountid=’0012800000hVdfO’];
return conresults;
}
public List<Opportunity> getOpportunities() {
List<Opportunity> oppresults = [Select Id,CloseDate,Amount,StageName,Name from Opportunity where accountid=’0012800000hVdfO’];
return oppresults;
}

}
One object (s1) & 3 tasks (t1, t2, t3) are there. Each task performing discount related stuff. Write a trigger that should calculate the sum of 3 tasks. And if any task is modified than trigger should fire automatically & perform the same.
Ans: List<Task> listof tasks = [select id, name from Task where whatId=Trigger.new];

How can you convert a lead?
Manual
Trigger
Web Service

What is the custom settings ?
List Custom Settings
A type of custom setting that provides a reusable set of static data that can be accessed across your organization.
If you use a particular set of data frequently within your application, putting that data in a list custom setting streamlines access to it.
Data in list settings does not vary with profile or user, but is available organization-wide. Examples of list data include two-letter state abbreviations, international dialing prefixes, and catalog numbers for products.
Because the data is cached, access is low-cost and efficient: you don't have to use SOQL queries that count against your governor limits.

CSR_Settings__c settings = CSR_Settings__c.getInstance('csr');
String  CSR_USER_ID      = settings.CSR_User_ID__c;
Decimal OPP_MIN_VALUE    = settings.Opp_Minimum_Value__c;

Hierarchy Custom Settings
A type of custom setting that uses a built-in hierarchical logic that lets you “personalize” settings for specific profiles or users.
The hierarchy logic checks the organization, profile, and user settings for the current user and returns the most specific, or “lowest,” value.
In the hierarchy, settings for an organization are overridden by profile settings, which, in turn, are overridden by user settings.
CustomSettingName__c mc = CustomSettingName__c.getOrgDefaults();

Difference between SOSL and SOQL in Salesforce ?
SOQL
SOQL (Salesforce Object Query Language ) retrieves the records from the database by using “SELECT” keyword.
By Using SOQL we can know in Which objects or fields the data resides
We can retrieve data from single object or from multiple objects that are related to each other.
We can Query on only one table.
Used In: List Views, Reports, Apex
Indexing Happens: Synchronously (Can have Custom Indexes or Standard Indexes)
Search Focus: Accuracy. Gives full set of results that match criteria.
Search Scope : Can search 1 object at a time.
SOSL
SOSL(Salesforce Object Search Language) retrieves the records from the database by using the “FIND” keyword.
By using SOSL, we don’t know in which object or field the data resides.
We can retrieve multiple objects and field values efficiently when the objects may or may not be related to each other.
We can query on multiple tables.
    Used In: (Global, Sidebar, Advanced) Search, Apex
Indexing Happens: Happens Asynchronously. Usually 2-3 min. If over 9000 records loaded at one time, the excess are moved to the bulk index queue. (slower).
Search Focus: Relevance & Speed. Similar to Google Search. Weightage placed on recently viewed records.
Search Scope : Can search multiple objects at a time.

What is Sales cloud & Service cloud?
Sales Cloud:
Sales Cloud is mainly focused towards Sales and Marketing for business development.”Sales Cloud” refers to the Sales module in salesforce.com.
It includes Leads, Accounts, Contacts, Contracts, Opportunities, Products, Price books, Quotes, and Campaigns .
It includes features such as Web-to-lead to support online lead capture, with auto-response rules. It is designed to be for completely setup for the entire sales process.
You can use this to help your company to generate revenue or increase revenue.

Service Cloud:
Service Cloud” refers to the “service” or “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, and billing.
You use this to help make people happy.

can a Checkbox as controlling field?
Yes we can make a Checkbox as controlling field.

What is System.RunAs ()?
Generally, all Apex code runs in system mode, where the permissions and record sharing of the current user are not taken into account.
The system method runAs enables you to write test methods that change the user context to an existing user or a new user so that the user’s record sharing is enforced.
The runAs method doesn’t enforce user permissions or field-level permissions, only record sharing.
You can use runAs only in test methods.
The original system context is started again after all runAs test methods complete.
The runAs method ignores user license limits. You can create new users with runAs even if your organization has no additional user licenses.

Explain Test.setPage ()?

Data Migration?
Identify the required fields:

The first step is to list the fields involved in the migration process:

Required fields
Optional fields
System Generated fields
Then identify any additional fields that might be required, like:

Legacy IDs
Business rules
Determine the order of migration

In Salesforce, relationships that exist between objects and dependencies dictate the order of migration. For example, all accounts have owners, and opportunities are associated with an account. In this case, the order would be to

Load users
Load accounts
Load opportunities
Relationships are expressed through related lists and lookups in a Salesforce application while IDs(foreign key) create relationships in a database.

Data Migration Workbook

Create and follow a data migration workbook throughout the scope of migration. This is a consolidated workbook that holds the data mapping for each object involved in the process. A single template with multiple tabs (one each for each mapping object) including a DM checklist and storage requirements. The workbook can be personalized based on your own business requirements.

Pre-data migration considerations:

Create and set up a user with a system administrator profile for data migration.
Complete system configuration.
Set up roles/profiles.
Be sure to store all possible legacy IDs for a record in Salesforce. (This can help with troubleshooting later on.)
Confirm that record types and picklist values are defined.
Set up every single product/currency combination in the pricebooks if it will be used in Salesforce. (This will need to be loaded into the standard pricebook first.)
Proper mapping needs to be defined.
Data load considerations:

Clean and optimize your data before loading. It’s always good practice to standardize, clean, de-dupe and validate source data prior to migration.
Use Bulk API for better throughput, especially when working with large data volumes to increase load speed.
Disable and defer what you can. When you know your data is clean, you can safely disable the processes that you would normally have in place to protect against data entry errors in batch loads, or made by users during daily operations. All of these operations can add substantial time to inserts — complex triggers in particular. These are the first things you should investigate when you debug a slow load.
While loading large data volumes, the calculations can take a considerable amount of time. We can probably increase load performance by deferring the sharing calculations until after the load is complete.
Some additional rules for migration:

Clearly define the scope of the project.
The process builder must be aware of source format and target (Salesforce) required data format.
Your migration process must have the ability to identify failed and successful records. The common approach is to have an extra column in a source table that stores the target table’s unique ID. That way, if there are fewer failure records after the first iteration, you can re-execute the process, which will only pick failed records that are not yet migrated.
Actively refine the scope of the project through targeted profiling and auditing.
Minimize the amount of data to be migrated.
Profile and audit all source data in the scope before writing mapping specifications.
Define a realistic project budget and timeline based on knowledge of data issues.
Aim to volume-test all data in the scope as early as possible at the unit level.
These best practices can help you prepare for and execute a successful large-volume Salesforce data migration.
Roll-up summary?
Master Detail Relationship

What are default methods for Batch Apex?
Ans: start(), execute() and finish()

Mention changing what may cause data loss?
Changing to or from type Date or Date/Time
Changing to Number from any other type
Changing to Percent from any other type
Changing to Currency from any other type
Changing from Checkbox to any other type
Changing from Picklist (Multi-Select) to any other type
Changing to Picklist (Multi-Select) from any other type
Currently defined picklist values are retained when you change a picklist to a multi-select picklist.
If records contain values that are not in the picklist definition, those values are deleted from those records when the data type changes.
Changing from Auto Number to any other type
Changing to Auto Number from any type except Text
Changing from Text to Picklist
Changing from Text Area (Long) to any type except Email, Phone, Text, Text Area, or URL

Mention what is the difference between isNull and isBlank?
isNull: It supports for number field
isBlank: It supports for Text field

Is it possible to schedule a dynamic dashboard in Salesforce?
What does it indicate if an error state this “list has no rows for assignment”?
'List has no rows for assignment to SObject' error. The error "List has no rows for assignment to SObject" occurs when query doesn't return any rows.
While a SELECT normally returns an array/list, these statements are using the shorthand syntax that assumes only one row is returned.

------------------------------------------------------------------------------------------------------------------

5. What are activities
Task
Events

6. What is the difference between Task and Event
An event is a calendar event scheduled for a specific day and time.
Examples of events are:

1)      Meetings
2)      Scheduled Conference Calls

A task is an activity not scheduled for an exact day and time. You can specify a due date for a task or there may not be a particular time or date that the tasks or activities need to be completed by.

Examples of tasks are:

- A list of phone calls you need to make.
-  An email that needs to be sent.

------------------------------------------------------------------------------------------------
1. What are recursive triggers. How can we avoid the recursion problem
Recursion occurs when same code is executed again and again. It can lead to infinite loop and which can result to governor limit sometime.
Sometime it can also result in unexpected output.
public class RecursiveTriggerHandler{
public static Boolean isFirstTime = true;
}
trigger SampleTrigger on Contact (after update){

Set<String> accIdSet = new Set<String>();

if(RecursiveTriggerHandler.isFirstTime){
RecursiveTriggerHandler.isFirstTime = false;

for(Contact conObj : Trigger.New){
if(conObj.name != 'SFDC'){
accIdSet.add(conObj.accountId);
}
}

// Use accIdSet in some way
}
}
Action Function: –
Action Function is used in the Visualforce page to call the Service Side method using JavaScript and does not add the Ajax Request before calling the Controller method.

<apex:actionFunction name=”myactionfun” action=”{!actionFunctionTest}” reRender=”pgBlock, pbSection” />

Let us talk about above example. In any Javascript Method where the name of ActionFunction ( In our example myactionfun() ) will be invoked, it will call the controller method name actionFunctionTest. Example myactionfun();

Action Support: –
As the name indicates action support is used to provide the support to the input field where we can not get event either manually or external event. It adds the AJAX request to VF page and then Calls the Controller method. For

For example, if we want to call any server side method when input changes then we will go for action support because we can not get any event for this.

<apex:inputText value=”{!dummyString}” >
  <apex:actionSupport event=”onchange” action=”{!actionSupportTest}”                                     reRender=”pgBlock, pbSection” />
</apex:inputText>

Action Poller: –
A timer that sends an AJAX request to the server according to a time interval that you specify. Each request can result in a full or partial page update.

<apex:actionPoller action=”{!incrementCounter}” reRender=”counter” interval=”15″ enabled = “true” />

Enabled attribute is used to make poller as active or inactive by default value is true. If we provide false then poller will be inactivate.

-------------------------------------------------------------------------------------------------
1. What is Apex
Ans: It is the in-house technology of salesforce.com which is similar to Java programming with object oriented concepts and to write our own custom logic.

2. What is an S-Control
Ans: S-Controls are the predominant salesforce.com widgets which are completely based on Javascript. These are hosted by salesforce but executed at client side. S-Controls are superseded by Visualforce now.

3. What is a Visualforce Page
Ans: As I said in the above answer, S-controls are superseded by Visulaforce, Visualforce is the new markup language from salesforce, by using which, We can render the standard styles of salesforce. We can still use HTML here in Visualforce. Each visualforce tag always begins with "apex" namespace. All the design part can be acomplished by using Visualforce Markup Language and the business logic can be written in custom controllers associated with the Page.

4. Will Visual force still supports the mege fields usage like S-control.
Ans: Yes. Just like S-Controls, Visualforce Pages support embedded merge fields, like the {!$User.FirstName} used in the example.

5. Where can I write my Visualforce code
Ans: You can write the code basically in 3 ways. One go to, setup->App Setup->Develop->Pages and create new Visulaforce page. While creating the Page, You will find a salesforce editor. You can write your Visualforce content there. Or go to Setup -> My Personal Information -> Personal Information -> Edit check the checkbox development mode. When you run the page like this, https://ap1.salesforce.com/apex/MyTestPage. you will find the Page editor at the bottom of the page. You can write you page as well as the controller class associated with it, there it self. OR Using EclipseIDE you can create the Visulaforce page and write the code.

Batch Apex

1. What are transaction limits in apex? Total number of SOQL queries issued1 - 100 Total number of records retrieved by SOQL queries - 50...