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
Priya MishraPriya Mishra 

101 error in the apex class

Hello All,

I am having a apex class which is uploading the data to a custom object via csv file through vf page. 

I am checking a column into the csv file if it is valid only it has to insert the data but since it is coming into the for loop i am facing 101 error. please suggest me how to correct the code so that we this error can be avoid.

My code:

public class importDataFromCSVController {

public transient Blob csvFileBody{get;set;}
public string csvAsString{get;set;}
public String[] csvFileLines{get;set;}
public transient List<Call_Log__c> acclist{get;set;}
List<String> failedLines;
Public Call_Log__c Call{get;set;}
public Integer totalunsuccessrec { get; set; }
public Integer totalsuccessrec { get; set; }
public string upload_err_msg{get; set;}
List<String> rows;
public String usernamelable {get;set;}
public integer totalrecords { get; set; }
public String fileName { get; set; }

   public importDataFromCSVController(){
    upload_err_msg='';
    csvFileLines = new String[]{};
    acclist = New List<Call_Log__c>(); 
    usernamelable = apexpages.currentpage().getparameters().get('att');
  }
  
  
 /**This function checks the validations in the vf page for the csv file. **/ 
  public PageReference importCSVFile(){
  
  
   acclist= new list<Call_Log__c >();
        failedlines = new list<string>();
        rows = new list<string>();  
        
        totalrecords =0;
        totalsuccessrec = 0;
        totalunsuccessrec = 0;
        
        try
        {
       
        if(csvFileBody!=null)
        {
            fileName = csvAsString;
           // csvAsString= csvAsString.toString();
            System.debug('csvAsString'+csvAsString);
                      
          //Convert the uploaded file which is in BLOB format into a string
            csvAsString = blobToString( csvFileBody,'ISO-8859-1');
           
          //Now sepatate every row of the csv file   
            csvFileLines = csvAsString.split('\n'); 
            
        }
                
        else{

            ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.ERROR, 'Please choose a file to upload !'));
            return null;
        }

            acclist= uploadprocess();

        System.debug('aftrlist'+acclist);
            
        }
        
        Catch(Exception e)
        {     
            System.debug('e.getCause'+e.getCause());
            System.debug('e.getLinenumber'+e.getLinenumber());
            System.debug('e.getMessage'+e.getMessage());
            
            ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.Error,'The data in the file you have attempted to upload is not in the correct format and therefore did not upload successfully.'+'Cause:'+ e.getCause()+ 'Line:' +e.getLinenumber()+'  '+ 'Error Message:'+ '   ' + e.getMessage() );
            ApexPages.addMessage(errormsg);    
        }  
        
        System.debug('befsrlist'+acclist);
        Database.SaveResult[] srList ;                  
        if(acclist!=Null) {
        totalrecords = acclist.size(); 
        srList   = Database.insert(acclist, false);
        
        System.debug('srList'+srList);
        }
        
        if(srList!=Null){
        for(Database.SaveResult sr: srList)
        {
            if(!sr.IsSuccess())
            {    
                for(Database.Error err : sr.getErrors())
                {
                     ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.Error,'An error has occured while importing data Please make sure input csv file is correct.');
                     ApexPages.addMessage(errorMessage);      
                }
            }
        }           
       } 
        return null;  
    }
   
   
   
 /**This function reads the CSV file and inserts records into the calllog object. **/     
     public list<Call_Log__c > uploadprocess()
    {
    
     Integer counter = 1; 
        
    
              for(Integer i=1;i<csvFileLines.size();i++){
           
              Call_Log__c accObj = new Call_Log__c() ;
               
               accObj.Is_Bulk_Follow_up_Upload__c=true;
               accObj.Uploaded_By__c = usernamelable;
               accObj.Status__c='New';
               
               accObj.recordtypeid=label.Followuprecordtyopype;
               string[] csvRecordData = csvFileLines[i].split(',');
               
               
           //Mapping the Csv header with the fields.     
           
         //   List<Login__c> loginlist=[select Id,UserName__c from Login__c where UserName__c=:csvRecordData[23]];
           
          //  System.debug('Records on List are '+loginlist);
               
         //  if(loginlist.size()>0)
           
         //  {
               
               accObj.UserNameNew__c=csvRecordData[0];
               accObj.BusinessName__c=csvRecordData[1];
               accObj.EIN__c= csvRecordData[2];
               accObj.Phone_number__c= csvRecordData[3];
               accObj.CellPhone__c= csvRecordData[4];
               accObj.SA_Name__c= csvRecordData[5];
               accObj.First_Name__c= csvRecordData[6] ; 
               accObj.Last_Name__c= csvRecordData[7];  
               accObj.Email__c= csvRecordData[8];        
               accObj.Return_ID__c=csvRecordData[9];
               accObj.SKU__c=csvRecordData[10];
               accObj.Form_Type__c=csvRecordData[11];
               Datetime myDateTime = DateTime.valueof(csvRecordData[12]);
               String dtConverted = myDateTime.format('yyyy-MM-dd hh:mm:ss');
               accObj.Paid_Date__c= Datetime.valueof(dtConverted);
               accObj.Paid_Amount__c=csvRecordData[13];      
               Datetime myDateTim = DateTime.valueof(csvRecordData[14]);
               String dtConverte = myDateTim.format('yyyy-MM-dd hh:mm:ss');
               accObj.Registered_Date__c= Datetime.valueof(dtConverte);    
               accObj.Address__c=csvRecordData[15];
               accObj.City__c= csvRecordData[16]; 
               accObj.State__c = csvRecordData[17];
               accObj.Zip__c= csvRecordData[18];
               accObj.Country__c= csvRecordData[19];
               accObj.Time_Zone__c=(csvRecordData[20]);
               accObj.Others__c= csvRecordData[21];
               accObj.followup_type__c=csvRecordData[22];
                accObj.Assign__c= csvRecordData[23];
              
             
                                                                                       
               acclist.add(accObj);
               
              //}
               
               
               //else {
               // accObj.addError('Usename is not available Please provide the Correct Username');
               
              // }
             totalsuccessrec++;
              totalunsuccessrec++;
             
           }
            

            //Finally, insert the collected records
          //Database.insert(acclist,false);
          
             insert acclist;
             
                
       counter++; 
     System.debug('this has ' + acclist.size() + ' records total.');
     
     return null;
    
      } 
      
   
  
   /**
         This function convers the input CSV file in BLOB format into a string
        @param input    Blob data representing correct string in @inCharset encoding
        @param inCharset    encoding of the Blob data (for example 'ISO 8859-1')
     */
  
  public static String blobToString(Blob input, String inCharset){
        String hex = EncodingUtil.convertToHex(input);
        System.assertEquals(0, hex.length() & 1);
        final Integer bytesCount = hex.length() >> 1;
        String[] bytes = new String[bytesCount];
        for(Integer i = 0; i < bytesCount; ++i)
        bytes[i] =  hex.mid(i << 1, 2);
        return EncodingUtil.urlDecode('%' + String.join(bytes, '%'), inCharset);
    }
 
 
 
   public PageReference getViewrequest() 
    {
        pagereference ref4 = new pagereference('/apex/View_Request_Admin?att='+usernamelable);
        return ref4;
    }


    public String getFollowups() {
        return null;
    }


    public PageReference getReport() 
    {
     pagereference ref= new pagereference('/apex/TaxReport?att='+usernamelable ); 
     return ref;
        
    }


    public PageReference getCalllog() 
    {
         pagereference ref1= new pagereference('/apex/CallDetailsDashboard?att='+usernamelable);
        return ref1;
    }


    public PageReference getAddmembaer() 
    {
        pagereference ref3= new pagereference('/apex/Add_Member_Page?att='+usernamelable);
        return ref3;
    }


    public PageReference getProfile() 
    {
        pagereference ref2= new pagereference('/apex/Tax_Admin_Profile?att='+usernamelable);
        return ref2; 
    }

    public PageReference getUsers() 
    {
        pagereference ref5= new pagereference('/apex/Tax_View_Users_Admin?att='+usernamelable);
        return ref5; 
    }
    
    public PageReference getTicket() 
    {
         pagereference ref6= new pagereference('/apex/Tickets_Tax_Admin?att='+usernamelable);
        return ref6; 
    }

}User-added imagesee the image where i am facing the problem. this is the below code where i ma facing.


 //   List<Login__c> loginlist=[select Id,UserName__c from Login__c where UserName__c=:csvRecordData[23]];
           
          //  System.debug('Records on List are '+loginlist);
               
         //  if(loginlist.size()>0)
           


 
ShirishaShirisha (Salesforce Developers) 
Hi Mishra,

Greetings!

I would suggest you to capture the debug logs while executing the class since the SOQL query is not inside the for loop.Once,you capture the debug logs then it will be easier to debug the code.

Kindly mark it as best answer if it helps so that it can help others in the future.

Warm Regards,
Shirisha Pathuri