Monday, May 28, 2012

Working with the Developer Console - Salesforce

How to Play with Developer Console and Debug logs

Developer Console
The Developer Console is a collection of tools you can use to analyze and troubleshoot applications in your Salesforce organization. It’s a separate window composed of a set of related tools that allow you to access your source code and review how it executes. It can also be used to monitor database events, workflow, callouts, validation logic, cumulative resources used versus system limits, and other events that are recorded in debug logs. It’s a context-sensitive execution viewer, showing the source of an operation, what triggered that operation, and what occurred afterward. Access the Developer Console by clicking Your Name | Developer Console.
The Developer Console System Log
The System Log console

Debug Log Categories

You can specify the following log categories. The amount of information logged for each category depends on the log level:
Log Category Description
Database Includes information about database activity, including every data manipulation language (DML) statement or inline SOQL or SOSL query.
Workflow Includes information for workflow rules, such as the rule name, the actions taken, and so on.
Validation Includes information about validation rules, such as the name of the rule, whether the rule evaluated true or false, and so on.
Callout Includes the request-response XML that the server is sending and receiving from an external Web service. This is useful when debugging issues related to using Force.com Web services API calls.
Apex Code Includes information about Apex code and can include information such as log messages generated by DML statements, inline SOQL or SOSL queries, the start and completion of any triggers, and the start and completion of any test method, and so on.
Apex Profiling Includes cumulative profiling information, such as the limits for your namespace, the number of emails sent, and so on.
Visualforce Includes information about Visualforce events including serialization and deserialization of the view state or the evaluation of a formula field in a Visualforce page.
System Includes information about calls to all system methods such as the System.debug method.

Debug Logs
A debug log records database operations, system processes, and errors that occur when executing a transaction or while running unit tests. The system generates a debug log for a user every time that user executes a transaction that is included in the filter criteria.
You can retain and manage the debug logs for specific users.
Log Lines
Included inside the units of code. These indicate what code or rules are being executed, or messages being specifically written to the debug log. For example:
Debug Log Line Example
Debug Log Line Example
Log lines are made up of a set of fields, delimited by a pipe (|). The format is:
  • timestamp: consists of the time when the event occurred and a value between parentheses. The time is in the user's time zone and in the format HH:mm:ss.SSS. The value represents the time elapsed in nanoseconds since the start of the request. The elapsed time value is excluded from logs reviewed in the Developer Console.
  • event identifier: consists of the specific event that triggered the debug log being written to, such as SAVEPOINT_RESET or VALIDATION_RULE, and any additional information logged with that event, such as the method name or the line and character number where the code was executed.
Now we start playing with System Logs:-

System Log Containing Output of Formula Build: --- (Developer Console)

   
1. Integer remainder = math.mod(12, 2);
system.debug('######### value of remainder'+remainder);

output :-- 11:47:31:042 USER_DEBUG [2]|DEBUG|######### value of remainder0

2. system.Debug(Math.mod(3,10));

Output :-- 11:55:56:053 USER_DEBUG [1]|DEBUG|3

3. system.debug(math.min(12.3, 156.6));

Output:-- 12:04:09:097 USER_DEBUG [1]|DEBUG|12.3

4. system.debug(math.max(12.3, 156.6));
output:--12:07:21:067 USER_DEBUG [1]|DEBUG|156.6

5. system.debug(math.abs(-42));

output:-- 12:11:52:043 USER_DEBUG [1]|DEBUG|42

6. Integer numberDays = date.daysInMonth(1960, 2);
   system.debug('###### value of days'+numberDays);

output:--12:22:05:046 USER_DEBUG [2]|DEBUG|###### value of days29

7.  system.debug(date.daysInMonth(1960, 2));

output:-- 12:23:39:054 USER_DEBUG [1]|DEBUG|29

8. system.debug(date.newinstance(1960, 2, 17));

output:-- 12:26:09:042 USER_DEBUG [1]|DEBUG|1960-02-17 00:00:00

Note:-- newInstance Constructs a Date from Integer representations of the year,
month (1=Jan), and day. The following example creates the date February 17th, 1960.


9. system.debug(date.isLeapYear(1960));

output:-- 12:28:31:038 USER_DEBUG [1]|DEBUG|true

10. system.debug(date.today());

output:--12:33:41:047 USER_DEBUG [1]|DEBUG|2012-05-15 00:00:00

11. date mydate = date.today();
      system.debug(mydate.day());

output:-- 12:38:55:038 USER_DEBUG [2]|DEBUG|15

12. date mydate = date.today();
system.debug(mydate.year());

output :-- 12:37:36:057 USER_DEBUG [2]|DEBUG|2012

13. system.debug((date.today()+365));

output:-- 13:15:38:030 USER_DEBUG [1]|DEBUG|2013-05-15 00:00:00

14. system.debug((date.today()-365));

Output:-- 13:17:17:035 USER_DEBUG [1]|DEBUG|2011-05-16 00:00:00

15. Date myDate = Date.Today();
String sDate = String.valueOf(myDate);
system.debug('###### value of sDate'+sDate);

output:--- 13:25:28:042 USER_DEBUG [3]|DEBUG|###### value of sDate2012-05-15

16. Double myDouble = 12.34;
String myString = String.valueOf(myDouble);
System.Debug('##### value of myDouble'+myString);

output:--- 13:27:57:036 USER_DEBUG [4]|DEBUG|##### value of myDouble12.34

17. date startDate = date.newInstance(2003, 1, 1);
date dueDate = date.newInstance(2008, 1, 30);
integer numberDaysDue =  startDate.daysBetween(dueDate);
system.debug('##### value of numberDaysDue'+numberDaysDue);
   
output:-- 13:53:35:041 VARIABLE_ASSIGNMENT [5]|numberDaysDue|1855

18.date startDate = date.newInstance(2003, 1, 1);
date dueDate = date.newInstance(2008, 1, 30);
integer numberDaysDue = startDate.daysBetween(dueDate);
system.debug('##### value of numberDaysDue'+numberDaysDue);
system.debug(math.mod(numberDaysDue,7));

output:-- 13:55:26:049 USER_DEBUG [8]|DEBUG|0

Keep Playing with Debug Logs and Developer Console because they are extremely useful. Enjoy Coding.

                                         =======  Abhinav Sharma  =========



Triggers in Salesforce

How to Play with Apex Triggers


Definition of Apex Triggers:--
A trigger is an Apex code that executes before or after the following types of operations:
  • insert
  • update
  • delete
  • merge
  • upsert (Update + Insert)
  • undelete
For example, you can have a trigger run before an object’s records are inserted into the database, after records have been deleted, or even after a record is restored from the recycle bin.
Triggers can be divided into two types:--

·         Before triggers can be used to update or validate record values before they are saved to the database.
·         After triggers can be used to access field values that are set by the database (such as a record's Id or last Updated field) and to affect changes in other records, such as logging into an audit table or firing asynchronous events with a queue.

Trigger.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.

Trigger. 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.

Trigger.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.

Trigger.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.

Summary
Before Insert: new
Before update: old, new, newMap, oldMap
Before delete: old, oldMap
Before undelete: Similar to Insert
After Insert: new, newMap
After update: old, new, newMap, oldMap
After Delete: old, oldMap

Point to Remember
·         You cannot delete Trigger.New.
·         Trigger. Old is always read only.
·         Trigger.New and Trigger. Old cannot be used in Apex DML operations. 

Understanding Concepts of Old and New values for different Events 

Important: -- For before events: List of Records, Map of Records did not have Id, Formulas, and Parent fields.

====================
Before Insert
====================
trigger conceptOldandNew on Contact (before Insert) {
public Map<Id,String> conIds = new Map<ID, String>();
    system.debug('##### value of trigger.new'+trigger.new);
    system.debug('##### value of trigger.old'+trigger.old);
}

=======================
Debug Log Values
=======================
##### ##### value of trigger.new(Contact:{ OwnerId=00590000000aleEAAQ,Salutation=Mr.,
 LastName=test, Email=test@test.com, FirstName=test, IsDeleted=false})

##### value of trigger.old {null}



========================
Before Delete
========================
trigger conceptOldandNew on contact (before delete) {
public Map<id,String> conIds = new Map<ID, String>();
    system.debug('##### value of trigger.new'+trigger.new);
    system.debug('##### value of trigger.old'+trigger.old);
     for(Contact con : Trigger.old){
        //Create an old and new map so that we can compare values
        Contact oldCon = Trigger.oldMap.get(con.ID);
        system.debug('###### value of oldMap'+oldCon);    
     }
}

======================
Debug Log values
======================
##### value of trigger.new {null}
##### value of trigger.old (Contact:{OwnerId=00590000000aleEAAQ,Salutation=Mr.,
LastName=test,Email=test@test.com, FirstName=test, Id=0039000000CY9URAA1})

###### value of oldMap  Contact:{OwnerId=00590000000aleEAAQ,Salutation=Mr.,
LastName=test,Email=test@test.com,  FirstName=test, Id=0039000000CY9URAA1})


====================
After undelete
===================
Important:-- When a record is deleted it goes into recycle bin. We can undelete a deleted
             record from recycle bin and this caused undelete trigger to fire.

trigger conceptOldandNew on Contact (before Insert) {
public Map<Id,String> conIds = new Map<ID, String>();
    system.debug('##### value of trigger.new'+trigger.new);
    system.debug('##### value of trigger.old'+trigger.old);
}

=======================
Debug Log Values
=======================
##### ##### value of trigger.new(Contact:{ OwnerId=00590000000aleEAAQ,Salutation=Mr.,
 LastName=test, Email=test@test.com,FirstName=test, IsDeleted=false})

##### value of trigger.old {null}


=====================
Before update
=====================

trigger testEmail on Contact (before Insert, before update){
    public Map<Id,String> conIDs = new Map<Id,String>();
    List<Contact>lstContacts= Trigger.New;
    Set<Id> setAccId = new Set<Id>();
    for(Contact con : lstContacts){
        setAccId.add(con.AccountId);
        system.debug('###### value of setAccId'+setAccId);
        //Create an old and new map so that we can compare values
        Contact oldCon = Trigger.oldMap.get(con.ID);
        system.debug('###### value of oldMap'+oldCon);  
        Contact newCon = Trigger.newMap.get(con.ID);
        system.debug('###### value of newMap'+newCon);           
        //Retrieve the old and new Reseller Email Field           
        string oldEmail = oldCon.Email;
        system.debug('###### value of oldEmail'+oldEmail);
        string newEmail = newCon.Email;
        system.debug('###### value of newEmail'+newEmail);
        //If the fields are different, the email has changed
        if(oldEmail != newEmail){
            conIDs.put(con.Id,con.Email);   
        }
        system.debug('###### value of conIds'+conIds);
    }
    Map<Id, Account> mapAccounts = new Map<Id,Account>([SELECT Id, Name from Account   where Id In:setAccId]);
    system.debug('###### value in mapAccounts'+ mapAccounts);
    system.debug('###### value of trigger.old'+ trigger.old);
    system.debug('####### oldMap'+trigger.newMap.size());
    system.debug('####### oldMap'+trigger.oldMap.size());
}

=====================
Debug Log Values
=====================

###### value of setAccId {0019000000C4pEyAAJ}

###### value of trigger.old (Contact:{HasOptedOutOfFax=false, OwnerId=00590000000aleEAAQ,
FirstName=test,LastName=Contact,Email=test567@gmail.com,AccountId=0019000000C4pEyAAJ,  Id=0039000000CBHVzAAP})

###### value of trigger.new (Contact:{HasOptedOutOfFax=false, OwnerId=00590000000aleEAAQ,
FirstName=test,LastName=Contact,Email=test600@gmail.com,AccountId=0019000000C4pEyAAJ,  Id=0039000000CBHVzAAP})


###### value of oldMap  Contact{OwnerId=00590000000aleEAAQ,LastName=Contact,
Experience__c=2.0,LastModifiedById=00590000000aleEAAQ,Email=test567@gmail.com,
AccountId=0019000000C4pEyAAJ, FirstName=test,Id=0039000000CBHVzAAP}

###### value of newMap Contact:{OwnerId=00590000000aleEAAQ,LastName=Contact,
FirstName=test,Email=test600@gmail.com, AccountId=0019000000C4pEyAAJ, 
Experience__c=2.0, Id=0039000000CBHVzAAP}

###### value of oldEmail      test567@gmail.com
###### value of newEmail     test600@gmail.com
###### value of conIds          {0039000000CBHVzAAP=test600@gmail.com}

###### value in mapAccounts {0019000000C4pEyAAJ=Account:{Name=test Account,                Id=0019000000C4pEyAAJ}}

####### oldMap  1
####### newMap  1


==================
After Insert
==================

//Create a trigger on Account object to insert a contact, when an account is getting inserted.
//Contact Name will be same as Account Name

trigger AccountName on Account (after insert){
    List<Contact> contacts = new List<Contact>();
    system.debug('##### value of trigger.new'+trigger.new);
    system.debug('##### value of trigger.old'+trigger.old);
    for(Account acc : Trigger.new){
        //Create new map so that we can compare values  
        Account newAcc = Trigger.newMap.get(acc.ID);
        system.debug('###### value of newMap'+newAcc);                      
     }
    for (Account a : Trigger.new){           
        contacts.add(new Contact (lastname = a.name, AccountId = a.Id));
    }
    insert contacts; 
}

====================
Debug Log values
====================

##### value of trigger.new (Account:{OwnerId=00590000000aleEAAQ, Name=Poddar,
Id=0019000000CaFDzAAN})

##### value of trigger.old {null}

###### value of newMap Account:{OwnerId=00590000000aleEAAQ, Name=Poddar,  Id=0019000000CaFDzAAN}


====================
After Update
====================

trigger Consetup on Contact (after insert, after update)
{
   system.debug('##### value of Trigger.New'+trigger.new);
   system.debug('##### value of Trigger.Old'+trigger.old);
   Set<Id> Accid = new Set<Id>();
   for (Contact con : Trigger.new){
       Accid.add(con.AccountId);
   }
   Map<Id,Account> accs = new Map<Id,Account>([Select Name, Id from Account Where Id in : Accid]);
 
    for (Contact con : Trigger.new)
    {
       accs.get(con.AccountId).Fax = con.Fax ;
       //Create an old and new map so that we can compare values
        Contact oldCon = Trigger.oldMap.get(con.ID);
        system.debug('###### value of oldMap'+oldCon);  
        Contact newCon = Trigger.newMap.get(con.ID);
        system.debug('###### value of newMap'+newCon);
    }
    update accs.values();
}

=======================
Debug Log Values
=======================

##### value of Trigger.New(Contact:{OwnerId=00590000000aleEAAQ,
Fax=(452)152-1000,LastName=Amul, AccountId=0019000000CaFCDAA3,
Id=0039000000CY9m0AAD})

##### value of Trigger.Old(Contact:{OwnerId=00590000000aleEAAQ,
Fax=(452) 152-1325, LastName=Amul, AccountId=0019000000CaFCDAA3, Id=0039000000CY9m0AAD})

###### value of oldMapContact:{OwnerId=00590000000aleEAAQ,LastName=Amul,
Fax=(452) 152-1325, AccountId=0019000000CaFCDAA3,Id=0039000000CY9m0AAD}

###### value of newMapContact:{OwnerId=00590000000aleEAAQ, Fax=(452) 152-1000, LastName=Amul, AccountId=0019000000CaFCDAA3,Id=0039000000CY9m0AAD}


===================
After Delete
===================

trigger afterTrigger on Account (after delete){
    system.debug('##### value of Trigger.old'+trigger.old);
    system.debug('##### value of Trigger.new'+trigger.new);
    system.debug('####### oldMap'+trigger.oldMap.size());
    for(Account acc : Trigger.old){
    List<Contact> contacts = [SELECT Id, AccountId from Contact where AccountId = :acc.Id Limit 20];
    for(Contact con : contacts){
        if(contacts.size()>0){
           delete contacts;
        }
    }
    }
}
   
======================   
Debug Log Values
======================

##### value of Trigger.old(Account:{OwnerId=00590000000aleEAAQ,Fax=(525) 325-3233, Name=Test1, Id=0019000000CaEroAAF,Ownership=Public})
##### value of Trigger.new {null}

####### oldMap 1







Friday, May 18, 2012

Javascript - Reload parent window from child window

Reload Using JavaScript:---

Oh.. How many time this type of requirement generate where we have to close child(Pop up) window and reload Parent Window as a result of this due to which we can see the resultant changes occurs in Parent Window. There are different JavaScript functions uses for this among them one or more working properly for the requirements. I uses different functions in past for this purpose and they are as given:--

1. <script>
        //alert({!isSaved});
        if({!isSaved} == true){
       // alert({!isSaved});
       // window.parent.location.reload();
        window.opener.location.reload();
        window.close();
    }
    </script>
 
2.  <script>
    function refresh(){
        opener.focus();
        opener.location.href = opener.location;
        self.close();
        }
    </script>

 3.  <script>
      function saveRec(){ 
            alert('Hi');
            UploadAttachment();
            var success = {!isSaved};
             // alert(success);
            if(success!= true){
                 window.open("https://ap1.salesforce.com/0039000000CNgaa");
                 window.close();
            }
        }
       </script>

4.    <script>
       function saveRec(){
           //alert('Hi');
           var parent = window.opener;
           parent.location ='https://ap1.salesforce.com/0019000000Ap7rK';
           UploadAttachment();
           //alert('reload done');
           window.location.reload(true);
           window.close();
       }
       </script>

 5. <script>
     function closepopup()
     {
          window.close();
          window.opener.location.href="give the parent url here";
      }  
      </script>

6. <form action="whatever" onsubmit="window.opener.location.reload();">

7. function CloseAndRefresh()
    {
        opener.location.reload(true);
        self.close();
    }
    </script>

 8. function SaveSetting()
     {
          //alert("Settings have been saved successfully.");
          var url = "CalInstitutions.aspx";
          opener.location.reload(true);
          //opener.history.go(0);
          opener.focus();
          self.close();
     }

9. function refreshParent() {
        window.opener.location.href = 'index.php';
         if (window.opener.progressWindow)
              window.opener.progressWindow.close();
              window.close();
    }

10.<script>
     function refreshmainwindow() {
     // this will close the pop up window
     window.close();
    // this will reload the parent window...
    if (!window.opener.closed) {
         window.opener.location.reload();
         window.opener.focus();
   }
   </script>


Enjoy Coding , Implement Thinking and Cloud is Future.
                                                                          ------  Abhinav Sharma

Friday, May 11, 2012

Send email to multiple contacts in Salesforce

Task:-- SendEmail() to Multiple Contacts onclick on CheckBox Corresponding to them through use of Wrapper Class

Description:-- In this task we have to perform mainly three different work and they are :--
1. Firstly we have to make a Wrapper Class for getting Table of Contacts with Check Box  corresponding to them.
2. After getting all records we have to use JavaScript for getting Id corresponding to each selected Check Box, Same  for Select All functionality and in the Last for placing Email of contacts for which check box is selected and placing it in To Section of Email.
3. Finally we have to write code for sending Email.

So, Apex Class for this is looking like this:---

public class CheckBoxEmailAssignmentPage{
    public List<Contact> allContacts{get;set;}
    public List<ContactModel> modelList{get;set;}
    public string to{get;set;}
    public List<string> addresses{get;set;}
    public String fromAdd{set;get;}
    public String body{set;get;}
    public String subject{get;set;}
    public CheckBoxEmailAssignmentPage(){
        addresses = new List<String>();
        integer  i =0;
        allContacts = [SELECT id, FirstName,LastName, email from Contact];
        modelList = new List<ContactModel>();
        for(Contact con :allContacts){
        if(con.Email!=null){
            ContactModel cm = new ContactModel();
            cm.srno = ++i;
            cm.con = con;
            modelList.add(cm);
            }
        }
    }
    public void sendEmail(){
        List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        addresses = to.split(',');
        email.setInReplyTo(fromAdd);
        email.setSubject(subject);
        email.setToAddresses(addresses);
        email.setPlainTextBody(body);
        emails.add(email);
        Messaging.sendEmail(emails);
    } 
    public class ContactModel{
        public Integer srno{get;set;}
        public Contact con{set;get;}
        public String text{get;set;}   
        public ContactModel(){
            srno = 0;
            con = new Contact();
        }
    }
}


Page:--

<apex:page controller="CheckBoxEmailAssignmentPage" id="pg">
    <apex:form id="frm">
     <apex:actionStatus id="st" startText="Email Sending....." startStyle="color:red"></apex:actionStatus>
        <script>
            function checkAll(cb,cbid){
                var inputElem = document.getElementsByTagName("input");
                if(inputElem.id != 'pg:frm:pb:pbt:allcheck'){
                for(var i=0; i<inputElem.length; i++){
                    if(inputElem[i].id.indexOf(cbid)!=-1){
                        inputElem[i].checked = cb.checked;
                    }
                }
                }
            }
            function selectedContacts(){
                var divObj = document.getElementById("contacts");
                var inputs = divObj.getElementsByTagName("input");
                var emails = '';
                var comma = "";
                if(inputs.length > 0 ){
                    for(i=0; i<inputs.length; i++){
                        if(inputs[i].type == "checkbox" && inputs[i].checked && inputs[i].id != 'pg:frm:pb:pbt:allcheck'){
       
                            emails += comma + inputs[i].value;
                            comma = ",";
                        }
                    }
                }
                 document.getElementById('pg:frm:pbs:pbs1:to').value=emails;
                 document.getElementById('pg:frm:pbs:pbs1:to1').value=emails;
            }
        </script>  
        <apex:pageBlock title="All Contacts" id="pb">
        <apex:actionFunction name="sendEmail" action="{!sendEmail}" reRender="frm" status="st"/>
        <apex:pageBlockButtons >
            <apex:commandButton value="Send" onclick="sendEmail();return false;"/>
        </apex:pageBlockButtons>
        <div id="contacts">
            <apex:pageBlockTable value="{!modelList}" var="mCon" id="pbt">
                <apex:column headerValue="Srno" value="{!mCon.srno}"/>
                <apex:column >
                    <apex:facet name="header">
                        <apex:inputCheckbox onclick="checkAll(this,'chk')" id="allcheck" onchange="selectedContacts()"/>
                        </apex:facet>                
                    <input type="checkbox" id="chk" value="{!mCon.con.email}" onclick="selectedContacts()"/>
                </apex:column>
                <apex:column headerValue="First Name" value="{!mCon.con.FirstName}"/>
                <apex:column headerValue="Last Name" value="{!mCon.con.LastName}"/>
                <apex:column value="{!mCon.con.Email}"/>
            </apex:pageBlockTable> 
        </div>         
        </apex:pageBlock>
        <apex:pageBlock id="pbs" rendered="true">
            <apex:pageBlockSection id="pbs1">
                <apex:outputLabel >From </apex:outputLabel>
                <apex:inputText value="{!fromAdd}"/>
                <apex:outputLabel >To </apex:outputLabel>
                <apex:inputText value="{!to}" id="to"/>
                <apex:outputText value="{!to}" id="to1"/>
                <apex:outputLabel >Subject </apex:outputLabel>
                <apex:inputText value="{!subject}"/>
                <apex:outputLabel >Message </apex:outputLabel>
                <apex:inputTextarea value="{!body}" rows="5"/>
            </apex:pageBlockSection>
        </apex:pageblock>
    </apex:form>
</apex:page>




Run this Code and send Email to selected Contacts and enjoy coding.

                                                                ======Abhinav Sharma===========