• sfadm sfadm
  • NEWBIE
  • 165 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 28
    Questions
  • 13
    Replies
As described in the following article:
​https://developer.salesforce.com/forums/?id=906F0000000BPXxIAO
I make the suggested validation to finind out if the uploaded file is ".csv" or not. Therefore I'm using the suggested try/catch in my controller class 
blob docBlob = doc.body;
string blobString;
try
{
blobString = docBlob.toString();
}
catch(Exception e)
    {
        ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL,'Please upload a valid CSV document');
        ApexPages.addMessage(myMsg); 
        return ;   
    }

The try/catch is working for specific file formats such as:
".pdf" , ".xlsx", ".docx".

But when I try to upload files with the following file formats:
".log", ".eml", ".cls"
they become successfully uploaded in Salesforce, creating hundreds of records in Salesforce which is totaly wrong and inadmissable.

Please advise how to adjust the try/catch block in order to allow only ".csv" file formats to be uploaded?
 

I have a blob object which is a CSV file and I need a method to return all lines from that file in the following data structure:
List<List<String>>
where each element of that data structure
(List<String>)
is a separate line in the file.

Please advise how this can be achieved and implemented?

I am looking for an approach to upload a CSV file into Salesforce:

1. I've created a vf page to read a CSV file from the local drive and insert its contents into Salesforce via Browse button.
2. Once the read is complete only particular columns from the CSV file content is necessary to be uploaded. Please advise how this can be achieved?
3. Locally create an Error Log with the failed rows and error message.
4. After the user choose the file for Upload in Salesforce the file has to be passed from the vf page to a controller class and the file has to be read and parsed by the controller class. Please advise how this can be achieved?
5. Please advise how the controller can update large number of records without exceeding number of soql queries?

I'll strongly appreciate if you can provide suitable examples to each of the avobe points.

Please advise how to move dynamic HTML code from my controller class into VF page.

My VF page implementation:
<apex:page standardController="task" extensions="SomeController">
 <apex:stylesheet value="{!$Resource.Task}"/>
  <apex:form >
   <apex:pageBlock >
       <apex:pageMessages escape="false"/> 
   </apex:pageBlock>
 </apex:form>
I have the following HTML code implemented in controller class:
public SomeController(ApexPages.StandardController controller) {
        objTask = (Task)controller.getRecord();
        String resultAll = buildTemplate(objTask);
        ApexPages.Message infoPage = new 
        ApexPages.Message(ApexPages.Severity.INFO, resultAll);
        ApexPages.addMessage(infoPage);
    }

public String buildTemplate(Task task) {

        ...

        String pageHTMLContent = '<HTML><HEAD></HEAD><BODY><TABLE class="task_history_class">';
        pageHTMLContent += '<TR><TH>Value1</TH><TH>Value2</TH><TH>Value3</TH><TH>Value4</TH>';
        for(Task_Activity_History__c taskActivityHistory :listTaskActivityHistory) {
            String oldValue = taskActivityHistory.Old_Value__c;
            if(oldValue == null || oldValue.equals('')) {
                oldValue = '&nbsp;';
            }
            String newValue = taskActivityHistory.New_Value__c;
            if(newValue == null || newValue.equals('')) {
                oldValue = '&nbsp;';
            }
            String userName = '&nbsp;';
            Id userId = taskActivityHistory.LastModifiedById;
            if(userId != null) {
                User user = usersMap.get(userId);
                if (user != null) {
                    userName = user.Name;
                }
            }

            DateTime lastModifiedByDate = taskActivityHistory.LastModifiedDate;
            if(lastModifiedByDate == null) {
                oldValue = '&nbsp;';
            }
            pageHTMLContent += '<TR>';
            pageHTMLContent += '<TD>' + oldValue + '</TD><TD>' + newValue + '</TD><TD>' + userName + '</TD><TD>' + lastModifiedByDate + '</TD>';
            pageHTMLContent += '</TR>';
        }
        pageHTMLContent += '</TABLE></BODY></HTML>';
        return pageHTMLContent;
    }
With this row
ApexPages.addMessage(infoPage);
I add dynamically generated HTML code in my VF page.

Please advise how to move the entire HTML code including the dynamically generated HTML from my controller class into my VF page?


 
When I try to deploy on my production environment I receive the following error message:
Apex CPU time limit exceeded and An unexpected error has occurred. Your development organization has been notified.
The last method in stacktrace where the error happens is my custom method.

I presume that the error is due to the fact that some of the other methods is taking considerable amount of time to be executed.

Please advise how to realize which is the method that is trowing such error and is consuming the entire cpu time.

Please advise how to avoid such error because I really need to find a solution as every time I try to deploy on production I receive such error message:

Apex CPU time limit exceeded and An unexpected error has occurred. Your development organization has been notified.
 
I have a controller class with the following method implementation:
public String buildTemplate(Task task) {

    Id taskId = task.Id;

    List<Task_History__c> listTaskHistory = [SELECT Field1, Id, Field2, Username__c, LastModifiedDate FROM Task_History__c WHERE Task_ID__c = :taskId];
    String pageHTMLContent = '<HTML><HEAD><STYLE>{! $Resource.Stylesheet }</STYLE></HEAD><BODY><TABLE class="css_class">';
    pageHTMLContent += '<TR><TH>Comment1</TH><TH>Comment2/TH><TH>Last Modified By</TH><TH>Last Modified Date</TH>';

    for(Task_History__c taskHistory :listTaskHistory) {
        String oldValue = taskHistory.Old_Value__c;
        String newValue = taskActivityHistory.New_Value__c;
        String userName = taskActivityHistory.Username__c;
        DateTime lastModifiedByDate = taskActivityHistory.LastModifiedDate;
        pageHTMLContent += '<TR>';
        pageHTMLContent += '<TD>' + oldValue + '</TD><TD>' + newValue + '</TD><TD>' + userName + '</TD><TD>' + lastModifiedByDate + '</TD>';
        pageHTMLContent += '</TR>';
    }

    pageHTMLContent += '</TABLE></BODY></HTML>';

    return pageHTMLContent;
}
I'd like to know how to include the contents of a static resource file in controller class?
In the Static Resource I have a file called "Stylesheet" with content:
table.css_class , .css_class th, .css_class td { border: 1px solid black; padding: 10px; } table.css_class th { text-align: center; }
Please advise how to include the contents of a static resource file in controller class?

 
Hello,

I have the following error message:
Error: Illegal assignment from Schema.SObjectField to Id
when I try to update lookup field in apex.

Here is the method implementation:
public void addTaskCommentHistory(Task task) {
    if(task == Null) {
            return;
    }

    String newValue = task.Description;

    if(newValue != Null && !newValue.equals('')) {
        String taskId = task.Id;
        String fieldName = 'Comments';
        String oldValue = '';

        Task_History__c taskHistory = new Task_History__c();
        taskHistory.Task_ID__c = taskId;
        taskHistory.Field_Name__c = fieldName;
        taskHistory.Old_Value__c = oldValue;
        taskHistory.New_Value__c = newValue;


        String lastModifiedBy = task.LastModifiedById; 
        String userName = '';
        // the query will return no more than one row because the data is extracted by user id
        List<User> listOfUsers = [SELECT Name FROM User where Id = :lastModifiedBy];
        if(listOfUsers.size() > 0){
            User user = listOfUsers.get(0);
            userName = user.Name;
        }

        taskHistory.User__c = user.Name;

        insert taskHistory;
    }    
}

When I try to add
user.Name
to
taskHistory.User__c
in
taskHistory.User__c = user.Name;
I get the "Error: Illegal assignment from Schema.SObjectField to Id" message.

Please advise how to update the User__c lookup field without the error message?


 
I have the following method 
public String buildTemplate(Task task) {
       
        Id taskId = task.Id;
        List<Task_History__c> listTaskHistory = [SELECT Field1, Id, Field2, Username__c, LastModifiedDate FROM Task_History__c WHERE Task_ID__c = :taskId];
        String pageHTMLContent = '<HTML><HEAD><STYLE>table.css_class , .css_class th, .css_class td { border: 1px solid black; padding: 10px; } table.css_class th { text-align: center; } </STYLE></HEAD><BODY><TABLE class="css_class">';
        pageHTMLContent += '<TR><TH>Comment1</TH><TH>Comment2/TH><TH>Last Modified By</TH><TH>Last Modified Date</TH>';
        System.debug('pageHTMLContent ' + pageHTMLContent);
        for(Task_History__c taskHistory :listTaskHistory) {
            String oldValue = taskHistory.Old_Value__c;
            String newValue = taskActivityHistory.New_Value__c;
            String userName = taskActivityHistory.Username__c;
            DateTime lastModifiedByDate = taskActivityHistory.LastModifiedDate;
            pageHTMLContent += '<TR>';
            // '<a href="' + mainURL + '">' + LeadId + '</a>';
            // '<a href="realURL">accountId</a>'
            //String mainAccURL = URL.getSalesforceBaseUrl().toExternalForm() + '/' + accountId;
            pageHTMLContent += '<TD>' + oldValue + '</TD><TD>' + newValue + '</TD><TD>' + userName + '</TD><TD>' + lastModifiedByDate + '</TD>';
            pageHTMLContent += '</TR>';
        }
        pageHTMLContent += '</TABLE></BODY></HTML>';
        return pageHTMLContent;
    }

in my controller class.

Please advise how to move the css "String pageHTMLContent = '<HTML><HEAD><STYLE>table.css_class , .css_class th, .css_class td { border: 1px solid black; padding: 10px; } table.css_class th { text-align: center; } </STYLE></HEAD><BODY><TABLE class="css_class">';" part into a Visual Force page or external file?

I'll strognly appreciate if you can provide an example.

Thank you

I'm using the after update trigger to update the "BillingCity" field in the Account object and make the field in proper case.
 
trigger on Account (after update) {

            String billingCity = Account.billingCity;

            toTitleCase(billingCity);
}

And the code in the invoked toTitleCase(billingCity) method:
 
//converts a given string to Title Case where the
//first letter of every word is capitalised and the rest are small
public String toTitleCase(String billingCity) {
   System.debug('billingCity ' + billingCity);
   String titlePhrase = '';
   //a set of words that should always be in lower case when in Title Case
   Set<String> forceLower = new Set<String>{'of', 'the', 'for', 'and', 'a', 'to', 'at' ,'an', 'but', 'if', 'or', 'nor'};

   if(billingCity != null && billingCity.length() > 0){
      String[] splitPhrase = billingCity.trim().split(' ');

      for(integer i = 0; i < splitPhrase.size(); i++){
          if(!forceLower.contains(splitPhrase[i].toLowerCase()) || i == 0 || i == (splitPhrase.size()-1) ) {
             titlePhrase += (splitPhrase[i].substring(0,1).toUpperCase())+(splitPhrase[i].substring(1).toLowerCase())+' ';

          } else {
               titlePhrase += splitPhrase[i].toLowerCase()+' ';

               }
          }
       }

       return titlePhrase.trim();
}
In the debug log I can see that the "BillinCity" field is updated with the proper case:
 
17:00:57:945 USER_DEBUG [40]|DEBUG|billingCity San Marino
but on a record level the field remains with upper case: "SAN MARINO"

Please advise an appropriate solution.

 
I'm getting this error while running this VF Page
 
Error: SObject row was retrieved via SOQL without querying the requested field: Task.LastModifiedById

An unexpected error has occurred. Your development organization has been notified.

VF Page:

<apex:page standardController="task" extensions="TaskHistoryController">
  <apex:form >
   <apex:pageBlock >
       <apex:pageMessages escape="false"/> 
    </apex:pageBlock>
  </apex:form>   
</apex:page>

Controller:
public with sharing class TaskHistoryController {



Task objTask;
String objTaskId;

public TaskHistoryController(ApexPages.StandardController controller) {
    objTask = (Task)controller.getRecord();
    Id taskId = objTask.Id;
    List<Task_Activity_History__c> listTaskActivityHistory = [SELECT Field_Name__c, Id, Old_Value__c, New_Value__c, LastModifiedById, LastModifiedDate FROM Task_Activity_History__c WHERE Task_ID__c = :taskId]; 
    Task_Activity_History__c taskHistory1 = listTaskActivityHistory.get(0);
    Task_Activity_History__c taskHistory2 = listTaskActivityHistory.get(1);
    String newValue1 = taskHistory1.New_Value__c;
    String newValue2 = taskHistory2.New_Value__c;
    String resultAll = buildTemplate(objTask);
    ApexPages.Message infoPage = new ApexPages.Message(ApexPages.Severity.INFO, resultAll);
    ApexPages.addMessage(infoPage);
}

public String buildTemplate(Task task) {
    Id lastModifiedBy = task.LastModifiedById;
    String userName = '';
    List<User> listOfUsers = [SELECT Id, IsActive, LastModifiedById, Name FROM User where Id = :lastModifiedBy];
    for(User user :listOfUsers) {
        userName = user.Name;
    }
    Id taskId = task.Id;
    List<Task_Activity_History__c> listTaskActivityHistory = [SELECT Field_Name__c, Id, Old_Value__c, New_Value__c, LastModifiedById, LastModifiedDate FROM Task_Activity_History__c WHERE Task_ID__c = :taskId];
    String pageHTMLContent = '<HTML><HEAD><STYLE>table.user_class, .user_class th, .user_class td { border: 1px solid black; padding: 10px; } table.user_class th { text-align: center; } </STYLE></HEAD><BODY><TABLE class="user_class">';
    pageHTMLContent += '<TR><TH>Comment Old Value</TH><TH>Comment New Value</TH><TH>Last Modified By</TH><TH>Last Modified Date</TH>';
    for(Task_Activity_History__c taskActivityHistory :listTaskActivityHistory) {
        String newValue1 = taskActivityHistory.Old_Value__c;
        String newValue2 = taskActivityHistory.New_Value__c;
        String lastModifiedById = taskActivityHistory.LastModifiedById;
        DateTime lastModifiedByDate = taskActivityHistory.LastModifiedDate;
        pageHTMLContent += '<TR>';
        pageHTMLContent += '<TD>' + newValue1 + '</TD><TD>' + newValue2 + '</TD><TD>' + userName + '</TD><TD>' + lastModifiedByDate + '</TD>';
        pageHTMLContent += '</TR>';
        System.debug('pageHTMLContent7 ' + pageHTMLContent);
    }
    pageHTMLContent += '</TABLE></BODY></HTML>';

    return pageHTMLContent;
}
Please advise an appropriate solution.
Hello,

I'd like to know is there a formula or some other feasible way in Salesforce to set Camel case?

I have data entered into the fields of all upper or all lower case. I need "SALESFORCE FORMULA" , to be dispalyed like "Salesforce Formula".

Please advise how this can be achieved in Salesforce?
I need a validation in the Biliing Post Code code field to prevent users from typing and entering City and Coutry into the Post Code field the way it is displayed in the followng image
User-added image
Please advise how such validation can be achieved?
I have an Application object an in the Application object I have list with custom CC App records.

When CC App record is edit is executed the beforeUpdate trigger.

I'm using an algorith to calculate average responce time of the record and the calculated value is stored in a custom field of type number.

When I try to save the value

I write CCApp1.averageHours = value; //for instance value = 8.00

For some reason the value is not saved in the field of the record.

I've tried with trigger.new as explained in the following:
http://https://salesforce.stackexchange.com/questions/198273/trigger-not-updating-a-record-field

The value is saved into the field of the current CCApp record.

What I need to achieve is to store and save the value in ALL CCApp records from the CCApp recod list in the Application.

Please advise how this can be achieved?
I keep getting the following error message:
FATAL_ERROR System.NullPointerException: Class.System.BusinessHours.diff:
Here is the stacktrace:
16:12:53.0 (303362690)|FATAL_ERROR|System.NullPointerException: Start date cannot be null
Class.System.BusinessHours.diff: line 23, column 1
Class.CCApprovalHandler.calculateWorkingHours: line 36, column 1
Class.CCApprovalHandler.processRiskRecords: line 188, column 1
Class.CCApprovalHandler.calculateAverageResponceTime: line 289, column 1
Class.CCApprovalHandler.beforeUpdate: line 341, column 1
Class.TriggerFactory.execute: line 93, column 1
Class.TriggerFactory.createHandler: line 27, column 1
Trigger.CCApprovalTrigger: line 2, column 1
16:12:53.0 (303383089)|FATAL_ERROR|System.NullPointerException: Start date cannot be null
and part of the source code where the exception happens:
 
private Double calculateWorkingHours(Datetime createdDate, Datetime completedDate) {
        List<BusinessHours> bhList = [SELECT id FROM BusinessHours WHERE IsDefault=true AND Name='Test Business Hours'];
        if(bhList.size() == 0) {
            return -1;
        }

        String bhId = bhList.get(0).id;
        System.debug('bhId ' + bhId);

        //is line 36 where the exception happens
        Long businessMillis = BusinessHours.diff(bhId, createdDate, completedDate);

        System.debug('businessMillis ' + businessMillis);
        Boolean areMillisZero = false;
        if(businessMillis == 0) {
            areMillisZero = true;
        }

        Integer bMinutes = (Integer)(businessMillis/1000)/60;
        Integer bHours = bMinutes/60;
        Integer bReminder = Math.mod(bMinutes, 60);
        Double hoursToAdd = 0;
        if(bReminder == 0) {
             hoursToAdd = 0;
        } else if(bReminder <= 30) {
             hoursToAdd = 0.5;
        } else {
             hoursToAdd = 1;
        }

        Double realBHours = bHours + hoursToAdd;
        if(realBHours == 0 && !areMillisZero) {
            realBHours = 0.5;
        }

        return realBHours;
    }
The line 36 is indicated in the comment above the row where the exception happens.

I'm also executing this method in beforeUpdate trigger.

Please advise how to avoid such exception?


 
In my code
trigger ContactRole on Application__c (before update) {

// Get the time between the last aTeam and bTeam
                DateTime lastUWCreated = lastCCUW.Created_Date__c;
                System.debug('lastUWCreated ' + lastUWCreated);
                DateTime lastAmTeamCreated = lastCCRiskAndChecked.Created_Date__c;
                System.debug('lastAmTeamCreated ' + lastAmTeamCreated);
                
                Double workingHours = calculateWorkingHours(lastUWCreated, lastAmTeamCreated);
                System.debug('workingHours ' + workingHours);
                Id ccAppId = lastAmTeamCreated.Id;
                
                List<Application__c> ccAppList = [SELECT CalculatedWorkingHours__c from Application__c where id = :ccAppId];
                Application__c appRecord = ccAppList.get(0);
                appRecord.CalculatedWorkingHours__c = workingHours;
                System.debug('appRecord.CalculatedWorkingHours__c ' + appRecord.CalculatedWorkingHours__c);
}

I'm using the before update trigger in order to populate the calculated working hours into a custom field called "CalculatedWorkingHours__c".

I can see in the debug log that the  "CalculatedWorkingHours__c" field is updated
 
USER_DEBUG [184]|DEBUG|workingHours 17.5

USER_DEBUG [194]|DEBUG|ccAppRecord.CalculatedWorkingHours__c 17.5
but on a record level the field remains blank

Please advise what can be the issue and why the field is not populated in the record?

Hello,

I need to calculate hours between two DateTime objects in apex excluding non-working days and weekends. Here is my method:
// calculate working hours between createdDate and completedDate
private Integer calculateWorkingHours(Datetime createdDate, Datetime completedDate) {
    List<BusinessHours> bhList = [Select id From BusinessHours Where IsDefault=true];
    if(bhList.size() == 0) {
        //If there is a problem to get hours from the BusinessHours database table return -1
        return -1;
    }

    // Get id of used set of business hours
    String bhId = bhList.get(0).id;

    // Returns the difference in milliseconds between a start and end Datetime based on a specific set of business hours.
    System.debug('createdDate ' + createdDate);
    System.debug('completedDate ' + completedDate);
    Long businessMillis = BusinessHours.diff(bhId, createdDate, completedDate);
    //Convert milliseconds to hours
    System.debug('businessMillis ' + businessMillis); 
    Integer bHours = (Integer)((businessMillis/1000)/60)/60;
    System.debug('bHours ' + bHours);
    return bHours;
}
And the data from the BusinessHours database table:

User-added image

Method 
BusinessHours.diff()
is calculating the Saturday and Sunday such as 24 hours working days!

How do I change Saturday and Sunday to be non-working days, hence zero working hours?
Hello,

I have setup a new SalesForce environment and I have to transfer my Apex classes on it.

In order to deploy my code I use a test class with test methods.

A validation process is started when I try to deploy the changes.

This validation invokes all existing test methods and the environment throws the following exception:
System.LimitException: Apex CPU time limit exceeded

Oddly enough on the old environment there is no such exceptions

I'm sending you a method of my source code where the Apex CPU time limit exceeded is most likely to happen:
 
private List<LeadConversionContainer> checkByWebsite(Lead leadObj) {
        List<LeadConversionContainer> accountWebsites = new 
        List<LeadConversionContainer>();
        String website = leadObj.Website;
        String leadId = leadObj.Id;
        List<Account> accWebsiteList = [SELECT Website, Url__c, Status__c FROM 
        Account];
        if(website != null && !website.equals('') && accWebsiteList != null) {
            List<String> leadWebsites = extractWebsites(website);
            for (String leadUrl : leadWebsites) {
                String normWebsite = normalizeWebsite(leadUrl);
                String leadWebsite = normWebsite.trim();
                for(Account acc : accWebsiteList) {
                    String accountWebsite = acc.Url__c;
                    String accountId = acc.Id;
                    List<String> extractedAccountWebsite = 
                    extractWebsites(accountWebsite);
                    for(String accWebsite :extractedAccountWebsite) {
                        String accountSite = normalizeWebsite(accWebsite);
                        if(accountSite != null) {
                            List<String> leadSplitWebsitesList = leadWebsite.split('[,;\\s]');
                            for(String leadSplitUrls :leadSplitWebsitesList) {
                                if(accountSite.equals(leadSplitUrls)) {
                                    boolean isAccountStatusActive = isAccountActive(acc);
                                    boolean isMerchantApplication = 
                                    isMerchantApplicationsAttached(acc);
                                    if(isAccountStatusActive || isMerchantApplication) {
                                        String reasonToStopConversion = 'Lead Website coincide with 
                                        Account Website';
                                        LeadConversionContainer leadConvert = new 
                                        LeadConversionContainer(acc.Id, '', reasonToStopConversion);
                                        accountWebsites.add(leadConvert);
                                    }
                                }    
                            }
                        }
                    }
                }    
            }
        }
        return accountWebsites;
    }

Please advise how to solve the issue with my deploy and avoid such System.LimitException: Apex CPU time limit exceeded exception?
I have an apex source code where I have plenty of if/else conditions which depend on the business hours Mon - Fri 9h - 18h settings in Salesforce.
I'm creating a test method to validate my code but because of the business hours settings the apex code enters only in few if conditions.
And I cannot reach the necessary percentage to validate my code.

Is it possible in the test method to change the business hours so that I can validate my code on 100% or is there a way to validate my code despite the fact that it is depending on the business hours?
I've created a custom field of type DateTime in Task object.

I try to add to my custom field an object from type DateTime.

But I receive the following error message:
A value cannot be stored to my_custom_field in type Task
Do you know how to solve this error?
 
Hello,

When the priority in a task is changed I calculate dynamically the calendar hours.

The calculated calendar hours are set and updated in a custom field called "timeframe".

After the value in the "timeframe" field is changed I want to send an e-mail alert based on the number of hours set in the "timeframe" field.

Example: If task priority is set to "High", the calendar hours in the "timeframe" filed will be 23 hours.

I want to know how to send an e-mail alert after 23 hours?

Could you please advise how to do that in Salesforce?

I have a blob object which is a CSV file and I need a method to return all lines from that file in the following data structure:
List<List<String>>
where each element of that data structure
(List<String>)
is a separate line in the file.

Please advise how this can be achieved and implemented?
I'm getting this error while running this VF Page
 
Error: SObject row was retrieved via SOQL without querying the requested field: Task.LastModifiedById

An unexpected error has occurred. Your development organization has been notified.

VF Page:

<apex:page standardController="task" extensions="TaskHistoryController">
  <apex:form >
   <apex:pageBlock >
       <apex:pageMessages escape="false"/> 
    </apex:pageBlock>
  </apex:form>   
</apex:page>

Controller:
public with sharing class TaskHistoryController {



Task objTask;
String objTaskId;

public TaskHistoryController(ApexPages.StandardController controller) {
    objTask = (Task)controller.getRecord();
    Id taskId = objTask.Id;
    List<Task_Activity_History__c> listTaskActivityHistory = [SELECT Field_Name__c, Id, Old_Value__c, New_Value__c, LastModifiedById, LastModifiedDate FROM Task_Activity_History__c WHERE Task_ID__c = :taskId]; 
    Task_Activity_History__c taskHistory1 = listTaskActivityHistory.get(0);
    Task_Activity_History__c taskHistory2 = listTaskActivityHistory.get(1);
    String newValue1 = taskHistory1.New_Value__c;
    String newValue2 = taskHistory2.New_Value__c;
    String resultAll = buildTemplate(objTask);
    ApexPages.Message infoPage = new ApexPages.Message(ApexPages.Severity.INFO, resultAll);
    ApexPages.addMessage(infoPage);
}

public String buildTemplate(Task task) {
    Id lastModifiedBy = task.LastModifiedById;
    String userName = '';
    List<User> listOfUsers = [SELECT Id, IsActive, LastModifiedById, Name FROM User where Id = :lastModifiedBy];
    for(User user :listOfUsers) {
        userName = user.Name;
    }
    Id taskId = task.Id;
    List<Task_Activity_History__c> listTaskActivityHistory = [SELECT Field_Name__c, Id, Old_Value__c, New_Value__c, LastModifiedById, LastModifiedDate FROM Task_Activity_History__c WHERE Task_ID__c = :taskId];
    String pageHTMLContent = '<HTML><HEAD><STYLE>table.user_class, .user_class th, .user_class td { border: 1px solid black; padding: 10px; } table.user_class th { text-align: center; } </STYLE></HEAD><BODY><TABLE class="user_class">';
    pageHTMLContent += '<TR><TH>Comment Old Value</TH><TH>Comment New Value</TH><TH>Last Modified By</TH><TH>Last Modified Date</TH>';
    for(Task_Activity_History__c taskActivityHistory :listTaskActivityHistory) {
        String newValue1 = taskActivityHistory.Old_Value__c;
        String newValue2 = taskActivityHistory.New_Value__c;
        String lastModifiedById = taskActivityHistory.LastModifiedById;
        DateTime lastModifiedByDate = taskActivityHistory.LastModifiedDate;
        pageHTMLContent += '<TR>';
        pageHTMLContent += '<TD>' + newValue1 + '</TD><TD>' + newValue2 + '</TD><TD>' + userName + '</TD><TD>' + lastModifiedByDate + '</TD>';
        pageHTMLContent += '</TR>';
        System.debug('pageHTMLContent7 ' + pageHTMLContent);
    }
    pageHTMLContent += '</TABLE></BODY></HTML>';

    return pageHTMLContent;
}
Please advise an appropriate solution.
In my code
trigger ContactRole on Application__c (before update) {

// Get the time between the last aTeam and bTeam
                DateTime lastUWCreated = lastCCUW.Created_Date__c;
                System.debug('lastUWCreated ' + lastUWCreated);
                DateTime lastAmTeamCreated = lastCCRiskAndChecked.Created_Date__c;
                System.debug('lastAmTeamCreated ' + lastAmTeamCreated);
                
                Double workingHours = calculateWorkingHours(lastUWCreated, lastAmTeamCreated);
                System.debug('workingHours ' + workingHours);
                Id ccAppId = lastAmTeamCreated.Id;
                
                List<Application__c> ccAppList = [SELECT CalculatedWorkingHours__c from Application__c where id = :ccAppId];
                Application__c appRecord = ccAppList.get(0);
                appRecord.CalculatedWorkingHours__c = workingHours;
                System.debug('appRecord.CalculatedWorkingHours__c ' + appRecord.CalculatedWorkingHours__c);
}

I'm using the before update trigger in order to populate the calculated working hours into a custom field called "CalculatedWorkingHours__c".

I can see in the debug log that the  "CalculatedWorkingHours__c" field is updated
 
USER_DEBUG [184]|DEBUG|workingHours 17.5

USER_DEBUG [194]|DEBUG|ccAppRecord.CalculatedWorkingHours__c 17.5
but on a record level the field remains blank

Please advise what can be the issue and why the field is not populated in the record?
Hello,

I have setup a new SalesForce environment and I have to transfer my Apex classes on it.

In order to deploy my code I use a test class with test methods.

A validation process is started when I try to deploy the changes.

This validation invokes all existing test methods and the environment throws the following exception:
System.LimitException: Apex CPU time limit exceeded

Oddly enough on the old environment there is no such exceptions

I'm sending you a method of my source code where the Apex CPU time limit exceeded is most likely to happen:
 
private List<LeadConversionContainer> checkByWebsite(Lead leadObj) {
        List<LeadConversionContainer> accountWebsites = new 
        List<LeadConversionContainer>();
        String website = leadObj.Website;
        String leadId = leadObj.Id;
        List<Account> accWebsiteList = [SELECT Website, Url__c, Status__c FROM 
        Account];
        if(website != null && !website.equals('') && accWebsiteList != null) {
            List<String> leadWebsites = extractWebsites(website);
            for (String leadUrl : leadWebsites) {
                String normWebsite = normalizeWebsite(leadUrl);
                String leadWebsite = normWebsite.trim();
                for(Account acc : accWebsiteList) {
                    String accountWebsite = acc.Url__c;
                    String accountId = acc.Id;
                    List<String> extractedAccountWebsite = 
                    extractWebsites(accountWebsite);
                    for(String accWebsite :extractedAccountWebsite) {
                        String accountSite = normalizeWebsite(accWebsite);
                        if(accountSite != null) {
                            List<String> leadSplitWebsitesList = leadWebsite.split('[,;\\s]');
                            for(String leadSplitUrls :leadSplitWebsitesList) {
                                if(accountSite.equals(leadSplitUrls)) {
                                    boolean isAccountStatusActive = isAccountActive(acc);
                                    boolean isMerchantApplication = 
                                    isMerchantApplicationsAttached(acc);
                                    if(isAccountStatusActive || isMerchantApplication) {
                                        String reasonToStopConversion = 'Lead Website coincide with 
                                        Account Website';
                                        LeadConversionContainer leadConvert = new 
                                        LeadConversionContainer(acc.Id, '', reasonToStopConversion);
                                        accountWebsites.add(leadConvert);
                                    }
                                }    
                            }
                        }
                    }
                }    
            }
        }
        return accountWebsites;
    }

Please advise how to solve the issue with my deploy and avoid such System.LimitException: Apex CPU time limit exceeded exception?
I have an apex source code where I have plenty of if/else conditions which depend on the business hours Mon - Fri 9h - 18h settings in Salesforce.
I'm creating a test method to validate my code but because of the business hours settings the apex code enters only in few if conditions.
And I cannot reach the necessary percentage to validate my code.

Is it possible in the test method to change the business hours so that I can validate my code on 100% or is there a way to validate my code despite the fact that it is depending on the business hours?
Hello,

When the priority in a task is changed I calculate dynamically the calendar hours.

The calculated calendar hours are set and updated in a custom field called "timeframe".

After the value in the "timeframe" field is changed I want to send an e-mail alert based on the number of hours set in the "timeframe" field.

Example: If task priority is set to "High", the calendar hours in the "timeframe" filed will be 23 hours.

I want to know how to send an e-mail alert after 23 hours?

Could you please advise how to do that in Salesforce?
I need to get the current time but to be in type DateTime.

I use:
DateTime now = System.now();
but it returns wrong time.

I execute the code in 2017-08-04 00:38:46 AM

but it returns
00:38:46:023 USER_DEBUG [138]|DEBUG|now 2017-08-03 21:38:46
How can I get my correct current local time 2017-08-04 00:38:46?

I had even tried with:
DateTime now = DateTime.parse(System.Now().format());
but I still get wrong time.
01:10:09:021 USER_DEBUG [139]|DEBUG|now 2017-08-03 22:10:00
How can I get the correct current local time?



 
I have an object of type Time startWorkingTime and object of type DateTime nextBusinessDay. I want to create new object of type DateTime based on startWorkingTime and nextBusinessDay.
Here is my code:
DateTime startWorkingTime = DateTime.newInstance(nextBusinessDay.year(), nextBusinessDay.month(), nextBusinessDay.day(), currentStartHours.hour(), currentStartHours.minute(), currentStartHours.second());
After startworkingtime the time is set one hour earlier
For example:
23:59:24:025 USER_DEBUG [188]|DEBUG|currentStartHours 09:00:00.000Z
23:59:24:025 USER_DEBUG [189]|DEBUG|currentStartHours.hour() 9
23:59:24:025 USER_DEBUG [197]|DEBUG|startWorkingTime 2017-08-04 08:00:00
Could you please explain why the hour in startWorkingTime is 08:00:00 and advise how to fix it?


 

I need to calculate the out of office hours in apex.

The hours are:
6 pm – 9 am Mon – Fri
and
6 pm on Fri till 9 am on Mon

I've already configured the Business Hours:

Monday09:00to18:00
Tuesday09:00to18:00
Wednesday09:00to18:00
Thursday09:00to18:00
Friday09:00to18:00
Saturday24 Hours
Sunday24 Hours

and activate it in Salesforce.

Please advise how it can be achieved in apex?

Hello,

I have a custom vf page which is controlling the conversion process from Lead to Account. What I'd like to achieve is that once I convert the system to automatically redirect to the opportunity page. Could you please advise how this can be achieved?
Hello,

I'd like to know how to display a dialog or pop up window in Salesforce.

I'm using a convert button with associated custom visualforce page. I use custom visualfoce page to invoke appex controller class.

Depending on the given parameters the appex class the end result of the class is to return a message. The message is displayed in a visualforce page(see the attached screenshot).Custom Visualforce page

What I would like to know is how to dispaly a message in a dialog or a pop-up window instead of entire visualforce page.

Here is what I would like to achive:
Once the convert button is pressed(see the attached screenshot)Standard Convert Page
I would like to know how to dispaly the message in a dialog or a pop-up window.

Could you please advise how this can be achieved?

 
I have an existing workflow and some part of the workflow involves approval process for opportunities. During the approval process Opportunity object is locked. The unlock takes place at the end of the approval process. The lock for Opportunity object can not be removed in administrative way. What I strive to achieve is during the approval process the Opportunity object to be unlocked. There are two apex methods to lock and unlock in the Approval class but I'm not aware where to use those methods and which apex method and apex class exactly is invoked when the approval process is submitted. Please advise which apex method is invoked when the approval process is submitted.