function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
krishn chaithanyakrishn chaithanya 

Salesforce chckmarx issue : How to resolve Bulkify apex methods using collections in methods?

I am working on an app which we plan to publish on app exchange. As per pre-requisite requirement by salesforce, any app before getting listed on app exchange should go through code review from checkmarx.we submitted our code base to checkmarx and get one of warning reported by checkmarx. The error says "Bulkify Apex Methods - Using Collections in methods".
I'm getting checkmarx warning below line:
public void sendEmail(Purchase_order__c orders,Attachment attachment){

Here i'l update my Class:
public with sharing class PurchaseorderContrllor {
    private ApexPages.StandardController sc;
    public String projectid{get;set;}
    public String subprojectid{get;set;}
    public String purchaseordersId{get;set;}
    public String markID{get;set;}
    public string contenttype{get;set;}
    public decimal a1{get;set;}
    public string a2{get;set;}
    public string a3{get;set;} 
    public musqot__Purchase_order_setting__c pos{get;set;}
    public integer i; 
    public List<Purchase_article__c> PA_Temp = new List<Purchase_article__c>();
    public Purchase_order__c orders{get;set;}
    public Static Boolean notWildInvoicePurchOrdr;
    public PurchaseorderContrllor (ApexPages.StandardController controller) {
        This.sc = sc; 

        projectid = ApexPages.currentPage().getParameters().get('planid');   
        subprojectid= ApexPages.currentPage().getParameters().get('prjId'); 
        markID=ApexPages.currentPage().getParameters().get('markID');  
        orders= new Purchase_order__c ();
        orders.Project__c= projectid;  
        orders.subproject__c= subprojectid;
        orders.Marketing_activity__c=markID;          
    }
    
    public List<SelectOption> PAList
    {
        get
        {
            PA_Temp = [Select u.Name, u.Id From Purchase_article__c u order by u.Name limit 250];
            PAList = new List<SelectOption>(); 
            for(Purchase_article__c temp : PA_Temp)
            {
                PAList.add(new SelectOption(temp.Id, temp.Name));
            }
            return PAList;
        }
        set;
    }
    
    public Pagereference insertOrders(){
        integer i;
        try{
            if (Purchase_order__c.sObjectType.getDescribe().isCreateable())
            {
                notWildInvoicePurchOrdr = true;
                pos=[select id,PO_Startnumber__c,musqot__PO_Lastnumber__c ,musqot__PO_Prefix__c from musqot__Purchase_order_setting__c limit 250];
                if (pos.musqot__PO_Prefix__c!=null){                
                a1=pos.musqot__PO_Lastnumber__c+1;
                a2=pos.musqot__PO_Prefix__c;      
                a3=a2 +''+''+''+a1;
                orders.musqot__Purchase_order_name__c=a3;      
                  }        
                else{
                a1=pos.musqot__PO_Lastnumber__c+1;
                a2 =''+a1;
                orders.musqot__Purchase_order_name__c = a2;
                }
                               
                insert orders;
                
                i=[select count() from musqot__Purchase_order__c limit 250];
                if(i==i++){
                    pos=[select id,PO_Startnumber__c,musqot__PO_Lastnumber__c ,musqot__PO_Prefix__c from musqot__Purchase_order_setting__c limit 250];
                    pos.musqot__PO_Lastnumber__c=a1 ;
                    
                    update pos;
                }
                
            }           
            //Attachment Code
            User u = [select Id from user where id=:userinfo.getuserid()];
            
            attachment.OwnerId = u.Id;
            attachment.ParentId = orders.Id; // the record the file is attached to
            //attachment.OwnerId = u.id;
            attachment.ContentType=contentType;
            if(attachment.body<>null){
                if (Schema.sObjectType.Attachment.fields.body.isCreateable()){
                
                    attachment.Name = orders.Purchase_order_name__c;
                    //attachment.Body=null;
                    insert attachment;                     
                }                  
            }
            sendEmail(orders,attachment);
           
            Pagereference PR;
            if(subprojectid<>null){  
                String tabId = System.currentPageReference().getParameters().get('tabId');
                string pageRef='/apex/SubProject?id='+EncodingUtil.urlEncode(subprojectid,'UTF-8')+'&tab='+EncodingUtil.urlEncode('purchase','UTF-8');
                pr=new Pagereference (pageRef);              
                // PR = new Pagereference('/apex/SubProject?id='+EncodingUtil.urlEncode(subprojectid,'UTF-8'));
            }
            else if(projectid<>null)
            {
                String tabId = System.currentPageReference().getParameters().get('tabId');
                string pageRef='/apex/ProjectDetails?id='+EncodingUtil.urlEncode(projectid,'UTF-8')+'&tab='+EncodingUtil.urlEncode('purchase','UTF-8');
                pr=new Pagereference (pageRef);
                //PR = new Pagereference('/apex/ProjectDetails?id='+EncodingUtil.urlEncode(projectid,'UTF-8'));
            }
            else if(markID<>null)
            {
                String tabId = System.currentPageReference().getParameters().get('tabId');
                string pageRef='/apex/Marketingactivity?id='+EncodingUtil.urlEncode(markID,'UTF-8')+'&tab='+EncodingUtil.urlEncode('purchase','UTF-8');
                pr=new Pagereference (pageRef);
                // PR = new Pagereference('/apex/Marketingactivity?id='+EncodingUtil.urlEncode(markID,'UTF-8'));
            }
            return PR;
        }
        catch(Exception e){
            return null;
        }
    }
   public Attachment attachment {
        get {
            if (attachment == null)
                attachment = new Attachment();
            return attachment;
        }
        set;
    }
    Public Pagereference cancel(){
        
        Pagereference PR;
           if(projectid<>null)
        {
            String tabId = System.currentPageReference().getParameters().get('tabId');
            string pageRef='/apex/ProjectDetails?id='+EncodingUtil.urlEncode(projectid,'UTF-8')+'&tab='+EncodingUtil.urlEncode('purchase','UTF-8');
            pr=new Pagereference (pageRef);
            // PR = new Pagereference('/apex/ProjectDetails?id='+EncodingUtil.urlEncode(projectid,'UTF-8'));
        }
        
      else  if(subprojectid<>null)
        {
            String tabId = System.currentPageReference().getParameters().get('tabId');
            string pageRef='/apex/SubProject?id='+EncodingUtil.urlEncode(subprojectid,'UTF-8')+'&tab='+EncodingUtil.urlEncode('purchase','UTF-8');
            pr=new Pagereference (pageRef);
            //PR = new Pagereference('/apex/SubProject?id='+EncodingUtil.urlEncode(subprojectid,'UTF-8'));
        }
       
        else if(markID<>null)
        {
            String tabId = System.currentPageReference().getParameters().get('tabId');
            string pageRef='/apex/Marketingactivity?id='+EncodingUtil.urlEncode(markID,'UTF-8')+'&tab='+EncodingUtil.urlEncode('purchase','UTF-8');
            pr=new Pagereference (pageRef);
            //PR = new Pagereference('/apex/Marketingactivity?id='+EncodingUtil.urlEncode(markID,'UTF-8'));
        }
        
        return PR;
    }       
    public String getRedirectToTemplate() {
        return null;
    }
    public Purchase_order__c  templateInfo {get; set;}
    public Pagereference redirectToTemplate() {
        try{
            insert templateInfo;
        }catch(Exception e){
            ApexPages.addMessages(e);
        }
        return null;
    }    
    public void sendEmail(Purchase_order__c orders,Attachment attachment){
        if(orders.Send_date__c ==System.today() && orders.musqot__Supplier_email__c != null && orders.musqot__Supplier_email__c != ''){ 
            Purchase_order__c  purchOrdr = [SELECT Id,musqot__Purchase_order_name__c,Name,musqot__Total_cost__c,musqot__Description__c, OwnerId FROM Purchase_order__c WHERE Id = :orders.Id];
            EmailTemplate template = [SELECT Id, name,Subject, HtmlValue, Body FROM EmailTemplate WHERE name= 'Purchaseorder'];
            //Contact cnt = [select id from Contact where email != null limit 1];
            Contact cnt = new Contact();
            cnt.LastName = 'Supplier';
            cnt.Email = orders.musqot__Supplier_email__c;
            insert cnt;
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.setWhatId(purchOrdr.Id);
            mail.setTargetObjectId(cnt.Id);
            mail.setTemplateId(template.Id);
            mail.saveAsActivity = false;
          
              if(attachment.body<>null){
                //Set email file attachments
                List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
                // Add to attachment file list
                Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
                efa.setFileName(attachment.Name);
                efa.setBody(attachment.Body);
                efa.setContentType(attachment.ContentType);
                fileAttachments.add(efa);
                mail.setFileAttachments(fileAttachments);
            }
            //Send email
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); 
            delete cnt;           
        }       
     }
 }



In the class i didn't use any where soql query's and DML statemets inside for loops, but still i'l get bulkify apex methods warning from this line...
public void sendEmail(Purchase_order__c orders,Attachment attachment){............
I have updated my controller, can u pls tell me from where i did wrong in my code??????
 
Best Answer chosen by krishn chaithanya
Himanshu ParasharHimanshu Parashar
Hi Krishn,

I think that you are getting this error because you are calling your Email sending method single time you need to bulkify that. Please find inline comments what I have changed in your sendEmail method.
public void sendEmail(Purchase_order__c orders,Attachment attachment){

List<Messaging.SingleEmailMessage> SendEmails = new List<Messaging.SingleEmailMessage>(); //Added by Himanshu
        
if(orders.Send_date__c ==System.today() && orders.musqot__Supplier_email__c != null && orders.musqot__Supplier_email__c != ''){ 
            Purchase_order__c  purchOrdr = [SELECT Id,musqot__Purchase_order_name__c,Name,musqot__Total_cost__c,musqot__Description__c, OwnerId FROM Purchase_order__c WHERE Id = :orders.Id];
            EmailTemplate template = [SELECT Id, name,Subject, HtmlValue, Body FROM EmailTemplate WHERE name= 'Purchaseorder'];
            //Contact cnt = [select id from Contact where email != null limit 1];
            Contact cnt = new Contact();
            cnt.LastName = 'Supplier';
            cnt.Email = orders.musqot__Supplier_email__c;
            insert cnt;
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.setWhatId(purchOrdr.Id);
            mail.setTargetObjectId(cnt.Id);
            mail.setTemplateId(template.Id);
            mail.saveAsActivity = false;
          
              if(attachment.body<>null){
                //Set email file attachments
                List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
                // Add to attachment file list
                Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
                efa.setFileName(attachment.Name);
                efa.setBody(attachment.Body);
                efa.setContentType(attachment.ContentType);
                fileAttachments.add(efa);
                mail.setFileAttachments(fileAttachments);
            }
            //Send email
            SendEmails.add(mail);  // Added by Himanshu
            Messaging.sendEmail(SendEmails); // Added by Himanshu

            delete cnt;           
        }  
     
     }

Let me know if that works.


Thanks,
Himanshu
Salesforce Certified Developer | Administrator | Service Cloud Consultant

P.S. If my answer helps you to solve your problem please mark it as best answer. It will help others to find best answer.
 

All Answers

Himanshu ParasharHimanshu Parashar
Hi Krishn,

I think that you are getting this error because you are calling your Email sending method single time you need to bulkify that. Please find inline comments what I have changed in your sendEmail method.
public void sendEmail(Purchase_order__c orders,Attachment attachment){

List<Messaging.SingleEmailMessage> SendEmails = new List<Messaging.SingleEmailMessage>(); //Added by Himanshu
        
if(orders.Send_date__c ==System.today() && orders.musqot__Supplier_email__c != null && orders.musqot__Supplier_email__c != ''){ 
            Purchase_order__c  purchOrdr = [SELECT Id,musqot__Purchase_order_name__c,Name,musqot__Total_cost__c,musqot__Description__c, OwnerId FROM Purchase_order__c WHERE Id = :orders.Id];
            EmailTemplate template = [SELECT Id, name,Subject, HtmlValue, Body FROM EmailTemplate WHERE name= 'Purchaseorder'];
            //Contact cnt = [select id from Contact where email != null limit 1];
            Contact cnt = new Contact();
            cnt.LastName = 'Supplier';
            cnt.Email = orders.musqot__Supplier_email__c;
            insert cnt;
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.setWhatId(purchOrdr.Id);
            mail.setTargetObjectId(cnt.Id);
            mail.setTemplateId(template.Id);
            mail.saveAsActivity = false;
          
              if(attachment.body<>null){
                //Set email file attachments
                List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
                // Add to attachment file list
                Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
                efa.setFileName(attachment.Name);
                efa.setBody(attachment.Body);
                efa.setContentType(attachment.ContentType);
                fileAttachments.add(efa);
                mail.setFileAttachments(fileAttachments);
            }
            //Send email
            SendEmails.add(mail);  // Added by Himanshu
            Messaging.sendEmail(SendEmails); // Added by Himanshu

            delete cnt;           
        }  
     
     }

Let me know if that works.


Thanks,
Himanshu
Salesforce Certified Developer | Administrator | Service Cloud Consultant

P.S. If my answer helps you to solve your problem please mark it as best answer. It will help others to find best answer.
 
This was selected as the best answer
krishn chaithanyakrishn chaithanya
Hi,
    Thanks for replying to my post...
    I have added your changed code, at this time mail will sent to supplier with attachments successfully.i have run checkmarx scan, based on report we have to know if it's fixed or still reproduced???
Himanshu ParasharHimanshu Parashar
yes. you need to. 
krishn chaithanyakrishn chaithanya
Thanks, it's working...
              we have run new scan at this time we didn't find any warnings....