Tag: Salesforce

  • You are trying to log in through an instance URL (example: sandbox) and you do this.

          
    sfdx auth:web:login -a myusername@myorg.sandbox --instanceurl=https://mysandbox-domain.lightning.force.com
    
    

    And you get this error in console:

    In your browser you get this

    image

    The problem is you are using lightning.force.com domain instead of my.salesforce.com

          
    sfdx auth:web:login -a myusername@myorg.sandbox --instanceurl=https://mysandbox-domain.my.salesforce.com
    
    

  •       
    sfdx force:source:deploy -x manifest/package.xml -l RunLocalTests --checkonly
          
        
          
    *** Deploying with SOAP API ***
    Deploy ID: 0Bf7D000003ygUYWBY
    SOURCE PROGRESS | █████████████████████████████████░░░░░░░ | 92/111 Components
    
    === Component Failures [0]
    Type  Name  Problem
    ────  ────  ───────
    
    
    === Test Results Summary
    Passing: 30
    Failing: 17
    Total: 47
    Time: 0
    ERROR running force:source:deploy:  Deploy failed.
          
        
          
    sfdx force:source:deploy:report -i 0Bf7D000003ygUYWBY  --json > deploy.log
          
        

    Open deploy.log and look for the node “runTestResult” and then “failures”.

    Example:

          
     "failures": [
              {
                "id": "01p0W000003fXQIQA2",
                "message": "System.DmlException: Insert failed. First exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Validation Formula [THE COMPLETE ERROR HERE] ",
                "methodName": "myUnitTest",
                "name": "MyApexClass",
                },
                "packageName": "MyApexClass",
                "stackTrace": "MyApexClass myUnitTest: line 38, column 1",
                "time": "1927.0",
                "type": "Class"
              }, 
             {
                   (...)
             }
        ]
          
        

    Photo by Siora Photography on Unsplash

  • If you’re an administrator of a Salesforce org, you need to know how your users are interacting with your Visualforce pages. With Salesforce VisualforceAccessMetrics, you can easily get usage stats for your Visualforce pages and track page performance.

    VisualforceAccessMetrics is a tool that lets you see which Visualforce pages are being accessed, how long users are staying on the page, and the page performance status. The data from VisualforceAccessMetrics can be used to optimize page performance and provide a better user experience.

    If you want to know how frequently your Visualforce pages are accessed, you just have to run a simple query on VisualforceAccessMetrics:

    SELECT ApexPageId,DailyPageViewCount,Id,MetricsDate 
    FROM VisualforceAccessMetrics

    More options

    SELECT ApexPageId, MetricsDate, TotalTime, AverageTime, TotalRequests, UniqueUsers
    FROM VisualforceAccessMetrics
    WHERE MetricsDate = TODAY

    Have in mind that query will return stats from the latest 90 days

    Pageviews are tallied the day after the page is viewed, and each VisualforceAccessMetrics object is removed after 90 days.

    But beware, that query could return deleted pages.

    To fix that, let’s tweak the query to:

    SELECT Id, Markup, Name, NamespacePrefix 
    FROM ApexPage 
    WHERE Id IN (SELECT ApexPageId FROM VisualforceAccessMetrics)

    Now the query will return only existing pages.

  • Why convert attachments to Salesforce files?

    Files are more versatile and provide better functionality than attachments. Attachments can only be
    attached to a single record, while files:

    • Can be shared with multiple records and users
    • Appear in Files home and can be added to Libraries
    • Track multiple versions
    • Provide file previews of documents, images, PDFs, and more

    Salesforce files are optimized for Lightning Experience.
    Attachments can’t be uploaded in Lightning Experience. Attachments may be visible (and read-only) in
    Lightning Experience, but only if the org admin has enabled this on each page layout.

    Why convert classic notes to enhanced notes?

    Enhanced notes are more versatile and provide better functionality than classic notes. Classic notes can only be attached to the records of one object. Enhanced notes, however, can be added to multiple objects, like accounts, opportunity, contact, and lead.
    Enhanced notes are optimized for Lightning Experience. They can also be used in Salesforce1.

    This package includes 3 tools:

    • Admins use the Attachments to Files tool to do bulk conversion of all the attachments in an org.
    • Admins use the Notes Conversion tool to do bulk conversion of all the classic notes in an org.
    • Admins use the Update Page Layouts tools to update layouts to use the new related lists exclusively.

    Conversion of attachments and notes is supported for custom objects and the following standard objects: Account, Asset, Campaign, Case, Contact, Contract, Lead, Opportunity, Product, Quote, and Solution.

    Convert attachments to files because files are optimized for Lightning Experience and provide additional capabilities beyond attachments, including the ability to relate files to multiple records, track multiple versions, and view file previews.

    Convert classic notes to enhanced notes, which are optimized for Lightning Experience and provide additional capabilities beyond classic notes, such as the ability to relate a note to multiple records, and track multiple versions

    If you have comments or feedback, please reach out to us in this Success Community Group:

    https://success.salesforce.com/_ui/core/chatter/groups/GroupProfilePage?g=0F93A000000LgpS

    Resources

  • As you probably know, JavaScript buttons are not supported in Lightning Experience (LEX). In particular, you can’t use REQUIRESCRIPT.

    In this post, the idea is to show how to migrate a particular JavaScript button that uses sforce.connection.query sentence.

    Suppose our JavaScript button is like this:

          
    {!REQUIRESCRIPT("/soap/ajax/37.0/connection.js")} 
    {!REQUIRESCRIPT("/soap/ajax/37.0/apex.js")} 
     
    var query ="SELECT Id, Name FROM Account LIMIT 10";
    var queryRecords= sforce.connection.query(query);
    var records = queryRecords.getArray("records"); 
    //Do something with the records...
          
        

    A Lightning equivalent solution requires several steps. I assume that you have some knowledge about Lightning Components development as well as Apex development.

    Well, let’s go!

    Create a Lightning component called MyQueryResult and Its JavaScript controller

    MyQueryResult.cmp

          
    <aura:component controller="MyQueryResultService" >
        <aura:attribute name="queryResult" type="SObject[]" />
        <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
      
        <!-- It just displays the results. Modify It depending on your needs -->
        <aura:iteration items="{! v.queryResult}" var="item">
            {!item.Id} - {!item.Name}<br/>
         </aura:iteration>
    </aura:component>
          
        

    MyQueryResult.js

          
    ({
        doInit : function(component, event, helper) {
            var myQuery = 'SELECT Id, Name FROM Account LIMIT 10';
            var action = component.get("c.executeQuery");
            action.setParams({
                "theQuery": myQuery
            });
            action.setCallback(this, function(response) {
                var state = response.getState();
                if(state == "SUCCESS" && component.isValid()){
                    console.log("success") ;
                    var queryResult = response.getReturnValue();
                    console.log(queryResult);
                    component.set("v.queryResult", queryResult);
                }else{
                    console.error("fail:" + response.getError()[0].message); 
                }
            });
            $A.enqueueAction(action);
        }
    })
          
        

    We will need also a service (an Apex class) to execute our query

    MyQueryResultService

          
    public class MyQueryResultService {
     
        @AuraEnabled
        public static List executeQuery(String theQuery){
            try{
                String query = String.escapeSingleQuotes(theQuery);
                return Database.query(query);
            }catch(Exception e){
                throw new AuraHandledException('Error doing the query: '+theQuery+' Error: '+e.getMessage());
            }
        }
    }
          
        

    After that, we need a quick action pointing to our component.

    The last step is to add our quick action to the layouts we need

    Read more about this at Lightning Alternatives to JavaScript Buttons

    Photo by Glenn Carstens-Peters on Unsplash

  • What about if we add a component with a pie chart on the Campaign object’s record page? It’s very useful to see how the campaign is going in terms of leads’ statuses. So we want to know the percentage of leads converted, not converted, contacted, etc.

    I will use Lightning in a Developer org that I just created to take advantage of its default data. So let’s go!

    Assumption

    You are familiar with a Salesforce org, Lightning and you have created some reports in the past. If you haven’t created any report yet, you can read this module in Trailhead: Reports & Dashboards for Lightning Experience

    Add leads to a campaign

    First of all, let’s add some leads to a campaign. You only have to add leads to a campaign, you don’t have to create any data.

    Create the report

    Go to Reports, New Report, expand Campaigns, select Campaign with leads and click on Create.

    Drag Lead status field and group by this field

    image

    Save the report with the name you want and, importantly, in a public folder.

    Run the report and add a pie chart. Don’t forget to save it.

    image

    Add the report component

    Now let’s add our report to the Campaign’s record page.

    Open any campaign and Edit Page to open the App Builder.

    image

    Drag the Report Chart component and set those parameters

    image

    Save the page and press Back to see the record page again with the report

    image

  • Salesforce and Amazon Web Services (AWS) are two of the most popular cloud computing platforms widely used across various industries. Integrating Salesforce with AWS can offer tremendous benefits in terms of scalability, functionality, and convenience. One such integration is between Salesforce Apex and AWS Simple Queue Service (SQS) which allows developers to send and receive messages to an AWS SQS queue from Salesforce Apex code.

    To send a message to an SQS queue from a Salesforce Apex class, you first need to set up an AWS account and an SQS queue with appropriate permissions to allow Salesforce to access and send messages. 


    So let’s create a wrapper in Salesforce Apex to send messages to a given SQS queue.

    Important: before creating your Apex class you will need a Custom Metadata Type value to store your AWS keys. In this example, it assumes you have your keys under “my was keys”. See the method loadAwsKeys()

    public with sharing class SqsSender {
    
        public class AwsException extends Exception {}
    
        private static String access_key;
        private static String secret_key;
        private static String aws_region;
        private static String aws_account_id;
        private static String aws_queue_name;
        private static String host {get;set;}
        private static String endpoint {get;set;}
        private static String request_parameters {get;set;}
    
        private static final String aws_service = 'sqs';
        private static final String content_type = 'application/x-www-form-urlencoded';
    
        // Create a date for headers and the credential string
        private static final Datetime now = Datetime.now();
        private static final String amz_date = now.formatGmt('YMMdd') + 'T' + now.formatGmt('HHmmss') + 'Z';
        private static final String date_stamp = now.formatGmt('YMMdd');
    
    
        /**
         * Load AWS credentials from Custom Metadata Types: https://help.salesforce.com/articleView?id=custommetadatatypes_about.htm&type=5
         */
        private static void loadAwsKeys(){
            my_aws_keys__mdt result = [SELECT aws_access_key__c, aws_secret_key__c, aws_region__c, aws_account_id__c, aws_queue_name__c
            FROM my_aws_keys__mdt WHERE Label = 'keys' LIMIT 1];
            access_key= result.aws_access_key__c;
            secret_key= result.aws_secret_key__c;
            aws_account_id= result.aws_account_id__c;
            aws_region= result.aws_region__c;
            aws_queue_name= result.aws_queue_name__c;
        }
    
        public static void SendMessageBatch(List<String> messageBodies) {
            if (messageBodies == null || messageBodies.size() == 0) {
                throw new AwsException('Body is mandatory');
            }
            SqsSender.aws_region = aws_region;
            SqsSender.aws_queue_name = aws_queue_name;
            SqsSender.aws_account_id = aws_account_id;
            String message_body = '';
            SqsSender.request_parameters = 'Action=SendMessageBatch';
            for(Integer i = 0;i<messageBodies.size();i++){
                SqsSender.request_parameters = SqsSender.request_parameters
                        + '&SendMessageBatchRequestEntry.'+(i+1)+'.Id=msg_0'+(i+1)
                        + '&SendMessageBatchRequestEntry.'+(i+1)+'.MessageBody='+EncodingUtil.urlEncode(messageBodies[i], 'UTF-8');
            }
            SqsSender.host = aws_service + '.' + aws_region + '.amazonaws.com';
            SqsSender.endpoint = 'https://' + host + '/' + aws_account_id + '/' + aws_queue_name;
    
            String canonical_request = SqsSender.createCanonicalRequest();
            String string_to_sign = SqsSender.createTheStringToSign(canonical_request);
            String signature = SqsSender.calculateTheSignature(string_to_sign);
            String authorization_header = SqsSender.addSigningInfoToTheRequest(signature);
    
            SqsSender.sendRequest(authorization_header, amz_date, request_parameters, endpoint);
        }
    
        public static void SendMessage(String messageBody, String messageGroupId, String messageDeduplicationId) {
            if (messageBody == null) {
                throw new AwsException('Body is mandatory');
            }
            loadAwsKeys();
            System.debug('message body: '+messageBody);
            System.debug('messageGroupId: '+messageGroupId);
            System.debug('messageDeduplicationId: '+messageDeduplicationId);
            System.debug('aws queue name: '+aws_queue_name);
          
            SqsSender.aws_region = aws_region;
            SqsSender.aws_queue_name = aws_queue_name;
            SqsSender.aws_account_id = aws_account_id;
            SqsSender.request_parameters = 'Action=SendMessage&MessageGroupId='+messageGroupId+'&MessageDeduplicationId='+messageDeduplicationId+'&MessageBody=' + messageBody;
            SqsSender.host = aws_service + '.' + aws_region + '.amazonaws.com';
            SqsSender.endpoint = 'https://' + host + '/' + aws_account_id + '/' + aws_queue_name;
            System.debug('endpoint: '+SqsSender.endpoint);
    
            String canonical_request = SqsSender.createCanonicalRequest();
            String string_to_sign = SqsSender.createTheStringToSign(canonical_request);
            String signature = SqsSender.calculateTheSignature(string_to_sign);
            String authorization_header = SqsSender.addSigningInfoToTheRequest(signature);
    
            SqsSender.sendRequest(authorization_header, amz_date, request_parameters, endpoint);
        }
    
        /**
         * @param authorization_header
         * @param amz_date
         * @param request_parameters
         * @param endpoint
         */
        @future(Callout=true)
        public static void sendRequest(String authorization_header, String amz_date, String request_parameters, String endpoint){
            Http http = new Http();
            HttpRequest request = new HttpRequest();
            System.debug('endpoint: '+endpoint);
            request.setEndpoint(endpoint);
            request.setMethod('POST');
            request.setHeader('Content-Type', 'application/x-www-form-urlencoded');
            request.setHeader('Authorization', authorization_header);
            request.setHeader('x-amz-date', amz_date);
            
            System.debug('request_parameters: '+request_parameters);
            // Set the body as a JSON object
            request.setBody(request_parameters);
            HttpResponse response = http.send(request);
            // Parse the JSON response
            if (response.getStatusCode() != 200) {
                System.debug('The status code returned was not expected: ' +
                        response.getStatusCode() + ' ' + response.getStatus());
                System.debug(response.getBody());
            } else {
                System.debug('message sent successfully to SQS');
                System.debug(response.getBody());
            } 
        }
    
        // http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
        private static String createCanonicalRequest() {
    
            String host = aws_service + '.' + aws_region + '.amazonaws.com';
    
            // Step 1 is to define the verb (GET, POST, etc.)
            String method = 'POST';
    
            // Step 2: Create canonical URI--the part of the URI from domain to query
            String canonical_uri = '/' + aws_account_id + '/' + aws_queue_name;
    
            // Step 3: Create the canonical query string. In this example, request
            // parameters are passed in the body of the request and the query string  is blank.
            String canonical_querystring = EncodingUtil.urlEncode('', 'UTF-8');
    
            // Step 4: Create the canonical headers. Header names must be trimmed
            // and lowercase, and sorted in code point order from low to high.
            // Note that there is a trailing n
            String canonical_headers = 'content-type:' + content_type + 'n' + 'host:' + host + 'n' + 'x-amz-date:' + amz_date + 'n';
    
            // Step 5: Create the list of signed headers. This lists the headers
            // in the canonical_headers list, delimited with ";" and in alpha order.
            String signed_headers = 'content-type;host;x-amz-date';
    
            // Step 6: Create payload hash. In this example, the payload
            // (body of the request) contains the request parameters.
            String payload_hash = hashLibSha256(request_parameters);
    
            // Step 7: Combine elements to create canonical request
            String canonical_request =
                    method + 'n' +
                            canonical_uri + 'n' +
                            canonical_querystring + 'n' +
                            canonical_headers + 'n' +
                            signed_headers + 'n' +
                            payload_hash;
    
            return canonical_request;
        }
    
        private static String createTheStringToSign(String canonical_request) {
            // Match the algorithm to the hashing algorithm you use,
            // either SHA-1 or SHA-256 (recommended)
            String algorithm = 'AWS4-HMAC-SHA256';
            String credential_scope = date_stamp + '/' + aws_region + '/' + aws_service + '/' + 'aws4_request';
            String string_to_sign =
                    algorithm + 'n' +
                            amz_date + 'n' +
                            credential_scope + 'n' +
                            hashLibSha256(canonical_request);
            return string_to_sign;
        }
    
        private static String calculateTheSignature(String string_to_sign) {
            // Create the signing key using the function defined above.
            Blob signing_key = getSignatureKey(secret_key, date_stamp, aws_region, aws_service);
    
            // Sign the string_to_sign using the signing_key
            String signature = EncodingUtil.convertToHex(Crypto.generateMac('HmacSHA256', Blob.valueof(string_to_sign), signing_key));
            return signature;
        }
    
        private static String addSigningInfoToTheRequest(String signature) {
            String credential_scope = date_stamp + '/' + aws_region + '/' + aws_service + '/' + 'aws4_request';
            String signed_headers = 'content-type;host;x-amz-date';
            String algorithm = 'AWS4-HMAC-SHA256';
            // Put the signature information in a header named Authorization.
            String authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' + 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature;
            return authorization_header;
        }
        private static Blob getSignatureKey(String key, String date_stamp, String region_name, String service_name) {
            Blob kDate = sign(date_stamp, Blob.valueof('AWS4' + key));
            Blob kRegion = sign(region_name, kDate);
            Blob kService = sign(service_name, kRegion);
            Blob kSigning = sign('aws4_request', kService);
            return kSigning;
        }
        private static Blob sign(String data, Blob key) {
            return Crypto.generateMac('HmacSHA256', Blob.valueOf(data), key);
        }
        private static String hashLibSha256(String message) {
            return EncodingUtil.convertToHex(Crypto.generateDigest('SHA-256', Blob.valueOf(message)));
        }
    }

    How to call it

    SqsSender.SendMessage('{"entity":"user","data":{"id":"1", "name":"user from salesforce"}}', 'user', '1');

    By following these simple steps, you can easily send a message to an AWS SQS queue from a Salesforce Apex class. This integration can be extremely useful when you need to decouple components of a large application and enable efficient message transfer between them. With Salesforce and AWS, sky’s the limit when it comes to innovation and collaboration.


    Based on https://github.com/arthurimirzian/salesforce-aws-sqs/blob/master/Sqs.cls