Wednesday, 14 November 2012

Loading Test Data from Static Resources

Loading Test Data from Static Resources

Using the new Test.loadData method, you can populate data in your test methods without having to write many lines of code. Simply, add the data in a .csv file, create a static resource for this file, and then call Test.loadData within your test method by passing it the sObject type token and the static resource name. For example, for Account records and a static resource name of myResource, make the following call:
List<sObject> ls = Test.loadData(Account.sObjectType, 'myResource');

The Test.loadData method returns a list of sObjects that correspond to each record inserted.

You must create the static resource prior to calling this method. The static resource is a comma-delimited file ending with a.csv extension. The file contains field names and values for the test records. The first line of the file must contain the field names and subsequent lines are the field values.

Once you create a static resource for your .csv file, the static resource will be assigned a MIME type. Supported MIME types are:

Test.loadData Example

The following are steps for creating a sample .csv file and a static resource, and calling Test.loadData to insert the test records.
1.       Create a .csv file that has the data for the test records. This is a sample .csv file with three account records. You can use this sample content to create your .csv file.

sForceTest1,,(415) 901-7000,The Landmark @ One Market,San

sForceTest2,,(415) 901-7000,The Landmark @ One Market Suite
300,San Francisco,CA,94105,US
sForceTest3,,(415) 901-7000,1 Market St,San Francisco,CA,94105,US

2.       Create a static resource for the .csv file:
a.       Click Your Name > Setup > Develop > Static Resources, and then New Static Resource.
b.      Name your static resource testAccounts.
c.       Choose the file you just created.
d.      Click Save.
3.       Call Test.loadData in a test method to populate the test accounts.

private class DataUtil {
                static testmethod void testLoadData() {
// Load the test accounts from the static resource
List<sObject> ls = Test.loadData(Account.sObjectType, 'testAccounts');
// Verify that all 3 test accounts were created
System.assert(ls.size() == 3);

// Get first test account
Account a1 = (Account)ls[0];
String acctName = a1.Name;

// perform some testing using the test records

Tuesday, 13 November 2012

What's the date format for the Apex Data Loader?

What's the date format for the Apex Data Loader?

The Apex data loader allows you SOQL statements to pull data - therefore you have to use date formats that SOQL statements will use.

here's a quick example, but there are so many options, you should really check out the guide.  I included a link under my example:

FormatFormat SyntaxExample
Date onlyYYYY-MM-DD1999-01-01
Date, time, and time zone offset
  • YYYY-MM-DDThh:mm:ss+hh:mm
  • YYYY-MM-DDThh:mm:ss-hh:mm
  • YYYY-MM-DDThh:mm:ssZ
  • 1999-01-01T23:01:01+01:00
  • 1999-01-01T23:01:01-08:00
  • 1999-01-01T23:01:01Z

Friday, 9 November 2012

Inline Editing for List views

Inline Editing for List views

To edit one record, double-click the editable value, specify a new value, and click OK.

If you have the “Mass Edit from Lists” permission, you can edit up to 200 records at once. To edit multiple records:

  1. Select the checkbox next to each record you want to update. If you select records on multiple pages, Salesforce remembers which records are selected.
  2. Double-click one of the cells you want to edit. A dialog box displays allowing you to apply your edit to one record, or to every record selected
Note the following tips when using inline editing with lists:
  1. Some standard fields do not support inline editing. For example, Case Status, Opportunity Stage, Opportunity Amount, Opportunity Quantity and Lead Status, and most Task and Event fields can only be edited from a record's edit page. For more information, see Editing Data Using Inline Editing.
  2. If your organization uses record types, inline editing with lists is only available when all of the records in the list are of the same record type. Therefore, you must specify a filter of Record Type equals X, where X is the name of a single record type (or blank for the master record type).
  3. To perform inline editing on an enhanced list, filter logic must be turned off in the list view filter criteria.
  4. For lists of activities, you must specify an additional filter of either Task equals True (for tasks) or Task equals False (for events) for inline editing to be available.
  5. If your organization is using Person Accounts:
  • You can't use inline editing to change them from a Contact list. You can only inline edit Person Accounts from an Account list.
  • You can only use inline editing on contacts associated to business accounts by specifying an additional filter of Is Person Account EQUALS False in your list criteria.

Tuesday, 6 November 2012

Salesforce Interview questions

1 ) What is the difference between Lookup Relationship and Master-Detail Relationship?
Ans  : Master – Detail Relationship :
1. We cannot create master – detail relationship type fields directly if records already exists. Instead we have to first create Look up fields then fill all the records with that lookup filed. After that we can convert the lookup fields to master – detail relationship.
2. If we delete master records then detail (Child) records are deleted.
3. It creates the parent(master) child(Detail) relationship between objects.
Look up relationship :
1. Look up relationship creates relations between two objects.
2. If we delete any object then other object is not deleted
2) True or False? If you were to delete a record that had a lookup to a child object, all child object records would get deleted as well.
Ans :  False
3) Where can you make a field required?
Ans : At page layout and from field level security
4) I'm setting up different page layouts for different user profiles.  As a system administrator, is there another way to see what the user sees instead of them granting log in access to you?
Ans  : There is a button on edit layout 'Preview As', on click of that button, you can select the profile name and view thr layout from that profile perspective
5) What is Dataloader?
Ans : Tool to export/delete/upsert/insert bulk records using CSV file in salesforce, only csv files can be used and can be used even for record size greater than 50k
6) What is the difference between Profiles and Roles in
Ans: Roles : one of the ways you can control access to records. They also impact reports (e.g. "My Teams" filter). Roles come into play if your security model (OWDs) are set to private. A little more on Roles and how they impact security:Depending on sharing settings, roles can control the level of visibility that users have into your organization’s data. Users at any given role level can view, edit, and report on all data owned by or shared with users below them in the hierarchy, unless your organization’s sharing model for an object specifies otherwise. Specifically, in the Organization-Wide Defaults related list, if the Grant Access Using Hierarchies option is disabled for a custom object, only the record owner and users granted access by the organization-wide defaults receive access to the object's records.

    • Every user must be assigned to a role, or their data will not display in opportunity reports, forecast roll-ups, and other displays based on roles. If your organization uses territory management, forecasts are based on the territory hierarchy rather than the role hierarchy.
    • All users that require visibility to the entire organization should belong to the highest level in the hierarchy.
    • It is not necessary to create individual roles for each title at your company, rather you want to define a hierarchy of roles to control access of information entered by users in lower level roles.
    • When you change a user’s role, any relevant sharing rules are evaluated to add or remove access as necessary.
    • When an account owner is not assigned a role, the sharing access for related contacts is Read/Write, provided the organization-wide default for contacts is not Controlled by Parent. Sharing access on related opportunities and cases is No Access.
    • Users that gain access to data due to their position in hierarchies do so based on a setting in your organization-wide defaults.
Profiles : help determine record privileges. Assuming the User can see the record, Profiles determine what the User can do, view or edit on that record. Profiles control other system privileges as well (mass email, export data, etc)
Profiles control:

    • Which standard and custom apps users can view
    • Which tabs users can view
    • Which record types are available to users
    • Which page layouts users see
    • Object permissions that allow users to create, read, edit, and delete records
    • Which fields within objects users can view and edit
    • Permissions that allow users to manage the system and apps within it
    • Which Apex classes and Visualforce pages users can access
    • Which desktop clients users can access
    • The hours during which and IP addresses from which users can log in
    • Which service providers users can access (if Salesforce is enabled as an identity provider)

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

2. What is S-Control ?
Ans: S-Controls are the predominant 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: 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 merge 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 to write Visualforce code ?
Ans: You can write the code basically in 3 ways.

  1. setup->App Setup->Develop->Pages and create new Visulaforce page.
  2. Setup -> My Personal Information -> Personal Information -> Edit check the checkbox development mode. When you run the page like this, 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.
  3. Using EclipseIDE you can create the Visulaforce page and write the code.

6.What are Apex Governor Limits?
Governor limits are runtime limits enforced by the Apex runtime engine. Because Apex runs in a shared, multitenant environment, the Apex runtime engine strictly enforces a number of limits to ensure that code does not monopolize shared resources. Types of limits that Apex enforces are resources like memory, database resources, number of script statements to avoid infinite loops, and number of records being processed. If code exceeds a limit, the associated governor issues a runtime exception.

7. How to create and host S Control in Salesforce ?

8. Difference between Sandbox and Development environment?

9. How to schedule export or take the backup of salesforce?

10. Do governor limits apply to sandbox instances?
Ans : Governor limits do apply to all Salesforce instances (trial, developer, production or sandbox environments). However code coverage and successful execution of test classes is only enforced when deploying to a production environment.

11. What is difference in ISNULL and ISBLANK?

  • Determines if an expression is null (blank) and returns TRUE if it is. If it contains a value, this function returns FALSE.
  • Text fields are never null, so using this function with a text field always returns false. For example, the formula field IF(ISNULL(new__c) 1, 0) is always zero regardless of the value in the New field. For text fields, use the ISBLANK function instead.
  • Multi-select picklist fields are never null in s-controls, buttons, and email templates, so using this function with a multi-select picklist field in those contexts always returns false.
  • Empty date and date/time fields always return true when referenced in ISNULL functions.
  • Choose Treat blank fields as blanks for your formula when referencing a number, percent, or currency field in an ISNULL function. Choosing Treat blank fields as zeroes gives blank fields the value of zero so none of them will be null.
  • Merge fields can be handled as blanks, which can affect the results of components like s-controls because they can call this function.
  • When using a validation rule to ensure that a number field contains a specific value, use the ISNULL function to include fields that do not contain any value. For example, to validate that a custom field contains a value of ’1,’ use the following validation rule to display an error if the field is blank or any other number: OR(ISNULL(field__c), field__c<>1)

  • Determines if an expression has a value and returns TRUE if it does not. If it contains a value, this function returns FALSE.
  • Use ISBLANK instead of ISNULL in new formulas. ISBLANK has the same functionality as ISNULL, but also supports text fields. will continue to support ISNULL, so you do not need to change any existing formulas.
  • A field is not empty if it contains a character, blank space, or zero. For example, a field that contains a space inserted with the spacebar is not empty.
  • Use the BLANKVALUE function to return a specified string if the field does not have a value; use the ISBLANK function if you only want to check if the field has a value.
  • If you use this function with a numeric field, the function only returns TRUE if the field has no value and is not configured to treat blank fields as zeroes.

12. Is it possible to write the Apex code from user Interface?
You can add, edit, or delete Apex using the user interface only in a Developer Edition organization, a Enterprise Edition trial organization, or sandboxorganization. In a production organization, you can only make changes to Apex by using the Metadata API ,
deploycall, the IDE, or Migration Tool. The IDE and Migration Tool are free resources provided by to support its users and partners, but are not considered part of our Services for purposes of the Master Subscription Agreement.

13. When you can’t add Time dependent action in Workflow rule?
You can’t add time-dependent actions to a rule if you choose Every time a record is created or edited.

14. What are the types of email templates available in

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

15. What are the different Editions and Limits?

16. What is Roll up summary field in Salesforce?
Roll up summary field in salesforce calculates the Count, Sum, Min or Maxof particular field of any child record. Thus, we can say that Roll up summary field can only be created on Master object. To read further, please check this URL

17. What will happen if the Account is deleted?
If the Account is deleted then Contact, Opportunity will also be deleted from Salesforce which are related to that Account.
From the database perspective, check below image of child relationships of Account:
Account Child relationship in salesforce
If we use schema builder, released in Winter 12 it would look like:
Account Contact and Opportunity of salesforce in schema builder

18. How many types of the relationship fields available in Salesforce>
Ans :

  1. Master Detail
  2. Many to Many
  3. Lookup
  4. Hierarchical

19. How to create many to many relationships between object?
Creating many to many relationship in salesforce is little tricky. You cannot create this type of relationship directly. Follow below steps to create this type of relationship.
Create both objects which should be interlinked.
Create one custom object (also called as junction object), which should have autonumber as unique identification and create two master relationships for both objects, no need create tab for this object.
Now on both object, add this field as related list.
20. In Which sequence Trigger and automation rules run in The following is the order salesforce logic is applied to a record.

  1. Old record loaded from database (or initialized for new inserts)
  2. New record values overwrite old values
  3. System Validation Rules
  4. All Apex “before” triggers (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. Escalation rules
  13. Parent Rollup Summary Formula value updated (if present)
  14. Database commit
  15. Post-commit logic (sending email)
Additional notes: There is no way to control the order of executionwithin each group above.

21. If one object in Salesforce have 2 triggers which runs “before insert”. Is there any way to control the sequence of execution of these triggers?
Ans : has documented that trigger sequence cannot be predefined. As a best practice create one trigger per object and use comment blocks to separate different logic blocks. By having all logic in one trigger you may also be able to optimize on your SOQL queries.

22. How to delete the User from Salesforce?
Ans : As per now, salesforce does not allow to delete any user, however you can deactivate the user.

23. How to delete the users data from Salesforce?
Ans : To delete the Users Data go to Setup | Administration Setup | Data Management |  Mass Delete Record, from there select the objects like Account, Lead etc and in criteria select the users name and delete all records of that user related to particular object.

24. How to restrict the user to see any record, lets say opportunity?
Ans : set up opportunity sharing to be private.  If both users are admins or have view all records on opportunity, then that overrides private sharing.

25. What is the difference between and trigger.old in Apex – SFDC?
Ans : :
Returns a list of the new versions of the sObject records.
Note that this sObject list is only available ininsert
triggers, and the records can only be modified inbefore
Trigger.old :
Returns a list of the old versions of the sObject records.
Note that this sObject list is only available inupdate

26. How to restrict any Trigger to fire only once ?
Triggers can fire twice, once before workflows and once after workflows, this is documented at
“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.”
Add a static boolean variable to a class, and check its value within the affected triggers.
1public class HelperClass {
2   public static boolean firstRun = true;

4trigger affectedTrigger on Account (before delete, after delete, after undelete) {

5    if(Trigger.isBefore){
6        if(Trigger.isDelete){

7            if(HelperClass.firstRun){
8                Trigger.old[0].addError('Before Account Delete Error');

9                HelperClass.firstRun=false;
10            }

11        }
12    }


27.  What is difference between WhoId and WhatId in the Data Model of Task ?
Ans :
WhoID refers to people things. So that would be typically a Lead ID or a Contact ID
WhatID refers to object type things. That would typically be an Account ID or an Opportunity ID

28. Where is the option of the report for the “Custom Object with related object” and what are the condition to generate related reports?
Ans :
If the parent object is the standard object provided by the salesforce like “Account”, “Contact” then the report will be in there section with related custom object.
If both objects are the custom then the report will be in “
Other Reports” Sections.
Following are the conditions to get the report of related objects:

  • On both the objects, Reports option must be enable.
  • The relationship between both of them must be “Master – detail relationship”.

29. How you can provide the User Login (Authentication) in Public sites created by Salesforce.
Answer : We can provide the authentication on public sites using “Customer Portal”.

30 : What is the dynamic Apex?
Ans :

Dynamic Apex enables developers to create more flexible applications by providing them with the ability to 
“Access sObject and field describe information”, “Write Dynamic SOQL Queries”, “Write Dynamic SOSL Queries” and “Dynamic DML”.

31 : How to get the list of all available sobject in salesforce database using Apex (Dynamic Apex)?

1Map m =  Schema.getGlobalDescribe();

32 : How to create instance of sobject dynamically? Normally the sobject is created like “Account a = new Account();”. But if you are in situation that you don’t know which sobject is going to be instantiated ? Means it will be decided at runtime, how you will handle it? Hint : Use Dynamic Apex.
1public SObject getNewSobject(String t)

4    // Call global describe to get the map of string to token.

5    Map gd = Schema.getGlobalDescribe();

7    // Get the token for the sobject based on the type.
8    Schema.SObjectType st = gd.get(t);

10    // Instantiate the sobject from the token.

11    Sobject s = st.newSobject();

13    return s;

33 : How to get all the fields of sObject using dynamic Apex?
1Map m  = Schema.getGlobalDescribe() ;
2Schema.SObjectType s = m.get('API_Name_Of_SObject') ;

3Schema.DescribeSObjectResult r = s.getDescribe() ;
4Map fields = r.fields.getMap() ;

34 : How to get all the required fields of sObject dynamically?

There is no direct property available in Apex dynamic API to represent the required field. However there is another way to know about it.
If any field have below three properties then it is mandatory field.

  1. If it is Creatable
  2. If it is not nillable and
  3. If it does not have any default value
    1Map m  = Schema.getGlobalDescribe() ;
    2Schema.SObjectType s = m.get(so.apiName) ;

    3Schema.DescribeSObjectResult r = s.getDescribe() ;
    4Map fields = r.fields.getMap() ;

    6for(String f : fields.keyset())

    8    Schema.DescribeFieldResult desribeResult = fields.get(f).getDescribe();

    9    if( desribeResult.isCreateable() && !desribeResult.isNillable() && !desribeResult.isDefaultedOnCreate() )
    10    {

    11//This is mandatory / required field
    12    }


    35 : How to display error messages in the visualforce page ?
    In Apex use below code to create the error message for visualforce.
    1Apexpages.addMessage( new ApexPages.Message (ApexPages.Severity.ERROR, 'Required fields are missing. '));

    in Visualforce page add below tag where you want to display the error message.
    <apex:pageMessages ></apex:pageMessages>

    36 : What is property in Apex? Explain with advantages.

    Apex mainly consist of the syntax from the well known programming language Java. As a practice of 
    encapsulation in java we declare any variable as private and then creates the setters and getters for that variable.
    1private String name;
    2public void setName(String n)

    4  name = n;

    6public String getName()

    8 return name;


    However, the Apex introduced the new concept of property from language C# as shown below:
    1public String name {get; set;}

    As we can see how simple the code is and instead of using nearly 8 to 11 lines all done in 1 line only. It will be very useful when lots of member is declared in Apex class. It has another advantage in “number of lines of code” limit by salesforce which will drastically reduced.

    37 : What is the controller extension ?

    Any apex class having a public constructor with Custom Controller or Standard Controller object as a single argument is known as controller extension.

    38 : Explain the need or importance of the controller extension.

    Controller extension is very useful and important concept introduced by the salesforce recently. It gives the power to programmer to extend the functionality of existing custom controller or standard controller.
    A Visualforce can have a single Custom controller or standard controller but many controller extensions.
    we can say that the custom extension is the supporter of custom or standard controller.
    Consider one example : If there is one controller written and used by the multiple visualforce pages and one of them needs some extra logic. Then instead of writing that logic to controller class (Which is used by many visualforce pages) we can create a controller extension and apply to that page only.

    39 : How to read the parameter value from the URL in Apex?

    Consider that the parameter name is “RecordType”.
    1String recordType = Apexpages.currentPage().getParameters().get('RecordType');


Why to use Database.Stateful()?

Database Stateful is interface. It is used in batch classes to maintain the state of the class across transactions i.e. if you want to use ...