• Akhil Mehra
  • NEWBIE
  • 70 Points
  • Member since 2015
  • Certified Salesforce Developer
  • Self


  • Chatter
    Feed
  • 1
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 1
    Questions
  • 15
    Replies
Hi,

I have written a test class for this rest callouts but its not covering 100% code coverage. Can someone please help me

It throws me error when I run the test class 
Class.AnimalLocator.getAnimalNameById: line 16, column 1 Class.AnimalLocatorTest.testcallout: line 7, column 1

Apex class 

public class AnimalLocator {

public static string getAnimalNameById (integer i)
{
    string a;
    Http ht = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals/' + i);
        request.setMethod('GET');
        HttpResponse response = ht.send(request);
        // If the request is successful, parse the JSON response.
    if (response.getStatusCode() == 200) 
    {
            Map<String, Object> result = (Map<String, Object>)JSON.deserializeUntyped(response.getBody());
             Map<string,object> cc = (Map<string,object>) result.get('animals');
        a = (string)cc.get('name');
    }
    return a;
  }
}


Test class

@isTest
public class AnimalLocatorTest 
{
@isTest static void testcallout()
{
      Test.setMock(HttpCalloutMock.class, new AnimalLocatorMock()); 
    string response = AnimalLocator.getAnimalNameById (2); 
String expectedValue = '{"animal":{"id":2,"name":"bear","eats","berries, campers, adam seligman","says":"yum yum"}}'; 
system.assertEquals('eats', response);
   
   }
}

@isTest
global class AnimalLocatorMock implements HttpCalloutMock 
{
global HTTPResponse respond(HTTPRequest request) 
{
        // Create a fake response
         HttpResponse response = new HttpResponse(); 
     response.setHeader('Content-Type', 'application/json');
    response.setBody('{"animal":{"i":2,"name":"bear","eats":"berries, campers, adam seligman","says":"yum yum"}}'); 
        response.setStatusCode(200);
        return response;
}
}
 
  • January 29, 2016
  • Like
  • 0
Hi , 
I have a report which have 48000  records  , when i run a report using synchronous Approach in apex code , it will only return 2000 records  so in order to overcome this problem i have used filter in report but after returning 4000 records it throw exception " FATAL_ERROR System.LimitException: reports:Too many query rows: 50001 "  . (I can't Use Asynch Approach as i am using this class inside batch class).
In order to Apply Filter i am using Autonumber field and sort them in ascending order, Please have a look to my code and help me to figure out the problem , Thanks to All In Advance.


String reportId='00Of1000004jG5h'; // Report Id
Integer filterNumber=0; // Set Lower Row Limit For Filter 
boolean getAllData=False;
integer count=0;

while(getAllData==false) {
Reports.ReportDescribeResult describe = Reports.ReportManager.describeReport(reportId); // describe report metadata
            Reports.ReportMetadata reportMd = describe.getReportMetadata();
    
                string b =reportMd.getDetailColumns()[0]; //get Filtered Column From Report , it is Autonumber Field
                String column1=b;
                Integer value1=filterNumber;
                String operator1='greaterOrEqual';
    
              Reports.ReportFilter filter = reportMd.getReportFilters()[0];// get Filter and Update filter values in apex
             
            filter.setColumn(column1);
            filter.setValue(string.valueOf(value1));
            filter.setOperator(operator1);
             Integer value2=value1+2000; // Upper Limit for Second Filter
            String operator2='lessOrEqual';
                
             Reports.ReportFilter filter1 =reportMd.getReportFilters()[0]; // Second Filter to report on same column 
            filter1.setColumn(column1);
            filter1.setValue(string.valueOf(value2));
            filter1.setOperator(operator2);
    
        
           // Run a report synchronously
            Reports.reportResults ActiveISOContacts = Reports.ReportManager.runReport(reportId,reportMd, true);
            getAllData=ActiveISOContacts.getAllData();
           system.debug(ActiveISOContacts.getAllData());//this will return true and false .

           // Get the fact map from the report results
            Reports.ReportFactWithDetails factDetails = (Reports.ReportFactWithDetails)ActiveISOContacts.getFactMap().get('T!T');
            //create a list of report rows and populate it with the result rows from fact map
            List<Reports.ReportDetailRow> reportRows = factDetails.getRows();
            filterNumber =filterNumber+reportRows.size();
            count++;
                system.debug(filterNumber);
    system.debug(count);
    }           


 
Hi , 
I have a report which have 48000  records  , when i run a report using synchronous Approach in apex code , it will only return 2000 records  so in order to overcome this problem i have used filter in report but after returning 4000 records it throw exception " FATAL_ERROR System.LimitException: reports:Too many query rows: 50001 "  . (I can't Use Asynch Approach as i am using this class inside batch class).
In order to Apply Filter i am using Autonumber field and sort them in ascending order, Please have a look to my code and help me to figure out the problem , Thanks to All In Advance.


String reportId='00Of1000004jG5h'; // Report Id
Integer filterNumber=0; // Set Lower Row Limit For Filter 
boolean getAllData=False;
integer count=0;

while(getAllData==false) {
Reports.ReportDescribeResult describe = Reports.ReportManager.describeReport(reportId); // describe report metadata
            Reports.ReportMetadata reportMd = describe.getReportMetadata();
    
                string b =reportMd.getDetailColumns()[0]; //get Filtered Column From Report , it is Autonumber Field
                String column1=b;
                Integer value1=filterNumber;
                String operator1='greaterOrEqual';
    
              Reports.ReportFilter filter = reportMd.getReportFilters()[0];// get Filter and Update filter values in apex
             
            filter.setColumn(column1);
            filter.setValue(string.valueOf(value1));
            filter.setOperator(operator1);
             Integer value2=value1+2000; // Upper Limit for Second Filter
            String operator2='lessOrEqual';
                
             Reports.ReportFilter filter1 =reportMd.getReportFilters()[0]; // Second Filter to report on same column 
            filter1.setColumn(column1);
            filter1.setValue(string.valueOf(value2));
            filter1.setOperator(operator2);
    
        
           // Run a report synchronously
            Reports.reportResults ActiveISOContacts = Reports.ReportManager.runReport(reportId,reportMd, true);
            getAllData=ActiveISOContacts.getAllData();
           system.debug(ActiveISOContacts.getAllData());//this will return true and false .

           // Get the fact map from the report results
            Reports.ReportFactWithDetails factDetails = (Reports.ReportFactWithDetails)ActiveISOContacts.getFactMap().get('T!T');
            //create a list of report rows and populate it with the result rows from fact map
            List<Reports.ReportDetailRow> reportRows = factDetails.getRows();
            filterNumber =filterNumber+reportRows.size();
            count++;
                system.debug(filterNumber);
    system.debug(count);
    }           


 
Hello,

 i am getting an Error "Too many SOQL queries: 101".
 
public class WarengruppenZuordnung {
    /********************* Properties used by getRootNodeOfUserTree function - starts **********************/
    // map to hold roles with Id as the key
    private static Map <Id, Warengruppen_Struktur__c> warengruppeMap;
    
    // map to hold child roles with parentRoleId as the key
    private static Map <Id, List<Warengruppen_Struktur__c>> parentWarengruppeMap;
    
    // List holds all subordinates
    private static List<Warengruppen_Struktur__c> allProducts {get; set;}
    
    // Global JSON generator
    private static JSONGenerator gen {get; set;}
    public static String folderId{get;set;}
    public static String folderName{get;set;}
    public static String endpointId{get;set;}
    /********************* Properties used by getRootNodeOfUserTree function - ends **********************/
    
    
    /********************* Properties used by getSObjectTypeById function - starts ********************* */
    // map to hold global describe data
    private static Map<String,Schema.SObjectType> gd;
    
    // map to store objects and their prefixes
    private static Map<String, String> keyPrefixMap;
    
    // to hold set of all sObject prefixes
    private static Set<String> keyPrefixSet;
    /********************* Properties used by getSObjectTypeById function - ends **********************/
    
    public static String redirUrl{get;set;}
    public String contactId {get;set;}
    
    /* // initialize helper data */ 
    static {
        // initialize helper data for getSObjectTypeById function
        Map<String, String> UrlParameterMap = ApexPages.currentPage().getParameters();
        //redirUrl = getRedirUrl();
        gen = JSON.createGenerator(true);
        init1();
        gen = JSON.createGenerator(true);
        // initialize helper data for getRootNodeOfUserTree function
        init2();
    }
    
    /* // init1 starts <to initialise helper data> */
    private static void init1() {
        // get all objects from the org
        gd = Schema.getGlobalDescribe();
        // to store objects and their prefixes
        keyPrefixMap = new Map<String, String>{};
            
            //get the object prefix in IDs
            keyPrefixSet = gd.keySet();
        
        // fill up the prefixes map
        for(String sObj : keyPrefixSet) {
            Schema.DescribeSObjectResult r =  gd.get(sObj).getDescribe();
            String tempName = r.getName();
            String tempPrefix = r.getKeyPrefix();
            keyPrefixMap.put(tempPrefix, tempName);
        }
    }
    /* // init1 ends */
    
    /* // init2 starts <to initialise helper data> */
    private static void init2() {
        
        // Create a blank list
        allProducts = new List<Warengruppen_Struktur__c>();

        for(AggregateResult wsc : [SELECT Name, RecordTypeId, RecordType.DeveloperName FROM Warengruppen_Struktur__c GROUP BY RecordTypeId, RecordType.DeveloperName, Name ORDER BY Name]) {
            if(String.valueOf(wsc.get('DeveloperName')).contains('Ordner')){
                folderId = String.valueOf(wsc.get('RecordTypeId'));
                folderName = String.valueOf(wsc.get('Name'));
            }
            if(String.valueOf(wsc.get('DeveloperName')).contains('Endpunkt')){
                endpointId = String.valueOf(wsc.get('RecordTypeId'));
                
            }
        }
        
        warengruppeMap = new Map<Id, Warengruppen_Struktur__c>([select Id, Name, Parent_Warengruppe__c, RecordTypeId from Warengruppen_Struktur__c order by Name]);
        // populate parent role - child roles map
        parentWarengruppeMap = new Map <Id, List<Warengruppen_Struktur__c>>();        
        for (Warengruppen_Struktur__c r : warengruppeMap.values()) {
            List<Warengruppen_Struktur__c> tempList;
            if (!parentWarengruppeMap.containsKey(r.Parent_Warengruppe__c)){
                tempList = new List<Warengruppen_Struktur__c>();
                tempList.Add(r);
                parentWarengruppeMap.put(r.Parent_Warengruppe__c, tempList);
            }
            else {
                tempList = (List<Warengruppen_Struktur__c>)parentWarengruppeMap.get(r.Parent_Warengruppe__c);
                tempList.add(r);
                parentWarengruppeMap.put(r.Parent_Warengruppe__c, tempList);
            }
        }
    } 
    /* // init2 ends */
    
    /* // public method to get the starting node of the RoleTree along with user list */
    public static RoleNodeWrapper getRootNodeOfUserTree (Id userOrRoleId) {
        return createNode(userOrRoleId);
    }
    
    /* // createNode starts */
    private static RoleNodeWrapper createNode(Id objId) {
        RoleNodeWrapper n = new RoleNodeWrapper();
        Id roleId;
        if (isRole(objId)) {
            roleId = objId;
            if (!(warengruppeMap.get(objId).Parent_Warengruppe__c == null)) {
                List<Warengruppen_Struktur__c> tempFolderList = new List<Warengruppen_Struktur__c>();
                Warengruppen_Struktur__c tempFolder = [Select Id, Name, Parent_Warengruppe__c, RecordTypeId, RecordType.DeveloperName from Warengruppen_Struktur__c where Id =: objId ORDER BY Name];
                tempFolderList.add(tempFolder);
                if(tempFolderList.size()== 1){
                    if(tempFolderList[0].RecordType.DeveloperName.contains('Ordner')){
                        n.hasFolders = false;
                        n.myFolders = tempFolderList;
                        n.isLeafNode = false;
                        allProducts.addAll(n.myFolders);
                    }
                    else{
                        n.hasFolders = false;
                        n.myFolders = tempFolderList;
                        n.isLeafNode = true;
                        allProducts.addAll(n.myFolders);
                    }
                }
            }
        }
        else {
            List<Warengruppen_Struktur__c> tempFolderList = new List<Warengruppen_Struktur__c>();
            Warengruppen_Struktur__c tempFolder = [Select Id, Name, Parent_Warengruppe__c, RecordTypeId from Warengruppen_Struktur__c where Id =: objId ORDER BY Name];
            tempFolderList.add(tempFolder);
            n.myFolders = tempFolderList;
            roleId = tempFolder.Parent_Warengruppe__c;
        }
        n.myRoleId = roleId;
        n.myRoleName = warengruppeMap.get(roleId).Name;
        n.myParentRoleId = warengruppeMap.get(roleId).Parent_Warengruppe__c;
        n.RecordTypeId = warengruppeMap.get(roleId).RecordTypeId;
        if (parentWarengruppeMap.containsKey(roleId)){
            n.hasChildren = true;
            n.isLeafNode = false;
            List<RoleNodeWrapper> lst = new List<RoleNodeWrapper>();
            for (Warengruppen_Struktur__c r : parentWarengruppeMap.get(roleId)) {
                lst.add(createNode(r.Id));
            }           
            n.myChildNodes = lst;
        }
        else {
            n.isLeafNode = true;
            n.hasChildren = false;
            
        }
        return n;
    }
    
    public static List<Warengruppen_Struktur__c> getAllProducts(Id warengruppeId){
        createNode(warengruppeId);
        return allProducts;
    }
    
    public static String getTreeJSON(Id userOrRoleId) {
        gen = JSON.createGenerator(true);
        RoleNodeWrapper node = createNode(userOrRoleId);
        gen.writeStartArray();
        convertNodeToJSON(node);
        gen.writeEndArray();
        return gen.getAsString();
    }
    
    public static String getTreeJSON() {
        gen = JSON.createGenerator(true);
        List<Warengruppen_Struktur__c> wRoots = [Select Id, Name, RecordTypeId From Warengruppen_Struktur__c Where Parent_Warengruppe__c = '' ORDER BY Name];
        gen.writeStartArray();
        for(Warengruppen_Struktur__c ws : wRoots){
            RoleNodeWrapper node = createNode(ws.Id);
            convertNodeToJSON(node);
        }
        gen.writeEndArray();
        return gen.getAsString();
    }
    
    private static void convertNodeToJSON(RoleNodeWrapper objRNW){
        gen.writeStartObject();
        gen.writeStringField('title', objRNW.myRoleName);
        gen.writeStringField('key', objRNW.myRoleId);
        gen.writeStringField('RecordTypeID', String.valueOf(objRNW.RecordTypeId));
        gen.writeBooleanField('unselectable', false);
        gen.writeBooleanField('expand', true);
        gen.writeBooleanField('isFolder', true);
        if (objRNW.hasFolders || objRNW.hasChildren)
        {
            gen.writeFieldName('children');
            gen.writeStartArray();
            if (objRNW.hasFolders)
            {
                for (Warengruppen_Struktur__c u : objRNW.myFolders)
                {
                    gen.writeStartObject();
                    gen.writeStringField('title', u.Name);
                    gen.writeStringField('key', u.Id);
                    gen.writeStringField('RecordTypeID', String.valueOf(objRNW.RecordTypeId));
                    gen.writeBooleanField('isFolder', false);
                    gen.WriteEndObject();
                }
            }
            if (objRNW.hasChildren)
            {
                
                for (RoleNodeWrapper r : objRNW.myChildNodes)
                    
                {
                    convertNodeToJSON(r);
                    
                }
            }
            gen.writeEndArray();
        }
        gen.writeEndObject();
    }
    
    /* // general utility function to get the SObjectType of the Id passed as the argument, to be used in conjunction with */ 
    public static String getSObjectTypeById(Id objectId) {
        String tPrefix = objectId;
        tPrefix = tPrefix.subString(0,3);
        String objectType = keyPrefixMap.get(tPrefix);
        return objectType;
    }
    /* // utility function getSObjectTypeById ends */
    
    /* // check the object type of objId using the utility function getSObjectTypeById and return 'true' if it's of Role type */
    public static Boolean isRole (Id objId) {
        if (getSObjectTypeById(objId) == String.valueOf(Warengruppen_Struktur__c.sObjectType)) {
            return true;
        }
        else if (getSObjectTypeById(objId) != String.valueOf(Warengruppen_Struktur__c.sObjectType)) {
            return false;
        } 
        return false;
    }
    /* // isRole ends */
    
    public class RoleNodeWrapper {
        
        // Role info properties - begin
        public String myRoleName {get; set;}
        
        public Id myRoleId {get; set;}
        public Id RecordTypeId {get; set;}
        public String myParentRoleId {get; set;}
        // Role info properties - end
        
        
        // Node children identifier properties - begin
        public Boolean hasChildren {get; set;}
        
        public Boolean isLeafNode {get; set;}
        
        public Boolean hasFolders {get; set;}
        // Node children identifier properties - end
        
        
        // Node children properties - begin
        public List<Warengruppen_Struktur__c> myFolders {get; set;}
        
        public List<RoleNodeWrapper> myChildNodes {get; set;}
        // Node children properties - end   
        
        public RoleNodeWrapper(){
            hasFolders = false;
            hasChildren = false;
        }
    }
    
    public static String getRedirUrl(){
        Map<String, String> UrlParameterMap = ApexPages.currentPage().getParameters();
        redirUrl = UrlParameterMap.values()[1];
        return redirUrl;        
    }
    
    public String getContactId()
    {
        return Apexpages.currentPage().getParameters().get('id');
        
    }

}

This Error occur in this line
 
Warengruppen_Struktur__c tempFolder = [Select Id, Name, Parent_Warengruppe__c, RecordTypeId, RecordType.DeveloperName from Warengruppen_Struktur__c where Id =: objId ORDER BY Name];
How to change this to get it working?

Any Ideas :(?

Thanks
Peter
Hi All,

I have to cover test class for a WDL2 generated class. However I wrote a test class and succeed in achieving 70% but not able to cover further.
Below is the WSDL2 generated class:
public class SendPickupRequestInfoToTranSend1 {
    public class pickupRequest {
        public SendPickupRequestInfoToTranSend1.PickupRequestData PickupRequestData;
        public SendPickupRequestInfoToTranSend1.DGData[] DGData;
        private String[] PickupRequestData_type_info = new String[]{'PickupRequestData','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'1','1','true'};
        private String[] DGData_type_info = new String[]{'DGData','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'1','-1','true'};
        private String[] apex_schema_type_info = new String[]{'http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest','false','false'};
        private String[] field_order_type_info = new String[]{'PickupRequestData','DGData'};
    }
    public class getPickupRequest {
        public SendPickupRequestInfoToTranSend1.pickupRequest pickupRequestSalesforce;
        private String[] pickupRequestSalesforce_type_info = new String[]{'pickupRequestSalesforce','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'1','1','true'};
        private String[] apex_schema_type_info = new String[]{'http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest','false','false'};
        private String[] field_order_type_info = new String[]{'pickupRequestSalesforce'};
    }
    public class getPickupRequestResponse {
        public SendPickupRequestInfoToTranSend1.pickupResponse pickupResponseSalesforce;
        private String[] pickupResponseSalesforce_type_info = new String[]{'pickupResponseSalesforce','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'1','1','true'};
        private String[] apex_schema_type_info = new String[]{'http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest','false','false'};
        private String[] field_order_type_info = new String[]{'pickupResponseSalesforce'};
    }
    public class PickupRequestData {
        public String pickupStatus;
        public String businessUnit;
        public String bookingRef;
        public String createdDate;
        public String accountNumber;
        public String accountName;
        public String pickupAddressLine1;
        public String pickupAddressLine2;
        public String pickupAddressState;
        public String pickupAddressPostCode;
        public String pickupAddressSuburb;
        public String pickupDepot;
        public String pickupContactName;
        public String pickupContactPhone;
        public String isItThirdParty;
        public String readyTime;
        public String closeTime;
        public String remarks;
        public String serviceCode;
        public String payType;
        public String noOfItems;
        public String itemDescription;
        public String totalWt;
        public String lengthcm;
        public String widthcm;
        public String heightcm;
        public String destinationPostcode;
        public String destinationState;
        public String destinationSuburb;
        public String deliveryDepot;
        public String dangerousGoods;
        public String pickupDate;
        private String[] pickupStatus_type_info = new String[]{'pickupStatus','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'0','1','true'};
        private String[] businessUnit_type_info = new String[]{'businessUnit','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'0','1','true'};
        private String[] bookingRef_type_info = new String[]{'bookingRef','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'0','1','true'};
        private String[] createdDate_type_info = new String[]{'createdDate','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'0','1','true'};
        private String[] accountNumber_type_info = new String[]{'accountNumber','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'0','1','true'};
        private String[] accountName_type_info = new String[]{'accountName','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'0','1','true'};
        private String[] pickupAddressLine1_type_info = new String[]{'pickupAddressLine1','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'0','1','true'};
        private String[] pickupAddressLine2_type_info = new String[]{'pickupAddressLine2','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'0','1','true'};
        private String[] pickupAddressState_type_info = new String[]{'pickupAddressState','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'0','1','true'};
        private String[] pickupAddressPostCode_type_info = new String[]{'pickupAddressPostCode','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'0','1','true'};
        private String[] pickupAddressSuburb_type_info = new String[]{'pickupAddressSuburb','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'0','1','true'};
        private String[] pickupDepot_type_info = new String[]{'pickupDepot','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'0','1','true'};
        private String[] pickupContactName_type_info = new String[]{'pickupContactName','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'0','1','true'};
        private String[] pickupContactPhone_type_info = new String[]{'pickupContactPhone','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'0','1','true'};
        private String[] isItThirdParty_type_info = new String[]{'isItThirdParty','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'0','1','true'};
        private String[] readyTime_type_info = new String[]{'readyTime','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'0','1','true'};
        private String[] closeTime_type_info = new String[]{'closeTime','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'0','1','true'};
        private String[] remarks_type_info = new String[]{'remarks','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'0','1','true'};
        private String[] serviceCode_type_info = new String[]{'serviceCode','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'0','1','true'};
        private String[] payType_type_info = new String[]{'payType','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'0','1','true'};
        private String[] noOfItems_type_info = new String[]{'noOfItems','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'0','1','true'};
        private String[] itemDescription_type_info = new String[]{'itemDescription','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'0','1','true'};
        private String[] totalWt_type_info = new String[]{'totalWt','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'0','1','true'};
        private String[] lengthcm_type_info = new String[]{'lengthcm','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'0','1','true'};
        private String[] widthcm_type_info = new String[]{'widthcm','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'0','1','true'};
        private String[] heightcm_type_info = new String[]{'heightcm','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'0','1','true'};
        private String[] destinationPostcode_type_info = new String[]{'destinationPostcode','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'0','1','true'};
        private String[] destinationState_type_info = new String[]{'destinationState','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'0','1','true'};
        private String[] destinationSuburb_type_info = new String[]{'destinationSuburb','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'0','1','true'};
        private String[] deliveryDepot_type_info = new String[]{'deliveryDepot','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'0','1','true'};
        private String[] dangerousGoods_type_info = new String[]{'dangerousGoods','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'0','1','true'};
        private String[] pickupDate_type_info = new String[]{'pickupDate','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'0','1','true'};
        private String[] apex_schema_type_info = new String[]{'http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest','false','false'};
        private String[] field_order_type_info = new String[]{'pickupStatus','businessUnit','bookingRef','createdDate','accountNumber','accountName','pickupAddressLine1','pickupAddressLine2','pickupAddressState','pickupAddressPostCode','pickupAddressSuburb','pickupDepot','pickupContactName','pickupContactPhone','isItThirdParty','readyTime','closeTime','remarks','serviceCode','payType','noOfItems','itemDescription','totalWt','lengthcm','widthcm','heightcm','destinationPostcode','destinationState','destinationSuburb','deliveryDepot','dangerousGoods','pickupDate'};
    }
    public class DGData {
        public String unCode;
        public String unCodeDescription;
        private String[] unCode_type_info = new String[]{'unCode','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'0','1','true'};
        private String[] unCodeDescription_type_info = new String[]{'unCodeDescription','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'0','1','true'};
        private String[] apex_schema_type_info = new String[]{'http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest','false','false'};
        private String[] field_order_type_info = new String[]{'unCode','unCodeDescription'};
    }
    public class pickupResponse {
        public String BookingNumber;
        public String ErrorDescription;
        public String ReceivedDateTime;
        public String ResponseCode;
        private String[] BookingNumber_type_info = new String[]{'BookingNumber','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'1','1','true'};
        private String[] ErrorDescription_type_info = new String[]{'ErrorDescription','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'1','1','true'};
        private String[] ReceivedDateTime_type_info = new String[]{'ReceivedDateTime','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'1','1','true'};
        private String[] ResponseCode_type_info = new String[]{'ResponseCode','http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',null,'1','1','true'};
        private String[] apex_schema_type_info = new String[]{'http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest','false','false'};
        private String[] field_order_type_info = new String[]{'BookingNumber','ErrorDescription','ReceivedDateTime','ResponseCode'};
    }
    public class aSalesforce_ws_provider_PickupRequest_receivePickupRequest_Port {
        public String endpoint_x = 'https://b2b-uat-farm.toll.com.au:7590/ws/aSalesforce.ws.provider.PickupRequest:receivePickupRequest/aSalesforce_ws_provider_PickupRequest_receivePickupRequest_Port';
        //public String endpoint_x = 'https://requestb.in/rahjklra';
        //public String endpoint_x = 'https://b2b-uat-farm.toll.com.au:7590/aSalesforce.ws.provider.PickupRequest:receivePickupRequest/aSalesforce_ws_provider_PickupRequest_receivePickupRequest_Port';
        
        public Map<String,String> inputHttpHeaders_x;
        public Map<String,String> outputHttpHeaders_x;
        public String clientCertName_x;
        public String clientCert_x;
        public String clientCertPasswd_x;
        public Integer timeout_x;
        private String[] ns_map_type_info = new String[]{'http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest', 'SendPickupRequestInfoToTranSend1'};
        public SendPickupRequestInfoToTranSend1.pickupResponse getPickupRequest(SendPickupRequestInfoToTranSend1.pickupRequest pickupRequestSalesforce) {
            SendPickupRequestInfoToTranSend1.pickupResponse res =  new SendPickupRequestInfoToTranSend1.pickupResponse();
            try{
            SendPickupRequestInfoToTranSend1.getPickupRequest request_x = new SendPickupRequestInfoToTranSend1.getPickupRequest();
            request_x.pickupRequestSalesforce = pickupRequestSalesforce;
            SendPickupRequestInfoToTranSend1.getPickupRequestResponse response_x;
            Map<String, SendPickupRequestInfoToTranSend1.getPickupRequestResponse> response_map_x = new Map<String, SendPickupRequestInfoToTranSend1.getPickupRequestResponse>();
            response_map_x.put('response_x', response_x);
            WebServiceCallout.invoke(
              this,
              request_x,
              response_map_x,
              new String[]{endpoint_x,
              'aSalesforce_ws_provider_PickupRequest_receivePickupRequest_Binder_getPickupRequest',
              'http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',
              'getPickupRequest',
              'http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',
              'getPickupRequestResponse',
              'SendPickupRequestInfoToTranSend1.getPickupRequestResponse'}
            );
            response_x = response_map_x.get('response_x');
            return response_x.pickupResponseSalesforce;
            }Catch(Exception e){
                return res;
            }
            return res;
        }
    }
}

My test class is follows:
@IsTest
private with sharing class SendPickupRequestInfoToTranSend1_test
{
    
    
    private class WebServiceMockImpl implements WebServiceMock
    {
        public void doInvoke(
            Object stub, Object request, Map<String, Object> response,
            String endpoint, String soapAction, String requestName,
            String responseNS, String responseName, String responseType)
        {
            if(request instanceof SendPickupRequestInfoToTranSend1.getPickupRequest)
                response.put('response_x', new SendPickupRequestInfoToTranSend1.getPickupRequestResponse());
            return;
        }
    }
    private static testMethod void coverTypes()
    {
        new SendPickupRequestInfoToTranSend1.pickupRequest();
		new SendPickupRequestInfoToTranSend1.getPickupRequest();
		new SendPickupRequestInfoToTranSend1.getPickupRequestResponse();
		new SendPickupRequestInfoToTranSend1.PickupRequestData();
		new SendPickupRequestInfoToTranSend1.DGData();
		new SendPickupRequestInfoToTranSend1.pickupResponse();
		new SendPickupRequestInfoToTranSend1.aSalesforce_ws_provider_PickupRequest_receivePickupRequest_Port ();
		new SendPickupRequestInfoToTranSend1.DGData();
	}

I am not able to cover the lines for the method of port class.Please see below lines:
public SendPickupRequestInfoToTranSend1.pickupResponse getPickupRequest(SendPickupRequestInfoToTranSend1.pickupRequest pickupRequestSalesforce) {
            SendPickupRequestInfoToTranSend1.pickupResponse res =  new SendPickupRequestInfoToTranSend1.pickupResponse();
            try{
            SendPickupRequestInfoToTranSend1.getPickupRequest request_x = new SendPickupRequestInfoToTranSend1.getPickupRequest();
            request_x.pickupRequestSalesforce = pickupRequestSalesforce;
            SendPickupRequestInfoToTranSend1.getPickupRequestResponse response_x;
            Map<String, SendPickupRequestInfoToTranSend1.getPickupRequestResponse> response_map_x = new Map<String, SendPickupRequestInfoToTranSend1.getPickupRequestResponse>();
            response_map_x.put('response_x', response_x);
            WebServiceCallout.invoke(
              this,
              request_x,
              response_map_x,
              new String[]{endpoint_x,
              'aSalesforce_ws_provider_PickupRequest_receivePickupRequest_Binder_getPickupRequest',
              'http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',
              'getPickupRequest',
              'http://10.164.163.3/aSalesforce.ws.provider.PickupRequest:receivePickupRequest',
              'getPickupRequestResponse',
              'SendPickupRequestInfoToTranSend1.getPickupRequestResponse'}
            );
            response_x = response_map_x.get('response_x');
            return response_x.pickupResponseSalesforce;
            }Catch(Exception e){
                return res;
            }
            return res;
        }
Also I am attaching the screenshot from Developer Console:
User-added image

Kindly help me

Thanks & Regards,
Harjeet
 
Hi All,

I have a requirement, if i create any field in saleforce object other system should be notied with any of the channel. I need to notify them with metadata information like field label name, api name, field type ext.. How to achive this.

Thanks,
Anil Kumar 
Hi everyone!  I am looking for people to build a trusted working relationship with; people that I can turn to that will help me execute my projects.  

My goal is to have a group of us that all work together, as projects arise, based on our individual specialties.  Right now I am acting as the project manager, technical architect, designer, builder, and administator for each one of my clients; its too much! 

If you are a Certified Developer or Certified Administrator with at least 5 years of experience, live in the U.S., and would like to become part of a trusted team of excellence, please send me your resume along with your hourly rate detail.   (dea@deasimon.com) 

This is a contract position that is ad-hoc in nature, no guarantee of consisent work is given at this time but you will be the first I call when assistance is needed.  My apologies but no oveseas applicants will be considered, previous experience with significant differences in timezones has proven to be too difficult to manage.
Hi,
i have create an custom button to change (calculate) Values in my own object. It seems a very good solution, but "overnight" the calculated values are not updated in the formula. What can be the reason for this problem. Have i changed a special flag anywhere in Salesforce which prevented the correct functionality?

{!REQUIRESCRIPT("/soap/ajax/34.0/connection.js")}

var aw = confirm ("Wollen Sie die Anpassung von Schwellenwert und \nHöchstbetrag jetzt vornehmen?")

if (aw == true) {

var qr = sforce.connection.query("SELECT Inflationsfaktor__c FROM Inflationsrate__c WHERE Name = '{!Rueckzahlungsjahr__c.Inflationszeitraum__c}'");

var qr2 = sforce.connection.query("SELECT Schwellenwert_exkl_Inflation__c, Jaehrlicher_Hoechstbetrag__c FROM Contract WHERE ContractNumber = '{!Rueckzahlungsjahr__c.Vertrag__c}'");

var records = qr.getArray("records");
var records2 = qr2.getArray("records");


var tempOb = new sforce.SObject("Rueckzahlungsjahr__c");
tempOb.Id = "{!Rueckzahlungsjahr__c.Id}";



//Schwellenwert infaltionieren
tempOb.tempSchwellenwert__c = records[0].Inflationsfaktor__c * records2[0].Schwellenwert_exkl_Inflation__c;

//Jährlichen Höchstbetrag inflationieren
//alert (records2[0].Jaehrlicher_Hoechstbetrag__c)
tempOb.Jaehrlicher_Hoechstbetrag__c = records[0].Inflationsfaktor__c * records2[0].Jaehrlicher_Hoechstbetrag__c;

//Flag setzen das Inflationierung erfolgt ist
tempOb.Schwellenwert_aktualisiert__c = true;

alert("Faktor: " + qr.records.Inflationsfaktor__c + " * " + "Basis-Schwellenwert: " + qr2.records.Schwellenwert_exkl_Inflation__c + " = " + tempOb.tempSchwellenwert__c + " EUR")

sforce.connection.update([tempOb]);

window.location.reload();
 
Hi,

I have a soql query where i am using LIKE operator.
String sql = 'Select Name From Account WHERE Name LIKE \'%' + searchKeyword + '%\'';
Here 'searchKeyword' variable holds values like 'Test 1, Test 2, Test 3, Test 4'.
When i search a Name in my VF page which is a Textbox, like this 'Test 1, Test 4' its not returning the searchKeyword values. Because LIKE operator searches values only in Orderwise. It cant search middle values.

Is there any possible solution where it searches all values that are contained in the textbox?

Thanks
Vivek
Hi,

I have written a test class for this rest callouts but its not covering 100% code coverage. Can someone please help me

It throws me error when I run the test class 
Class.AnimalLocator.getAnimalNameById: line 16, column 1 Class.AnimalLocatorTest.testcallout: line 7, column 1

Apex class 

public class AnimalLocator {

public static string getAnimalNameById (integer i)
{
    string a;
    Http ht = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals/' + i);
        request.setMethod('GET');
        HttpResponse response = ht.send(request);
        // If the request is successful, parse the JSON response.
    if (response.getStatusCode() == 200) 
    {
            Map<String, Object> result = (Map<String, Object>)JSON.deserializeUntyped(response.getBody());
             Map<string,object> cc = (Map<string,object>) result.get('animals');
        a = (string)cc.get('name');
    }
    return a;
  }
}


Test class

@isTest
public class AnimalLocatorTest 
{
@isTest static void testcallout()
{
      Test.setMock(HttpCalloutMock.class, new AnimalLocatorMock()); 
    string response = AnimalLocator.getAnimalNameById (2); 
String expectedValue = '{"animal":{"id":2,"name":"bear","eats","berries, campers, adam seligman","says":"yum yum"}}'; 
system.assertEquals('eats', response);
   
   }
}

@isTest
global class AnimalLocatorMock implements HttpCalloutMock 
{
global HTTPResponse respond(HTTPRequest request) 
{
        // Create a fake response
         HttpResponse response = new HttpResponse(); 
     response.setHeader('Content-Type', 'application/json');
    response.setBody('{"animal":{"i":2,"name":"bear","eats":"berries, campers, adam seligman","says":"yum yum"}}'); 
        response.setStatusCode(200);
        return response;
}
}
 
  • January 29, 2016
  • Like
  • 0
Hi all,

I'm stuck in the Apex Integration Services - Apex SOAP Callouts challenge with the following message "The Apex class 'ParkLocator' does not appear to be calling the SOAP endpoint.".

Could you please advise ?

Hi All,

After attempting lighting component module.I am facing with the following problem.
https://developer.salesforce.com/trailhead/force_com_dev_intermediate/lightning_components/lightning_components_events_handle
1-PhoneNumberInput.cmp
<aura:component >
    <aura:registerEvent name="PhoneNumberEvent" type="c:PhoneNumberEvent"/>
    <ui:inputPhone aura:id="phone" label="phone" />
    <ui:button label="Show Phone" press="{!c.send}"/>
</aura:component>

2-PhoneNumberOutput.cmp
<aura:component >
    <aura:attribute name="phone" type="String" default="No Phone Number"/>
    <ui:outputText aura:id="phone" value="{!v.phone}"/>
    <aura:handler event="c:PhoneNumberEvent" action="{!c.answer}"/>
</aura:component>

3-PhoneNumberEvent.evt
<aura:event type="APPLICATION" description="Event template">
    <aura:attribute name="phone" type="String"/>
</aura:event>


4-PhoneNumberInputController.js

({
    setphone:function (component, event,helper){
        var phone=component.find("phone").get("v.value");
        $A.get("e.c:PhoneNumberEvent").set Params({
            phone:phone
        }).fire(),
    }
        
    })

5-PhoneNumber.app
<aura:application >
    <c:PhoneNumberInput />
    <c:PhoneNumberOutput />
</aura:application>

User-added image

Thanks 
Prashant 

<aura:component controller="DisplayCaseController" implements="force:appHostable">
    <aura:attribute name="record" type="Case[]"/>
    <ui:inputNumber label="Case ID" aura:id="CaseID"/><br/><br/>
    <ui:button label="Get Case" press="{ !c.getCaseFromId }"/><br/><br/>
    <aura:iteration var="c" items="{!v.record}">
         <p>{!c.Subject} : {!c.Description} : {!c.Status}</p>
    </aura:iteration>
</aura:component>

 

 

client-side controller:-

({
    getCaseFromId : function(component) {
        var caseID = component.find("CaseID").get("v.value");
        var action = component.get("c.getCaseFromId");
        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set("v.record", response.getReturnValue());
            }
        });
        $A.enqueueAction(action);
    }
})

 

 

public class DisplayCaseController {
@AuraEnabled
public static Case getCaseFromId(Id caseID) {
if(caseID == null) {
return [SELECT ID, Subject, Description, STATUS from Case LIMIT 1];
}
List<Case> cases = [ SELECT Id, Subject, Description, Status from CASE where ID = :caseID ];
if(cases.size() == 0) {
return [SELECT ID, Subject, Description, STATUS from Case LIMIT 1];
} else {
return cases[0];
}
}
}

 

Challenge not yet complete... here's what's wrong: 
The client side controller does not refer to the 'getCaseFromId' method of the Apex controller class

Thnaks In Advance

Prashant

 

 

Hi all,

I have implemented an SMS service from Twilio that can handle incoming messages. I have pretty much followed this awesome video from Pat Patterson.

I am struggling to write a test class that passes the Twilio request validation. Can anybody please help me out and show how to do it? 

Here is my class:
@RestResource(urlMapping='/TwilioRecruitment')
global class TwilioRecruitment {
    static TwilioAccount account = TwilioAPI.getDefaultAccount();
    
    @future(callout=true)
    public static void reply(string fromNumber, string toNumber, string message){
        Map<String, String> params = new Map<String, String> {
            'From' => fromNumber,
            'To' => toNumber,
            'Body' => message
        };
        
        TwilioSms sms = account.getSmsMessages().create(params);
        system.debug('Send SMS SId' +  ' ' + sms.getSid());
    }
    
    @HttpPost
    global static void incomingSMS() {
        
        String expectedSignature = 
            RestContext.request.headers.get('X-Twilio-Signature');
            system.debug('expectedSignature ' + expectedSignature);
        String url = 'https://' + RestContext.request.headers.get('Host') + 
            '/services/apexrest' + RestContext.request.requestURI;
            system.debug('url ' + url);
        Map <String, String> params = RestContext.request.params;
        system.debug('params ' + params);
        system.debug('TwilioAPI.getDefaultClient().validateRequest(expectedSignature, url, params) ' + TwilioAPI.getDefaultClient().validateRequest(expectedSignature, url, params));
        // Validate signature
        if (!TwilioAPI.getDefaultClient().validateRequest(expectedSignature, url, params)) {
            RestContext.response.statusCode = 403;
            RestContext.response.responseBody = 
                Blob.valueOf('Failure! Rcvd '+expectedSignature+'\nURL '+url);
            return;
        } 
        
        //Twilio to check if something is in the response body otherwise report
        // a 502 error in https://twilio.com/account/log/notifications
        
        RestContext.response.responseBody = Blob.valueOf('ok');
        
        //Extract useful fields from the incoming SMS
        String senderNumber = params.get('From');
        String receiver = params.get('To');
        String body = params.get('Body');
        system.debug('From, To, Body' + ' ' + senderNumber + ' ' + receiver + ' ' + body);
        //Try find matching TFP employee
        TFP_Employee__c tfpEmpl = null;
        try{
            String prefixAU = '+61';
            String formattedSenderNumber = '';
            if(senderNumber.startsWith(prefixAU)){
                formattedSenderNumber = 0 + senderNumber.removeStart(prefixAU);
            }
           ... More logic below here...

This is the test class that fails at the validation:
@isTest
global class TwilioRecruitmentTest {

    static testMethod void testGet() {

        RestRequest req = new RestRequest(); 
        RestResponse res = new RestResponse();
        
        req.requestURI = '/services/apexrest/TwilioRecruitment';
        req.httpMethod = 'POST';

        req.addParameter('From','+61458883222');
        req.addParameter('Body','This is a test');
        req.addParameter('To','+61437879336');
        req.addParameter('ToCountry','AU');
        req.addParameter('ToState','');
        req.addParameter('SmsMessageSid','SMS MESSAGE ID HERE ');
        req.addParameter('NumMedia','0');
        req.addParameter('ToCity','');
        req.addParameter('FromZip','');
        req.addParameter('SmsSid','SMS ID HERE');
        req.addParameter('SmsStatus','received');
        req.addParameter('FromCity','');
        req.addParameter('FromCountry','AU');
        req.addParameter('ToZip','');
        req.addParameter('MessageSid','MESSAGE SID HERE');
        req.addParameter('AccountSid','ACCOUNT SID HERE');
        req.addParameter('ApiVersion','2010-04-01');

        req.httpMethod = 'POST';
        RestContext.request = req;
        RestContext.response = res;
        
        TwilioRecruitment.incomingSMS();
        
    }
}

Any help would be awesome!
Thanks!
Hi everyone!  I am looking for people to build a trusted working relationship with; people that I can turn to that will help me execute my projects.  

My goal is to have a group of us that all work together, as projects arise, based on our individual specialties.  Right now I am acting as the project manager, technical architect, designer, builder, and administator for each one of my clients; its too much! 

If you are a Certified Developer or Certified Administrator with at least 5 years of experience, live in the U.S., and would like to become part of a trusted team of excellence, please send me your resume along with your hourly rate detail.   (dea@deasimon.com) 

This is a contract position that is ad-hoc in nature, no guarantee of consisent work is given at this time but you will be the first I call when assistance is needed.  My apologies but no oveseas applicants will be considered, previous experience with significant differences in timezones has proven to be too difficult to manage.