Wednesday, 13 July 2016

Salesforce Interview questions

1. What is Track Field History?
  • While creating the object, we can enable 'Track Field History'.
  • If, we enable 'Track Field History' user can see 'Set History Tracking' button under 'Custom Fields & Relationships' section which is available on the object detail page.
  • By clicking on 'Set History Tracking' button, we can enable tracking for the fields which ever we want.
  • To see the object history, go to object's record layout and add Object Name History related list to the layout.
  • Whenever, user changes field value from one value to another value, it will show the history of the field in 'Object History' related list.
2. What are the Activities in Salesforce?
To create the Activities, while creating the object, we should check for 'Allow Activities' check box then user can add open Activities and Activity History related lists on the Object layout.
There are two types of activities -
  1. Task: Task is nothing but work assigned to a particular person, it doesn't have certain time limit.
  2. Event: It has certain time limit in that time only all persons should assemble after the time limit over, event will get complete.
- Once event or task status changed to 'Completed' then we can see those records under Activity History Related List.

3. How to Rename the tab?

Tab name will be decided based on the Plural Label of the custom object, to rename go to corresponding object detail page and rename the plural label.

4. How to display multiple columns after clicking on the tab?

Click on the tab(Which should be realted to any of the custom/standard object) > Expand Force.com Quick Access Menu > Edit Columns > Move the needed fields from Available Fields to Selected Fields. > Click on Save > User should be able to see multiple columns.
(OR)
Click on Setup > Create > Objects > Select the corresponding object link > Under Search Layouts section > Click Edit which should be left to Object Tab > Move the needed fields from Available Fields to Selected Fields. > Click on Save > User should be able to see multiple columns.

5. What is the difference between ISBLANK() AND ISNULL()?
  • ISNULL() works only for number data type fieds, if we don't populate with value for number fields it will return true.
  • ISNULL() won't support TEXT data type fields because text fields never become null.
  • ISBLANK() supports both number as well as text data types.
6. What is dependent picklist?
In some scenario's, we should be able to control one of the field(Dependent field) from another field(Controlling field), example If we select Country(Controlling field) as US then City(Dependent Field) should display only US cities.
  • We can use checkbox data type fields also while creating dependent picklist (Note: Checkbox should be always controlling field)
  • We can use multi-select data type fields also while creating dependent picklist (Note: multi-select data type field should be always dependent field)
7. What is the architecture of the salesforce
  • MVC Architecutre - Model, View , Controller
  • View - It is the user interface (Apps, Tabs, Page Layouts, Fields and Record Types)
  • Controller - Business Logic (Save, Edit, New, Cancel and Delete - upon click on these button salesforce execute some logic from controller)
  • Model - It is the Database, which stores Schema (Meta-Data(Data about Data) --> Apps, Tabs, sObjects, fields, Apex Classes, Visualforce pages, etc...) and Instance (Records)
8. What is the difference between 15 digit and 18 digit id in Salesforce?
  • In Salesforce, whenever user create any component (Object, field, tab etc...) or record then salesforce will generate an unique id with which user can identify the record or component.
  • After creating the record, in the URL user can see the id of the record which is of 15 digits length.
  • Through user interface user always see 15 digit id which is Cases-Sensitive
.
  • If the user query the existing records from the database through API (Either from Query Tool or from a program), it will always return 18 digit id which is Case-Insensitive.
  • Last 3 digits of the 18 digit representschecksum of the capitalization of 15 digit id.
  • Based on the first 3 digits user can identify the object of the record.
  • All the records belongs to same object will contain same firt 3 digits.
9. What is Record Type?
  • For an object based on the Record Type, we can show different fields and different picklist values by assigning different page layouts for the record types and profiles.
  • After creating the record type, on the record type detail page user can see all the picklist data type fields, user can edit the picklist and decide which values should display for this particular record type.
10. What is the difference between detail page and edit page?
  • Whenever user try to create a new record or edit an existing record user can input the values for the fields, this page is nothing but edit page.
  • After creating a new record or editing an existing record, user can see the information of the record, this page is nothing but detail page.

 

 

11. What is out of box functionality?

Within the sfdcstandered functionality (no need to code).
12. What are the type of tabs?
  • Custom tabs (create for objects)
  • Web tabs (create to display a website)
  • Visual force tabs (create to display the visual force page)

13. What is validation rule?

While creating or modifying the record based on the certain conditions we can display error messages on top of the page or below to the filed.

14. There are two fields, if the user populate two field values if we combine those values uniqueness should be maintain, how to achieve this without coding?

Using vlookup function in the validation rule we can achieve this.
15. What are Governor Limits?
Since we are working in multitenant environment Salesforce is enforcing the limits for all the functionalities.
  • How many no of fields for an object: 500
  • No of master detail relationships for an object: 2
  • No of lookup relationship for an object: 25
  • No of rollup summery fields: 10
  • How many external ids we can enable for an object: 7 (increased from 3 to 7 in Winter-15)

16. For which data type we can enable external id?

text, number, auto number, email.

17. What is list view?

After clicking on the tab on the top of the page we can see views, by default we can see the value called ‘all’. If we click on ‘Go’ beside that all we can see all the records of that object. If we want we can create new views. While creating the view we can give the filter conditions so that based on the filter condition only we can see the records.

18. What is Inline editing?

On the detail page without clicking on edit button we can edit particular field if it is not read-only.

19. How to disable Inline editing?

To enable or disable Inline editing follow the below navigation - Setup-->Customise--> User Interface--> Enable Inline Editing

20. What is Enhanced list view?

In list views we can modify multiple records at a time using Enhanced list views Note: To modify multiple records, all the records should belong to same record type in the list view otherwise we cannot modify.
21. What is search layout?
Whenever we click on a tab or we click on a lookup icon or search for a record we see only one standard field by default, to enable remaining fields -
  • To show multiple fields for the records which display under a tab, on object detail page > under Search layouts edit tab and add required fields.
  • To show multiple fields for the records which display when we click on lookup of a field, on object detail page > under Search layouts edit Lookup Dialogs and add required fields.
  • To show multiple fields for the records which display when we search for the records, on object detail page > under Search layouts edit Search Results and add required fields.

22. What is mini page layout and how to enable?

For lookup fields on record detail page we see a link, whenever we put cursor on that link we see a popup window which displays few fields. To control the fields visibility, on that look up field parent object page layout we see a mini page layout in that we can control.
23. What is lead process?
To control the picklist values of the status field on the lead object we should create lead process.
  • Without selecting the lead process we can't create the record type for lead object
24. What is sales process?
To control the picklist values of the stage field on the opportunity object we should create sales process.
  • Without selecting the sales process we can't create the record type for opportunity object
25. What is Support process?
To control the picklist values of the status field on the case object we should create support process.
  • Without selecting the support process we can't create the record type for case object

26. What is web-to-lead?

On lead object we can generate the HTML code by selecting lead fields and by mentioning return URL from web-to-lead option. The generated HTML code can be hosted in any of the website. Upon entering the information in those fields and clicking on submit button that information will be saved into lead object of the Salesforce.

27. What is Queue?

In queue we can add group of users and we can assign the objects to the Queue. After creating the queue one of the list view automatically created on the objects which are selected for the queue. We can assign this queue as the owner of the records (objects which are selected for this queue). Later users who are part of that queue can claim the ownership by navigating to list view corresponding to the queue. In that list view users who are part of the queue can select the record and click on accept button so that record ownership will be transferred from queue to accepted person.

28. What is public group?

We can add set of random users in the public group. We can't assign public group as an owner of the record. In manual sharing, sharing rules and in list views we can use public group.

29. What are the Assignment rules?

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

30. What are Auto-Response Rules?

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

31. What are the Escalation rules?

On case object we can create Escalation rule. Based on the priority we can send escalation mails.
8. How to provide security for the Records(Instance)?
  1. Roles
  2. OWD(Organigation Wide Defaults)
  3. Sharing Rules.
  4. Manual Sharing
  5. Apex Managed sharing
  6. View all.
  7. Modify all.
  8. View all data.
  9. Modify all data.
12. What is recursive workflow rule? How to avoid recursive workflow rules?
Whenever we enable Re-evaluate Workflow Rules after Field Change checkbox in the Field Update of a workflow rule, due to this field update other workflow rules on the same object will be fired if the entery criteria of those workflow rules satisfied.
Incase, in other workflow rules also if we enable Re-evaluate Workflow Rules after Field Change checkbox in the Field Update recursive workflow rules will come in some scenarios.
We can take two steps to avoid recursive workflow rules -
  1. For the workflow Evaluation Criteria if you choose created, and any time it’s edited to subsequently meet criteria option, we can avoid recursive workflow rules.
  2. If you don't enable Re-evaluate Workflow Rules after Field Change checkbox in the Field Update of a workflow rule we can avoid.

2. What is the difference between List and Set ?

List
Set
List is Ordered.
Set is unordered.
List allows duplicates.
Set doesn't allow duplicates.
We can access list elements with index.
Set elements cannot be accessed with index.
We can sort list elements with sort method (default sorting order is ascending).
sort method is not available for Set.
Contains method is not available in List.
Contains method is available for Set to search for a particular element in the set.
We can process records which are stored in list using DML statements(insert, update, delete and undelete).
We cannot process records which are stored in set using DML statements.
  1. keyset(): To fetch only keys from the map.
  2. values(): To fetch only values from the map.
  3. containsKey(value): To search a key from the map.
  4. get(key): By supplying the key we can fetch the value.
  5. put(key,value): To add key and value in a map.
  6.  

5. Difference between insert/update and Database.insert/ Database.update?

insert/update
Database.insert/Database.update
Assume that you are inserting 100 records. If any one of the record fail due to error then entire operation will fail. None of the records will be saved into the database.
Assume that you are inserting 100 records. If any one of the record fail due to error then it will perform partial operation (valid records will be inserted/updated) if we use Database.insert(list,false)/ Database.update(list,false).
with insert/update if we use try-catch then we can capture only one error which will cause to stop the operation.
withDatabase.insert/Database.update we can capture all the errors by saving result in Database.saveResult[].

6. There is a Queue with name MyQueue. How to query it using SOQL query from the database?

Queues will store in Group object. To query for MyQueue from the database using SOQL, we should use the following syntax -
?
1
Group grp = [select Id, Name from Group where Name = 'MyQueue'and
2. Governor Limits for DML statements ?
  1. Number of DML statements per transaction: 150 (as a whole including insert, update, delete and undelete)
  2. Number of rows processed per DML stmt: 10000
3. What is SOQL?
  1. SOQL: Salesforce Object Query Language
  2. SOQL Purpose: To fetch info. from an object and related objects.
  3. We can write query on one object while querying on those objects we can fetch the child object info. or parent object info. (we cannot capture un related objects info.)
  4. SOQL queries per transaction: 100.
  5. SOQL query rows returned: 50000.
4. What is SOSL?
  1. SOSL: Salesforce Object Search Language
  2. SOSL Purpose:We can search for a value in multiple objects (no need of any relationship).
  3. Results of SOSL query can be stored in List of List.
  4. SOSL queries per transaction: 20.
  5. SOSL query rows returned: 2000.

1. What are the trigger events?

Before Mode: Before the record is saving into the database, it will fire.
After Mode: After the record is saved into the database (doesn't commit at this point of time), it will fire.
Before
After
before insert
after insert
before update
after update
before delete
after delete
-
after undelete
Note: before undelete event is not available.
2. What are the trigger context variables?
To capture the runtime information we use trigger context variables.
Below context variables will return either true or false.
  1. Trigger.isBefore (returns true if the trigger context is Before Mode)
  2. Trigger.isAfter (returns true if the trigger context is After Mode)
  3. Trigger.isInsert (returns true if the trigger context is Insert)
  4. Trigger.isUpdate (returns true if the trigger context is Update)
  5. Trigger.isDelete (returns true if the trigger context is Delete)
  6. Trigger.isUndelete (returns true if the trigger context is Undelete)
  7. Trigger.isExecuting (returns true if the apex class method is getting call from Apex Trigger)
Below context variables will store records at runtime.
  1. trigger.old (stores history (old versions) of the records.)
  2. trigger.oldMap (stores history (old versions) of the records along with id.)
  3. trigger.new (stores new version of the records.)
  4. trigger.newMap (stores new version of the records along with id.)

3. Availability of trigger.old and trigger.new for the different trigger events?

Apex Trigger Collections availability for the different events -
Events
trigger.old
trigger.oldMap
trigger.new
trigger.newMap
before insert
after insert
before update
after update
before delete
after delete
after undelete

4. Read/Write accessibility of trigger.old and trigger.new?

Read/Write access over the trigger collections on different events -
Events
trigger.old
trigger.oldMap
trigger.new
trigger.newMap
before insert
NA
NA
Read/Write
NA
after insert
NA
NA
Read Only
Read Only
before update
Read Only
Read Only
Read/Write
Read Only
after update
Read Only
Read Only
Read Only
Read Only
before delete
Read Only
Read Only
Read Only
Read Only
after delete
Read Only
Read Only
Read Only
Read Only
after undelete
Read Only
Read Only
Read Only
Read Only
5. When to use before triggers and when to use after triggers?
Before Triggers
  1. To perform the validations we should use before triggers.
  2. If you are updating any field on the same object on which you are writing the trigger and no need to explicitly include the DML statemetns (already due to DML operation only trigger fire and it is still in progress at this point of time.)
After Triggers
  1. If you are dealing with relationship records and if you need record id in these situations we should use after trigger (in before insert record doesn't contain the record id).

6. For the same event if there are multiple triggers on the object, how to control the order of execution?

We cannot control the order of execution in this situation. It is recommended to have only one trigger per one object.
Note: We can keep the logic of the apex trigger in an apex class and can invoke from that class.

7. What are the recursive triggers and how to avoid?

If we perform update operation on the record in after update event logic recursive triggers will arise.
Using static boolean variable in an apex class (we should not keep static boolean variable inside of the trigger) we can avoid recursive triggers.

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.

9. How many batch jobs can be active/queued at a time?

Up to 5 batch jobs can be queued or active.

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.

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.

How to schedule batch apex in minutes/hours?

To schedule the batch class in minutes/hours, in the finish method we should use System.schedule method which will take 3 parameters Job Name, Chrone Expression and schedulable class instance name respectively.
?
1
2
3
4
5
6
7
8
9
/*** Scheduling in minutes or hours ***/
//Create object for schedulable class
SchedulableUsagesu = newSchedulableUsage();
//Preparing chron_exp
DatetimesysTime = 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

3. How to schedule batch apex?

To schedule the batch class we should write a separate class by implementing Schedulable interface.
After writing the above mentioned class to schedule navigate to: Develop> Apex Classes> Schedule Apex.
By clicking on Schedule Apex button we can schedule the batch class through user interface.
Note: Through user interface we cannot schedule in hours/minutes.
Schedulable Class Syntax:
?
1
2
3
4
5
6
global classSchedulableUsage implementsSchedulable {
global voidexecute(SchedulableContextsc) {
BatchUsagebu = newBatchUsage();
//Database.executeBatch(bu);//Default Batch Size is: 200.
Database.executeBatch(bu,1500);//Max. Batch Size is: 2000.
}
}



Trigger handler controller in Salesforce
Trigger:

trigger Sample on Opportunity(before insert, before update, after insert, after update ) {
                if ( trigger.isBefore ) {
                                if ( trigger.isInsert ) {
                                                OpportunityHandlerController.onBeforeInsert(trigger.new);
                                } else if ( trigger.isUpdate ) {
                                                OpportunityHandlerController.onBeforeUpdate(trigger.new, trigger.oldMap);
                                } else if ( trigger.isDelete ) {
                                                OpportunityHandlerController.onBeforeDelete(trigger.old, trigger.oldMap);
                                }
                } else if ( trigger.isAfter ) {
                                if ( trigger.isInsert ) {
                                                OpportunityHandlerController.onAfterInsert(trigger.new);
                                } else if ( trigger.isUpdate ) {
                                                OpportunityHandlerController.onAfterUpdate(trigger.new, trigger.oldMap);
                                }
                                else if ( trigger.isDelete ) {
                                                OpportunityHandlerController.onAfterDelete(trigger.old, trigger.oldMap);
                                }
                }
}

Apex Controller:

public class OpportunityHandlerController {
                public static void onBeforeInsert(List<Opportunity> OpportunityList) {
                                /*
                                call before insert actions
                                */
                }

                public static void onBeforeUpdate(List<Opportunity> OpportunityList, Map<Id, Opportunity> mapOpptyOld) {
                                /*
                                call before update actions
                                */
                }

                public static void onAfterInsert(List<Opportunity> OpportunityList) {
                                /*
                                call after insert actions
                                */
                }

                public static void onAfterUpdate(List<Opportunity> OpportunityList, Map<Id, Opportunity> mapOpptyOld) {
                                /*
                                call after update actions
                                */
                }

                public static void onAfterDelete(List<Opportunity> OpportunityList, Map<Id, Opportunity> mapOpptyOld) {
                                /*
                                call after delete actions
                                */
                }

                public static void onBeforeUpdate(List<Opportunity> OpportunityList, Map<Id, Opportunity> mapOpptyOld) {
                                /*
                                call before delete actions
                                */
                }

}

 

How to write Test Class for after update Trigger handler class and trigger

hi   can anybody help me to write Test class for this Trigger  and trigger handler class (after update)
custom object(Meeting__c in this checkbox field defult checked)
scenario:if opportunity stage is 'closed own' or 'closed lost' then meeting__object check box is unchecked

opportunityTrigger
trigger opportunityFactoryTrigger on Opportunity (after update) {
  opportunityFactoryTriggerHandler.doAfterUpdate(trigger.new,trigger.newMap);
   
}

opportunityFactoryTriggerHandler​
public  class opportunityFactoryTriggerHandler {
     public static void doAfterUpdate(List<Opportunity> oppRecList, Map<Id, Opportunity> newMap){
      List<Meeting__c> mettingRecList1 = new List<Meeting__c>();
      List<Meeting__c> meetingRecListToBeUpdated = new List<Meeting__c>();
      mettingRecList1 = [SELECT Id, Opportunity__c FROM Meeting__c WHERE Opportunity__c IN :newMap.keySet()];
        for(Opportunity oppRec : oppRecList){
               if(oppRec.StageName == 'Closed Won' || oppRec.StageName == 'Closed Lost' ) {
                    for(Meeting__c meetingRec : mettingRecList1) {
                        if(meetingRec.Opportunity__c == oppRec.Id) {
                          meetingRec.Outcome_Flag__c = false;
                          meetingRecListToBeUpdated.add(meetingRec);
                        }   
                       
                    }
                   
                }
         }
          update meetingRecListToBeUpdated;
    }    

}
Your Test Class should contains the following items.
     --> Write a Test Method
             --> Create one Opportunity Record.
             --> Using the Opportunity Record, create a Meeting__c record. Make sure that it is a child to the created opportunity.
             --> Update the Stage to 'Closed Won' or 'Closed Lost' on above created Opportunity.
             --> Retrieve the Meeting__c records using SOQL and write the Assertions
01
@isTest
02
public class opportunityFactoryTriggerHandler {

03
    @isTest
04
    public static void testDoAfterUpdate() {

05
         
06
        Opportunity opp = new Opportunity();

07
        opp.Name = 'Test Opp';
08
        opp.CloseDate=System.Today();

09
                opp.StageName='Prospect';
10
         

11
        insert opp;
12
         

13
        Meeting__c me = new Meeting__c();
14
        me.Name = 'Test Meeting';

15
        me.Opportunity__c = opp.Id;
16
        insert me;

17
         
18
        opp.StageName = 'Closed Won';

19
        update opp;
20
    }

21
}

 

 

How to do Integration between two different organizations in salesforce Using REST API and REST Web Service and Apex Web Service?

For this post, I will offer a simple explanation of the complex, yet interesting areas essential for the complete understanding of Salesforce Integration’s capabilities. The business scenario quoted, along with the working code samples, will be a good starting point for entering into the world of non-declarative ways for integrating with Salesforce. Here’s what I’ll cover:

Understanding authentication and its prerequisites
OAuth authentication flows for REST API calls
Apex triggers and callouts
REST API, REST web services, and Apex web services

1) Authentication and Its Prerequisites
Authenticating a client application is the first and foremost step while building an interface.

The authentication method depends on your chosen call type (REST or SOAP). Let’s see how to do it using REST.

Before moving any further, let’s frame a business scenario. We’ll use two Salesforce instances that exchange Account details. When a new Account is created in one org, it will flow down to the other Salesforce org, and in return the source org will get the Salesforce Record ID of the created record. These two orgs are:

Source Salesforce org (used for callout) – Source
Target Salesforce org (used for receiving requests) – Target

Following our business scenario, we can say that authentication is a collection of the following sub-steps. Though actual authentication calls a trigger from the Apex code, consider these steps as the prerequisites because without them being completed first, the authentication calls won’t work.

Choosing OAuth Endpoint (to be invoked from Source org)
Choosing OAuth Authentication flow (to be used by Source org)

Remote Site Setting in Source Org.



Connected App enables Salesforce to recognize and authenticate an external application as a new entry point. OAuth is used for this authentication. We need to create a Connected App record in Target org. Below is an illustration.

Connected App in Target Org.



callback url should be specified in the remote site setting
Once after saving the record the client id and clientSecret are generated.

Create a Trigger to make an asynchronous call from source org to target org

Trigger on account Object:
trigger SendAccount on Account(after insert)
{
for(Account a : Trigger.new){
SendAccountFromSource.createAccount(a.Name, a.Id);
}
}

Apex Class to make a callout :

Replace the clientid,secret,username and password's of your org.
public class SendAccountFromSource {
private final String clientId = 'Clent Id from App';
private final String clientSecret = 'clientSecretfrom app';
private final String username = 'username';
private final String password = 'passwordwithsecuritytoken';
public class deserializeResponse
{
public String id;
public String access_token;
}
public String ReturnAccessToken (SendAccountFromSource acount)
{
String reqbody = 'grant_type=password&client_id='+clientId+'&client_secret='+clientSecret+'&username='+username+'&password='+password;
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setBody(reqbody);
req.setMethod('POST');
HttpResponse res = h.send(req);
deserializeResponse resp1 = (deserializeResponse)JSON.deserialize(res.getbody(),deserializeResponse.class);
return resp1.access_token;
}
@future(callout=true)
public static void createAccount(String accName, String accId)
{
SendAccountFromSource acount = new SendAccountFromSource();
String accessToken = acount.ReturnAccessToken (acount);

if(accessToken != null)
{
String jsonstr = '{"Name" : "' + accName + '"}';
Http h2 = new Http();
HttpRequest req1 = new HttpRequest();
req1.setHeader('Authorization','Bearer ' + accessToken);
req1.setHeader('Content-Type','application/json');
req1.setHeader('accept','application/json');
req1.setBody(jsonstr);
req1.setMethod('POST');
req1.setEndpoint(endPoint);
HttpResponse res1 = h2.send(req1);

deserializeResponse resp2 = (deserializeResponse)JSON.deserialize(res1.getbody(),deserializeResponse.class);
Account a = [SELECT Id FROM Account WHERE Id = :accId];
a.externalId__c = resp2.id;
update a;
}
}
}
Explanation –
1 Setting the REST API resource to create an Account (sObject)
2 Creating the JSON string to be sent as the input
3 Setting the Header to include the access token
4 Querying the Account record in Source Org so it can be updated
5 Setting the custom foreign key field on Account in Source Org with the extracted Account ID from the response.

Till here we have worked with 
Rest API.

REST Webservices

When working with rest webservices we need to change the code in the createAccount method in SendAccountFromSource class . Which looks like
if(accessToken != null)
{
String jsonstr = '{"AccName" : "' + accName + '"}';

Http h2 = new Http();
HttpRequest req1 = new HttpRequest();
req1.setHeader('Authorization','Bearer ' + accessToken);
req1.setHeader('Content-Type','application/json');
req1.setHeader('accept','application/json');
req1.setBody(jsonstr);
req1.setMethod('POST');
req1.setEndpoint(endPoint);
HttpResponse res1 = h2.send(req1);

String trimmedResponse = res1.getBody().unescapeCsv().remove('\\');
deserializeResponse resp2 = (deserializeResponse)JSON.deserialize(trimmedResponse, deserializeResponse.class);
Account a = [SELECT Id FROM Account WHERE Id = :accId];
a.externalId__c= resp2.id;
update a;
}

Here in this example we need to change the endpoint url that is pointing to createAccount class in the target org. Create a new rest web service class createAccount in target org.
@RestResource(urlMapping='/v1/createAccount/*')
global with sharing class createAccount
{
@HttpPost
global static String createAccount(String AccName)
{
Account a = new Account();
a.Name = AccName;
insert a;
String returnResponse = JSON.serialize(a);
return returnResponse;
}
}
Explanation –
1 Exposing the web service using the @RestResource annotation
2 Exposing method as REST resource to be called when HTTP Post request is made to this web service
3 Creating a new Account in Target org and setting the name as passed from Source org
4 Serializing the response (Account details) before sending
5 Sending the response.

Apex Web Service

Finally, the third option is the Apex Web Service that uses SOAP to handle integration. The class written at the target needs to be exposed as a global Web Service.
global class CreateAccountApexWS
{
global class sAccount
{
webservice String name;
}
webservice static String createAccount(sAccount sAcct)
{
Account acct = new Account();
acct.Name = sAcct.name;
insert acct;
String returnResponse = JSON.serialize(acct);
return returnResponse;
}
}
Explanation –
1 Creating a Global class that can be accessed from anywhere
2 Using the webservice keyword to expose class variable as an input to the web service
3 Using the webservice keyword to expose the class method as a custom SOAP Web Service

Saturday, November 21, 2015

How to encrypt string to Base64 in salesforce

Base64 is often used when you need to encode binary data into characters. Base64 is a good way of taking binary data and turning it into text so that it can easily be transmitted in things like HTML form data and email. Salesforce.com makes it pretty easy to perform Base-64 encoding in Apex via their EncodingUtil class. Below is an Apex code snippet with a very simple example of the base-64 encode/decode.
string before = 'Testing base 64 encode';

// create a blob from our parameter value before we send it as part of the url
Blob beforeblob = Blob.valueOf(before);

// base64 encode the blob that contains our url param value
string paramvalue = EncodingUtil.base64Encode(beforeblob);

// print out the encoded value to the debug log so we can see it before/after base64 encode
System.debug(before + ' is now encoded as: ' + paramvalue);

// take the base64 encoded parameter and create base64 decoded Blob from it
Blob afterblob = EncodingUtil.base64Decode(paramvalue);

// Convert the blob back to a string and print it in the debug log
System.debug(paramvalue + 'is now decoded as: ' + afterblob.toString());


Interview questions on triggers In salesforce
1.What is trigger ?
Ans: Trigger is piece of code that is executes before and after a record is Inserted/Updated/Deleted from the force.com database.

2.What are different types of triggers in sfdc?
Ans: 1.Before Triggers-These triggers are fired before the data is saved into the database.
2.After Triggers-These triggers are fired after the data is saved into the database.

3.What are trigger context variables?
Ans:
Trigger.isInsert: Returns true if the trigger was fired due to insert operation.
Trigger.isUpdate: Returns true if the trigger was fired due to update operation.
Trigger.isDelete: Returns true if the trigger was fired due to delete operation.
Trigger.isBefore: Returns true if the trigger was fired before record is saved.
Trigger.isAfter: Returns true if the trigger was fired after record is saved.
Trigger.New: Returns a list of new version of sObject records.
Trigger.Old: Returns a list of old version of sObject records.
Trigger.NewMap: Returns a map of new version of sObject records. (map is stored in the form of map)
Trigger.OldMap: Returns a map of old version of sObject records. (map is stored in the form of map)
Trigger.Size: Returns a integer (total number of records invoked due to trigger invocation for the both old and new)
Trigger.isExecuting: Returns true if the current apex code is a trigger.

4.What is the difference between Trigger.New and Trigger.NewMap?
Ans:
Trigger.New is Returns a list of new version of sObject records but Trigger.NewMap is Returns a map of new version of sObject records.

5.What is the difference between Trigger.New and Trigger.Old?
Ans:
Trigger.New is Returns a list of new version of sObject records and Trigger.Old is Returns a list of old version of sObject records.

6.What is the difference between Trigger.New and Trigger.Old in update triggers?
Ans:

7.Can we call batch apex from the Trigger?
Ans: 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);

8.What are the problems you have encountered when calling batch apex from the trigger?
Ans:

9.Can we call the callouts from trigger?
Ans: 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

10.What are the problems you have encountered when calling apex the callouts in trigger?
Ans:

11.What is the recursive trigger?
Ans: 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)

12.What is the bulkifying triggers?

Ans: 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.

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

14.What is the order of executing the trigger apex?
Ans:
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.

15.What is the trigger handler?
Ans:

16.How do we avoid recursive triggers?
Ans: Use a static variable in an Apex class to avoid an infinite loop. Static variables are local to the context of a Web request.

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

18.Can we define triggers with same event on single object?
Ans:

19.Tell me more scenarios where you have written triggers?
Ans:

20.What is the best scenario that you have developed on triggers?
Ans:

21.How many time workflow filed update will be called in triggers?
Ans:

Interview Questions on Batch Apex In salesforce
1.What are the soql limitations in apex?
Ans: Total number of records retrieved by SOQL queries-50,000

2.What are the transaction limitations in apex?
Ans: Each execution of a batch Apex job is considered a discrete transaction.
For example, a batch Apex job that contains 1,000 records and is executed without the optional scope parameter from Database.executeBatch is considered five transactions of 200 records each.
The Apex governor limits are reset for each transaction.
If the first transaction succeeds but the second fails, the database updates made in the first transaction are not rolled back.

3.What is the need of batch apex?
Ans: By using Batch apex classes we can process the records in batches in asynchronously.

4.What is Database.Batchable interface?
Ans: The class that implements this interface can be executed as a batch Apex job.

5.Define the methods in batchable interface?
Ans:
Start:
global Database.Querylocator start (Database.BatchableContext bc){}
Execute:
global void execute(Database.BatchableContext bc,List <p>){}
Finish:
global void finish(Database.BatchableContext bc) {}

6.What is purpose of start method in batch apex?
Ans: It collect the records or objects to be passed to the interface method execute.

7.What is the Database.QueryLocator?
Ans: If we use a Database.QueryLocator,
the governor limit for the total number of records retrieved by SOQL queries is bypassed. (Default 50,000 It allow up to 50 million records).

8.What is the iterable<Sobject>?
Ans: If you use an iterable,
the governor limit for the total number of records retrieved by SOQL queries is still enforced.

9.What is the use of execute method?
Ans: Contains or calls the main execution logic for the batch job.

10.How many times execute method is called?
Ans: Execute method is called for  each batch of records.

11.What is the scope of execute method?
Ans: The maximum value for the optional scope parameter is 2,000

12.Can we call callouts from batch apex?
Ans: Yes we can call.

13.Can we call another batch apex from batch apex?
Ans: Yes you can call a batch apex from another batch apex .Either in start method or in finish method you can call other batch

14.How many callouts we can call in batch apex?
Ans: Batch executions are limited to one callout per execution.

15.Batch is synchronous or Asynchronous operations?
Ans: Asynchronous operations.

16.What is the maximum size of the batch and minimum size of the batch ?
Ans: The default batch size is 200 records. min?
max?

17.What is the Database.BatchableContext?
Ans: BatchableContext Interface is Represents the parameter type of a batch job method and
contains the batch job ID. This interface is implemented internally by Apex.

18.How to track the details of the current running Batch using BatchableContext?
Ans: You can check the AsyncApexJob.Status using the JobId from the Database.BatchableContext.

19.How many batch jobs can be added to queue?
Ans: Queued counts toward the limit of 5.

20.What is Database.State full interface?
Ans:To maintain variable value inside the Batch class, Database.Stateful is used.

21.What is Database.AllowCallouts?
Ans:
To use a callout in batch Apex, you must specify Database.AllowsCallouts in the class definition. For example:
global class SearchAndReplace implements Database.Batchable<sObject>,
   Database.AllowsCallouts{
              //Business logic you want by implementing Batchable interface methods
}
Callouts include HTTP requests as well as methods defined with the webService keyword.

22.What is AsyncApexJob object?
Ans: AsyncApexJob is Represents an individual Apex sharing recalculation job.
Use this object to query Apex batch jobs in your organization.

23.When a BatchApexworker record is created?
Ans: For each 10,000 AsyncApexJob records, Apex creates one additional AsyncApexJob record of type BatchApexWorker for internal use. 

1.Whatis work flow ?
Ans: Work flow works based on certain criteria,By using workflow we can automate the business process like Email alerts,tasks,filed updates

2. What are the different kinds of evaluation criteria’s (events)?
Ans: 1.created
2.created, and every time it’s edited
3.created, and any time it’s edited to subsequently meet criteria

3. In which object workflows are stored?
Ans: Workflow

4. What is the difference between Created and everytime edited to meet the criteria and Created and edited to subsequently meet the criteria?
Ans: If we select 'Created and everytime edited to meet the criteria' whenever we create a record or edit a record if the criteria of the workflow rule meets then it will trigger every time. If we select 'Created and edited to subsequently meet the criteria' -

While creating the record criteria meets so that workflow will fire and while editing the record again criteria meets workflow won't fire (meeting the criteria to meeting the criteria)
While creating the record criteria doesn't meet so workflow won't fire and while editing the record workflow criteria meets then workflow will fire (not meeting the criteria to meeting the criteria)
Conclusion: Previous state of record should be not meeting criteria and current state of record should be meeting the criteria then only in current state workflow will fire.

5.What are the types of rule criteria’s?
Ans: 1.Criteria meet (field - operator - value, if there are multiple criteria’s then in filter criteria we can give conditions like ( 1 or 2) and 3, field to field comparison is not possible, we can't fetch the previous state information of the field )
2.Formula evaluated (we can write formulas with this we can do field to field comparison and we can fetch previous state value of the record)

6. What is immediate workflow action?
Ans: The action which will be performed immediately after the record criteria meets.

7. What is time dependent workflow action?
Ans: The action which will be performed in future based on the any of the date field. To create time dependent workflow action we should create one time trigger. in time trigger we can give either days or hours with the maximum of 999 value and we can select either before or after.

8. For which event we can't create time dependent workflow action?
Ans: Created and everytime edited to meet the criteria.

9. What are the different kinds of workflow actions?
Ans: New field update (we can update a field of the same object or the fields of the parent objects which are at master side in master-detail relationship, only for master-detail parent objects we can update the field and for lookup we can't update)
New email alert (we can send emails if the criteria meets)
New task (we can create new task)
New outbound Message (we can make a callout)

10. What are the types of email templates?
Ans:1.Text
2.HTML (with letter head)
3.Custom HTML (without letter head)
4.Visual Force

12. How can you monitor future actions of time based workflow?
Ans: setup --> administration set up --> monitoring --> time based workflow

13. There is a timebased workflow which will update one of the fields if the criteria meet. User submits the record with valid criteria, workflow triggered so that the field update is queued in the 'time based flow' queue which will fire after one day. If the user modifies the record which is submitted before the scheduled date, after modification, a record criterion is not meeting. Whether the field will be updated or not in schedule date?
Ans: It won't trigger in the schedule date because if we modify the record to not meeting criteria that queued field update will be removed from the 'time based flow' queue.

14. For the same scenario explained in the above question what happens when we deactivate or modify the criteria of the workflow to different criteria? Whether the field will be updated or not in schedule date?
Ans: Yes, It will trigger in scheduled date.

15. Scenario: There are two workflow rules on the same object say namely wf1 and wf2. If wf1 fires then a field will be updated on the same object, if the field updated and due to this wf2 criteria meets then what will happen, wf2 will fire or not?
Ans: It won't fire. To fire wf2 we should enable 'Re-evaluate Workflow Rules' checkbox of the field update which is there in wf1.

16. What is recursive workflow rule? How to avoid recursive workflow rules?
Ans:Whenever we enable Re-evaluate Workflow Rules after Field Change checkbox in the Field Update of a workflow rule, due to this field update other workflow rules on the same object will be fired if the entery criteria of those workflow rules satisfied.

Incase, in other workflow rules also if we enable Re-evaluate Workflow Rules after Field Change checkbox in the Field Update recursive workflow rules will come in some scenarios.

We can take two steps to avoid recursive workflow rules -

For the workflow Evaluation Criteria if you choose created, and any time it’s edited to subsequently meet criteria option, we can avoid recursive workflow rules.
If you don't enable Re-evaluate Workflow Rules after Field Change checkbox in the Field Update of a workflow rule we can avoid.

17. What is Approval Process?

Ans: If the criteria of the record meets then by clicking on submit for Approval button user can submit the record for approval (Note: Approval history related list should be displayed on the record detail page)

18. Scenario: After activating the approval process, I want to add one more step. Is it possible?
Ans: It’s not possible, to add one more step deactivate the approval process and clone the deactivated approval process and add the new steps.

19.In which object all Approval process are stored?
Ans: Approval
Interview Questions on Profiles,Permission set,users,OWD,Roles and Sharing Rules in salesforce
1.What is Profile?
ANS: Profile contains set of permissions and access settings that controls what user can do with in the organization.

2. What are permission sets?
ANS: A set of permissions is given to the users without changing the profile.

3.What is OWD?
ANS: OWD'S are base line record level security for objects in the organization.
It is used to restrict access to data.

4.What is Roles?
ANS: A role controls the level of visibility that users have to an organization's data.

5.What is User?
ANS:The people who have authenticated username and password to login to the salesforce successfully.

6.What is Sharing Rules?
ANS:These are used to override the OWD permissions.
Sharing rules are two types
1.Based on record owner
2.Based on createria.

7.What is the role hierarchy?
ANS:Role Hierarchy states that higher hierarchy person can see lower hierarchy person records.

8.Can you override profile permissions with permission sets(i have defined some permissions in profile,i am trying to use permission sets for the same object,can i override permissions for a particular object in the permission sets over to the profile?
ANS:No. Permission Sets are used only to extend the Profile permissions. It never overrides.

9. I want to have read/write permission for User 1 and read only for User 2, how can you acheive?
ANS:Create a Permission Set with read/write and assign it to User 1.

10. I have an OWD which is read only, how all can access my data and I want to give read write access for a particular record to them, how can i do that?
ANS:All users can just Read the record.
Create a Sharing Rule to give Read/Write access with "Based on criteria" Sharing Rules.

11.What is the difference between role hierarchy and sharing rules?will both do the same permissions?
ANS:Role Hierarchy states that higher hierarchy person can see lower hierarchy person records.
Sharing Rule is used to extend Role Hierarchy.

12. Is it possible to delete the user in salesforce?
ANS:No, once we create an user in salesforce we cannot delete the user record. We can only deactivate the user record.

13.How to provide security for Meta-Data files (Schema)?
ANS:Using Profiles and Permission Sets.

13. How to give permissions to two fields for different users who belongs to different profiles?
ANS:Permission set

14. How many users are there in your project salesforce instance?
ANS:1000 (It will depends upon the number of licenses taken by the client, it will be like upto 4000 like that based on the client)

15.What is Grant Access Using Hierarchies?
ANS:In OWD we have Private but your higher position persons should see that time we go for Grant Access Using Hierarchies.

16. How we can change the Grant access using role hierarchy for standard objects?
ANS:Not possible.

17.What is manual sharing?
ANS:Manual sharing is to share a record to a particular user manually.
Go to detail page of record and click on manual sharing button and assign that record to other user with Read or Read/Write access.
Manual Sharing button enables only when OWD is private to that object.

18.Can you tell the difference between Profile and Roles?
ANS:Profiles are used for Object level access settings.
Roles are used for Record level access settings.

1.What is SOAP and What is REST?

REST API

Representational State Transfer.
It is based URI
It works with GET,POST,PUT,DELETE
Works Over with HTTP and HTTPS


SOAP API

Simple Object Access Protocol.
It is based on Standard XML format
It is works with WSDL
Works Over with HTTP,HTTPS,SMPT,XMPP


2.Difference between REST API and SOAP API?
Ans :Varies on records that can be handled. Generally if we want to access less number of records we go for REST API.

3.What is WSDL?
A WSDL is an XML Document which contains a standardized description of how to communicate using webservice.

4.What are the different type of WSDL'S?
Ans:
Enterprise WSDL
Partner WSDL
Apex WSDL
Metadata WSDL
Tooling WSDL
Delegated Atuntection WSDL

5.Difference between Enterprise WSDL and Partner WSDL?
Ans:
Enterprise WSDL:
It is used for building client applications for a single salesforce organization.
Customers who use enterprise WSDL document must download and re-consume it when ever their organization makes a change to its custom objects or fields or when ever they want to use a different version of the API.
Partner WSDL:
It is used for building client applications for multiple organizations.
The partner WSDL documention only needs to be downloaded consumed once per version of the API.

6.How can you expose an apex class as a REST web service in salesforce?
Ans - An apex class can be exposed as REST web service by using keyword '@RestResource'

7.How to fetch data from another Salesforce instance using API?
Ans :Use the Force.com Web Services API or Bulk API to transfer data We this this is a great job for the Bulk API.

8.How to call Apex method from a Custom Button?
Ans :An Apex callout enables you to tightly integrate your Apex with an external service by making a call to an external Web service or sending a HTTP request from Apex code and then receiving the response.
Apex provides integration with Web services that utilize SOAP and WSDL, or HTTP services (RESTful services).

9.What is the use of Chatter REST API?
The Chatter API (also called Chatter REST API) lets you access Chatter information via an optimized REST-based API accessible from any platform. Developers can now build social applications for mobile devices, or highly interactive websites, quickly and efficiently.

10.How to fetch data from another Salesforce instance using API?
Answer: Use the FORCE.COM WEB SERVICES API or BULK API to transfer data We this this is a great job for the Bulk API.

11.What are callouts and call ins?
Making a request to an external system from salsforce is callout.

Getting requests from an external system is a call in.

12.How many callouts to external service can be made in a single apex transaction?
Ans - A total of 10 callouts are allowed in a single apex transaction.

13.What is the maximum allowed time limit while making a callout to external service in apex?
Ans - maximum of 120 second time limit is enforced while making callout to external service

14.What is the default timeout period while calling webservice from Apex.
Ans : 10 sec.

15.can we define custom time out for each call out?
Ans :
A custom time time can be defined for each callout.
the minimum time is 1 millisecond and maximum is 120,000 milli seconds.

16.How to increase timeout while calling web service from Apex ?
Ans :
docSample.DocSamplePort stub = new docSample.DocSamplePort();
stub.timeout_x = 2000; // timeout in milliseconds

Dear readers, these RESTful Web services Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of RESTful Web services. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer −
What REST stands for?
REST stands for REpresentational State Transfer.
What is REST?
REST is web standards based architecture and uses HTTP Protocol for data communication. It revolves around resource where every component is a resource and a resource is accessed by a common interface using HTTP standard methods. REST was first introduced by Roy Fielding in 2000.
In REST architecture, a REST Server simply provides access to resources and REST client accesses and presents the resources. Here each resource is identified by URIs/ global IDs. REST uses various representations to represent a resource like text, JSON and XML. Now a days JSON is the most popular format being used in web services.
Name some of the commonly used HTTP methods used in REST based architecture?
Following well known HTTP methods are commonly used in REST based architecture −
·        GET − Provides a read only access to a resource.
·        PUT − Used to create a new resource.
·        DELETE − Ued to remove a resource.
·        POST − Used to update a existing resource or create a new resource.
·        OPTIONS − Used to get the supported operations on a resource.
What are webservices?
A web service is a collection of open protocols and standards used for exchanging data between applications or systems. Software applications written in various programming languages and running on various platforms can use web services to exchange data over computer networks like the Internet in a manner similar to inter-process communication on a single computer.
What are RESTful webservices?
Web services based on REST Architecture are known as RESTful web services. These web services use HTTP methods to implement the concept of REST architecture. A RESTful web service usually defines a URI, Uniform Resource Identifier a service, provides resource representation such as JSON and set of HTTP Methods.
What is a Resource in REST?
REST architecture treats every content as a resource. These resources can be text files, html pages, images, videos or dynamic business data. REST Server simply provides access to resources and REST client accesses and modifies the resources. Here each resource is identified by URIs/ global IDs.
How to represent a resource in REST?
REST uses various representations to represent a resource where text, JSON, XML. XML and JSON are the most popular representations of resources.
What are the best practices to design a resource representation?
Following are important points to be considered while designing a representation format of a resource in a RESTful web services −
·        Understandability − Both Server and Client should be able to understand and utilize the representation format of the resource.
·        Completeness − Format should be able to represent a resource completely. For example, a resource can contain another resource. Format should be able to represent simple as well as complex structures of resources.
·        Linkablity − A resource can have a linkage to another resource, a format should be able to handles such situations.
Which protocol is used by RESTful webservices?
RESTful web services make use of HTTP protocol as a medium of communication between client and server.
What is messaging in RESTful webservices?
A client sends a message in form of a HTTP Request and server responds in form of a HTTP Response. This technique is termed as Messaging. These messages contain message data and metadata i.e. information about message itself.
What are the core components of a HTTP Request?
A HTTP Request has five major parts −
·        Verb − Indicate HTTP methods such as GET, POST, DELETE, PUT etc.
·        URI − Uniform Resource Identifier (URI) to identify the resource on server.
·        HTTP Version − Indicate HTTP version, for example HTTP v1.1 .
·        Request Header − Contains metadata for the HTTP Request message as key-value pairs. For example, client ( or browser) type, format supported by client, format of message body, cache settings etc.
·        Request Body − Message content or Resource representation.
What are the core components of a HTTP response?
A HTTP Response has four major parts −
·        Status/Response Code − Indicate Server status for the requested resource. For example 404 means resource not found and 200 means response is ok.
·        HTTP Version − Indicate HTTP version, for example HTTP v1.1 .
·        Response Header − Contains metadata for the HTTP Response message as key-value pairs. For example, content length, content type, response date, server type etc.
·        Response Body − Response message content or Resource representation.
What is addressing in RESTful webservices?
Addressing refers to locating a resource or multiple resources lying on the server. It is analogous to locate a postal address of a person.
What is URI?
URI stands for Uniform Resource Identifier. Each resource in REST architecture is identified by its URI.
What is purpose of a URI in REST based webservices?
Purpose of an URI is to locate a resource(s) on the server hosting the web service.
What is format of a URI in REST architecture?
A URI is of following format −
<protocol>://<service-name>/<ResourceType>/<ResourceID>
What is the purpose of HTTP Verb in REST based webservices?
VERB identifies the operation to be performed on the resource.
What are the best practices to create a standard URI for a web service?
Following are important points to be considered while designing a URI −
·        Use Plural Noun − Use plural noun to define resources. For example, we've used users to identify users as a resource.
·        Avoid using spaces − Use underscore(_) or hyphen(-) when using a long resource name, for example, use authorized_users instead of authorized%20users.
·        Use lowercase letters − Although URI is case-insensitive, it is good practice to keep url in lower case letters only.
·        Maintain Backward Compatibility − As Web Service is a public service, a URI once made public should always be available. In case, URI gets updated, redirect the older URI to new URI using HTTP Status code, 300.
·        Use HTTP Verb − Always use HTTP Verb like GET, PUT, and DELETE to do the operations on the resource. It is not good to use operations names in URI.
What is statelessness in RESTful Webservices?
As per REST architecture, a RESTful web service should not keep a client state on server. This restriction is called statelessness. It is responsibility of the client to pass its context to server and then server can store this context to process client's further request. For example, session maintained by server is identified by session identifier passed by the client.
What are the advantages of statelessness in RESTful Webservices?
Following are the benefits of statelessness in RESTful web services −
·        Web services can treat each method request independently.
·        Web services need not to maintain client's previous interactions. It simplifies application design.
·        As HTTP is itself a statelessness protocol, RESTful Web services work seamlessly with HTTP protocol.
What is statelessness in RESTful Webservices?
As per REST architecture, a RESTful web service should not keep a client state on server. This restriction is called statelessness. It is responsibility of the client to pass its context to server and then server can store this context to process client's further request. For example, session maintained by server is identified by session identifier passed by the client.
What are the advantages of statelessness in RESTful Webservices?
Following are the benefits of statelessness in RESTful web services −
·        Web services can treat each method request independently.
·        Web services need not to maintain client's previous interactions. It simplifies application design.
·        As HTTP is itself a statelessness protocol, RESTful Web services work seamlessly with HTTP protocol.
What are the disadvantages of statelessness in RESTful Webservices?
Following is the disadvantage of statelessness in RESTful web services −
Web services need to get extra information in each request and then interpret to get the client's state in case client interactions are to be taken care of.
What do you mean by idempotent operation?
Idempotent operations means their result will always same no matter how many times these operations are invoked.
Which type of Webservices methods are to be idempotent?
PUT and DELETE operations are idempotent.
Which type of Webservices methods are to be read only?
GET operations are read only and are safe.
What is the difference between PUT and POST operations?
PUT and POST operation are nearly same with the difference lying only in the result where PUT operation is idempotent and POST operation can cause different result.
What should be the purpose of OPTIONS method of RESTful web services?
It should list down the supported operations in a web service and should be read only.
What should be the purpose of HEAD method of RESTful web services?
It should return only HTTP Header, no Body and should be read only.
What is caching?
Caching refers to storing server response in client itself so that a client needs not to make server request for same resource again and again. A server response should have information about how a caching is to be done so that a client caches response for a period of time or never caches the server response.
Which header of HTTP response, provides the date and time of the resource when it was created?
Date header provides the date and time of the resource when it was created.
Which header of HTTP response, provides the date and time of the resource when it was last modified?
Last Modified header provides the date and time of the resource when it was last modified.

Post a Comment