Tuesday, 11 April 2017

all sfdc(@feature Annotation)

What is @feature Annotation?
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. The specified parameters must be primitive data types, arrays of primitive data types, or collections of primitive data types. Methods with the future annotation cannot take sObjects or objects as arguments.

To make a method in a class execute asynchronously, define the method with the future annotation. For example:

global class MyFutureClass {

  static void myMethod(String a, Integer i) {
    System.debug('Method called with: ' + a + ' and ' + i);
    // Perform long-running code
Specify (callout=true) to allow callouts in a future method. Specify (callout=false) to prevent a method from making callouts.

The following snippet shows how to specify that a method executes a callout:

@future (callout=true)
  public static void doCalloutFromFuture() {
   //Add code to perform callout
Future Method Considerations
·         Remember that any method using the future annotation requires special consideration because the method does not necessarily execute in the same order it is called.
·             Methods with the future annotation cannot be used in Visualforce controllers in either getMethodName or setMethodName methods, nor in the constructor.
·             You cannot call a method annotated with future from a method that also has the future annotation. Nor can you call a trigger from an annotated method that calls another annotated method.
·             The get Content and getContentAsPDFPageReference methods cannot be used in methods with the future annotation.
·         Use @future when you want to run methods asynchronously. You can use @future for the following use cases
(i) Call to external web services
(ii) To perform some background calculations.

10 future calls per Apex invocation
Future calls in a 24 hour period, which is 250,000 or the number of user licenses in your organization multiplied by 200, whichever is greater
You cannot call a method annotated with @future from a method that also has the @future annotation
·         What is Future Method:

A future method runs in the background, asynchronously. You can call a future method for executing long-running operations, such as callouts to external Web services or any operation you'd like to run in its own thread, on its own time.

When to use Future Method:

If you want to make the execution of the apex program to run asynchronously then we make use of future method.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.

Apex class with Future Method:
public class AccountProcessor 
  public static void countContacts(Set setId) 
      List lstAccount = [select id,Number_of_Contacts__c , (select id from contacts ) from account where id in :setId ];
      for( Account acc : lstAccount )
          List lstCont = acc.contacts ;
          acc.Number_of_Contacts__c = lstCont.size();
      update lstAccount;
public class AccountProcessorTest {
    public static testmethod void TestAccountProcessorTest()
        Account a = new Account();
        a.Name = 'Test Account';
        Insert a;

        Contact cont = New Contact();
        cont.FirstName ='Bob';
        cont.LastName ='Masters';
        cont.AccountId = a.Id;
        Insert cont;
        set setAccId = new Set();

        Account ACC = [select Number_of_Contacts__c from Account where id = :a.id LIMIT 1];
        System.assertEquals ( Integer.valueOf(ACC.Number_of_Contacts__c) ,1);
global class ScheduledDispatcher Implements Schedulable{

    public Interface IScheduleDispached{
        void execute(SchedulableContext sc);

    global void execute(SchedulableContext sc){
        Type targetType = Type.forName('{HANDLERNAME');
        if(targetType != null){
            IScheduleDispached obj = (IScheduleDispached)targetType.newInstance();


public class {HANDLERNAME} implements ScheduledDispatcher.IScheduleDispached {

  public void execute(SchedulableContext sc)

        //Call your Future Method Here



1) Methods with the future annotation must be static methods
2) can only return a void type
3) The specified parameters must be primitive data types, arrays of primitive data types, or collections of primitive data types
4) Methods with the future annotation cannot take sObjects or objects as arguments.
5) You can invoke future methods the same way you invoke any other method. However, a future method can’t invoke another future method
6) No more than 50 method calls per Apex invocation
7) Asynchronous calls, such as @future or executeBatch, called in a startTest, stopTest block, do not count against your limits for the number of queued jobs
8) The maximum number of future method invocations per a 24-hour period is 250,000 or the number of user licenses in your organization multiplied by 200, whichever is greater
9) To test methods defined with the future annotation, call the class containing the method in a startTest(), stopTest() code block. All asynchronous calls made after the startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously

Salesforce one org to another salesforce org integration
>One of the ways to Integrate two Salesforce Instances will be using oauth for session management and using REST API

>Lets Assume you have SalesforceA as Source ORG and SalesforceB as Destination ORG .Now lets assume flow of data is from SalesforceA to SalesforceB Instance

>1)For oauth 2.0 in Destination org(SalesforceB) create a Connected App .To help you configure the Connected App in Destination below screenshot should assist.Callback Url may not be of any significant as we are using User-Name Password flow model.You will obtain client secret,consumer key in this process and one should store in Source org custom object or custom setting

![enter image description here][1]

>2)In your source org create a Remote site settings with url as the URL of the Destination Instance

>3)Create a Integration User in the Destination org whose credentials you will use to call API from Salesforce Source ORG

>4)Use the username,password and security token(Also i would prefer setting password never expires here for integration User) and also client secret and consumer key in a custom object or custom setting (Protected) in Source org.

The below code is sample code to get authenticated and how to use access token to further make any API call

    Settings__c ts=settings;//Here write a sample query or fetch from custom settings the consumer ,client secret and username and password of destination org
    String clientId = ts.ConsumerKey__c;
    String clientSecret = ts.Client_Secret__c;
    String username=ts.Username__c;
    String password=ts.Password__c+ts.SecurityToken__c;
    String reqbody = 'grant_type=password&client_id='+clientId+'&client_secret='+clientSecret+'&username='+username+'&password='+password;

    Http h = new Http();
    HttpRequest req = new HttpRequest();
    req.setEndpoint(ts.URL__c+'/services/oauth2/token');//Note if my domain is set up use the proper domain name else use login.salesforce.com for prod or developer or test.salesforce.com for sandbox instance

    HttpResponse res = h.send(req);
    OAuth2 objAuthenticationInfo = (OAuth2)JSON.deserialize(res.getbody(), OAuth2.class);
    RequestWrapper reqst=new RequestWrapper();
      Http h1 = new Http();
      HttpRequest req1 = new HttpRequest();
      req1.setHeader('Authorization','Bearer '+objAuthenticationInfo.access_token);
      req1.setBody(jsonstr);//Send JSON body
      req1.setEndpoint(ts.URL__c+URL);//URL will be your Salesforce REST API end point where you will do POST,PUT,DELETE orGET
      HttpResponse res1 = h1.send(req1);
      system.debug('RESPONSE_BODY'+res1 .getbody());
>To deserialize the initial response here is wrapper class the above code uses

    /*To get aouthentication detail Wrapper*/
    public class OAuth2{
     public String id{get;set;}
     public String issued_at{get;set;}
     public String instance_url{get;set;}
     public String signature{get;set;}
     public String access_token{get;set;}   

What is Apex Sharing? How to share a records via apex?

Sharing rules, let us make automatic exceptions to organization-wide defaults for particular groups of users.Sharing rules can never be stricter than our org-wide default settings.We can extend the organization wide default setting with sharing rules.
Example – If any object is private with org-wide default  then we can extend the access to public read only or public read write with sharing rule.
Salesforce provide a way by which we can create sharing rule by only point and click  from the salesforce standard. You can set any criteria and give access to the object’s record . Example – Suppose u need to create a sharing rule for lead object when the lead field “Is_public” become true then you can easily add this criteria and give public access to the particular User or group etc.
But some cases are there where we can’t use the standard sharing rule functionality that’s why we need to create sharing rules with apex.
Let’s take a case example  –  I have a field “Reports to” in case object and this field is lookup to User object and we need to give public access to that user for their particular record. Suppose when a case is created and we select some user in the “Reports to” field then we want to give public access to this selected user for that record.So it is not possible with standard sharing rules. We need to create sharing rule for case object via apex.
Here I am sharing the code for how to create sharing rule for any object via Apex,each object has their own sharing object for case it is “CaseShare ” .We need to write down a trigger on case :
trigger ShareWithReportingMng on Case (after insert) {
    List csShareList = new List();
    for( Case cs : trigger.new ) {
        if( cs.Reports_to__c != NULL ) {
            // Create a new caseShare object for each case where reports_to__c field is not NULL.
            CaseShare csShare = new CaseShare();
            // Give Read write access to that user for this particular case record.
            csShare.CaseAccessLevel = 'edit';
            // Assign case Id of case record.
            csShare.CaseId = cs.id;
            // Assign user id to grant read write access to this particular case record.
            csShare.UserOrGroupId = cs.Reports_to__c;
            csShareList.add( csShare );
    if( csShareList != null && csShareList.size() != 0 ) {
        try {
            insert csShareList;
        }catch( Exception e ) {

So now you can create sharing rules from apex as above and delete that sharing when needed with apex(delete event).
Considerations and Limits of Sharing Rules

  • Sharing Rules cannot be stricter than Organization Wide Defaults. If access needs to be restricted, another type of security should be used.  Sharing rules are typically used to extend access to records.
  • Manual Sharing is only available on individual records, it is not available for all records of a certain object.
  • Sharing Rules are only applicable on records that have Private or Public Read Only access.
  • With Sharing Rules you have the option to give read only or read/write access to records.  We recommend being very conscious of what level of security users really need (i.e. is the access for informational purposes only or full collaboration).
  • When setting Automatic and Manual Sharing users and admins have the ability to define if the security should be extended to related records.  Make sure that extending the security makes sense before making the final decision to give this access.

Using the this Keyword

There are two different ways of using the this keyword.

You can use the this keyword in dot notation, without parenthesis, to represent the current instance of the class in which it appears. Use this form of the this keyword to access instance variables and methods. For example:

public class myTestThis {


string s;  {      this.s = 'TestString'; }}

In the above example, the class myTestThis declares an instance variable s. The initialization code populates the variable using the this keyword

Or you can use the this keyword to do constructor chaining, that is, in one constructor, call another constructor. In this format, use the this keyword with parentheses. For example:



public class testThis {

// First constructor for the class. It requires a string parameter.

   public testThis(string s2) {   }

// Second constructor for the class. It does not require a parameter.

// This constructor calls the first constructor using the this keyword.

   public testThis() {


Using the transient Keyword

Use the transient keyword to declare instance variables that can't be saved, and shouldn't be transmitted as part of the view state for a Visualforce page. For example:
Transient Integer currentTotal;
You can also use the transient keyword in Apex classes that are serializable, namely in controllers, controller extensions, or classes that implement the Batchable or Schedulable interface. In addition, you can use transient in classes that define the types of fields declared in the serializable classes.
Declaring variables as transient reduces view state size. A common use case for the transient keyword is a field on a Visualforce page that is needed only for the duration of a page request, but should not be part of the page's view state and would use too many system resources to be recomputed many times during a request.
Some Apex objects are automatically considered transient, that is, their value does not get saved as part of the page's view state. These objects include the following:
·         PageReferences
·         XmlStream classes
·         Collections automatically marked as transient only if the type of object that they hold is automatically marked as transient, such as a collection of Savepoints
·         Most of the objects generated by system methods, such as Schema.getGlobalDescribe.
·         JSONParser class instances.
Static variables also don't get transmitted through the view state.
The following example contains both a Visualforce page and a custom controller. Clicking the refresh button on the page causes the transient date to be updated because it is being recreated each time the page is refreshed. The non-transient date continues to have its original value, which has been deserialized from the view state, so it remains the same.
  T1: {!t1}
  T2: {!t2}

public class ExampleController {
    DateTime t1;
    transient DateTime t2;
    public String getT1() {
        if (t1 == null) t1 = System.now();
        return '' + t1;
    public String getT2() {
        if (t2 == null) t2 = System.now();
        return '' + t2;


An Apex annotation modifies the way that a method or class is used, similar to annotations in Java.
Annotations are defined with an initial @ symbol, followed by the appropriate keyword. To add an annotation to a method, specify it immediately before the method or class definition. For example:
·         @AuraEnabled
·         @Deprecated
·         @Future
·         global class MyClass {
·              @future
·              Public static void myMethod(String a)
·              {
·                   //long-running Apex code
·              }
·         }
·         @InvocableMethod
·         @InvocableVariable
·         @IsTest
·         @ReadOnly
·         @RemoteAction
·         @TestSetup
·         @TestVisible
·         Apex REST annotations:
·         @RestResource(urlMapping='/yourUrl')
·         @HttpDelete
·         @HttpGet
·         @HttpPatch
·         @HttpPost
·         @HttpPut

ReadOnly Annotation

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.
Visualforce pages can call controller methods with the @ReadOnly annotation, and those methods will run with the same relaxed restrictions. To increase other Visualforce-specific limits, such as the size of a collection that can be used by an iteration component like >, you can set the readonly attribute on the > tag to true. For more information, see Working with Large Sets of Data in the Visualforce Developer's Guide.

RemoteAction Annotation

Methods with the RemoteAction annotation must be static and either global or public.

Apex @RemoteAction methods must be static and either global or public.
Your method can take Apex primitives, collections, typed and generic sObjects, and user-defined Apex classes and interfaces as arguments. Generic sObjects must have an ID or sobjectType value to identify actual type. Interface parameters must have an apexType to identify actual type. Your method can return Apex primitives, sObjects, collections, user-defined Apex classes and enums, SaveResultUpsertResultDeleteResultSelectOption, or PageReference.

Classes defined with the isTest annotation don't count against your organization limit of 3 MB for all Apex code.

IsTest(SeeAllData=true) Annotation

For Apex code saved using Salesforce API version 24.0 and later, use the isTest(SeeAllData=true) annotation to grant test classes and individual test methods access to all data in the organization, including pre-existing data that the test didn’t create. Starting with Apex code saved using Salesforce API version 24.0, test methods don’t have access by default to pre-existing data in the organization. However, test code saved against Salesforce API version 23.0 and earlier continues to have access to all data in the organization and its data access is unchanged. See Isolation of Test Data from Organization Data in Unit Tests.
Considerations for the IsTest(SeeAllData=true) Annotation
·         If a test class is defined with the isTest(SeeAllData=true) annotation, this annotation applies to all its test methods whether the test methods are defined with the @isTest annotation or the testmethod keyword.
·         The isTest(SeeAllData=true) annotation is used to open up data access when applied at the class or method level. However, using isTest(SeeAllData=false) on a method doesn’t restrict organization data access for that method if the containing class has already been defined with the isTest(SeeAllData=true) annotation. In this case, the method will still have access to all the data in the organization.
The JavaScript invoked if the onclick event occurs that is, if the user clicks the tabPanel.
The JavaScript invoked if the ondblclick event occurs that is, if the user clicks the tabPanel twice.
The JavaScript invoked if the onkeydown event occurs that is, if the user presses a keyboard key.
The JavaScript invoked if the onkeypress event occurs that is, if the user presses or holds down a keyboard key.
The JavaScript invoked if the onkeyup event occurs that is, if the user releases a keyboard key.
The JavaScript invoked if the onmousedown event occurs that is, if the user clicks a mouse button.
The JavaScript invoked if the onmousemove event occurs that is, if the user moves the mouse pointer.
The JavaScript invoked if the onmouseout event occurs that is, if the user moves the mouse pointer away from the tabPanel component.
The JavaScript invoked if the onmouseover event occurs that is, if the user moves the mouse pointer over the tabPanel component.
The JavaScript invoked if the onmouseup event occurs that is, if the user releases the mouse button.
A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true.
The ID of one or more components that are redrawn when the result of an AJAX update request returns to the client. This value can be a single ID, a comma-separated list of IDs, or a merge field expression for a list or collection of IDs. Note that this value only applies when the switchType attribute is set to "ajax".
The name of the default selected tab when the page loads. This value must match the name attribute on a child tab component. If the value attribute is defined, the selectedTab attribute is ignored.
The style used to display the tabPanel component, used primarily for adding inline CSS styles.
The style class used to display the tabPanel component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet.
The implementation method for switching between tabs. Possible values include "client", "server", and "ajax". If not specified, this value defaults to "server".
The style class used to display the tabPanel component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet.
The text to display as a tooltip when the user's mouse pointer hovers over this component.
The current active tab. You can specify this with an expression to dynamically control the active tab. For example, value="{!TabInFocus}", where TabInFocus is a variable set by a custom controller. The value of this attribute overrides the one set in selectedTab.
Using the final Keyword. You can use the final keyword to modify variables. Final variables can only be assigned a value once, either when you declare a variable or inside a constructor. ...
Static final variables can be changed in static initialization code or where defined.
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, 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 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 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 external ID to refer to records. You can have multiple records with the same external ID (though it is not recommended, as it will defeat the purpose of the external id)
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.A controller extension is an Apex class that extends the functionality of a standard or custom controller. 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.
 What are Custom Controllers and Controller Extensions?
A custom controller is an Apex class that implements all of the logic for a page without leveraging a standard controller. 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.
A controller extension is an Apex class that extends the functionality of a standard or custom controller. 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.
Although custom controllers and controller extension classes execute in system mode and thereby ignore user permissions and field-level security, you can choose whether they respect a user's organization-wide defaults, role hierarchy, and sharing rules by using the with sharing keywords in the class definition. For information, see
 “Using the with sharing or without sharing Keywords” in the Apex Developer Guide.
 what is the difference between workflow and process builder in salesforce?
 With process builder, you can also update all child records starting from the parent record, which is not possible with workflows (only vice versa is possible using cross object field updates). ...
 You can use the Process Builder to perform more actions than with workflow: Create a record. Update any related record.
 You can use the Process Builder to perform more actions than with workflow:
Create a record
Update any related record
Use a quick action to create a record, update a record, or log a call
Launch a flow
Send an email
Post to Chatter
Submit for approval
Call apex methods
But the process builder doesn’t support outbound messages.
Workflow does only 4 actions
Create Task
Update Fiel
Email Alert
Outbound Message
Workflow: Workflow is business logic that evaluates records as they are created and updated and determines if an automated action needs to occur. In a way it allows records to speak up or do something – update data, notify people or external systems.
It is part of Salesforce platform from very long time.
Recently Salesforce enhanced the workflow features with a new UI tool called Lightning Process builder.
Process Builder:
The Lightning Process Builder is a new workflow tool that helps you easily automate your business processes by providing a powerful and user-friendly visual representation of your process as you build it. Instead of doing this repetitive work manually, you can configure processes to do it automatically. The Process Builder’s simple and powerful design allows you to automate processes.
Above both tool don't have any interaction with end user they work behind the scene.
Flow:Visual Workflow lets you automate business processes by building flows and distributing them to the right users or systems. A flow is an application that can execute logic, interact with the Salesforce database, call Apex classes, and collect data from users. You can build flows by using the Cloud Flow Designer.
(1) Workflow : inbuilt functionality, used on single obj /master-detail

 (2) Trigger : Used for complex business process in which multiple Obj can handle. 

Before  jump  into coding check first is it possible to solve an issue using wfr.

Users with the “Two-Factor Authentication for User Interface Logins” permission have to provide a second factor, such as a mobile authenticator app or U2F security key, each time they log in to Salesforce.

Salesforce Identity Verification

When a user logs in from outside a trusted IP range and uses a browser or app we don’t recognize, the user is challenged to verify identity. We use the highest-priority verification method available for each user. In order of priority, the methods are:
1.   Verification via push notification or location-based automated verification with the Salesforce Authenticator mobile app (version 2 or later) connected to the user’s account.
2.   Verification via a U2F security key registered with the user’s account.
3.   Verification code generated by a mobile authenticator app connected to the user’s account.
4.   Verification code sent via SMS to the user’s verified mobile phone.
5.   Verification code sent via email to the user’s email address.
After identity verification is successful, the user doesn’t have to verify identity again from that browser or app, unless the user:
§  Manually clears browser cookies, sets the browser to delete cookies, or browses in private or incognito mode
§  Deselects Don’t ask again on the identity verification page

Org Policies That Require Two-Factor Authentication

You can set policies that require a second level of authentication on every login, every login through the API (for developers and client applications), or for access to specific features. Your users can provide the second factor by downloading and installing a mobile authenticator app, such as the Salesforce Authenticator app or the Google Authenticator app, on their mobile device. They can also use a U2F security key as the second factor. After they connect an authenticator app or register a security key with their account in Salesforce, they use them whenever your org’s policies require two-factor authentication.
The Salesforce Authenticator mobile app (version 2 and later) sends a push notification to the user’s mobile device when activity on the Salesforce account requires identity verification. The user responds on the mobile device to verify or block the activity. The user can enable location services for the app and automate verifications from trusted locations, such as a home or office. Salesforce Authenticator also generates verification codes, sometimes called “time-based one-time passwords” (TOTPs). Users can choose to enter a password plus the code instead of responding to a push notification from the app for two-factor verification. Or they can get a verification code from another authenticator app.
If users lose or forget the device they usually use for two-factor authentication, you can generate a temporary verification code for them. You set when the code expires, from 1 to 24 hours after you generate it. Your user can use the code multiple times until it expires. A user can have only one temporary code at a time. If a user needs a new code while the old code is still valid, you can expire the old code, then generate a new one. Users can expire their own valid codes in their personal settings.

Salesforce.com is a cloud computing and social enterprise software-as-a-service (SaaS) provider based in San Francisco. It was founded in March 1999, in part by former Oracle executive Marc Benioff.

Platform as a Service (PaaS) The platform is infrastructure for the development of software applications. ... Many variations exist on this acronym, including SaaS (Software as a Service), IaaS (Infrastructure as a Service), and so forth. PaaS is a category within the umbrella of cloud computing
2. What is Data Loader?
Data Loader is a stand-alone tool to process bulk records. With Dataloader we can process maximum of 5 million records. Most of the time we use only Dataloader. Default batch size of the Dataloader is 200.
3. Which operations we can perform on dataloader?
Insert (Inserting brand new records, no need of ID)
Update (Updating the existing records based on the record ID)
Upsert (To Upsert we should have one external ID field on the object, based on the external id field if the value already exists it will update, if doesn't exist then it will insert)
Delete (Delete the records based on the id provided, to delete we need only id, deleted records can be found in recycle bin)
Hard delete (Delete the records based on the id provided, to delete we need only id, deleted records can't be found in recycle bin, Note: If we enable bulk API in data loader settings then only we can perform Hard delete.)
Export (From any object we can export records based on the SOQL query, Note: We can't export deleted records which are there in the recycle bin)
Export all (From any object we can export records based on the SOQL query, Note: Using Export all we can export deleted records which are there in the recycle bin also)
4. Data loader or Import wizard supports which file format?
.CSV (Comma Separated Values)
5. What is the filed mapping file format of the data loader?
6. How to insert null values into dataloader?
In dataloader settings we should enable 'insert null values' checkbox otherwise we can't insert null values.
7. What is external ID?
Suppose we have account table in Salesforce and account table outside of the Salesforce (ex: .csv file, sql database). In Salesforce all the records can be identified with record id and outside of the Salesforce we can't recognize records with Salesforce id that is the reason to compare outside table and salesforce table in Salesforce for one of the field we have to enable external ID (we can enable external id for text, number, auto number and email). If we enable external id we can compare that particular column with the column which is available in external table. While comparing if the both column values are same then it will update otherwise it will insert.
8. Maximum batch size of data loader?
10,000 records and minimum 1 record.
9. What is default batch size if we enable bulk API?
2,000 records.

Process order for automation rules and Apex triggers:
When you're implementing processes that will automate tasks or jobs that need to be performed it always helps to know the order that they'll be processed. We'll go over the logic that is followed.
  1. Old record loaded from database (or initialized for new inserts)
  2. New record values overwrite old values
  3. System Validation Rules (If inserting Opportunity Products, Custom Validation Rules will also fire in addition to System Validation Rules)
  4. All Apex before triggers (EE / UE only)
  5. Custom Validation Rules
  6. Record saved to database (but not committed)
  7. Record reloaded from database
  8. All Apex after triggers (EE / UE only)
  9. Assignment rules
10. Auto-response rules
11. Workflow rules
12. Processes
13. Escalation rules
14. Parent Rollup Summary Formula value updated (if present)
15. Database commit
16. Post-commit logic (sending email)
  NOTE: There's no way to control the order of execution within each group above.
Workflow field updates that run based on an approval process or time-dependent action don't trigger any rules.
Formula fields don't execute in this way. They calculate and display their results in real-time whenever the field is accessed in any way. For example, if a Workflow Rule uses a Formula Field in its criteria or formula, the formula field is evaluated when the Workflow Rule criteria is checked.

1. What is Batch Apex?
We can call the apex code by creating object for the class (or) if the variables or methods are static then we can call with class name.
Apex Code in the trigger will execute automatically for the DML operations.
If you want to execute apex code on a specific time then we should write batch class.
With Batch Apex we can process maximum of 50 million records.
Batch Apex is asynchronous (execute in future context).
While writing the batch class we should inherit Database.Batchable interface.
Database is a built in global class which contains inner global interface.

2. What are the Batch Apex methods?
Since we are inheriting Database.Batchable interface we should implement all the method prototypes declared in the interface.
We should implement the following global methods -
start: It will prepare the records to process and execute only one time.
execute: It will take the records prepared in start method and split those records into batches and it will execute multiple times. For example if the start method is returning 1000 records then execute method executes 5 times if you don't mention the batch size (Default Batch Size is: 200). Maximum batch size is: 2000.
finish: We can perform post commit logic like sending emails with the success or error information. It will execute only one time.
Batch Class Syntax:
 //Database is Class provided by Salesforce.
 //Batchable is an global interface which is inside of the Database class.
 //Batchable include 3 method prototypes: 1. start 2. execute 3. finish
 //start and finish methods will execute only one time.
 //execute method executes multiple times.
 global class BatchUsage implements Database.Batchable , Database.Stateful {
  //at a time we can inherit multiple interfaces but we cannot inherit multiple classes.
  //By default batch class is stateless (variable info. store in one method cannot be remembered in other method),
  //to make it stateful we should inherit Database.Stateful interface.
  String name = '';
  global Database.queryLocator start(Database.BatchableContext bc) {
   //From asynchronous to asynchronous we cannot call
   //(from batch class we cannot call future mehthod vice versa.).
   name += 'start';
   system.debug('@@@Start Method: '+name);
   //Collects the records to process. It will forward these records to execute method.
   //If we use Iterable as return type for this start method it can hold
   //max. of 50k records only.
   //If we use Database.queryLocator as return type for this start method it can hold
   //max. of 50 million records.
   return Database.getQueryLocator('select id, name, Location__c from Department__c where Location__c = \'\'');
  global void execute(Database.BatchableContext bc, LIST sObjLst) {
   name += 'execute';
   system.debug('@@@Execute Method: '+name);
   //Split the records forwarded by start method into batches.
   //Default batch size is: 200.
   //Max. batch size is: 2000.
   List depUPdLst = new List();
   for(SObject sObj: sObjLst) {
    Department__c dept = (Department__c) sObj;//Type Casting.
    dept.Location__c = 'Bangalore';
   if(depUPdLst.size() > 0)
    update depUPdLst;
  global void finish(Database.BatchableContext bc) {
   name += 'finish';
   system.debug('@@@Finish Method: '+name);
   //Post Commit logic like sending emails for the success or failures of the batches.
   AsyncApexJob a = [select id, Status, NumberOfErrors, JobItemsProcessed,
   TotalJobItems, CreatedBy.Email from AsyncApexJob where id =: bc.getJobId()];
   Messaging.singleEmailMessage mail = new Messaging.singleEmailMessage();
   mail.setToAddresses(new String[]{a.CreatedBy.Email});
   mail.setSubject('Batch Class Result');
   mail.setHtmlBody('The batch Apex job processed ' + '' + a.TotalJobItems + '' +
   ' batches with '+ '' + a.NumberOfErrors + '' + ' failures.');
   //sendEmail methods
   Messaging.sendEmail(new Messaging.singleEmailMessage[]{mail});
   /*** Scheduling in minutes or hours ***/
   /*//Create object for schedulable class
   SchedulableUsage su = new SchedulableUsage();
   //Preparing chron_exp
   Datetime sysTime = System.now();
   sysTime = sysTime.addminutes(6);
   String chron_exp = '' + sysTime.second() + ' ' + sysTime.minute() + ' ' +
   sysTime.hour() + ' ' + sysTime.day() + ' ' + sysTime.month() + ' ? ' + sysTime.year();           
   System.schedule('Dep Update'+sysTime.getTime(),chron_exp, su);*/

5. How to maintain the state between the methods of batch class?
By default batch class is stateless (variable value which is stored in one method cannot be remembered in another method).
To maintain the state for the batch class, we should inherit Database.Stateful interface.
Scenario: In a set list of emails are stored in execute method. In the finish method that set is not having any emails. What is the reason?
Answer: By default batch class is stateless. Emails which are added to set can be remembered only in execute method. If we try to access the set in finish method you won't see those emails. In finish method if you want to access those emails of that set we should inherit the interface called Database.Stateful
6. Is it possible to call batch class from one more batch class?
Yes it is possible, starting with Apex saved using Salesforce API version 26.0, you can call Database.executeBatch or System.scheduleBatch from the finish method. This enables you to start or schedule a new batch job when the current batch job finishes.
For previous versions, you can’t call Database.executeBatch or System.scheduleBatch from any batch Apex method. Note that the version used is the version of the running batch class that starts or schedules another batch job. If the finish method in the running batch class calls a method in a helper class to start the batch job, the Salesforce API version of the helper class doesn’t matter.

7. Is it possible to call future method from a batch class?
We cannot call one asynchronous process from another asynchronous process.
Since @future method and Batch Class both are asynchronous we cannot call future method from batch class or we cannot call batch class from the future method.
8. How to cover the code for a batch class?
To cover the code for the batch class we should call the batch class from the inside of the Test.startTest() and Test.stopTest().
    //Call the batch class from here.

9. How many batch jobs can be active/queued at a time?
Up to 5 batch jobs can be queued or active.
10. Is it possbile to write batch class and schedulable class in a same class?
By implementing Database.Batchable and Schedulable interfaces we can implement the methods in a same class.
Though it is possible it is not recommended to write like this.

Test Classes
1. What is the purpose of writing the test class?
After developing an apex class or apex trigger we should write the unit tests and ensure that we are able to execute at least 75% of the lines of code.
If you are moving the code from sandbox to sandbox regarding code coverage you won't face any issue.
If you are moving the code from sandbox to production, you need to include all the test classes at the time of deployment and salesforce will run all the test classes which you included for the deployment as well as test classes which are already present in production, if the code coverage is less than 75% deployment will fail.

2. Is it possible to write test code inside of an apex class or apex trigger?
we cannot write test code (test methods) inside of the apex trigger.
From API Version 28.0, we cannot write the test methods inside of an apex class which is not decorated with @isTest.
We can write test methods only in a class which is decorated with @isTest.
Note: We have a governor limit for the overall Apex Code size of the organization which is of 3 MB. If we decorate a class with @isTest annotation Apex Code Size governor limit will be bypassed.

3. Syntax of testMethod?
    private class MyTestClass {
   static testMethod void myTest1() {
Note: Test Class can be either public or private.

4. 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.

5. 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().

6. What is the purpose of system.runAs()?
By default test class runs in System Mode. If you want to execute a piece of code in a certain user context then we can use system.runAs(UserInstance). For more details refer 2nd question in visualforce category.
To avoid MIXED-DML-OPERATION error we can include DML statements inside of system.runAs(), still the error persists keep DML statements inside of Test.startTest() and Test.stopTest().

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

8. 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())

9. 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.

10. What are the test class best approaches?
We should not depend on the existing data in the database. We should create the test data for all the possible scenarios. Note: Profiles and recordTypes cannot be created programmatically, we can query from the database. For the remaining objects including users we should create the test data.
While testing apex triggers and batch classes, we should do bulk testing at least with 200 records.
We should test for all the positive and negative scenarios.

Action Support : A component that adds AJAX support to another component, allowing the component to be refreshed asynchronously by the server when a particular event occurs, such as a button click or mouseover.?
Used when we want to perform an action on a particular event of any control like onchange of any text box or picklist.

Action Function : provides support for invoking controller action methods directly from JavaScript code using an AJAX request
Used when we need to perform similar action on various events. Even though you can use it in place of action Support as well where only event is related to only one control.

action Function : provides support for invoking controller action methods directly from JavaScript code using an AJAX request

1. Action function can call the controller method directly from java script.
2. Action support adds AJAX support to another visual force component and then call the controller method.
  It makes sense to me that,

--Action Function works only with the help of JavaScript(that invokes controller method),but
--actionupports does not need any JavaScript to call the controller method
--Actionfunc can be used for popup message etc,which cant be done by Actionsupport
--We can use one controller method for multiple Action function components on a vf page
     Are my above conclusions right till here or please correct me if i am wrong.
1. Command link: Executes a function defined in a controller synchronously.
2. Action Support: Provides AJAX support to another component that is executes function defined in controller asynchronously.
3. Action Function: Executes function defined in controller directly from JavaScript code using an AJAX request.

1)What is the use of standard ,custom controller and Extensions definitions other than standard?.[Live Cases Example]
The Force.com platform provides a number of standard controllers that contain the same functionality and logic that are used for standard Salesforce pages. For example, if you use the standard Accounts controller, clicking a Save button in a Visualforce page results in the same behavior as clicking Save on a standard Account edit page.

2)In which scenario we will use these controllers i.e When and where Required?
When you do want to use the standard functions and logics then developing custom use standard controllers. You coud add extension classes is you want some custom logic with standard controller. If you only want custom logics to use then you could create a custom controller instead on standard controller.

3)What is the Use of Constructors we are using in Standard Controller and Why we are not using Constructor in Custom Controllers.

Constructors are used to initialize properties on page load. In standard controllers constructer of extension need to have Standard Controller instance as parameter so you need to create such constructer.

When using custom controller you may or may not create constructor as a default constructor is always present when you create any class.

What is difference between trigger and workflow? 
Workflow is automated process that fired an action based on Evaluation criteria and rule criteria. We can access a workflow across the object. Trigger is a piece of code that executes before or after a record is inserted or updated.
·         The trigger can work across objects and where in you can query the object as well as you can do DMLs.
·         The workflow will be only helpful to update the same object or master object in custom master-detail relationships. We cannot query from database
·          The trigger works before and after some actions.
·         Workflows work only after some actions.
·         Trigger get fired on more actions like on insert, update, delete and undelete.
·         Workflow gets fired on insert and update
·         Triggers cannot be updated on production org after being created via a managed package.
·         Actions in workflows can be edited, removed and new actions can be added in production org.
What is MIXED-DML-OPERATION error and how to avoid?
If we perform DML operation on standard/custom object and global objects(User, UserRole, Group, GroupMember, Permission Set, etc...) in same transaction this error will come.
To avoid this error, we should perform DML operation on standard/custom object records in a different transaction.
In general all the apex classes and apex triggers execute synchronously (execute immediately).
if we perform DML operation on standard/custom object records asynchronously (execute in future context), we can avoid MIXED-DML-OPERATION error.
To execute logic asynchronously keep the logic in an apex method (in a separate apex class, not in same apex trigger) which is decorated with @future annotation.
Note: To analyse the code copy it and paste it in notepad for the convenience.
 public class TriggerUtility {
  1. Following future method execute asynchronously (whenever server is free it will execute in future context).
  2. We should not declare @future method in Apex Trigger.
  3. @future method should be always static.
  4. @future method accepts only primitive data types (Integer, String, Boolean, Date, etc...) as parameters and it won't accept
  non-primitive data types (sObject,Custom Objects and standard Objects etc.. ) as parameters.
  5. @future method should not contain return type. Always it should be void.
  6. From an apex trigger we can make only make asynchronous call outs. To make call out we should include "callout = true" beside the future @annotation.
  7. We cannot perform synchronous call outs from Apex Trigger.
  //Below is the example for the future method -
  @future(callout = true)
  public static void processAsync(primitive parameters) {
   //Logic to insert/update the standard/custom object.
  } }
What is Synchronous and Asynchronous in Salesforce?
Apex can be executed synchronously or asynchronously.
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.
Controller Extension
Custom Controller
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.
@future Annotation




Post a Comment