Thursday, December 24, 2015

Using Constructor in Apex

A Constructor is code that is invoked when an object is created from the class. You do not need to write a constructor for every class. If a class does not have a user-defined constructor, an implicit, no-argument, public one is used.
public class AClass {
// No argument Constructor
public AClass() {
//Constructor code
}
}

Object can be instantiated as below -
AClass obj = new AClass();

If you write a constructor with argument(i.e parametrised constructor), you can use that constructor to create an object using those argument.  If a class contain parametrised constructor, then default constructor wont create by automatically,you need to create no-argument constructor explicitly.
# Constructor can be overloaded i.e. there can be more then one Constructor for a class, each having different parameters.
# One constructor can call another constructor using this(...) syntax also called as Constructor chaining as in below example with no argument and one argument constructor.
public class TestClass2 {
private static final Integer DEFAULT_SIZE = 10;
Integer size;
//Constructor with no arguments
public TestClass2() {
this(DEFAULT_SIZE); // Using this(...) calls the one argument constructor
}
// Constructor with one argument
public TestClass2(Integer ObjectSize) {
size = ObjectSize;
}
}
Object can be instantiated either -
TestClass2 objOne = new TestClass2();
TestClass2 objTo = new TestClass2(31);

# Constructor overloading- Constructor with different order argument is possible 
public class Leads {
//No-argument constructor
public Leads () {}
// A constructor with one argument
public Leads (Boolean call) {}
// A constructor with two arguments
public Leads (String email, Boolean call) {}
// Though this constructor has the same arguments as the one above, they are in a different order,            so this is legal
public Leads (Boolean call, String email) {}
}


Static and Instance in Apex Salesforce

In Apex, you can have static methods, variables, and initialization code. However, Apex classes can’t be static.You can also have instance methods, member variables, and initialization code, which have no modifier, and local variables.
Static : Static methods, variables and initialization code have following characteristics.
  • They are associated with a class.
  • They'r allowed only in outer class.
  • They'r initialized only when the class is loaded.
  • They'r not transmitted as part of the view state for a VF page.
Instance(Local) : Instance methods, member variables, and initialization code have these characteristics.
  • They'r are associated with a particular object.
  • They'r created with every object instantiated from the class in which they'r declared.
Local Variables have following characteristics -
  • They’re associated with the block of code in which they’re declared
  • They must be initialized before they’re used.
Static Methods and Variables - 
Static methods ans variables used only with outer class. Inner class have no static methods or variables. A static method or variable doesn't require an instance of the class to access, you can access directly using the class name.
A static variable is static only within the scope of the apex transaction, it's not static across the server or organization. Ex - If an apex DML cause a trigger to fire multiple time, the static variable persist across these trigger call. [Use static variable to avoid trigger recursive]
Static variable is used to store information that is shared across all instances of a class. Ex- A recursive trigger can use the value of a class variable to determine when to exit the recursion.
 public class runOnce {  
     public static boolean firstRun = true;  
 }  
 trigger AccTrigger on Account (before delete, after delete, after undelete) {  
     if(Trigger.isBefore && Trigger.isDelete){  
         if(runOnce.firstRun){  
             Trigger.old[0].addError('Before Account Delete Error');  
             runOnce.firstRun=false;  
         }  
     }  
 }
A static variable defined in a trigger doesn’t retain its value between different trigger contexts within the same transaction, such as between before insert and after insert invocations. Instead, define the static variables in a class so that the trigger can access these class member variables and check their static values.
 public static void method() {  
     String Database = '';  
     Database.insert(new Account());  
 }  
Local variable names are evaluated before class names. If a local variable has the same name as a class, the local variable hides methods and variables on the class of the same name. As in the above example you have local variable and class having same name- Database, it will give compile time error, because Salesforce reports that the method doesn’t exist or has an incorrect signature.
Instance Methods and Variables -
An instance member variable is declared inside a class, but not within a method. 
Initialization Code :-
{                                                                              static {
        //Code Here                                                              // Code Here
 }                                                                               }
Initialization code is a block of code as above and static initialization code is a block of code preceded with keyword static.
The instance initialization code in a class is executed each time an object is instantiated from that class. These code blocks run before the constructor. A static initialization block runs only once, regardless of how many times you access the class that contains it.
A class can have any number of either static or instance initialization code blocks. The code blocks are executed in the order in which they appear in the file.

Saturday, December 19, 2015

Apex Class Defination

A class is a template or blue print from which objects are created. A class can contain variables and methods. Variables are used to specify the state of an object and Methods are used to control behaviour. A class can contain other classes, exception type and initialization code.
An Interface is a class which none of the methods have been implemented- the method signatures are there, but the body of each method is empty.
public class outerClass {
    // Outer Class Code
    class innerClass {
       //Inner Class Code
    }
}
# Access modifier for outer class should be public or global.
# You do not have to use an access modifier in the declaration of an inner class.
Use the Syntax for class defination -

private | public | global | [virtual | abstract | with sharing | without sharing] class ClassName [Implements InterfaceNameList] [extends ClassName]
{
      //The body of the class
}

# Private access modifier declares that this class is only known locally, that is, only by this section of code. This is the default access for inner classes—that is, if you don't specify an access modifier for an inner class, it is considered private. This keyword
can only be used with inner classes.
# Public access modifier declares that this class is visible in your application or namespace.
# The global access modifier declares that this class is known by all Apex code everywhere. All classes that contain methods defined with the webService keyword must be declared as global. If a method or inner class is declared as global, the outer,
top-level class must also be defined as global.
# The with sharing and without sharing keywords specify the sharing mode for this class.
# The virtual definition modifier declares that this class allows extension and overrides. You cannot override a method with the override keyword unless the class has been defined as virtual.
The abstract definition modifier declares that this class contains abstract methods, that is, methods that only have their signature declared and no body defined.
A class can implement multiple interfaces, but only extend one existing class. This restriction means that Apex does not support multiple inheritance. The interface names in the list are separated by commas.

Class Variables -
To declare a variable, specify the following:
• Optional:  Modifiers, such as public or final, as well as static.
• Required: The data type of the variable, such as String or Boolean.
• Required: The name of the variable.

• Optional:  The value of the variable.
Syntax - 
[public | private | protected | global] [final] [static] data_type variable_name
[= value]

Class Methods-
To define a method, specify the following:
• Optional: Modifiers, such as public or protected.
• Required: The data type of the value returned by the method, such as String or Integer. Use void if the method does not return a value.
• Required: A list of input parameters for the method, separated by commas, each preceded by its data type, and enclosed in parentheses(). If there are no parameters, use a set of empty parentheses. A method can only have 32 input parameters.
• Required: The body of the method, enclosed in braces {}. All the code for the method, including any local variable declarations, is contained here.
Syntax for defining a method:
[public | private | protected | global] [override] [static] data_type method_name (input parameters)
{
     // The body of the method
}
Note: You can only use override to override methods in classes that have been defined as virtual.

Thursday, December 17, 2015

Dynamic Apex in Salesforce

Dynamic Apex enable developers to create more flexible applications by providing them with the ability to :
  • Access sObject and field describe information.
  • Access Saelsforce app information.
  • Write dynamic SOQL queries, dynamic SOSL queries and dynamic DML.

Live Agent Setting and Customization

Live Agent lets service organizations connect with customers or website visitors in real time through a Web-based, text-only chat. After you set up and customize your basic Live Agent implementation, add it to the Salesforce console so that your agents and supervisor can start chat to assist customers.

You can Customize Live Agent to create a personalize chat experience for your customer service agents and customers using custom code. We will explain the details about how :
  • How to enable and setup Live Agent in the Org.
  • Customize deployment using the Deployment API.
  • Customize the appearance of customer facing chat window using VF page and components.
  • Create Prechat form to collect basci information from customer before they begin chat with an agent.
  • Create post-chat pages that appear to customer after chat complete.
  • Enable Quick Text for the agent for quick response to customer.
  • Enable to share details from Knowledge article in Live agent chat.
Enable Live Agent
You have to enable live agent in your org before you start customizing live agent in Salesforce. To enable live agent in your org.
          Setup > Quick Find/Search > Type Live Agent and enable Live agent as below screen. 
Once you have enebaled Live Agent, you can see the 4 objects marked in green in above screen shot-
  1. Live Chat Transcripts.
  2. Live Chat Transcript Events.
  3. Live Chat Visitors.
  4. Live Agent Sessions
Live Chat Transcripts - Live Chat Transcripts is a standard object is automatically created for each Live Agent chat session and Live Chat Transcript fields help you to keep track information about your agents chat with customer.

Live Chat Transcript Events - Live Chat Transcript Events is a standard object that keep tack events that occur between your agent and customer during chat. It contains event details like Chat requested, Accpeted, Transfer, cancelled, agent left, visitor left etc.

Live Chat Visitors - Live Chat Visitor is a website visitor who has started chat or tried a start chat session. Every time an agent chat with a customer, Salesforce automatically create a visitor record that identifies the customer's computer.

Each new visitor is associated with a session key, which Salesforce creates automatically. A session key is a unique ID that is stored in the visitor record and on the visitor's PC as a cookie. If a customer participates in multiple chats, Salesforce uses the session key to link the customer to their visitor record, associating that record to all related chat transcripts.

Live Agent Sessions - Live Agent Sessions object stores live agent session information, created automatically. This contain information about the agent session, time spent online, Time spent in chats etc.
Live agent session object information is used to create most report in Live Agent called Live Agent Session Report.

Saturday, December 12, 2015

Territory Management in Depth

Territory management is an account sharing system that grants access to accounts based on the characteristics of the accounts. It enables the Company to structure the Salesforce data and users the same way you structure your sales territory.
Notes :- Account ownership and its effect on record sharing remains valid and unchanged when territory management is in use.
Territory management only affects Accounts and standard objects that have a master-detail relationship to accounts.
For Ex - Opportunities are included in territory management but Leads are not.

Key benefits of using Terriotory Management :-
  1. The ability to use account criteria to expand a private sharing model.
  2. Support complex and frequently changed sales organization structure.
  3. Support for transferring users between territories, with option to retain opportunities.
  4. Multiple forecasts per user, based on territory membership.
  5. Territory based sales report.
What is a Territory ?
  • A territory is a collection of Accounts and Users where the users have at-least read access to accounts, regardless of account owner.
  • Users in a territory can be granted read, read/write or owner like access(i.e. ability to view, edit , transfer and delete records) to the accounts in that territory.
  • Both Accounts and Users can exist in multiple territories.
  • You can add account to territories either manually or account assignment rules.
  • You can also controller users' access to Opportunity or Cases associated with Accounts in the territory, regardless of who own the records.
What is Territory Hierarchy ?
Territory exist in hierarchy which you can set up with as many nested level as you wish. Territory hierarchy does not depend on geography, they can be defined however you like.

Enabling Territory Management -
Your organization must have customizable forecasting enabled before territory management can be turned on. 
If you plan to deploy territory management immediately after enabling customizable forecasting, you do not need to build forecast hierarchy. After you enable territory management, the territory hierarchy drives your forecast data.

When enabling territory management, you have the option to create your territory hierarchy from your forecast hierarchy. Your forecast hierarchy is automatically derived from your role hierarchy when you enable customizable forecasting.

Notes - 
  • A territory can have unlimited number of users and a user can be assigned to unlimited number of territories.
  • In the context of a specific territory, users have both active status and active in territory status.
  • Users with Active in Territory checked on the territory detail page have open opportunities, closed opportunities, or no opportunities at all in that territory. 
  • Users with Active in Territory deselected have been transferred out of or removed from the territory, but retain ownership of opportunities in the old territory.
Forecast Manager for Territory :-
  • A territory can have only one forecast manager. 
  • Forecasts from child and lower-level territories roll up to forecast managers.
  • If a territory has no forecast manager, there is no forecast for that territory.
  • Forecast managers can receive opportunities when users are transferred out of or removed from a territory.
  • Forecast managers can receive opportunities when account assignment rules are run.
  • On the territory settings page, you can enable forecast managers to act as delegated administrators for territories below them in the hierarchy.
Managing Account Assignment Rules :-

     Account assignment rules are governed by the following :

  • A territory can have inherited account assignment rules, meaning that the rules were created somewhere higher in the territory hierarchy and consequently also impact the given territory.
  • A territory can have locally defined account assignment rules, meaning that the rule was created at the given territory.
  • If a territory doesn't have any inherited or locally-defined account assignment rules, then it only contains accounts that were manually added.
  • If an account matches all inherited and locally-defined account assignment rules for multiple territories on the same branch of the hierarchy, then the account is assigned to the lowest matching territory.
  • If an account matches a territory's inherited account assignment rules but not all of the territory's locally-defined rules, then the account isn't assigned to the territory, but is evaluated for child territories.
        For example, you have three territories:
     Territory A has four rules marked “Apply to child territories“, and is a parent of territory B.
                – Territory B has three rules not marked “Apply to child territories”, and is a parent of territory C.
                     Territory C has two rules.
       If you assign an account that matches all of territory A’s and territory C’s rules but only one of territory B’s rules, then the account is assigned to territory C. However, if territory B's rules are marked “Apply to child territories,” then the account is assigned only to territory A.



  






Thursday, December 10, 2015

Page Access Counter and Last Viewed ?

Q - I have a VF page, how can I check how many users have viewed my page and who has viewed  last ?

Currently we don't have a standard functionality on Salesforce to get this. We can do this through Apex Controller and VF page.


We can create a field to save the number of time page accessed and a field to save the user who accessed  the page last.

Create custom fields in Account -
  1. PageCount - Number Type
  2. Last VIewed By - Text Type
Create a Controller - 



public class VFC_AccountPageViewCounter {
    public Account acc {get;set;}
    public User us {get;set;}
    public decimal count;
     
    public VFC_AccountPageViewCounter(ApexPages.StandardController controller){}
    
    public pagereference updateCount() {
        acc = [SELECT Id, bibhuotalightn__PageCount__c FROM Account Where Id =: ApexPages.currentPage().getParameters().get('Id')];
        us = [SELECT name from User where Id=:Userinfo.getUserId()];
        if(acc.bibhuotalightn__PageCount__c==null) {
            acc.bibhuotalightn__PageCount__c = 1;
            acc.bibhuotalightn__Last_Viewed_By__c = us.Name;            
        }
        else {
            acc.bibhuotalightn__PageCount__c += 1;
            acc.bibhuotalightn__Last_Viewed_By__c = us.Name;
        }
        update acc;
        return null;
    }
}

Create a VF Page-











Question - Why can't you write your logic inside Construcotr ? What is the need of a method again ?

Ans - As we can't write DML statement inside Constructor, we have to write a method for the logic to get the count and last viewed user details and can called the method on page load by using the page action attribute.

Monday, December 7, 2015

Salesforce Lightning Part-1

Understanding Salesforce Lightning and Salesforce Classic
Lightning experience is a new, modern user interface for your sales reps to help them sell faster and smarter. Not every feature is supported in Lightning.
Salesforce you are using is called Salesforce classic, and is still available for you, and the users you enable for Lightning Experience can switch between the two.

Features that aren’t supported in Lightning
1)      Custom Javascript and URL Buttons:-
Custom Javascript and URL buttons are not supported in Lightning experience.
Custom links with parameters for filling in form fields are not supported in Lightning experience.

2)      Inline Editing
In Lightning experience, inline editing isn’t supporting currently. Users is required to make updates by opening up the record for editing.

Factors to decide Lightning is Right for Me
Lightning Experience might be right for you if:
Salesforce Classic might be right for you if:
·         You have a sales team within your company with a standard sales process
·         You want to pilot the features with a group of sales reps
·         You’re looking to reboot your Salesforce implementation. This is a great opportunity to introduce new features because you’re doing change management anyway.
·         Your sales team makes regular use of features that aren’t yet available in LEX, such as campaigns, quotes, forecasting, or territory management.
·         You primarily use customer service tools or other non-sales features
·         You want a single experience across service and sales
·         You’re using person accounts
Salesforce Lightning Experience is great for customers doing B2B sales using Accounts, Contacts, Opportunities, Leads, Tasks, Custom Objects and other supported features .

Enabling Lightning Experience in Org:-
Person Accounts are not supported in Lightning Experience, If your org uses Person Account, you can’t enable Lightning experience.

Step 1-  Go to Lightning Experience from Home



Step 2 – Enabled the Lightning features to start.



Step 3 – Switch between Lightning and Classic view



Monday, August 17, 2015

Set Up Test Data for an Entire Test Class

Link - Set Up Test Data for an Entire Test Class
Use test setup methods (methods that are annotated with @testSetup) to create test records once and then access them in every test method in the test class. Test setup methods can be time-saving when you need to create reference or prerequisite data for all test methods, or a common set of records that all test methods operate on.

Test setup methods enable you to create common test data easily and efficiently. By setting up records once for the class, you don’t need to re-create records for each test method. Also, because the rollback of records that are created during test setup happens at the end of the execution of the entire class, the number of records that are rolled back is reduced. As a result, system resources are used more efficiently compared to creating those records and having them rolled back for each test method.

If a test class contains a test setup method, the testing framework executes the test setup method first, before any test method in the class. If a test method changes those records, such as record field updates or record deletions, those changes are rolled back after each test method finishes execution. The next executing test method gets access to the original unmodified state of those records.

Syntax

Test setup methods are defined in a test class, take no arguments, and return no value. The following is the syntax of a test setup method.
@testSetup static void methodName() {
}

Example-
@isTest
private class CommonTestSetup {
    @testSetup static void setup() {
        // Create common test accounts
        List<Account> testAccts = new List<Account>();
        for(Integer i=0;i<2;i++) {
            testAccts.add(new Account(Name = 'TestAcct'+i));
        }
        insert testAccts;        
    }
    
    @isTest static void testMethod1() {
        // Get the first test account by using a SOQL query
        Account acct = [SELECT Id FROM Account WHERE Name='TestAcct0' LIMIT 1];
        // Modify first account
        acct.Phone = '555-1212';
        // This update is local to this test method only.
        update acct;        
        // Delete second account
        Account acct2 = [SELECT Id FROM Account WHERE Name='TestAcct1' LIMIT 1];
        // This deletion is local to this test method only.
        delete acct2;        
        // Perform some testing
    }
    @isTest static void testMethod2() {
        // The changes made by testMethod1() are rolled back and 
        // are not visible to this test method.        
        // Get the first account by using a SOQL query
        Account acct = [SELECT Phone FROM Account WHERE Name='TestAcct0' LIMIT 1];
        // Verify that test account created by test setup method is unaltered.
        System.assertEquals(null, acct.Phone);        
        // Get the second account by using a SOQL query
        Account acct2 = [SELECT Id FROM Account WHERE Name='TestAcct1' LIMIT      1];
        // Verify test account created by test setup method is unaltered.
        System.assertNotEquals(null, acct2);
        // Perform some testing
    }
}

Test Setup Method Considerations

·         Test setup methods are supported only with the default data isolation mode for a test class. If the test class or a test method has access to organization data by using the @isTest(SeeAllData=true) annotation, test setup methods aren’t supported in this class. Because data isolation for tests is available for API versions 24.0 and later, test setup methods are also available for those versions only.
·         Multiple test setup methods are allowed in a test class, but the order in which they’re executed by the testing framework isn’t guaranteed.
·         If a fatal error occurs during the execution of a test setup method, such as an exception that’s caused by a DML operation or an assertion failure, the entire test class fails, and no further tests in the class are executed.
·         If a test setup method calls a non-test method of another class, no code coverage is calculated for the non-test method.