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
nasknask 

automation of text file genration

HI I have two VF page and corresponding to them i have 2 controllers.

 

In first page i invoke a method on page load where it gets text version vf page2 and sends it in a form of attachement.

 

i have used VF page because to create a specific format.

 

So i get a get text attached email every time i load my first VF page but when i try to automate it by using a  batch class its sending the mail with text attachment but with  incorrect data.  Any idea how can this achieved.

 

We need to automate this sending of mail from salesforce.

 

this file contains data from two different objects and for more than one record.

 

IspitaIspita

Hi nask,

The reason why your data is getting corrupt can be pinpointed if you could share the code snippet causing the issue.

On a high level it seems that as your are automating for mass email generation probably some mismatch is happening at that point.  Still a more appropriate analysis and cause correction can be only if one looks at the code which is causing the error .

It may turn out that the issue is not with scheduling  or bulkification but the issue may be minir w.r.t. code structuring.

 

Do let me know about these...

nasknask

Hi Ispita,

First of all thanks for your reply. My data is not corrupted its not coming at all. PLease try to have a look at my different codes:

********************1st VF Page**************************

<apex:page controller="sendMailTest" action="{!sendMail}" sidebar="false">
<apex:pageMessage detail="Consumable orders have been mailed to Callidus team for today" severity="info" title="Orders Placed" rendered="{!!flag}"></apex:pageMessage>
<apex:pageMessage detail="All orders have been placed. There are no more Orders to be processed" severity="info" title="NO More Orders" rendered="{!flag}"></apex:pageMessage>
</apex:page>

 

************* 1st Controller******************************

public class sendMailTest {
public boolean flag{get;set;}
public PageReference sendMail()
    {
        PageReference  p = Page.testSpaces;
        
        Blob b = p.getContent();
       
        // Define the email
        if(b.tostring() !='')
        {
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();         
        
        // Create the email attachment
    
        Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
        string fileName = 'BGSO_'+system.now().format()+'.text';
        efa.setFileName(fileName);
        efa.setBody(b);        

        String[] toAddresses = new String[]{'ashokkumar.nagaleekar@centrica.com'};
        String subject = 'Callidus Order for '+System.now();
        email.setSubject( subject );
        email.setToAddresses( toAddresses );
        email.setPlainTextBody('PFA for Consumbale Request');
        
        email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});

            // Sends the email
    
        Messaging.SendEmailResult [] r =
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});   
        }else
        {
                flag= true;     
        }    

        return null;
    }

}

************** 2nd VF Page*************************************************

 

<apex:page controller="consumbleRequestTextFileGenerator" contentType="text/plain" standardStylesheets="false" showHeader="false" action="{!updateConsumables}">
    <apex:repeat value="{!testname}" var="v">
        <apex:repeat value="{!v}" var="i">
            <apex:outputText value="{!i}"/>
        </apex:repeat>    
    </apex:repeat>
</apex:page>

 

 contd...........................

nasknask

**************************************2nd Vf Controller********************

public with sharing class consumbleRequestTextFileGenerator {
   public list<list<string>> testname{get;set;}
   public String leftpad(String source, integer maxlength) {
        if(source==null) return null;
        if(source.length()>maxlength) return source;
        return '                                                                                ' .substring(0,maxlength-source.length()) + source;
    }

    public String rightpad(String source, integer maxlength) {
        if(source==null) return null;
        if(source.length()>maxlength) return source;
        return source + '                                                                                                    ' .substring(0,maxlength-source.length());
    }
    public string createHeaderString(Consumables_Requests__c cReq)
    {
        boolean error = false;
        string headerSting;
        if(cReq.Employee_ID__c!=null)
        {
            string payrollNum = string.valueof(cReq.Employee_ID__c);
            payrollNum = padChar(payrollNum,7,'0',true);
            headerSting = payrollNum;
        }else
        {
            return null;
        }
        
        if(cReq.Name!=null)
        {
            string orderId = string.valueof(cReq.Name);
            orderId = rightpad(orderId,15);
            headerSting = headerSting+orderId;  
        }else
        {
            headerSting = headerSting+rightpad('',15);
        }
        
        string orderType = 'OTG';
        headerSting = headerSting+orderType;
        
        Date deliveryDt = system.today()+1;
        string dateString;
        dateString = deliveryDt.format().substring(6,10)+deliveryDt.format().substring(3,5)+deliveryDt.format().substring(0,2);
        headerSting =headerSting+dateString;
        
        if(cReq.Callidus_Patch_Id__c!=null)
        {
            string patchId = string.valueof(cReq.Callidus_Patch_Id__c);
            patchId = rightpad(patchId,5);
            headerSting = headerSting+patchId;  
        }else
        {
            headerSting = null;
            return null;
        }
        
        string marketCode = 'BGAS';
        headerSting =headerSting+marketCode;
        
        string productType = '0000';
        headerSting = headerSting+productType;
        
        string empDetails = '';
        empDetails = leftpad(empDetails,80);
        headerSting = headerSting+empDetails + leftpad('',80)+leftpad('',20);
        
        return headerSting;
    }
    public string createChildString(string headerSting, Consumable_Items__c cItem, integer itemNumber)
    {
        string childString;
        if(itemNumber!=null)
        {
            string itemString = string.valueof(itemNumber);
            itemString = padChar(itemString,4,'0',true);
            headerSting = headerSting+itemString;   
        }else
        {
            headerSting = headerSting + padChar('0',4,'0',true);
        }
        if(cItem.Product_Code__c!=null)
        {
            string productCode = string.valueof(cItem.Product_Code__c);
            productCode = rightpad(productCode,6);
            headerSting = headerSting+productCode;  
        }else
        {
            return null;
        }
        if(cItem.Quantity__c!=null)
        {
            string quantity = string.valueof(cItem.Quantity__c);
            quantity = padChar(quantity,6,'0',true);
            headerSting = headerSting+quantity;
        }else
        {
            headerSting = headerSting + padChar('0',6,'0',true);
        }
        
        headerSting = headerSting+ '000';
        
        return headerSting;
    }
    private string padChar(string word, integer length, string charcter, boolean direction )
    {
        integer diff =  length - word.length();
                
        if(diff>0 && direction == true)
        {
            for(integer i=0;i< diff ;i++)
            {
                word = charcter+word;
            }
            return word;
        }else if(diff>0 && direction == false)
        {
            for(integer i=0;i< diff ;i++)
            {
                word = word+charcter;
            }
            return word;
        }else if(diff<0)
        {
            return word.substring(0,length);
        }else{
            return word;
        }
        
    }
    public void  updateConsumables()
    {
        String[] str = new String[]{};
        list<list<string>> stringLst = new list<list<string>>();
        string body ;
        list<Id>temp = new list<Id>();
       // temp.add('a1020000000bmZy');
        //temp.add('a10P0000000E2CN');
        Date CreatedDate = date.newinstance(2011, 11, 1);    
        list<Consumables_Requests__c> conReqLst = new list<Consumables_Requests__c>();
        conReqLst = [Select c.Id,c.Raised_By__c,Name, Employee_ID__c,Picked_Up_by_Email__c,c.Item_Count__c, c.Employee__c, c.Delivery_Date__c, c.Callidus_Patch_Id__c, c.ApprovedTick__c, (Select Id, Product_Code__c, Quantity__c From Consumable_Items__r) From Consumables_Requests__c c where Picked_Up_by_Email__c = false and CreatedDate >=:CreatedDate and Status__c = 'Submitted' and (Approval_Required__c= 'No' OR (Approval_Required__c= 'Yes' and Approved__c = true))limit 595 ];// where id in :temp];
        //conReqLst = [Select c.Id,c.Raised_By__c, Employee_ID__c,c.Item_Count__c, c.Employee__c, c.Delivery_Date__c, c.Callidus_Patch_Id__c, c.ApprovedTick__c, (Select Id, Product_Code__c, Quantity__c From Consumable_Items__r) From Consumables_Requests__c c limit 100];
        list<Consumables_Requests__c> conReqToUpdate = new list<Consumables_Requests__c>();
        for(Integer i=0;i<conReqLst.size();i++)
        {
            string headerSting = createHeaderString(conReqLst[i]);
            if(headerSting!= null)
            {
            
                list<Consumable_Items__c> cItems = conReqLst[i].Consumable_Items__r;
                integer j = 1;
                for(Consumable_Items__c c: cItems)
                    {
                        string sinlgleLineItem;
                        if(sinlgleLineItem!=null)
                        {
                            sinlgleLineItem = sinlgleLineItem +createChildString(headerSting,c,j);
                        }
                        else
                        {
                            sinlgleLineItem = createChildString(headerSting,c,j);
                        }
                        if(sinlgleLineItem!=null)
                        {
                            if(str.size()>999)
                            {
                                    stringLst.add(str);
                                    str = new String[]{};
                                    
                            }
                            str.add(sinlgleLineItem +'\n');
                        }
                        j++;
                       
                    }
                     conReqLst[i].Picked_Up_by_Email__c = true;
                     conReqToUpdate.add(conReqLst[i]);
                
              }     
               
        }
        if(conReqToUpdate.size()>0)
        {
            try{
                update conReqToUpdate;
            }catch(Exception e)
            {
                system.debug('Exception occurred in Generating to Text Attachment for Consumable Request'+e);
            }
        }
        testname = new list<list<string>>();
        stringLst.add(str);   
        testname.addall(stringLst);
        system.debug('----->'+str.size());
        system.debug('----->'+stringLst.size());   
        
        
    }
}

 

nasknask

******************* Please see my Batch class******************************************

global class sendConsumableRequests implements Database.Batchable<sObject> {
    
    public void createConReqBatch()
    {
        sendConsumableRequests objConReq = new sendConsumableRequests();
        ID batchprocessid = Database.executeBatch(objConReq);
    }
    Date yesterda = system.today()-1;
    
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
         return Database.getQueryLocator('Select c.Id,c.Raised_By__c, Employee_ID__c,c.Item_Count__c, c.Employee__c, c.Delivery_Date__c, c.Callidus_Patch_Id__c, c.ApprovedTick__c, (Select Id, Product_Code__c, Quantity__c From Consumable_Items__r) From Consumables_Requests__c c where id = \'a10P0000000E2CN\'');
    }
    
    
    global void execute(Database.BatchableContext BC, List<sObject> consumablerequest)
    {
        sendMailTest s = new sendMailTest();
        s.sendMail();
            
    }
        global void finish(Database.BatchableContext bc){
        
       
    }

}
***********************************************************************************************************************

Could you please have a look and tell me now.

When i try to load VF page 1 it does send put text attachemnt in correct format some thing like this:

 

0019547ICR019339              OTG20111124CHI76BGAS0000                                                           0001W15110000001000

 

 

but when i tried to run the batch it end up some HTML tags and W3School tags.

nasknask

Just to make clear , this is not all about mass email generation. Its all about Text file creation with correct format. Now i am able to achieve this using the two Vf pages.

Now i need to automate this process sending this mail everyday ata a particular time.

Just to add to this this text file conatains data from two different object from different records.