Sunday, 8 November 2015

SingleEmailMessage Vs MassEmailMessage | Send Email by Apex


SingleEmailMessage Vs MassEmailMessage





SINGLE EMAILMASS EMAIL
Multiple recipients?YesYes
Personalized body?Yes (single body only)Yes
Special permission needed?NoYes, has to be enabled
Merge fields?YesYes
Personalized merge fields?Yes (only one record at a time)Yes
Templates?YesYes
Template possibilities?Text/HTML/Visualforce/Custom TemplatesText/HTML/Custom Template


SingleEmailMessage:

Single emails are like regular individual emails that may go to one or more addresses (to/cc/bcc), but each of these emails has the same body

Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
message.toAddresses = new String[] { 'abc@gmail.com', 'xyz@gmail.com' };
message.optOutPolicy = 'FILTER';
message.subject = 'Opt Out Test Message';
message.plainTextBody = 'This is the message body.';
Messaging.SingleEmailMessage[] messages =   new List<Messaging.SingleEmailMessage> {message};
Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);

if (results[0].success) 
{
    System.debug('The email was sent successfully.');
} else 
{
    System.debug('The email failed to send: ' + results[0].errors[0].message);
}
Please check below post to see all other method
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_email_outbound_single.htm 

 
MassEmailMessage:

Mass emails typically go to a large number of addresses (currently capped to 250 per email), with personalized message bodies.
public void SendEmail()
{
 List<contact> lstcon=[Select id from contact limit 2];
 List<Id> lstids= new List<Id>();
 for(Contact c:lstcon)
 {
  lstids.add(c.id);
 }
 EmailTemplate et=[Select id from EmailTemplate where name = 'EmailTemplatename' limit 1];
 
 Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
 mail.setTargetObjectIds(lstIds);
 mail.setSenderDisplayName('System Admin');
 mail.setTemplateId(et.id);
 Messaging.sendEmail(new Messaging.MassEmailMessage[] { mail });
}
 Please check below post to see all other method

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_email_outbound_mass.htm 

 
Related link
https://developer.salesforce.com/page/An_Introduction_To_Email_Services_on_Force.com 
 
Please let us know if this will help you

Thanks
Amit Chaudhary

 

Default from address while sending emails | Controlling 'From Address' in salesforce | Salesforce Org Wide Email Address


If you want to control the From Email address in salesforce then you can control this with "Organization-Wide Email Addresses".
An organization-wide email address associates a single email address to a user profile. Each user in the profile can send email using this address. Users will share the same display name and email address

Step 1:-  Setup "Organization-Wide Email Addresses"

1. Navigate Setup -> Email Administration ->  Organization-Wide Email Addresses

2. Click on Add button.

3. Enter email Id and display name of sender.
4. In order to complete this process you need to get verified email id you are putting here




Step 2:- Fetch "Org Wide Email Address" in code like below code.



public class EmailHelper 
{
 public static void sendEmail() 
 {
  Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();  
  string body = 'Demo Body ';
  String[] toAddresses = new String[] {'abc@gmail.com'}; 
  mail.setToAddresses(toAddresses);
  mail.setSubject('Test Subject');  
  mail.setSaveAsActivity(false);  
  for(OrgWideEmailAddress owa : [select id, Address, DisplayName from OrgWideEmailAddress]) 
  {
   if(owa.DisplayName.contains('System Admin'))
   { 
    mail.setOrgWideEmailAddressId(owa.id); 
   } 
  }
  mail.setHtmlBody(body);  
  Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }  
}





Some Use Full Link :-
http://salesforce.stackexchange.com/questions/5169/whats-the-advantage-of-using-massemailmessage-instead-of-multiple-singleemailme/5174#5174
http://developer.force.com/cookbook/recipe/creating-email-templates-and-automatically-sending-emails

Please let us know if this will help you

Thanks
Amit Chaudhary

Wednesday, 7 October 2015

Trigger Context Variables in Salesforce

All triggers define implicit variables that allow developers to access run-time context. These variables are contained in the System.Trigger class. Following are the context variable available in triggers. Please note variable availability in trigger varies according to the type of trigger events.

Trigger context variables in Salesforce


1) isExecuting Returns true if the current context for the Apex code is a trigger, not a Visualforce page, a Web service, or anexecuteanonymous() API call.
2) isInsert Returns true if this trigger was fired due to an insert operation, from the Salesforce user interface, Apex, or theAPI.
3) isUpdate Returns true if this trigger was fired due to an update operation, from the Salesforce user interface, Apex, or theAPI.
4) isDelete Returns true if this trigger was fired due to a delete operation, from the Salesforce user interface, Apex, or theAPI.
5) isBefore Returns true if this trigger was fired before any record was saved.
6) isAfter Returns true if this trigger was fired after all records were saved.
7) isUndelete Returns true if this trigger was fired after a record is recovered from the Recycle Bin (that is, after an undelete operation from the Salesforce user interface, Apex, or the API.)
8) new Returns a list of the new versions of the sObject records.Note that this sObject list is only available in insert and update triggers, and the records can only be modified in before triggers.
9) newMap A map of IDs to the new versions of the sObject records. Note that this map is only available in before update, after insert, and after update triggers.
10) old Returns a list of the old versions of the sObject records.Note that this sObject list is only available in update and delete triggers.
11) oldMap A map of IDs to the old versions of the sObject records.Note that this map is only available in update and delete triggers.
12) size The total number of records in a trigger invocation, both old and new.

Sample trigger


trigger AccountTrigger on Account( after insert, after update, before insert, before update)
{

    AccountTriggerHandler handler = new AccountTriggerHandler(Trigger.isExecuting, Trigger.size);
    
    if( Trigger.isInsert )
    {
        if(Trigger.isBefore)
        {
            handler.OnBeforeInsert(trigger.New);
        }
        else
        {
            handler.OnAfterInsert(trigger.New);
        }
    }
    else if ( Trigger.isUpdate )
    {
        if(Trigger.isBefore)
        {
            handler.OnBeforeUpdate(trigger.New ,trigger.Old,Trigger.NewMap,Trigger.OldMap);
        }
        else
        {
            handler.OnAfterUpdate(trigger.New ,trigger.Old,Trigger.NewMap,Trigger.OldMap);
        }
    }
}


Create one Trigger Handler Class


public with sharing class AccountTriggerHandler 
{
    private boolean m_isExecuting = false;
    private integer BatchSize = 0;
    public static boolean IsFromBachJob ;
    public static boolean isFromUploadAPI=false;
    
    public AccountTriggerHandler(boolean isExecuting, integer size)
    {
        m_isExecuting = isExecuting;
        BatchSize = size;
    }
            

    public void OnBeforeInsert(List<Account> newAccount)
    {
        system.debug('Account Trigger On Before Insert');
    }
    public void OnAfterInsert(List<Account> newAccount)
    {
        system.debug('Account Trigger On After Insert');
    }
    public void OnAfterUpdate( List<Account> newAccount, List<Account> oldAccount, Map<ID, Account> newAccountMap , Map<ID, Account> oldAccountMap )
    {
        system.debug('Account Trigger On After Update ');
        AccountActions.updateContact (newAccount);
    }
    public void OnBeforeUpdate( List<Account> newAccount, List<Account> oldAccount, Map<ID, Account> newAccountMap , Map<ID, Account> oldAccountMap )
    {
        system.debug('Account Trigger On Before Update ');
    }

    @future 
    public static void OnAfterUpdateAsync(Set<ID> newAccountIDs)
    {

    }      
    public boolean IsTriggerContext
    {
        get{ return m_isExecuting;}
    }
    
    public boolean IsVisualforcePageContext
    {
        get{ return !IsTriggerContext;}
    }
    
    public boolean IsWebServiceContext
    {
        get{ return !IsTriggerContext;}
    }
    
    public boolean IsExecuteAnonymousContext
    {
        get{ return !IsTriggerContext;}
    }
} 

Create one Trigger Action Class



public without sharing class AccountActions 
{
    public static void updateContact ( List<Account> newAccount)
    {
        // Add your logic here
    }
}

SourcePlease check below post for full example of Trigger
http://amitsalesforce.blogspot.in/2015/06/trigger-best-practices-sample-trigger.html


Please let us know if this will help you. 
Thanks,

Amit Chaudhary

Sunday, 20 September 2015

Code Coverage Report in excel Format | Test Class Result in XLS





Now you can view the overall and individual entity code coverage in your organization. The results of the code coverage can be downloaded in Excel format

For Same you Can install the below App Exchange Product


Code Coverage Report

https://appexchange.salesforce.com/listingDetail?listingId=a0N3000000DXzlpEAD

How to configure the App. 
Please check below link for same.
https://appexchange.salesforce.com/servlet/servlet.FileDownload?file=00P3000000Qq5GkEAJ

How To Configure This APP

You can check the Setup step in Installation and Configuration Tab



Step 1:- Setup Remote Site Setting

Add a value for Remote site setting (In same org in which package is installed)
Goto Setup > Administration Setup > Security Controls > Remote Site Settings Add value to your Salesforce instance, for example  'https://na34.salesforce.com’



Step 2 Setup Base URL

Please set your Base URL.
Go to Setup > Develop > Custom Settings > Code Coverage Configuration > Manage > New. Set the name to 'baseUrl' and the value to your Salesforce instance, for example 'https://ap2.salesforce.com'

à Open Custom Setting and Click on Code Coverage Configuration 


à Then click on Manage


à Then click on Manage and then New Button and then Enter the below detail
Name as :- baseUrl

(Please enter your org base url.)






Thursday, 3 September 2015

Test classes with @isTest

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
  8. Methods of a public 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.

@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,

  1. 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
  2. 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


Thursday, 6 August 2015

INVALID_FIELD_FOR_INSERT_UPDATE: Account: bad field names on insert/update


Insert error code INVALID_FIELD_FOR_INSERT_UPDATE: Account: bad field names on insert/update call: Salutation

This error often occurs when the default Account record type in Salesforce has been changed to a Person Account record type. The default Account Record Type must be set to a Business Account record type.

Resolution:


To resolved this, login to Salesforce and go to

Setup --> Manage Users --> profile --> and click on the Administrator profile ( or the profile of the Salesforce user specified in the Data Migration setup).


Scroll down to the Record Type settings and click on edit in the Accounts section. Modify the default record type to be a business account record type and click Save.


Wednesday, 5 August 2015

How to check which Salesforce edition we are using | Which salesforce edition



What edition of Salesforce do you have?

Solution :- We can check the same from below two option

1) Browser :- Click on Tab then you can see the detail like below screen shot




2) By Company Setup :- Best Option is to check the same from company profile.
Setup- > Company profile 
like below screen shot. 



Thanks,
Amit Chaudhary