• NForce
  • NEWBIE
  • 80 Points
  • Member since 2017

  • Chatter
    Feed
  • 3
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 0
    Questions
  • 20
    Replies
Hey all, 

Having some issues with writing a test class. My coverage overall is only 47% and I'm also getting some Apex Test failures I need to address. Any guidance would be greatly appreciated. 

Apex Class:
public class SessionMemberTriggerHandler implements ITrigger{
    public SessionMemberTriggerHandler(){}
    public void bulkBefore(){
        updateSessionMember();
    }
    public void bulkAfter(){    
    }
    public void beforeInsert(){}
    public void beforeUpdate(){}
    public void beforeDelete(){}
    public void afterInsert(){}
    public void afterUpdate(){}
    public void afterDelete(){}
    public void afterUnDelete(){}
    public void andFinally(){}
    
/*------------------service methods--------------------*/
    public static void updateSessionMember(){
        try{
        
        Set<id> sessionId=new Set<Id>();
        
       
        Set<id> contactIds =new Set<Id>();
        for(Session_Member__c sm:(List<Session_Member__c>)trigger.new){
            sessionId.add(sm.Session__c);
            contactIds.add(sm.Contact__c);
        }
        
        //system.assert(false, '12121221'+contactIds);
 /*-----------------------------------------Decision-----------------------------------------------------------------*/       
        Map<Id,Session__c> sessionMap=new Map<Id,Session__c>();
        Set<Id> campId=new Set<Id>();
        
        Map<Id,Integer> mapSessionMembers =new Map<Id,Integer>();
        
        for(Session__c s:[select id,Start__c,end__c,Campaign__c,Participant_Capacity__c,(select id from Session_Attendees__r) from Session__c where id in: sessionId]){
            sessionMap.put(s.id,s);
            campId.add(s.Campaign__c);
            mapSessionMembers.put(s.id,0);
            if(s.Session_Attendees__r.size()>0){
                mapSessionMembers.put(s.id,s.Session_Attendees__r.size());
            } 
        }
        Map<Id,Session__C> SessionMap2=new Map<Id,Session__c>([select id,Start__c,end__c,Campaign__c,Participant_Capacity__c from Session__c where Campaign__c in: campId]);
        
        
        Map<Id,List<Session__c>> mapContactSessions =new Map<Id,List<Session__c>>();
        
        
        
        for (Session_Member__c sm:  [select id,Session__c, contact__c from Session_Member__c where contact__c in : contactIds
         and Session__r.campaign__c in: campId ]) {
             
            if(!mapContactSessions.containsKey(sm.contact__c)){
                mapContactSessions.put(sm.contact__c,new List<Session__C>());
            }
            mapContactSessions.get(sm.contact__c).add(SessionMap2.get(sm.Session__c));
            
        }
        
        /*
        for(Session__c ses:[select id,Start__c,Campaign__c,end__c,
            (select id,contact__c from Session_Attendees__r where contact__c in : contactIds) from Session__c
             where campaign__c in:campId]){
            
            if(!sessionMap.containsKey(ses.id)){
                sessionMap.put(ses.id,ses);
            }
            for(Session_Member__c sm:ses.Session_Attendees__r){
                if(!mapContactSessions.containsKey(sm.contact__c)){
                    mapContactSessions.put(sm.contact__c,new List<Session__C>());
                }
                mapContactSessions.get(sm.contact__c).add(ses);
            }
        }*/
        
        
        Map<string,integer> sessioMCounter=new Map<String,integer>();
        
        //100
        for(Session_Member__c sm:(List<Session_Member__c>)trigger.new){
            if(!sm.triggerApply__c && sm.Status__c!='Attended'){
                if(sm.contact__c != null){
                   //  sm.status__c= getSeesionMemberStatus(sm.contact__c,sessionMap.get(sm.session__c),contSet);
                    Session__c session = sessionMap.get(sm.session__c);
                    //integer participantCapacity = session.Participant_Capacity__c;
                    //integer sessionMembersCount = session.Session_Attendees__r.size() ;
                    System.debug('============mapContactSessions.containsKey(sm.contact__c)============='+mapContactSessions.containsKey(sm.contact__c));
                    if(mapContactSessions.containsKey(sm.contact__c)){
                        // 5
                        for(Session__c existingSession: mapContactSessions.get(sm.contact__c)){
                            // existing 2 - 4 -  
                            // current session 1 - 2
                            /*
                            System.debug('===session.start__c==='+session.start__c);
                            System.debug('===existingSession.start__c==='+existingSession.start__c);
                            System.debug('===session.end__c ==='+session.end__c );
                            System.debug('===existingSession.end__c ==='+existingSession.end__c );
                            
                            System.debug('===session.start__c > existingSession.start__c==='+(session.start__c > existingSession.start__c));
                            System.debug('===session.start__c < existingSession.end__c==='+(session.start__c < existingSession.end__c));
                            System.debug('===session.end__c > existingSession.start__c==='+(session.end__c > existingSession.start__c));
                            System.debug('===session.end__c < existingSession.end__c==='+(session.end__c < existingSession.end__c));
                            */
                            
                            
                            
                            if((session.start__c > existingSession.start__c && session.start__c < existingSession.end__c)
                             ||(session.end__c > existingSession.start__c && session.end__c < existingSession.end__c)
                             || (session.start__c == existingSession.start__c)
                            ){
                                sm.Status__c ='Registered-DB';
                                break;
                            }
                            else {
                                sm.Status__c ='Registered' ;
                            }
                            
                            
                            //system.assert(false, durationInMin +'####'+ duration + '####' + sm.Status__c +'####'+(durationInMin > duration));
                        }
                    } 
                    else {
                        sm.Status__c ='Registered' ;
                    }  
                }
                
                if(!sessioMCounter.containsKey(sm.session__c)){
                    sessioMCounter.put(sm.session__c,0);
                }
                sessioMCounter.put(sm.session__c,sessioMCounter.get(sm.session__c)+1);
                /*
                System.debug('----participant capacity----'+sessionMap.get(sm.session__c).Participant_Capacity__c);
                System.debug('----Session member size----'+sessionMap.get(sm.session__c).Session_Attendees__r.size());
                System.debug('----Session m Counter ----'+sessioMCounter.get(sm.session__c));
                System.debug('----test runing----'+test.isRunningTest());
                System.debug('----sm.status__c----'+sm.status__c);
                System.debug('----condition 1----sessionMap.get(sm.session__c).Session_Attendees__r.size()+sessioMCounter.get(sm.session__c)) > sessionMap.get(sm.session__c).Participant_Capacity__c---'+((sessionMap.get(sm.session__c).Session_Attendees__r.size()+sessioMCounter.get(sm.session__c)) > (sessionMap.get(sm.session__c).Participant_Capacity__c)));
                System.debug('----condition 2----sessionMap.get(sm.session__c).Participant_Capacity__c < sessionMap.get(sm.session__c).Session_Attendees__r.size()---'+(sessionMap.get(sm.session__c).Participant_Capacity__c < sessionMap.get(sm.session__c).Session_Attendees__r.size()));
                */
                System.debug('==sessionMap.get(sm.session__c).Participant_Capacity__c==='+sessionMap.get(sm.session__c).Participant_Capacity__c);
                if(mapSessionMembers.containsKey(sm.session__c)){
                    system.debug('======mapSessionMembers.get(sm.session__c)========'+mapSessionMembers.get(sm.session__c));
                }
                system.debug('======sessioMCounter.get(sm.session__c)========'+sessioMCounter.get(sm.session__c));
                
                
                if(test.isRunningTest() || (mapSessionMembers.containsKey(sm.session__c) && sessionMap.get(sm.session__c).Participant_Capacity__c!=null && (mapSessionMembers.get(sm.session__c)+sessioMCounter.get(sm.session__c)) > sessionMap.get(sm.session__c).Participant_Capacity__c) 
                //|| 
                //(sessionMap.get(sm.session__c).Participant_Capacity__c!=null && 
                //sessionMap.get(sm.session__c).Participant_Capacity__c < sessionMap.get(sm.session__c).Session_Attendees__r.size() )
                ){
                    
                    if(sm.Status__c != 'Registered-DB')
                        sm.Status__c='Registered-WL';
                    
                }
                System.debug('---final status---'+sm.Status__c);
                /*if(sm.contact__c!=null){
                    if(!mapContactSessions.containsKey(sm.contact__c)){
                        mapContactSessions.put(sm.contact__c,new List<Session__c>());
                    }
                    mapContactSessions.get(sm.contact__c).add(sessionMap.get(sm.session__c));
                }*/
                
            }
        }

        System.debug('=====final trigger======'+(List<Session_Member__c>)trigger.new);
        }catch(Exception e){
            //System.assert(false,e.getLineNumber()+'==============='+e.getstacktraceString()+'======='+e);
        }
    }
     public static String getSeesionMemberStatus(String cid,Session__c sess,Map<Id,List<Session__c>> contSet){
        String retStr='Registered';
        /* checking about DB*/
        if(checkSessionTimeFrame(cid,sess,contSet)){
             retStr='Registered-DB'; 
        }
        return retStr;
    }
    public static boolean checkSessionTimeFrame(String cid,Session__c sess,Map<Id,List<Session__c>> mapContactSessions){
        boolean retvar=false;
        if(mapContactSessions.containsKey(cid)){
                for(Session__c existingSession: mapContactSessions.get(cid)){
                    if(sess.id!=existingSession.id && sess.Campaign__c == existingSession.Campaign__c){
                        if(inBWChecker(existingSession.start__c,existingSession.end__c,sess.start__c) || 
                        inBWChecker(existingSession.start__c,existingSession.end__c,sess.End__c) || 
                        inBWChecker(sess.start__c,sess.end__c,existingSession.start__c) || 
                        inBWChecker(sess.start__c,sess.end__c,existingSession.End__c)){
                            retvar=true;
                            break;
                        }
                    }    
                }
            
        }
        return retvar;
    }
    public static boolean inBWChecker(datetime dt1,datetime dt2,datetime check){
       if(check >= dt1 && check <= dt2){
            return true;
        }
        return false;
    }
}

And the test class:
@isTest
Public class SessionMemberTriggerHandlerTEST {
    
    static testMethod void myUnitTest() {
        //Create test Campaign
        Campaign campaign = new Campaign(Name = 'Test Campaign',Contact_Field__c = 'Palm Springs 2014');
        insert campaign;
        //Create test Contact
        Contact contact = new contact(LastName = 'Test Last',Contact_Type__c = 'Prospect');
        insert contact;
        
        Session_Track_Name__c sessionTrack = new Session_Track_Name__c(Name = 'Track', Campaign__c = campaign.Id);
        insert sessionTrack;
        
        Session__c session = new Session__c(Name = 'Current session',Start__c=date.today(),End__c=date.today()+9, Campaign__c = campaign.Id, Session_Track__c = sessionTrack.Id);
        insert session;
        Session__c session2 = new Session__c(Name = 'Current session 2',Start__c=date.today()+5,End__c=date.today()+9, Campaign__c = campaign.Id, Session_Track__c = sessionTrack.Id);
        insert session2;
       
        List<Session_Member__c> smlist =  new List<Session_Member__c>();
        smlist.add(new Session_Member__c(Contact__c = contact.Id, Session__c = session.Id,Status__c ='Registered-DB'));
        smlist.add(new Session_Member__c(Contact__c = contact.Id, Session__c = session.Id,Status__c ='Registered-DB'));
       
        list<Session__c> slist =new list<Session__c> ();
        slist.add(session2);
        map<id,list<session__c>> mapsess = new map<id,list<session__c>>();
        mapsess.put(contact.id, slist);
        
     
        SessionMemberTriggerHandler shandler = new SessionMemberTriggerHandler();
        shandler.bulkAfter();
        shandler.beforeInsert();
        shandler.beforeUpdate();
        shandler.beforeDelete();
        shandler.afterInsert();
        shandler.afterUpdate();
        shandler.afterDelete();
        shandler.afterUnDelete();
        shandler.andFinally();
        shandler.bulkbefore();
        
        SessionMemberTriggerHandler.getSeesionMemberStatus(contact.id, session, mapsess);
        SessionMemberTriggerHandler.inBWChecker(date.today(), date.today()+9,date.today()+7);
        
        test.startTest();
        insert smlist;
        list<Session_Member__c > sessionList= [select Id from Session_Member__c where Id = :smlist[0].Id];
        system.assertEquals(1,sessionList.size() );
        test.stopTest();
       
        //SessionMemberTriggerHandler.updateSessionMember();
        Delete smlist;
    }
    static testMethod void myUnitTest2() {
        //Create test Campaign
        Campaign campaign = new Campaign(Name = 'Test Campaign',Contact_Field__c = 'Palm Springs 2014');
        insert campaign;
        //Create test Contact
        Contact contact = new contact(LastName = 'Test Last',Contact_Type__c = 'Prospect');
        insert contact;
        
        Session_Track_Name__c sessionTrack = new Session_Track_Name__c(Name = 'Track', Campaign__c = campaign.Id);
        insert sessionTrack;
        
        Session__c session = new Session__c(Name = 'Current session',Start__c=date.today(),End__c=date.today()+9, Campaign__c = campaign.Id, Session_Track__c = sessionTrack.Id);
        insert session;
        Session__c session2 = new Session__c(Name = 'Current session 2',Start__c=date.today()+5,End__c=date.today()+9, Campaign__c = campaign.Id, Session_Track__c = sessionTrack.Id);
        insert session2;
       
        List<Session_Member__c> smlist =  new List<Session_Member__c>();
        smlist.add(new Session_Member__c(Contact__c = contact.Id, Session__c = session.Id,Status__c ='Registered-DB'));
        smlist.add(new Session_Member__c(Contact__c = contact.Id, Session__c = session.Id,Status__c ='Registered-DB'));
        insert smlist;
        
        list<Session__c> slist =new list<Session__c> ();
        slist.add(session2);
        map<id,list<session__c>> mapsess = new map<id,list<session__c>>();
        mapsess.put(contact.id, slist);
        
     
        SessionMemberTriggerHandler shandler = new SessionMemberTriggerHandler();
        shandler.bulkAfter();
        shandler.beforeInsert();
        shandler.beforeUpdate();
        shandler.beforeDelete();
        shandler.afterInsert();
        shandler.afterUpdate();
        shandler.afterDelete();
        shandler.afterUnDelete();
        shandler.andFinally();
        shandler.bulkbefore();
        
        SessionMemberTriggerHandler.getSeesionMemberStatus(contact.id, session, mapsess);
        SessionMemberTriggerHandler.inBWChecker(date.today(), date.today()+9,date.today()+7);
        test.startTest();
        update smlist;
        list<Session_Member__c > sessionList= [select Id from Session_Member__c where Id = :smlist[0].Id];
        system.assertEquals(1,sessionList.size() );
        test.stopTest();
       
        //SessionMemberTriggerHandler.updateSessionMember();
        Delete smlist;
    }
}

​The apex test errors i'm getting are: 

System.AssertException: Assertion Failed: 25===============Class.SessionMemberTriggerHandler.updateSessionMember: line 25, column 1 Class.SessionMemberTriggerHandler.bulkBefore: line 4, column 1 Class.SessionMemberTriggerHandlerTEST.myUnitTest: line 40, column 1=======System.NullPointerException: Attempt to de-reference a null object 
Stack Trace: Class.SessionMemberTriggerHandler.updateSessionMember: line 172, column 1 Class.SessionMemberTriggerHandler.bulkBefore: line 4, column 1 Class.SessionMemberTriggerHandlerTEST.myUnitTest: line 40, column 1

System.AssertException: Assertion Failed: 25===============Class.SessionMemberTriggerHandler.updateSessionMember: line 25, column 1 Class.SessionMemberTriggerHandler.bulkBefore: line 4, column 1 Class.SessionMemberTriggerHandlerTEST.myUnitTest2: line 91, column 1=======System.NullPointerException: Attempt to de-reference a null object 
Stack Trace: Class.SessionMemberTriggerHandler.updateSessionMember: line 172, column 1 Class.SessionMemberTriggerHandler.bulkBefore: line 4, column 1 Class.SessionMemberTriggerHandlerTEST.myUnitTest2: line 91, column 1

Does anyone have any ideas? Thanks!
 
I have been working on a visual flow, launched from an account page to create cases. As an admin, I have no issues running it. However, some users are generating this error when the case is created at the end of the flow:

This error occurred when the flow tried to create records: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY: CaseTrigger: execution of AfterInsert caused by: System.DmlException: Update failed. First exception on row 0 with id 5000V000018MPzLQAW; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id: [] Class.CaseServices.generateUniqueBase64IDs: line 58, column 1 Trigger.CaseTrigger: line 15, column 1. For details, see API Exceptions.

Here's the method from Case Services: 
public static void generateUniqueBase64IDs(List<Case> caseList)
    {
        List<Case> casesToUpdate = new List<Case>();
        for(Case inputCase: caseList)
        {
            Case c = new Case(id = inputCase.id);
            c.Base64ID__c = EncodingUtil.base64Encode(Blob.valueOf(c.id));
            casesToUpdate.add(c);
        }
        
        update casesToUpdate;
    }
And here's the case trigger:
trigger CaseTrigger on Case (after insert, before update, after update) 
{
  System.debug('\n\nGenericServices.getGeneralSettingValueForKey(Constants.CASE_TRIGGER_KEY) = '+GenericServices.getGeneralSettingValueForKey(Constants.CASE_TRIGGER_KEY)+'\n\n');
    if(Trigger.isBefore && Trigger.isUpdate)
    {
        if(GenericServices.getGeneralSettingValueForKey(Constants.CASE_TRIGGER_KEY) == '1')
        {
          CaseServices.addCaseTrackerAndCaseHistoryEntries(Trigger.newMap, Trigger.oldMap);
        }
    }
    if(Trigger.isAfter)
    {
        if(Trigger.isInsert)
        {
            CaseServices.generateUniqueBase64IDs(Trigger.new);
        }
        else if(Trigger.isUpdate)
        {
            if(GenericServices.getGeneralSettingValueForKey(Constants.CASE_TRIGGER_KEY) == '1')
            {
                //CaseServices.deleteCasesCreatedFromEmailWithoutThreadID(Trigger.newMap);
                CaseServices.closeAndUpdateChildCases(Trigger.newMap, Trigger.oldMap);
            }
        }
    }
    //CaseServices.closeAndUpdateChildCases(Trigger.newMap, Trigger.oldMap);
}

The user is able to create an identical case outside of a flow. 

Any ideas here? 

-Michael 
 
Scenario: When contact last name does not equal to null, send an email to that contact

public class sendemail_contacts 
{
list<contact>lstcont=new list<contact>();    
for(lstcont=[select id,name from contact where firstname!=''])
{
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();  
string body = 'Hi ';
String[] toAddresses = new String[] {'example@gmail.com'}; 
mail.setToAddresses(toAddresses);
mail.setSubject('Test Subject'); 
}
}

I am new to Salesforce development. I dont know why this error has been occured.
Can you please anyone explain and suggest the answer for this below code?
 
  • December 04, 2017
  • Like
  • 0
Im currently writing a trigger handler to add a parent id to an account based on a variable called DUNS Number. When I add a new record I run into a DML Error 50001 limit reached.  

/******************************************************************************************************
 * @NAME         : OnBeforeInsert
 * @DESCRIPTION  : Catch any missing data before inserting a Account record
 * @PARAMETER    : List of Accounts to affect
 ******************************************************************************************************/
    public void BeforeInsert(Account[] newAccounts){
        Map<String, Id> dunsMap = getDUNSMap(newAccounts);
        try{
            FOR(Account acct : newAccounts){
                //acct.Sales_Region__c = region.getCorrectAccountRegionSingle(acct);
                if(acct.Parent_DUNS_Number__c != null){
                    acct.ParentId = dunsMap.get(acct.Parent_DUNS_Number__c);
                }
            }
        }catch(Exception ex){}
    }

 /******************************************************************************************************
 * @NAME         : getDUNSMap
 * @DESCRIPTION  : Gets the Id of the Parent Account based on the DUNS Number
 * @PARAMETER    : Account List to search for
 * @RETURN       : Map<String, Id> of the Queried Parent Account with their duns numbers
 ******************************************************************************************************/   
    private Map<String, Id> getDUNSMap(List<Account> accountList){
        Map<String, Id> dunsMap = new Map<String, Id>();
        
        List<String> parentDunsList = new List<String>();
        
        For(Account a : accountList){ 
            parentDunsList.add(a.Parent_DUNS_Number__c);
        }
        List<Account> parentList =[SELECT id, DUNS_Number__c FROM Account WHERE DUNS_Number__c In : parentDunsList];
        
        FOR(Account a1 : parentList){
            dunsMap.put(a1.DUNS_Number__c, a1.Id);
        }
        
        return dunsMap;
    }
Hello, I'm just starting to use Salesforce.
Let's say I've got a website with a form to insert a Contact. After the contact is inserted on my web, I want to send a JSON to Salesforce so this Contact is inserted on the Contact Object.

I don't quite understand what I need on my website to communicate with Salesforce.

Thanks!!
Hi,

  I have a helperclass code which is working perfect in salesforce issue is when data is loaded most of the records are not getting update Please let me know what might be the issue with code below Please suggest.
public class CampaignMemberTriggerUtils{

   public static void processResponseDateUpdate(List<CampaignMember> newRec){
       List<Lead> leadLst = new List<Lead>();
       List<Contact> contLst = new List<Contact>();
       Set<Id> leadIdLst = new Set<ID>();
       Set<Id> ContIdLst = new Set<ID>();
       Map<ID, datetime> lastCamResDateMap = new Map<ID, datetime>();
       for(CampaignMember cm : newRec) {
           if(cm.LeadId != null)
             leadIdLst.add(cm.LeadId);
           if(cm.ContactId != null)
             contIdLst.add(cm.ContactId);
       }
       
       List<CampaignMember> camMems = [SELECT Id, LeadId, ContactId, CampaignId, Status, FCRM__FCR_Response_Date__c FROM CampaignMember 
                   where (LeadId = :leadidLst or ContactId = :contIdLst) and FCRM__FCR_Response_Date__c <> null order by FCRM__FCR_Response_Date__c desc];
       for(CampaignMember cam : camMems) {
           if(!lastCamResDateMap.containsKey(cam.LeadId))
               lastCamResDateMap.put(cam.LeadId, cam.FCRM__FCR_Response_Date__c);
           if(!lastCamResDateMap.containsKey(cam.ContactId))
               lastCamResDateMap.put(cam.ContactId, cam.FCRM__FCR_Response_Date__c);
       }
           
       for( ID leadid : leadIdLst) {
        leadLst.add(new Lead(id = leadid, Last_Campaign_Response_Date__c = lastCamResDateMap.get(leadid)));
       }
        for( ID contactid : contIdLst) {
        contLst.add(new Contact(id = contactid,Last_Campaign_Response_Date__c =  lastCamResDateMap.get(ContactId)));
       }
       system.debug(leadLst + '_'+  contLst);
       if(!leadLst.isEmpty())
         update leadLst; 
       if(!contLst.isEmpty())
         update contLst; 
   } 
    
}

Thanks
Sudhir
Hello Group,

I'm trying to create a simple inline VF page but not able to filter just the records I need.

I'm working with 3 objects = Accounts >Customer Visit >Visit Notes.  
I just want to display the last 2 or 3 "Visit Notes" records when a new "Customer Visit" is created,  so our Reps can more easily follow up on their action items.

Customer Visit is a Lookup to Accounts, and Visit Notes is a Master-Detail to Customer Visit.
Visit Notes also has a Lookup relationship to Accounts.

I've tried several different WHERE clauses but only to produce a variety of compiler errors.
Any help would be greatly appreciated!
Hey all, 

Having some issues with writing a test class. My coverage overall is only 47% and I'm also getting some Apex Test failures I need to address. Any guidance would be greatly appreciated. 

Apex Class:
public class SessionMemberTriggerHandler implements ITrigger{
    public SessionMemberTriggerHandler(){}
    public void bulkBefore(){
        updateSessionMember();
    }
    public void bulkAfter(){    
    }
    public void beforeInsert(){}
    public void beforeUpdate(){}
    public void beforeDelete(){}
    public void afterInsert(){}
    public void afterUpdate(){}
    public void afterDelete(){}
    public void afterUnDelete(){}
    public void andFinally(){}
    
/*------------------service methods--------------------*/
    public static void updateSessionMember(){
        try{
        
        Set<id> sessionId=new Set<Id>();
        
       
        Set<id> contactIds =new Set<Id>();
        for(Session_Member__c sm:(List<Session_Member__c>)trigger.new){
            sessionId.add(sm.Session__c);
            contactIds.add(sm.Contact__c);
        }
        
        //system.assert(false, '12121221'+contactIds);
 /*-----------------------------------------Decision-----------------------------------------------------------------*/       
        Map<Id,Session__c> sessionMap=new Map<Id,Session__c>();
        Set<Id> campId=new Set<Id>();
        
        Map<Id,Integer> mapSessionMembers =new Map<Id,Integer>();
        
        for(Session__c s:[select id,Start__c,end__c,Campaign__c,Participant_Capacity__c,(select id from Session_Attendees__r) from Session__c where id in: sessionId]){
            sessionMap.put(s.id,s);
            campId.add(s.Campaign__c);
            mapSessionMembers.put(s.id,0);
            if(s.Session_Attendees__r.size()>0){
                mapSessionMembers.put(s.id,s.Session_Attendees__r.size());
            } 
        }
        Map<Id,Session__C> SessionMap2=new Map<Id,Session__c>([select id,Start__c,end__c,Campaign__c,Participant_Capacity__c from Session__c where Campaign__c in: campId]);
        
        
        Map<Id,List<Session__c>> mapContactSessions =new Map<Id,List<Session__c>>();
        
        
        
        for (Session_Member__c sm:  [select id,Session__c, contact__c from Session_Member__c where contact__c in : contactIds
         and Session__r.campaign__c in: campId ]) {
             
            if(!mapContactSessions.containsKey(sm.contact__c)){
                mapContactSessions.put(sm.contact__c,new List<Session__C>());
            }
            mapContactSessions.get(sm.contact__c).add(SessionMap2.get(sm.Session__c));
            
        }
        
        /*
        for(Session__c ses:[select id,Start__c,Campaign__c,end__c,
            (select id,contact__c from Session_Attendees__r where contact__c in : contactIds) from Session__c
             where campaign__c in:campId]){
            
            if(!sessionMap.containsKey(ses.id)){
                sessionMap.put(ses.id,ses);
            }
            for(Session_Member__c sm:ses.Session_Attendees__r){
                if(!mapContactSessions.containsKey(sm.contact__c)){
                    mapContactSessions.put(sm.contact__c,new List<Session__C>());
                }
                mapContactSessions.get(sm.contact__c).add(ses);
            }
        }*/
        
        
        Map<string,integer> sessioMCounter=new Map<String,integer>();
        
        //100
        for(Session_Member__c sm:(List<Session_Member__c>)trigger.new){
            if(!sm.triggerApply__c && sm.Status__c!='Attended'){
                if(sm.contact__c != null){
                   //  sm.status__c= getSeesionMemberStatus(sm.contact__c,sessionMap.get(sm.session__c),contSet);
                    Session__c session = sessionMap.get(sm.session__c);
                    //integer participantCapacity = session.Participant_Capacity__c;
                    //integer sessionMembersCount = session.Session_Attendees__r.size() ;
                    System.debug('============mapContactSessions.containsKey(sm.contact__c)============='+mapContactSessions.containsKey(sm.contact__c));
                    if(mapContactSessions.containsKey(sm.contact__c)){
                        // 5
                        for(Session__c existingSession: mapContactSessions.get(sm.contact__c)){
                            // existing 2 - 4 -  
                            // current session 1 - 2
                            /*
                            System.debug('===session.start__c==='+session.start__c);
                            System.debug('===existingSession.start__c==='+existingSession.start__c);
                            System.debug('===session.end__c ==='+session.end__c );
                            System.debug('===existingSession.end__c ==='+existingSession.end__c );
                            
                            System.debug('===session.start__c > existingSession.start__c==='+(session.start__c > existingSession.start__c));
                            System.debug('===session.start__c < existingSession.end__c==='+(session.start__c < existingSession.end__c));
                            System.debug('===session.end__c > existingSession.start__c==='+(session.end__c > existingSession.start__c));
                            System.debug('===session.end__c < existingSession.end__c==='+(session.end__c < existingSession.end__c));
                            */
                            
                            
                            
                            if((session.start__c > existingSession.start__c && session.start__c < existingSession.end__c)
                             ||(session.end__c > existingSession.start__c && session.end__c < existingSession.end__c)
                             || (session.start__c == existingSession.start__c)
                            ){
                                sm.Status__c ='Registered-DB';
                                break;
                            }
                            else {
                                sm.Status__c ='Registered' ;
                            }
                            
                            
                            //system.assert(false, durationInMin +'####'+ duration + '####' + sm.Status__c +'####'+(durationInMin > duration));
                        }
                    } 
                    else {
                        sm.Status__c ='Registered' ;
                    }  
                }
                
                if(!sessioMCounter.containsKey(sm.session__c)){
                    sessioMCounter.put(sm.session__c,0);
                }
                sessioMCounter.put(sm.session__c,sessioMCounter.get(sm.session__c)+1);
                /*
                System.debug('----participant capacity----'+sessionMap.get(sm.session__c).Participant_Capacity__c);
                System.debug('----Session member size----'+sessionMap.get(sm.session__c).Session_Attendees__r.size());
                System.debug('----Session m Counter ----'+sessioMCounter.get(sm.session__c));
                System.debug('----test runing----'+test.isRunningTest());
                System.debug('----sm.status__c----'+sm.status__c);
                System.debug('----condition 1----sessionMap.get(sm.session__c).Session_Attendees__r.size()+sessioMCounter.get(sm.session__c)) > sessionMap.get(sm.session__c).Participant_Capacity__c---'+((sessionMap.get(sm.session__c).Session_Attendees__r.size()+sessioMCounter.get(sm.session__c)) > (sessionMap.get(sm.session__c).Participant_Capacity__c)));
                System.debug('----condition 2----sessionMap.get(sm.session__c).Participant_Capacity__c < sessionMap.get(sm.session__c).Session_Attendees__r.size()---'+(sessionMap.get(sm.session__c).Participant_Capacity__c < sessionMap.get(sm.session__c).Session_Attendees__r.size()));
                */
                System.debug('==sessionMap.get(sm.session__c).Participant_Capacity__c==='+sessionMap.get(sm.session__c).Participant_Capacity__c);
                if(mapSessionMembers.containsKey(sm.session__c)){
                    system.debug('======mapSessionMembers.get(sm.session__c)========'+mapSessionMembers.get(sm.session__c));
                }
                system.debug('======sessioMCounter.get(sm.session__c)========'+sessioMCounter.get(sm.session__c));
                
                
                if(test.isRunningTest() || (mapSessionMembers.containsKey(sm.session__c) && sessionMap.get(sm.session__c).Participant_Capacity__c!=null && (mapSessionMembers.get(sm.session__c)+sessioMCounter.get(sm.session__c)) > sessionMap.get(sm.session__c).Participant_Capacity__c) 
                //|| 
                //(sessionMap.get(sm.session__c).Participant_Capacity__c!=null && 
                //sessionMap.get(sm.session__c).Participant_Capacity__c < sessionMap.get(sm.session__c).Session_Attendees__r.size() )
                ){
                    
                    if(sm.Status__c != 'Registered-DB')
                        sm.Status__c='Registered-WL';
                    
                }
                System.debug('---final status---'+sm.Status__c);
                /*if(sm.contact__c!=null){
                    if(!mapContactSessions.containsKey(sm.contact__c)){
                        mapContactSessions.put(sm.contact__c,new List<Session__c>());
                    }
                    mapContactSessions.get(sm.contact__c).add(sessionMap.get(sm.session__c));
                }*/
                
            }
        }

        System.debug('=====final trigger======'+(List<Session_Member__c>)trigger.new);
        }catch(Exception e){
            //System.assert(false,e.getLineNumber()+'==============='+e.getstacktraceString()+'======='+e);
        }
    }
     public static String getSeesionMemberStatus(String cid,Session__c sess,Map<Id,List<Session__c>> contSet){
        String retStr='Registered';
        /* checking about DB*/
        if(checkSessionTimeFrame(cid,sess,contSet)){
             retStr='Registered-DB'; 
        }
        return retStr;
    }
    public static boolean checkSessionTimeFrame(String cid,Session__c sess,Map<Id,List<Session__c>> mapContactSessions){
        boolean retvar=false;
        if(mapContactSessions.containsKey(cid)){
                for(Session__c existingSession: mapContactSessions.get(cid)){
                    if(sess.id!=existingSession.id && sess.Campaign__c == existingSession.Campaign__c){
                        if(inBWChecker(existingSession.start__c,existingSession.end__c,sess.start__c) || 
                        inBWChecker(existingSession.start__c,existingSession.end__c,sess.End__c) || 
                        inBWChecker(sess.start__c,sess.end__c,existingSession.start__c) || 
                        inBWChecker(sess.start__c,sess.end__c,existingSession.End__c)){
                            retvar=true;
                            break;
                        }
                    }    
                }
            
        }
        return retvar;
    }
    public static boolean inBWChecker(datetime dt1,datetime dt2,datetime check){
       if(check >= dt1 && check <= dt2){
            return true;
        }
        return false;
    }
}

And the test class:
@isTest
Public class SessionMemberTriggerHandlerTEST {
    
    static testMethod void myUnitTest() {
        //Create test Campaign
        Campaign campaign = new Campaign(Name = 'Test Campaign',Contact_Field__c = 'Palm Springs 2014');
        insert campaign;
        //Create test Contact
        Contact contact = new contact(LastName = 'Test Last',Contact_Type__c = 'Prospect');
        insert contact;
        
        Session_Track_Name__c sessionTrack = new Session_Track_Name__c(Name = 'Track', Campaign__c = campaign.Id);
        insert sessionTrack;
        
        Session__c session = new Session__c(Name = 'Current session',Start__c=date.today(),End__c=date.today()+9, Campaign__c = campaign.Id, Session_Track__c = sessionTrack.Id);
        insert session;
        Session__c session2 = new Session__c(Name = 'Current session 2',Start__c=date.today()+5,End__c=date.today()+9, Campaign__c = campaign.Id, Session_Track__c = sessionTrack.Id);
        insert session2;
       
        List<Session_Member__c> smlist =  new List<Session_Member__c>();
        smlist.add(new Session_Member__c(Contact__c = contact.Id, Session__c = session.Id,Status__c ='Registered-DB'));
        smlist.add(new Session_Member__c(Contact__c = contact.Id, Session__c = session.Id,Status__c ='Registered-DB'));
       
        list<Session__c> slist =new list<Session__c> ();
        slist.add(session2);
        map<id,list<session__c>> mapsess = new map<id,list<session__c>>();
        mapsess.put(contact.id, slist);
        
     
        SessionMemberTriggerHandler shandler = new SessionMemberTriggerHandler();
        shandler.bulkAfter();
        shandler.beforeInsert();
        shandler.beforeUpdate();
        shandler.beforeDelete();
        shandler.afterInsert();
        shandler.afterUpdate();
        shandler.afterDelete();
        shandler.afterUnDelete();
        shandler.andFinally();
        shandler.bulkbefore();
        
        SessionMemberTriggerHandler.getSeesionMemberStatus(contact.id, session, mapsess);
        SessionMemberTriggerHandler.inBWChecker(date.today(), date.today()+9,date.today()+7);
        
        test.startTest();
        insert smlist;
        list<Session_Member__c > sessionList= [select Id from Session_Member__c where Id = :smlist[0].Id];
        system.assertEquals(1,sessionList.size() );
        test.stopTest();
       
        //SessionMemberTriggerHandler.updateSessionMember();
        Delete smlist;
    }
    static testMethod void myUnitTest2() {
        //Create test Campaign
        Campaign campaign = new Campaign(Name = 'Test Campaign',Contact_Field__c = 'Palm Springs 2014');
        insert campaign;
        //Create test Contact
        Contact contact = new contact(LastName = 'Test Last',Contact_Type__c = 'Prospect');
        insert contact;
        
        Session_Track_Name__c sessionTrack = new Session_Track_Name__c(Name = 'Track', Campaign__c = campaign.Id);
        insert sessionTrack;
        
        Session__c session = new Session__c(Name = 'Current session',Start__c=date.today(),End__c=date.today()+9, Campaign__c = campaign.Id, Session_Track__c = sessionTrack.Id);
        insert session;
        Session__c session2 = new Session__c(Name = 'Current session 2',Start__c=date.today()+5,End__c=date.today()+9, Campaign__c = campaign.Id, Session_Track__c = sessionTrack.Id);
        insert session2;
       
        List<Session_Member__c> smlist =  new List<Session_Member__c>();
        smlist.add(new Session_Member__c(Contact__c = contact.Id, Session__c = session.Id,Status__c ='Registered-DB'));
        smlist.add(new Session_Member__c(Contact__c = contact.Id, Session__c = session.Id,Status__c ='Registered-DB'));
        insert smlist;
        
        list<Session__c> slist =new list<Session__c> ();
        slist.add(session2);
        map<id,list<session__c>> mapsess = new map<id,list<session__c>>();
        mapsess.put(contact.id, slist);
        
     
        SessionMemberTriggerHandler shandler = new SessionMemberTriggerHandler();
        shandler.bulkAfter();
        shandler.beforeInsert();
        shandler.beforeUpdate();
        shandler.beforeDelete();
        shandler.afterInsert();
        shandler.afterUpdate();
        shandler.afterDelete();
        shandler.afterUnDelete();
        shandler.andFinally();
        shandler.bulkbefore();
        
        SessionMemberTriggerHandler.getSeesionMemberStatus(contact.id, session, mapsess);
        SessionMemberTriggerHandler.inBWChecker(date.today(), date.today()+9,date.today()+7);
        test.startTest();
        update smlist;
        list<Session_Member__c > sessionList= [select Id from Session_Member__c where Id = :smlist[0].Id];
        system.assertEquals(1,sessionList.size() );
        test.stopTest();
       
        //SessionMemberTriggerHandler.updateSessionMember();
        Delete smlist;
    }
}

​The apex test errors i'm getting are: 

System.AssertException: Assertion Failed: 25===============Class.SessionMemberTriggerHandler.updateSessionMember: line 25, column 1 Class.SessionMemberTriggerHandler.bulkBefore: line 4, column 1 Class.SessionMemberTriggerHandlerTEST.myUnitTest: line 40, column 1=======System.NullPointerException: Attempt to de-reference a null object 
Stack Trace: Class.SessionMemberTriggerHandler.updateSessionMember: line 172, column 1 Class.SessionMemberTriggerHandler.bulkBefore: line 4, column 1 Class.SessionMemberTriggerHandlerTEST.myUnitTest: line 40, column 1

System.AssertException: Assertion Failed: 25===============Class.SessionMemberTriggerHandler.updateSessionMember: line 25, column 1 Class.SessionMemberTriggerHandler.bulkBefore: line 4, column 1 Class.SessionMemberTriggerHandlerTEST.myUnitTest2: line 91, column 1=======System.NullPointerException: Attempt to de-reference a null object 
Stack Trace: Class.SessionMemberTriggerHandler.updateSessionMember: line 172, column 1 Class.SessionMemberTriggerHandler.bulkBefore: line 4, column 1 Class.SessionMemberTriggerHandlerTEST.myUnitTest2: line 91, column 1

Does anyone have any ideas? Thanks!
 
I have been working on a visual flow, launched from an account page to create cases. As an admin, I have no issues running it. However, some users are generating this error when the case is created at the end of the flow:

This error occurred when the flow tried to create records: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY: CaseTrigger: execution of AfterInsert caused by: System.DmlException: Update failed. First exception on row 0 with id 5000V000018MPzLQAW; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id: [] Class.CaseServices.generateUniqueBase64IDs: line 58, column 1 Trigger.CaseTrigger: line 15, column 1. For details, see API Exceptions.

Here's the method from Case Services: 
public static void generateUniqueBase64IDs(List<Case> caseList)
    {
        List<Case> casesToUpdate = new List<Case>();
        for(Case inputCase: caseList)
        {
            Case c = new Case(id = inputCase.id);
            c.Base64ID__c = EncodingUtil.base64Encode(Blob.valueOf(c.id));
            casesToUpdate.add(c);
        }
        
        update casesToUpdate;
    }
And here's the case trigger:
trigger CaseTrigger on Case (after insert, before update, after update) 
{
  System.debug('\n\nGenericServices.getGeneralSettingValueForKey(Constants.CASE_TRIGGER_KEY) = '+GenericServices.getGeneralSettingValueForKey(Constants.CASE_TRIGGER_KEY)+'\n\n');
    if(Trigger.isBefore && Trigger.isUpdate)
    {
        if(GenericServices.getGeneralSettingValueForKey(Constants.CASE_TRIGGER_KEY) == '1')
        {
          CaseServices.addCaseTrackerAndCaseHistoryEntries(Trigger.newMap, Trigger.oldMap);
        }
    }
    if(Trigger.isAfter)
    {
        if(Trigger.isInsert)
        {
            CaseServices.generateUniqueBase64IDs(Trigger.new);
        }
        else if(Trigger.isUpdate)
        {
            if(GenericServices.getGeneralSettingValueForKey(Constants.CASE_TRIGGER_KEY) == '1')
            {
                //CaseServices.deleteCasesCreatedFromEmailWithoutThreadID(Trigger.newMap);
                CaseServices.closeAndUpdateChildCases(Trigger.newMap, Trigger.oldMap);
            }
        }
    }
    //CaseServices.closeAndUpdateChildCases(Trigger.newMap, Trigger.oldMap);
}

The user is able to create an identical case outside of a flow. 

Any ideas here? 

-Michael 
 
Hi Guys,
i am getting this error when i call the class to generate invoices. the piece of code was working fine but due to over 10,000 records i have to put records in array and since then i am getting the above insert_update error.  

qryGift[i].Item__c = itemDTL1.Id; 
above code through error when insert L; gets executed.

thanks in advance.
 
failedUpdates = 0;
         // Billing Cycle variables
        String CycleType = '';
       Integer CycleMonths = 3; 
       //Integer CycleMonths = 0;
            
        // Set start and end dates. Assumes run at start of new month for preceding quarter        
       Date t =   Date.valueOf('2017-10-03'); 
      // Date t = Date.today();
        Integer m = t.Month();
        dateEnd = t.toStartOfMonth().addDays(-1);
            
        // Determine what the billing cycle is
        List<System_Settings__c> qrySettings = new List<System_Settings__c>();
        qrySettings = Database.query('SELECT Name, Value__c FROM System_Settings__c WHERE Name LIKE \'Billing Cycle%\' ORDER BY NAME');
        for (Integer i = 0; i < qrySettings.size(); i++) 
        {
            // Set the cycle type
            if (qrySettings[i].Name == 'Billing Cycle')
            {
                CycleType = qrySettings[i].Value__c;

                // TempC Print CycleType
                System.debug('Info-01: ' + CycleType);
                
                // If monthly just set and quit
                if (CycleType == 'Monthly')
                {
                    CycleMonths = 1;
                    break; 
                }                
            }
    
            // If quarterly see if this month is a billing month
            if (CycleType == 'Quarterly')
            {
                String RunMonth = String.ValueOf(m);
                if (qrySettings[i].Value__c == RunMonth)
                {
                    CycleMonths = 3;
                    break; 
                }
            }
        }
            
		// Step 3 **** custom duration invoice generation		
    			// CycleMonths = 3;
				// CycleType = 'Quarterly';

       	// TempC Print CycleType
                System.debug('Info-02 ' + CycleType);
        // Check all okay
        if (CycleType == '')
        {
            runok = 'NO BILLING CYCLE';
            System.debug('ERROR: No Billing Cycle type found. Invoice run aborted.');
            return;
        }
        if (CycleType != 'Monthly' && CycleType != 'Quarterly')
        {
            runok = 'INVALID BILLING CYCLE';
            System.debug('ERROR: Invalid Billing Cycle type found. Invoice run aborted.');
            return;
        }
        if (CycleMonths == 0)
        {
            runok = 'QUARTERLY - NOT A RUN MONTH';
            System.debug('ERROR: Quarterly Billing Cycle but not a run month. Invoice run aborted.');
            return;
        }
            
        Date s = t.toStartOfMonth();
        dateStart = s.addMonths(-CycleMonths);
        
    }
    
    global Database.queryLocator 
                    start(Database.BatchableContext ctx){
        return Database.getQueryLocator([SELECT Id, Country__c, End_Date__c, Invoiced_Up_To__c, Orphan__c, Start_Date__c, Orphan__r.Country__r.Orphan_Invoice_Amount__c,
                                                       Orphan__r.IRP_Sponsorship_Start__c, Orphan__r.Donor__c, Orphan__r.Donor_Start_Date__c, Orphan__r.Country__r.Orphan_Transfer_Amount__c,
                                                       Country__r.Primary_PO_User__c, Orphan__r.OwnerId
                                                  FROM IRP_Sponsorship__c 
                                                 WHERE Start_Date__c < :dateEnd 
                                                 AND ((End_Date__c = NULL
                                                 AND (Invoiced_Up_To__c = NULL
                                                  OR Invoiced_Up_To__c < :dateEnd)) 
                                                  OR (End_Date__c >= :dateStart
                                                 AND (Invoiced_Up_To__c = NULL
                                                  OR Invoiced_Up_To__c < :dateEnd)) 
                                                  OR (End_Date__c < :dateStart
                                                 AND  Billable__c = 0
                                                 AND (Invoiced_Up_To__c = NULL
                                                  OR (Invoiced_Up_To__c < :dateEnd))))
                                                 AND Orphan__r.Sponsored_Directly__c = FALSE Limit 200]);
    }
    
    global void execute(Database.BatchableContext ctx, List<Sobject>
                        scope){

        List<IRP_Sponsorship__c> qrySponsors = (List<IRP_Sponsorship__c>)scope;

        // Check a run month
        if(runok != 'TRUE'){
            return;
        }
                        
        // Cycle through list and get a unique list of Partner Offices
        Map<Id,String> setPtnr = new Map<Id,String>();
        // Add the invoice headers
        List<Invoice__c> newHdr = new List<Invoice__c>();

        // Get any generated open invoice headers
        List<Invoice__c> qryInv = [SELECT Id, IRP_Country__c
                                     FROM Invoice__c 
                                    WHERE Invoice_Status__c = 'Generated'
                                      AND Invoice_Date__c >= YESTERDAY];

                            // Make sure a header appears for this country                        
        for (Integer i = 0; i < qryInv.size(); i++) {
            if(!setPtnr.containsKey(qryInv[i].IRP_Country__c)){
                setPtnr.put(qryInv[i].IRP_Country__c,'Inv Hdr');
            }
        }    
            
        //Get initial record type id for invoice
        RecordType invrt = [SELECT Id FROM RecordType WHERE Name = 'Invoice Stage 1' AND sObjectType = 'Invoice__c' LIMIT 1];
        Id hdrRT = invrt.Id;
    
        // Invoice header
        Date invDate = Date.today();
        // Get number of rows
        //recs = qrySponsors.size();
        for (Integer i = 0; i < qrySponsors.size(); i++) {

            if(!setPtnr.containsKey(qrySponsors[i].Country__c)){
                setPtnr.put(qrySponsors[i].Country__c,'Inv Hdr');
                Invoice__c itmHdr = new Invoice__c (                    
                    IRP_Country__c = qrySponsors[i].Country__c,
                    Invoice_Date__c = invDate,
                    Invoice_Status__c = 'Generated',
                    RecordTypeId = hdrRT,
                    OwnerId = qrySponsors[i].Country__r.Primary_PO_User__c
                );
                newhdr.add(itmHdr);
            }
        }

        // Get any unbilled gifts
        List<Gift__c> qryGift = [SELECT Id, Donor__c, Donor__r.IRP_Country__c, Item__c, Orphan_Id__c, Gift_Amount__c, Gift_Date__c, Invoiced_On__c,
                                        Donor__r.IRP_Country__r.Primary_PO_User__c, Orphan_Id__r.OwnerId
                                   FROM Gift__c 
                                  WHERE Gift_Date__c <= :dateEnd
                                    AND Invoiced_On__c = NULL FOR UPDATE];
                            
        // Make sure a header appears for this country                        
        for (Integer i = 0; i < qryGift.size(); i++) {

            if(!setPtnr.containsKey(qryGift[i].Donor__r.IRP_Country__c)){
                setPtnr.put(qryGift[i].Donor__r.IRP_Country__c,'Inv Hdr');
     
                    Invoice__c itmHdr1 = new Invoice__c (                    
                    IRP_Country__c = qryGift[i].Donor__r.IRP_Country__c,
                    Invoice_Date__c = invDate,
                    Invoice_Status__c = 'Generated',
                    RecordTypeId = hdrRT,
                    OwnerId = qryGift[i].Donor__r.IRP_Country__r.Primary_PO_User__c
                );
                newhdr.add(itmHdr1);
            }
        }
                 // Debug
                 for (Integer i = 0; i < newHdr.size(); i++) {
                 system.debug('New Header ' +i+ newHdr[i]);
                 }
                            insert newHdr;

        // Create a map of country and invoice id
        Map<String,Id> newHdr1 = new Map<String, Id>();
        // Get new list of generated invoices
        List<Invoice__c> qryInv1 = [SELECT Id, IRP_Country__c
                                      FROM Invoice__c 
                                     WHERE Invoice_Status__c = 'Generated'
                                       AND Invoice_Date__c >= YESTERDAY];
                
        for (Integer i = 0; i < qryInv1.size(); i++) {
            newHdr1.put(qryInv1[i].IRP_Country__c, qryInv1[i].Id);
        }        

         // Map for keeping invoice items
          //Map<integer, list<Item__c>> finalinsertlist = new Map<integer, list<Item__c>>(); 
          list<list<Item__c>> finalinsertlist = new list<list<Item__c>>();                      

        // Add the item details
        List<Item__c> newITM = new List<Item__c>();
        // Get a list of the affected orphans
        Map<Id,Date> updOrp = new Map<Id,Date>();
                
        // Now go back through the sponsorship records and add the item records
        for (Integer i = 0; i < qrySponsors.size(); i++) {
            if(newHdr1.containsKey(qrySponsors[i].Country__c)){
            
                String itmHDR1 = newHdr1.get(qrySponsors[i].Country__c);
                
                // Use donor start date if present, otherwise use IRP start date
                Date dateSpons = qrySponsors[i].Orphan__r.Donor_Start_Date__c;
                if (dateSpons == NULL){ dateSpons = qrySponsors[i].Start_Date__c; }
                
                // Work out the number of months involved
                Date billfrom = qrySponsors[i].Invoiced_Up_To__c;
                if (billfrom == NULL){ billfrom = qrySponsors[i].Start_Date__c; }
                // Adjust bill from based on 15th of month
                if (billfrom.day() >= 15){
                    Date bf = billfrom;
                    Date bf1 = bf.toStartOfMonth();
                    Date bf2 = bf1.addMonths(1);
                    billfrom = bf2;
                } 
                Integer billqty = 1;
                Date billto = dateEnd;
                if (qrySponsors[i].End_Date__c < dateEnd){billto = qrySponsors[i].End_Date__c;}
                
                if (billfrom.year() == billto.year()){
                    billqty = billto.month() - billfrom.month() + 1;
                }
                else
                {
                    billqty = billto.month() + ((billto.year() - billfrom.year()) * 12) - billfrom.month() + 1;                    
                }
                
                // Add new item record
                Item__c itemDTL = new Item__c (
                    Date_Sponsored__c = dateSpons,
                    Donor__c = qrySponsors[i].Orphan__r.Donor__c,
                    Invoice_Price__c = qrySponsors[i].Orphan__r.Country__r.Orphan_Invoice_Amount__c,
//                    Item_Status__c = 'Generated',
                    Orphan__c = qrySponsors[i].Orphan__c,
                    Item_Type__c = 'Sponsorship',
                    Payment_Cost__c = qrySponsors[i].Orphan__r.Country__r.Orphan_Transfer_Amount__c,
                    Qty__c = billqty,
                    IRP_Sponsorship_Ref__c = qrySponsors[i].Id,
                    Quarterly_Billing_Number__c = itmHDR1,
                    OwnerId = qrySponsors[i].Orphan__r.OwnerId
                );
                     if (math.mod(i, 9999)==0 && !newITM.isempty()){
                           finalinsertlist.add(newITM);   
                           newITM.clear() ; //= new list<item__c>();  
                     }

                newITM.add(itemDTL);
                
                // Make a note of the latest bill to for an orphan
                if (updOrp.containsKey(qrySponsors[i].Orphan__c)){
                    Date orpCheck = updOrp.get(qrySponsors[i].Orphan__c); 
                    if (billto > orpCheck) {
                        updOrp.put(qrySponsors[i].Orphan__c, billto);
                    }
                }
                else
                {
                    updOrp.put(qrySponsors[i].Orphan__c, billto);
                }   
                // Update IRP sponsorship record
                qrySponsors[i].Invoiced_Up_To__c = billto;
            }
        }                 

        // Now go back through the gift records and add the item records
        for (Integer i = 0; i < qryGift.size(); i++) {
            if(newHdr1.containsKey(qryGift[i].Donor__r.IRP_Country__c)){
            
                String itmHDR2 = newHdr1.get(qryGift[i].Donor__r.IRP_Country__c);

                // Add new item record
                Item__c itemDTL1 = new Item__c (
                    Donor__c = qryGift[i].Donor__c,
                    Invoice_Price__c = qryGift[i].Gift_Amount__c,
//                    Item_Status__c = 'Generated',
                    Orphan__c = qryGift[i].Orphan_Id__c,
                    Item_Type__c = 'Gift',
                    Payment_Cost__c = qryGift[i].Gift_Amount__c,
                    Qty__c = 1,
                    Quarterly_Billing_Number__c = itmHDR2,
                    OwnerId = qryGift[i].Orphan_Id__r.OwnerId                    
                );
                  if (math.mod(i, 9999)==0 && !newITM.isempty()){
                      finalinsertlist.add(newITM);   
                      newITM.clear(); // = new list<item__c>();  
                  }
              newITM.add(itemDTL1);
                // Update Gift record
                qryGift[i].Invoiced_On__c = dateEnd;
                qryGift[i].Item__c = itemDTL1.Id;
            }
        }
                
                for(list<Item__c> L:finalinsertlist){
                system.debug('Array size:' + L.size());   
                    insert L ;                 
                 }

 
Hi,
Please Help to resolve this issue. Error: System.LimitException: Too many SOQL queries: 101 Trigger  line 28, column 1


Trigger RollupCountOnLoans on Loan__c(after insert, after update) {
    List <Id> Ids = new List<Id> ();
   List <Customer__c> Cust1 = new List<Customer__c>();
    List <AggregateResult> Agr = new List<AggregateResult>();
    
    for(Loan__c req:trigger.new){
        Ids.add(req.Customer_ID__c);
    }
    
    List<Customer__c> Cust = [Select Id, Number_of_Approved_Loans__c From Customer__c Where Id In :Ids];
    Agr = [Select Customer_ID__c, Count(Id) From Loan__c Where Customer_ID__c IN: Ids
            AND Customer_Journey_Status__c IN ('Approved','Active', 'PaidOff')
            Group By Customer_ID__c];
            
            for(AggregateResult ar: Agr){
        for(Customer__c p:Cust){
            if(ar.get('Customer_ID__c') == p.Id)
            {
               p.Number_of_Approved_Loans__c = Decimal.ValueOf(String.ValueOf(ar.get('expr0')));
            }
        }
    }
    update(Cust);
}
  • December 05, 2017
  • Like
  • 0
Scenario: When contact last name does not equal to null, send an email to that contact

public class sendemail_contacts 
{
list<contact>lstcont=new list<contact>();    
for(lstcont=[select id,name from contact where firstname!=''])
{
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();  
string body = 'Hi ';
String[] toAddresses = new String[] {'example@gmail.com'}; 
mail.setToAddresses(toAddresses);
mail.setSubject('Test Subject'); 
}
}

I am new to Salesforce development. I dont know why this error has been occured.
Can you please anyone explain and suggest the answer for this below code?
 
  • December 04, 2017
  • Like
  • 0
Hi guys,

I don't understand why I get "System.LimitException: Apex CPU time limit exceeded" on mass update.

Basically I want to count opportunity team members with specific role and store the counter in a custom field on opportunity level.
 
Trigger roleUpdateOnly on OpportunityTeamMember (after update) {
  
  
  Set<Id> setOpptyIdsUpdateOnly = new Set<Id>();
  
    
    for(OpportunityTeamMember optm: Trigger.new) {
        if(trigger.isUpdate){
        
         String oldRole = trigger.OldMap.get(optm.Id).TeamMemberRole;
             if(oldRole == 'specific role' || optm.TeamMemberRole == 'specific role') {
                setOpptyIdsUpdateOnly.add(optm.OpportunityId);
             }
           }
        }  
  
  List<Opportunity> listOpps= [Select id,Counter_specific_role__c ,
 (Select id from OpportunityTeamMembers WHERE TeamMemberRole = 'specific role')
 from Opportunity where Id in : setOpptyIdsUpdateOnly];

  for(Opportunity opp :listOpps) {
   
   opp.Counter_specific_role__c = opp.opportunityTeamMembers.size();
  }
  update listOpps; 
   
}


Thanks in advance.
 
Please help me how to fix it?
hi can anyone help me with my requirement i.e,
how to send an email with the count of number of records in a Standard Object
Hi,
This code has been written by previous developer. I would really appreicate if someone helps me with this error. Thank you.
  : execution of AfterInsert
 
caused by: System.QueryException: Non-selective query against large object type (more than 200000 rows). Consider an indexed filter or contact salesforce.com about custom indexing.
Even if a field is indexed a filter might still not be selective when:
1. The filter value includes null (for instance binding with a list that contains null) 2. Data skew exists whereby the number of matching rows is very large (for instance, filtering for a particular foreign key value that occurs many times)

trigger AssessmentAnswers on Assessment__c (before insert,before update,after insert) {
    Map<String,List<List<List<String>>>> questionsMap=AssessmentTemplate.getQuestionMap();
    if(Trigger.isInsert && Trigger.isBefore){
        Map<String,Id> rtMap=new Map<String, Id>();
        List<RecordType> rtList=[select id,name from recordtype where name in ('Postsession','Presession','Dass','HolmesRahe')];
        For(RecordType rt:rtList){
            rtMap.put(rt.name,rt.id);
        }
        List<Assessment__c> assList=trigger.new;
        For(Assessment__c ass : assList){
            if(ass.Type__c!=null  && rtMap.containsKey(ass.Type__c.split('::')[1])){
                ass.RecordTypeId=rtMap.get(ass.Type__c.split('::')[1]);
            }
            Integer i=1;
            List<List<List<String>>> assTemplate=questionsMap.get(ass.Type__c);
            if(assTemplate!=null && ass.Answers__c!=null){
                For(String answer : ass.Answers__c.split(',')){
                    if(answer.isNumeric() && i<=assTemplate.size() && Integer.valueof(answer)<assTemplate[i-1][1].size()) { 
                        ass.put('Answer_'+i+'__c',assTemplate[i-1][1][Integer.valueof(answer)]);
                        ass.put('Answer_Value_'+i+'__c',Integer.valueof(answer));
                        ass.put('Question_'+i+'__c',assTemplate[i-1][0][0]);
                    }
                    i++;
                }
            }
        }
    }else if(Trigger.isInsert && Trigger.isAfter){
        AssessmentTemplate.cleanupAssessments();
    }else if(Trigger.isUpdate && Trigger.isBefore){
        List<Assessment__c> assList=trigger.new;
        For(Assessment__c ass : assList){
            Integer i=1;
            List<List<List<String>>> assTemplate=questionsMap.get(ass.Type__c);
            if(assTemplate!=null && ass.Answers__c!=null){
                For(String answer : ass.Answers__c.split(',')){
                    if(answer.isNumeric() && i<=assTemplate.size() && Integer.valueof(answer)<assTemplate[i-1][1].size()) { 
                        ass.put('Answer_'+i+'__c',assTemplate[i-1][1][Integer.valueof(answer)]);
                        ass.put('Answer_Value_'+i+'__c',Integer.valueof(answer));
                        ass.put('Question_'+i+'__c',assTemplate[i-1][0][0]);
                    }
                    i++;
                }
            }
        }
    }
}
I have a trigger that queries the Period object for the FiscalYearSettings to use. This is to allow my trigger to automatically update is the Fiscal Year was ever changed in the Company Profile. The issue I have is that it seems to run an SOQL query for every run of the trigger meaning I exceed the SOQL limit. I've looked at bulkifying it but non of the guides I've read help as I only use the SOQL to get a date. My code is as below;
 
trigger SetProductQuarter on OpportunityLineItem (before insert, before update) 
{
    Date FYStartDate = [SELECT FiscalYearSettings.StartDate FROM Period WHERE Type = 'Year' AND StartDate <= TODAY AND EndDate >= TODAY].FiscalYearSettings.StartDate;
     
    for(OpportunityLineItem opitem : Trigger.new){
    	//Current Date Q1
    	if(opitem.Date_Today__c < FYStartDate.addMonths(3) && opitem.Date_Today__c > FYStartDate){
	    	if(opitem.ServiceDate < FYStartDate.addMonths(3) && opitem.ServiceDate > FYStartDate)
	    	{
	    		opitem.Product_Quarter__c = 'Q1';
	    	}
	    	else if(opitem.ServiceDate < FYStartDate.addMonths(6) && opitem.ServiceDate > FYStartDate.addMonths(3))
	    	{
	    		opitem.Product_Quarter__c = 'Q2';
	    	}
	    	else if(opitem.ServiceDate < FYStartDate.addMonths(9) && opitem.ServiceDate > FYStartDate.addMonths(6))
	    	{
	    		opitem.Product_Quarter__c = 'Q3';
	    	}      
	    	else if(opitem.ServiceDate < FYStartDate.addMonths(12) && opitem.ServiceDate > FYStartDate.addMonths(9))
	    	{
	    		opitem.Product_Quarter__c = 'Q4';
	    	}      
	    	else
	    	{
	    		opitem.Product_Quarter__c = '=';
	    	}
    	}
    	//Current Date Q2
    	else if(opitem.Date_Today__c < FYStartDate.addMonths(6) && opitem.Date_Today__c > FYStartDate.addMonths(3)){
	    	if(opitem.ServiceDate < FYStartDate.addMonths(15) && opitem.ServiceDate > FYStartDate.addMonths(12))
	    	{
	    		opitem.Product_Quarter__c = 'Q1';
	    	}
	    	else if(opitem.ServiceDate < FYStartDate.addMonths(6) && opitem.ServiceDate > FYStartDate.addMonths(3))
	    	{
	    		opitem.Product_Quarter__c = 'Q2';
	    	}
	    	else if(opitem.ServiceDate < FYStartDate.addMonths(9) && opitem.ServiceDate > FYStartDate.addMonths(6))
	    	{
	    		opitem.Product_Quarter__c = 'Q3';
	    	}      
	    	else if(opitem.ServiceDate < FYStartDate.addMonths(12) && opitem.ServiceDate > FYStartDate.addMonths(9))
	    	{
	    		opitem.Product_Quarter__c = 'Q4';
	    	} 
	    	else if(opitem.ServiceDate < FYStartDate.addMonths(3) && opitem.ServiceDate > FYStartDate)
	    	{
	    		opitem.Product_Quarter__c = 'PQ1';
	    	}     
	    	else
	    	{
	    		opitem.Product_Quarter__c = '=';
	    	}
    	}
    	//Current Date Q3
    	else if(opitem.Date_Today__c < FYStartDate.addMonths(9) && opitem.Date_Today__c > FYStartDate.addMonths(6)){
	    	if(opitem.ServiceDate < FYStartDate.addMonths(15) && opitem.ServiceDate > FYStartDate.addMonths(12))
	    	{
	    		opitem.Product_Quarter__c = 'Q1';
	    	}
	    	else if(opitem.ServiceDate < FYStartDate.addMonths(18) && opitem.ServiceDate > FYStartDate.addMonths(15))
	    	{
	    		opitem.Product_Quarter__c = 'Q2';
	    	}
	    	else if(opitem.ServiceDate < FYStartDate.addMonths(9) && opitem.ServiceDate > FYStartDate.addMonths(6))
	    	{
	    		opitem.Product_Quarter__c = 'Q3';
	    	}      
	    	else if(opitem.ServiceDate < FYStartDate.addMonths(12) && opitem.ServiceDate > FYStartDate.addMonths(9))
	    	{
	    		opitem.Product_Quarter__c = 'Q4';
	    	}
	    	else if(opitem.ServiceDate < FYStartDate.addMonths(3) && opitem.ServiceDate > FYStartDate)
	    	{
	    		opitem.Product_Quarter__c = 'PQ1';
	    	}
	    	else if(opitem.ServiceDate < FYStartDate.addMonths(6) && opitem.ServiceDate > FYStartDate.addMonths(3))
	    	{
	    		opitem.Product_Quarter__c = 'PQ2';
	    	}      
	    	else
	    	{
	    		opitem.Product_Quarter__c = '=';
	    	}
    	}
    	//Current Date Q4
    	else if(opitem.Date_Today__c < FYStartDate.addMonths(12) && opitem.Date_Today__c > FYStartDate.addMonths(9)){
	    	if(opitem.ServiceDate < FYStartDate.addMonths(15) && opitem.ServiceDate > FYStartDate.addMonths(12))
	    	{
	    		opitem.Product_Quarter__c = 'Q1';
	    	}
	    	else if(opitem.ServiceDate < FYStartDate.addMonths(18) && opitem.ServiceDate > FYStartDate.addMonths(15))
	    	{
	    		opitem.Product_Quarter__c = 'Q2';
	    	}
	    	else if(opitem.ServiceDate < FYStartDate.addMonths(21) && opitem.ServiceDate > FYStartDate.addMonths(18))
	    	{
	    		opitem.Product_Quarter__c = 'Q3';
	    	}      
	    	else if(opitem.ServiceDate < FYStartDate.addMonths(12) && opitem.ServiceDate > FYStartDate.addMonths(9))
	    	{
	    		opitem.Product_Quarter__c = 'Q4';
	    	}
	    	else if(opitem.ServiceDate < FYStartDate.addMonths(3) && opitem.ServiceDate > FYStartDate)
	    	{
	    		opitem.Product_Quarter__c = 'PQ1';
	    	}
	    	else if(opitem.ServiceDate < FYStartDate.addMonths(6) && opitem.ServiceDate > FYStartDate.addMonths(3))
	    	{
	    		opitem.Product_Quarter__c = 'PQ2';
	    	}
	    	else if(opitem.ServiceDate < FYStartDate.addMonths(9) && opitem.ServiceDate > FYStartDate.addMonths(6))
	    	{
	    		opitem.Product_Quarter__c = 'PQ3';
	    	}      
	    	else
	    	{
	    		opitem.Product_Quarter__c = '=';
	    	}
    	}                        
    }  
}

 
While changing account owner encountering Error :: Too many query rows: 50001

I have gone through many post they are suggesting to change script means adding limit to the query.

Here in my class there is no chance to change the query and query not inside the for loop. 

for suppose if i Put Limit clause what about records which count more than 50000.  

For example i have 60000 records to change then what is the result. 
Best Practice : When someone takes the time/effort to repspond to your question, you should take the time/effort to either mark the question as "Solved", or post a Follow-Up with addtional information.

User-added image


      That way people with a similar question can find the Solution without having to re-post the same question again and again. And the people who reply to your post know that the issue has been resolved and they can stop working on it. 

Thanks #Copy_Steve Molis