• Yogesh Biyani
  • NEWBIE
  • 120 Points
  • Member since 2015

  • Chatter
    Feed
  • 0
    Best Answers
  • 4
    Likes Received
  • 0
    Likes Given
  • 77
    Questions
  • 69
    Replies
I have created a Schedule-Triggered flow on Duplicate Record Set to convert a new lead into an existing contact and it works. However the same flow when converted to Record-Triggered flow does not work. Any idea why this would be the case? 

Here is the Schedule-Triggered flow. User-added image
I am writing a trigger to prevent detetion of certain accounts 
trigger doNotDelete on Account (before delete) {
    // Prevent the deletion of accounts if it is a customer
    for (Account a : Trigger.old) {
       if(a.Customer_ID__c!=NULL)
            a.adderror('Cannot delete Active Account!');
    }
    
}
How do I write a test class to this success of the trigger? 
@isTest 
public class doNotDeleteTest {
    
    @isTest public static void
        deleteTest()
    {
        Account a =new Account(Name='Test');
        a.Customer_ID__c =1234;
        insert a;
        
        try {
            delete a;
        }
        catch (Exception e) {
   		   System.debug(e.getTypeName());
           System.debug(e.getMessage());
                                          
        }
        finally {
            // Something executed whether there was an error or not
        }
        
    }
}
I am looking for an way to present adhoc data based on a field value.  How can I do this? For e.g. when the country is UK, show the full country name United Kingdom, channel manager, sales rep for this region.

Currently this data is not is a record but we can either put this is a Custom Metadata or a Custom object.  
I currently have a detail page button which call following VF page 
<apex:page standardController="Contact_Preference__c" extensions="myContactPreferenceControllerExtension" action="{!autoRun}">
   
    <apex:sectionHeader title="Auto-Running Apex Code"/>
    <apex:outputPanel >
        You tried calling Apex Code from a button.  If you see this page, something went wrong.  You should have 
        been redirected back to the record you clicked the button from.
       
    </apex:outputPanel>
</apex:page>
How can this be converted to a list view button without additional code? i.e. select all the records from the list view and call autorun for each record? 

Yogesh
I am currently using following apex code to check if the user exists in a discourse site. How do I set up the named credentials so that I remove the username/key from this code ?
HttpRequest req3 = new HttpRequest();
req3.setEndpoint('https://forumname/admin/users/list/all.json?&email=' + emailAddress);
req3.setMethod('GET');
req3.setHeader('api-username','myusername');
req3.setHeader('api-key','myapikey');

Http http3 = new Http();
HTTPResponse res3 = new HTTPResponse();

if (Test.isRunningTest() && (mock!=null)) {
res3 = mock.respond(req3);
} else {
res3= http3.send(req3);
} 

System.debug(res3.getBody().length());
if(res3.getBody().length()==2)
    System.debug('Discourse Not found');
else 
{
    System.debug(res3.getBody());
    System.debug('Discourse found ');   
    Discourse=true;
}

TIA
I am trying to deploy changes to the States/Country picklist via workbench and it fails with "No package.xml found" message. I am not sure what I am doing wrong.  I am on mac and ensured that the folder __MACOS is not in the folder as suggested in this article. (https://medium.com/@wangyidan621/salesforce-workbench-zip-deployment-no-package-xml-found-error-on-mac-ec7ce49a7126)

Here is the link to the package (https://drive.google.com/file/d/1GSTb0aN0hv2TMTVi_I6AgkdaMPTqLVGS/view?usp=sharing)
User-added image
I am trying to install https://github.com/ericrsmith35/Flow-PB-List-View-with-Batch-Delete using Deploy to Salesforce button in Production. However, this runs all tests and I am encountring some test failures in legacy code. While I will review the failures and fix it I believe there is a way to install packages from VS Code to production and run only specific tests related to this package. Where can I find detailed steps to do the same? 
I have a flow that takes a recordId and works well for the Contact lighting page by passing in the {!Record.Id}. How can I use the same flow on the Case lighting page and pass in the Case Contact Id? 
I am using the following code to create an access token. How do I convert this to named credentials? 

TIA
String uuidAPIKeyString = 'somesecret:somekey';
        
        Blob uuidBlob = Blob.valueof(uuidAPIKeyString);
        
        String uuidAuthorization = 'basic ' + EncodingUtil.base64Encode(uuidBlob);
        HttpRequest uuidRequest = new HttpRequest();
        
        uuidRequest.setEndpoint('https://api.somedomain.com/token');
        uuidRequest.setMethod('POST');
        
        uuidRequest.setBody('grant_type=client_credentials');
        uuidRequest.setHeader('Authorization', uuidAuthorization);
        uuidRequest.setHeader('Content-Type', 'application/x-www-form-urlencoded');
        
        Http http = new Http();
        
        HTTPResponse res = new HTTPResponse();
        
        if (Test.isRunningTest() && (mock!=null)) {
            System.debug('Mock Response');
            res = mock.respond(uuidRequest);
            
        } else {
            System.debug('Callout Response');
            res= http.send(uuidRequest);
            
        }
        
        System.debug(res.getBody());     
        
        
        uuidAuthorizationJSON2Apex objuuidAuthJSON2Apex = new 
        uuidAuthorizationJSON2Apex(System.JSON.createParser(res.getBody()));
        System.debug(objuuidAuthJSON2Apex.access_token);
 
        String access_token= objuuidAuthJSON2Apex.access_token;
        system.debug(access_token);
How I insert a related object using the external id field on the parent object?

I have a custom parent object License__c and related object Activation__c which have a Related_License__c lookup field to the License__c object and the relations ship name is License Activations.

License__c has l_id__c external id field. I would like to import the Activation__c object using the l_id__c field so that the parent-child relationship is automatically created.

This works using the data import wizard but fails when I try to import use the Bulk Api 1.0 

Here is the sample CVS file 

Activation_Id__c,License_Activations__r.l_id__c 
9249,1665029 
9250,1665029 
I have created a class to parse text data and want to use Static Resource (text file) to import the data for testing. How do I use test.loaddata so that it is imported as a String?  
I am currently using Apex to query an endpoint and parse the JSON result. I am making a call to an endpoint with consumer key/secret to get the access token and then using the token to query the final endpoint as shown in the code below.

I would like to convert this to External Service so that I can use it in a flow. Can someone give me detailed steps on how to convert this to external service? 

TIA.
public static void findidbyEmail(String email)
    {
        String idAPIKeyString = 'KEY:SECRET';
        
        Blob idBlob = Blob.valueof(idAPIKeyString);
        
        String idAuthorization = 'basic ' + EncodingUtil.base64Encode(idBlob);
        HttpRequest idRequest = new HttpRequest();
        
        idRequest.setEndpoint('https://api.sitename.com/token');
        idRequest.setMethod('POST');
        
        idRequest.setBody('grant_type=client_credentials');
        idRequest.setHeader('Authorization', idAuthorization);
        idRequest.setHeader('Content-Type', 'application/x-www-form-urlencoded');
        
        Http http = new Http();
        
        HTTPResponse res = new HTTPResponse();
        
        if (Test.isRunningTest() && (mock!=null)) {
            System.debug('Mock Response');
            res = mock.respond(idRequest);
            
        } else {
            System.debug('Callout Response');
            res= http.send(idRequest);
            
        }
        
        
        System.debug(res.getBody());     
        
        
        idAuthorizationJSON2Apex objidAuthJSON2Apex = new idAuthorizationJSON2Apex(System.JSON.createParser(res.getBody()));
        System.debug(objidAuthJSON2Apex.access_token);
  
        String access_token= objidAuthJSON2Apex.access_token;
        system.debug(access_token);
        
        
        //    Get the id        
        HttpRequest req2= new HttpRequest();
        
        req2.setEndpoint('https://api.sitename.com/users?email='+email);
        req2.setMethod('GET');
        req2.setHeader('Authorization', 'bearer '+ access_token);
        
        req2.setHeader('Content-Type', 'application/json');
        
        Http http2 = new Http();
        
        HTTPResponse res2 = new HTTPResponse();
        
        if (Test.isRunningTest() && (mock!=null)) {
            res2 = mock.respond(req2);
            System.debug('Mock Response ' + res2);
        } else {
            res2= http.send(req2);
            System.debug('Callout Response '+res2);
        }
        
        
        if(res2.getBody()=='')
            System.debug('id Not found');
        else 
        {
            System.debug(res2.getBody());
            System.debug('id found');
            idJSON2Apex objidJSON2Apex = new idJSON2Apex(System.JSON.createParser(res2.getBody()));
            System.debug(objidJSON2Apex.theEmail.uniqueid);
           
        } 
    }

 
This test fails with the above message 
 
@isTest
public class AmplitudeApiCallsTest {

    @testSetup static void setup() {
        // Create common test accounts
        List<Account> testAccts = new List<Account>();
        for(Integer i=0;i<2;i++) {
            testAccts.add(new Account(Name = 'TestAcct'+i,Account_FCH_Id__c= '123456789'+i));
            
        }
        insert testAccts;        
    }

    @isTest
     public static void  AmplitudeCallOut()
    {
       
        
        String fakeAmplitudejson = '{\"novaRuntime\": 309, \"minSampleRate\": 1.0, \"throttleTime\": 2, \"partialMergedAndNewUserInformation\": false, \"timeComputed\": 1584390210280, \"wasCached\": false, \"backend\": \"novaV2\", \"realtimeDataMissing\": false, \"novaRequestDuration\": 378, \"queryIds\": [\"OwY0CjZuIC\"], \"hitChunkGroupByLimit\": false, \"prunedResult\": false, \"transformationIds\": [], \"novaCost\": 900, \"subcluster\": 3, \"timedOutRealtimeData\": false, \"data\": {\"seriesIntervals\": {}, \"seriesCollapsed\": [[{\"setId\": \"\", \"value\": 72002}]], \"xValues\": [\"2019-01-01\", \"2019-02-01\", \"2019-03-01\", \"2019-04-01\", \"2019-05-01\", \"2019-06-01\", \"2019-07-01\", \"2019-08-01\", \"2019-09-01\", \"2019-10-01\", \"2019-11-01\", \"2019-12-01\", \"2020-01-01\", \"2020-02-01\", \"2020-03-01\"], \"seriesLabels\": [0], \"series\": [[1, 2334, 6194, 9963, 13706, 16731, 20586, 23982, 27697, 32154, 34940, 36863, 44026, 48629, 43613]]}, \"cacheFreshness\": \"FRESH\"}';
        SingleRequestMock fakeAmplitudeResponse = new SingleRequestMock(200,
                                                                      'Complete',
                                                                      fakeAmplitudejson,
                                                                      null);
        Test.setMock(HttpCalloutMock.class, fakeAmplitudeResponse);
        
     
    
        List<Account> acc1=[Select id,Account_FCH_Id__c from Account Where Account_FCH_Id__c='1234567891' LIMIT 1];
		system.debug(AmplitudeApiCalls.dataForChartId(acc1[0].id));
        
        List<Account> acc2=[Select id,Account_FCH_Id__c from Account Where Account_FCH_Id__c='' LIMIT 1];
        system.debug(AmplitudeApiCalls.dataForChartId(acc2[0].id));
      
        
    }
}

 
I tried the following today in apex anonymous window and I see an unexpected behavior 
System.debug(Datetime.now());
System.debug(Datetime.now().format('YYYY-MM-DD'));
Why id the DD 84 when I use System.debug(Datetime.now().format('YYYY-MM-DD'))? 
13:09:14.1 (2508337)|USER_DEBUG|[1]|DEBUG|2020-03-24 19:09:14
13:09:14.1 (2587013)|USER_DEBUG|[2]|DEBUG|2020-03-84
Based on this (https://success.salesforce.com/answers?id=9063A000000pzg0QAA) I have created a chart LWC but I have to always resize my window for the chart to display it correctly. What am I doing wrong? TIA.

Here is the Apex Class 
public with sharing class TestData {
     @AuraEnabled(cacheable=true)
    public static Map<String,Integer> dataForChartSample() {
        
       Map<String,Integer> chartData= new Map<String,Integer>();
       for (integer i =0;i< 10; i++)
       {
           chartData.put(String.valueOf(i),Integer.valueof((math.random() * 10)));
       }
       system.debug(chartData);
       return chartData;
    }
}

Here is the component js 
 
import { LightningElement,wire,track } from "lwc";
import { ShowToastEvent } from "lightning/platformShowToastEvent";
import { loadScript } from "lightning/platformResourceLoader";
import ChartJS from "@salesforce/resourceUrl/ChartJS";
import dataForChart from "@salesforce/apex/TestData.dataForChartSample";


export default class ChartDemo extends LightningElement {
    @track mapData= [];
    cLabel=[];
    cData=[];

    @wire(dataForChart)
    wiredResult(result) { 
        if (result.data) {
            //mapData = [];
            var conts = result.data;
            for(var key in conts){
                this.cLabel.push(key);
                this.cData.push(conts[key]);
            }

        }
    }
    
    chartJSLoaded;
    chart;

    constructor() {
        super();
        this.chartJSLoaded = false;
    }

    renderedCallback() {
        if (!this.chartJSLoaded) {
            loadScript(this, ChartJS)
                .then(() => {
                    this.chartJSLoaded = true;
                    var labels1=this.cLabel;
                    var data1=this.cData;
                    console.log( "This is the Label");
                    console.log(labels1);
                    console.log( "This is the Data");
                    console.log(data1);
                    
                    this._buildChart2(labels1,data1);
                })
                .catch(error => {
                    this.dispatchEvent(
                        new ShowToastEvent({
                            title: "Error Loading Chart JS",
                            message: error.message,
                            variant: "error"
                        })
                    );
                });
        }
    }

    _buildChart2(labels1,data1) {
        let canvas = this.template.querySelector("canvas");
        let context = canvas.getContext("2d");

        this.chart = new window.Chart(context, {
            type: "bar",
            data: {
                labels: labels1,
                datasets: [
                    {
                        label: "# of activations",
                        data: data1,
                        borderWidth: 1
                    }
                ]
            },
            options: {
                scales: {
                    yAxes: [
                        {
                            ticks: {
                                beginAtZero: true
                            }
                        }
                    ]
                }
            }
        });
    }

    _buildChart() {
        let canvas = this.template.querySelector("canvas");
        let context = canvas.getContext("2d");

        this.chart = new window.Chart(context, {
            type: "bar",
            data: {
                labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
                datasets: [
                    {
                        label: "# of Votes",
                        data: [12, 19, 3, 5, 2, 3],
                        backgroundColor: [
                            "rgba(255, 99, 132, 0.2)",
                            "rgba(54, 162, 235, 0.2)",
                            "rgba(255, 206, 86, 0.2)",
                            "rgba(75, 192, 192, 0.2)",
                            "rgba(153, 102, 255, 0.2)",
                            "rgba(255, 159, 64, 0.2)"
                        ],
                        borderColor: [
                            "rgba(255, 99, 132, 1)",
                            "rgba(54, 162, 235, 1)",
                            "rgba(255, 206, 86, 1)",
                            "rgba(75, 192, 192, 1)",
                            "rgba(153, 102, 255, 1)",
                            "rgba(255, 159, 64, 1)"
                        ],
                        borderWidth: 1
                    }
                ]
            },
            options: {
                scales: {
                    yAxes: [
                        {
                            ticks: {
                                beginAtZero: true
                            }
                        }
                    ]
                }
            }
        });
    }
}

component html
<template>
    <div class="slds-theme_default">
        <canvas width="400" height="400" lwc:dom="manual"></canvas>
    </div>
</template>

compoment xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>46.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
      <target>lightning__RecordPage</target>
      <target>lightning__AppPage</target>
      <target>lightning__HomePage</target>
  </targets>
</LightningComponentBundle>

 
I have converted the following python script to apex code and I get the HTTP 405 method not allowed error. Can someone review and let me know what is wrong? 

Python  
url = 'https://amplitude.com/api/2/events/segmentation'

# json parameters for querying monthly uniques for Launched App  between dates
# Add gp: in front of custom user_property
params1 = {
    'e': '{"event_type":"Launched Application","filters":[{"subprop_type":"user","subprop_key":"gp:app_name","subprop_op":"is","subprop_value":["su-desktop"]}, \
         {"subprop_type":"user","subprop_key":"gp:sku","subprop_op":"contains","subprop_value":["PRO"]}]}',
    'm': 'uniques',
    'start': '20190101',
    'end': '20200131',
    'i':'30'
}

# Set to -300000, -3600000, 1, 7, or 30 for real-time, hourly, daily, weekly, and monthly counts,



r = requests.get(url, params = params1,  auth=(api_key, secret_key))
response = r.json()
print( response)
#print r.status_code
#print r.url
Apex
 
HttpRequest req4= new HttpRequest();
req4.setEndpoint('https://amplitude.com/api/2/events/segmentation');
req4.setMethod('GET');
Blob myBlob1 = Blob.valueof(api_key + ':'+ secret_key);
String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(myBlob1);
req4.setHeader('Authorization', authorizationHeader);

String params1='{"e": "{\"event_type\":\"Launched Application\",\"filters\":[{\"subprop_type\":\"user\",\"subprop_key\":\"gp:app_name\",\"subprop_op\":\"is\",\"subprop_value\":[\"su-desktop\"]},{\"subprop_type\":\"user\",\"subprop_key\":\"gp:sku\",\"subprop_op\":\"contains\",\"subprop_value\":[\"PRO\"]}]}","end": "20200131","i": "30","m": "uniques","start": "20190101"}';


req4.setBody(params1);

Http http4 = new Http();
HTTPResponse res4 = http4.send(req4);
System.debug(res4.getBody());
How do I convert the following python code into json body to be sent with the HTTP request? 

TIA

 
params1 = {
        'e': '{"event_type":"Launched Application","filters":[{"subprop_type":"user","subprop_key":"gp:app_name","subprop_op":"is","subprop_value":["desktop"]}, \
             {"subprop_type":"user","subprop_key":"gp:sku","subprop_op":"contains","subprop_value":["SPEC"]}]}',
        'm': 'uniques',
        'start': '20190101',
        'end': '20200131',
        'i':'30'
    }

 
We are using this toolkit to allow the customer to submit cases and are using the Attachment object to submit relevant files. Does anyone have a sample that shows how to use Salesforce Files? 
What is the SOQL to find all the subscribed/scheduled dashboards? 
I am a bit confused about the relationship between Task and EmailMessage objects.

One can find the Task from EmailMessage using ActivityId but not sure how to get the EmailMessage from Task. Can someone show how to get the EmailMessage from the Task object? 
I am currently using following apex code to check if the user exists in a discourse site. How do I set up the named credentials so that I remove the username/key from this code ?
HttpRequest req3 = new HttpRequest();
req3.setEndpoint('https://forumname/admin/users/list/all.json?&email=' + emailAddress);
req3.setMethod('GET');
req3.setHeader('api-username','myusername');
req3.setHeader('api-key','myapikey');

Http http3 = new Http();
HTTPResponse res3 = new HTTPResponse();

if (Test.isRunningTest() && (mock!=null)) {
res3 = mock.respond(req3);
} else {
res3= http3.send(req3);
} 

System.debug(res3.getBody().length());
if(res3.getBody().length()==2)
    System.debug('Discourse Not found');
else 
{
    System.debug(res3.getBody());
    System.debug('Discourse found ');   
    Discourse=true;
}

TIA
I tried the following today in apex anonymous window and I see an unexpected behavior 
System.debug(Datetime.now());
System.debug(Datetime.now().format('YYYY-MM-DD'));
Why id the DD 84 when I use System.debug(Datetime.now().format('YYYY-MM-DD'))? 
13:09:14.1 (2508337)|USER_DEBUG|[1]|DEBUG|2020-03-24 19:09:14
13:09:14.1 (2587013)|USER_DEBUG|[2]|DEBUG|2020-03-84
Here is the Apex Class
public class AssignLeadsUsingAssignmentRules
{
    @InvocableMethod
    public static void LeadAssign(List<Id> LeadIds)
    {
            Database.DMLOptions dmo = new Database.DMLOptions();
            dmo.assignmentRuleHeader.useDefaultRule= true;          
            Lead Leads=[select id,OwnerId from lead where lead.id in :LeadIds];
            Leads.setOptions(dmo);
        	system.debug('Before Update Lead Details' + Leads);
         	Database.update(Leads,dmo);
        	Lead Leads2=[select id,OwnerId from lead where lead.id in :LeadIds];
        	system.debug('After Update Lead Details' + Leads2);
   }
}

Here is the test class 
@isTest 
      public class TestAssignLeadsUsingAssignmentRules{
      static testMethod void createnewlead() {
     
   //   Test.startTest();    
      Lead leadToCreate =new Lead();
      List<id> Ids= New List<Id>();
    //  leadToCreate.ownerid= userToCreate.id;
      leadToCreate.ownerid= UserInfo.getUserId();  
      leadToCreate.LastName ='Sample1';
      leadToCreate.Email='Someone@somewhere.com';
      leadToCreate.Company='OneTwo34';
      leadToCreate.LeadSource='Partner Referral';
      leadToCreate.Country='IN';
      leadToCreate.Source_Last_Lead_Source_Detail__c='Form - Contact Form';
          
      insert leadToCreate; 
      
      Ids.add(leadToCreate.id);
      AssignLeadsUsingAssignmentRules.leadAssign(Ids);
      System.assertEquals('00G1W000002RyhMUAS', leadToCreate.OwnerId, 'Something is wrong');

 	//  Test.stopTest();
      
   }
}

The test class fails as shown below User-added imageAs you can see the debug log shows the lead OwnerId has changed but the change does not persist outside the class in the test. What am I missing? 
I was planning to bring in data from an external database and found that it will cost us 13+GB of storage. The data has more than 7 million records across 4 tables, so at 2kb per record, the total cost would be 7000000*2/(1024*1024) = 13.4 GB. We would like to search and report on the data and add associated contacts and accounts to campaigns. What are our options?  
I am writing a trigger to prevent detetion of certain accounts 
trigger doNotDelete on Account (before delete) {
    // Prevent the deletion of accounts if it is a customer
    for (Account a : Trigger.old) {
       if(a.Customer_ID__c!=NULL)
            a.adderror('Cannot delete Active Account!');
    }
    
}
How do I write a test class to this success of the trigger? 
@isTest 
public class doNotDeleteTest {
    
    @isTest public static void
        deleteTest()
    {
        Account a =new Account(Name='Test');
        a.Customer_ID__c =1234;
        insert a;
        
        try {
            delete a;
        }
        catch (Exception e) {
   		   System.debug(e.getTypeName());
           System.debug(e.getMessage());
                                          
        }
        finally {
            // Something executed whether there was an error or not
        }
        
    }
}
I am trying to deploy changes to the States/Country picklist via workbench and it fails with "No package.xml found" message. I am not sure what I am doing wrong.  I am on mac and ensured that the folder __MACOS is not in the folder as suggested in this article. (https://medium.com/@wangyidan621/salesforce-workbench-zip-deployment-no-package-xml-found-error-on-mac-ec7ce49a7126)

Here is the link to the package (https://drive.google.com/file/d/1GSTb0aN0hv2TMTVi_I6AgkdaMPTqLVGS/view?usp=sharing)
User-added image
I am trying to install https://github.com/ericrsmith35/Flow-PB-List-View-with-Batch-Delete using Deploy to Salesforce button in Production. However, this runs all tests and I am encountring some test failures in legacy code. While I will review the failures and fix it I believe there is a way to install packages from VS Code to production and run only specific tests related to this package. Where can I find detailed steps to do the same? 
I am using the following code to create an access token. How do I convert this to named credentials? 

TIA
String uuidAPIKeyString = 'somesecret:somekey';
        
        Blob uuidBlob = Blob.valueof(uuidAPIKeyString);
        
        String uuidAuthorization = 'basic ' + EncodingUtil.base64Encode(uuidBlob);
        HttpRequest uuidRequest = new HttpRequest();
        
        uuidRequest.setEndpoint('https://api.somedomain.com/token');
        uuidRequest.setMethod('POST');
        
        uuidRequest.setBody('grant_type=client_credentials');
        uuidRequest.setHeader('Authorization', uuidAuthorization);
        uuidRequest.setHeader('Content-Type', 'application/x-www-form-urlencoded');
        
        Http http = new Http();
        
        HTTPResponse res = new HTTPResponse();
        
        if (Test.isRunningTest() && (mock!=null)) {
            System.debug('Mock Response');
            res = mock.respond(uuidRequest);
            
        } else {
            System.debug('Callout Response');
            res= http.send(uuidRequest);
            
        }
        
        System.debug(res.getBody());     
        
        
        uuidAuthorizationJSON2Apex objuuidAuthJSON2Apex = new 
        uuidAuthorizationJSON2Apex(System.JSON.createParser(res.getBody()));
        System.debug(objuuidAuthJSON2Apex.access_token);
 
        String access_token= objuuidAuthJSON2Apex.access_token;
        system.debug(access_token);
How I insert a related object using the external id field on the parent object?

I have a custom parent object License__c and related object Activation__c which have a Related_License__c lookup field to the License__c object and the relations ship name is License Activations.

License__c has l_id__c external id field. I would like to import the Activation__c object using the l_id__c field so that the parent-child relationship is automatically created.

This works using the data import wizard but fails when I try to import use the Bulk Api 1.0 

Here is the sample CVS file 

Activation_Id__c,License_Activations__r.l_id__c 
9249,1665029 
9250,1665029 
I have created a class to parse text data and want to use Static Resource (text file) to import the data for testing. How do I use test.loaddata so that it is imported as a String?  
I am currently using Apex to query an endpoint and parse the JSON result. I am making a call to an endpoint with consumer key/secret to get the access token and then using the token to query the final endpoint as shown in the code below.

I would like to convert this to External Service so that I can use it in a flow. Can someone give me detailed steps on how to convert this to external service? 

TIA.
public static void findidbyEmail(String email)
    {
        String idAPIKeyString = 'KEY:SECRET';
        
        Blob idBlob = Blob.valueof(idAPIKeyString);
        
        String idAuthorization = 'basic ' + EncodingUtil.base64Encode(idBlob);
        HttpRequest idRequest = new HttpRequest();
        
        idRequest.setEndpoint('https://api.sitename.com/token');
        idRequest.setMethod('POST');
        
        idRequest.setBody('grant_type=client_credentials');
        idRequest.setHeader('Authorization', idAuthorization);
        idRequest.setHeader('Content-Type', 'application/x-www-form-urlencoded');
        
        Http http = new Http();
        
        HTTPResponse res = new HTTPResponse();
        
        if (Test.isRunningTest() && (mock!=null)) {
            System.debug('Mock Response');
            res = mock.respond(idRequest);
            
        } else {
            System.debug('Callout Response');
            res= http.send(idRequest);
            
        }
        
        
        System.debug(res.getBody());     
        
        
        idAuthorizationJSON2Apex objidAuthJSON2Apex = new idAuthorizationJSON2Apex(System.JSON.createParser(res.getBody()));
        System.debug(objidAuthJSON2Apex.access_token);
  
        String access_token= objidAuthJSON2Apex.access_token;
        system.debug(access_token);
        
        
        //    Get the id        
        HttpRequest req2= new HttpRequest();
        
        req2.setEndpoint('https://api.sitename.com/users?email='+email);
        req2.setMethod('GET');
        req2.setHeader('Authorization', 'bearer '+ access_token);
        
        req2.setHeader('Content-Type', 'application/json');
        
        Http http2 = new Http();
        
        HTTPResponse res2 = new HTTPResponse();
        
        if (Test.isRunningTest() && (mock!=null)) {
            res2 = mock.respond(req2);
            System.debug('Mock Response ' + res2);
        } else {
            res2= http.send(req2);
            System.debug('Callout Response '+res2);
        }
        
        
        if(res2.getBody()=='')
            System.debug('id Not found');
        else 
        {
            System.debug(res2.getBody());
            System.debug('id found');
            idJSON2Apex objidJSON2Apex = new idJSON2Apex(System.JSON.createParser(res2.getBody()));
            System.debug(objidJSON2Apex.theEmail.uniqueid);
           
        } 
    }

 
This test fails with the above message 
 
@isTest
public class AmplitudeApiCallsTest {

    @testSetup static void setup() {
        // Create common test accounts
        List<Account> testAccts = new List<Account>();
        for(Integer i=0;i<2;i++) {
            testAccts.add(new Account(Name = 'TestAcct'+i,Account_FCH_Id__c= '123456789'+i));
            
        }
        insert testAccts;        
    }

    @isTest
     public static void  AmplitudeCallOut()
    {
       
        
        String fakeAmplitudejson = '{\"novaRuntime\": 309, \"minSampleRate\": 1.0, \"throttleTime\": 2, \"partialMergedAndNewUserInformation\": false, \"timeComputed\": 1584390210280, \"wasCached\": false, \"backend\": \"novaV2\", \"realtimeDataMissing\": false, \"novaRequestDuration\": 378, \"queryIds\": [\"OwY0CjZuIC\"], \"hitChunkGroupByLimit\": false, \"prunedResult\": false, \"transformationIds\": [], \"novaCost\": 900, \"subcluster\": 3, \"timedOutRealtimeData\": false, \"data\": {\"seriesIntervals\": {}, \"seriesCollapsed\": [[{\"setId\": \"\", \"value\": 72002}]], \"xValues\": [\"2019-01-01\", \"2019-02-01\", \"2019-03-01\", \"2019-04-01\", \"2019-05-01\", \"2019-06-01\", \"2019-07-01\", \"2019-08-01\", \"2019-09-01\", \"2019-10-01\", \"2019-11-01\", \"2019-12-01\", \"2020-01-01\", \"2020-02-01\", \"2020-03-01\"], \"seriesLabels\": [0], \"series\": [[1, 2334, 6194, 9963, 13706, 16731, 20586, 23982, 27697, 32154, 34940, 36863, 44026, 48629, 43613]]}, \"cacheFreshness\": \"FRESH\"}';
        SingleRequestMock fakeAmplitudeResponse = new SingleRequestMock(200,
                                                                      'Complete',
                                                                      fakeAmplitudejson,
                                                                      null);
        Test.setMock(HttpCalloutMock.class, fakeAmplitudeResponse);
        
     
    
        List<Account> acc1=[Select id,Account_FCH_Id__c from Account Where Account_FCH_Id__c='1234567891' LIMIT 1];
		system.debug(AmplitudeApiCalls.dataForChartId(acc1[0].id));
        
        List<Account> acc2=[Select id,Account_FCH_Id__c from Account Where Account_FCH_Id__c='' LIMIT 1];
        system.debug(AmplitudeApiCalls.dataForChartId(acc2[0].id));
      
        
    }
}

 
I tried the following today in apex anonymous window and I see an unexpected behavior 
System.debug(Datetime.now());
System.debug(Datetime.now().format('YYYY-MM-DD'));
Why id the DD 84 when I use System.debug(Datetime.now().format('YYYY-MM-DD'))? 
13:09:14.1 (2508337)|USER_DEBUG|[1]|DEBUG|2020-03-24 19:09:14
13:09:14.1 (2587013)|USER_DEBUG|[2]|DEBUG|2020-03-84
I have converted the following python script to apex code and I get the HTTP 405 method not allowed error. Can someone review and let me know what is wrong? 

Python  
url = 'https://amplitude.com/api/2/events/segmentation'

# json parameters for querying monthly uniques for Launched App  between dates
# Add gp: in front of custom user_property
params1 = {
    'e': '{"event_type":"Launched Application","filters":[{"subprop_type":"user","subprop_key":"gp:app_name","subprop_op":"is","subprop_value":["su-desktop"]}, \
         {"subprop_type":"user","subprop_key":"gp:sku","subprop_op":"contains","subprop_value":["PRO"]}]}',
    'm': 'uniques',
    'start': '20190101',
    'end': '20200131',
    'i':'30'
}

# Set to -300000, -3600000, 1, 7, or 30 for real-time, hourly, daily, weekly, and monthly counts,



r = requests.get(url, params = params1,  auth=(api_key, secret_key))
response = r.json()
print( response)
#print r.status_code
#print r.url
Apex
 
HttpRequest req4= new HttpRequest();
req4.setEndpoint('https://amplitude.com/api/2/events/segmentation');
req4.setMethod('GET');
Blob myBlob1 = Blob.valueof(api_key + ':'+ secret_key);
String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(myBlob1);
req4.setHeader('Authorization', authorizationHeader);

String params1='{"e": "{\"event_type\":\"Launched Application\",\"filters\":[{\"subprop_type\":\"user\",\"subprop_key\":\"gp:app_name\",\"subprop_op\":\"is\",\"subprop_value\":[\"su-desktop\"]},{\"subprop_type\":\"user\",\"subprop_key\":\"gp:sku\",\"subprop_op\":\"contains\",\"subprop_value\":[\"PRO\"]}]}","end": "20200131","i": "30","m": "uniques","start": "20190101"}';


req4.setBody(params1);

Http http4 = new Http();
HTTPResponse res4 = http4.send(req4);
System.debug(res4.getBody());
How do I convert the following python code into json body to be sent with the HTTP request? 

TIA

 
params1 = {
        'e': '{"event_type":"Launched Application","filters":[{"subprop_type":"user","subprop_key":"gp:app_name","subprop_op":"is","subprop_value":["desktop"]}, \
             {"subprop_type":"user","subprop_key":"gp:sku","subprop_op":"contains","subprop_value":["SPEC"]}]}',
        'm': 'uniques',
        'start': '20190101',
        'end': '20200131',
        'i':'30'
    }

 
Here is the Apex Class
public class AssignLeadsUsingAssignmentRules
{
    @InvocableMethod
    public static void LeadAssign(List<Id> LeadIds)
    {
            Database.DMLOptions dmo = new Database.DMLOptions();
            dmo.assignmentRuleHeader.useDefaultRule= true;          
            Lead Leads=[select id,OwnerId from lead where lead.id in :LeadIds];
            Leads.setOptions(dmo);
        	system.debug('Before Update Lead Details' + Leads);
         	Database.update(Leads,dmo);
        	Lead Leads2=[select id,OwnerId from lead where lead.id in :LeadIds];
        	system.debug('After Update Lead Details' + Leads2);
   }
}

Here is the test class 
@isTest 
      public class TestAssignLeadsUsingAssignmentRules{
      static testMethod void createnewlead() {
     
   //   Test.startTest();    
      Lead leadToCreate =new Lead();
      List<id> Ids= New List<Id>();
    //  leadToCreate.ownerid= userToCreate.id;
      leadToCreate.ownerid= UserInfo.getUserId();  
      leadToCreate.LastName ='Sample1';
      leadToCreate.Email='Someone@somewhere.com';
      leadToCreate.Company='OneTwo34';
      leadToCreate.LeadSource='Partner Referral';
      leadToCreate.Country='IN';
      leadToCreate.Source_Last_Lead_Source_Detail__c='Form - Contact Form';
          
      insert leadToCreate; 
      
      Ids.add(leadToCreate.id);
      AssignLeadsUsingAssignmentRules.leadAssign(Ids);
      System.assertEquals('00G1W000002RyhMUAS', leadToCreate.OwnerId, 'Something is wrong');

 	//  Test.stopTest();
      
   }
}

The test class fails as shown below User-added imageAs you can see the debug log shows the lead OwnerId has changed but the change does not persist outside the class in the test. What am I missing? 
We have some accounts with incorrect account team and the following query identifies all such accounts. Basically, accounts with two or more account team members with the Distributor role has incorrect teams.
Select AccountId, Account.Name, count(id) from AccountTeamMember WHERE TeamMemberRole ='Distributor License Share' AND UserId!='0051W000004SVNhQAO' Group BY AccountId, Account.Name HAVING count(id) >=2 LIMIT 2000
What is the easiest way to delete all such account teams? 

I am still learning Apex/SOQL; how do I collect the AccountIds from the above aggregate result and pass it to get all the AccountTeamMember IDs to delete? The following code in developer console fails with the following error

Invalid identifier ' '. Apex identifiers must start with an ASCII letter (a-z or A-Z) followed by any number of ASCII letters (a-z or A-Z), digits (0 - 9), '$', '_'.​​​​​​​
List<AggregateResult> results =  [Select  AccountId, Account.Name, count(id) from AccountTeamMember 
                      WHERE TeamMemberRole ='Distributor License Share' AND UserId!='0051W000004SVNhQAO' 
                      Group BY AccountId, Account.Name HAVING count(id) >=2 LIMIT 2000 ];

System.debug(results.size());

System.debug(results[0]);

Set<id > AccountIds = new Set<id>();
      
for(AggregateResult exp: results){
    AccountIds.add((Id)exp.get('AccountId'));
}



 
On the Opportunity record I have a quick action to create Contact roles. When I click on the quick action , I am opening a flow screen. And on that screen I need to prepopulate the Opportunity Id from where I came . What is the way ? 

I created a variable called recordID and set the type as input. Foe some reason that is not working. Any help ??
I have below JSON ,How can I send in my request using apex:

"objects":[
{
"fieldsToNull":["DefaultPaymentMethodId"],
"AccountNumber":"A00000036",
"Id":"2c92c0f95a4085a8015a41f4012d183e"
}
]
, "type":"Account"
I was solving this challenge and my VF code is:

<apex:page standardController="Account" recordSetVar="Accounts" >
    <apex:pageblock>
        <apex:repeat var="a" value="{!Accounts}" rendered="true"  id="account_list">
            <li>
                <apex:outputLink value="https://ap1.salesforce.com/{!a.ID}" >
                    <apex:outputText value="{!a.Name}"/>
                </apex:outputLink>
            </li>
        </apex:repeat>
    </apex:pageblock>
</apex:page>

I am getting the list of accounts as required and on clicking on any of the accouts, it redirects to that accounts detail page.
Still I am getting following error from trailhead:

"The page does not bind to the record ID value (in order to link to the record detail page)"