Wednesday, 17 October 2012

maximum trigger depth exceeded MyObject__c trigger

* The above error is mainly because of the recursive execution of the trigger after update again and again.
* To control the recursive trigger, use if condition or any other controllable steps to avoid the recursion.
Refer:
http://boards.developerforce.com/t5/Apex-Code-Development/Classic-Error-maximum-trigger-depth-exceeded-Opportunity-trigger/td-p/209817

Using case in formula fields of sfdc

CASE(MONTH(Mon_Field__c ), 01, 'January/2012', 02, 'February/2012',03, 'March/2012',04,'April/2012',05, 'May/2012',06,'June/2012',07,'July/2012',08,'August/2012',09, 'September/2012',10,'October/2012',11,'November/2012',12,'December/2012','')

* In the above formula, to display year dynameically intead of 'January/2012' use like below:
'January/'+Text( YEAR(Mon_Field__c ))

Scheduling Batch Class after 6 minutes whenever a batch finish method executed in salesforce

AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed,
         TotalJobItems, CreatedBy.Email
         FROM AsyncApexJob WHERE Id =:BC.getJobId()];

* Above syntax is to retrieve information regarding to the jobs.
             Batch_classname bs = new Batch_classname();
             Datetime sysTime = System.now();
             sysTime = sysTime.addminutes(6);
             String chron_exp = '' + sysTime.second() + ' ' + sysTime.minute() + ' ' +
             sysTime.hour() + ' ' + sysTime.day() + ' ' + sysTime.month() + ' ? ' + sysTime.year();           
             System.schedule('Update Actual'+sysTime.getTime(),chron_exp, bs);

Tuesday, 16 October 2012

Scheduling batch class for every 5 minutes using system.schedule method in salesforce

Batch_scheduledclassname bs = new Batch_scheduledclassname bs();
String sch = '0 6 * * * ? ';
System.schedule('My Job1', sch, bs);

Note: While writing schedular class don't forget to use datebase.executeBatch method which inturn will run the apex batch class.
* Above 6 means every hour 6th minute.
* If you want to schedule the calss for every 5 minutes then you need paste above code with some changes for 10 times in developer console.
* Changes are:
- instead of 6 replace with 12,18,24..... like that.
- Change the Batch Job name My Job1 to some other name whenever we want to submit new job

Tuesday, 2 October 2012

Using Batch Apex to Change the Account Owners


global class AccountOwnerReassignment implements 
             Database.Batchable<SObject>, Database.Stateful{
    
    User fromUser{get; set;}
    User toUser{get; set;}
    Double failedUpdates{get; set;}
    //Parameter Construcotr
    global AccountOwnerReassignment(User fromUser, User toUser){
        this.fromUser = fromUser;
        this.toUser = toUser;
        failedUpdates = 0;
    }
    
    global Database.queryLocator 
                    start(Database.BatchableContext ctx){
        return Database.getQueryLocator([SELECT id, name, ownerId 
                        FROM Account WHERE ownerId = :fromUser.id]);
    }
    
    global void execute(Database.BatchableContext ctx, List<Sobject> scope){
        List<Account> accs = (List<Account>)scope;
        
        for(Integer i = 0; i < accs.size(); i++){
            accs[i].ownerId = toUser.id;
        }
        
        List<Database.SaveResult> dsrs = Database.update(accs, false);
        for(Database.SaveResult dsr : dsrs){
            if(!dsr.isSuccess()){
                failedUpdates++;
            }
            
        } 
    }
    
    global void finish(Database.BatchableContext ctx){
    
        AsyncApexJob a = [SELECT id, ApexClassId, 
                       JobItemsProcessed, TotalJobItems, 
                       NumberOfErrors, CreatedBy.Email 
                       FROM AsyncApexJob 
                       WHERE id = :ctx.getJobId()];
        
        String emailMessage = 'Your batch job '
             + 'AccountOwnerReassignment '
             + 'has finished.  It executed ' 
             + a.totalJobItems 
             + ' batches.  Of which, ' + a.jobitemsprocessed 
             + ' processed without any exceptions thrown and ' 
             + a.numberOfErrors +
             ' batches threw unhandled exceptions.'
             + '  Of the batches that executed without error, ' 
             + failedUpdates 
             + ' records were not updated successfully.';
        
        Messaging.SingleEmailMessage mail = 
              new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {a.createdBy.email};
        mail.setToAddresses(toAddresses);
        mail.setReplyTo('noreply@salesforce.com');
        mail.setSenderDisplayName('Batch Job Summary');
        mail.setSubject('Batch job completed');
        mail.setPlainTextBody(emailMessage);
        mail.setHtmlBody(emailMessage);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] 
                           { mail });
    }    
}
In Developer Console Paste below code:

User fromUser = [select id,firstname from user where firstname = 'name of the user'];
User toUser = [select id,firstname from user where firstname = 'name of the user'];                 
Database.executeBatch(new AccountOwnerReassignment(fromUser,toUser));
Note: Name of the user means, Goto Managed Users>Click on particuar user> At the top below the User one name will display that name we should give in place of 'name of the user'

Calling Batch Apex from Trigger:
* Goto App Setup> Customize> Account> Triggers

Trigger AccountOwnerReassignment on Account (before insert) {
    List<Account> al = Trigger.new;
    for(Account a:al) {
        User fromUser = [select id,firstname from user where alias = 'alias name'];
        User toUser = [select id,firstname from user where alias = 'alias name'];                 
        try {
            Database.executeBatch(new AccountOwnerReassignment(fromUser,toUser));
        }
        Catch(Exception E) {
        }
    }
}
Note: In case, no rows queried from the SOQL Queries below error will arise.
Error: Invalid Data. Review all error messages below to correct your data.Apex trigger AccountOwnerReassignment caused an unexpected exception, contact your administrator: AccountOwnerReassignment: execution of BeforeInsert caused by: System.QueryException: List has no rows for assignment to SObject: Trigger.AccountOwnerReassignment: line 4, column 1

Refer:
http://developer.force.com/cookbook/recipe/using-batch-apex-to-reassign-account-owners

Monday, 1 October 2012

Changing hyperlink from one color to another color



<script type="text/javascript"> 
  function turnRed(id) { 
  alert("hi"); 
  var myPara = document.getElementById(id); 
  alert(myPara); 
  myPara.style.color = "green"; 
  } 
  </script> 
  <apex:commandLink action="{!gogoogle}" target="_blank" value="Go Google" id="check" style="color:red" onclick="turnRed('{!$Component.check}')"/>

Labels