Wednesday 31 May 2017

Delete Code In Developer console


List <Entitlement> defEntitlement = [SELECT Id, Default_Entitlement__C FROM Entitlement WHERE Default_Entitlement__C = TRUE];
dsr=database.delete(defEntitlement,true);
                for (Database.SaveResult sr : dsr) {
                    if (sr.isSuccess()) {
                        // Operation was successful, so get the ID of the record that was processed
                        System.debug('Successfully deleted entitlement. Entitlement ID: ' + sr.getId());
                        insertedEntIds.add(sr.getId());
                    }
                    else {
                        for(Database.Error err : sr.getErrors()) {
                            System.debug('The following error has occurred.');                   
                            System.debug(err.getStatusCode() + ': ' + err.getMessage());
                            System.debug('Fields that affected this error: ' + err.getFields());
                        }
                    }
                }

Monday 15 May 2017

Post Chatter with multipe User names to address

Trigger Handler Class & Trigger on After Update:

 private void postChatterupdatecase(ClsWrappers.TriggerContext trgCtx) {
        if (trgCtx.isAfter && trgCtx.isUpdate){
            Set<Id> ownerManagerIdSet = new Set<Id>();
            Map<Id,Case> oldCaseMap = new Map<Id,Case>();
            for(sobject so : trgCtx.oldList){
                Case csOld = (Case)so;
                oldCaseMap.put(csOld.Id,csOld);
            }
            for(sobject so : trgCtx.newList){
                Case cs = (Case)so;
                ownerManagerIdSet.add(cs.OwnerId);
            }
           
            Map<id,User> user_map = new Map<id, User>(
                [select Id,isActive,manager.Id from User where isActive = true AND Id IN: ownerManagerIdSet LIMIT 5000]);
            System.debug('*********** user_map *' + user_map);
            for(sobject so : trgCtx.newList){
                Case cs = (Case)so;
                if (cs.Milestone_message__c != oldCaseMap.get(cs.Id).Milestone_message__c && user_map.containsKey(cs.Ownerid)){
                    if(cs.Is_Violation_Action__c == true && cs.Milestone_message__c != null){
                        if(user_map.get(cs.OwnerId).manager.Id != null){
                            CreateChatterFeed.ChatterAPI(cs.Milestone_message__c,  new List<Id> {user_map.get(cs.OwnerId).manager.Id, cs.OwnerId}, cs.Id);
                          // cs.Milestone_message__c = null;
                        }
                        else{
                            CreateChatterFeed.ChatterAPI(cs.Milestone_message__c, new List<Id> {cs.OwnerId}, cs.Id);  
                        }
                    }
                    if(cs.Is_Violation_Action__c == false && cs.Milestone_message__c != null){
                        CreateChatterFeed.ChatterAPI(cs.Milestone_message__c, new List<Id> {cs.OwnerId}, cs.Id);    
                    }
                }
            }
        }
    }

// Chatter posting API

public without sharing class CreateChatterFeed {
    public static void ChatterAPI(String messageToPost, List<id> usersToPost, id objectToPost){
        ConnectApi.FeedItemInput feedItemInput_1 = new ConnectApi.FeedItemInput();
    String delimitor = ', ';
        ConnectApi.MessageBodyInput messageBodyInput_1 = new ConnectApi.MessageBodyInput();
        ConnectApi.TextSegmentInput textSegmentInput_1 = new ConnectApi.TextSegmentInput();
    ConnectApi.TextSegmentInput delimitorInput = new ConnectApi.TextSegmentInput();
    delimitorInput.text = delimitor;
        messageBodyInput_1.messageSegments = new List<ConnectApi.MessageSegmentInput>();
       
        for (id userToMention : usersToPost){
      ConnectApi.MentionSegmentInput mentionSegmentInput = new ConnectApi.MentionSegmentInput();
            mentionSegmentInput.id = userToMention;
            messageBodyInput_1.messageSegments.add(mentionSegmentInput);
            messageBodyInput_1.messageSegments.add(delimitorInput);
        }

           
        textSegmentInput_1.text = messageToPost;
        messageBodyInput_1.messageSegments.add(textSegmentInput_1);
        feedItemInput_1.body = messageBodyInput_1;
        feedItemInput_1.feedElementType = ConnectApi.FeedElementType.FeedItem;
        feedItemInput_1.subjectId = objectToPost;
        if(!Test.isRunningTest()){
            ConnectApi.FeedElement feedElement = ConnectApi.ChatterFeeds.postFeedElement(Network.getNetworkId(), feedItemInput_1);
        }
    }
}

Output:


Trigger Order of Execution

  1. System Validation rule (required field, field format) (SV)
  2. Before Triggers are executed (BT)
  3. Custom Validation rules are checked (CV)
  4. After Triggers are executed (AT)
  5. Assignment Rules are executed (AR)
  6. Auto-Response Rules are executed (ARR)
  7. Workflow Rules are executed (WR)
    1. Before and after triggers are executed one more time if the workflow rule updates a field (BT & AT)
  8. Escalation Rules are executed (ER)
  9. Parent Rollup Summary Formula or Cross Object Formula fields are updated in the respective objects. (RSF, COF) (These parent records also goes through the entire execution order)
  10. Criteria Based Sharing rules are evaluated (CBS)
  11. Any Post-Commit Logic is executed (PCL)  (like sending an email)
To remember this sequence you can memorise the following.
SV -> BT -> CV -> AT -> AR -> ARR -> WR (BT, AT) -> ER -> RSFCOF -> CBS -> PCL

Thursday 11 May 2017

Query Case related Chatter Feed & Post Chatter Related Record

Query

SELECT Id, Type, Body FROM caseFeed WHERE ParentId = '5004E0000035Ggw'

Code to post Chatter Feed

if (trgCtx.isAfter && trgCtx.isUpdate){
            for(sobject so : trgCtx.oldList){
            Case csOld = (Case)so;
                if(csOld.Is_Violation_Action__c == true && csOld.Milestone_message__c != null){
                    ConnectApi.FeedItemInput feedItemInput_1 = new ConnectApi.FeedItemInput();
                    ConnectApi.MentionSegmentInput mentionSegmentInput_1 = new ConnectApi.MentionSegmentInput();
                    ConnectApi.MessageBodyInput messageBodyInput_1 = new ConnectApi.MessageBodyInput();
                    ConnectApi.TextSegmentInput textSegmentInput_1 = new ConnectApi.TextSegmentInput();
                    messageBodyInput_1.messageSegments = new List<ConnectApi.MessageSegmentInput>();
                   
                    textSegmentInput_1.text = csOld.Milestone_message__c;
                    System.debug('****textSegmentInput_1.text******* ' + textSegmentInput_1.text);
                    System.debug('****csOld.Milestone_message__c******* ' + csOld.Milestone_message__c);
                    mentionSegmentInput_1.id = csOld.Ownerid;
                    System.debug('****mentionSegmentInput_1.id******* ' + mentionSegmentInput_1.id);
                    System.debug('****csOld.Ownerid******* ' + csOld.Ownerid);
                    messageBodyInput_1.messageSegments.add(mentionSegmentInput_1);                                
                    messageBodyInput_1.messageSegments.add(textSegmentInput_1);
                    feedItemInput_1.body = messageBodyInput_1;
                    feedItemInput_1.feedElementType = ConnectApi.FeedElementType.FeedItem;
                    feedItemInput_1.subjectId = csOld.id;
                    System.debug('*****feedItemInput_1.subjectId ****** ' + csOld.id);
             
                    if(!Test.isRunningTest()){
                        ConnectApi.FeedElement feedElement = ConnectApi.ChatterFeeds.postFeedElement(Network.getNetworkId(), feedItemInput_1);
                   }
                 }
            }
       }

Wednesday 10 May 2017

Update child to Grand parent

Updating Child to grandparent

1. Entitlement - Grand Parent
2. Case - Parent
3. Task - Child for case
4. Task -  Grand Child for Entitlement
5. Getting the Task object have the field called "Duration".
6. Getting the duration value and updating the Entitlement.
7. Entitlement was related to case & we are fetching the case related task.

        public void setRollupsummaryent(List<task> lstask)
        {
             if(Trigger.isUpdate)
              {
                Set<Id> caseId = new Set<Id>();
                for(Task ts1 : lstask)
                {
                    caseId.add(ts1.whatId);
                }
               
                Set<Id> entId = new Set<Id>();
                for(Case cs : [select Entitlementid, (Select Id,Duration__c from Tasks) from case where id in : caseId])
                {
                    entId.add(cs.EntitlementId);  
                }
               
                Map<Id,Decimal> entWithDuration = new Map<Id,Decimal>();
                for(Case cs : [select Entitlementid, (Select Id,Duration__c from Tasks) from case where Entitlementid in : entId ])
                {  
                   
                    Decimal duration = 0;
                    for(Task tk: cs.tasks){
                        if(tk.Duration__c != null){
                        duration += tk.Duration__c;
                        System.debug('&&&&&&&&&&&&' + duration);
                    }
                    }
                    if(entWithDuration.containsKey(cs.EntitlementId)){
                        Decimal temp = entWithDuration.get(cs.EntitlementId) + duration;
                        entWithDuration.put(cs.entitlementId, duration);
                    }else{
                        entWithDuration.put(cs.entitlementId, duration);
                    }
                }
               
                List<Entitlement> updateList = new List<Entitlement>();
                for(Entitlement etm: [Select Id,Used_hours__c from Entitlement where Id In:entWithDuration.keySet()]){
                   
                    etm.Used_hours__c = entWithDuration.get(etm.Id);
                    updateList.add(etm);
                }
               
                if(updateList.size() > 0){
                    update updateList;
                }
               
              }
        }

Sunday 7 May 2017

Summarize Case Total:

Rollup child to parent using Batch Class:

global class SummarizeCaseTotal implements Database.Batchable<sObject>, Database.Stateful{

   global final String query;
   global Map<Id, Case> casemap;
  
   global SummarizeCaseTotal(){
   casemap = new Map<Id, Case> ();
   }
 global Database.QueryLocator start(Database.BatchableContext BC){
      String query = 'select id, Duration__c, whatID from task';
      return Database.getQueryLocator(query);
   }
global void execute(Database.BatchableContext BC, List<sObject> scope){
   
   List<Task> ops = (List<Task>)scope;
   
   for (Task T : ops) 
{
    if(t.Duration__c != null)
    {
        if(casemap.containsKey(t.whatId))
        {
            Case c = caseMap.get(t.whatId);
            c.Billable_Hours__c += t.Duration__c;
            System.debug('#####################'+t.Duration__c);
            System.debug('$$$$$$$$$$$$$'+c.Billable_Hours__c);
            caseMap.put(t.whatId, c);
        }
        else
        {
            casemap.put(t.whatId, new Case (Id = t.whatID, Billable_Hours__c = t.Duration__c));
        }
    }
}
}
global void finish(Database.BatchableContext BC){
   
   try {
   update casemap.values();
   }
   catch (Exception Ex) {
   system.debug(Ex);
   }
   
   }
}


Scheduling the Batch Class:


global class scheduleSummarizeCaseTotal implements Schedulable {
   global void execute(SchedulableContext SC) {
      SummarizeCaseTotal sct = new SummarizeCaseTotal();
      database.executebatch(sct); 
   }
}


Schedule every 1 hour

System.schedule('Summarize Case Total', '0 0 0/1 * * ?', new scheduleSummarizeCaseTotal());

1. Entitlement have a multiple cases
2. Case have multiple Task
3. Rollup Task to Entitlement


Trigger:

trigger trgTaskDueDateUpd on Task (after insert, after update, after delete) {                                                                                                                                        
    if (!System.label.SYS_RunTaskTrigger.equalsIgnoreCase(System.Label.SYS_TRIGGER_NO)) { 
    
       ClsTriggerTaskHandler clsTaskhdr = new ClsTriggerTaskHandler();         
       if ((Trigger.isAfter && Trigger.isInsert)|| (Trigger.isAfter && Trigger.isUpdate)) 
       {
          clsTaskhdr.setDueDateFunction(Trigger.new,Trigger.old, Trigger.oldMap,True,False);
       }
       if (Trigger.isAfter && Trigger.isDelete) 
       {
           clsTaskhdr.setDueDateFunction(Trigger.new,Trigger.old, Trigger.oldMap,False,True);
       }
       /* if (Trigger.isAfter && Trigger.isUpdate) 
       {
           clsTaskhdr.ClsTriggerRolluHandler(Trigger.new,Trigger.old, Trigger.oldMap,True,False);
       }*/
    }
}

Trigger Handler

/*
Grandparent : Entitlement
Parent    : Case
Child       : Task

*/
        public void setRollupsummaryent(List<task> lstask)
        {
              if(Trigger.isUpdate)
              {
                Set<Id> caseId = new Set<Id>();
                for(Task ts1 : lstask)
                {
                    caseId.add(ts1.whatId);
                }
               
                Set<Id> entId = new Set<Id>();
                for(Case cs : [select Entitlementid, (Select Id,Duration__c from Tasks) from case where id in : caseId])
                {
                    entId.add(cs.EntitlementId);  
                }
               
                Map<Id,Decimal> entWithDuration = new Map<Id,Decimal>();
                for(Case cs : [select Entitlementid, (Select Id,Duration__c from Tasks) from case where Entitlementid in : entId ])
                {  
                    Decimal duration = 0;
                    for(Task tk: cs.tasks){
                        duration += tk.Duration__c;
                        System.debug('&&&&&&&&&&&&' + duration);
                    }

Wednesday 3 May 2017

1. Account is inserted we need to insert "Entitlement"
2. Contact is inserted we need to insert "Entitlement Contact"
3. Entitlement Contact is a junction between "Contact" & "Entitlement"
4. In Contact we need to give the account related Entitlement Id dynamically.

private void createEntitlementontacts(ClsWrappers.TriggerContext trgCtx) {
     
               if (trgCtx.isInsert || trgCtx.isUpdate)
               {
                               Set<Id> accIds = new Set<Id>();
                               Map<Id,Id> accEntlIdMap = new Map<Id,Id>();
                               List<EntitlementContact> entctlist = new List<EntitlementContact>();
                             
                               for(sobject so : trgCtx.newList)
                               {
                                              Contact con = (Contact)so;
                                              if(con.accountId != null){
                                                             accIds.add(con.accountId);
                                              }
                               }
                               if(accIds.size() > 0){
                                              for(Account acc : [select id, name, (select id, name from Entitlements) from Account where Id in: accIds])
                                              {
                                                             if(acc.Entitlements.size() > 0){
                                                                             accEntlIdMap.put(acc.Id,acc.Entitlements[0].Id);
                                                              }
                                              }
                               }
                               for(sobject so : trgCtx.newList)
                               {
                                              Contact con = (Contact)so;
                                              EntitlementContact en = new EntitlementContact();
                                              if(accEntlIdMap.containsKey(con.accountId)){
                                                              en.EntitlementId = accEntlIdMap.get(con.accountId);
                                                              en.ContactId = con.id;
                                                              entctlist.add(en);
                                              }
                               }
                               if(entctlist.size() > 0){
                                              System.debug('entctlist: '+entctlist);
                                              insert entctlist;
                               }
               }
}

Batch Apex

1. What are transaction limits in apex? Total number of SOQL queries issued1 - 100 Total number of records retrieved by SOQL queries - 50...