Thursday, November 26, 2015

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.

Interview Questions on REST API and SOAP API in salesforce

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

17.What is the use of JSON?

Interview questions on Sandbox environment in salesforce

1.What is refreshing of sandbox and how to do it?
In order to update the sandbox with the data in production.
Refresh is done and refreshing a sandbox delete s the previous copy and updates sandbox with copy of production.

To refresh a sandbox logon to salesforce.com
With production id and password
Go to setup>company name>administrative tools>data management >sandbox
Click refresh link next to sandbox

Note: make sure u have a copy of it before u refresh sandbox

2.What is sandbox?
To make any changes for the exiting application we should copy all contents of the production into sandbox and make all changes after that test thoroughly after that move those changes into production.
To create the sandbox, in production we can find one link called sandboxes. by clicking on that link we can create the sandbox by choosing type of the sandbox.

3.What is sandbox url?
test.salesforce.com

4. What are the types of Sandboxes?

Interview questions on Reports and Dashboard in salesforce

1. What is Report?
To summarize the information of an object we use reports.

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

3. How many blocks we can create for join reports?
5 blocks.

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

5. What is bucketing in reports?
Bucket field in Reports in Salesforce is used to group values to the name we specify.
It can group only the below data types fields
1. Picklist
2. Number
3. Text

6. How many records we can display on page for a report?
We can display up to 2000 records on a page. If more records are there to display we cannot see those through user interface. If you export the records to a excel sheet then you can export all records.

7.Can we mass delete reports using Apex (Anonymous Apex)?
Salesforce has not exposed any API for Reports. So best way is :
Move all reports needs to delete in new folder.
Inform everyone that reports will be deleted after some time may be 30 days.
Import your reports folder in Eclipse including all reports to be deleted and then delete the the reports folder in eclipse. It will delete all the reports at once.

8.Explain what is dashboard?
Dashboard is the pictorial representation of the report, and we can add up to 20 reports in a single dashboard.

9.What are the different Dashboard Components?
Salesforce dashboard components are used to represent data. Salesforce dashboards have some visual representation components like graphs, charts, gauges, tables, metrics and visualforce pages. We can use up to 20 components in single dashboard.

10.Is it possible to schedule a dynamic dashboard in Salesforce?
No, it is not possible to schedule a dynamic dashboard in Salesforce.

11.Which type of report can be used for dashboard components?
Summary and matric report.

12.Explain dynamic Dashboard?
Dynamic dashboards in Salesforce displays set of metrics that we want across all levels of your organization.
Dynamic Dashboards in salesforce are Created to provide security settings for the dashboards in salesforce.com. We may have a requirement in an organization to “view all data” by every user in an organization according to their access we have to select Run as Logged-in User. There are two setting option in Dashboards.
They are
1.Run as specified User.
2.Run as Logged-in User.

Interview Questions on Workflows and Approval Process In salesforce

1. What is 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 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. 

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:

Wednesday, November 25, 2015

How to delete all records from custom object in salesforce

Go to Developer Console>Debug> Open execute anonymous window

Write the below code

List<sobject__c> objDelList= [SELECT Id FROM sobject__c];
delete objDelList;

Click on the button execute button

Note: Replace  sobject__c with original custom object API name 

How to do Avalara tax API Integration With Salesforce?

Special thanks to Ashish Agarwal

Step 1: go to below link and fill the form to get your token and secret

               http://developer.avalara.com/api-get-started/

after submitting the form you will receive an email to your email address. Go there and click on the developer area link provided in email. In this email you will get your login ID and password also.

On developer page you will prompted to give your Id and password . Please fill provide them and login.

Now reset your new password and save.

Step 2: Now go to setting tab and click on Reset Licence Key and then click on generate button.

Step 3: Now check your email .you will find an email from avalara support .open it and get your account number and Licence Key.

Step 4: Setup Avatax Select the Country and set Jurisdictions see below image


Step 5: Now go to SETUP | ADMINISTER | SECURITY CONTROLS | REMOTE SITE SETTINGS and create a new Remote site.

Give remote site name avalara and Remote site url as “https://development.avalara.net “ .

Step 6 : Now create a apex class namely “avalaraController” and copy the code from below link and paste it .

Apex Class:
public class avalaraController
 {

//string variable to show api result
    public string result{get;set;}
//string variable to hold amount of line item
    public String amount { get; set; }
//string varriable to hold quantity of line item
    public String count { get; set; }
//string varriable to hold postal code of address
    public String PostalCode { get; set; }
//line 1 of address
    public String Line1 { get; set; }
//line 2 of address
    public String Line2 { get; set; }

//method to get tex value from avalara tex api    
public String RestRequest(String body,String endPoint,String method){
        
         Blob headerValue = Blob.valueOf("acount no"+':'+"Licence key");
         String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(headerValue);
                
         //accessing end point for avalara request type
        
         Http h=new Http();
         HttpRequest req = new HttpRequest();
         req.setMethod(method);
  
         req.setHeader('Authorization', authorizationHeader);
         req.setEndPoint(endPoint);
         req.setBody(body);
         HttpResponse res = h.send(req);
         result = res.getBody();
         return result;



}

//method to get Text
       public void getTex(){
//calling method to create json body for request body from user provided data
        
         String texString = createTexRequestBody();
         RestRequest(texString ,"https://development.avalara.net/1.0/tax/get" ,'POST');
               }
  //method to validate address             
      public void validateAddress() {
     
        endpoint = 'https://development.avalara.net/1.0/address/validate?Line1='+EncodingUtil.urlEncode(Line1+Line2,'UTF-8')+'&PostalCode='+EncodingUtil.urlEncode(PostalCode,'UTF-8');
        RestRequest('' ,endPoint ,'GET');
    }
 //method to create json string for rest request body        
      public String createTexRequestBody(){
      
      
       JSONGenerator gen= JSON.createGenerator(true);
        gen.writeStartObject();
        gen.writeStringField('DocDate', '2013-06-19');
        gen.writeStringField('CustomerCode', 'CUST1');
        gen.writeFieldName('Addresses');
        gen.writeStartArray();
        gen.writeStartObject();
        gen.writeStringField('AddressCode', '1');
        gen.writeStringField('Line1',Line1 );
        gen.writeStringField('Line2', Line2 );
        
        gen.writeStringField('PostalCode',PostalCode);
        gen.writeEndObject();
        gen.writeEndArray();
        gen.writeFieldName('Lines');
        gen.writeStartArray();
        gen.writeStartObject();
        gen.writeStringField('LineNo', '1');
        gen.writeStringField('DestinationCode', '1');
        gen.writeStringField('OriginCode', '1');
        gen.writeNumberField('Qty',Integer.valueOf(count));
        gen.writeNumberField('Amount',Integer.valueOf(amount));
        
        gen.writeEndObject();
        gen.writeEndArray();
        gen.writeEndObject();
        return gen.getAsString();
      
      
      }

}

Now in header section of the code replace account Number with your account no and licence key with your licence key provided in email and DocDate should be the date given in the AVATAX Starting date.

Step 7: Now create a visualforce page and give it name as “ avalara” and copy the code from following link and paste it in page
Visualforce Page:

    
        
 
                
                    HP Printer
                

                    Quatity
                
                
                    amount
                
                        
                            
                
                    Address Line1 
                       
                

                    Address  Line2  
                    
                

                    PostalCode 
                    
                
{!tax}
            
            
            
                
                    
Loading...
{!result}


Run your visualforce page and fill the form with quantity ,amount(price) and any right address with valid postal code(required) ( only america and canada address).

And click on get Tex.

And you will find the response.

Check the response string and you will find tax for amount you entered.


Output:

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');
req.setEndpoint('https://ap2.salesforce.com/services/oauth2/token');
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 endPoint = 'https://ap2.salesforce.com/services/data/v32.0/sobjects/Account/';
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 endPoint = 'https://ap2.salesforce.com/services/apexrest/v1/createAccount/';
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

Tuesday, November 24, 2015

How to call apex class from custom button(Javascript) in salesforce

In this beloow i showed you custom Lead conversion .
Here I have taken a custom object Students,
In that i have created one custom button called convert.
If we click on the convert the account,contact and opportunity should create.

First we need to Create on global class and the method you intend to call from the javascript must be a Webservice Method.
Apex Class:
global class customLead
{
 public Students__c objStudents{get;set;}
  
    webservice static void coversion(string student) 
    { 
    Students__c objStudents=new Students__c();
    
         objStudents=[SELECT ID,Name FROM Students__c WHERE id=:student];
         
         Account objAcc=new Account();
         objAcc.Name=objStudents.Name;
         Insert objAcc;
         
         contact Objcon=new contact();
         Objcon.Lastname=objStudents.Name;
         Insert Objcon;
         
        
         Opportunity objOpp= new Opportunity();
         objOpp.Name=objStudents.Name;
         objOpp.StageName='Active';
         objOpp.CloseDate=System.Today();

         Insert objOpp;
    }
}

Goto -->Setup-->Objects-->Students--->Buttons,links and Actions section
Click new Button or link.

Enter the Name of the button
Behaviour: Execute Javascript
Content Source :On-Click Javascript




Java Script Code:

{!REQUIRESCRIPT("/soap/ajax/30.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/30.0/apex.js")}

    var result =sforce.apex.execute("customLead","coversion",{student:"{!Students__c.Id}"});
    alert("result ");

window.location.reload();

Monday, November 23, 2015

How to add visualforce page in home page in salesforce?

If you want add visualforce page to home please follow the below

Step 1:-


Setup-->Customize-->Home--> Home Page components
click on Home Page components
In custom components section click on New
Give the name you want
We can show four different components in that Choose Visualforce Area click next
Component Position: Wide (Right) Column
Visualforce Page : Graduate List
Height (in pixels): 400
click save

Step 2:-


Setup-->Customize-->Home-->Home Page Layouts
In Home Page Layouts click on default then click on edit
In Select Wide Components to Show section check the Graduate List
then click next and then save
now check it will display like below.

How to have a star rating field on custom object in salesforce


Well, in that case, you'll have to create a separate field, most probably a Picklist Field would suit the need. You can create a Picklist Field say -
Label: RatingCode
Type: Picklist
Values:
1
2
3
4
5
And then create a another Formula Field on the same object. This is to represent the Rating "pictorially". That field would look like this -
Formula Return Type: Text
Label: StarRating
Type: Formula
Formula: 
IF(
    ISBLANK(TEXT(RatingCode__c)),
    NULL,
    IMAGE(
        "/img/samples/stars_" + TEXT(RatingCode__c) + "00.gif",
        "Rating Level"
    )
)

Output:-

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());

How to show 10,000 records in visualforce page

As the number of records increases, the time required for the browser to render them increases. Paging is used to reduce the amount of data exchanged with the client. Paging is typically handled on the server side (standardsetcontroller). The page sends parameters to the controller, which the controller needs to interpret and then respond with the appropriate data set. Here is the controller which makes use of standard set controller for pagination.
public with sharing class Pagination {
    Public Integer noOfRecords{get; set;}
    Public Integer size{get;set;}
    public ApexPages.StandardSetController setCon {
        get{
            if(setCon == null){
                size = 10;
                string queryString = 'Select Name, Type, BillingCity, BillingState, BillingCountry from Account order by Name';
                setCon = new ApexPages.StandardSetController(Database.getQueryLocator(queryString));
                setCon.setPageSize(size);
                noOfRecords = setCon.getResultSize();
            }
            return setCon;
        }set;
    }
     
    Public List<account> getAccounts(){
        List <account> accList = new List<account>();
        for(Account a : (List<account>)setCon.getRecords())
            accList.add(a);
        return accList;
    }
     
    public pageReference refresh() {
        setCon = null;
        getAccounts();
        setCon.setPageNumber(1);
        return null;
    }
     
    public Boolean hasNext {
        get {
            return setCon.getHasNext();
        }
        set;
    }
    public Boolean hasPrevious {
        get {
            return setCon.getHasPrevious();
        }
        set;
    }
  
    public Integer pageNumber {
        get {
            return setCon.getPageNumber();
        }
        set;
    }
  
    public void first() {
        setCon.first();
    }
  
    public void last() {
        setCon.last();
    }
  
    public void previous() {
        setCon.previous();
    }
  
    public void next() {
        setCon.next();
    }
}
 
Using the above controller methods we can define the pagination.

    
        
            
                
                
                
                
                
           
            
                
                
                
                 
                {!(pageNumber * size)+1-size}-{!IF((pageNumber * size)>noOfRecords, noOfRecords,(pageNumber * size))} of {!noOfRecords}
                
                
                    
                
             
           
        
    

How to do deployment through Changesets in Salesforce

Step1:
Login into the Sandox and then follow the below

Setup > Depoly > Outbound changeset > create new changeset > add components(Let say classes,pages etc.,) > Upload

Then logout from sandbox.

Step2:

Login into the Production

Setup > Depoly > Inbound changeset > Validate > Deploy

Note:
1.From Sandbox Just create outbound changeset and in the Production receive the Inbound changeset.
2.If any of them failed due to any reason the total will be rolled back.

How to Return PageReference from a webservice method

In your Class use a String as a Returntype
and create your reference like this in your webservice class
return String.valueOf( new PageReference('/'+Case.Id).getUrl());
and in your Button, you have to catch your return String and reload the page:
var newurl = sforce.apex.execute("TestClass","CreateTestRecords", {id:"{!Case.Id}"});
parent.location.href = newurl; //refresh the page