• Suraj Makandar
  • NEWBIE
  • 83 Points
  • Member since 2015

  • Chatter
    Feed
  • 2
    Best Answers
  • 0
    Likes Received
  • 2
    Likes Given
  • 2
    Questions
  • 33
    Replies
i have  designed a apex class on custom object where it checks the duplicate value for Specific recordtype, it is invoked by a trigger handler, i am getting this error - 

QuotaTrigger: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object Class.QuotaTriggerHandler.dupQuotaError: line 5, column 1 Trigger.QuotaTrigger: line 3, column 1

I tried Googling the error but still   not able to Resolve the error, Any suggestions please

QuotaTrigger
 
trigger QuotaTrigger on Quota__c (before insert, before update) {

    QuotaTriggerHandler.dupQuotaError(Trigger.new);
    
}

QuotaTriggerHandler
 
public class QuotaTriggerHandler {
    
    public static void dupQuotaError (List <Quota__c> newTrigCon) {
        
        Id recordTypeId = Schema.SObjectType.Quota__c.getRecordTypeInfosByDeveloperName().get('Inside Sales Target(IS)').getRecordTypeId();
        
        //List of all Contact Records currently in the database    
        List <Quota__c> allCon = [SELECT ID, Name, Assignedto__c, Quater_Year__c, RecordTypeId, Month__c FROM Quota__c where RecordTypeId=:recordTypeId];
        
        //Iterate through new potential records
        for (Quota__c oneConTrig : newTrigCon) {
            
            //Needed to iterate through all existing records which is contained in the allCon List
            for (Integer i = 0; i < allCon.size(); i++)
                
                //If all conditions are met, there is a duplicate and thus, returns an error.
                if (oneContrig.Assignedto__c == allCon[i].Assignedto__c 
                    && oneContrig.Quater_Year__c == allCon[i].Quater_Year__c 
                    && oneConTrig.Month__c == allCon[i].Month__c
                    && oneConTrig.RecordTypeId == recordTypeId) {
                        
                        oneConTrig.addError('Duplicate Quota Detected! This record already exists.');
                        
                    }
        }      
    }
}

How do i resove this issue
Hi Everyone, 

I have trigger and class for a custom object, and in prod when data updated or loaded to the custom object I'm getting this error. can anyone please give a solution for this, I'm new to coding.

Error --
External E-Mail – Verify Email Address, Links, and Attachments

Apex script unhandled trigger exception by user/organization: 005A0000004JEGW/00DA0000000C46b

DivisionTrigger: execution of AfterUpdate

caused by: System.DmlException: Update failed. First exception on row 0 with id 0011200001DyK2BAAV; first error: UNABLE_TO_LOCK_ROW, unable to obtain exclusive access to this record or 200 records: 0011200001DyK2BAAV,0011200001DyKFAAA3,0011200001DyLr8AAF,0011200001DyNIQAA3,0011200001DyNJHAA3,0011200001DyNdZAAV,0011200001DyNycAAF,0011200001DyPHUAA3,0011200001DyQeIAAV,0011200001DyS64AAF, ... (190 more): []

Class.DivisionTriggerHandler.calculateCount: line 124, column 1
Trigger.DivisionTrigger: line 8, column 1


Trigger - 


trigger DivisionTrigger on Division__c (after insert,after update,after delete) {
//if( Division__c.Account__c != Null || Division__c.Account__c == Null){
  if ( trigger.isAfter ) {
        if ( trigger.isInsert ) {
            DivisionTriggerHandler.calculateCount(trigger.new);
        } 
        else if ( trigger.isUpdate ) {
            DivisionTriggerHandler.calculateCount(trigger.new);
        }
        else if ( trigger.isDelete ) {
            DivisionTriggerHandler.calculateCount(trigger.old);
        }
    }
//}
}



Class - 

public without sharing class DivisionTriggerHandler {
    
    public static void calculateCount(List<Division__c> divisionList) {
        
        System.debug(divisionList);
        Set<Id> accIds = new Set<Id>();
        
        for(Division__c dv: divisionList)
        {
            accIds.add(dv.Account__c);
        }
        System.debug(accIds);
        
        if(accIds.size()>0)
        {
            Map<Id,Account> accMap = new Map<id, Account>([Select id, of_DIvisions__c ,of_Divisions_ever_having_AP__c ,of_Participated_Divisions__c ,of_Blacklisted_Divisions__c ,of_Awarded_Divisions__c  from Account where Id in :accIds]);
            
            List<Division__c> divList = [Select id,Account__c, RecordType.Name,First_Awarded_Date__c,Status__c,
                                         First_Invoice_Load_Date__c,First_Participation_Date__c from Division__c where RecordType.Name in ('C2FO Division','International Division') and Account__r.RecordType.Name ='Strategic Supplier' and Account__c in: accIds];
            
            Map<Id,List<Division__c>> AccDivMap = new Map<Id, List<Division__c>>();
            for(Division__c dv: divList)
            {
                if(AccDivMap.containsKey(dv.Account__c))
                {
                    List<Division__c> tempList =  AccDivMap.get(dv.Account__c);
                    tempList.add(dv);
                    AccDivMap.put(dv.Account__c, tempList);
                }
                else{
                    List<Division__c> tempList =  new List<Division__c>();
                    tempList.add(dv);
                    AccDivMap.put(dv.Account__c, tempList);
                }
            }
            for(Id accId : accMap.keySet())
            {
                
                Account acc2 =  accMap.get(accId);
                System.debug(acc2);
                acc2.of_Awarded_Divisions__c=0;
                acc2.of_Blacklisted_Divisions__c=0;
                acc2.of_DIvisions__c=0;
                acc2.of_Divisions_ever_having_AP__c=0;
                acc2.of_Participated_Divisions__c =0;
                accMap.put(accId,acc2);
                List<Division__c> tempDivisionlist = AccDivMap.get(accId);
                System.debug(tempDivisionlist);
                if(tempDivisionlist!=null)
                {
                    for(Division__c div : tempDivisionlist)  
                    {
                        System.debug(div.Status__c);
                        if(div.First_Awarded_Date__c!=null)
                        {
                            Account acc =  accMap.get(div.Account__c);
                            if(acc.of_Awarded_Divisions__c != null)
                            {
                                acc.of_Awarded_Divisions__c  = acc.of_Awarded_Divisions__c + 1;
                            }
                            else
                            {
                                acc.of_Awarded_Divisions__c = 1;
                            }
                            accMap.put(acc.Id,acc);
                        }
                        if(div.Status__c=='Blacklisted')
                        {
                            System.debug('Hello I am here');
                            Account acc =  accMap.get(div.Account__c);
                            if(acc.of_Blacklisted_Divisions__c  != null)
                            {
                                acc.of_Blacklisted_Divisions__c   = acc.of_Blacklisted_Divisions__c  + 1;
                            }
                            else
                            {
                                acc.of_Blacklisted_Divisions__c  = 1;
                            }
                            accMap.put(acc.Id,acc);
                        }
                        if(div.First_Awarded_Date__c ==null&&div.First_Participation_Date__c!=null)
                        {
                            Account acc =  accMap.get(div.Account__c);
                            if(acc.of_Participated_Divisions__c  != null)
                            {
                                acc.of_Participated_Divisions__c  = acc.of_Participated_Divisions__c + 1;
                            }
                            else
                            {
                                acc.of_Participated_Divisions__c = 1;
                            }
                            accMap.put(acc.Id,acc);
                        }
                        if(div.First_Invoice_Load_Date__c!=null)
                        {
                            Account acc =  accMap.get(div.Account__c);
                            if(acc.of_Divisions_ever_having_AP__c   != null)
                            {
                                acc.of_Divisions_ever_having_AP__c   = acc.of_Divisions_ever_having_AP__c  + 1;
                            }
                            else
                            {
                                acc.of_Divisions_ever_having_AP__c  = 1;
                            }
                            
                            accMap.put(acc.Id,acc);
                        } 
                        
                        Account acc =  accMap.get(div.Account__c);
                        if(acc.of_DIvisions__c   != null)
                        {
                            acc.of_DIvisions__c   = acc.of_DIvisions__c  + 1;
                        }
                        else
                        {
                            acc.of_DIvisions__c  = 1;
                        }
                        
                        accMap.put(acc.Id,acc);
                        
                        
                    }
                }
                
            }
            update accMap.values();
        }
        
    }
    
    
}
I have a method "processResults(<Campaign ID>)" which calls batch class for bulk processing, which does API callout and after callout it does DML operation.

Now I want to call this method using scheduler (every week) to process camapigns in the org and pass camapaign Id for each call.

How I can achieve this?

A. I can not use batch class, as it will throw "Asyncexception."
B. I can not call this method twice in same trasaction as it will throw "Uncommited work pending exception".
 
We have a custom reset password functionality for our portal users and we need to add 2FA (mobile verification code) authentication method while resetting this password.

How we can achieve this?
Can somebody please tell me how to write a below given query in batach apex which I have writte in start method and then sent them to the execute method.

However ,My problem is I am not able to write where clause

string query='SELECT ID,Ownerid,Accountid,prestigious_contact__c from contact where assistantname='Christy'' && level__c='Primary' && prestigious_contact__c';

This  query is for the Batch Apex class.
1)Assistantname field is text
2) level__c is a picklist field
3)prestigious_contact__c is  a boolean field which is checkbox on the contact object


 
I am using dataloader to update and insert 1000 records. How many times will trigger and workflow fire in overall process 
global class DeleteAccountRecords implements Database.Batchable<sObject>{
    global DeleteAccountRecords(){
    }

    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator([
            select Id
            from Account
            where CreatedDate = LAST_N_DAYS:7
            ]);
    }

    global void execute(Database.BatchableContext BC, List<Account>scope){
        delete scope;
    }

    global void finish(Database.BatchableContext BC){
    }
}
 
global class Scheduler_class implements Schedulable{
    global void execute (SchedulableContext SC){
         DeleteAccountRecords b1 = new  DeleteAccountRecords();
       database.executeBatch(b1);
       string sch = '0 0 * * 0 ?';
       system.schedule ('Batch', sch, new Scheduler_class());
    }
}


Please correct me where I was going wrong

Thanks

I have a custom object named MDU_Squad to which I insert records using the Data Import Wizard. 
I have set 2 external ID fields in there, which are
1. Street_address [allow duplicates]
2. CIty_Name [allow duplicates]
Both the fields above have duplicate records as well.

I have created a batch class that pulls in all the records from the above MDU_Squad custom object and inserts into City_Master & Address_Master custom objects getting rid of all the duplicates. So at the end I will be having a master City_Master & Address_Master custom objects with no duplicates
The City_Master & Address_Master custom objects have external ids set, which are city_Name_Ext_Id & address_Ext_Id. Both the fields can't have any duplicates.

I am trying to use the upsert method, to have it insert if the record does not exist in the City_Master or Address_Master custom object or update if they exist in the object.
Here in the below code the addressList and the cityList objects have non-duplicate records which are extracted from the MDU_Squad which are to be saved to the Address_Master and City_Master custom objects.
 
Database.SaveResult[] saveAddressMaster = Database.Upsert(addressList, sumchans__MDU_Squad__c.STREET_ADDRESS__c, all);  
Database.SaveResult[] saveCityMaster = Database.Upsert(cityList, sumchans__MDU_Squad__c.City_Name__c, all);
Someone please help.

 
I created a protected custom setting in my managed application and installed it on my Dev Edition org and inserted a secret. However, I can still view/edit this secrets from the UI as a sysadmin. Can you tell me what I'm doing wrong here?
I'm trying to come up with a SOQL query that displays the following:


Account Name | Opportunity Closed Date (most recent, won) | Product Purchased | Opportunity Amount

So far I've only been able to get as far as this:
 
SELECT Account.Name, CloseDate, Amount, (SELECT Product2.Name FROM OpportunityLineItems) FROM Opportunity WHERE IsClosed = true AND StageName = 'Closed Won'

 


If this is not possible with SOQL, is it possible with Salesforce Reports? Thank you!

i have  designed a apex class on custom object where it checks the duplicate value for Specific recordtype, it is invoked by a trigger handler, i am getting this error - 

QuotaTrigger: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object Class.QuotaTriggerHandler.dupQuotaError: line 5, column 1 Trigger.QuotaTrigger: line 3, column 1

I tried Googling the error but still   not able to Resolve the error, Any suggestions please

QuotaTrigger
 
trigger QuotaTrigger on Quota__c (before insert, before update) {

    QuotaTriggerHandler.dupQuotaError(Trigger.new);
    
}

QuotaTriggerHandler
 
public class QuotaTriggerHandler {
    
    public static void dupQuotaError (List <Quota__c> newTrigCon) {
        
        Id recordTypeId = Schema.SObjectType.Quota__c.getRecordTypeInfosByDeveloperName().get('Inside Sales Target(IS)').getRecordTypeId();
        
        //List of all Contact Records currently in the database    
        List <Quota__c> allCon = [SELECT ID, Name, Assignedto__c, Quater_Year__c, RecordTypeId, Month__c FROM Quota__c where RecordTypeId=:recordTypeId];
        
        //Iterate through new potential records
        for (Quota__c oneConTrig : newTrigCon) {
            
            //Needed to iterate through all existing records which is contained in the allCon List
            for (Integer i = 0; i < allCon.size(); i++)
                
                //If all conditions are met, there is a duplicate and thus, returns an error.
                if (oneContrig.Assignedto__c == allCon[i].Assignedto__c 
                    && oneContrig.Quater_Year__c == allCon[i].Quater_Year__c 
                    && oneConTrig.Month__c == allCon[i].Month__c
                    && oneConTrig.RecordTypeId == recordTypeId) {
                        
                        oneConTrig.addError('Duplicate Quota Detected! This record already exists.');
                        
                    }
        }      
    }
}

How do i resove this issue
Hi,
I need to dispaly an apex:message in my center of my vf page 
how can i do that ?
Hi, I've created a custom, VF Page. It is having two pageBlockTables inside it. When I click a button "Get Records" the two tables should get refreshed. I am trying to refresh my entire page Block but that's not working n my case. I am attaching my page here along with a screenshot of my page.
 <apex:page standardController="Account" extensions="newWrapperClass">
    <apex:form >
        <apex:pageMessages></apex:pageMessages>
        <apex:pageBlock id="block">
            <apex:pageBlockButtons location="bottom">
                <apex:commandButton value="Get Records" action="{!processedRecords}" reRender="table1,table2"/>
                <apex:commandButton value="Send Email" action="{!sendEmail}"/>
            </apex:pageBlockButtons>
            <apex:pageBlockSection title="Detail Records">
                <apex:pageBlockTable value="{!wrapperTaskList}" var="wrap" id="table1">
                <apex:column >
                    <apex:inputCheckbox value="{!wrap.selected}"/>
                </apex:column>
                <apex:column value="{!wrap.chg.Name}" headerValue="Name"/>
                <apex:column value="{!wrap.chg.Phone__c}" headerValue="Phone"/>
                </apex:pageBlockTable>
                <apex:pageBlockTable value="{!existingRecords}" var="sel" id="table2">
                    <apex:column value="{!sel.Name}" headerValue="Name"/>
                    <apex:column value="{!sel.Phone__c}" headerValue="Phone"/>
                </apex:pageBlockTable>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>User-added image
  • February 27, 2020
  • Like
  • 0
We have a Salesforce org that uses a Salesforce Community. Is there a known security limitation on a Community User executing the Messaging Class SendEmail method in Apex? We are attempting to email a contact via Apex as the Community User.

Any user other than the community user can execute the SendEmail function as found in Apex. 

Please note, the Community user has a special profile that is only accessible via Salesforce Sites. The profile has the needed Apex Access and the following System Permissions are enabled...
  • Mass Email
  • Send Email
Please advise.
I am callling one method of different class from another merhod of different class, called method searches for record  and if not found it will create a record.(both methods are highlighted in bold).

I want if the search method (searches the record in MDM- third party) returns any record then only the create  method (addAccFromGaine) will execute.
Plesae help
/**
* @author: Shubham Sinha
* @date: 02/10/2020
* @description: This class is used for creating User Account and User records when a person tries to Login through Janrain
**/

Public Class BIIB_CreateAccountAndUser_Helper{
    /**
* 
* @description: Wrapper class for User and Account Creation, getting wrapper values from BIIB_ADU_Janrain_AuthProviderHandler Class

**/    
    Public class RegistrationDetails {
        
        public String firstName;
        public String lastName;
        public String fullName;
        public String email;
        public String username;
        public String locale;
        public String provider;
        Public String siteLoginUrl; 
        Public String identifier; 
        Public String link;
        Public Map<String,String> attributeMap;
        
        Public RegistrationDetails(){
            this.firstName ='';
            this.lastName ='';
            this.fullName = '';
            this.email= '';
            this.username = '';
            this.locale = '';
            this.provider ='';
            this.siteLoginUrl= '';
            this.identifier ='';
            this.link = '';
            
        }
    }
    /**
* @author: Shubham Sinha
* @description: Creates User Account and Patient therapy record.

**/
    public Static User createUserAccount(registrationDetails regDetailsWrapObj){
        Product_vod__c prodCatlog = [SELECT Name FROM Product_vod__c WHERE Name = :System.label.BIIB_Product_Aducanumab][0];
        Id recordTypeId = Schema.SObjectType.BIIB_Patient_Therapy__c.getRecordTypeInfosByName().get('Aducanumab').getRecordTypeId();
        Id recordTypeIdAccount = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Patient').getRecordTypeId();
        
        List<Account> checkAccountData = [SELECT id,FirstName, LastName, PersonEmail,BIIB_PASS_Zip_Code__c FROM Account 
                                          WHERE LastName =: regDetailsWrapObj.LastName AND FirstName =:regDetailsWrapObj.FirstName
                                          
                                           Limit 1 ];
        Account createAccount;
        if(checkAccountData.size()> 0)
        {
            createAccount = checkAccountData[0];
            BIIB_Patient_Therapy__c patTherapy = new BIIB_Patient_Therapy__c();
            patTherapy.RecordTypeId = recordTypeId;
            patTherapy.BIIB_Indication__c = System.label.BIIB_Patient_Therapy_Indication;
            patTherapy.BIIB_Therapy__c = prodCatlog.id;
            patTherapy.BIIB_Patient__c= createAccount.id;
            
            insert patTherapy;
        }
        else 
        {
      
           
            createAccount = new Account ();
            createAccount.FirstName= regDetailsWrapObj.firstName;
            createAccount.LastName =regDetailsWrapObj.lastName;
            createAccount.RecordTypeId = recordTypeIdAccount;
            insert createAccount;
 
          BIIB_Patient_Therapy__c accPatTherapy = new BIIB_Patient_Therapy__c();
            accPatTherapy.BIIB_Indication__c = System.label.BIIB_Patient_Therapy_Indication;
            accPatTherapy.BIIB_Therapy__c = prodCatlog.id;
            accPatTherapy.BIIB_Patient__c= createAccount.id;
            insert accPatTherapy;
            
            String searchTermFirst = regDetailsWrapObj.firstname;
            String searchTermLast = regDetailsWrapObj.Lastname;
            String email = regDetailsWrapObj.email;
            
         // Calling the method from SearchPatientController to search the record in MDM

            ApexPages.StandardController accStdControllerObj = new ApexPages.StandardController(new Account());
            SearchPatientController tc = new SearchPatientController(accStdControllerObj);
            tc.getMDMSearchResult( searchTermFirst, searchTermLast, null,null,email,null,null,null,null,null,null,null,null,null); 
          // this method creates the record.
           ApexPages.StandardController accStdControllerOb = new ApexPages.StandardController(new Account());
              SearchPatientController add = new SearchPatientController(accStdControllerOb);
             add.addAccFromGaine(); 
                   }
     
        User aduUser = createAduCommunityUser(regDetailsWrapObj, createAccount.id);
        return aduUser;
    }
}

 
The number of API calls seems to be increasing and I can't figure out why. I ran the Administrative report for API calls in the last 7 days. However, that does not tell me what process is using the API calls. The user with the highest number of calls is the user we have assigned to all of our automated processes. Is there a way to see what process is using the most API calls?
Hi I have created a customized lead conversion page  using lightning web component on click of which I want to display standard "Your lead has been converted" popup window. How can I implement this?

User-added image
|FATAL_ERROR|System.NullPointerException: Attempt to de-reference a null object

I'm getting the above error in this piece of code
//Returns the Rating Release date or the 'rating pending'
        IF (Today < currentQRpCase.Rating_Externally_Visible_Date__c){
            RatingRelease = 'Rating Pending';
        } else IF(Today > currentQRpCase.Rating_Externally_Visible_Date__c){
            RatingRelease = currentQRpCase.Rating_Externally_Visible_Date__c.format();
        } else {
            RatingRelease = '';
        }

On my test record, Rating_Externally_Visible_Date__c is not null.
 
Help troubleshooting!
I trying to test the Apex Call outs which uses the OAuth Authentication. I am not sure what I am missing here it throws error on the line HttpResponse res1 = http1.send(req1); like 

Line: 22, Column: 1
System.UnexpectedException: java.lang.IllegalArgumentException: invalid start or end
public class TestD365API {
    public final String clientId = 'xxxxxxxxxxxxx';
    public final String clientSecret = 'xxxxxxxx';
    
    public String getD365Customer(){             
        String reqbody = 'grant_type=client_credentials&client_id='+clientId+'&client_secret='+clientSecret;
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setBody(reqbody);
        req.setMethod('POST');
        req.setEndpoint('https://login.microsoftonline.com/tenant/oauth2/token');
        HttpResponse res = h.send(req);
        deserializeResponse resp1 = (deserializeResponse)JSON.deserialize(res.getbody(),deserializeResponse.class);
        String atoken = resp1.access_token;
        
        
        Http http1 = new Http();
        HttpRequest req1 = new HttpRequest();
        req1.setEndpoint('https://dev-xyz/data/Customers');
        req1.setMethod('GET');
        req1.setHeader('Authorization','Bearer '+atoken);
        HttpResponse res1 = http1.send(req1);
        System.debug('Response Body=========' + res1.getBody());
        return res1.getBody();   
    }  
    
    public class deserializeResponse
    {
        public String token_type;
        public String expires_in;
        public String ext_expires_in;
        public String expires_on;
        public String not_before;
        public String resource;
        public String access_token;
    }
}
Please help me fixing this issue.
  • February 13, 2020
  • Like
  • 0
I trying to test the Apex Call outs which uses the OAuth Authentication. I am not sure what I am missing here it throws error on the line HttpResponse res1 = http1.send(req1); like 

Line: 22, Column: 1
System.UnexpectedException: java.lang.IllegalArgumentException: invalid start or end
public class TestD365API {
    public final String clientId = 'xxxxxxxxxxxxx';
    public final String clientSecret = 'xxxxxxxx';
    
    public String getD365Customer(){             
        String reqbody = 'grant_type=client_credentials&client_id='+clientId+'&client_secret='+clientSecret;
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setBody(reqbody);
        req.setMethod('POST');
        req.setEndpoint('https://login.microsoftonline.com/tenant/oauth2/token');
        HttpResponse res = h.send(req);
        deserializeResponse resp1 = (deserializeResponse)JSON.deserialize(res.getbody(),deserializeResponse.class);
        String atoken = resp1.access_token;
        
        
        Http http1 = new Http();
        HttpRequest req1 = new HttpRequest();
        req1.setEndpoint('https://dev-xyz/data/Customers');
        req1.setMethod('GET');
        req1.setHeader('Authorization','Bearer '+atoken);
        HttpResponse res1 = http1.send(req1);
        System.debug('Response Body=========' + res1.getBody());
        return res1.getBody();   
    }  
    
    public class deserializeResponse
    {
        public String token_type;
        public String expires_in;
        public String ext_expires_in;
        public String expires_on;
        public String not_before;
        public String resource;
        public String access_token;
    }
}
Please help me fixing this issue.
  • February 13, 2020
  • Like
  • 1
I have a for loop running through a list which add items from one list to another list. The source list has 8 records, and the new list will get only 7 records.
for(sumchans__Address_Master__c city: addressList) {
            sumchans__City_Master__c theCity = new sumchans__City_Master__c();
            theCity.Name = city.sumchans__City_Name__c;
            theCity.sumchans__City_Name_Ext_Id__c = city.sumchans__City_Name__c;related data.
            theCity.sumchans__Province_Code__c = city.sumchans__Province_Code__c;
            cityList.add(theCity);
        }

Please help

THanks
Hi All,
I am weak in writing test class. I have written a controller class related to external object. I want to write test class for the same.
This is my controller class
global class DataSourcCon extends DataSource.Connection {

    public String LookupUrl {get; set;}

    global DataSourcCon(DataSource.ConnectionParams  connectionParams) {
        
    }
    
   global DataSourcCon(DataSource.ConnectionParams  connectionParams, String baseURL) {
       
        LookupUrl = baseURL;
   }

    override public DataSource.TableResult query(DataSource.QueryContext context)
    {
        
        String SOQLObject = context.tableSelection.columnsSelected.get(0).tableName;
        
        
        DataSource.Filter filter = context.tableSelection.filter;
        
      
      String validslordNumber = '666'; 
      String validgoId = '900'; 
      
      List<Map<String,String>> resultMap=new List<Map<String,String>>();    
      if(SOQLObject == 'sp_ord')
      {
        
        IntClass intdord = new IntClass();
        IntClass.SearchParameters searchParameter = new IntClass.SearchParameters();
            if(filter != null && filter.columnName != null && filter.columnValue != null)
            {
                if(filter.columnName == 'g_o_Id')    
                {
                    searchParameter.oppgRecId = String.valueof(filter.columnValue);
                }
                else if(filter.columnName == 'sl_ord_number')
                {
                    searchParameter.slordNumber = String.valueof(filter.columnValue);
                }
            }
            else
            {
                searchParameter.oppgRecId = validgoId;
            }
        intdord.searchParam = searchParameter; 
        
        IntWrap.SearchslordResponse resp = null;
        IntServ service = new IntServ();
        resp = (IntWrap.SearchslordResponse) service.getordchapByCriteria(intdord);
     
        IntViHel  helper=new IntViHel();
        resultMap = helper.getResponseDataAsListMap(resp);
        
        return DataSource.TableResult.get(context,resultMap);         
      }
      else if(SOQLObject == 'chap')
      {
        
        
        IntClass intdchap = new IntClass();
        IntClass.SearchParameters searchParameter = new IntClass.SearchParameters();
            
            if(filter != null && filter.columnName != null && filter.columnValue != null)
            {
                if(filter.columnName == 'g_o_Id')    
                {
                    searchParameter.oppgRecId = String.valueof(filter.columnValue);
                }
                else if(filter.columnName == 'sp_ord')
                {
                    searchParameter.slordNumber = String.valueof(filter.columnValue);
                }
            }
            else
            {
                searchParameter.oppgRecId = validgoId;
            }
        intdchap.searchParam = searchParameter; 
       
        IntWrap.SearchslordResponse resp = null;
        IntServ service = new IntServ();
        resp = (IntWrap.SearchslordResponse) service.getordchapByCriteria(intdchap);
        
        IntViHel  helper=new IntViHel();
        resultMap = helper.getResponseDataAsListMap(resp);
               
        return DataSource.TableResult.get(context,resultMap);         
      }
      else
      {
          return null;
      }
    
    }
    public DataSource.TableResult queryfromDBC(DataSource.QueryContext context)
    {
        
        System.PageReference lookupURL = Apexpages.currentPage();
        
        if (context.tableSelection.columnsSelected.size() == 1
            && context.tableSelection.columnsSelected.get(0).aggregation == DataSource.QueryAggregation.COUNT)
        {
            
            List<Map<String,Object>> rows = getRows(context);
           
            List<Map<String,Object>> response = DataSource.QueryUtils.filter(context, getRows(context));

            List<Map<String, Object>> countResponse = new List<Map<String, Object>>();
            Map<String, Object> countRow = new Map<String, Object>();

            countRow.put(context.tableSelection.columnsSelected.get(0).columnName,response.size());
            countResponse.add(countRow);
            return DataSource.TableResult.get(context,countResponse);
        }
        else
        {
            
            List<Map<String,Object>> filteredRows = DataSource.QueryUtils.filter(context, getRows(context));
            List<Map<String,Object>> filteredRowsCustom = filterRows(context, getRows(context));
            List<Map<String,Object>> sortedRows = DataSource.QueryUtils.sort(context, filteredRows);
            
            List<Map<String,Object>> limitedRows = DataSource.QueryUtils.applyLimitAndOffset(context,sortedRows);
            return DataSource.TableResult.get(context, limitedRows);
        }
    }

    override global List<DataSource.TableResult> search(DataSource.SearchContext c) { 
              
        List<DataSource.TableResult> results = new List<DataSource.TableResult>();
        for (DataSource.TableSelection tableSelection : c.tableSelections) {
            results.add(DataSource.TableResult.get(tableSelection, findRows(c)));
        }
        return results;
    }

    global override List<DataSource.UpsertResult> upsertRows(DataSource.UpsertContext 
            context) {
       
       if (context.tableSelected == 'Sample') {
           List<DataSource.UpsertResult> results = new List<DataSource.UpsertResult>();
           List<Map<String, Object>> rows = context.rows;
           
           for (Map<String, Object> row : rows){
              
              HttpResponse response;
              
              if (row.get('ExternalId') == null){
                 
                     response = null;
              }
              else {
                 
                   response = null;  
              }
         
              Map<String, Object> m = (Map<String, Object>)JSON.deserializeUntyped(
                      response.getBody());
              if (response.getStatusCode() == 200){
                  results.add(DataSource.UpsertResult.success(
                          String.valueOf(m.get('id'))));
              } 
              else {
                 results.add(DataSource.UpsertResult.failure(
                         String.valueOf(m.get('id')), 
                         'The callout resulted in an error: ' + 
                         response.getStatusCode()));
              }
           } 
           return results;
       } 
       return null;
    }

   
    global override List<DataSource.DeleteResult> deleteRows(DataSource.DeleteContext 
            context) {
       if (context.tableSelected == 'Sample'){
           List<DataSource.DeleteResult> results = new List<DataSource.DeleteResult>();
           for (String externalId : context.externalIds){
             
              HttpResponse response = null;
              if (response.getStatusCode() == 200){
                 results.add(DataSource.DeleteResult.success(externalId));
              } 
              else {
                 results.add(DataSource.DeleteResult.failure(externalId, 
                         'Callout delete error:' 
                         + response.getBody()));
              }
           }
           return results;
       }
       return null;
     }
  
    private DataSource.DataType getFieldDataType(String dataType)
    {
        
        DataSource.DataType fieldType;
        
        if(dataType == 'Checkbox')
            fieldType = DataSource.DataType.BOOLEAN_TYPE;   
        else if(dataType == 'Date/Time')
            fieldType = DataSource.DataType.DATETIME_TYPE;  
        else if(dataType == 'Lookup Relationship')
            fieldType = DataSource.DataType.LOOKUP_TYPE;  
        else if(dataType == 'External lookup relationship')
            fieldType = DataSource.DataType.EXTERNAL_LOOKUP_TYPE;  
        else if(dataType == 'Indirect lookup relationship')
            fieldType = DataSource.DataType.INDIRECT_LOOKUP_TYPE;  
        else if(dataType == 'Number')
            fieldType = DataSource.DataType.NUMBER_TYPE;
        else if(dataType == 'Text (40)')
            fieldType = DataSource.DataType.STRING_SHORT_TYPE;
        else if(dataType == 'Text Area (255)')
            fieldType = DataSource.DataType.STRING_LONG_TYPE;
        else if(dataType == 'Text Area Long (32768)')
            fieldType = DataSource.DataType.STRING_LONG_TYPE;
        else if(dataType == 'URL')
            fieldType = DataSource.DataType.URL_TYPE; 

        return fieldType;
    }

    
    private DataSource.Column setupCustomFieldData(ext_External_Field__c extField)
    {   
        
        DataSource.DataType fieldType = getFieldDataType(extField.Data_Type__c);
        DataSource.Column fieldData;
        Integer fieldLength = 0;
        Integer fieldDecimalsLength = 0;
       
        if(fieldType == DataSource.DataType.NUMBER_TYPE)
        {    
            fieldLength = ((extField.Length__c + extField.Decimal_Places__c) <= 18) ? Integer.valueof(extField.Length__c) : 16;
            fieldDecimalsLength = ((extField.Length__c + extField.Decimal_Places__c) <= 18) ? Integer.valueof(extField.Decimal_Places__c) : 2;
        }
        else if(fieldType == DataSource.DataType.STRING_SHORT_TYPE)
        {    
            fieldLength = (extField.Data_Type__c == 'Text (40)') ? 40 : 255;
        }
        else if(fieldType == DataSource.DataType.STRING_LONG_TYPE)
        {    
            fieldLength = 32768;
        }

        if(fieldType == DataSource.DataType.LOOKUP_TYPE)
        {
            fieldData = DataSource.Column.lookup(extField.Name, extField.ReferenceTo__c);
            
			
        }
        else if(fieldType == DataSource.DataType.EXTERNAL_LOOKUP_TYPE)
        {
            fieldData = DataSource.Column.externalLookup(extField.Name, extField.ReferenceTo__c);
           
        }
        else if(fieldType == DataSource.DataType.INDIRECT_LOOKUP_TYPE)
        {
            fieldData = DataSource.Column.indirectLookup(extField.Name, extField.ReferenceTo__c, extField.ReferenceTargetField__c);
           
        }
        else if(fieldType != DataSource.DataType.LOOKUP_TYPE && fieldType != DataSource.DataType.EXTERNAL_LOOKUP_TYPE && 
            fieldType != DataSource.DataType.INDIRECT_LOOKUP_TYPE)
        {
            fieldData = DataSource.Column.get(extField.Name, extField.Field_Label__c, extField.Description__c, extField.Sortable__c, extField.Filterable__c, fieldType, fieldLength, fieldDecimalsLength, null, null); 
        }

        return fieldData;
    }

   
    private DataSource.Table setupTableData(ext_External_Object__c extObj, List<DataSource.Column> columns_extObj)
    {   
        
        DataSource.Table extObj_Table = new DataSource.Table();
          extObj_Table.labelSingular = extObj.Label_Singular__c;
          extObj_Table.labelPlural = extObj.Label_Plural__c;
          extObj_Table.name = extObj.Name;
          extObj_Table.description = extObj.Description__c;
         
          extObj_Table.nameColumn = extObj.Name_Column__c;
         
          extObj_Table.columns = columns_extObj; 

        return extObj_Table;
    }

    
    private List<Map<String,Object>> filterRows(DataSource.QueryContext context, List<Map<String,Object>> allRows){
       
        List<Map<String,Object>> objRowList = new List<Map<String,Object>>();
        DataSource.TableSelection tableSelection=null;
        String tableName = null;
        if(context != null){
            tableSelection = context.tableSelection;
            tableName=tableSelection.tableSelected;
            
            if(tablename.equalsIgnoreCase('sp_ord'))
            {
                
            }
        }
        return objRowList;
    }   

    private List<Map<String,Object>> getObjRows(DataSource.QueryContext c){
        List<Map<String,Object>> objRowList=new List<Map<String,Object>>();
        DataSource.TableSelection tableSelection=null;
        String tableName=null;
        if(c!=null){
           tableSelection=c.tableSelection;
           tableName=tableSelection.tableSelected;
          
           
        }
        return objRowList;
    }   
    
   

    private List<Map<String,Object>> getRows(DataSource.ReadContext context)
    {
      
        List<Map<String, Object>> rows = new List<Map<String, Object>>();

        DataSource.QueryContext myContext = (DataSource.QueryContext)context;
        
        DataSource.Filter filter = myContext.tableSelection.filter;
        
        return rows;
    }

    private List<Map<String,Object>> findRows(DataSource.ReadContext context)
    {

        List<Map<String, Object>> rows = new List<Map<String, Object>>();

        DataSource.ReadContext myContext = (DataSource.ReadContext)context;
        
        

        return rows;
    }

     private Map<String,Object> foundRow(Map<String,Object> foundRow) {
        Map<String,Object> row = new Map<String,Object>();
        row.put('ExternalId', string.valueOf(foundRow.get('Id')));
        row.put('DisplayUrl', string.valueOf(foundRow.get('DisplayUrl')));
        row.put('Name', string.valueOf(foundRow.get('Name')));        
        return row;
    }
   
    private static HttpResponse makeGetCallout() {
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setEndpoint('https://test.com');
        req.setMethod('GET');
        HttpResponse response=h.send(req);         
        return response;
    }    

   
}
Please help me how to write test class for this

Thanks in Advance

 
Hello everyone,

When I am working with workflows, One question is roaming through my mind  i.e why don't we have time-dependent workflows actions when the evaluation criteria are "every time record is created and edited"


Thanks..........
  • February 03, 2016
  • Like
  • 1