[Salesforce] Apex Time Delay Function

  wait(10000);//Wait

    //Wait
    public static void wait(Integer millisec) {

        if(millisec == null || millisec < 0) {
            millisec = 0;
        }
        
        Long startTime = DateTime.now().getTime();
        Long finishTime = DateTime.now().getTime();
        while ((finishTime - startTime) < millisec) {
            //sleep for parameter x millisecs
            finishTime = DateTime.now().getTime();
        }
        // System.debug(‘>>> Done from ‘ + startTime + ‘ to ‘ + finishTime);
    }

[Salesforce]@RemoteAction

I will share about Salesforce’s @RemoteAction.

Features

  • You can execute Apex class processes from JavaScript.
  • It has the same functionality as actionFunction, but you can use the return value of the process in JavaScript.

For example, you can execute a process to get accounts and use the list of accounts retrieved.

Sample code

  • Apex class
 global with sharing class SampleRemoteController {
    @RemoteAction
    global static String setString(String str) {
        return  '----- ' + str + ' -----';
    }
    
    @RemoteAction
    global static List<sObject> exequery(String str){
        return Database.query(str);
    }
} 

Visualforce pages

<apex:page controller="SampleRemoteController">
    <apex:form >
        <!-- @RemoteActionSample:StringSet -->
        <apex:commandButton value=" String " onClick="return  setString('Yaho');" />
         
        <!-- @RemoteActionSample:SOQLGet -->
        <apex:commandButton value=" GetAcc " onClick="return getAcc();" />
        <hr/>
        <div id="output">Output</div>
    </apex:form>

    <script type="text/javascript">
        /*
         * @RemoteActionSample
         * StringSet
         */
        function setString(str) {
            {!$RemoteAction.SampleRemoteController.setString}(str, function(result, event){
                if(event.status) {
                    document.getElementById("output").innerHTML = result;
                }
            });
            return false;
        }
        
        /*
         * @RemoteActionSample
         * SOQLAccountGet
         */
        function getAcc() {
            var query = 'select Id,Name from Account limit 10';
            {!$RemoteAction.SampleRemoteController.exequery}(query, function(result, event){
                if(event.status) {
                    var names = '';
                    for (var i = 0; i < result.length; i++) {
                        names = names + result[i].Name + ' | ';
                    }
                    document.getElementById("output").innerHTML = names;
                }
            });
            return false;
        }
    </script>
</apex:page>                     

[Salesforce] Methods defined as TestMethod do not support Web service callouts.

Methods defined as TestMethod do not support Web service callouts.

Example of an error that occurred

@isTest
private class PostTest {
    @isTest
    static void test() {

        Test.startTest();
        Service.execute();
        Test.stopTest();
    }
}

public with sharing class Service {
  @future(callout=true)
  public static void execute() {
    ServiceC sc = new ServiceC();
    sc.post();
   }

}

public with sharing class ServiceC {

  private HttpResponse post() {
    HttpRequest request = new HttpRequest();

    (omission)

    HttpResponse response = new Http().send(request);

    return response;
  }

}

Example of resolving errors

@isTest
private class PostTest {
    @isTest
    static void test() {

        Test.startTest();
        Test.setMock(HttpCalloutMock.class, new ServiceHttpCalloutMock());
        Service.execute();
        Test.stopTest();
    }
}

@isTest
public class ServiceHttpCalloutMock implements HttpCalloutMock {
  public HTTPResponse respond(HTTPRequest req) {
    HttpResponse res = new HttpResponse();
    res.setStatusCode(200);
    res.setBody('test');
    return res;
  }
}

[Salesforce]Failed to run tests synchronously.: Your query request was running for too long.

Handling the error “Failed to run tests synchronously.: Your query request was running for too long.” when running a test class

Summary
Test classes failing with QUERY_TIMEOUT Failed to run tests synchronously when running in synchronous mode

Login to the org which has quite number of managed package apex classes.
Run the Apex Test Class from Developer Console in Sync Mode
You may notice below exception when running the apex test class:
Error Message:

“QUERY_TIMEOUT Failed to run tests synchronously: Your query request was running for too long”

Workaround
As a workaround, please try to run the test class in asynchronous mode.

[Salesforce] How to use HAVING in SOQL statements

SOQL statement HAVING

HAVING allows you to enter filtering conditions for the results grouped by GROUP BY.

It is similar to WHERE in that it is a filtering condition, but WHERE is before grouping and HAVING is after grouping.

The following sample groups by the lead source of the opportunity and displays the amount by lead source where the number of records with the same value is 1 or more.

AggregateResult[] results = [SELECT LeadSource, SUM(Amount) summary 
                               FROM Opportunity 
                               GROUP BY LeadSource 
                               HAVING Count(LeadSource) > 1];
for(AggregateResult ar: results){
  System.debug('LeadSource='+ ar.get('LeadSource') 
                   + ':Amount='+ ar.get('summary'));
}

Debugging Results

LeadSource=LeadSource1:Amount=2
LeadSource=LeadSource2:Amount=3

[Salesforce]JSENCODE

JSENCODE

Encode text strings and merge field values ​​for use in JavaScript by inserting an escape character, such as a backslash (), before unsafe JavaScript characters, such as an apostrophe (‘).

The JavaScript runs when the page loads and displays the alert.

<script>var ret = "foo";alert('xss');//";</script>

In this case, use the JSENCODE function to prevent JavaScript from being executed. Example

<script>var ret = "{!JSENCODE($CurrentPage.parameters.retURL)}";</script>

[Salesforce]CANNOT_EXECUTE_FLOW_TRIGGER

CANNOT_EXECUTE_FLOW_TRIGGER

Error details when executing test class

System.DmlException: Insert failed. First exception on row 0; first error:
CANNOT_EXECUTE_FLOW_TRIGGER,
This record cannot be saved due to a failure in the "Campaign Create, Member Status Auto Set" process.
Please report the following details to your Salesforce system administrator:
Salesforce has no records that match the deletion criteria.
Salesforce has no records that match the deletion criteria. : []

One of the solutions is as follows:

@isTest(SeeAllData=true)
※May be effective in some cases.