How to insert comma in formula field?


To insert ',' between two field values in Formula field in Salesforce use &","& between two fields values.

For example Phone and Mobile are two fields. Create a field as Telephone Numbers and in the formula editor type Phone&",'"&Mobile to separate those values with comma.

Cheers!!!

Apex Scheduler

To schedule an Apex class to run at regular intervals, first write an Apex class that implements the Salesforce-provided interface Schedulable.
The scheduler runs as system: all classes are executed, whether the user has permission to execute the class or not. For more information on setting class permissions, see “Apex Class Security Overview” in the Salesforce online help.
To monitor or stop the execution of a scheduled Apex job using the Salesforce user interface, go to Setup --> Monitoring --> Scheduled Jobs. For more information, see “Monitoring Scheduled Jobs” in the Salesforce online help.
The Schedulable interface contains one method that must be implemented, execute.
global void execute(SchedulableContext sc){}
Example:
global class scheduledAccountUpdate implements Schedulable {
    global void execute(SchedulableContext SC) {
        AccountUpdate acc = new AccountUpdate('Description','Updated Account');
    }
}


To get details about AccountUpdate Class go to http://www.infallibletechie.com/2012/05/batch-apex.html
Go to Setup à Develop à Apex Classes and then click ‘Schedule Apex’ button.


            Figure clearly explains how to schedule Batch Apex. The frequency may be set to Weekly or Monthly. Start and End dates are important. Preferred Start Time is also important. The job will be sent to Apex Job queue. The preferred Start Time won’t be the exact time because it depends upon the job queue. The job will be executed after other jobs in the job queue have been executed.

Cheers!!!

Batch Apex in Salesforce

A developer can now employ batch Apex to build complex, long-running processes that run on thousands of records on the Force.com platform. Batch Apex operates over small batches of records, covering your entire record set and breaking the processing down to manageable chunks. For example, a developer could build an archiving solution that runs on a nightly basis, looking for records past a certain date and adding them to an archive. Or a developer could build a data cleansing operation that goes through all Accounts and Opportunities on a nightly basis and updates them if necessary, based on custom criteria.

Batch Apex is exposed as an interface that must be implemented by the developer. Batch jobs can be programmatically invoked at runtime using Apex.

To use batch Apex, you must write an Apex class that implements the Salesforce-provided interface Database.Batchable, and then invoke the class programmatically.

To monitor or stop the execution of the batch Apex job, go to Setup --> Monitoring --> Apex Jobs. For more information, see “Monitoring the Apex Job Queue” in the Salesforce online help.

The Database.Batchable interface contains three methods that must be implemented:

start method

global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc) {}
The start method is called at the beginning of a batch Apex job. Use the start method to collect the records or objects to be passed to the interface method execute. This method returns either a Database.QueryLocator object or an iterable that contains the records or objects being passed into the job.

execute method

global void execute(Database.BatchableContext BC, list<P>){}
The execute method is called for each batch of records passed to the method. Use this method to do all required processing for each chunk of data.

This method takes the following:

1. A reference to the Database.BatchableContext object.

2. A list of sObjects, such as List<sObject>, or a list of parameterized types. If you are using a Database.QueryLocator, the returned list should be used.

Batches of records are not guaranteed to execute in the order they are received from the start method.

finish method

global void finish(Database.BatchableContext BC){}

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

Keep in mind the following governor limits for batch Apex:

  • Up to five queued or active batch jobs are allowed for Apex.
  • A user can have up to five query cursors open at a time. For example, if five cursors are open and a client application still logged in as the same user attempts to open a new one, the oldest of the five cursors is released.
  • Cursor limits for different Force.com features are tracked separately. For example, you can have five Apex query cursors, five batch cursors, and five Visualforce cursors open at the same time.
  • A maximum of 50 million records can be returned in the Database.QueryLocator object. If more than 50 million records are returned, the batch job is immediately terminated and marked as Failed.
  • The maximum value for the optional scope parameter is 2,000. If set to a higher value, Salesforce chunks the records returned by the QueryLocator into smaller batches of up to 2,000 records.
  • If no size is specified with the optional scope parameter, Salesforce chunks the records returned by the QueryLocator into batches of 200, and then passes each batch to the execute method. Apex governor limits are reset for each execution of execute.
  • The start, execute and finish methods can implement only one callout in each method.
  • Batch executions are limited to one callout per execution.
  • The maximum number of batch executions is 250,000 per 24 hours.
Only one batch Apex job's start method can run at a time in an organization. Batch jobs that haven’t started yet remain in the queue until they're started. Note that this limit doesn’t cause any batch job to fail and execute methods of batch Apex jobs still run in parallel if more than one job is running.

Step 1: Write an apex class for Batch Apex.

Sample code:

global class AccountUpdate implements Database.batchable<sObject>
{

    String query,field,value;
   
    global AccountUpdate(String f, String v)
    {
        field = f;
        value = v;
        query = 'Select ' + field + ' FROM Account';
    }

    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        return Database.getQueryLocator(query);
    }
   
    global void execute(Database.BatchableContext BC, List<sObject> scope)
    {
         for(sobject s : scope)
         {
             s.put(Field,Value);
         }
         update scope;
    }
   
    global void finish(Database.BatchableContext BC)
    {
    }
   
}

The above class is used to update Description field with some value.

Step 2: Go to Setup à Developer Console.


Step 3: Execute the Batch Apex.



Step 4: Monitor the Apex jobs.

To monitor the Apex jobs, go to Setup --> Monitoring --> Apex Jobs.



Cheers!!!

Example for System.assertEquals()

Sample Code:

public class SampleClass {
    public void insertAcct(String name, String extId) {
        Account acc = new Account(Name = name,External_ID__c = extId);
        insert acc;
        System.assertEquals('Test',acc.Name);
    }
}

In the above example, the expected name of the Account is 'Test'. If we give the name other than 'Test', it will throw error.

Opposite to System.assertEquals() is System.assertNotEquals().

Cheers!!!

Unit Testing for Triggers

Sample Trigger:

trigger DuplicateMemberCheck on Member__c (before insert)
{
for(Member__c memb:trigger.new)
{
List<Member__c> mem = new List<Member__c>();

String email = memb.E_Mail_Id__c;

String sql = 'SELECT E_Mail_Id__c FROM Member__c';
mem = Database.Query(sql);

for(Member__c tempMember:mem)
{
if(tempMember.E_Mail_Id__c == email)
{
memb.E_Mail_Id__c.addError('Duplicate Record');
}
}
}
}

Sample Test Class for Sample Trigger:

@isTest

public class TestDuplicateMemberCheckClass
{
    static testMethod void test()
    {
        Date birthday = Date.valueOf('2000-12-20');

        Member__c mem = new Member__c(Name = 'Test', E_Mail_Id__c = 'magulan.d@igatepatni.com', Mobile_Number__c = '99966663322', Birthday__c = birthday);
       
        Member__c mem1 = new Member__c(Name = 'Test', E_Mail_Id__c = 'magulan@igatepatni.com', Mobile_Number__c = '99966663322', Birthday__c = birthday);

        try
        {
            insert mem;
            insert mem1;
        }
        catch(DMLException e)
        {
            System.assert(e.getMessage().contains('Duplicate Record'));
        }
    }   
}

Output:

Running Unit Testing


To Run Unit test:



To run unit testing, go to Setup Menu à App Setup à Develop à Apex Test Execution and then Test Case and click ‘Run’ button.




To Run all unit tests:

To run unit testing, go to Setup Menu






The above figures clearly explains that it takes 69 ms (micro seconds) to execute MyTestClass and the code coverage is 100.

Go to Setup -->  App Setup --> Develop --> Apex Classes and then click ‘Run All Tests’ button.

Cheers!!!

Unit Testing

Unit tests are class methods that verify whether a particular piece of code is working properly. Unit test methods take no arguments, commit no data to the database, send no emails, and are flagged with the testMethod keyword in the method definition.

            Classes defined with the isTest annotation don't count against your organization limit of 2 MB for all Apex code. Individual methods defined with the isTest annotation do count against your organization limits.

You can run unit tests for:
-             A specific class
-             A subset of classes
-             All unit tests in your organization

To run a test, use any of the following:
-             The Salesforce user interface
          The Force.com IDE
-             The API

Required Average test coverage across all Apex Classes and Triggers is 75%.

Considerations:

  1. Test methods cannot be used to test Web service API.
  2. You can’t send email from test method
  3. Since test method doesn’t commit data creation, you need not delete upon completion.
  4. In Feed tracking, they don’t result in creation of Feed Tracked changes records.
Example:

Sample Class:

public class SampleClass
{
    public void insertAcct(String name, String extId)
    {
        Account acc = new Account(Name = name,External_ID__c = extId);
        insert acc;
    }
}

Test Class for Sample Class:

@isTest

private class MyTestClass
{
    static testMethod void insertAcc()
    {
        SampleClass sc = new SampleClass();
        sc.insertAcct('Test Account','100');
    }
}

OnLoad function in visualforce

Method 1:

<script type = "text/javascript">
    window.onload=function()      
    {        
        alert("Hi");
    };
</script>

Method 2:

Visuaforce page:

<apex:page action="{!onLoad}">

</apex:page>


Controller:

public class sample {
        public sample(){
        }

        public void onLoad(){

            ..................
            ..................
        }
}


Cheers!!!

How to run Batch apex instantly?

To run batch Apex, go to User Menu --> Developer Console.




In the Apex Code section,

mergeNumbers M = new mergeNumbers();
Database.executeBatch(M);

where mergeNumbers is a Batch Apex Class.

Cheers!!!

Calling batch process from apex code in salesforce

global class scheduledMerge implements Schedulable
{
            global void execute(SchedulableContext SC)
            {
                        mergeNumbers M = new mergeNumbers();// Batch Apex class to be called
            }
}

Cheers!!!

Trigger.isInsert() and trigger.isUpdate() in salesforce

Sample Trigger:

trigger memberInviteNotify on Member__c (after insert,after update)
{
    for(Member__c member:trigger.New)
    {
        String[] toAddresses = new String[] {member.E_Mail_Id__c};
        String messageBody;
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(toAddresses);
  
        //Email invitation
        if(trigger.isInsert)
        {
            mail.setSubject('Welcome to Sweet 16');
            messageBody = 'Hi ' + member.Name + ', Welcome to Sweet 16';
            mail.setHtmlBody(messageBody);
        }
        //Email notification
        if(trigger.isUpdate)
        {
            mail.setSubject('Updates in your details');
            messageBody = 'Hi ' + member.Name + ', Changes have been made to your details. Contact administrator if you are not responisble.';
            mail.setHtmlBody(messageBody);
        }
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
}


Cheers!!!