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

  • Chatter
    Feed
  • 92
    Best Answers
  • 0
    Likes Received
  • 2
    Likes Given
  • 1
    Questions
  • 564
    Replies
global class CsvFileExporter implements System.Schedulable {
   global void execute(SchedulableContext sc) {
List<Account> accList = [Select Id,Name, AccountNumber, Industry, CreatedDate,LastModifiedDate,Phone from Account where CreatedDate=TODAY];
       List<Account> latestModiaccList = [Select Id,Name, AccountNumber, Industry, CreatedDate,LastModifiedDate,Phone from Account where LastModifiedDate=TODAY AND CreatedDate !=TODAY];

       String header = '\bAccounts inserted Today\b\r\n'+ '\bId, Name, Account Number, Industry,Phone\b\r\n';
       String header1 ='\r\n\bAccounts Modified Today\b\r\n'+ '\bId, Name, Account Number, Industry,Phone\b\r\n';
String generatedCSVFile = header+'';
List<String> queryFields = new List<String>{'Id','Name','AccountNumber','Industry','Phone'};
       String fileRow = '';
for(Account a: accList){            
fileRow = '';
fileRow = fileRow +','+ a.Id;
fileRow = fileRow +','+ a.Name;
       fileRow = fileRow +','+ a.AccountNumber;
fileRow = fileRow +','+ a.Industry;
       fileRow = fileRow +','+ a.Phone;
fileRow = fileRow.replaceFirst(',','');
generatedCSVFile = generatedCSVFile + fileRow + '\n';
}
       generatedCSVFile = generatedCSVFile+header1+'';
       for(Account ac: latestModiaccList){
fileRow = fileRow +','+ ac.Id;
fileRow = fileRow +','+ ac.Name;
        fileRow = fileRow +','+ ac.AccountNumber;
fileRow = fileRow +','+ ac.Industry;
        fileRow = fileRow +','+ ac.Phone;
           fileRow = fileRow.replaceFirst(',','');
           generatedCSVFile = generatedCSVFile + fileRow + '\n';
       }
       system.debug('File:'+generatedCSVFile);
Messaging.EmailFileAttachment csvAttachment = new Messaging.EmailFileAttachment();
Blob csvBlob = blob.valueOf(generatedCSVFile);
String csvName = 'Accounts data inserted and modified Today.csv';
csvAttachment.setFileName(csvName);
csvAttachment.setBody(csvBlob);
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[]{'ranga.vangalapudi@gmail.com'};
String subject = 'Accounts data inserted and modified Today';
email.setSubject(subject);
email.setToAddresses(toAddresses);
I want to use 2 constructors within my Controller class, one for a VF component and another for VF page.is it possible to have the same SOQL within 2 constructors.Please give an example
Hello, I've just started to learn about Apex and I'm having difficulty writing a test class for the following Apex class. 

The following Apex class has code to retrieve Account records and logic to iterate over a list of Account records and update the Description field.  I learned this Apex class through Trailhead and wanted to write a test class for it but couldn't figure out how.
public class OlderAccountsUtility {
    public static void updateOlderAccounts() {
      // Get the 5 oldest accounts
      Account[] oldAccounts = [SELECT Id, Description FROM Account ORDER BY CreatedDate ASC LIMIT 5];
      // loop through them and update the Description field
      for (Account acct : oldAccounts) {
          acct.Description = 'Heritage Account';
      }
      // save the change you made
      update oldAccounts;
    }
}
This is what I have written.  Can anyone show me how to fix this Apex test unit so it works?  Any help would be much appreciated!
@isTest
private class OlderAccountsUtilityTest {
    
    @isTest static void createAccount() {
    
    List <Account> accts = new List<Account>();
      for(integer i = 0; i<200; i++) {
         Account a = new Account(Name='testAccount'+'i');
         accts.add(a);
    }
        
   	insert accts;

    Test.StartTest();	
        
        List<Account> accList = [SELECT Id, Description FROM Account ORDER BY CreatedDate ASC LIMIT 5];
     
 		for (Account acct : accList) {
        acct.Description = 'Heritage Account';
        }

    Test.StopTest();

	System.AssertEquals(
    
    	database.countquery('SELECT COUNT() FROM Account WHERE Description' = 'Heritage Account'), 5);
             
    }
}

 
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?
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
 
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
global class CsvFileExporter implements System.Schedulable {
   global void execute(SchedulableContext sc) {
List<Account> accList = [Select Id,Name, AccountNumber, Industry, CreatedDate,LastModifiedDate,Phone from Account where CreatedDate=TODAY];
       List<Account> latestModiaccList = [Select Id,Name, AccountNumber, Industry, CreatedDate,LastModifiedDate,Phone from Account where LastModifiedDate=TODAY AND CreatedDate !=TODAY];

       String header = '\bAccounts inserted Today\b\r\n'+ '\bId, Name, Account Number, Industry,Phone\b\r\n';
       String header1 ='\r\n\bAccounts Modified Today\b\r\n'+ '\bId, Name, Account Number, Industry,Phone\b\r\n';
String generatedCSVFile = header+'';
List<String> queryFields = new List<String>{'Id','Name','AccountNumber','Industry','Phone'};
       String fileRow = '';
for(Account a: accList){            
fileRow = '';
fileRow = fileRow +','+ a.Id;
fileRow = fileRow +','+ a.Name;
       fileRow = fileRow +','+ a.AccountNumber;
fileRow = fileRow +','+ a.Industry;
       fileRow = fileRow +','+ a.Phone;
fileRow = fileRow.replaceFirst(',','');
generatedCSVFile = generatedCSVFile + fileRow + '\n';
}
       generatedCSVFile = generatedCSVFile+header1+'';
       for(Account ac: latestModiaccList){
fileRow = fileRow +','+ ac.Id;
fileRow = fileRow +','+ ac.Name;
        fileRow = fileRow +','+ ac.AccountNumber;
fileRow = fileRow +','+ ac.Industry;
        fileRow = fileRow +','+ ac.Phone;
           fileRow = fileRow.replaceFirst(',','');
           generatedCSVFile = generatedCSVFile + fileRow + '\n';
       }
       system.debug('File:'+generatedCSVFile);
Messaging.EmailFileAttachment csvAttachment = new Messaging.EmailFileAttachment();
Blob csvBlob = blob.valueOf(generatedCSVFile);
String csvName = 'Accounts data inserted and modified Today.csv';
csvAttachment.setFileName(csvName);
csvAttachment.setBody(csvBlob);
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[]{'ranga.vangalapudi@gmail.com'};
String subject = 'Accounts data inserted and modified Today';
email.setSubject(subject);
email.setToAddresses(toAddresses);
We have a community and its having public access. we are trying to make the this site content as google searchable.  I have tried all the ways to verify the site by Google Console 
1. Using Meta data Tag
2. DNS 
3. HTML file 
4. Writing new VF page for Heager as 
<apex:page applyHtmlTag="false" applyBodyTag="false" showHeader="false">
<html>
<head> <meta name="google-site-verification" content="6gVRigIo4j09qSdIjONNEogH1YCIxxxfFITHPbZWnqM" />
<title> My title </title>
</head>
 </html>
</apex:page>

But still Im not able to verify my site in google web master tool.
Can any one help me to get my site verified by Google.
Appriciate your help.

Thanks
Nagesh
I want to use 2 constructors within my Controller class, one for a VF component and another for VF page.is it possible to have the same SOQL within 2 constructors.Please give an example
Hello, I've just started to learn about Apex and I'm having difficulty writing a test class for the following Apex class. 

The following Apex class has code to retrieve Account records and logic to iterate over a list of Account records and update the Description field.  I learned this Apex class through Trailhead and wanted to write a test class for it but couldn't figure out how.
public class OlderAccountsUtility {
    public static void updateOlderAccounts() {
      // Get the 5 oldest accounts
      Account[] oldAccounts = [SELECT Id, Description FROM Account ORDER BY CreatedDate ASC LIMIT 5];
      // loop through them and update the Description field
      for (Account acct : oldAccounts) {
          acct.Description = 'Heritage Account';
      }
      // save the change you made
      update oldAccounts;
    }
}
This is what I have written.  Can anyone show me how to fix this Apex test unit so it works?  Any help would be much appreciated!
@isTest
private class OlderAccountsUtilityTest {
    
    @isTest static void createAccount() {
    
    List <Account> accts = new List<Account>();
      for(integer i = 0; i<200; i++) {
         Account a = new Account(Name='testAccount'+'i');
         accts.add(a);
    }
        
   	insert accts;

    Test.StartTest();	
        
        List<Account> accList = [SELECT Id, Description FROM Account ORDER BY CreatedDate ASC LIMIT 5];
     
 		for (Account acct : accList) {
        acct.Description = 'Heritage Account';
        }

    Test.StopTest();

	System.AssertEquals(
    
    	database.countquery('SELECT COUNT() FROM Account WHERE Description' = 'Heritage Account'), 5);
             
    }
}

 
If we have a list of contracts and within a given contract we have a list of subscriptions. Can I change the product field from a VisualForce page? Could you point me to where I shoud read about doing so, if possible.

Thank you!
There was a new critical update named "Remove Instance Names From URLs for Visualforce, Community Builder, Site.com Studio, and Content Files". But after active it, all of the Tabs which contains a Visualforce Page could not be shown on one/one.app when display with the Safari browser on the iPhone.

To make sure this issue was not caused by any other reason, I created the following simple Visualforce Page
<apex:page >
    <apex:outputPanel id="output">Test Page</apex:outputPanel>
</apex:page>
And I also make it be "Available for Lightning Experience, Lightning Communities, and the mobile app"
Then I create a new Tab and also I add it in the Salesforce Navigation in Mobile Administration.

When I deactive that critical update, I can see the text "Test Page" when I click my sample Tab. But unfortunately, it shows nothing after I active that option.

Why? Anybody else meets the same probelm with me?

It looks like that Claibome mets a similar issue, but I think there is a little difference: https://developer.salesforce.com/forums?id=9060G0000005TW2QAM

BTW, I also noticed that when the problem occurs, there were several errors reported in the console, several 404 errors and also a strange "Failed to load resource: too many HTTP redirect" error.
  • February 22, 2018
  • Like
  • 0
why I am not getting 2nd email alert
Requirement- I need to send an email alert when RAI start date becomes current date and after every 30 days. For my testing I have made it after every 1 day.
I have used two workflows.
1. When RAI start date is today it will make that date field today again.
2. 2nd workflow will send an email alert and in time trigger it will make the RAI start date today() after one day.
what is happening I am getting first email alert, the RAi start date is converted to today() after 1 day , but I am not getting the 2nd alert. Where I am getting wrong.

Workflow 1
User-added image
workflow 1 and 2 field update
User-added image
Workflow 2
User-added image
 
  • February 21, 2018
  • Like
  • 0
I have a button on the account page that calls a js window.open() when clicked.  

I also have a field on account called Status.  

The button can be pushed any time.  However it must be clicked when Status is set to 47.

Since the users are forgetful i want to automatically call the window.open() for them whenever status=47.

How do I do this - by any realistic means (apex, wfr, flow, pb....) 

Thanks,

Steve 
 
Add to outlook button in event is visible in classic , but not visible in lightening experience
I've got this challenge all wired up, but I have 2 issues. First, the selected boat highlight only works if I name the style "selected". If I call it "tile selected" it breaks (no error, just doesn't show a highlight). I know the 'selected' parameter is being passed correctly -- as I mentioned, it works great with a different style name, but the validation is checking for the specific name 'tile selected'.

If I change the style name to 'tile selected', the validation makes it past that part of the test, even though the CSS styling isn't working right.

The second issue in the validation says: BoatSearchResults.cmp must handle the BoatSelect event by calling a controller function named onBoatSelect. Here's the code I have in BoatSearchResults.cmp:
<aura:handler name="BoatSelect" event="c.BoatSelect" action="{!c.onBoatSelect}" />
And here's the handler in BoatSearchResultsController.js:
onBoatSelect: function(component, event, helper){
        component.set("v.selectedBoatId", event.getParam("boatId"));  
    }
I'm not sure why the validation is choking on this. Any ideas? Did I miss something?



 
I am getting below error
User-added image

but my application has 
User-added image

May I know why am not able to pass this challenge ?
 
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});
    }
}

 
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.