Wednesday, December 23, 2015

What is Roll Up summary field in Salesforce?

We can perform different types of calculations with your roll-up summary fields. You can count the number of detail records related to a master record, or calculate the sum, minimum value, or maximum value of a field in the detail records.

Note : Roll up summary field can only be defined on the master object.

While your formula fields calculate values using fields within a single record, roll-up summary fields calculate values from a set of related records, such as those in a related list.
The Roll up Summary field is basically of 4 types:
Count
Sum
Min
Max

What is junction object and how to create it?

Salesforce supports 2 kinds of relationships like Master Detail and Lookup. They are both one-to-many relationship, and they are both defined from the many-to-one side, that is from a child to a parent. They can be made one-to-one relationship by adding validation rules, or maybe triggers to enforce the one-to-one nature, i.e. only one child is allowed.

Junction objects are used to create many to many relationships between objects. If you take the Recruiting application example, you can see that a Position can be linked to many Candidates, and a Candidate can apply for different Positions. To create this data model you need a third object "Job Application" that links the 2.

So you'd create a lookup field for both Position and Candidate object on the "Job Application" object. This will establish many to many relationship between Position and Candidate via the "Job Application" object known as the junction object.

What is the difference between configuration and customization in Salesforce.

Configuration:

•Configuration means providing a user defined values which will enable a given feature or module to function.
Example: Email setting is an example of configuration.
•salesforce users can configure CRM application. Marketing User can enable few tabs which are not available for Customer support people.
• Adding a new field to a given salesforce object is configuration.
• adding a new field which will use formula to perform some result is configuration

Customization:

•Any feature or functions which are not available as a part of application and the application needs to extend refers to customization.
•Despite you configured the things there are few actions which are not achievable and it results into adding some custom code, which results in Customization.
• Adding triggers on the object to perform some action is called customization
• Adding Apex Code which will generate a vCard from a given Contact is called Customization.

Validation Rules In Salesforce

Validation rules helps you to improve data quality by preventing users from entering incorrect data. We can write one or more validation rules that consists of an error and corresponding error message.

1. Validation rules are executed will executed, when you are saving the record.
2. A validation rule that contains a formula or an expression that evaluates the data in one or more fields and returns a value, true or false. We can display error message at the top of the page or below the field when rule returns true.
3. After writing validation rules for a field or for set of fields, following actions will fired when user creates a new record or edits an existing records and then click on save button.
Salesforce executes validation rules you defined and if data is valid then record will save.
If entered invalid data, it will display the associated error message without saving the record.
Even if the fields referenced in the validation rules are not visible on the page layouts, the validation rule still apply and will result in an error message if the rule fails.

Creating validation rules:
For standard objects Go to setup -> Build – > Customize -> select standard object you want to create validation rule (For Ex: Account) -> and click on validation rules and then define your validationrule.

For custom objects Go to setup -> Build -> create -> object -> select object you want to create validationrules -> go to validation rules section and then create your validation rule.

Difference between standardcontroller, controller and extensions in Salesforce?

Standard Controller:
Standard Controller contain the same functionality and logic that are used for standard Salesforce pages.Can be used with standard objects and custom objects.

Controller:
Custom Controller is noting but we can define our logic and Functionality.If we want fine control for how information is accessed for your page, you can write a custom Controller.
Only one Apex class is used.

Extensions:
By using the extensions we can extends the functionality of a standard or custom controller.Multiple Apex classes separated by comma are used.

Batch Class in Salesforce?

Batch Apex :

By using Batch apex classes we can process the records in batches in asynchronously.
If you have a large number of records to process, for example, for data cleansing or archiving, batch Apex is your solution.
The execution logic of the batch class is called once for each batch of records.
The default batch size is 200 records.
You can also specify a custom batch size. Furthermore, each batch execution is considered a discrete transaction.

With each new batch of records, a new set of governor limits is in effect. In this way, it’s easier to ensure that your code stays within the governor execution limits.

Another benefit of discrete batch transactions is to allow for partial processing of a batch of records in case one batch fails to process successfully, all other batch transactions aren’t affected and aren’t rolled back if they were processed successfully.

We must Write the apex class that must be implements the Database.Batchable Interface.

Batch apex class Syntax:
global Class cleanup implements Database.Batchable< sobject >{
}

Batch apex class contain 3 methods

Start Method:

1.Use the start method to collect the records or objects to be passed to the interface method execute.
2.Start method execute only one time.

Syntax for Start Method:
global (Database.Querylocator|Iterable(< sobject>)start(Database.BatchableContext bc){
}
Database.QueryLocator

1.Database.QueryLocator object when you are using a simple query (SELECT).
2.If you use a querylocator object, 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).
Iterable

1.Whenever we write the Complex queries that time the Written type of the method should be Iterable.
2.If you use an iterable, the governor limit for the total number of records retrieved by SOQL queries is still enforced.

Execute Method:

Execute method is called for each batch of records.
Batches of records are not guaranteed to execute in the order they are received from the start method.

Syntax for Execute 

global void execute(Database.BatchableContext BC,List
){ }

Finish Method:

The finish method is called after all batches are processed. Use this method to send confirmation emails or execute post-processing operations.

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.

Syntax for Finish Method
global void Finish(Database.BatchableContext BC){
}
Returns the ID of the AsyncApexJob object associated with this batch job as a string. Use this method to track the progress of records in the batch job. You can also use this ID with theSystem.abortJob method.

How to Open a Visual force page as pop up from another visual force page with parameters.



    Click



 

How do I to stop Visualforce page from rendering when i click on Outputlink or Commond link?



 Write a Review


 

How to create expand and collapse link for an Div in Visualforce page using Jquery?


    

    
        
            
            
                
                 
                                    
                    
Output:


How to use Read more in Visualfoce page ?

lign="justify"> 

 
font color ="#3399f3">Read more

Output:

How to print a Visualforce page in Salesforce?


To print visualforce page add below line to visualforce page.



How to rendered Visualforce page that renders as PDF,when a button is clicked?


We may need Visualforce page that renders as PDF ,when a button is clicked

    
         Some Text Here 
    
    
        
    

How to add visualforce page in home page?


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.




Test classes with @isTest in salesforce?

Use the isTest annotation to define classes and methods that only contain code used for testing your application. The isTest annotation on methods is equivalent to the testMethod keyword.

1.Classes and methods defined as isTest can be either private or public. Classes defined as isTest must be top-level classes.
2.One advantage to creating a separate class for testing is that classes defined with isTest don't count against your organization limit of 3 MB for all Apex code.
3.You can also add the @isTest annotation to individual methods
4.Classes defined as isTest can't be interfaces or enums
5.Methods of a test class can only be called from a running test, that is, a test method or code invoked by a test method, and can't be called by a non-test request.
6.Test methods can’t be used to test Web service callouts. Instead, use mock callouts
7.You can’t send email messages from a test method
@isTest
                    
private class MyTestClass {
   @isTest static void test1() {
      // Implement test code
   }
   @isTest static void test2() {
      // Implement test code
   }
}
IsTest(SeeAllData=true) Annotation

use the isTest(SeeAllData=true) annotation to grant test classes and individual test methods access to all data in the organization,

If a test class is defined with the isTest(SeeAllData=true) annotation, this annotation applies to all its test methods whether the test methods are defined with the @isTest annotation or the testmethod keyword
The isTest(SeeAllData=true) annotation is used to open up data access when applied at the class or method leve

IsTest(OnInstall=true) Annotation

Use the IsTest(OnInstall=true) annotation to specify which Apex tests are executed during package installation. This annotation is used for tests in managed or unmanaged packages

How to find IP Address Geolocation In salesforce?

If you would like to know your ip address location based on the user ip address. here is best option you can go with.

I have created a visualforce page and an apex controller that makes a callout to external application with the user logged in ip address and will get back the response and displays in vf page.

Visualforce Page:

Country:{!country}
 
Isp:{!isp}
 
IP:{!ip}
 
Latitude:{!latitude}
 
Longitude{!longitude}
 
TimeZone: {!timezone}
 


Apex class:
public class FindIpAddress {
    public String country {get;set;}
    public String isp {get;set;}
    public String ip {get;set;}
    public integer latitude {get;set;}
    public integer longitude {get;set;}
    public String timezone {get;set;}
  
 public void getipaddress() {
  string ReturnValue = '';  
  ReturnValue = ApexPages.currentPage().getHeaders().get('True-Client-IP');
  if (ReturnValue == '' || ReturnValue == null) {
   ReturnValue = ApexPages.currentPage().getHeaders().get('X-Salesforce-SIP');
  } 
  if (ReturnValue == '' || ReturnValue == null) {
   ReturnValue = ApexPages.currentPage().getHeaders().get('X-Forwarded-For');
  } 
  Http h = new Http();
  HttpRequest req = new HttpRequest();
  req.setEndpoint('http://www.telize.com/geoip/'+ReturnValue);
  req.setMethod('GET');
  HttpResponse res;
  try{
   res = h.send(req);
   Map<string object="">m = (Map<string object="">)JSON.deserializeUntyped(res.getbody());
   country =(String)m.get('country');
   isp=(String)m.get('isp');
   ip=(String)m.get('ip');
   latitude=(Integer)m.get('latitude');
   longitude =(Integer)m.get('longitude');
   timezone =(String)m.get('timezone');
  }catch(Exception e){
  }
 }
}

Trigger Handler Patterns In salesforce?

There's no defined pattern as such but it is always considered as a best practice to have all your trigger logic inside one handler class and only have one trigger on each object.

Example Trigger
An Apex Trigger should be written so that every operation calls a method in an external Apex Class. By doing so code can easily be added or removed, and variables can be used multiple times without additional queries to the database.

Apex Trigger:
trigger objectTrigger on Object (after delete, after insert, after undelete, after update, before delete, before insert, before update) {

    objectTriggerHandler handler = new objectHandler();

    /* Before Insert */
    if(Trigger.isInsert && Trigger.isBefore){
        handler.OnBeforeInsert(Trigger.new);
    }
    /* After Insert */
    else if(Trigger.isInsert && Trigger.isAfter){
        handler.OnAfterInsert(Trigger.new);
    }
    /* Before Update */
    else if(Trigger.isUpdate && Trigger.isBefore){
        handler.OnBeforeUpdate(Trigger.old, Trigger.new, Trigger.newMap);
    }
    /* After Update */
    else if(Trigger.isUpdate && Trigger.isAfter){
        handler.OnAfterUpdate(Trigger.old, Trigger.new, Trigger.newMap);
    }
    /* Before Delete */
    else if(Trigger.isDelete && Trigger.isBefore){
        handler.OnBeforeDelete(Trigger.old, Trigger.oldMap);
    }
    /* After Delete */
    else if(Trigger.isDelete && Trigger.isAfter){
        handler.OnAfterDelete(Trigger.old, Trigger.oldMap);
    }

    /* After Undelete */
    else if(Trigger.isUnDelete){
        handler.OnUndelete(Trigger.new);
    }

}

Example Trigger Handler Class
The Apex Trigger template above calls a handler class to execute the trigger logic, the trigger handler class should be defined as follows:
Trigger Handler Class:
public with sharing class ObjectTriggerHandler {

    private boolean m_isExecuting = false;

    public ObjectTriggerHandler(boolean isExecuting){
        m_isExecuting = isExecuting;
    }

    public void OnBeforeInsert(Object[] newObjects){
        // EXECUTE BEFORE INSERT LOGIC
    }

    public void OnAfterInsert(Object[] newObjects){
        // EXECUTE AFTER INSERT LOGIC
    }

    public void OnBeforeUpdate(Object[] oldObjects, Object[] updatedObjects, MapObjectMap){
        // BEFORE UPDATE LOGIC
    }

    public void OnAfterUpdate(Object[] oldObjects, Object[] updatedObjects, MapObjectMap){
        // AFTER UPDATE LOGIC
    }

    public void OnBeforeDelete(Object[] ObjectsToDelete, MapObjectMap){
        // BEFORE DELETE LOGIC
    }

    public void OnAfterDelete(Object[] deletedObjects, MapObjectMap){
        // AFTER DELETE LOGIC
    }

    public void OnUndelete(Object[] restoredObjects){
        // AFTER UNDELETE LOGIC
    }

    public boolean IsTriggerContext{
        get{ return m_isExecuting;}
    }
}

Best Practices for Test Classes in salesforce?

  1. Very important and first, “Test Coverage Target Should not be limited to 75%”. It is not about coverage, It is about testing complete functionality. It will be always better if your code fails during testing, It will be less devastating than failing functionality after product release.
  2. If possible Don’t use seeAllData=true, Create your Own Test Data.
  3. Create Different Class which will create Dummy Data for testing, and use it everywhere (You have to be very careful, as sometimes it may slow down test class execution by creating unnecessary data which does not require by every test methods. So few developer prefer test data creation per Test class)
  4. If your Object’s Schema is not changing frequently, you can create CSV file of records and load in static resource. This file will act as Test data for your Test Classes.
  5. Use As much as Assertions like System.AssertEquals or System.AssertNotEquals
  6. Use Test.startTest() to reset Governor limits in Test methods
  7. If you are doing any Asynchronous operation in code, then don’t forget to call Test.stopTest() to make sure that operation is completed.
  8. Use System.runAs() method to enforce OWD and Profile related testings. This is very important from Security point of View.
  9. Always try to pass null values in every methods. This is the area where most of program fails, unknowingly.
  10. Always test Batch Capabilities of your code by passing 20 to 100 records.
  11. Use Test.isRunningTest() in your code to identify that context of class is Test or not. You can use this condition with OR (||) to allow test classes to enter inside code bock. It is very handy while testing for webservices, we can generate fake response easily.
  12. @TestVisible annotation can be used to access private members and methods inside Test Class. Now we don’t need to compromise with access specifiers for sake of code coverage.

Tuesday, December 22, 2015

Recursive trigger in salesforce and how to avoid it?

Recursion occurs when the code gets called again and again and goes into a infinite loop. It is always advisable to write a code that does not call itself. However, sometimes we are left with no choice. 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)
For example, if your trigger fires on after update on contact and you update any contact record in your trigger then the same trigger will be called and will lead to a infinite loop.
To avoid this kind of recursion and call the trigger only once we can use global class static variable.
As an example let says you have following trigger on contact:
trigger recursiveTrigger on Contact (after update) {
Id recordId ;
 for(contact con : trigger.new){
     recordId = con.id; 
 }
 Contact conRec =[select id,name,email from contact where id !=: recordId limit 1];

 conRec.email = 'test@test.com';
 update conRec;
 }
}
As you can see the trigger is getting called on after update and as the trigger has a DML update statement on the same object, same trigger will be called again leading to recursion.
To avoid this, just create one global class with a static global boolean variable as below.
global Class recusrssionPreventController{
Global static boolean flag = true;
 Public recusrssionPreventController(){
 }
}
And set this boolean variable in your trigger and then set this boolean variable to false as done in the trigger below
trigger recursiveTrigger on Contact (after update) {
Id recordId ;
if(recusrssivePreventController.flag == true){
   recusrssivePreventController.flag = false;
 for(contact con : trigger.new){
     recordId = con.id; 
 }
 Contact conRec =[select id,name,email from contact where id !=: recordId limit 1];

 conRec.email = 'test@test.com';
 update conRec;
 }
}
This will call the trigger only once and hence avoid recursion.

How to remove last character from a String in Apex?

String body= '{"userID" : "115f0000001i1gu"}';
String finalBody= body.removeEnd('}');
system.debug('Value is ' + finalBody);
output: {"userID" : "115f0000001i1gu"

How to Implement Single Sign On for Across Multiple Organizations In salesforce?

In this Article we will use one Salesforce Intense as Identity Provider and Other Salesforce Instance as Service provider.
Before Starting you have to decide which salesforce instance will act as Identity Provider and which will act as Service Provider.

Step 1: Enable Domain In Identity Provider Organization

From Click Domain Management | My Domain. Enter a new sub domain name, and click Check availability. If the name is available, click the term and condition box,Then click register domain.

Step 2: Enable Identity Provider

From Set up click  Security controls | Identity Provider
Click Enable
Click "Download Certificate". Remember where you save the certificate , as you will upload it later.

Once you enable identity provider ,you will see page like below with Identity Provider related Information.

Image 

In Above Image ,Issuer is Nothing But  domain URL of Identity Provider Org.

Step 3: Enable Single Sign On in Service Provider Org

Now we have to go to other Salesforce Instance which is acting as Service Provider.
From Setup,Click "Security Controls | Single Sign-On Setting" then click  Edit.
Select SAML Enabled check box.


We have to upload certificate download from Identity Provider to here in Service provider while declaring SSO related settings. we have to come back again here to setup "Identity Provider Login URL".

We will get this URL once we define Connected App in Identity Provider instance.
Use the following settings

Image 

Step 4: Define Connected App in Identity  Provider Instance 

Log into the salesforce organization that act as the Identity provider.

From Setup.Click Create | Apps, then in the "Connected APP" Section , Click New

Specify the following information:

Connected App Name: Salesforce Service Provider
Contact Email :
Enable SAML: Select this option to enter service provider details.
Entity ID:
ACS URL:

Once you save, you should be able to see settings page something like shown below :

Image


NOTE: Once you define Connected App, We need to add which profiles should be able to access this app.

From above setting page ,copy url of "IDP-Initiated Login URL" and  go back to SSO setting page of Service Provider and Add this URL.

Image

Step 5: Setting up Users

Everything is already at place, Lets start with user setup.

Copy one of User name from Identity Provider Instance to "Federation ID" fields of related user in Service Provider.

Example : In Identity Provider , ihave user "".Now in Service Provider i have user "" and want to relate this user. SO In federation ID filed of "" user, i will copy "".


Image

Testing Scenario :

To Test this, We need to inform salesforce that Instead of standard login page, Users have to use single sign on settings.


Image















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}