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