• karthikeyan perumal
  • PRO
  • 3092 Points
  • Member since 2015

  • Chatter
    Feed
  • 86
    Best Answers
  • 0
    Likes Received
  • 2
    Likes Given
  • 1
    Questions
  • 522
    Replies
Hello,
I have a batch job which runs to populate two objects.. Monthly Activity(MonAct) and URL Individual monthly Activity (URLIndMonAct)...
The problem with the response is that I am quering for MonAct records and I am getting back 5 of them . And each of those MonAct records contains with it thousands of URLIndMonAct records...

I have limited my query to just 2 records per batch but I am still getting DML Rows : 10001 error ..
If I redice the size to 1 record, the batch is running for too long...

Can any one please guide me, how can I modify my code to prevent this error and not lose any records while processing...
Any help is appreciated.

Thanks!
global class BatchToUpdateGARecords implements Database.Batchable<sObject>, Database.Stateful, Schedulable, Database.AllowsCallouts{

    private List<String> EMAIL_BATCH_RESULTS = new List<String>{System.Label.Email_List};  
    global  IndividualMonthlyGARecords.BatchResponse runningBatchResponse;
    private String query;
    private Integer queryYear;
    private Integer queryMonth;

    global BatchToUpdateGARecords(Integer year, Integer month){
        runningBatchResponse = new IndividualMonthlyGARecords.BatchResponse();

        // Validate user input, if request to run batch is not for todays date
        if(month != null && year != null && month >= 0 && month <= 12 && year > 1950){
            this.queryYear  = year;
            this.queryMonth = month;
        }
        else{
            Date yesterdaysDate = Date.today().addDays(-1);

            this.queryYear  = yesterdaysDate.year();
            this.queryMonth = yesterdaysDate.month();
        }

        this.query  = 'SELECT Id, GID__c ';
        this.query += 'FROM Monthly_Activity__c ';
        this.query += 'WHERE Year__c = ' + queryYear + ' ';
        this.query += 'AND Month__c = ' + queryMonth + ' ';
        this.query += 'AND GID__c <> null ';
        this.query += 'AND GID__c > 0 ';
        
    }

    global BatchToUpdateGARecords(){
        this(null, null);
    }
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<Monthly_Activity__c> currentBatchRecords){
	
        List<Monthly_Activity__c> MonthlyActivities = [
            SELECT Id, GID__c, Month__c, Year__c
            FROM Monthly_Activity__c 
            WHERE Year__c =: queryYear
            AND Month__c =: queryMonth
            AND GID__c IN: Pluck.decimals('GID__c', currentBatchRecords)
        ];        

        List<URL_Individual_Monthly_Activity__c> urlIndividualMonthlyActivities = [
            SELECT Id, GID__c, URL__c, Month__c, Year__c
            FROM URL_Individual_Monthly_Activity__c 
            WHERE Year__c =: queryYear
            AND Month__c =: queryMonth
            AND GID__c IN: Pluck.decimals('GID__c', currentBatchRecords)
        ];        
         
        if(MonthlyActivities.isEmpty()){
            return;
        }
    
        try{           
            IndividualMonthlyGARecords.batchHandlerToUpdateRecords(
                runningBatchResponse,
                MonthlyActivities,
                urlIndividualMonthlyActivities,
                queryYear,
                queryMonth
            );
        
       }catch(exception ex){
            system.debug('exception call :'+ ex.getMessage());
            system.debug('exception call line :'+ ex.getStackTraceString());
        }
        if(runningBatchResponse != null && !runningBatchResponse.getSuccessRecords().isEmpty()){
            List<Database.SaveResult> updateResults =
                Database.update(runningBatchResponse.getSuccessRecords(), false);

            for(Database.SaveResult updateResult : updateResults){
              if(!updateResult.isSuccess()){
                for(Database.Error err : updateResult.getErrors()){
                  runningBatchResponse.addDatabaseError(err.getMessage());
                }
              }
            }
        }

        runningBatchResponse.clearSuccessRecords();
    
        if(runningBatchResponse != null && !runningBatchResponse.getSuccessRecordsIMA().isEmpty()){

            List<Database.SaveResult> updateResults1 =
                Database.update(runningBatchResponse.getSuccessRecordsIMA(), false);

            for(Database.SaveResult updateResult1 : updateResults1){
              if(!updateResult1.isSuccess()){
                for(Database.Error err : updateResult1.getErrors()){
                  runningBatchResponse.addDatabaseError(err.getMessage());
                }
              }
            }
        }

        runningBatchResponse.clearSuccessRecords();
  
    }

    global void execute(SchedulableContext SC){
        Database.executeBatch(new BatchToUpdateGARecords(), 2);                            //Changed from 5    }
    
    global void finish(Database.BatchableContext BC){
        AsyncApexJob apexBatchResult = [
            SELECT Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email
            FROM AsyncApexJob
            WHERE Id =: BC.getJobId()
        ];
    
        // Generate email body
        String emailBody = 'Apex Batch to Update PageviewSessions processed '
            + apexBatchResult.TotalJobItems + ' batches with '+ apexBatchResult.NumberOfErrors + ' failures.\n\n'
            + 'Database errors (if any): ' + JSON.serialize(runningBatchResponse.getDatabaseErrors()) + '\n';
        
        // Extract error string from batch response
        //emailBody += runningBatchResponse.generateErrorString();

        // Send email
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(EMAIL_BATCH_RESULTS);
        mail.setSenderDisplayName('About.com Experts - Batch Results');
        mail.setSubject('About.com - Batch to Update PageviewSessions - status: ' + apexBatchResult.Status);
        mail.setPlainTextBody('Batch Process has completed\n\n' + emailBody);

        Messaging.sendEmail(new List<Messaging.SingleEmailMessage>{mail});
    }
}

 
I am trying to write a trigger on my Lead Object that will not allow a user to click Convert unless a boolean field is True. I need help with some sample code to get started. 

I plan to create an Approval Process on the lead record, then with the final Approver action have a field update to have my custom checkbox (Approved) set to True. 

Once this happens I want the user to be able to click Convert, but only once the checkbox is set to true. If it has not gone through the approval process, the user shoudnt be able to click convert. 

I should also note I would only want this for a specific record type of my lead object.
Can you send data (via SOAP) out from Sandbox to another System (not Salesforce)?
#newbie
Do requests with the If-None-Match header, that return a 304 response, count towards my API limit?
We have users in both Classic and Lightning using the standard "New" button on leads.  I need to override the standard "New" button and redirect the user to a lightning app.  I created a VF page action that will redirect the user to the lightning app.  Everything works great however for lightning users, the redirect opens a new tab in the browser.  How do I keep the redirect on the same browser window in lightning?  Do I need to create a VF page pulling in a lightning component?
My salesforce for outlook account was automatically logged out but when I click to log back in and enter my credentials I get this message: 
User-added image
 
//BlockContentLinkTrigger
trigger BlockContentLinkTrigger on ContentDocumentLink (before insert) {  
    for(ContentDocumentLink  contDocL : Trigger.new) {
      if (CDLHelper.isSharingAllowed(contDocL)) {  
          contDocL.addError('Pièce joint bloquée depuis objet ContentDocumentLink');
     } 
   }  
}

//CDLHelper
public class CDLHelper {
    public static boolean isSharingAllowed(ContentDocumentLink cdl) {
        //String docId = cdl.ContentDocumentId;        
        ContentVersion version = [select PublishStatus, FileExtension from ContentVersion
                                  where ContentDocumentId =: cdl.ContentDocumentId limit 5];              
        if (version.PublishStatus.equals('P') && (version.FileExtension != 'null')) {
            return false;
        }
        return true;
    }
}

 
Hi,
I need update the fields when I create a new register and when I update the same.
I created a trigger that execute a method that make this update.

When I create a new register This method works, and when I try update occurs a error.

Can you evaluate my code and see if I did the right way, and what is wrong?

Trigger code:
Trigger INSERT
trigger CalcularTudoTrigger on Item_de_oportunidade__c (after insert) {
    
    Item_de_oportunidade__c item = new Item_de_oportunidade__c();
    item = [SELECT Id, Name, Margin__c, Sales_Type__c, nome_oportunidade__c, Category__c, Extra_Expenses__c
            FROM Item_de_oportunidade__c
               WHERE Id IN : Trigger.newMap.keyset() limit 1];
    
    Opportunity op = new Opportunity();
    op = [SELECT Id FROM Opportunity WHERE Id = : item.nome_oportunidade__c];

    if(trigger.isAfter){
         if(trigger.isInsert){
            AutomatizaCalculos.inserirCalculoMVS(item.Id, op.Id, item.Sales_Type__c, item.Category__c, item.Margin__c, item.Extra_Expenses__c);
         }
    }
}

Trigger UPDATE
trigger CalcularAtualizacao on Item_de_oportunidade__c (before update) {
    
    Item_de_oportunidade__c item = new Item_de_oportunidade__c();
    item = [SELECT Id, Name, Margin__c, Sales_Type__c, nome_oportunidade__c, Category__c, Extra_Expenses__c
            FROM Item_de_oportunidade__c
               WHERE Id IN : Trigger.newMap.keyset() limit 1];
    
    Opportunity op = new Opportunity();
    op = [SELECT Id FROM Opportunity WHERE Id = : item.nome_oportunidade__c];

    if(trigger.isBefore){
         if(trigger.isUpdate){
            AutomatizaCalculos.inserirCalculoMVS(item.Id, op.Id, item.Sales_Type__c, item.Category__c, item.Margin__c, item.Extra_Expenses__c);
         }
    }

}

APEX CODE:

global class AutomatizaCalculos {
    
    public static void inserirCalculoMVS(String id_item, String regional, String tipoVenda, String categoria, Decimal margem, Decimal gastos){
        Item_de_oportunidade__c item = new Item_de_oportunidade__c();
        item = [SELECT Id, Name, Sales_Type__c, Category__c, Margin__c, Extra_Expenses__c FROM Item_de_oportunidade__c WHERE Id = : id_item];
        
        if(regional == 'AR'){
            if(tipoVenda == 'FEE'){
                item.MVS__c = (margem * 0.956) - gastos;
                inserirCalculoComissao(item.MVS__c, item.Id, categoria);
            }else{
                item.MVS__c = margem - gastos;
                inserirCalculoComissao(item.MVS__c, item.Id, categoria);
            }
            
        }else if(regional == 'CL' || regional == 'US'){
                item.MVS__c = margem - gastos;
            inserirCalculoComissao(item.MVS__c, item.Id, categoria);
        }else{
            if(tipoVenda == 'FEE'){
                item.MVS__c = (margem * 0.8725)-gastos;
                inserirCalculoComissao(item.MVS__c, item.Id, categoria);
            }else{
                item.MVS__c = margem - gastos;
                inserirCalculoComissao(item.MVS__c, item.Id, categoria);
            }  
        }
    update item;
    }
    public static void inserirCalculoComissao(Decimal mvs, String item_id, String categoria){
        Item_de_oportunidade__c item = new Item_de_oportunidade__c();
        item = [SELECT Id, Name, Margin__c, MVS__c, MS_Customer__c, Category__c FROM Item_de_oportunidade__c WHERE Id = : item_id];
        if(categoria == 'IT SERVICES' || categoria == 'MANAGED SERVICES'){
            if(item.MS_Customer__c == true){
                item.Fee_Pre_Sales__c = mvs *0.015;
                item.Fee_Pre_Manager__c = mvs * 0.075;
                item.Fee_Pre_Rep__c = mvs * 0.03;
            }else{
                item.Fee_Pre_Sales__c = mvs *0.03;
                item.Fee_Pre_Manager__c = mvs * 0.015;
                item.Fee_Pre_Rep__c = mvs * 0.06;
            }
            
        }else{
            if(item.MS_Customer__c == true){
                item.Fee_Pre_Sales__c = mvs *0.015;
                item.Fee_Pre_Manager__c = mvs * 0.075;
                item.Fee_Pre_Rep__c = mvs * 0.03;
            }else{
                item.Fee_Pre_Sales__c = mvs *0.02;
                item.Fee_Pre_Manager__c = mvs * 0.01;
                item.Fee_Pre_Rep__c = mvs * 0.04;
            } 
        }
        
        update item;
    }
}

Thanks
Rafael
I have a custom object called Service Contract. The object contains the following fields Effective Date (date) and Calls Per Year (number) End Contract (checkbox). 

When a user sets up the service contract for a customers machine the customer will decide how many times per year they want the machine serviced.

For example: Starting April 1,2017 I want my machine serviced 2 times per year.
I need the event/reminder to tell the user on October 1 and April 1 to create a work order untill End Contract is checked. 
I have no idea how to work this out. My expirence with Apex is null, I do have other programing expirience and want to learn how to do this just really need some help. 

I had been advised previously to create a custom setting which I have but do not know how to proceed. 
I created a custom object and a Submit for Approval button appeared on it that I can't remove from the page layout.  I have no approval processes linked to it, no approval history, no Visualforce.  It's tangentially linked to Contracts, but I have three layers of custom master-detail objects linked to Contracts where the Submit button is not present.  The lowest level object in that hierarchy has a lookup to the object in question, but there are no lookups or master-detail fields on the object with the button.  Frustratingly, all users see the button, even the ones who only have read access to the records.

What on earth did I do to make this button appear and how do I get rid of it? 
Hello,

I have a custom sObject called AccountDetail that is the child in a lookup relationship with Account. It is also the parent in a lookup relationship with Opportunity. In my situation, I have Master Accounts that have AccountDetail objects, and I have Child Accounts that have Opportunity objects. Here's a diagram to help you visualize these relationships:

Diagram describing relationship between the relevant sObjects
I need to find all the Child Accounts related to each Master Account based on the relationships between their Opportunity and AccountDetail objects (I understand that organizing the data this way does not seem to make sense, but because of reasons outside of my control, this is how I have to do it). 

The query I am trying to use looks like this:
List<Account> accounts = 
   [SELECT Account.Id, Account.Name FROM Opportunity
    WHERE AccountDetail__c IN 
    (SELECT Id FROM AccountDetail__c
    WHERE Account__r.Id= :masterAccountId)].Account;
but this results in an Illegal assignment from Account to List<Account> error.

How do I make this query work to select all the Child Accounts instead of just one? Is there a better way to query the Child Accounts?
I have a custom button that SELECTS a Product for the Opportunity Lines.   This works great

Addition that is needed:
When the product is SELECTED and the Number of Years = 1 or greater  ---  I need it to populate a value  that is on the Opportunity Line Number that equals the number of years.  I am not sure the best way to get this to work.  If the Number of Years = 0 I do not want to change the dollar value for them.  


Do I need to use a Flow or Process builder?
 
Muddling my way through my first visual force page; not a developer by trade.  I've created a visual force button that will output the content of a related list to my opportunities (Visit Report) to a PDF file so that people can easily scroll through all VR's associated with an Opportunity & share with non-SF users.  My code is listed below.  

I have everything working as I like except the following 2 elements which I'm not sure how to handle (hoping for some help):

1) I want to sort the output Descending by the report date field
2) I want to make the headers of the table appear at the top of each page (repeating headers)

Can anybody help with this?  It seems simple but I'm getting lost in the details.
 
<apex:page standardController="Opportunity" renderAs="PDF">
<head>
<style>
@page { size:landscape;}
.headerRow .TableTitle {
            background-color: #139cd8 !important;
            cellPadding="5";}
            body {font-family: 'Arial Unicode MS'; font-size:12px}


 </style></head>
 <apex:image id="logo1" url="/servlet/servlet.ImageServer?id=015i0000002XNDw&oid=00D630000009OtH&lastMod=1394633629000" width="25%" height="25%"/>
 <br/>
 <apex:pageBlock >

        <apex:pageBlockTable value="{!Opportunity.Visit_reports__r}" var="item" cellpadding="5" columnsWidth="5%,5%,5%,10%,65%" border="1">
            <apex:column style="vertical-align:top; text-align:center" headerValue="Name" headerClass="TableTitle" value="{!item.Name}"/>
            <apex:column style="vertical-align:top; text-align:center" headerValue="Account" headerClass="TableTitle" value="{!item.Account__c}"/>
            <apex:column style="vertical-align:top; text-align:center" headerValue="Report Date" headerClass="TableTitle" value="{!item.Report_Date__c}"/>
            <apex:column style="vertical-align:top; text-align:left" headerValue="Purpose of Visit" headerClass="TableTitle" value="{!item.Purpose_of_Visit__c}"/>
            <apex:column style="vertical-align:top; text-align:left" headerValue="Visit Details" headerClass="TableTitle" value="{!item.Visit_Details__c}"/>
        </apex:pageBlockTable> 
        </apex:pageBlock>
</apex:page>

 
User-added image
User-added image

I Can not find any certificates that are expiring soon. What Should i do?
Processbuilder allows me to create nearly 17 Scheduled actions per Criteria, but would like to know if there is actually any limit or is it implied upon execution of the critiera... There is no direct answer in documentation...
Hello
Has anyone worked on soap api & rest api testing & java application testing?
what are the commonly used tools?
how to perform technical & function testing?
what the pros and cons involved?

Pls provide explanation.

Thanks
Pooja
Hi,
In the below, there are two pageblock, in first block is to display the list of Account and second block is to insert the account.And inserted account in second block should be dynamicaly displayed in 1st block. when I click on Save button it's showing the below error.
System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Account Name]: [Account Name]
 
Please can anyone help me to solve this error.

<apex:page controller="multiAccountInsert">
    <apex:form >
        <apex:pageBlock >
         
            <apex:pageBlockTable value="{!accts}" var="a" reRender="display" >
                  <apex:column value="{!a.Name}"/>  
                  <apex:column value="{!a.Industry}"/>
                  <apex:column value="{!a.phone}"/>             
            </apex:pageBlockTable>
     </apex:pageBlock>
         <apex:pageBlock >
              <apex:pageBlockButtons location="top" >
                <apex:commandButton value="Save" action="{!Save}" id="display"/>
            </apex:pageBlockButtons>
                <apex:pageblocksection >
                    Enter Name: <apex:inputText value="{!at.Name}"/>
                </apex:pageblocksection>
         </apex:pageBlock>
    </apex:form>
</apex:page>
------------------------------------------
public class multiAccountInsert{

    public Account at { get; set; }

    public PageReference Save() {
    at = new Account();
    insert at;
        return null;
    }


    public List<Account> accts {get; set;}
        
        public multiAccountInsert(){
        accts = new List<Account>();
        accts = [Select id, Name, Industry, Phone from Account];
       }
}
Hi,

First bear with me, I'm an admin learning Apex.

I created a trigger that creates an Opportunity once an Account is created, it's working great but im struggling with the test class.

User-added image

I realize I have an issues with line 5, but im unsure how to insert the date fields into the test account that will then pull through to the new test opportunity (I tried to remove them and got an error that Variable did not exist).  
User-added image

Thoughts?  Help? 

 
Hi All,
I have written batch apex to insert data in Task from two objects.
I am able to get data from Obj1__c. I am not able to get from Obj2__c
Here is my code.
 
global class batchTwo Implements Schedulable, Database.Batchable<sObject>{
global void execute(SchedulableContext sc) {
    Database.executeBatch(this);
}

global database.queryLocator start(Database.BatchableContext BC) {
    
    
        return database.getQueryLocator([SELECT Id,AccountId__c,F1__c,F2__c FROM Obj1__c]);
    
} 

global void execute(Database.BatchableContext BC, list <obj1__c> scope) {

    List <Task> taskList = new List<Task>();

   Map<Id, Obj2__c> mapObj2=new Map<Id, Obj2__c>([SELECT Account_Name__r.Id,Obj2_F2__c FROM Obj2__c]);
    
    for(Obj1__c c : scope) {
            Task tsk             = new Task();
            if(mapObj2.containsKey(c.AccountId__c)) {
             Obj2__c tmpSales = mapObj2.get(c.AccountId__c);
            
             tsk.F1__c=tmpSales.Obj2_F2__c;
             
            }
            
            tsk.WhatId           = c.AccountId__c;
            tsk.ActivityDate     = System.today();
            tsk.Status           = 'Open';
            tsk.Priority         = 'Normal';
            tsk.Subject          = 'call';
            tsk.P1__c=c.F1__c;
            tsk.P2__c=c.F2__c;
            
           taskList.add(tsk);
    } //close for-loop

   
        insert taskList;
    
       
    
} 

global void finish(Database.BatchableContext BC) {


} 
}

I am getting problem in Line no. 21 to 24.
Please suggest me what changes need to be done.
Please help me.
Thanks in Advance
i want to do pagination for account object . and all the records shown in that vf page we can edit and save in the same vf page

Hi All,

I want to created a Lead Conversion Report (Converted Percentage) based on Lead Owner and Lead Source.
How to create this report ??

Thanks,
Raghu

hello, i'm trying to open a new visualforce from a button and it works, the problem is that i need to open it in a new window, not in te same page, is it possible to do that?
first i was doing this:
<button id="vpre" hidden="hidden" type="button" onClick="window.open('/apex/vistaauth?ida='{!res},'Vista Previa','width=700,height=650');">V. Previa</button>
and it work very well but i cant pass values from the controller to the new vf

now i can pass them but i cant set the new page in a new window or customize the size
public PageReference abrir()
{   
       PageReference pageRef= new PageReference('/apex/vistaauth');
       pageRef.getParameters().put('tp', tipoo);
       pageRef.setRedirect(true);        
       return pageRef;           
   }


 
I have an Apex Trigger in my org (written well before me) that is not making sense. It is now causing some of my newer processes to fail.
I disabled it in the sandbox but have not yet pushed the change set over for fear of breaking something unkonw to me.
Here is my trigger:
trigger changeAssignTo on Task (before insert) {
     for (Task t : Trigger.new) {
        if (t.Subject.contains('{!') && t.Subject.contains('}')) {
           String lookup = t.Subject.substring(t.Subject.indexOf('{!') + 2, t.Subject.indexOf('}'));
           String[] lookupSplit = lookup.split('\\.');
           SObject s = Database.query('select ' + lookupSplit[1] + ' from ' + lookupSplit[0] + ' where Id = \'' + t.WhatId + '\'');
           t.OwnerId = (Id)s.get(lookupSplit[1]);
           t.Subject = t.Subject.substring(0, t.Subject.indexOf('{!')) + t.Subject.substring(t.Subject.indexOf('}') + 1); 
        }
     }    
}
If I deploy the change set and something fails, can I undo it?
And does this trigger make sense to anyone for any reason??
I don't want tasks reassinged when created.
Thanks..
 
I'm working through the Map Your Workflow Criteria to Process Criteria unit of the Workflow Rule Migration module. When I check my challenge, I'm getting this error code: XPVHLWGV.
Hi,
I need your help with the point calculation below.  How do I modify the formula so that when StageName is
Discovery should be 1 Point,
Consensus 1.5,
Evluation 1.5,
Justification 1.5,
Negotiate 1.5 ,
Won 1.5.
Currently, it's defaulting points on above stages to 1. 

Below formula is working great but needed add additional stages to 1.5 points.

IF(ISPICKVAL([Opportunity].StageName , "7 Closed Lost") && ISPICKVAL([Opportunity].Lost_Reason__c , "Duplicate Opp"), 0, 
IF(ISPICKVAL([Opportunity].StageName , "7 Closed Lost" )&&
ISPICKVAL([Opportunity].Count__c ,"<200"), 1,

IF(ISPICKVAL([Opportunity].StageName , "7 Closed Lost") &&
ISPICKVAL([Opportunity].Count__c , "200 - 999"),1.5,

IF(ISPICKVAL([Opportunity].StageName , "7 Closed Lost" )&&
ISPICKVAL([Opportunity].Count__c ,"1000+") ,2,

IF(!ISPICKVAL([Opportunity].StageName , "7 Closed Lost" )&&
ISPICKVAL([Opportunity].Count__c ,"<200"), 1,

IF(!ISPICKVAL([Opportunity].StageName , "7 Closed Lost") &&
ISPICKVAL([Opportunity].Count__c , "200 - 999"),1.5,

IF(!ISPICKVAL([Opportunity].StageName , "7 Closed Lost" )&&
ISPICKVAL([Opportunity].Count__c ,"1000+") ,2,

IF(AND(!ISPICKVAL([Opportunity].StageName , "7 Closed Lost" ),
 !ISPICKVAL([Opportunity].Lost_Reason__c , "Duplicate Opp"),
ISPICKVAL([Opportunity].Count__c ,"")), 1,
0))))))))
Hello,
I have a batch job which runs to populate two objects.. Monthly Activity(MonAct) and URL Individual monthly Activity (URLIndMonAct)...
The problem with the response is that I am quering for MonAct records and I am getting back 5 of them . And each of those MonAct records contains with it thousands of URLIndMonAct records...

I have limited my query to just 2 records per batch but I am still getting DML Rows : 10001 error ..
If I redice the size to 1 record, the batch is running for too long...

Can any one please guide me, how can I modify my code to prevent this error and not lose any records while processing...
Any help is appreciated.

Thanks!
global class BatchToUpdateGARecords implements Database.Batchable<sObject>, Database.Stateful, Schedulable, Database.AllowsCallouts{

    private List<String> EMAIL_BATCH_RESULTS = new List<String>{System.Label.Email_List};  
    global  IndividualMonthlyGARecords.BatchResponse runningBatchResponse;
    private String query;
    private Integer queryYear;
    private Integer queryMonth;

    global BatchToUpdateGARecords(Integer year, Integer month){
        runningBatchResponse = new IndividualMonthlyGARecords.BatchResponse();

        // Validate user input, if request to run batch is not for todays date
        if(month != null && year != null && month >= 0 && month <= 12 && year > 1950){
            this.queryYear  = year;
            this.queryMonth = month;
        }
        else{
            Date yesterdaysDate = Date.today().addDays(-1);

            this.queryYear  = yesterdaysDate.year();
            this.queryMonth = yesterdaysDate.month();
        }

        this.query  = 'SELECT Id, GID__c ';
        this.query += 'FROM Monthly_Activity__c ';
        this.query += 'WHERE Year__c = ' + queryYear + ' ';
        this.query += 'AND Month__c = ' + queryMonth + ' ';
        this.query += 'AND GID__c <> null ';
        this.query += 'AND GID__c > 0 ';
        
    }

    global BatchToUpdateGARecords(){
        this(null, null);
    }
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<Monthly_Activity__c> currentBatchRecords){
	
        List<Monthly_Activity__c> MonthlyActivities = [
            SELECT Id, GID__c, Month__c, Year__c
            FROM Monthly_Activity__c 
            WHERE Year__c =: queryYear
            AND Month__c =: queryMonth
            AND GID__c IN: Pluck.decimals('GID__c', currentBatchRecords)
        ];        

        List<URL_Individual_Monthly_Activity__c> urlIndividualMonthlyActivities = [
            SELECT Id, GID__c, URL__c, Month__c, Year__c
            FROM URL_Individual_Monthly_Activity__c 
            WHERE Year__c =: queryYear
            AND Month__c =: queryMonth
            AND GID__c IN: Pluck.decimals('GID__c', currentBatchRecords)
        ];        
         
        if(MonthlyActivities.isEmpty()){
            return;
        }
    
        try{           
            IndividualMonthlyGARecords.batchHandlerToUpdateRecords(
                runningBatchResponse,
                MonthlyActivities,
                urlIndividualMonthlyActivities,
                queryYear,
                queryMonth
            );
        
       }catch(exception ex){
            system.debug('exception call :'+ ex.getMessage());
            system.debug('exception call line :'+ ex.getStackTraceString());
        }
        if(runningBatchResponse != null && !runningBatchResponse.getSuccessRecords().isEmpty()){
            List<Database.SaveResult> updateResults =
                Database.update(runningBatchResponse.getSuccessRecords(), false);

            for(Database.SaveResult updateResult : updateResults){
              if(!updateResult.isSuccess()){
                for(Database.Error err : updateResult.getErrors()){
                  runningBatchResponse.addDatabaseError(err.getMessage());
                }
              }
            }
        }

        runningBatchResponse.clearSuccessRecords();
    
        if(runningBatchResponse != null && !runningBatchResponse.getSuccessRecordsIMA().isEmpty()){

            List<Database.SaveResult> updateResults1 =
                Database.update(runningBatchResponse.getSuccessRecordsIMA(), false);

            for(Database.SaveResult updateResult1 : updateResults1){
              if(!updateResult1.isSuccess()){
                for(Database.Error err : updateResult1.getErrors()){
                  runningBatchResponse.addDatabaseError(err.getMessage());
                }
              }
            }
        }

        runningBatchResponse.clearSuccessRecords();
  
    }

    global void execute(SchedulableContext SC){
        Database.executeBatch(new BatchToUpdateGARecords(), 2);                            //Changed from 5    }
    
    global void finish(Database.BatchableContext BC){
        AsyncApexJob apexBatchResult = [
            SELECT Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email
            FROM AsyncApexJob
            WHERE Id =: BC.getJobId()
        ];
    
        // Generate email body
        String emailBody = 'Apex Batch to Update PageviewSessions processed '
            + apexBatchResult.TotalJobItems + ' batches with '+ apexBatchResult.NumberOfErrors + ' failures.\n\n'
            + 'Database errors (if any): ' + JSON.serialize(runningBatchResponse.getDatabaseErrors()) + '\n';
        
        // Extract error string from batch response
        //emailBody += runningBatchResponse.generateErrorString();

        // Send email
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(EMAIL_BATCH_RESULTS);
        mail.setSenderDisplayName('About.com Experts - Batch Results');
        mail.setSubject('About.com - Batch to Update PageviewSessions - status: ' + apexBatchResult.Status);
        mail.setPlainTextBody('Batch Process has completed\n\n' + emailBody);

        Messaging.sendEmail(new List<Messaging.SingleEmailMessage>{mail});
    }
}

 
System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, APTS_OpportunityTrigger: execution of AfterInsert

caused by: System.DmlException: Update failed. First exception on row 0 with id 006S0000009qj2DIAQ; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, OpportunityAfterEventListener: execution of AfterUpdate

caused by: System.NullPointerException: Attempt to de-reference a null object

Trigger.OpportunityAfterEventListener: line 178, column 1: []

Class.OpportunityTriggerHelper.updatePriceBook: line 23, column 1
Class.OpportunityTriggerHandler.OnAfterInsert: line 7, column 1
Trigger.OpportunityTrigger: line 5, column 1:
Hi I am running a batch job in that i am getting Too many DML rows: 10001 error .Eventhough i am spliting the batch every 10000 Records but still i am getting that error.i tried all possible ways still i am getting same error.

List<Candidate__c> Candidatelist = new List<Candidate__c>();
List<Database.Saveresult> saveList = new List<Database.Saveresult>();
 if(Candidatelist!=null && Candidatelist.size()>0){
            integer i=0;
            List<Candidate__c> Candidatelistk = new List<Candidate__c>();
            for(Candidate__c ctc: Candidatelist){
                i=i+1;
                Candidatelistk.add(ctc);
                if(i>=9999){
                    saveList.addAll(Database.insert(Candidatelistk, false));//error in this line
                    i=0;
                   Candidatelistk.clear();
                }
            }
            saveList.addAll(Database.insert(CandidatelistK, false));

Thanks in advance
      
  • April 05, 2017
  • Like
  • 0
I am not able to run tests in either of our sandboxes. I always get the error "Could not run tests on class<ID> ." I have tried clearing test history, verifying and modifying my options. Compiling all class and then estimating my orgs code coverage and running all tests. Almost every class was failing with the error. I had another admin run the test and it worked. I logged in as her and it did not work, same error. I tried on IE, Chrome, and Firefox as well as a different machine, same error. When I deployed the trigger and test to another sandbox, same error. I deployed to prod using the other admin's code coverage and ran the test in production and it worked. The trigger and unit test are not the problem.
Trying to sign in and this is the message displayed:

"We can't authorize you because of an OAuth error. For more information, contact your Salesforce administrator.
1800 : There was a problem in setting up your remote access"

Can someone please help resolve this issue so that it doesn't ever prevent me from accessing Salesforce in the future?

Thanks.
I am trying to write a trigger on my Lead Object that will not allow a user to click Convert unless a boolean field is True. I need help with some sample code to get started. 

I plan to create an Approval Process on the lead record, then with the final Approver action have a field update to have my custom checkbox (Approved) set to True. 

Once this happens I want the user to be able to click Convert, but only once the checkbox is set to true. If it has not gone through the approval process, the user shoudnt be able to click convert. 

I should also note I would only want this for a specific record type of my lead object.
So I have an issue with a flow.  When I did a test it worked but now its not and I have no idea why.  The error message makes very little sense to me but appears to be an issue with the student field?

Can anyone help me with this:
Error element myRule_1_A1 (FlowRecordCreate).
This error occurred when the flow tried to create records: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY: Meal_Transaction_AIAIAD: execution of BeforeInsert caused by: System.ListException: List index out of bounds: 0 Trigger.Meal_Transaction_AIAIAD: line 24, column 1. For details, see API Exceptions.
This report lists the elements that the flow interview executed. The report is a beta feature.
We welcome your feedback on IdeaExchange.
Flow Details
Flow Name: Payment_Meals_Update_Ver_3
Type: Workflow
Version: 1
Status: Active
Flow Interview Details
Interview Label: Payment_Meals_Update_Ver_3-1_InterviewLabel
Current User: Scott Walker (00XX000000#XXXXXXX)
Start time: 4/3/2017 4:46 PM
Duration: 0 seconds
How the Interview Started
Scott Walker (00X0000000000) started the flow interview.
Some of this flow's variables were set when the interview started.
myVariable_old = null
myVariable_current = a00000000aa0000008
ASSIGNMENT: myVariable_waitStartTimeAssignment
{!myVariable_waitStartTimeVariable} Equals {!Flow.CurrentDateTime}
Result
{!myVariable_waitStartTimeVariable} = "4/3/2017 4:46 PM"
DECISION: myDecision
Executed this outcome: myRule_1
Outcome conditions: and
1. {!myVariable_current.Payment_for__c} (Lunch Billing) Equals Lunch Billing
Logic: All conditions must be true (AND)
RECORD CREATE: myRule_1_A1
Create one Meal_Transaction__c record where:
Student__c = {!myVariable_current.Student__c} (null)
Transaction_Amount__c = {!myVariable_current.Amount_Paid__c} (1)
Transaction_Date__c = {!myVariable_current.CreatedDate} (4/3/2017 4:46 PM)
Transaction_Type__c = Credit
Result
Failed to create record.

Error Occurred: This error occurred when the flow tried to create records: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY: Meal_Transaction_AIAIAD: execution of BeforeInsert caused by: System.ListException: List index out of bounds: 0 Trigger.Meal_Transaction_AIAIAD: line 24, column 1. For details, see API Exceptions.

I have mapped the fields and I believe they are correct, as follows:

User-added image

the fields on the right are:

Student__c
Amount_Paid__c
CreatedDate


Any help really appreciated I really need to get this to work
 
I was able to do API calls with partner.wsdl.  However, i am no longer able to do so and get the following error message:

com.sforce.ws.ConnectionException: Failed to parse detail:  START_TAG seen ...</sf:exceptionMessage><sf:upgradeURL>... @1:752 due to: com.sforce.ws.ConnectionException: unable to find end tag at:  START_TAG seen ...</sf:exceptionMessage><sf:upgradeURL>... @1:752
    at com.sforce.ws.transport.SoapConnection.parseDetail(SoapConnection.java:238)
    at com.sforce.ws.transport.SoapConnection.createException(SoapConnection.java:204)
    at com.sforce.ws.transport.SoapConnection.receive(SoapConnection.java:150)
    at com.sforce.ws.transport.SoapConnection.send(SoapConnection.java:99)
    at com.sforce.soap.partner.PartnerConnection.login(PartnerConnection.java:790)
    at com.sforce.soap.partner.PartnerConnection.<init>(PartnerConnection.java:406)
    at com.sforce.soap.partner.Connector.newConnection(Connector.java:27)

According to the login history, each call was actually log in successfully.  Any suggestion to resolve the issue?  Thanks!
  • October 18, 2016
  • Like
  • 0
Unable to login  @ Dev Org. dectivate a flow assicated with login flow for system admin. unable to login  thrown error message while login " no active flow"
Hi,
I am new in salesforce. I have question about relationships. Is it possible to generate dynamically a generic link between objects? My scenario is to have a custom object with fields like object_id,object_name, field_id, field_name. I would like to build  links between my custom object and other objects.