- devloper sfdc
- NEWBIE
- 99 Points
- Member since 2017
- Salesforce Developer
- EVC Campus
-
ChatterFeed
-
0Best Answers
-
0Likes Received
-
0Likes Given
-
48Questions
-
56Replies
Code Coverage problem on my apex trigger
Hello All,
I am controlling our spam ticket using this trigger. And also Trigger running as expected my requirment. but I am not able to getting full code coverge by test class. Please check my test class and tell me what the actual error in my code .
Screen shot
Thanks & Regards
My Apex Trigger is
and my Test class is
I am controlling our spam ticket using this trigger. And also Trigger running as expected my requirment. but I am not able to getting full code coverge by test class. Please check my test class and tell me what the actual error in my code .
Screen shot
Thanks & Regards
My Apex Trigger is
trigger SpamControllerTrigger on Case (before insert) { /*===================================================hhjjf====================================*/ List<String> lstBasedOnDesc=new List<String>(); for(Keywords__c ks:[Select name from Keywords__c]){ lstBasedOnDesc.add(ks.name);} List<String>LstSpamkeyword=new List<String>(); /*===================================================hhjjf====================================*/ for(Trigger_Control__c tc:Trigger_Control__c.getAll().values()) { if( tc.Enable_Spam_Controller_Trigger__c==true) { for(case cs:Trigger.new) {//0050W0000061RWD sebastian //005d000000187CwAAI automated if(userinfo.getUserId()=='005d000000187CwAAI') { if(lstBasedOnDesc.size()>0) { for(String s:lstBasedOnDesc){ if(cs.Description!=null && ( cs.Description).Contains(s)) { cs.ownerId='00Gd00000027kH7'; cs.Spam_criteria__c='Based on Description'; cs.Possible_Spam__c=true;cs.Identified_Keyword__c=s; CalculatingScoreValue.getScoreValue(s); } else if(cs.Subject!=null && (cs.Subject).Contains(s)) { cs.ownerId='00Gd00000027kH7'; cs.Spam_criteria__c='Based on Subject'; cs.Possible_Spam__c=true; cs.Identified_Keyword__c=s; CalculatingScoreValue.getScoreValue(s); } else if((cs.SuppliedEmail).Contains(s)) {cs.ownerId='00Gd00000027kH7'; cs.Spam_criteria__c='Based on Webmail'; cs.Possible_Spam__c=true;cs.Identified_Keyword__c=s; CalculatingScoreValue.getScoreValue(s); } }}}}}}}
and my Test class is
@isTest public class SpamControllerTriggerTest { @isTest public Static void SpamTestmethod() { Account acc = new Account(Name='MassBay'); insert acc; Contact con = new Contact(AccountId=acc.Id,LastName='test',Email='desd.red@test.tst'); insert con; Trigger_Control__c tc=new Trigger_Control__c(); tc.Enable_Spam_Controller_Trigger__c=true; tc.Name='test tc'; insert tc; Keywords__c key=new keywords__c(name='badword'); insert key; List<case>lstcase=new List<case>(); List<RecordType> listRecType = [select Id from RecordType where sObjectType = 'Case' And Name = 'MassBay_Ticket']; Case cs = new Case(RecordTypeId = listRecType[0].Id,AccountId=acc.Id,ContactId=con.Id); cs.Spam_criteria__c='Based on Description'; cs.Subject='Testing for spam'; cs.Description=key.Name; cs.SuppliedEmail='xxx@test.com'; cs.Possible_Spam__c=true; cs.Identified_Keyword__c='s'; lstcase.add(cs); insert lstcase; } }
- devloper sfdc
- February 10, 2021
- Like
- 0
Code coverage issue on apex trigger
Hi All ,
I am getting code coverage only 40 percent in my apex trigger. Please check my apex trigger and test class . Please let me where the issue on my test class . I am attaching screenshot of the class where i struct for code coverage.
My apex trigger is
and Here is Test class
I am getting code coverage only 40 percent in my apex trigger. Please check my apex trigger and test class . Please let me where the issue on my test class . I am attaching screenshot of the class where i struct for code coverage.
My apex trigger is
trigger EMailToCaseMerge on Case (After insert) { List<string> lstSubject=new List<String>(); Set<Id>AccId =new Set<Id>(); Set<Id>RecId = new Set<Id>(); String casId=''; List<String> dupCas=new List<String>(); list<String> getuserId =CaseMergeEmail.getuserIdlst(); system.debug('userIds'+getuserId); List<Case> lstUpdateCase= new list<case>(); for(Trigger_Control__c tc:Trigger_Control__c.getall().values()){ if(tc.Enable_zGlobalCaseMerge__c==true) { for(Case cs :Trigger.new) { AccId.add(cs.AccountId); lstSubject.add(cs.Subject); RecId.add(cs.recordTypeId); } if(userInfo.getUserName()=='sf_XXXX@XXX.newapi') { Set<Id>aId=new Set<Id>(); List<Account> getAccountlist= [select id ,Enable_zGlobalCaseMerge__c from account where Enable_zGlobalCaseMerge__c=true and Id in:AccId]; if(getAccountlist.size()>0) { for(Account a:getAccountlist) { aId.add(a.id); } } List<Case> getCaslst=[select status,parentId, Prevent_Closure_Email__c,Prevent_CaseComment_Notification__c,id from case where accountId in:aId and subject in:lstSubject and isClosed=false and recordtypeId in:RecId and status!='Escalated' order by createddate]; if(getCaslst.size()>0){ system.debug('getCaslst[0].id'+getCaslst[0].id); casId=getCaslst[0].id; for(Case cs:getCaslst) { if(cs.id!=getCaslst[0].id) { cs.parentId=getCaslst[0].id; cs.Prevent_Closure_Email__c=true; cs.Prevent_CaseComment_Notification__c=true; cs.status='Closed (Duplicate)'; lstUpdateCase.add(cs); dupCas.add(cs.Id); } } update lstUpdateCase; if(dupCas.size()>0) { CaseMergeEmail.casAttachment(dupCas,casId); CaseMergeEmail.CasCommnet(dupCas,casId); } } } } } }
and Here is Test class
@IsTest public class CaseMergeHandlerTest { static testMethod void testMerge(){ List<String>DupCase =new List<String>(); Account testAccount = new Account(Name='Test Company Name123'); insert testAccount; Contact con = new Contact(LastName='Testcont' ,Email='sss@test.com', AccountId=testAccount.Id); insert con; Trigger_Control__c tc=new Trigger_Control__c(); tc.name='testCustumer'; tc.Enable_zGlobalCaseMerge__c=true; insert tc; User u; User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()]; System.runAs (thisUser) { Profile p = [SELECT Id FROM Profile WHERE Name='CH_Tier1-Partner']; u = new User(alias = 'tstwy', email='testmail@tst.com', emailencodingkey='UTF-8', lastname='testL', languagelocalekey='en_US', localesidkey='en_US', profileid = p.Id, ContactId = con.Id, timezonesidkey='America/Los_Angeles', username='XXXXX@XXXX.org.newapi'); insert u; } System.runAs (u) { List<RecordType> listRecType = [select Id from RecordType where sObjectType = 'Case' And Name = 'Mass_Ticket']; List<Case>lstcase =new List<Case>(); for(Integer i=0; i <2; i++){ lstcase.add(new Case( Prevent_Closure_Email__c=true,Prevent_CaseComment_Notification__c=true,AccountId=testAccount.Id, ContactId = con.Id,Origin='Email', subject='test',recordtypeId= listRecType[0].Id ,Status='New',ownerid='00Gd0000001QYQU')); } insert lstcase; integer k; DupCase.add(lstcase[0].Id); DupCase.add(lstcase[1].Id); Attachment attach=new Attachment(); attach.Name='test.html'; Blob bodyBlob=Blob.valueOf('Unit Test Attachment Body'); attach.Body=bodyBlob; attach.ParentId=lstcase[0].Id; insert attach; List<Attachment> attachments=[SELECT Id, Name, ParentId FROM Attachment WHERE Parent.Id=:lstcase[0].Id]; System.assertEquals(1, attachments.size()); //Sanity check caseComment newcmt=new casecomment(); newcmt.ParentId=lstcase[0].Id; newcmt.CommentBody='Test comments'; insert newcmt; List<caseComment> lstCaseComments=[SELECT Id, CommentBody, ParentId FROM caseComment WHERE Parent.Id=:lstcase[0].Id limit 1]; System.assertEquals(1, lstCaseComments.size()); //Sanity check*/ Test.startTest(); CaseMergeEmail.casAttachment(DupCase, lstcase[0].Id); CaseMergeEmail.CasCommnet(DupCase, lstcase[0].Id); //CaseMergeEmail.TicketLogs(lstcase); Test.stopTest(); attachments=[SELECT Id, Name, ParentId FROM Attachment WHERE Parent.Id=:lstcase[0].Id]; System.assertEquals(2, attachments.size()); //real check - did we duplicate the attachment System.assertEquals(attachments[0].Name, attachments[1].Name); lstCaseComments=[SELECT Id, CommentBody,ParentId FROM CaseComment WHERE Parent.Id=:lstcase[0].Id]; System.assertEquals(2, lstCaseComments.size()); System.assertEquals(lstCaseComments[0].CommentBody, lstCaseComments[1].CommentBody); } } }
- devloper sfdc
- February 10, 2021
- Like
- 0
Getting error List index out of bound 0 and i got 36% code coverage
Hello All,
I am getting error in test class is ''List index out of bound 0" . And I getting 36% code coverage in my test class. Please help me both are class are there
apex class.
and my test class is
I am getting error in test class is ''List index out of bound 0" . And I getting 36% code coverage in my test class. Please help me both are class are there
apex class.
public class CaseMergeApexClass { Public String textEnter {get;set;} public List<sObjectWrapper> wrappers {get;set;} public List<case> lstcas {get;set;} public String selectMasterCase {get;set;} public boolean addOnChkbx {get;set;} public boolean isSelected{get;set;} public boolean flagmerged; Public String caseId {get;set;} public List<case>mappsub {get;set;} public CaseMergeApexClass(ApexPages.StandardController stdController) { caseId = apexpages.currentpage().getparameters().get('id'); lstcas = new List<case>(); wrappers=new List<sObjectWrapper>(); flagmerged =true; mappsub =new List<case>(); for(case cs:[select id,Account.name,Contact.name,RecordType.name,owner.name,subject from case where id=:caseId limit 1]) { mappsub.add(cs); } } public void mergeCase() { list<Case>lstgetcas=[select zGloblal_Total_attachments__c, RecordType.name,CaseNumber,id,subject,account.name,contact.name from case where RecordType.name=:mappsub.get(0).RecordType.name and Contact.name=:mappsub.get(0).Contact.name and Subject like :'%'+mappsub.get(0).subject+'%' and status!='Closed Duplicate' ]; for(case cs:lstgetcas) { if(flagmerged){ wrappers.add(new sObjectWrapper(cs,addOnChkbx)); } } flagmerged=false; } public void selectForMaster() { lstcas.clear(); for(sObjectWrapper wrap : wrappers){ /*Check if record is selected*/ if(wrap.isSelected==true){ lstcas.add(wrap.cas); } } } public void mergedTicket() { list<case> updcase=new List<case>(); list<caseComment> NewCaseCommet=new List<caseComment>(); list<caseComment> lstComment= [select id ,commentbody,parentid from casecomment where parentId in:lstcas]; for(casecomment cmt:lstComment) { caseComment newcmt=new casecomment(); newcmt.ParentId=caseId; newcmt.CommentBody=cmt.CommentBody; NewCaseCommet.add(newcmt); } insert NewCaseCommet; List<attachment> newAttachment =new list<attachment>(); List<attachment> lstAttachments=[select id,Body,Name,ParentId from attachment where parentId in:lstcas]; for(attachment att:lstAttachments) { attachment newattch=new attachment(); newattch.parentId=caseId; newattch.Body=att.body; newattch.name=att.name; newAttachment.add(newattch); } insert newAttachment; closedDuplicate(); urlre(); } public void closedDuplicate() { List<case> closedcase =new List<case>(); for(case cs:lstcas) { cs.Status='Closed Duplicate'; closedcase.add(cs); } update closedcase; } public pagereference urlre() { caseId = apexpages.currentpage().getparameters().get('id'); pagereference pg =new pagereference('/'+caseId); return pg; } public class sObjectWrapper { public boolean isSelected{get;set;} public case cas{get;set;} public sObjectWrapper(case cas,Boolean isSelected){ this.cas = cas; this.isSelected = isSelected; } } }
and my test class is
@isTest public class CaseMergeApexClassTest { static testMethod void testMerge(){ Account testAccount = new Account(Name='Test Company Name123'); insert testAccount; Contact con = new Contact(LastName='Testcont' ,Email='sss@test.com', AccountId=testAccount.id); insert con; list<case>lstcase =new LIst<case>(); Case caseObj1 = new Case(); caseObj1.AccountId = testAccount.Id; caseObj1.contactId=con.id; caseObj1.Status = 'Action-Automated Escalation'; caseObj1.Origin ='Email'; lstcase.add(caseObj1); Case caseObj2 = new Case(); caseObj2.AccountId = testAccount.Id; caseObj2.contactId=con.id; caseObj2.Status = 'Closed Duplicate'; caseObj2.Origin ='Email'; lstcase.add(caseObj2); test.startTest(); insert lstcase; string casId=lstcase[0].id; ApexPages.StandardController sc = new ApexPages.StandardController(lstcase[0]); CaseMergeApexClass testCon = new CaseMergeApexClass(sc); testCon.CaseId = lstcase[0].id ; PageReference pageRef = Page.CaseMergePage; pageRef.getParameters().put('id', String.valueOf(lstcase[0].id)); Test.setCurrentPage(pageRef); testCon.addOnChkbx=true; testCon.closedDuplicate(); testCon.textEnter='899898'; testCon.selectMasterCase='89898'; testCon.flagmerged=true; testCon.isSelected=true; testCon.urlre(); testCon.mergeCase(); testCon.selectForMaster(); testCon.mergedTicket(); test.stopTest(); } }
- devloper sfdc
- July 06, 2020
- Like
- 0
i need case id when i click on button
Hi All
Please help on this issue i am getting undefined value in alert message when i clicked in view detail button . I want to Id of the record when i clicked the button .
This is my page
dohandelClick : function(component, event, helper){
var eventSource=event.getSource();
var Id=eventSource.get('v.name');
var navEvt = $A.get("e.force:navigateToSObject");
alert(Id);
navEvt.setParams({
"recordId": Id
});
navEvt.fire();
},
Please help on this issue i am getting undefined value in alert message when i clicked in view detail button . I want to Id of the record when i clicked the button .
This is my page
dohandelClick : function(component, event, helper){
var eventSource=event.getSource();
var Id=eventSource.get('v.name');
var navEvt = $A.get("e.force:navigateToSObject");
alert(Id);
navEvt.setParams({
"recordId": Id
});
navEvt.fire();
},
- devloper sfdc
- May 29, 2020
- Like
- 0
I am getting error during deployment
Salesfore Experts,
I am working on a requirement where I need to trigger email with all attachments on a ticket when owner gets changed. The below mentioned code works as expected in Sandbox and I get 87% code coverage but when we try to deploy in production the code coverage is reduced to 25% which I am unable to figure out what is causing it.
And We are getting error is
" ystem.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, zGLOBAL_New_Owner_Notifi_Trigger: execution of BeforeUpdate 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) Class.zGLOBAL_New_Owner_Notifi_Attachment.emailSender: line 9, column 1 Trigger.z "
And Test class is
I am working on a requirement where I need to trigger email with all attachments on a ticket when owner gets changed. The below mentioned code works as expected in Sandbox and I get 87% code coverage but when we try to deploy in production the code coverage is reduced to 25% which I am unable to figure out what is causing it.
And We are getting error is
" ystem.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, zGLOBAL_New_Owner_Notifi_Trigger: execution of BeforeUpdate 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) Class.zGLOBAL_New_Owner_Notifi_Attachment.emailSender: line 9, column 1 Trigger.z "
public class zGLOBAL_New_Owner_Notifi_Attachment { public static void emailSender(Map<Id,Case> oldMap, Map<Id,Case> newMap) { // this is a list for storing email for settoAddress List<String>toAddress =new List<String>(); // this is a list for storing email for setccAddress List<String>CCAddress =new List<String>(); List<contact> lstcont=[select id ,Email,name,phone from contact]; Map<String,String> mapContact=new Map<String,String>(); list<String> ccAddresslst=new List<String>(); map<string,String> mapuser=new map<string,string>(); Set<Id> accIds=new Set<Id>(); Set<Id> recId=new Set<Id>(); String ownerName=''; String baseUrl = URL.getSalesforceBaseUrl().toExternalForm(); //for getting user email and store in map where user id is key and email is value for(User u:[select id, name, Email from user]) { mapuser.put(u.id,u.email); } //for getting Contact name and store in map where id is key and name is value for(contact con:lstcont) { mapContact.put(con.id,con.name); } //Change Trigger.new with udtCases for(Id key : oldMap.keySet()) { case oldcase=oldMap.get(key); case cs=newMap.get(key); if(cs.zGloblal_Total_attachments__c>=1 && cs.APEX_Owner_notifications_Attachments__c==true) { //Changed Trigger.oldMap if(oldcase.OwnerId!=cs.OwnerId) { if(string.valueOf(cs.OwnerId).startsWith('005')) { toAddress.add(mapuser.get(cs.OwnerId)); ownerName=Getqueuemember.getOwnername(cs.OwnerId); } else{ CCAddress=Getqueuemember.getEmailfromuser(cs.OwnerId); ownerName=Getqueuemember.getqueueOwnername(cs.OwnerId); } List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>(); List<Attachment> attlist=[select Name, Body, BodyLength from Attachment where ParentId = :cs.id ]; for (Attachment a :attlist){ Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment(); efa.setFileName(a.Name); efa.setBody(a.Body); fileAttachments.add(efa); } String Subject='Ticket #'+cs.CaseNumber+' has been assigned to '+' '+ownerName; try{ Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage(); semail.setSubject(Subject); semail.setSenderDisplayName('Salesforce Support'); semail.setTargetObjectId(cs.ContactId); //semail.setTemplateId(et.id); semail.setCcAddresses(CCAddress); semail.setToAddresses(toAddress); semail.setHtmlBody('***THIS IS A SYSTEM GENERATED MESSAGE! DO NOT REPLY!***<br/><br/>Please be advised that the following SalesForce ticket has been assigned to '+ownerName+'<br/><br/> Ticket #:'+cs.CaseNumber+ '<br/>Subject:'+cs.subject+'<br/><br/>Contact Name: '+mapContact.get(cs.Contactid)+'<br/>Contact Phone (primary): '+Getqueuemember.r(cs.ContactPhone)+'<br/>Contact Mobile (primary): '+Getqueuemember.r(cs.ContactMobile)+ '<br/> Contact Email:'+Getqueuemember.r(cs.ContactEmail)+'<br/><br/>Category: '+Getqueuemember.r(cs.Ticket_Category__c)+Getqueuemember.r(cs.Service_Category__c)+Getqueuemember.r(cs.Ticket_Category2__c)+ '<br/>Type: '+Getqueuemember.r(cs.Ticket_Type__c)+Getqueuemember.r(cs.Service_Type__c)+Getqueuemember.r(cs.Ticket_Type2__c)+ '<br/>Item: '+Getqueuemember.r(cs.Ticket_Item__c)+Getqueuemember.r(cs.Service_Item__c)+Getqueuemember.r(cs.Ticket_Item2__c)+ '<br/>Ticket Source: '+Getqueuemember.r(cs.Case_Source__c)+'<br/><br/><br/>Building: '+Getqueuemember.r(cs.building__c)+'<br/>Room: '+Getqueuemember.r(cs.Room_Number__c)+'<br/>Area Description: '+Getqueuemember.r(cs.Area_description__c)+ '<br/><br/><br/>Click the appropriate link below to view the ticket directly:<br/><br/>Partner Portal Users: <a href='+baseUrl+'/'+cs.id+'>'+baseUrl+'/'+cs.id+'</a><br/>BlackbeltHelp (Community Users): <a href='+Getqueuemember.getcommunityurl(cs.AccountId)+cs.id+ '>'+Getqueuemember.getcommunityurl(cs.AccountId)+cs.id+'</a><br/><br/>Description:'+cs.Description+'<br/><br/>Internal Notes: '+Getqueuemember.r(cs.Internal_Notes__c)); semail.setFileAttachments(fileAttachments); semail.setWhatId(cs.id); Messaging.sendEmail(new Messaging.SingleEmailMessage[] {semail}); } catch(exception e) {} } } } } }
And Test class is
@isTest public class zGLOBAL_New_Owner_Notifi_AttachmentTest { @isTest public Static void emailTest() { // create test account Account acc = TestUtilityController.getAccount('MassBay'); acc.APEX_Owner_notifications_Attachments__c=true; insert acc; // create test contact Contact con = TestUtilityController.getContact('Test Last Name','testing@testing.com',acc.Id); insert con; // fill utility UtilityController.fillUtilities(); UtilityController.isUtility = false; trigger_control__c tc = new trigger_control__c(); tc.name='test'; tc.Enable_Owner_Notification_Trigger__c=true; insert tc; // Create test cases List<Case> listCase = new List<Case>(); if(UtilityController.caseRecordType.containsKey('MassBayCC_Ticket')){ String recordTypeId = UtilityController.caseRecordType.get('MassBayCC_Ticket').Id; Case csanew = TestUtilityController.getCase(recordTypeId,con.Id,acc.Id); csanew.status = 'Action - Automated Escalation'; csanew.zGloblal_Total_attachments__c=2; csanew.Ticket_Category2__c = 'Blackboard Learn - LMS'; csanew.Ticket_Type2__c = 'Faculty/Staff'; csanew.Ticket_Item2__c='Tutorial'; listCase.add(csanew); //Added additional code here System.test.startTest(); insert listCase; System.Test.stopTest(); Getqueuemember.getcommunityurl(acc.id); Getqueuemember.getEmailfromuser('0050W0000061RWD'); Getqueuemember.getOwnername('0050W0000061RWD'); Getqueuemember.getqueueOwnername('00Gd00000027kH7'); Getqueuemember.r(csanew.Ticket_Category2__c); } } }
- devloper sfdc
- February 18, 2020
- Like
- 0
ffff
Salesfore Experts,
I am working on a requirement where I need to trigger email with all attachments on a ticket when owner gets changed. The below mentioned code works as expected in Sandbox and I get 87% code coverage but when we try to deploy in production the code coverage is reduced to 25% which I am unable to figure out what is causing it.
And We are getting error is
" ystem.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, zGLOBAL_New_Owner_Notifi_Trigger: execution of BeforeUpdate 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) Class.zGLOBAL_New_Owner_Notifi_Attachment.emailSender: line 9, column 1 Trigger.z "
If any one have experianced such an issue earlier, any pointers in fixing this would be greatly appriciated.
Here is my APEX class
And Test Class is
I am working on a requirement where I need to trigger email with all attachments on a ticket when owner gets changed. The below mentioned code works as expected in Sandbox and I get 87% code coverage but when we try to deploy in production the code coverage is reduced to 25% which I am unable to figure out what is causing it.
And We are getting error is
" ystem.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, zGLOBAL_New_Owner_Notifi_Trigger: execution of BeforeUpdate 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) Class.zGLOBAL_New_Owner_Notifi_Attachment.emailSender: line 9, column 1 Trigger.z "
If any one have experianced such an issue earlier, any pointers in fixing this would be greatly appriciated.
Here is my APEX class
public class zGLOBAL_New_Owner_Notifi_Attachment { public static void emailSender(Map<Id,Case> oldMap, Map<Id,Case> newMap) { // this is a list for storing email for settoAddress List<String>toAddress =new List<String>(); // this is a list for storing email for setccAddress List<String>CCAddress =new List<String>(); List<contact> lstcont=[select id ,Email,name,phone from contact]; Map<String,String> mapContact=new Map<String,String>(); list<String> ccAddresslst=new List<String>(); map<string,String> mapuser=new map<string,string>(); Set<Id> accIds=new Set<Id>(); Set<Id> recId=new Set<Id>(); String ownerName=''; String baseUrl = URL.getSalesforceBaseUrl().toExternalForm(); //for getting user email and store in map where user id is key and email is value for(User u:[select id, name, Email from user]) { mapuser.put(u.id,u.email); } //for getting Contact name and store in map where id is key and name is value for(contact con:lstcont) { mapContact.put(con.id,con.name); } //Change Trigger.new with udtCases for(Id key : oldMap.keySet()) { case oldcase=oldMap.get(key); case cs=newMap.get(key); if(cs.zGloblal_Total_attachments__c>=1 && cs.APEX_Owner_notifications_Attachments__c==true) { //Changed Trigger.oldMap if(oldcase.OwnerId!=cs.OwnerId) { if(string.valueOf(cs.OwnerId).startsWith('005')) { toAddress.add(mapuser.get(cs.OwnerId)); ownerName=Getqueuemember.getOwnername(cs.OwnerId); } else{ CCAddress=Getqueuemember.getEmailfromuser(cs.OwnerId); ownerName=Getqueuemember.getqueueOwnername(cs.OwnerId); } List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>(); List<Attachment> attlist=[select Name, Body, BodyLength from Attachment where ParentId = :cs.id ]; for (Attachment a :attlist){ Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment(); efa.setFileName(a.Name); efa.setBody(a.Body); fileAttachments.add(efa); } String Subject='Ticket #'+cs.CaseNumber+' has been assigned to '+' '+ownerName; try{ Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage(); semail.setSubject(Subject); semail.setSenderDisplayName('Salesforce Support'); semail.setTargetObjectId(cs.ContactId); //semail.setTemplateId(et.id); semail.setCcAddresses(CCAddress); semail.setToAddresses(toAddress); semail.setHtmlBody('***THIS IS A SYSTEM GENERATED MESSAGE! DO NOT REPLY!***<br/><br/>Please be advised that the following SalesForce ticket has been assigned to '+ownerName+'<br/><br/> Ticket #:'+cs.CaseNumber+ '<br/>Subject:'+cs.subject+'<br/><br/>Contact Name: '+mapContact.get(cs.Contactid)+'<br/>Contact Phone (primary): '+Getqueuemember.r(cs.ContactPhone)+'<br/>Contact Mobile (primary): '+Getqueuemember.r(cs.ContactMobile)+ '<br/> Contact Email:'+Getqueuemember.r(cs.ContactEmail)+'<br/><br/>Category: '+Getqueuemember.r(cs.Ticket_Category__c)+Getqueuemember.r(cs.Service_Category__c)+Getqueuemember.r(cs.Ticket_Category2__c)+ '<br/>Type: '+Getqueuemember.r(cs.Ticket_Type__c)+Getqueuemember.r(cs.Service_Type__c)+Getqueuemember.r(cs.Ticket_Type2__c)+ '<br/>Item: '+Getqueuemember.r(cs.Ticket_Item__c)+Getqueuemember.r(cs.Service_Item__c)+Getqueuemember.r(cs.Ticket_Item2__c)+ '<br/>Ticket Source: '+Getqueuemember.r(cs.Case_Source__c)+'<br/><br/><br/>Building: '+Getqueuemember.r(cs.building__c)+'<br/>Room: '+Getqueuemember.r(cs.Room_Number__c)+'<br/>Area Description: '+Getqueuemember.r(cs.Area_description__c)+ '<br/><br/><br/>Click the appropriate link below to view the ticket directly:<br/><br/>Partner Portal Users: <a href='+baseUrl+'/'+cs.id+'>'+baseUrl+'/'+cs.id+'</a><br/>BlackbeltHelp (Community Users): <a href='+Getqueuemember.getcommunityurl(cs.AccountId)+cs.id+ '>'+Getqueuemember.getcommunityurl(cs.AccountId)+cs.id+'</a><br/><br/>Description:'+cs.Description+'<br/><br/>Internal Notes: '+Getqueuemember.r(cs.Internal_Notes__c)); semail.setFileAttachments(fileAttachments); semail.setWhatId(cs.id); Messaging.sendEmail(new Messaging.SingleEmailMessage[] {semail}); } catch(exception e) {} } } } } }
And Test Class is
@isTest public class zGLOBAL_New_Owner_Notifi_AttachmentTest { @isTest public Static void emailTest() { // create test account Account acc = TestUtilityController.getAccount('MassBay'); acc.APEX_Owner_notifications_Attachments__c=true; insert acc; // create test contact Contact con = TestUtilityController.getContact('Test Last Name','testing@testing.com',acc.Id); insert con; // fill utility UtilityController.fillUtilities(); UtilityController.isUtility = false; trigger_control__c tc = new trigger_control__c(); tc.name='test'; tc.Enable_Owner_Notification_Trigger__c=true; insert tc; // Create test cases List<Case> listCase = new List<Case>(); if(UtilityController.caseRecordType.containsKey('MassBayCC_Ticket')){ String recordTypeId = UtilityController.caseRecordType.get('MassBayCC_Ticket').Id; Case csanew = TestUtilityController.getCase(recordTypeId,con.Id,acc.Id); csanew.status = 'Action - Automated Escalation'; csanew.zGloblal_Total_attachments__c=2; csanew.Ticket_Category2__c = 'Blackboard Learn - LMS'; csanew.Ticket_Type2__c = 'Faculty/Staff'; csanew.Ticket_Item2__c='Tutorial'; listCase.add(csanew); //Added additional code here System.test.startTest(); insert listCase; System.Test.stopTest(); Getqueuemember.getcommunityurl(acc.id); Getqueuemember.getEmailfromuser('0050W0000061RWD'); Getqueuemember.getOwnername('0050W0000061RWD'); Getqueuemember.getqueueOwnername('00Gd00000027kH7'); Getqueuemember.r(csanew.Ticket_Category2__c); } } }
- devloper sfdc
- February 18, 2020
- Like
- 0
Problem in test class i am getting only 36% code coverage
Hi Salesforce Expert,
We are getting only 36% code coverage in our apex class. my Apex trigger please help me apex code is here-
And test class is
code which is not covering is below here--
We are getting only 36% code coverage in our apex class. my Apex trigger please help me apex code is here-
trigger EmailSendToOwnerUpdate on Case (before update) { // this is a list for storing email for settoAddress List<String>toAddress =new List<String>(); // this is a list for storing email for setccAddress List<String>CCAddress =new List<String>(); List<contact> lstcont=[select id ,Email,name,phone from contact]; Map<String,String> mapContact=new Map<String,String>(); list<String> ccAddresslst=new List<String>(); map<string,String> mapuser=new map<string,string>(); String ownerName=''; String baseUrl = URL.getSalesforceBaseUrl().toExternalForm(); //for getting user email and store in map where user id is key and email is value for(User u:[select id, name, Email from user]) { mapuser.put(u.id,u.email); } //for getting Contact name and store in map where id is key and name is value for(contact con:lstcont) { mapContact.put(con.id,con.name); } for(case cs:trigger.new) { if(cs.total_attachments__c>=1) { case oldcase=Trigger.oldMap.get(cs.id); if(oldcase.OwnerId!=cs.OwnerId) { if(string.valueOf(cs.OwnerId).startsWith('005')) { toAddress.add(mapuser.get(cs.OwnerId)); ownerName=Getqueuemember.getOwnername(cs.OwnerId); } else{ CCAddress=Getqueuemember.getEmailfromuser(cs.OwnerId); ownerName=Getqueuemember.getqueueOwnername(cs.OwnerId); } List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>(); List<Attachment> attlist=[select Name, Body, BodyLength from Attachment where ParentId = :cs.id ]; for (Attachment a :attlist){ Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment(); efa.setFileName(a.Name); efa.setBody(a.Body); fileAttachments.add(efa); } String Subject='Apex template Ticket #'+cs.CaseNumber+' has been assigned to '+' '+ownerName; try{ EmailTemplate et = [SELECT Id,Subject, Body FROM EmailTemplate WHERE DeveloperName ='Sebastian_page']; Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage(); semail.setSubject(Subject); semail.setSenderDisplayName('Salesforce Support'); semail.setTargetObjectId(cs.ContactId); //semail.setTemplateId(et.id); semail.setCcAddresses(CCAddress); semail.setToAddresses(toAddress); semail.setHtmlBody('***THIS IS A SYSTEM GENERATED MESSAGE! DO NOT REPLY!***<br/><br/>Please be advised that the following SalesForce ticket has been assigned to '+ownerName+'<br/><br/> Ticket #:'+cs.CaseNumber+ '<br/>Subject:'+cs.subject+'<br/><br/>Contact Name: '+mapContact.get(cs.Contactid)+'<br/>Contact Phone (primary): '+Getqueuemember.r(cs.ContactPhone)+'<br/>Contact Mobile (primary): '+Getqueuemember.r(cs.ContactMobile)+ '<br/> Contact Email:'+Getqueuemember.r(cs.ContactEmail)+'<br/><br/>Category: '+Getqueuemember.r(cs.Ticket_Category__c)+Getqueuemember.r(cs.Service_Category__c)+Getqueuemember.r(cs.Ticket_Category2__c)+ '<br/>Type: '+Getqueuemember.r(cs.Ticket_Type__c)+Getqueuemember.r(cs.Service_Type__c)+Getqueuemember.r(cs.Ticket_Type2__c)+ '<br/>Item: '+Getqueuemember.r(cs.Ticket_Item__c)+Getqueuemember.r(cs.Service_Item__c)+Getqueuemember.r(cs.Ticket_Item2__c)+ '<br/>Ticket Source: '+Getqueuemember.r(cs.Case_Source__c)+'<br/><br/><br/>Building: '+Getqueuemember.r(cs.building__c)+'<br/>Room: '+Getqueuemember.r(cs.Room_Number__c)+'<br/>Area Description: '+Getqueuemember.r(cs.Area_description__c)+ '<br/><br/><br/>Click the appropriate link below to view the ticket directly:<br/><br/>Partner Portal Users: <a href='+baseUrl+'/'+cs.id+'>'+baseUrl+'/'+cs.id+'</a><br/>BlackbeltHelp (Community Users): <a href='+Getqueuemember.getcommunityurl(cs.AccountId)+cs.id+ '>'+Getqueuemember.getcommunityurl(cs.AccountId)+cs.id+'</a><br/><br/>Description:'+cs.Description+'<br/><br/>Internal Notes: '+Getqueuemember.r(cs.Internal_Notes__c)); semail.setFileAttachments(fileAttachments); semail.setWhatId(cs.id); Messaging.sendEmail(new Messaging.SingleEmailMessage[] {semail}); } catch(exception e) {} } } } }
And test class is
@isTest public class TestEmailSendToOwner { @isTest public Static void emailTest() { // create test account Account acc = TestUtilityController.getAccount('MassBay'); insert acc; // create test contact Contact con = TestUtilityController.getContact('Test Last Name','testing@testing.com',acc.Id); insert con; // fill utility UtilityController.fillUtilities(); UtilityController.isUtility = false; // Create test cases List<Case> listCase = new List<Case>(); if(UtilityController.caseRecordType.containsKey('MassBayCC_Ticket')){ String recordTypeId = UtilityController.caseRecordType.get('MassBayCC_Ticket').Id; Case csanew = TestUtilityController.getCase(recordTypeId,con.Id,acc.Id); csanew.status = 'Action - Automated Escalation'; csanew.total_attachments__c=2; csanew.Ticket_Category2__c = 'Blackboard Learn - LMS'; csanew.Ticket_Type2__c = 'Faculty/Staff'; csanew.Ticket_Item2__c='Tutorial'; listCase.add(csanew); insert listCase; Getqueuemember.getcommunityurl(acc.id); Getqueuemember.getEmailfromuser(listCase[0].ownerId); Getqueuemember.getOwnername(listCase[0].ownerId); Getqueuemember.r(csanew.Ticket_Category2__c); } } }
code which is not covering is below here--
if(string.valueOf(cs.OwnerId).startsWith('005')) { toAddress.add(mapuser.get(cs.OwnerId)); ownerName=Getqueuemember.getOwnername(cs.OwnerId); } else{ CCAddress=Getqueuemember.getEmailfromuser(cs.OwnerId); ownerName=Getqueuemember.getqueueOwnername(cs.OwnerId); } List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>(); List<Attachment> attlist=[select Name, Body, BodyLength from Attachment where ParentId = :cs.id ]; for (Attachment a :attlist){ Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment(); efa.setFileName(a.Name); efa.setBody(a.Body); fileAttachments.add(efa); } String Subject='Apex template Ticket #'+cs.CaseNumber+' has been assigned to '+' '+ownerName; try{ EmailTemplate et = [SELECT Id,Subject, Body FROM EmailTemplate WHERE DeveloperName ='Sebastian_page']; Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage(); semail.setSubject(Subject); semail.setSenderDisplayName('Salesforce Support'); semail.setTargetObjectId(cs.ContactId); //semail.setTemplateId(et.id); semail.setCcAddresses(CCAddress); semail.setToAddresses(toAddress); semail.setHtmlBody('***THIS IS A SYSTEM GENERATED MESSAGE! DO NOT REPLY!***<br/><br/>Please be advised that the following SalesForce ticket has been assigned to '+ownerName+'<br/><br/> Ticket #:'+cs.CaseNumber+ '<br/>Subject:'+cs.subject+'<br/><br/>Contact Name: '+mapContact.get(cs.Contactid)+'<br/>Contact Phone (primary): '+Getqueuemember.r(cs.ContactPhone)+'<br/>Contact Mobile (primary): '+Getqueuemember.r(cs.ContactMobile)+ '<br/> Contact Email:'+Getqueuemember.r(cs.ContactEmail)+'<br/><br/>Category: '+Getqueuemember.r(cs.Ticket_Category__c)+Getqueuemember.r(cs.Service_Category__c)+Getqueuemember.r(cs.Ticket_Category2__c)+ '<br/>Type: '+Getqueuemember.r(cs.Ticket_Type__c)+Getqueuemember.r(cs.Service_Type__c)+Getqueuemember.r(cs.Ticket_Type2__c)+ '<br/>Item: '+Getqueuemember.r(cs.Ticket_Item__c)+Getqueuemember.r(cs.Service_Item__c)+Getqueuemember.r(cs.Ticket_Item2__c)+ '<br/>Ticket Source: '+Getqueuemember.r(cs.Case_Source__c)+'<br/><br/><br/>Building: '+Getqueuemember.r(cs.building__c)+'<br/>Room: '+Getqueuemember.r(cs.Room_Number__c)+'<br/>Area Description: '+Getqueuemember.r(cs.Area_description__c)+ '<br/><br/><br/>Click the appropriate link below to view the ticket directly:<br/><br/>Partner Portal Users: <a href='+baseUrl+'/'+cs.id+'>'+baseUrl+'/'+cs.id+'</a><br/>BlackbeltHelp (Community Users): <a href='+Getqueuemember.getcommunityurl(cs.AccountId)+cs.id+ '>'+Getqueuemember.getcommunityurl(cs.AccountId)+cs.id+'</a><br/><br/>Description:'+cs.Description+'<br/><br/>Internal Notes: '+Getqueuemember.r(cs.Internal_Notes__c)); semail.setFileAttachments(fileAttachments); semail.setWhatId(cs.id); Messaging.sendEmail(new Messaging.SingleEmailMessage[] {semail}); } catch(exception e) {} } } } }
- devloper sfdc
- February 05, 2020
- Like
- 0
how to parse this string using map
How to parse json string
{"ticket":{"item": 4, "change": "40", "limit": 400}}
Please help
{"ticket":{"item": 4, "change": "40", "limit": 400}}
Please help
- devloper sfdc
- August 07, 2019
- Like
- 0
how to write test class for this apex class
Hello All ,
I need test class for this code please help me i am not able to create test class for this code.
I need test class for this code please help me i am not able to create test class for this code.
public class BBH_Survey { public String Survey_res {get;set;} public String UpdateSurvey_res {get;set;} public Survey_Question__c ques_id{get;set;} Public String CasId; Public String Survey_comments {get;set;} public boolean flag{get;set;} public list<BBH_Surveys__c> lstbbhsury; Public New_Surveys__c surveyName {get;set;} public String modifySurvey{get;set;} public string surveyId; public String imageURL{get;set;} public String modiFiResponce {get;set;} public BBH_Survey(apexPages.StandardController std) { Survey_comments=''; flag=false; CasId=ApexPages.currentPage().getParameters().get('caId'); surveyId = Apexpages.currentPage().getParameters().get('id'); // contactId = Apexpages.currentPage().getParameters().get('cId'); lstbbhsury=[select id from BBH_Surveys__c where CaseId__c =:CasId]; List<New_Surveys__c> schoolsurvey =[select School_URL__c,School_Logo__c from New_Surveys__c where id=:surveyId]; imageURL='/servlet/servlet.FileDownload?file='+schoolsurvey[0].School_Logo__c; //imageURL='/servlet/servlet.FileDownload?file=01523000000NUuc'; } Public PageReference survey_1(){ if(lstbbhsury.size()>0) { PageReference Checksuvey = page.SurveyAlreadyFillAndUpdate; Checksuvey.setRedirect(true); return Checksuvey; }else { try{ List<case> lstCase=[select id,status ,Survey_fill__c from case where id =:CasId]; List<New_Surveys__c> schoolsurvey =[select School_URL__c,School_Logo__c from New_Surveys__c where id=:surveyId]; // PageReference myVFPage = page.Survey_saved; string url=schoolsurvey[0].School_URL__c; PageReference myVFPage = new PageReference(url); BBH_Surveys__c bbh=new BBH_Surveys__c(); bbh.CaseId__c=lstCase[0].id; bbh.Survey_Response__c= '1'; bbh.Surveys_Name__c=surveyId; bbh.Survey_Comments__c =Survey_comments; insert bbh; myVFPage.setRedirect(true); return myVFPage; } catch(Exception e) { PageReference myVFPage1 =page.Survey_Permission_Required; myVFPage1.setRedirect(true); return myVFPage1; } } } }
- devloper sfdc
- June 18, 2019
- Like
- 0
how to build site url
Hi Team
I want to create Survey link . Which need two object id in url first is Case Id and second is Survey__c Id . Please suggest me how to do.
My Site Link is
http://partialcpy-ceai.cs28.force.com/bbhsurvey
and whenever add case id it is working fine
http://partialcpy-ceai.cs28.force.com/bbhsurvey?Id=5000m000004y2Hd
but i want to pass custom object survey__c Id.
i want to this type url
http://partialcpy-ceai.cs28.force.com/bbhsurvey?Id=CaseID?surveyID=SurveyID
Please help me.
I want to create Survey link . Which need two object id in url first is Case Id and second is Survey__c Id . Please suggest me how to do.
My Site Link is
http://partialcpy-ceai.cs28.force.com/bbhsurvey
and whenever add case id it is working fine
http://partialcpy-ceai.cs28.force.com/bbhsurvey?Id=5000m000004y2Hd
but i want to pass custom object survey__c Id.
i want to this type url
http://partialcpy-ceai.cs28.force.com/bbhsurvey?Id=CaseID?surveyID=SurveyID
Please help me.
- devloper sfdc
- June 10, 2019
- Like
- 0
Action Function Not working please help
public class BBH_Survey { public String Survey_res {get;set;} Public BBH_Survey() { CasId='50023000001pb1w'; } Public static void survey_1(){ List<case> lstCase=[select id,status ,Survey_fill__c from case where id =:CasId]; BBH_Surveys__c bbh=new BBH_Surveys__c(); bbh.CaseId__c=lstCase[0].id; bbh.Survey_Response__c= '1'; insert bbh; } } <apex:page controller="BBH_Survey" sidebar="false" > <apex:form > <script> function bbh_survey_1() { survey_1(); } </script> <apex:actionFunction name="survey_1" action="{!survey_1}"/> <apex:commandButton value="1" onclick="bbh_survey_1();" styleClass="btn1" /> </apex:form> <apex:page>
Hello All,
My Action function is not working please help me.
Regards
Sebastian
- devloper sfdc
- May 13, 2019
- Like
- 0
Json String Parse
{ "result": [ { "parent": "", "made_sla": "true", "caused_by": "", "watch_list": "", "upon_reject": "cancel", "sys_updated_on": "2019-05-09 15:36:38", "child_incidents": "0", "hold_reason": "", "approval_history": "", "number": "INC0000060", "resolved_by": { "link": "https://dev59401.service-now.com/api/now/table/sys_user/5137153cc611227c000bbd1bd8cd2007", "value": "5137153cc611227c000bbd1bd8cd2007" }, "sys_updated_by": "admin", "opened_by": { "link": "https://dev59401.service-now.com/api/now/table/sys_user/681ccaf9c0a8016400b98a06818d57c7", "value": "681ccaf9c0a8016400b98a06818d57c7" }, "user_input": "", "sys_created_on": "2016-12-12 15:19:57", "sys_domain": { "link": "https://dev59401.service-now.com/api/now/table/sys_user_group/global", "value": "global" }, "state": "7", "sys_created_by": "employee", "knowledge": "false", "order": "", "calendar_stc": "102197", "closed_at": "2016-12-14 02:46:44", "cmdb_ci": { "link": "https://dev59401.service-now.com/api/now/table/cmdb_ci/109562a3c611227500a7b7ff98cc0dc7", "value": "109562a3c611227500a7b7ff98cc0dc7" }, "delivery_plan": "", "impact": "2", "active": "false", "work_notes_list": "", "business_service": { "link": "https://dev59401.service-now.com/api/now/table/cmdb_ci_service/27d32778c0a8000b00db970eeaa60f16", "value": "27d32778c0a8000b00db970eeaa60f16" }, "priority": "3", "sys_domain_path": "/", "rfc": "", "time_worked": "", "expected_start": "", "opened_at": "2016-12-12 15:19:57", "business_duration": "1970-01-01 08:00:00", "group_list": "", "work_end": "", "caller_id": { "link": "https://dev59401.service-now.com/api/now/table/sys_user/681ccaf9c0a8016400b98a06818d57c7", "value": "681ccaf9c0a8016400b98a06818d57c7" }, "reopened_time": "", "resolved_at": "2016-12-13 21:43:14", "approval_set": "", "subcategory": "email", "work_notes": "", "short_description": "hello this is testing", "close_code": "Solved (Permanently)", "correlation_display": "", "delivery_task": "", "work_start": "", "assignment_group": { "link": "https://dev59401.service-now.com/api/now/table/sys_user_group/287ebd7da9fe198100f92cc8d1d2154e", "value": "287ebd7da9fe198100f92cc8d1d2154e" }, "additional_assignee_list": "", "business_stc": "28800", "description": "this is test for steve", "calendar_duration": "1970-01-02 04:23:17", "close_notes": "This incident is resolved.", "notify": "1", "sys_class_name": "incident", "closed_by": { "link": "https://dev59401.service-now.com/api/now/table/sys_user/681ccaf9c0a8016400b98a06818d57c7", "value": "681ccaf9c0a8016400b98a06818d57c7" }, "follow_up": "", "parent_incident": "", "sys_id": "1c741bd70b2322007518478d83673af3", "contact_type": "self-service", "reopened_by": "", "incident_state": "7", "urgency": "2", "problem_id": "", "company": { "link": "https://dev59401.service-now.com/api/now/table/core_company/31bea3d53790200044e0bfc8bcbe5dec", "value": "31bea3d53790200044e0bfc8bcbe5dec" }, "reassignment_count": "2", "activity_due": "2016-12-13 01:26:36", "assigned_to": { "link": "https://dev59401.service-now.com/api/now/table/sys_user/5137153cc611227c000bbd1bd8cd2007", "value": "5137153cc611227c000bbd1bd8cd2007" }, "severity": "3", "u_account_name": { "link": "https://dev59401.service-now.com/api/now/table/core_company/f66b14e1c611227b0166c3a0df4046ff", "value": "f66b14e1c611227b0166c3a0df4046ff" }, "comments": "", "approval": "not requested", "sla_due": "", "comments_and_work_notes": "", "due_date": "", "sys_mod_count": "22", "u_case_source": "Phone\r\nEmail\r\nWeb", "reopen_count": "0", "sys_tags": "", "u_salesforce_ticket": "00001050", "escalation": "0", "upon_approval": "proceed", "correlation_id": "", "location": "", "category": "inquiry" } ] }Please parse my json String i am working on last one week but still can't get solution please help.
- devloper sfdc
- May 09, 2019
- Like
- 0
why test class is not covering code coverage for all line
Hi All ,
I have cover only 58 percent code covergage for trigger but i want to 100% . Please understand my test code and tell me what the issue .
my apex trigger is .
Test Class is
Regards
Shiv Patel
I have cover only 58 percent code covergage for trigger but i want to 100% . Please understand my test code and tell me what the issue .
my apex trigger is .
trigger Prevent_Escalation_SupportType on Case (before insert,after update) { List<String> LstRecTypeName=new List<String>{'American Sentinel University_Ticket','Limestone_Ticket','CSU_Ticket','Extension_Ticket','Healthcare Learning Innovations_Ticket','LinnBenton_Ticket','Lipscomb_Ticket', 'Reinhardt University_Ticket','UMKC_Ticket','Bridgeport_Ticket','GardnerWebb_Ticket','Joliet_Ticket','Lynchburg_Ticket','LakeMichiganC_Ticket','RogersState_Ticket','SCKans_Ticket','SewardCCC_Ticket','SUShreveport_Ticket','UTSW_Ticket','Benedictine University_Ticket'}; Set<Id>LstRecordTypIds =new Set<Id>(); List<RecordType> lstrecType=[Select id From RecordType where sobjecttype = 'case' and name in:LstRecTypeName]; for(RecordType Rec:lstrecType) { LstRecordTypIds.add(Rec.id); } for(case cs:trigger.new) { if((userinfo.getLastName().contains('BBH') || (userinfo.getLastName().contains('BlackBeltHelp')))) { if(LstRecordTypIds.contains(cs.RecordTypeId)) { if(cs.Support_Type__c==null) { if(cs.Status=='Action - Automated Escalation' ||cs.Status=='Escalated') { cs.addError('Please select a Support type value before escalating the ticket.'); } } else if(cs.Support_Type__c!=null) { if(!(cs.Status=='Action - Automated Escalation' ||cs.Status=='Escalated')) { cs.addError('Please make sure Support type value is blank unless you want to escalate the ticket'); } } } } } }
Test Class is
@isTest public class Prevent_Escalation_SupportTypeTest { @isTest private static void test1(){ Account acc = new Account(Name='LimeStone'); insert acc; Contact con = new Contact(AccountId=acc.Id,LastName='test'); insert con; Trigger_Control__c tc=new Trigger_Control__c(); tc.Enable_CaseCreation_Trigger__c=true; tc.Name='test tc'; insert tc; User u; User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()]; System.runAs (thisUser) { Profile p = [SELECT Id FROM Profile WHERE Name='CH_Tier1-Partner']; u = new User(alias = 'tstwy', email='testmail@tst.com', emailencodingkey='UTF-8', lastname='testL', languagelocalekey='en_US', localesidkey='en_US', profileid = p.Id, ContactId = con.Id, timezonesidkey='America/Los_Angeles', username='testmailxxx@tst.com'); insert u; } List<RecordType> listRecType = [select Id from RecordType where sObjectType = 'Case' And Name = 'Limestone_Ticket']; if(listRecType[0].Id!=null) { System.runAs (u) { Case cs = new Case(RecordTypeId = listRecType[0].Id,AccountId=acc.Id,ContactId=con.Id ); insert cs; } } } }
Regards
Shiv Patel
- devloper sfdc
- March 27, 2019
- Like
- 0
I need to write test code for apex class
Hi All ,
I need to write test class for below code please help me it is very urgent.
public class QueueAssignController{
Public List<SelectOption> QueueList {get;set;}
public List<Group> GroupNameList {get;set;}
Public list<GroupMember> mlist {get;set;}
public String queue {get;set;}
public String queueid {get;set;}
public List<String> selectedUserIds { get; set; }
public List<String> removedUserIds { get; set; }
public String whereClause { get; set; }
public String AccName {get;set;}
private Map<Id, String> availableUsersMap;
private Map<Id, String> selectedUsersMap;
public QueueAssignController(ApexPages.StandardController std) {
initializeCollections();
ID contactId = [Select contactid from User where id =: Userinfo.getUserid()].contactId;
// Pid = [Select ProfileId from User where id =: Userinfo.getUserid()].ProfileId;
String aid = [Select AccountID from Contact where id =: contactid].AccountId;
// String aid=ApexPages.currentPage().getParameters().get('id');
List<String> accName=new List<String>();
account[] a=[select WFSSFriendlyName__c from account where id=:aid limit 1 ];
String wffs=a[0].WFSSFriendlyName__c;
GroupNameList = new List<Group>();
String j='%'+wffs+'%';
GroupNameList = [select g.Id, g.Name from Group g where Type = 'Queue' AND name like:j Order by Name Asc];
QueueList = new List<SelectOption>();
for(Group temp : GroupNameList)
{
queueid = temp.id;
QueueList.add(new SelectOption(temp.Id, temp.Name));
}
if(queue == null){
queue = queueid;
getUsers();
}
system.debug('QueueList++++++'+QueueList);
system.debug('queue ++++++'+queue );
}
public PageReference UpdateList() {
initializeCollections();
getUsers();
return null;
}
public void filterAvailableOptions() {
availableUsersMap = new Map<Id, String>();
selectedUserIds = new List<String>();
string userid =userinfo.getUserId();
user[] uac=[select AccountId from user where id=:userid limit 1];
String likeClause = '%' + whereClause + '%';
for (User u : [SELECT id, name FROM User WHERE name like :likeClause AND Name!='Chatter Expert' AND IsActive = true order by Name Asc]) {
if (!selectedUsersMap.containsKey(u.Id)) {
availableUsersMap.put(u.Id, u.Name);
}
}
}
public void add() {
if (!selectedUserIds.isEmpty()) {
for (String userId : selectedUserIds) {
selectedUsersMap.put(userId, availableUsersMap.get(userId));
availableUsersMap.remove(userId);
}
}
}
public void remove() {
if (!removedUserIds.isEmpty()) {
for (String userId : removedUserIds) {
availableUsersMap.put(userId, selectedUsersMap.get(userId));
selectedUsersMap.remove(userId);
}
}
}
public List<SelectOption> getAvailableUsers() {
List<SelectOption> availableUsers = new List<SelectOption>();
for (Id userId : availableUsersMap.keySet()) {
availableUsers.add(new SelectOption(userId, availableUsersMap.get(userId)));
}
return availableUsers;
}
public List<SelectOption> getSelectedUsers() {
List<SelectOption> selectedUsers = new List<SelectOption>();
for (String userId : selectedUsersMap.keySet()) {
selectedUsers.add(new SelectOption(userId, selectedUsersMap.get(userId)));
}
return selectedUsers;
}
private void initializeCollections() {
selectedUserIds = new List<String>();
removedUserIds = new List<String>();
availableUsersMap = new Map<Id, String>();
selectedUsersMap = new Map<Id, String>();
}
private void getUsers() {
QueueSobject qs = [SELECT QueueId,SobjectType FROM QueueSobject where QueueId=:queue];
list<GroupMember> gms = [SELECT Group.Name,UserOrGroupId FROM GroupMember WHERE Group.Type = 'Queue' AND GroupId =:qs.QueueId];
system.debug(gms);
set<id> gids =new set<id>();
for(GroupMember g:gms){
gids.add(g.UserOrGroupId);
}
String aid=ApexPages.currentPage().getParameters().get('id');
list<user> urs = [SELECT id, Name FROM User where IsActive = true AND id NOT IN:gids AND Name!='Chatter Expert' AND AccountId=:aid order by Name Asc];
system.debug(urs);
for(user u : urs){
availableUsersMap.put(u.Id, u.Name);
}
list<user> urss = [SELECT id, Name FROM User where IsActive = true AND id IN:gids AND Name!='Chatter Expert' order by Name Asc];
system.debug(urs);
for(user ur : urss){
selectedUsersMap.put(ur.Id, ur.Name);
}
}
public PageReference savenew(){
List<GroupMember> groups = new List<GroupMember>();
List<GroupMember> groupss = [select Id from GroupMember where Group.Type = 'Queue' and GroupId =:queue ];
if( !groupss.isEmpty() )
{
delete groupss;
}
if(selectedUsersMap.size() == 0){
ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.Error, 'Please select a user to Add to Queue') );
}
else{
for(id ids:selectedUsersMap.keyset()){
// ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.INFO, 'Added user to Queue'+queue) );
insert new GroupMember( GroupId = queue , UserOrGroupId = ids);
}
}
return null;
}
}
I need to write test class for below code please help me it is very urgent.
public class QueueAssignController{
Public List<SelectOption> QueueList {get;set;}
public List<Group> GroupNameList {get;set;}
Public list<GroupMember> mlist {get;set;}
public String queue {get;set;}
public String queueid {get;set;}
public List<String> selectedUserIds { get; set; }
public List<String> removedUserIds { get; set; }
public String whereClause { get; set; }
public String AccName {get;set;}
private Map<Id, String> availableUsersMap;
private Map<Id, String> selectedUsersMap;
public QueueAssignController(ApexPages.StandardController std) {
initializeCollections();
ID contactId = [Select contactid from User where id =: Userinfo.getUserid()].contactId;
// Pid = [Select ProfileId from User where id =: Userinfo.getUserid()].ProfileId;
String aid = [Select AccountID from Contact where id =: contactid].AccountId;
// String aid=ApexPages.currentPage().getParameters().get('id');
List<String> accName=new List<String>();
account[] a=[select WFSSFriendlyName__c from account where id=:aid limit 1 ];
String wffs=a[0].WFSSFriendlyName__c;
GroupNameList = new List<Group>();
String j='%'+wffs+'%';
GroupNameList = [select g.Id, g.Name from Group g where Type = 'Queue' AND name like:j Order by Name Asc];
QueueList = new List<SelectOption>();
for(Group temp : GroupNameList)
{
queueid = temp.id;
QueueList.add(new SelectOption(temp.Id, temp.Name));
}
if(queue == null){
queue = queueid;
getUsers();
}
system.debug('QueueList++++++'+QueueList);
system.debug('queue ++++++'+queue );
}
public PageReference UpdateList() {
initializeCollections();
getUsers();
return null;
}
public void filterAvailableOptions() {
availableUsersMap = new Map<Id, String>();
selectedUserIds = new List<String>();
string userid =userinfo.getUserId();
user[] uac=[select AccountId from user where id=:userid limit 1];
String likeClause = '%' + whereClause + '%';
for (User u : [SELECT id, name FROM User WHERE name like :likeClause AND Name!='Chatter Expert' AND IsActive = true order by Name Asc]) {
if (!selectedUsersMap.containsKey(u.Id)) {
availableUsersMap.put(u.Id, u.Name);
}
}
}
public void add() {
if (!selectedUserIds.isEmpty()) {
for (String userId : selectedUserIds) {
selectedUsersMap.put(userId, availableUsersMap.get(userId));
availableUsersMap.remove(userId);
}
}
}
public void remove() {
if (!removedUserIds.isEmpty()) {
for (String userId : removedUserIds) {
availableUsersMap.put(userId, selectedUsersMap.get(userId));
selectedUsersMap.remove(userId);
}
}
}
public List<SelectOption> getAvailableUsers() {
List<SelectOption> availableUsers = new List<SelectOption>();
for (Id userId : availableUsersMap.keySet()) {
availableUsers.add(new SelectOption(userId, availableUsersMap.get(userId)));
}
return availableUsers;
}
public List<SelectOption> getSelectedUsers() {
List<SelectOption> selectedUsers = new List<SelectOption>();
for (String userId : selectedUsersMap.keySet()) {
selectedUsers.add(new SelectOption(userId, selectedUsersMap.get(userId)));
}
return selectedUsers;
}
private void initializeCollections() {
selectedUserIds = new List<String>();
removedUserIds = new List<String>();
availableUsersMap = new Map<Id, String>();
selectedUsersMap = new Map<Id, String>();
}
private void getUsers() {
QueueSobject qs = [SELECT QueueId,SobjectType FROM QueueSobject where QueueId=:queue];
list<GroupMember> gms = [SELECT Group.Name,UserOrGroupId FROM GroupMember WHERE Group.Type = 'Queue' AND GroupId =:qs.QueueId];
system.debug(gms);
set<id> gids =new set<id>();
for(GroupMember g:gms){
gids.add(g.UserOrGroupId);
}
String aid=ApexPages.currentPage().getParameters().get('id');
list<user> urs = [SELECT id, Name FROM User where IsActive = true AND id NOT IN:gids AND Name!='Chatter Expert' AND AccountId=:aid order by Name Asc];
system.debug(urs);
for(user u : urs){
availableUsersMap.put(u.Id, u.Name);
}
list<user> urss = [SELECT id, Name FROM User where IsActive = true AND id IN:gids AND Name!='Chatter Expert' order by Name Asc];
system.debug(urs);
for(user ur : urss){
selectedUsersMap.put(ur.Id, ur.Name);
}
}
public PageReference savenew(){
List<GroupMember> groups = new List<GroupMember>();
List<GroupMember> groupss = [select Id from GroupMember where Group.Type = 'Queue' and GroupId =:queue ];
if( !groupss.isEmpty() )
{
delete groupss;
}
if(selectedUsersMap.size() == 0){
ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.Error, 'Please select a user to Add to Queue') );
}
else{
for(id ids:selectedUsersMap.keyset()){
// ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.INFO, 'Added user to Queue'+queue) );
insert new GroupMember( GroupId = queue , UserOrGroupId = ids);
}
}
return null;
}
}
- devloper sfdc
- January 17, 2019
- Like
- 0
I need to write test class for apex class
Hi All,
I need to write test class for apex class my code is here-
public class CommenttoEmail {
public String Commentbody {get;set;}
public String subject {get;set;}
public String Set_to{get;set;}
Public String Set_bcc{get;set;}
public String Set_cc{get;set;}
public List<String> SetTo {get;set;}
public List<String> SetCC {get;set;}
public List<String> SetBCC{get;set;}
Public String CaseId {get;set;}
public String Selec {get;set;}
public List<String> liststatus {get;set;}
public boolean flag {set;get;}
public string Str2;
public String test;
Public List<string> listall {get;set;}
public Attachment attachment {
get {
if (attachment == null)
attachment = new Attachment();
return attachment;
}
set;
}
public CommenttoEmail(apexpages.StandardController std)
{
liststatus=new List<string>{'New','Working','Escalated','Closed Successful'};
flag=false;
CaseId=ApexPages.CurrentPage().getParameters().get('Id');
listall=new List<String>();
SetTo=new List<String>{};
SetCC=new List<String>{};
SetBCC=new List<String>{};
}
public void senttoEmail()
{
Case cse = [select id ,CaseNumber ,Status,ContactEmail,subject from case where id=:caseId];
SetTo=Set_To.split(',');
}
public void bccEmail()
{
SetBCC=Set_bcc.split(',');
}
public void ccEmail()
{
SetCC=Set_cc.split(',');
}
public void ss()
{
senttoEmail();
bccEmail();
ccEmail();
}
public void attachemail()
{
listall.addAll(SetTo);
listall.addAll(SetBCC);
listall.addAll(SetCC);
}
public pagereference createCaseComment(){
ss();
upload();
attachemail();
sendingEmail();
ChangeStatus();
Case cse = [select id ,CaseNumber ,Status, Contact.name,Account.name,subject from case where id=:caseId];
String ss=string.join(listall, ',');
String Str1='\n\n';
String Str0='[Recipients:' +ss+']';
String Str3=cse.Contact.name+',\n\n';
String Reg='\n\n\n Sincerely,\n'+cse.Contact.name+'\n'+cse.Account.name;
Str2=Str0+Str1+Str3+Commentbody+Reg;
CaseComment cc = new CaseComment(ParentId = cse.Id,CommentBody = str2 , IsPublished=true);
insert cc;
pagereference pg =new pagereference('/'+CaseId);
return pg;
}
public PageReference sendingEmail()
{
upload();
Case cse = [select id ,CaseNumber ,Status, Contact.name,Account.name,subject from case where id=:caseId];
String ss=string.join(listall, ',');
String Str3=cse.Contact.name+',\n\n';
String Reg='\n\n\n Sincerely,\n'+cse.Contact.name+'\n'+cse.Account.name;
Str2=Str3+Commentbody+Reg;
List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
for (Attachment a : [select Name, Body, BodyLength from Attachment where ParentId = :caseId]){
Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
efa.setFileName(a.Name);
efa.setBody(a.Body);
fileAttachments.add(efa);
}
try{
Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage();
semail.setToAddresses(SetTo);
semail.setBccAddresses(SetBCC);
semail.setCcAddresses(SetCC);
semail.setSubject(cse.Subject);
semail.setPlainTextBody(Str2);
semail.setFileAttachments(fileAttachments);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {semail});
}catch(exception e)
{}
return null;
}
public pagereference redirectCasePage()
{
CaseId=ApexPages.CurrentPage().getParameters().get('Id');
pagereference pg =new pagereference('/'+CaseId);
return pg;
}
public void ChangeStatus()
{
List<Case> cse = [select id ,CaseNumber ,Status,subject from case where id=:caseId];
for(Case c:cse){
if(selec=='New')
{
c.Status='New';
}
if(selec=='Working')
{
c.Status='Working';
}
if(selec=='Escalated')
{
c.Status='Escalated';
}
if(selec=='Closed successful')
{
c.Status='Closed successful';
}
update c;
}
}
public List<SelectOption> getCaseStatus()
{
List<SelectOption> optlist=new List<SelectOption>();
Case cse = [select id ,CaseNumber ,Status,subject from case where id=:caseId];
optlist.add(new SelectOption(cse.Status,cse.Status));
for(String s:liststatus)
{
optlist.add(new SelectOption(s,s));
}
return optlist;
}
public PageReference upload() {
attachment.OwnerId = UserInfo.getUserId();
attachment.ParentId = CaseId;
attachment.IsPrivate = true;
attachment.ContentType = 'image/jpeg';
try {
insert attachment;
} catch (DMLException e) {
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading attachment'));
return null;
} finally {
attachment = new Attachment();
}
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Attachment uploaded successfully'));
return null;
}
}
I need to write test class for apex class my code is here-
public class CommenttoEmail {
public String Commentbody {get;set;}
public String subject {get;set;}
public String Set_to{get;set;}
Public String Set_bcc{get;set;}
public String Set_cc{get;set;}
public List<String> SetTo {get;set;}
public List<String> SetCC {get;set;}
public List<String> SetBCC{get;set;}
Public String CaseId {get;set;}
public String Selec {get;set;}
public List<String> liststatus {get;set;}
public boolean flag {set;get;}
public string Str2;
public String test;
Public List<string> listall {get;set;}
public Attachment attachment {
get {
if (attachment == null)
attachment = new Attachment();
return attachment;
}
set;
}
public CommenttoEmail(apexpages.StandardController std)
{
liststatus=new List<string>{'New','Working','Escalated','Closed Successful'};
flag=false;
CaseId=ApexPages.CurrentPage().getParameters().get('Id');
listall=new List<String>();
SetTo=new List<String>{};
SetCC=new List<String>{};
SetBCC=new List<String>{};
}
public void senttoEmail()
{
Case cse = [select id ,CaseNumber ,Status,ContactEmail,subject from case where id=:caseId];
SetTo=Set_To.split(',');
}
public void bccEmail()
{
SetBCC=Set_bcc.split(',');
}
public void ccEmail()
{
SetCC=Set_cc.split(',');
}
public void ss()
{
senttoEmail();
bccEmail();
ccEmail();
}
public void attachemail()
{
listall.addAll(SetTo);
listall.addAll(SetBCC);
listall.addAll(SetCC);
}
public pagereference createCaseComment(){
ss();
upload();
attachemail();
sendingEmail();
ChangeStatus();
Case cse = [select id ,CaseNumber ,Status, Contact.name,Account.name,subject from case where id=:caseId];
String ss=string.join(listall, ',');
String Str1='\n\n';
String Str0='[Recipients:' +ss+']';
String Str3=cse.Contact.name+',\n\n';
String Reg='\n\n\n Sincerely,\n'+cse.Contact.name+'\n'+cse.Account.name;
Str2=Str0+Str1+Str3+Commentbody+Reg;
CaseComment cc = new CaseComment(ParentId = cse.Id,CommentBody = str2 , IsPublished=true);
insert cc;
pagereference pg =new pagereference('/'+CaseId);
return pg;
}
public PageReference sendingEmail()
{
upload();
Case cse = [select id ,CaseNumber ,Status, Contact.name,Account.name,subject from case where id=:caseId];
String ss=string.join(listall, ',');
String Str3=cse.Contact.name+',\n\n';
String Reg='\n\n\n Sincerely,\n'+cse.Contact.name+'\n'+cse.Account.name;
Str2=Str3+Commentbody+Reg;
List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
for (Attachment a : [select Name, Body, BodyLength from Attachment where ParentId = :caseId]){
Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
efa.setFileName(a.Name);
efa.setBody(a.Body);
fileAttachments.add(efa);
}
try{
Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage();
semail.setToAddresses(SetTo);
semail.setBccAddresses(SetBCC);
semail.setCcAddresses(SetCC);
semail.setSubject(cse.Subject);
semail.setPlainTextBody(Str2);
semail.setFileAttachments(fileAttachments);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {semail});
}catch(exception e)
{}
return null;
}
public pagereference redirectCasePage()
{
CaseId=ApexPages.CurrentPage().getParameters().get('Id');
pagereference pg =new pagereference('/'+CaseId);
return pg;
}
public void ChangeStatus()
{
List<Case> cse = [select id ,CaseNumber ,Status,subject from case where id=:caseId];
for(Case c:cse){
if(selec=='New')
{
c.Status='New';
}
if(selec=='Working')
{
c.Status='Working';
}
if(selec=='Escalated')
{
c.Status='Escalated';
}
if(selec=='Closed successful')
{
c.Status='Closed successful';
}
update c;
}
}
public List<SelectOption> getCaseStatus()
{
List<SelectOption> optlist=new List<SelectOption>();
Case cse = [select id ,CaseNumber ,Status,subject from case where id=:caseId];
optlist.add(new SelectOption(cse.Status,cse.Status));
for(String s:liststatus)
{
optlist.add(new SelectOption(s,s));
}
return optlist;
}
public PageReference upload() {
attachment.OwnerId = UserInfo.getUserId();
attachment.ParentId = CaseId;
attachment.IsPrivate = true;
attachment.ContentType = 'image/jpeg';
try {
insert attachment;
} catch (DMLException e) {
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading attachment'));
return null;
} finally {
attachment = new Attachment();
}
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Attachment uploaded successfully'));
return null;
}
}
- devloper sfdc
- November 16, 2018
- Like
- 0
I need to write test class for casecomment trigger
trigger UpdLstMdfyDtFrmComt on CaseComment (before insert , before update) {
Map<Id, Case> cases = new Map<Id, Case>();
DateTime dT = System.now();
Date myDate = date.newinstance(dT.year(), dT.month(), dT.day());
for(CaseComment record:Trigger.new)
{
if (record.ParentId != null)
{
cases.put(record.ParentId, new Case(Id=record.ParentId, LastModifyDateCmtCas__c=myDate));
}
}
update cases.values();
}
Map<Id, Case> cases = new Map<Id, Case>();
DateTime dT = System.now();
Date myDate = date.newinstance(dT.year(), dT.month(), dT.day());
for(CaseComment record:Trigger.new)
{
if (record.ParentId != null)
{
cases.put(record.ParentId, new Case(Id=record.ParentId, LastModifyDateCmtCas__c=myDate));
}
}
update cases.values();
}
- devloper sfdc
- October 16, 2018
- Like
- 0
Error Display "Attempt to de-reference a null object"
Hello All ,
I am getting error Message "Attempt to de-reference a null object" when we run "permissionSett()" this method .
My Apex code is here please help me .
public class DeepcloneUser {
Public String fName {set;get;}
Public String lName {set;get;}
Public static String eMail {set;get;}
public static Id conId {set;get;}
Public Contact c;
Public static User u;
public Static User[] uid;
Public set<Id> CloneId;
Public static Set<Id> permiId;
public static PermissionSetAssignment[] Listperm;
public static list<PermissionSetAssignment> Listpermission;
public DeepcloneUser(ApexPages.StandardController stdController) {
// conId=apexpages.currentpage().getparameters().get('id');
CloneId=new Set<Id>();
permiId=new Set<Id>();
Listpermission=new List<PermissionSetAssignment>();
}
@future
Public static void CreateUser(String fname,String LName,String Email,Id Cid,String Pid ,String nickname)
{
u=new user();
// String alias = 'aaa';
u.FirstName=fname;
u.LastName=lName;
u.Email=eMail;
u.Username=email;
u.ProfileId=Pid;
u.ContactId=cid;
//u.CommunityNickname=attributes.get('u.CommunityNickname');
u.CommunityNickname=nickname;
u.EmailEncodingKey='UTF-8';
u.LocaleSidKey='en_US';
u.Alias='snsa';
u.LanguageLocaleKey='en_US';
u.TimeZoneSidKey='GMT';
insert u;
}
@InvocableMethod
public static void GetDetail()
{
conId=apexpages.currentpage().getparameters().get('id');
Contact[] co=[select id,firstName,Community_Nickname__c, Clone_Contact__c,LastName, Email from contact where id=:conId limit 1];
//String cCid=co[0].id;
String ffname=co[0].firstName;
String llname=co[0].lastName;
String eemail=co[0].email;
String nnickname=co[0].Community_Nickname__c;
// String pfid='00ed00000019frTAAQ';
String Clone=co[0].Clone_Contact__c;
uid=[select id, profileid from user where contactid=:Clone limit 1];
String pfid=uid[0].profileid;
CreateUser(ffname,ffname,eemail,conId,pfid,nnickname);
//Listperm=[SELECT Id FROM PermissionSetAssignment WHERE AssigneeId=:uid[0].id];
}
public void permissionSett()
{
List<PermissionSetAssignment> lstp=new list<PermissionSetAssignment>();
List<PermissionSetAssignment> lstcloUserpert=[SELECT Id, PermissionSet.Name,AssigneeId
FROM PermissionSetAssignment
WHERE AssigneeId = :uid[0].id];
conId=apexpages.currentpage().getparameters().get('id');
User Userid=[select id from user where contactId=:ConId limit 1];
for(PermissionSetAssignment p:lstcloUserpert)
{
PermissionSetAssignment pmr=new PermissionSetAssignment();
pmr.AssigneeId=userId.id;
pmr.PermissionSetId=p.id;
lstp.add(pmr);
}
upsert lstp;
}
}
I am getting error Message "Attempt to de-reference a null object" when we run "permissionSett()" this method .
My Apex code is here please help me .
public class DeepcloneUser {
Public String fName {set;get;}
Public String lName {set;get;}
Public static String eMail {set;get;}
public static Id conId {set;get;}
Public Contact c;
Public static User u;
public Static User[] uid;
Public set<Id> CloneId;
Public static Set<Id> permiId;
public static PermissionSetAssignment[] Listperm;
public static list<PermissionSetAssignment> Listpermission;
public DeepcloneUser(ApexPages.StandardController stdController) {
// conId=apexpages.currentpage().getparameters().get('id');
CloneId=new Set<Id>();
permiId=new Set<Id>();
Listpermission=new List<PermissionSetAssignment>();
}
@future
Public static void CreateUser(String fname,String LName,String Email,Id Cid,String Pid ,String nickname)
{
u=new user();
// String alias = 'aaa';
u.FirstName=fname;
u.LastName=lName;
u.Email=eMail;
u.Username=email;
u.ProfileId=Pid;
u.ContactId=cid;
//u.CommunityNickname=attributes.get('u.CommunityNickname');
u.CommunityNickname=nickname;
u.EmailEncodingKey='UTF-8';
u.LocaleSidKey='en_US';
u.Alias='snsa';
u.LanguageLocaleKey='en_US';
u.TimeZoneSidKey='GMT';
insert u;
}
@InvocableMethod
public static void GetDetail()
{
conId=apexpages.currentpage().getparameters().get('id');
Contact[] co=[select id,firstName,Community_Nickname__c, Clone_Contact__c,LastName, Email from contact where id=:conId limit 1];
//String cCid=co[0].id;
String ffname=co[0].firstName;
String llname=co[0].lastName;
String eemail=co[0].email;
String nnickname=co[0].Community_Nickname__c;
// String pfid='00ed00000019frTAAQ';
String Clone=co[0].Clone_Contact__c;
uid=[select id, profileid from user where contactid=:Clone limit 1];
String pfid=uid[0].profileid;
CreateUser(ffname,ffname,eemail,conId,pfid,nnickname);
//Listperm=[SELECT Id FROM PermissionSetAssignment WHERE AssigneeId=:uid[0].id];
}
public void permissionSett()
{
List<PermissionSetAssignment> lstp=new list<PermissionSetAssignment>();
List<PermissionSetAssignment> lstcloUserpert=[SELECT Id, PermissionSet.Name,AssigneeId
FROM PermissionSetAssignment
WHERE AssigneeId = :uid[0].id];
conId=apexpages.currentpage().getparameters().get('id');
User Userid=[select id from user where contactId=:ConId limit 1];
for(PermissionSetAssignment p:lstcloUserpert)
{
PermissionSetAssignment pmr=new PermissionSetAssignment();
pmr.AssigneeId=userId.id;
pmr.PermissionSetId=p.id;
lstp.add(pmr);
}
upsert lstp;
}
}
- devloper sfdc
- September 06, 2018
- Like
- 0
DML Operation Error in SamljitHandler for community user
I am getting DML operation error in SamlJitHandler
Hi All,
I am getting DML opration error In SamlJitHandler During parameter passing from identity provider (3rd Party) .
include parameter here(UserName,AccountOwner,ContactLastName,ContactFirstName,ContactEmail,userLastName,userFirstName,UserFederationidentyfier,AccountNumber,userCommunityNickName)
I am using Controller is
global class StandardUserHandler implements Auth.SamlJitHandler {
private class JitException extends Exception{}
private void handleUser(boolean create, User u, Map<String, String> attributes, String federationIdentifier, boolean isStandard)
{
if(create && attributes.containsKey('User.Username'))
{
u.Username = attributes.get('User.Username');
}
if(create)
{
if(attributes.containsKey('User.FederationIdentifier'))
{
u.FederationIdentifier = attributes.get('User.FederationIdentifier');
} else
{
u.FederationIdentifier = federationIdentifier;
}
}
if(attributes.containsKey('User.ProfileId'))
{
String profileId = attributes.get('User.ProfileId');
Profile p = [SELECT Id FROM Profile WHERE Id=:profileId]; u.ProfileId = p.Id;
}
if(attributes.containsKey('User.UserRoleId'))
{
String userRole = attributes.get('User.UserRoleId');
UserRole r = [SELECT Id FROM UserRole WHERE Id=:userRole];
u.UserRoleId = r.Id; } if(attributes.containsKey('User.Phone'))
{
u.Phone = attributes.get('User.Phone');
}
if(attributes.containsKey('User.Email'))
{
u.Email = attributes.get('User.Email');
}
if(!create)
{
update(u);
}
}
private void handleJit(boolean create, User u, Id samlSsoProviderId, Id communityId, Id portalId, String federationIdentifier, Map<String, String> attributes, String assertion) {
if(communityId != null || portalId != null)
{
String account = handleAccount(create, u, attributes); handleContact(create, account, u, attributes); handleUser(create, u, attributes, federationIdentifier, false);
} else
{
handleUser(create, u, attributes, federationIdentifier, true);
}
}
global User createUser(Id samlSsoProviderId, Id communityId, Id portalId, String federationIdentifier, Map<String, String> attributes, String assertion) {
User u = new User(); handleJit(true, u, samlSsoProviderId, communityId, portalId, federationIdentifier, attributes, assertion); return u;
}
global void updateUser(Id userId, Id samlSsoProviderId, Id communityId, Id portalId, String federationIdentifier, Map<String, String> attributes, String assertion)
{
User u = [SELECT Id FROM User WHERE Id=:userId]; handleJit(false, u, samlSsoProviderId, communityId, portalId, federationIdentifier, attributes, assertion);
}
}
Hi All,
I am getting DML opration error In SamlJitHandler During parameter passing from identity provider (3rd Party) .
include parameter here(UserName,AccountOwner,ContactLastName,ContactFirstName,ContactEmail,userLastName,userFirstName,UserFederationidentyfier,AccountNumber,userCommunityNickName)
I am using Controller is
global class StandardUserHandler implements Auth.SamlJitHandler {
private class JitException extends Exception{}
private void handleUser(boolean create, User u, Map<String, String> attributes, String federationIdentifier, boolean isStandard)
{
if(create && attributes.containsKey('User.Username'))
{
u.Username = attributes.get('User.Username');
}
if(create)
{
if(attributes.containsKey('User.FederationIdentifier'))
{
u.FederationIdentifier = attributes.get('User.FederationIdentifier');
} else
{
u.FederationIdentifier = federationIdentifier;
}
}
if(attributes.containsKey('User.ProfileId'))
{
String profileId = attributes.get('User.ProfileId');
Profile p = [SELECT Id FROM Profile WHERE Id=:profileId]; u.ProfileId = p.Id;
}
if(attributes.containsKey('User.UserRoleId'))
{
String userRole = attributes.get('User.UserRoleId');
UserRole r = [SELECT Id FROM UserRole WHERE Id=:userRole];
u.UserRoleId = r.Id; } if(attributes.containsKey('User.Phone'))
{
u.Phone = attributes.get('User.Phone');
}
if(attributes.containsKey('User.Email'))
{
u.Email = attributes.get('User.Email');
}
if(!create)
{
update(u);
}
}
private void handleJit(boolean create, User u, Id samlSsoProviderId, Id communityId, Id portalId, String federationIdentifier, Map<String, String> attributes, String assertion) {
if(communityId != null || portalId != null)
{
String account = handleAccount(create, u, attributes); handleContact(create, account, u, attributes); handleUser(create, u, attributes, federationIdentifier, false);
} else
{
handleUser(create, u, attributes, federationIdentifier, true);
}
}
global User createUser(Id samlSsoProviderId, Id communityId, Id portalId, String federationIdentifier, Map<String, String> attributes, String assertion) {
User u = new User(); handleJit(true, u, samlSsoProviderId, communityId, portalId, federationIdentifier, attributes, assertion); return u;
}
global void updateUser(Id userId, Id samlSsoProviderId, Id communityId, Id portalId, String federationIdentifier, Map<String, String> attributes, String assertion)
{
User u = [SELECT Id FROM User WHERE Id=:userId]; handleJit(false, u, samlSsoProviderId, communityId, portalId, federationIdentifier, attributes, assertion);
}
}
- devloper sfdc
- July 05, 2018
- Like
- 0
I am getting DML operation error in SamlJitHandler
Hi All,
I am getting DML opration error In SamlJitHandler During parameter passing from identity provider (3rd Party) .
include parameter here(UserName,AccountOwner,ContactLastName,ContactFirstName,ContactEmail,userLastName,userFirstName,UserFederationidentyfier,AccountNumber,userCommunityNickName)
I am using Controller is
global class StandardUserHandler implements Auth.SamlJitHandler {
private class JitException extends Exception{}
private void handleUser(boolean create, User u, Map<String, String> attributes, String federationIdentifier, boolean isStandard)
{
if(create && attributes.containsKey('User.Username'))
{
u.Username = attributes.get('User.Username');
}
if(create)
{
if(attributes.containsKey('User.FederationIdentifier'))
{
u.FederationIdentifier = attributes.get('User.FederationIdentifier');
} else
{
u.FederationIdentifier = federationIdentifier;
}
}
if(attributes.containsKey('User.ProfileId'))
{
String profileId = attributes.get('User.ProfileId');
Profile p = [SELECT Id FROM Profile WHERE Id=:profileId]; u.ProfileId = p.Id;
}
if(attributes.containsKey('User.UserRoleId'))
{
String userRole = attributes.get('User.UserRoleId');
UserRole r = [SELECT Id FROM UserRole WHERE Id=:userRole];
u.UserRoleId = r.Id; } if(attributes.containsKey('User.Phone'))
{
u.Phone = attributes.get('User.Phone');
}
if(attributes.containsKey('User.Email'))
{
u.Email = attributes.get('User.Email');
}
if(!create)
{
update(u);
}
}
private void handleJit(boolean create, User u, Id samlSsoProviderId, Id communityId, Id portalId, String federationIdentifier, Map<String, String> attributes, String assertion) {
if(communityId != null || portalId != null)
{
String account = handleAccount(create, u, attributes); handleContact(create, account, u, attributes); handleUser(create, u, attributes, federationIdentifier, false);
} else
{
handleUser(create, u, attributes, federationIdentifier, true);
}
}
global User createUser(Id samlSsoProviderId, Id communityId, Id portalId, String federationIdentifier, Map<String, String> attributes, String assertion) {
User u = new User(); handleJit(true, u, samlSsoProviderId, communityId, portalId, federationIdentifier, attributes, assertion); return u;
}
global void updateUser(Id userId, Id samlSsoProviderId, Id communityId, Id portalId, String federationIdentifier, Map<String, String> attributes, String assertion)
{
User u = [SELECT Id FROM User WHERE Id=:userId]; handleJit(false, u, samlSsoProviderId, communityId, portalId, federationIdentifier, attributes, assertion);
}
}
Please suggest what to be changes needed in this controller ;
I am getting DML opration error In SamlJitHandler During parameter passing from identity provider (3rd Party) .
include parameter here(UserName,AccountOwner,ContactLastName,ContactFirstName,ContactEmail,userLastName,userFirstName,UserFederationidentyfier,AccountNumber,userCommunityNickName)
I am using Controller is
global class StandardUserHandler implements Auth.SamlJitHandler {
private class JitException extends Exception{}
private void handleUser(boolean create, User u, Map<String, String> attributes, String federationIdentifier, boolean isStandard)
{
if(create && attributes.containsKey('User.Username'))
{
u.Username = attributes.get('User.Username');
}
if(create)
{
if(attributes.containsKey('User.FederationIdentifier'))
{
u.FederationIdentifier = attributes.get('User.FederationIdentifier');
} else
{
u.FederationIdentifier = federationIdentifier;
}
}
if(attributes.containsKey('User.ProfileId'))
{
String profileId = attributes.get('User.ProfileId');
Profile p = [SELECT Id FROM Profile WHERE Id=:profileId]; u.ProfileId = p.Id;
}
if(attributes.containsKey('User.UserRoleId'))
{
String userRole = attributes.get('User.UserRoleId');
UserRole r = [SELECT Id FROM UserRole WHERE Id=:userRole];
u.UserRoleId = r.Id; } if(attributes.containsKey('User.Phone'))
{
u.Phone = attributes.get('User.Phone');
}
if(attributes.containsKey('User.Email'))
{
u.Email = attributes.get('User.Email');
}
if(!create)
{
update(u);
}
}
private void handleJit(boolean create, User u, Id samlSsoProviderId, Id communityId, Id portalId, String federationIdentifier, Map<String, String> attributes, String assertion) {
if(communityId != null || portalId != null)
{
String account = handleAccount(create, u, attributes); handleContact(create, account, u, attributes); handleUser(create, u, attributes, federationIdentifier, false);
} else
{
handleUser(create, u, attributes, federationIdentifier, true);
}
}
global User createUser(Id samlSsoProviderId, Id communityId, Id portalId, String federationIdentifier, Map<String, String> attributes, String assertion) {
User u = new User(); handleJit(true, u, samlSsoProviderId, communityId, portalId, federationIdentifier, attributes, assertion); return u;
}
global void updateUser(Id userId, Id samlSsoProviderId, Id communityId, Id portalId, String federationIdentifier, Map<String, String> attributes, String assertion)
{
User u = [SELECT Id FROM User WHERE Id=:userId]; handleJit(false, u, samlSsoProviderId, communityId, portalId, federationIdentifier, attributes, assertion);
}
}
Please suggest what to be changes needed in this controller ;
- devloper sfdc
- June 26, 2018
- Like
- 0
Test class running successfully but apex class code coverage None
Hi All
I write test class it is running successfully but apex class code coverage is none .
i am mention class and test class please help me.
public class Case_Automated_Escalation_MidState{
public static void beforeTriggerCall(List<Case> listCase){
for(Case cs : listCase){
String queueName = manageQueueName(cs);
if(UtilityController.mapQueue.containsKey(queueName)){
cs.Status = 'Escalated';
cs.OwnerId = UtilityController.mapQueue.get(queueName);
}
}
}
private static String manageQueueName(Case cs){
String queueName = '';
/*----------------------------------------------------------------------MidState - Media Services-------------------------------------------------------------------------------*/
if(cs.Ticket_Category2__c=='Digital Storefront'||cs.Ticket_Category2__c=='Printing' &&((cs.Ticket_Type2__c=='Troubleshoot (Printing / Imaging)' && (cs.Ticket_Item2__c!='Software / Configuration')) ||(cs.Ticket_Type2__c=='Setup / Configuration (Printing / Imaging)' && (cs.Ticket_Item2__c!='Connecting to an existing printer')))&& cs.Status=='Action - Automated Escalation'){
queueName='MidState - Media Services';
}
/*-------------------------------------------------------------------MidState - Desktop Services---------------------------------------------------------------------------*/
if((cs.Ticket_Category2__c=='Software (Computer)'||cs.Ticket_Category2__c=='Mobile Device - Mid-State Owned'|| cs.Ticket_Category2__c=='Email' && cs.Ticket_Type2__c=='Troubleshoot (Email)' ) && cs.Status=='Action - Automated Escalation'){
queueName='MidState Dsktop Services';
}
if((cs.Ticket_Category2__c=='Computers and Classroom Technology' &&((cs.Ticket_Type2__c=='Install / Configuration' || cs.Ticket_Type2__c=='Troubleshoot')&&(cs.Ticket_Item2__c=='Desktop Computer'||cs.Ticket_Item2__c=='Desktop Monitor'||cs.Ticket_Item2__c=='Wired Mouse'||cs.Ticket_Item2__c=='Wired Keyboard' ))||
(cs.Ticket_Type2__c=='Move/Add/Change (Computer)'&& cs.Ticket_Item2__c=='Hardware')|| cs.Ticket_Type2__c=='Imaging'||cs.Ticket_Type2__c== 'Other')&& cs.Status=='Action - Automated Escalation'){
queueName='MidState Dsktop Services';
}
if(cs.Ticket_Category2__c=='Network' &&(cs.Ticket_Type2__c=='VPN / Remote Access'||cs.Ticket_Type2__c=='Wireless'||cs.Ticket_Type2__c=='Troubleshoot (Network)')
&&(cs.Ticket_Item2__c=='Troubleshoot (Network)' || cs.Ticket_Item2__c=='Setup '||cs.Ticket_Item2__c=='Troubleshoot'||cs.Ticket_Item2__c=='Wireless'||cs.Ticket_Item2__c=='VPN / Remote Access') && cs.Status=='Action - Automated Escalation'){
queueName='MidState Dsktop Services';
}
if((cs.Ticket_Category2__c=='Printing'&& cs.Ticket_Type2__c=='Setup / Configuration (Printing / Imaging)' && cs.Ticket_Item2__c=='Connecting to an existing printer') && cs.Status=='Action - Automated Escalation'){
queueName='MidState Dsktop Services';
}
/*------------------------------------------------------------------------------MidState - Network Services--------------------------------------------------------------------------*/
if(cs.Ticket_Category2__c=='Email' && (cs.Ticket_Type2__c=='Login'||cs.Ticket_Type2__c=='Access / Permissions (MS)'||cs.Ticket_Type2__c=='Setup / Configuration (Email)'||( cs.Ticket_Type2__c=='Troubleshoot (Email)'&& cs.Ticket_Item2__c!='Email - Outlook/365'))&& cs.Status=='Action - Automated Escalation')
{
queueName ='MidState - Network Services';
}
if((cs.Ticket_Category2__c=='ImageNow (Perceptive Content)'||(cs.Ticket_Category2__c=='Outage'&& cs.Ticket_Type2__c=='Email')||(cs.Ticket_Category2__c=='Printing' && cs.Ticket_Type2__c=='Troubleshoot (Printing / Imaging)'&& cs.Ticket_Item2__c=='Software / Configuration')) && cs.Status=='Action - Automated Escalation' ){
queueName ='MidState - Network Services';
}
if(cs.Ticket_Category2__c=='Network'&& (cs.Ticket_Type2__c=='File Maintenance'||cs.Ticket_Type2__c=='Login (Network)'||cs.Ticket_Type2__c=='Other' ||(cs.Ticket_Type2__c=='VPN / Remote Access'&& cs.Ticket_Item2__c=='Setup / Configuration (Network)')||(cs.Ticket_Type2__c=='Setup / Configuration (Network)'&& cs.Ticket_Item2__c=='VPN / Remote Access')
||(cs.Ticket_Type2__c=='Troubleshoot (Network)'&& cs.Ticket_Item2__c=='File Maintainance'))&& cs.Status=='Action - Automated Escalation')
{
queueName ='MidState - Network Services';
}
if((cs.Ticket_Category2__c=='Portal (MidState)' && cs.Ticket_Type2__c=='MyCampus')&& cs.Status=='Action - Automated Escalation')
{
queueName='MidState - Network Services';
}
if((cs.Ticket_Category2__c=='Outage' && cs.Ticket_Type2__c=='MyCampus Portal') && cs.Status=='Action - Automated Escalation')
{
queueName='MidState - Network Services';
}
/*-----------------------------------------------------------------------------MidState - Network Infrastructure-----------------------------------------------------------------*/
if(cs.Ticket_Category2__c=='Network/Services' ||(cs.Ticket_Category2__c=='Outage' && (cs.Ticket_Type2__c=='Power'||cs.Ticket_Type2__c=='Telephone'||(cs.Ticket_Type2__c=='Network'&& (cs.Ticket_Item2__c=='Wired'||cs.Ticket_Item2__c=='Wireless'))))&& cs.Status=='Action - Automated Escalation' )
{
queueName ='MidState - Network Infrastructure';
}
if(cs.Ticket_Category2__c=='Network' && (cs.Ticket_Type2__c=='Setup/ Troubleshoot (Network)' && cs.Ticket_Item2__c=='Network Drops /Installation') && cs.Status=='Action - Automated Escalation')
{
queueName ='MidState - Network Infrastructure';
}
if(cs.Ticket_Category2__c=='Network' && ((cs.Ticket_Type2__c=='Troubleshoot (Network)')&& (cs.Ticket_Item2__c=='Wired'|| cs.Ticket_Item2__c=='Wireless AP /Devices'|| cs.Ticket_Item2__c=='Internet /WILM Connectivity'||
cs.Ticket_Item2__c=='Video Conferencing /LTC/NWTC'|| cs.Ticket_Item2__c=='Video Surveillance /Campus'|| cs.Ticket_Item2__c=='Card Access/Door Schedules/keypads'||
cs.Ticket_Item2__c=='Video Surveillance /Testing Centers'||cs.Ticket_Item2__c=='Digital Display /Digital Marquees' ||cs.Ticket_Item2__c=='Digital Display /Digital Marquees'))&& cs.Status=='Action - Automated Escalation')
{
queueName ='MidState - Network Infrastructure';
}
/*--------------------------------------------------------------------------------MidState - Telephony----------------------------------------------------------------------------*/
if((cs.Ticket_Category2__c=='Phone System'|| cs.Ticket_Category2__c=='Phone System/Services') && cs.Status=='Action - Automated Escalation')
{
queueName='MidState - Telephony';
}
/*-------------------------------------------------------------------MidState - Classroom Instructional Technology------------------------------------------------------------------------------*/
if(cs.Ticket_Category2__c=='Computers and Classroom Technology' && (cs.Ticket_Type2__c=='Classroom EMERGENCY')&& cs.Status=='Action - Automated Escalation')
{
queueName='MidState - Classroom Instructional Tech';
}
if(cs.Ticket_Category2__c=='Computers and Classroom Technology' && ((cs.Ticket_Type2__c=='Install / Configuration'||cs.Ticket_Type2__c=='Troubleshoot') && (cs.Ticket_Item2__c=='Document Camera'||cs.Ticket_Item2__c=='Microphone'||cs.Ticket_Item2__c=='Projector'||cs.Ticket_Item2__c=='Projector Screen'
||cs.Ticket_Item2__c=='Interactive screen/monitor'||cs.Ticket_Item2__c=='Speakers/Amplifier'||cs.Ticket_Item2__c=='Monitor/Television'||cs.Ticket_Item2__c=='Printer'||cs.Ticket_Item2__c=='Telepresence'||cs.Ticket_Item2__c=='AV Conferencing'||cs.Ticket_Item2__c=='Wireless Mouse'||
cs.Ticket_Item2__c=='Wireless Keyboard'||cs.Ticket_Item2__c=='Conferencing camera')) && cs.Status=='Action - Automated Escalation')
{
queueName='MidState - Classroom Instructional Tech';
}
if(cs.Ticket_Category2__c=='Computers and Classroom Technology' && (cs.Ticket_Type2__c=='Troubleshoot' && (cs.Ticket_Item2__c=='Document Camera'||cs.Ticket_Item2__c=='Microphone'||cs.Ticket_Item2__c=='Projector'||cs.Ticket_Item2__c=='Projector Screen'||cs.Ticket_Item2__c=='AV Conferencing'||cs.Ticket_Item2__c=='Wireless Mouse'||cs.Ticket_Item2__c=='Wireless Keyboard'||cs.Ticket_Item2__c=='Conferencing camera')) && cs.Status=='Action - Automated Escalation')
{
queueName='MidState - Classroom Instructional Tech';
}
if(cs.Ticket_Category2__c=='Outage' && cs.Ticket_Type2__c=='Telepresence' && cs.Status=='Action - Automated Escalation')
{
queueName='MidState - Classroom Instructional Tech';
}
/*-----------------------------------------------------------------------MidState - Online Instructional Tech-----------------------------------------------------------------*/
if(cs.Ticket_Category2__c=='Outage' && cs.Ticket_Type2__c=='Blackboard' && cs.Status=='Action - Automated Escalation')
{
queueName='MidState - Online Instructional Tech';
}
if(cs.Ticket_Category2__c=='Blackboard' && (cs.Ticket_Type2__c=='Login'|| cs.Ticket_Type2__c=='Access / Permissions'|| cs.Ticket_Type2__c=='Instructor (LMS)'|| cs.Ticket_Type2__c=='Student (LMS)')&& cs.Status=='Action - Automated Escalation')
{
queueName='MidState - Online Instructional Tech';
}
/*-------------------------------------------------------------------------------------------Misslenius CTI------------------------------------------------------------------*/
if((cs.Ticket_Category2__c=='Network' && (cs.Ticket_Type2__c=='Setup / Configuration (Network)' && cs.Ticket_Item2__c=='VPN / Remote Access')) && cs.Status=='Action - Automated Escalation')
{
queueName ='MidState - Network Services';
}
if(cs.Ticket_Category2__c=='Network' && cs.Ticket_Type2__c=='Setup / Configuration (Network)' && cs.Ticket_Item2__c=='Wireless' && cs.Status=='Action - Automated Escalation')
{
queueName ='MidState Dsktop Services';
}
if(cs.Ticket_Category2__c=='Network' && (cs.Ticket_Type2__c=='Setup / Configuration (Network)' && (cs.Ticket_Item2__c=='Wired' || cs.Ticket_Item2__c=='Wireless AP /Devices')) && cs.Status=='Action - Automated Escalation')
{
queueName ='MidState - Network Infrastructure';
}
/*----------------------------------------------------------------------------MidState - Student Records----------------------------------------------------------------*/
if(((cs.Ticket_Category2__c=='Portal (MidState)' && cs.Ticket_Type2__c=='MyMSTC')|| cs.Ticket_Category2__c== 'Registration'|| (cs.Ticket_Category2__c=='Outage' && cs.Ticket_Type2__c=='MyMSTC (Outage)'))&& cs.Status=='Action - Automated Escalation'){
queueName='MidState - Student Records';
}
return queueName;
}
}
and test class is
@isTest
public class TestCase_Automated_escalation_Midstate {
// test method
@isTest
private static void test(){
/*Group queuename=[select Id from Group where Name = 'MidState - Classroom Instructional Tech' and Type = 'Queue'];*/
// create test account
Account acc = TestUtilityController.getAccount('Mid-State Technical College');
insert acc;
// create test contact
Contact con = TestUtilityController.getContact('Test Last Name','testing@testing.com',acc.Id);
insert con;
// fill utility
UtilityController.fillUtilities();
UtilityController.isUtility = false;
// Create test cases
List<Case> listCase = new List<Case>();
if(UtilityController.caseRecordType.containsKey('Mid-State Technical College_Ticket')){
String recordTypeId = UtilityController.caseRecordType.get('Mid-State Technical College_Ticket').Id;
Case csa = TestUtilityController.getCase(recordTypeId,con.Id,acc.Id);
csa.Status = 'Action - Automated Escalation';
csa.Ticket_Category2__c = 'Digital Storefront';
csa.Ticket_Type2__c = 'Printing';
listCase.add(csa);
Case csa1 = TestUtilityController.getCase(recordTypeId,con.Id,acc.Id);
csa1.Status = 'Action - Automated Escalation';
csa1.Ticket_Category2__c = 'Outage';
csa1.Ticket_Type2__c = 'Blackboard';
listCase.add(csa1);
Case csa2 = TestUtilityController.getCase(recordTypeId,con.Id,acc.Id);
csa2.Status = 'Action - Automated Escalation';
csa2.Ticket_Category2__c = 'Software (Computer)';
csa2.Ticket_Type2__c = 'Troubleshoot (Email)';
listCase.add(csa2);
Case csa3 = TestUtilityController.getCase(recordTypeId,con.Id,acc.Id);
csa3.Status = 'Action - Automated Escalation';
csa3.Ticket_Category2__c = 'Computers and Classroom Technology';
csa3.Ticket_Type2__c = 'Install / Configuration';
csa3.Ticket_Item2__c='Desktop Monitor';
listCase.add(csa3);
Case csa4 = TestUtilityController.getCase(recordTypeId,con.Id,acc.Id);
csa4.Status = 'Action - Automated Escalation';
csa4.Ticket_Category2__c = 'Network';
csa4.Ticket_Type2__c = 'VPN / Remote Access';
csa4.Ticket_Item2__c='Troubleshoot (Network)';
listCase.add(csa4);
Case csa5 = TestUtilityController.getCase(recordTypeId,con.Id,acc.Id);
csa5.Status = 'Action - Automated Escalation';
csa5.Ticket_Category2__c = 'Printing';
csa5.Ticket_Type2__c = 'Setup / Configuration (Printing / Imaging)';
csa5.Ticket_Item2__c= 'Connecting to an existing printer';
listCase.add(csa5);
Case csa6 = TestUtilityController.getCase(recordTypeId,con.Id,acc.Id);
csa6.Status = 'Action - Automated Escalation';
csa6.Ticket_Category2__c = 'Portal';
csa6.Ticket_Type2__c = 'Troubleshoot (Email)';
listCase.add(csa6);
Case csa7 = TestUtilityController.getCase(recordTypeId,con.Id,acc.Id);
csa7.Status = 'Action - Automated Escalation';
csa7.Ticket_Category2__c = 'ImageNow (Perceptive Content)';
csa7.Ticket_Type2__c = 'Email';
listCase.add(csa7);
Case csa8 = TestUtilityController.getCase(recordTypeId,con.Id,acc.Id);
csa8.Status = 'Action - Automated Escalation';
csa8.Ticket_Category2__c = 'Network';
csa8.Ticket_Type2__c = 'Login (Network)';
listCase.add(csa8);
Case csa9 = TestUtilityController.getCase(recordTypeId,con.Id,acc.Id);
csa9.Status = 'Action - Automated Escalation';
csa9.Ticket_Category2__c = 'Network/Services';
csa9.Ticket_Type2__c = 'Power';
listCase.add(csa9);
Case csa10 = TestUtilityController.getCase(recordTypeId,con.Id,acc.Id);
csa10.Status = 'Action - Automated Escalation';
csa10.Ticket_Category2__c = 'Network';
csa10.Ticket_Type2__c = 'Troubleshoot (Network)';
listCase.add(csa10);
Case csa11 = TestUtilityController.getCase(recordTypeId,con.Id,acc.Id);
csa11.Status = 'Action - Automated Escalation';
csa11.Ticket_Category2__c = 'Phone System';
listCase.add(csa11);
Case csa12 = TestUtilityController.getCase(recordTypeId,con.Id,acc.Id);
csa12.Status = 'Action - Automated Escalation';
csa12.Ticket_Category2__c = 'Registration';
csa12.Ticket_Type2__c = 'MyMSTC';
listCase.add(csa12);
Case csa13 = TestUtilityController.getCase(recordTypeId,con.Id,acc.Id);
csa13.Status = 'Action - Automated Escalation';
csa13.Ticket_Category2__c = 'Computers and Classroom Technology';
csa13.Ticket_Type2__c = 'Move/Add/Change (Computer)';
csa13.Ticket_Item2__c='Hardware';
listCase.add(csa13);
Case csa14 = TestUtilityController.getCase(recordTypeId,con.Id,acc.Id);
csa14.Status = 'Action - Automated Escalation';
csa14.Ticket_Category2__c = 'Computers and Classroom Technology';
csa14.Ticket_Type2__c = 'Install / Configuration';
csa14.Ticket_Item2__c='Speakers/Amplifier';
listCase.add(csa14);
Case csa15 = TestUtilityController.getCase(recordTypeId,con.Id,acc.Id);
csa15.Status = 'Action - Automated Escalation';
csa15.Ticket_Category2__c = 'Computers and Classroom Technology';
csa15.Ticket_Type2__c = 'Troubleshoot';
csa15.Ticket_Item2__c='Document Camera';
listCase.add(csa15);
insert listCase;
}
}
}
I write test class it is running successfully but apex class code coverage is none .
i am mention class and test class please help me.
public class Case_Automated_Escalation_MidState{
public static void beforeTriggerCall(List<Case> listCase){
for(Case cs : listCase){
String queueName = manageQueueName(cs);
if(UtilityController.mapQueue.containsKey(queueName)){
cs.Status = 'Escalated';
cs.OwnerId = UtilityController.mapQueue.get(queueName);
}
}
}
private static String manageQueueName(Case cs){
String queueName = '';
/*----------------------------------------------------------------------MidState - Media Services-------------------------------------------------------------------------------*/
if(cs.Ticket_Category2__c=='Digital Storefront'||cs.Ticket_Category2__c=='Printing' &&((cs.Ticket_Type2__c=='Troubleshoot (Printing / Imaging)' && (cs.Ticket_Item2__c!='Software / Configuration')) ||(cs.Ticket_Type2__c=='Setup / Configuration (Printing / Imaging)' && (cs.Ticket_Item2__c!='Connecting to an existing printer')))&& cs.Status=='Action - Automated Escalation'){
queueName='MidState - Media Services';
}
/*-------------------------------------------------------------------MidState - Desktop Services---------------------------------------------------------------------------*/
if((cs.Ticket_Category2__c=='Software (Computer)'||cs.Ticket_Category2__c=='Mobile Device - Mid-State Owned'|| cs.Ticket_Category2__c=='Email' && cs.Ticket_Type2__c=='Troubleshoot (Email)' ) && cs.Status=='Action - Automated Escalation'){
queueName='MidState Dsktop Services';
}
if((cs.Ticket_Category2__c=='Computers and Classroom Technology' &&((cs.Ticket_Type2__c=='Install / Configuration' || cs.Ticket_Type2__c=='Troubleshoot')&&(cs.Ticket_Item2__c=='Desktop Computer'||cs.Ticket_Item2__c=='Desktop Monitor'||cs.Ticket_Item2__c=='Wired Mouse'||cs.Ticket_Item2__c=='Wired Keyboard' ))||
(cs.Ticket_Type2__c=='Move/Add/Change (Computer)'&& cs.Ticket_Item2__c=='Hardware')|| cs.Ticket_Type2__c=='Imaging'||cs.Ticket_Type2__c== 'Other')&& cs.Status=='Action - Automated Escalation'){
queueName='MidState Dsktop Services';
}
if(cs.Ticket_Category2__c=='Network' &&(cs.Ticket_Type2__c=='VPN / Remote Access'||cs.Ticket_Type2__c=='Wireless'||cs.Ticket_Type2__c=='Troubleshoot (Network)')
&&(cs.Ticket_Item2__c=='Troubleshoot (Network)' || cs.Ticket_Item2__c=='Setup '||cs.Ticket_Item2__c=='Troubleshoot'||cs.Ticket_Item2__c=='Wireless'||cs.Ticket_Item2__c=='VPN / Remote Access') && cs.Status=='Action - Automated Escalation'){
queueName='MidState Dsktop Services';
}
if((cs.Ticket_Category2__c=='Printing'&& cs.Ticket_Type2__c=='Setup / Configuration (Printing / Imaging)' && cs.Ticket_Item2__c=='Connecting to an existing printer') && cs.Status=='Action - Automated Escalation'){
queueName='MidState Dsktop Services';
}
/*------------------------------------------------------------------------------MidState - Network Services--------------------------------------------------------------------------*/
if(cs.Ticket_Category2__c=='Email' && (cs.Ticket_Type2__c=='Login'||cs.Ticket_Type2__c=='Access / Permissions (MS)'||cs.Ticket_Type2__c=='Setup / Configuration (Email)'||( cs.Ticket_Type2__c=='Troubleshoot (Email)'&& cs.Ticket_Item2__c!='Email - Outlook/365'))&& cs.Status=='Action - Automated Escalation')
{
queueName ='MidState - Network Services';
}
if((cs.Ticket_Category2__c=='ImageNow (Perceptive Content)'||(cs.Ticket_Category2__c=='Outage'&& cs.Ticket_Type2__c=='Email')||(cs.Ticket_Category2__c=='Printing' && cs.Ticket_Type2__c=='Troubleshoot (Printing / Imaging)'&& cs.Ticket_Item2__c=='Software / Configuration')) && cs.Status=='Action - Automated Escalation' ){
queueName ='MidState - Network Services';
}
if(cs.Ticket_Category2__c=='Network'&& (cs.Ticket_Type2__c=='File Maintenance'||cs.Ticket_Type2__c=='Login (Network)'||cs.Ticket_Type2__c=='Other' ||(cs.Ticket_Type2__c=='VPN / Remote Access'&& cs.Ticket_Item2__c=='Setup / Configuration (Network)')||(cs.Ticket_Type2__c=='Setup / Configuration (Network)'&& cs.Ticket_Item2__c=='VPN / Remote Access')
||(cs.Ticket_Type2__c=='Troubleshoot (Network)'&& cs.Ticket_Item2__c=='File Maintainance'))&& cs.Status=='Action - Automated Escalation')
{
queueName ='MidState - Network Services';
}
if((cs.Ticket_Category2__c=='Portal (MidState)' && cs.Ticket_Type2__c=='MyCampus')&& cs.Status=='Action - Automated Escalation')
{
queueName='MidState - Network Services';
}
if((cs.Ticket_Category2__c=='Outage' && cs.Ticket_Type2__c=='MyCampus Portal') && cs.Status=='Action - Automated Escalation')
{
queueName='MidState - Network Services';
}
/*-----------------------------------------------------------------------------MidState - Network Infrastructure-----------------------------------------------------------------*/
if(cs.Ticket_Category2__c=='Network/Services' ||(cs.Ticket_Category2__c=='Outage' && (cs.Ticket_Type2__c=='Power'||cs.Ticket_Type2__c=='Telephone'||(cs.Ticket_Type2__c=='Network'&& (cs.Ticket_Item2__c=='Wired'||cs.Ticket_Item2__c=='Wireless'))))&& cs.Status=='Action - Automated Escalation' )
{
queueName ='MidState - Network Infrastructure';
}
if(cs.Ticket_Category2__c=='Network' && (cs.Ticket_Type2__c=='Setup/ Troubleshoot (Network)' && cs.Ticket_Item2__c=='Network Drops /Installation') && cs.Status=='Action - Automated Escalation')
{
queueName ='MidState - Network Infrastructure';
}
if(cs.Ticket_Category2__c=='Network' && ((cs.Ticket_Type2__c=='Troubleshoot (Network)')&& (cs.Ticket_Item2__c=='Wired'|| cs.Ticket_Item2__c=='Wireless AP /Devices'|| cs.Ticket_Item2__c=='Internet /WILM Connectivity'||
cs.Ticket_Item2__c=='Video Conferencing /LTC/NWTC'|| cs.Ticket_Item2__c=='Video Surveillance /Campus'|| cs.Ticket_Item2__c=='Card Access/Door Schedules/keypads'||
cs.Ticket_Item2__c=='Video Surveillance /Testing Centers'||cs.Ticket_Item2__c=='Digital Display /Digital Marquees' ||cs.Ticket_Item2__c=='Digital Display /Digital Marquees'))&& cs.Status=='Action - Automated Escalation')
{
queueName ='MidState - Network Infrastructure';
}
/*--------------------------------------------------------------------------------MidState - Telephony----------------------------------------------------------------------------*/
if((cs.Ticket_Category2__c=='Phone System'|| cs.Ticket_Category2__c=='Phone System/Services') && cs.Status=='Action - Automated Escalation')
{
queueName='MidState - Telephony';
}
/*-------------------------------------------------------------------MidState - Classroom Instructional Technology------------------------------------------------------------------------------*/
if(cs.Ticket_Category2__c=='Computers and Classroom Technology' && (cs.Ticket_Type2__c=='Classroom EMERGENCY')&& cs.Status=='Action - Automated Escalation')
{
queueName='MidState - Classroom Instructional Tech';
}
if(cs.Ticket_Category2__c=='Computers and Classroom Technology' && ((cs.Ticket_Type2__c=='Install / Configuration'||cs.Ticket_Type2__c=='Troubleshoot') && (cs.Ticket_Item2__c=='Document Camera'||cs.Ticket_Item2__c=='Microphone'||cs.Ticket_Item2__c=='Projector'||cs.Ticket_Item2__c=='Projector Screen'
||cs.Ticket_Item2__c=='Interactive screen/monitor'||cs.Ticket_Item2__c=='Speakers/Amplifier'||cs.Ticket_Item2__c=='Monitor/Television'||cs.Ticket_Item2__c=='Printer'||cs.Ticket_Item2__c=='Telepresence'||cs.Ticket_Item2__c=='AV Conferencing'||cs.Ticket_Item2__c=='Wireless Mouse'||
cs.Ticket_Item2__c=='Wireless Keyboard'||cs.Ticket_Item2__c=='Conferencing camera')) && cs.Status=='Action - Automated Escalation')
{
queueName='MidState - Classroom Instructional Tech';
}
if(cs.Ticket_Category2__c=='Computers and Classroom Technology' && (cs.Ticket_Type2__c=='Troubleshoot' && (cs.Ticket_Item2__c=='Document Camera'||cs.Ticket_Item2__c=='Microphone'||cs.Ticket_Item2__c=='Projector'||cs.Ticket_Item2__c=='Projector Screen'||cs.Ticket_Item2__c=='AV Conferencing'||cs.Ticket_Item2__c=='Wireless Mouse'||cs.Ticket_Item2__c=='Wireless Keyboard'||cs.Ticket_Item2__c=='Conferencing camera')) && cs.Status=='Action - Automated Escalation')
{
queueName='MidState - Classroom Instructional Tech';
}
if(cs.Ticket_Category2__c=='Outage' && cs.Ticket_Type2__c=='Telepresence' && cs.Status=='Action - Automated Escalation')
{
queueName='MidState - Classroom Instructional Tech';
}
/*-----------------------------------------------------------------------MidState - Online Instructional Tech-----------------------------------------------------------------*/
if(cs.Ticket_Category2__c=='Outage' && cs.Ticket_Type2__c=='Blackboard' && cs.Status=='Action - Automated Escalation')
{
queueName='MidState - Online Instructional Tech';
}
if(cs.Ticket_Category2__c=='Blackboard' && (cs.Ticket_Type2__c=='Login'|| cs.Ticket_Type2__c=='Access / Permissions'|| cs.Ticket_Type2__c=='Instructor (LMS)'|| cs.Ticket_Type2__c=='Student (LMS)')&& cs.Status=='Action - Automated Escalation')
{
queueName='MidState - Online Instructional Tech';
}
/*-------------------------------------------------------------------------------------------Misslenius CTI------------------------------------------------------------------*/
if((cs.Ticket_Category2__c=='Network' && (cs.Ticket_Type2__c=='Setup / Configuration (Network)' && cs.Ticket_Item2__c=='VPN / Remote Access')) && cs.Status=='Action - Automated Escalation')
{
queueName ='MidState - Network Services';
}
if(cs.Ticket_Category2__c=='Network' && cs.Ticket_Type2__c=='Setup / Configuration (Network)' && cs.Ticket_Item2__c=='Wireless' && cs.Status=='Action - Automated Escalation')
{
queueName ='MidState Dsktop Services';
}
if(cs.Ticket_Category2__c=='Network' && (cs.Ticket_Type2__c=='Setup / Configuration (Network)' && (cs.Ticket_Item2__c=='Wired' || cs.Ticket_Item2__c=='Wireless AP /Devices')) && cs.Status=='Action - Automated Escalation')
{
queueName ='MidState - Network Infrastructure';
}
/*----------------------------------------------------------------------------MidState - Student Records----------------------------------------------------------------*/
if(((cs.Ticket_Category2__c=='Portal (MidState)' && cs.Ticket_Type2__c=='MyMSTC')|| cs.Ticket_Category2__c== 'Registration'|| (cs.Ticket_Category2__c=='Outage' && cs.Ticket_Type2__c=='MyMSTC (Outage)'))&& cs.Status=='Action - Automated Escalation'){
queueName='MidState - Student Records';
}
return queueName;
}
}
and test class is
@isTest
public class TestCase_Automated_escalation_Midstate {
// test method
@isTest
private static void test(){
/*Group queuename=[select Id from Group where Name = 'MidState - Classroom Instructional Tech' and Type = 'Queue'];*/
// create test account
Account acc = TestUtilityController.getAccount('Mid-State Technical College');
insert acc;
// create test contact
Contact con = TestUtilityController.getContact('Test Last Name','testing@testing.com',acc.Id);
insert con;
// fill utility
UtilityController.fillUtilities();
UtilityController.isUtility = false;
// Create test cases
List<Case> listCase = new List<Case>();
if(UtilityController.caseRecordType.containsKey('Mid-State Technical College_Ticket')){
String recordTypeId = UtilityController.caseRecordType.get('Mid-State Technical College_Ticket').Id;
Case csa = TestUtilityController.getCase(recordTypeId,con.Id,acc.Id);
csa.Status = 'Action - Automated Escalation';
csa.Ticket_Category2__c = 'Digital Storefront';
csa.Ticket_Type2__c = 'Printing';
listCase.add(csa);
Case csa1 = TestUtilityController.getCase(recordTypeId,con.Id,acc.Id);
csa1.Status = 'Action - Automated Escalation';
csa1.Ticket_Category2__c = 'Outage';
csa1.Ticket_Type2__c = 'Blackboard';
listCase.add(csa1);
Case csa2 = TestUtilityController.getCase(recordTypeId,con.Id,acc.Id);
csa2.Status = 'Action - Automated Escalation';
csa2.Ticket_Category2__c = 'Software (Computer)';
csa2.Ticket_Type2__c = 'Troubleshoot (Email)';
listCase.add(csa2);
Case csa3 = TestUtilityController.getCase(recordTypeId,con.Id,acc.Id);
csa3.Status = 'Action - Automated Escalation';
csa3.Ticket_Category2__c = 'Computers and Classroom Technology';
csa3.Ticket_Type2__c = 'Install / Configuration';
csa3.Ticket_Item2__c='Desktop Monitor';
listCase.add(csa3);
Case csa4 = TestUtilityController.getCase(recordTypeId,con.Id,acc.Id);
csa4.Status = 'Action - Automated Escalation';
csa4.Ticket_Category2__c = 'Network';
csa4.Ticket_Type2__c = 'VPN / Remote Access';
csa4.Ticket_Item2__c='Troubleshoot (Network)';
listCase.add(csa4);
Case csa5 = TestUtilityController.getCase(recordTypeId,con.Id,acc.Id);
csa5.Status = 'Action - Automated Escalation';
csa5.Ticket_Category2__c = 'Printing';
csa5.Ticket_Type2__c = 'Setup / Configuration (Printing / Imaging)';
csa5.Ticket_Item2__c= 'Connecting to an existing printer';
listCase.add(csa5);
Case csa6 = TestUtilityController.getCase(recordTypeId,con.Id,acc.Id);
csa6.Status = 'Action - Automated Escalation';
csa6.Ticket_Category2__c = 'Portal';
csa6.Ticket_Type2__c = 'Troubleshoot (Email)';
listCase.add(csa6);
Case csa7 = TestUtilityController.getCase(recordTypeId,con.Id,acc.Id);
csa7.Status = 'Action - Automated Escalation';
csa7.Ticket_Category2__c = 'ImageNow (Perceptive Content)';
csa7.Ticket_Type2__c = 'Email';
listCase.add(csa7);
Case csa8 = TestUtilityController.getCase(recordTypeId,con.Id,acc.Id);
csa8.Status = 'Action - Automated Escalation';
csa8.Ticket_Category2__c = 'Network';
csa8.Ticket_Type2__c = 'Login (Network)';
listCase.add(csa8);
Case csa9 = TestUtilityController.getCase(recordTypeId,con.Id,acc.Id);
csa9.Status = 'Action - Automated Escalation';
csa9.Ticket_Category2__c = 'Network/Services';
csa9.Ticket_Type2__c = 'Power';
listCase.add(csa9);
Case csa10 = TestUtilityController.getCase(recordTypeId,con.Id,acc.Id);
csa10.Status = 'Action - Automated Escalation';
csa10.Ticket_Category2__c = 'Network';
csa10.Ticket_Type2__c = 'Troubleshoot (Network)';
listCase.add(csa10);
Case csa11 = TestUtilityController.getCase(recordTypeId,con.Id,acc.Id);
csa11.Status = 'Action - Automated Escalation';
csa11.Ticket_Category2__c = 'Phone System';
listCase.add(csa11);
Case csa12 = TestUtilityController.getCase(recordTypeId,con.Id,acc.Id);
csa12.Status = 'Action - Automated Escalation';
csa12.Ticket_Category2__c = 'Registration';
csa12.Ticket_Type2__c = 'MyMSTC';
listCase.add(csa12);
Case csa13 = TestUtilityController.getCase(recordTypeId,con.Id,acc.Id);
csa13.Status = 'Action - Automated Escalation';
csa13.Ticket_Category2__c = 'Computers and Classroom Technology';
csa13.Ticket_Type2__c = 'Move/Add/Change (Computer)';
csa13.Ticket_Item2__c='Hardware';
listCase.add(csa13);
Case csa14 = TestUtilityController.getCase(recordTypeId,con.Id,acc.Id);
csa14.Status = 'Action - Automated Escalation';
csa14.Ticket_Category2__c = 'Computers and Classroom Technology';
csa14.Ticket_Type2__c = 'Install / Configuration';
csa14.Ticket_Item2__c='Speakers/Amplifier';
listCase.add(csa14);
Case csa15 = TestUtilityController.getCase(recordTypeId,con.Id,acc.Id);
csa15.Status = 'Action - Automated Escalation';
csa15.Ticket_Category2__c = 'Computers and Classroom Technology';
csa15.Ticket_Type2__c = 'Troubleshoot';
csa15.Ticket_Item2__c='Document Camera';
listCase.add(csa15);
insert listCase;
}
}
}
- devloper sfdc
- June 12, 2018
- Like
- 0
Code Coverage problem on my apex trigger
Hello All,
I am controlling our spam ticket using this trigger. And also Trigger running as expected my requirment. but I am not able to getting full code coverge by test class. Please check my test class and tell me what the actual error in my code .
Screen shot
Thanks & Regards
My Apex Trigger is
and my Test class is
I am controlling our spam ticket using this trigger. And also Trigger running as expected my requirment. but I am not able to getting full code coverge by test class. Please check my test class and tell me what the actual error in my code .
Screen shot
Thanks & Regards
My Apex Trigger is
trigger SpamControllerTrigger on Case (before insert) { /*===================================================hhjjf====================================*/ List<String> lstBasedOnDesc=new List<String>(); for(Keywords__c ks:[Select name from Keywords__c]){ lstBasedOnDesc.add(ks.name);} List<String>LstSpamkeyword=new List<String>(); /*===================================================hhjjf====================================*/ for(Trigger_Control__c tc:Trigger_Control__c.getAll().values()) { if( tc.Enable_Spam_Controller_Trigger__c==true) { for(case cs:Trigger.new) {//0050W0000061RWD sebastian //005d000000187CwAAI automated if(userinfo.getUserId()=='005d000000187CwAAI') { if(lstBasedOnDesc.size()>0) { for(String s:lstBasedOnDesc){ if(cs.Description!=null && ( cs.Description).Contains(s)) { cs.ownerId='00Gd00000027kH7'; cs.Spam_criteria__c='Based on Description'; cs.Possible_Spam__c=true;cs.Identified_Keyword__c=s; CalculatingScoreValue.getScoreValue(s); } else if(cs.Subject!=null && (cs.Subject).Contains(s)) { cs.ownerId='00Gd00000027kH7'; cs.Spam_criteria__c='Based on Subject'; cs.Possible_Spam__c=true; cs.Identified_Keyword__c=s; CalculatingScoreValue.getScoreValue(s); } else if((cs.SuppliedEmail).Contains(s)) {cs.ownerId='00Gd00000027kH7'; cs.Spam_criteria__c='Based on Webmail'; cs.Possible_Spam__c=true;cs.Identified_Keyword__c=s; CalculatingScoreValue.getScoreValue(s); } }}}}}}}
and my Test class is
@isTest public class SpamControllerTriggerTest { @isTest public Static void SpamTestmethod() { Account acc = new Account(Name='MassBay'); insert acc; Contact con = new Contact(AccountId=acc.Id,LastName='test',Email='desd.red@test.tst'); insert con; Trigger_Control__c tc=new Trigger_Control__c(); tc.Enable_Spam_Controller_Trigger__c=true; tc.Name='test tc'; insert tc; Keywords__c key=new keywords__c(name='badword'); insert key; List<case>lstcase=new List<case>(); List<RecordType> listRecType = [select Id from RecordType where sObjectType = 'Case' And Name = 'MassBay_Ticket']; Case cs = new Case(RecordTypeId = listRecType[0].Id,AccountId=acc.Id,ContactId=con.Id); cs.Spam_criteria__c='Based on Description'; cs.Subject='Testing for spam'; cs.Description=key.Name; cs.SuppliedEmail='xxx@test.com'; cs.Possible_Spam__c=true; cs.Identified_Keyword__c='s'; lstcase.add(cs); insert lstcase; } }
- devloper sfdc
- February 10, 2021
- Like
- 0
Problem in test class i am getting only 36% code coverage
Hi Salesforce Expert,
We are getting only 36% code coverage in our apex class. my Apex trigger please help me apex code is here-
And test class is
code which is not covering is below here--
We are getting only 36% code coverage in our apex class. my Apex trigger please help me apex code is here-
trigger EmailSendToOwnerUpdate on Case (before update) { // this is a list for storing email for settoAddress List<String>toAddress =new List<String>(); // this is a list for storing email for setccAddress List<String>CCAddress =new List<String>(); List<contact> lstcont=[select id ,Email,name,phone from contact]; Map<String,String> mapContact=new Map<String,String>(); list<String> ccAddresslst=new List<String>(); map<string,String> mapuser=new map<string,string>(); String ownerName=''; String baseUrl = URL.getSalesforceBaseUrl().toExternalForm(); //for getting user email and store in map where user id is key and email is value for(User u:[select id, name, Email from user]) { mapuser.put(u.id,u.email); } //for getting Contact name and store in map where id is key and name is value for(contact con:lstcont) { mapContact.put(con.id,con.name); } for(case cs:trigger.new) { if(cs.total_attachments__c>=1) { case oldcase=Trigger.oldMap.get(cs.id); if(oldcase.OwnerId!=cs.OwnerId) { if(string.valueOf(cs.OwnerId).startsWith('005')) { toAddress.add(mapuser.get(cs.OwnerId)); ownerName=Getqueuemember.getOwnername(cs.OwnerId); } else{ CCAddress=Getqueuemember.getEmailfromuser(cs.OwnerId); ownerName=Getqueuemember.getqueueOwnername(cs.OwnerId); } List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>(); List<Attachment> attlist=[select Name, Body, BodyLength from Attachment where ParentId = :cs.id ]; for (Attachment a :attlist){ Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment(); efa.setFileName(a.Name); efa.setBody(a.Body); fileAttachments.add(efa); } String Subject='Apex template Ticket #'+cs.CaseNumber+' has been assigned to '+' '+ownerName; try{ EmailTemplate et = [SELECT Id,Subject, Body FROM EmailTemplate WHERE DeveloperName ='Sebastian_page']; Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage(); semail.setSubject(Subject); semail.setSenderDisplayName('Salesforce Support'); semail.setTargetObjectId(cs.ContactId); //semail.setTemplateId(et.id); semail.setCcAddresses(CCAddress); semail.setToAddresses(toAddress); semail.setHtmlBody('***THIS IS A SYSTEM GENERATED MESSAGE! DO NOT REPLY!***<br/><br/>Please be advised that the following SalesForce ticket has been assigned to '+ownerName+'<br/><br/> Ticket #:'+cs.CaseNumber+ '<br/>Subject:'+cs.subject+'<br/><br/>Contact Name: '+mapContact.get(cs.Contactid)+'<br/>Contact Phone (primary): '+Getqueuemember.r(cs.ContactPhone)+'<br/>Contact Mobile (primary): '+Getqueuemember.r(cs.ContactMobile)+ '<br/> Contact Email:'+Getqueuemember.r(cs.ContactEmail)+'<br/><br/>Category: '+Getqueuemember.r(cs.Ticket_Category__c)+Getqueuemember.r(cs.Service_Category__c)+Getqueuemember.r(cs.Ticket_Category2__c)+ '<br/>Type: '+Getqueuemember.r(cs.Ticket_Type__c)+Getqueuemember.r(cs.Service_Type__c)+Getqueuemember.r(cs.Ticket_Type2__c)+ '<br/>Item: '+Getqueuemember.r(cs.Ticket_Item__c)+Getqueuemember.r(cs.Service_Item__c)+Getqueuemember.r(cs.Ticket_Item2__c)+ '<br/>Ticket Source: '+Getqueuemember.r(cs.Case_Source__c)+'<br/><br/><br/>Building: '+Getqueuemember.r(cs.building__c)+'<br/>Room: '+Getqueuemember.r(cs.Room_Number__c)+'<br/>Area Description: '+Getqueuemember.r(cs.Area_description__c)+ '<br/><br/><br/>Click the appropriate link below to view the ticket directly:<br/><br/>Partner Portal Users: <a href='+baseUrl+'/'+cs.id+'>'+baseUrl+'/'+cs.id+'</a><br/>BlackbeltHelp (Community Users): <a href='+Getqueuemember.getcommunityurl(cs.AccountId)+cs.id+ '>'+Getqueuemember.getcommunityurl(cs.AccountId)+cs.id+'</a><br/><br/>Description:'+cs.Description+'<br/><br/>Internal Notes: '+Getqueuemember.r(cs.Internal_Notes__c)); semail.setFileAttachments(fileAttachments); semail.setWhatId(cs.id); Messaging.sendEmail(new Messaging.SingleEmailMessage[] {semail}); } catch(exception e) {} } } } }
And test class is
@isTest public class TestEmailSendToOwner { @isTest public Static void emailTest() { // create test account Account acc = TestUtilityController.getAccount('MassBay'); insert acc; // create test contact Contact con = TestUtilityController.getContact('Test Last Name','testing@testing.com',acc.Id); insert con; // fill utility UtilityController.fillUtilities(); UtilityController.isUtility = false; // Create test cases List<Case> listCase = new List<Case>(); if(UtilityController.caseRecordType.containsKey('MassBayCC_Ticket')){ String recordTypeId = UtilityController.caseRecordType.get('MassBayCC_Ticket').Id; Case csanew = TestUtilityController.getCase(recordTypeId,con.Id,acc.Id); csanew.status = 'Action - Automated Escalation'; csanew.total_attachments__c=2; csanew.Ticket_Category2__c = 'Blackboard Learn - LMS'; csanew.Ticket_Type2__c = 'Faculty/Staff'; csanew.Ticket_Item2__c='Tutorial'; listCase.add(csanew); insert listCase; Getqueuemember.getcommunityurl(acc.id); Getqueuemember.getEmailfromuser(listCase[0].ownerId); Getqueuemember.getOwnername(listCase[0].ownerId); Getqueuemember.r(csanew.Ticket_Category2__c); } } }
code which is not covering is below here--
if(string.valueOf(cs.OwnerId).startsWith('005')) { toAddress.add(mapuser.get(cs.OwnerId)); ownerName=Getqueuemember.getOwnername(cs.OwnerId); } else{ CCAddress=Getqueuemember.getEmailfromuser(cs.OwnerId); ownerName=Getqueuemember.getqueueOwnername(cs.OwnerId); } List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>(); List<Attachment> attlist=[select Name, Body, BodyLength from Attachment where ParentId = :cs.id ]; for (Attachment a :attlist){ Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment(); efa.setFileName(a.Name); efa.setBody(a.Body); fileAttachments.add(efa); } String Subject='Apex template Ticket #'+cs.CaseNumber+' has been assigned to '+' '+ownerName; try{ EmailTemplate et = [SELECT Id,Subject, Body FROM EmailTemplate WHERE DeveloperName ='Sebastian_page']; Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage(); semail.setSubject(Subject); semail.setSenderDisplayName('Salesforce Support'); semail.setTargetObjectId(cs.ContactId); //semail.setTemplateId(et.id); semail.setCcAddresses(CCAddress); semail.setToAddresses(toAddress); semail.setHtmlBody('***THIS IS A SYSTEM GENERATED MESSAGE! DO NOT REPLY!***<br/><br/>Please be advised that the following SalesForce ticket has been assigned to '+ownerName+'<br/><br/> Ticket #:'+cs.CaseNumber+ '<br/>Subject:'+cs.subject+'<br/><br/>Contact Name: '+mapContact.get(cs.Contactid)+'<br/>Contact Phone (primary): '+Getqueuemember.r(cs.ContactPhone)+'<br/>Contact Mobile (primary): '+Getqueuemember.r(cs.ContactMobile)+ '<br/> Contact Email:'+Getqueuemember.r(cs.ContactEmail)+'<br/><br/>Category: '+Getqueuemember.r(cs.Ticket_Category__c)+Getqueuemember.r(cs.Service_Category__c)+Getqueuemember.r(cs.Ticket_Category2__c)+ '<br/>Type: '+Getqueuemember.r(cs.Ticket_Type__c)+Getqueuemember.r(cs.Service_Type__c)+Getqueuemember.r(cs.Ticket_Type2__c)+ '<br/>Item: '+Getqueuemember.r(cs.Ticket_Item__c)+Getqueuemember.r(cs.Service_Item__c)+Getqueuemember.r(cs.Ticket_Item2__c)+ '<br/>Ticket Source: '+Getqueuemember.r(cs.Case_Source__c)+'<br/><br/><br/>Building: '+Getqueuemember.r(cs.building__c)+'<br/>Room: '+Getqueuemember.r(cs.Room_Number__c)+'<br/>Area Description: '+Getqueuemember.r(cs.Area_description__c)+ '<br/><br/><br/>Click the appropriate link below to view the ticket directly:<br/><br/>Partner Portal Users: <a href='+baseUrl+'/'+cs.id+'>'+baseUrl+'/'+cs.id+'</a><br/>BlackbeltHelp (Community Users): <a href='+Getqueuemember.getcommunityurl(cs.AccountId)+cs.id+ '>'+Getqueuemember.getcommunityurl(cs.AccountId)+cs.id+'</a><br/><br/>Description:'+cs.Description+'<br/><br/>Internal Notes: '+Getqueuemember.r(cs.Internal_Notes__c)); semail.setFileAttachments(fileAttachments); semail.setWhatId(cs.id); Messaging.sendEmail(new Messaging.SingleEmailMessage[] {semail}); } catch(exception e) {} } } } }
- devloper sfdc
- February 05, 2020
- Like
- 0
Trigger on case object
HI All,
I am writing a trigger as below to update Case due date automtically while insert.
I don't why this trigger is not working.
however when i remove caselst.add(c); this works fine. Please help
trigger DueDate on Case (before insert) {
list<case> caselst = new list <case>();
for(Case c:trigger.new){
if(c.Date_Due__c==Null){
c.Date_Due__c = system.today() + 1;
}
caselst.add(c);
}
Insert caselst;
}
I am writing a trigger as below to update Case due date automtically while insert.
I don't why this trigger is not working.
however when i remove caselst.add(c); this works fine. Please help
trigger DueDate on Case (before insert) {
list<case> caselst = new list <case>();
for(Case c:trigger.new){
if(c.Date_Due__c==Null){
c.Date_Due__c = system.today() + 1;
}
caselst.add(c);
}
Insert caselst;
}
- Anant Pandey 8
- March 27, 2019
- Like
- 0
why test class is not covering code coverage for all line
Hi All ,
I have cover only 58 percent code covergage for trigger but i want to 100% . Please understand my test code and tell me what the issue .
my apex trigger is .
Test Class is
Regards
Shiv Patel
I have cover only 58 percent code covergage for trigger but i want to 100% . Please understand my test code and tell me what the issue .
my apex trigger is .
trigger Prevent_Escalation_SupportType on Case (before insert,after update) { List<String> LstRecTypeName=new List<String>{'American Sentinel University_Ticket','Limestone_Ticket','CSU_Ticket','Extension_Ticket','Healthcare Learning Innovations_Ticket','LinnBenton_Ticket','Lipscomb_Ticket', 'Reinhardt University_Ticket','UMKC_Ticket','Bridgeport_Ticket','GardnerWebb_Ticket','Joliet_Ticket','Lynchburg_Ticket','LakeMichiganC_Ticket','RogersState_Ticket','SCKans_Ticket','SewardCCC_Ticket','SUShreveport_Ticket','UTSW_Ticket','Benedictine University_Ticket'}; Set<Id>LstRecordTypIds =new Set<Id>(); List<RecordType> lstrecType=[Select id From RecordType where sobjecttype = 'case' and name in:LstRecTypeName]; for(RecordType Rec:lstrecType) { LstRecordTypIds.add(Rec.id); } for(case cs:trigger.new) { if((userinfo.getLastName().contains('BBH') || (userinfo.getLastName().contains('BlackBeltHelp')))) { if(LstRecordTypIds.contains(cs.RecordTypeId)) { if(cs.Support_Type__c==null) { if(cs.Status=='Action - Automated Escalation' ||cs.Status=='Escalated') { cs.addError('Please select a Support type value before escalating the ticket.'); } } else if(cs.Support_Type__c!=null) { if(!(cs.Status=='Action - Automated Escalation' ||cs.Status=='Escalated')) { cs.addError('Please make sure Support type value is blank unless you want to escalate the ticket'); } } } } } }
Test Class is
@isTest public class Prevent_Escalation_SupportTypeTest { @isTest private static void test1(){ Account acc = new Account(Name='LimeStone'); insert acc; Contact con = new Contact(AccountId=acc.Id,LastName='test'); insert con; Trigger_Control__c tc=new Trigger_Control__c(); tc.Enable_CaseCreation_Trigger__c=true; tc.Name='test tc'; insert tc; User u; User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()]; System.runAs (thisUser) { Profile p = [SELECT Id FROM Profile WHERE Name='CH_Tier1-Partner']; u = new User(alias = 'tstwy', email='testmail@tst.com', emailencodingkey='UTF-8', lastname='testL', languagelocalekey='en_US', localesidkey='en_US', profileid = p.Id, ContactId = con.Id, timezonesidkey='America/Los_Angeles', username='testmailxxx@tst.com'); insert u; } List<RecordType> listRecType = [select Id from RecordType where sObjectType = 'Case' And Name = 'Limestone_Ticket']; if(listRecType[0].Id!=null) { System.runAs (u) { Case cs = new Case(RecordTypeId = listRecType[0].Id,AccountId=acc.Id,ContactId=con.Id ); insert cs; } } } }
Regards
Shiv Patel
- devloper sfdc
- March 27, 2019
- Like
- 0
I need to write test code for apex class
Hi All ,
I need to write test class for below code please help me it is very urgent.
public class QueueAssignController{
Public List<SelectOption> QueueList {get;set;}
public List<Group> GroupNameList {get;set;}
Public list<GroupMember> mlist {get;set;}
public String queue {get;set;}
public String queueid {get;set;}
public List<String> selectedUserIds { get; set; }
public List<String> removedUserIds { get; set; }
public String whereClause { get; set; }
public String AccName {get;set;}
private Map<Id, String> availableUsersMap;
private Map<Id, String> selectedUsersMap;
public QueueAssignController(ApexPages.StandardController std) {
initializeCollections();
ID contactId = [Select contactid from User where id =: Userinfo.getUserid()].contactId;
// Pid = [Select ProfileId from User where id =: Userinfo.getUserid()].ProfileId;
String aid = [Select AccountID from Contact where id =: contactid].AccountId;
// String aid=ApexPages.currentPage().getParameters().get('id');
List<String> accName=new List<String>();
account[] a=[select WFSSFriendlyName__c from account where id=:aid limit 1 ];
String wffs=a[0].WFSSFriendlyName__c;
GroupNameList = new List<Group>();
String j='%'+wffs+'%';
GroupNameList = [select g.Id, g.Name from Group g where Type = 'Queue' AND name like:j Order by Name Asc];
QueueList = new List<SelectOption>();
for(Group temp : GroupNameList)
{
queueid = temp.id;
QueueList.add(new SelectOption(temp.Id, temp.Name));
}
if(queue == null){
queue = queueid;
getUsers();
}
system.debug('QueueList++++++'+QueueList);
system.debug('queue ++++++'+queue );
}
public PageReference UpdateList() {
initializeCollections();
getUsers();
return null;
}
public void filterAvailableOptions() {
availableUsersMap = new Map<Id, String>();
selectedUserIds = new List<String>();
string userid =userinfo.getUserId();
user[] uac=[select AccountId from user where id=:userid limit 1];
String likeClause = '%' + whereClause + '%';
for (User u : [SELECT id, name FROM User WHERE name like :likeClause AND Name!='Chatter Expert' AND IsActive = true order by Name Asc]) {
if (!selectedUsersMap.containsKey(u.Id)) {
availableUsersMap.put(u.Id, u.Name);
}
}
}
public void add() {
if (!selectedUserIds.isEmpty()) {
for (String userId : selectedUserIds) {
selectedUsersMap.put(userId, availableUsersMap.get(userId));
availableUsersMap.remove(userId);
}
}
}
public void remove() {
if (!removedUserIds.isEmpty()) {
for (String userId : removedUserIds) {
availableUsersMap.put(userId, selectedUsersMap.get(userId));
selectedUsersMap.remove(userId);
}
}
}
public List<SelectOption> getAvailableUsers() {
List<SelectOption> availableUsers = new List<SelectOption>();
for (Id userId : availableUsersMap.keySet()) {
availableUsers.add(new SelectOption(userId, availableUsersMap.get(userId)));
}
return availableUsers;
}
public List<SelectOption> getSelectedUsers() {
List<SelectOption> selectedUsers = new List<SelectOption>();
for (String userId : selectedUsersMap.keySet()) {
selectedUsers.add(new SelectOption(userId, selectedUsersMap.get(userId)));
}
return selectedUsers;
}
private void initializeCollections() {
selectedUserIds = new List<String>();
removedUserIds = new List<String>();
availableUsersMap = new Map<Id, String>();
selectedUsersMap = new Map<Id, String>();
}
private void getUsers() {
QueueSobject qs = [SELECT QueueId,SobjectType FROM QueueSobject where QueueId=:queue];
list<GroupMember> gms = [SELECT Group.Name,UserOrGroupId FROM GroupMember WHERE Group.Type = 'Queue' AND GroupId =:qs.QueueId];
system.debug(gms);
set<id> gids =new set<id>();
for(GroupMember g:gms){
gids.add(g.UserOrGroupId);
}
String aid=ApexPages.currentPage().getParameters().get('id');
list<user> urs = [SELECT id, Name FROM User where IsActive = true AND id NOT IN:gids AND Name!='Chatter Expert' AND AccountId=:aid order by Name Asc];
system.debug(urs);
for(user u : urs){
availableUsersMap.put(u.Id, u.Name);
}
list<user> urss = [SELECT id, Name FROM User where IsActive = true AND id IN:gids AND Name!='Chatter Expert' order by Name Asc];
system.debug(urs);
for(user ur : urss){
selectedUsersMap.put(ur.Id, ur.Name);
}
}
public PageReference savenew(){
List<GroupMember> groups = new List<GroupMember>();
List<GroupMember> groupss = [select Id from GroupMember where Group.Type = 'Queue' and GroupId =:queue ];
if( !groupss.isEmpty() )
{
delete groupss;
}
if(selectedUsersMap.size() == 0){
ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.Error, 'Please select a user to Add to Queue') );
}
else{
for(id ids:selectedUsersMap.keyset()){
// ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.INFO, 'Added user to Queue'+queue) );
insert new GroupMember( GroupId = queue , UserOrGroupId = ids);
}
}
return null;
}
}
I need to write test class for below code please help me it is very urgent.
public class QueueAssignController{
Public List<SelectOption> QueueList {get;set;}
public List<Group> GroupNameList {get;set;}
Public list<GroupMember> mlist {get;set;}
public String queue {get;set;}
public String queueid {get;set;}
public List<String> selectedUserIds { get; set; }
public List<String> removedUserIds { get; set; }
public String whereClause { get; set; }
public String AccName {get;set;}
private Map<Id, String> availableUsersMap;
private Map<Id, String> selectedUsersMap;
public QueueAssignController(ApexPages.StandardController std) {
initializeCollections();
ID contactId = [Select contactid from User where id =: Userinfo.getUserid()].contactId;
// Pid = [Select ProfileId from User where id =: Userinfo.getUserid()].ProfileId;
String aid = [Select AccountID from Contact where id =: contactid].AccountId;
// String aid=ApexPages.currentPage().getParameters().get('id');
List<String> accName=new List<String>();
account[] a=[select WFSSFriendlyName__c from account where id=:aid limit 1 ];
String wffs=a[0].WFSSFriendlyName__c;
GroupNameList = new List<Group>();
String j='%'+wffs+'%';
GroupNameList = [select g.Id, g.Name from Group g where Type = 'Queue' AND name like:j Order by Name Asc];
QueueList = new List<SelectOption>();
for(Group temp : GroupNameList)
{
queueid = temp.id;
QueueList.add(new SelectOption(temp.Id, temp.Name));
}
if(queue == null){
queue = queueid;
getUsers();
}
system.debug('QueueList++++++'+QueueList);
system.debug('queue ++++++'+queue );
}
public PageReference UpdateList() {
initializeCollections();
getUsers();
return null;
}
public void filterAvailableOptions() {
availableUsersMap = new Map<Id, String>();
selectedUserIds = new List<String>();
string userid =userinfo.getUserId();
user[] uac=[select AccountId from user where id=:userid limit 1];
String likeClause = '%' + whereClause + '%';
for (User u : [SELECT id, name FROM User WHERE name like :likeClause AND Name!='Chatter Expert' AND IsActive = true order by Name Asc]) {
if (!selectedUsersMap.containsKey(u.Id)) {
availableUsersMap.put(u.Id, u.Name);
}
}
}
public void add() {
if (!selectedUserIds.isEmpty()) {
for (String userId : selectedUserIds) {
selectedUsersMap.put(userId, availableUsersMap.get(userId));
availableUsersMap.remove(userId);
}
}
}
public void remove() {
if (!removedUserIds.isEmpty()) {
for (String userId : removedUserIds) {
availableUsersMap.put(userId, selectedUsersMap.get(userId));
selectedUsersMap.remove(userId);
}
}
}
public List<SelectOption> getAvailableUsers() {
List<SelectOption> availableUsers = new List<SelectOption>();
for (Id userId : availableUsersMap.keySet()) {
availableUsers.add(new SelectOption(userId, availableUsersMap.get(userId)));
}
return availableUsers;
}
public List<SelectOption> getSelectedUsers() {
List<SelectOption> selectedUsers = new List<SelectOption>();
for (String userId : selectedUsersMap.keySet()) {
selectedUsers.add(new SelectOption(userId, selectedUsersMap.get(userId)));
}
return selectedUsers;
}
private void initializeCollections() {
selectedUserIds = new List<String>();
removedUserIds = new List<String>();
availableUsersMap = new Map<Id, String>();
selectedUsersMap = new Map<Id, String>();
}
private void getUsers() {
QueueSobject qs = [SELECT QueueId,SobjectType FROM QueueSobject where QueueId=:queue];
list<GroupMember> gms = [SELECT Group.Name,UserOrGroupId FROM GroupMember WHERE Group.Type = 'Queue' AND GroupId =:qs.QueueId];
system.debug(gms);
set<id> gids =new set<id>();
for(GroupMember g:gms){
gids.add(g.UserOrGroupId);
}
String aid=ApexPages.currentPage().getParameters().get('id');
list<user> urs = [SELECT id, Name FROM User where IsActive = true AND id NOT IN:gids AND Name!='Chatter Expert' AND AccountId=:aid order by Name Asc];
system.debug(urs);
for(user u : urs){
availableUsersMap.put(u.Id, u.Name);
}
list<user> urss = [SELECT id, Name FROM User where IsActive = true AND id IN:gids AND Name!='Chatter Expert' order by Name Asc];
system.debug(urs);
for(user ur : urss){
selectedUsersMap.put(ur.Id, ur.Name);
}
}
public PageReference savenew(){
List<GroupMember> groups = new List<GroupMember>();
List<GroupMember> groupss = [select Id from GroupMember where Group.Type = 'Queue' and GroupId =:queue ];
if( !groupss.isEmpty() )
{
delete groupss;
}
if(selectedUsersMap.size() == 0){
ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.Error, 'Please select a user to Add to Queue') );
}
else{
for(id ids:selectedUsersMap.keyset()){
// ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.INFO, 'Added user to Queue'+queue) );
insert new GroupMember( GroupId = queue , UserOrGroupId = ids);
}
}
return null;
}
}
- devloper sfdc
- January 17, 2019
- Like
- 0
I need to write test class for apex class
Hi All,
I need to write test class for apex class my code is here-
public class CommenttoEmail {
public String Commentbody {get;set;}
public String subject {get;set;}
public String Set_to{get;set;}
Public String Set_bcc{get;set;}
public String Set_cc{get;set;}
public List<String> SetTo {get;set;}
public List<String> SetCC {get;set;}
public List<String> SetBCC{get;set;}
Public String CaseId {get;set;}
public String Selec {get;set;}
public List<String> liststatus {get;set;}
public boolean flag {set;get;}
public string Str2;
public String test;
Public List<string> listall {get;set;}
public Attachment attachment {
get {
if (attachment == null)
attachment = new Attachment();
return attachment;
}
set;
}
public CommenttoEmail(apexpages.StandardController std)
{
liststatus=new List<string>{'New','Working','Escalated','Closed Successful'};
flag=false;
CaseId=ApexPages.CurrentPage().getParameters().get('Id');
listall=new List<String>();
SetTo=new List<String>{};
SetCC=new List<String>{};
SetBCC=new List<String>{};
}
public void senttoEmail()
{
Case cse = [select id ,CaseNumber ,Status,ContactEmail,subject from case where id=:caseId];
SetTo=Set_To.split(',');
}
public void bccEmail()
{
SetBCC=Set_bcc.split(',');
}
public void ccEmail()
{
SetCC=Set_cc.split(',');
}
public void ss()
{
senttoEmail();
bccEmail();
ccEmail();
}
public void attachemail()
{
listall.addAll(SetTo);
listall.addAll(SetBCC);
listall.addAll(SetCC);
}
public pagereference createCaseComment(){
ss();
upload();
attachemail();
sendingEmail();
ChangeStatus();
Case cse = [select id ,CaseNumber ,Status, Contact.name,Account.name,subject from case where id=:caseId];
String ss=string.join(listall, ',');
String Str1='\n\n';
String Str0='[Recipients:' +ss+']';
String Str3=cse.Contact.name+',\n\n';
String Reg='\n\n\n Sincerely,\n'+cse.Contact.name+'\n'+cse.Account.name;
Str2=Str0+Str1+Str3+Commentbody+Reg;
CaseComment cc = new CaseComment(ParentId = cse.Id,CommentBody = str2 , IsPublished=true);
insert cc;
pagereference pg =new pagereference('/'+CaseId);
return pg;
}
public PageReference sendingEmail()
{
upload();
Case cse = [select id ,CaseNumber ,Status, Contact.name,Account.name,subject from case where id=:caseId];
String ss=string.join(listall, ',');
String Str3=cse.Contact.name+',\n\n';
String Reg='\n\n\n Sincerely,\n'+cse.Contact.name+'\n'+cse.Account.name;
Str2=Str3+Commentbody+Reg;
List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
for (Attachment a : [select Name, Body, BodyLength from Attachment where ParentId = :caseId]){
Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
efa.setFileName(a.Name);
efa.setBody(a.Body);
fileAttachments.add(efa);
}
try{
Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage();
semail.setToAddresses(SetTo);
semail.setBccAddresses(SetBCC);
semail.setCcAddresses(SetCC);
semail.setSubject(cse.Subject);
semail.setPlainTextBody(Str2);
semail.setFileAttachments(fileAttachments);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {semail});
}catch(exception e)
{}
return null;
}
public pagereference redirectCasePage()
{
CaseId=ApexPages.CurrentPage().getParameters().get('Id');
pagereference pg =new pagereference('/'+CaseId);
return pg;
}
public void ChangeStatus()
{
List<Case> cse = [select id ,CaseNumber ,Status,subject from case where id=:caseId];
for(Case c:cse){
if(selec=='New')
{
c.Status='New';
}
if(selec=='Working')
{
c.Status='Working';
}
if(selec=='Escalated')
{
c.Status='Escalated';
}
if(selec=='Closed successful')
{
c.Status='Closed successful';
}
update c;
}
}
public List<SelectOption> getCaseStatus()
{
List<SelectOption> optlist=new List<SelectOption>();
Case cse = [select id ,CaseNumber ,Status,subject from case where id=:caseId];
optlist.add(new SelectOption(cse.Status,cse.Status));
for(String s:liststatus)
{
optlist.add(new SelectOption(s,s));
}
return optlist;
}
public PageReference upload() {
attachment.OwnerId = UserInfo.getUserId();
attachment.ParentId = CaseId;
attachment.IsPrivate = true;
attachment.ContentType = 'image/jpeg';
try {
insert attachment;
} catch (DMLException e) {
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading attachment'));
return null;
} finally {
attachment = new Attachment();
}
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Attachment uploaded successfully'));
return null;
}
}
I need to write test class for apex class my code is here-
public class CommenttoEmail {
public String Commentbody {get;set;}
public String subject {get;set;}
public String Set_to{get;set;}
Public String Set_bcc{get;set;}
public String Set_cc{get;set;}
public List<String> SetTo {get;set;}
public List<String> SetCC {get;set;}
public List<String> SetBCC{get;set;}
Public String CaseId {get;set;}
public String Selec {get;set;}
public List<String> liststatus {get;set;}
public boolean flag {set;get;}
public string Str2;
public String test;
Public List<string> listall {get;set;}
public Attachment attachment {
get {
if (attachment == null)
attachment = new Attachment();
return attachment;
}
set;
}
public CommenttoEmail(apexpages.StandardController std)
{
liststatus=new List<string>{'New','Working','Escalated','Closed Successful'};
flag=false;
CaseId=ApexPages.CurrentPage().getParameters().get('Id');
listall=new List<String>();
SetTo=new List<String>{};
SetCC=new List<String>{};
SetBCC=new List<String>{};
}
public void senttoEmail()
{
Case cse = [select id ,CaseNumber ,Status,ContactEmail,subject from case where id=:caseId];
SetTo=Set_To.split(',');
}
public void bccEmail()
{
SetBCC=Set_bcc.split(',');
}
public void ccEmail()
{
SetCC=Set_cc.split(',');
}
public void ss()
{
senttoEmail();
bccEmail();
ccEmail();
}
public void attachemail()
{
listall.addAll(SetTo);
listall.addAll(SetBCC);
listall.addAll(SetCC);
}
public pagereference createCaseComment(){
ss();
upload();
attachemail();
sendingEmail();
ChangeStatus();
Case cse = [select id ,CaseNumber ,Status, Contact.name,Account.name,subject from case where id=:caseId];
String ss=string.join(listall, ',');
String Str1='\n\n';
String Str0='[Recipients:' +ss+']';
String Str3=cse.Contact.name+',\n\n';
String Reg='\n\n\n Sincerely,\n'+cse.Contact.name+'\n'+cse.Account.name;
Str2=Str0+Str1+Str3+Commentbody+Reg;
CaseComment cc = new CaseComment(ParentId = cse.Id,CommentBody = str2 , IsPublished=true);
insert cc;
pagereference pg =new pagereference('/'+CaseId);
return pg;
}
public PageReference sendingEmail()
{
upload();
Case cse = [select id ,CaseNumber ,Status, Contact.name,Account.name,subject from case where id=:caseId];
String ss=string.join(listall, ',');
String Str3=cse.Contact.name+',\n\n';
String Reg='\n\n\n Sincerely,\n'+cse.Contact.name+'\n'+cse.Account.name;
Str2=Str3+Commentbody+Reg;
List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
for (Attachment a : [select Name, Body, BodyLength from Attachment where ParentId = :caseId]){
Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
efa.setFileName(a.Name);
efa.setBody(a.Body);
fileAttachments.add(efa);
}
try{
Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage();
semail.setToAddresses(SetTo);
semail.setBccAddresses(SetBCC);
semail.setCcAddresses(SetCC);
semail.setSubject(cse.Subject);
semail.setPlainTextBody(Str2);
semail.setFileAttachments(fileAttachments);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {semail});
}catch(exception e)
{}
return null;
}
public pagereference redirectCasePage()
{
CaseId=ApexPages.CurrentPage().getParameters().get('Id');
pagereference pg =new pagereference('/'+CaseId);
return pg;
}
public void ChangeStatus()
{
List<Case> cse = [select id ,CaseNumber ,Status,subject from case where id=:caseId];
for(Case c:cse){
if(selec=='New')
{
c.Status='New';
}
if(selec=='Working')
{
c.Status='Working';
}
if(selec=='Escalated')
{
c.Status='Escalated';
}
if(selec=='Closed successful')
{
c.Status='Closed successful';
}
update c;
}
}
public List<SelectOption> getCaseStatus()
{
List<SelectOption> optlist=new List<SelectOption>();
Case cse = [select id ,CaseNumber ,Status,subject from case where id=:caseId];
optlist.add(new SelectOption(cse.Status,cse.Status));
for(String s:liststatus)
{
optlist.add(new SelectOption(s,s));
}
return optlist;
}
public PageReference upload() {
attachment.OwnerId = UserInfo.getUserId();
attachment.ParentId = CaseId;
attachment.IsPrivate = true;
attachment.ContentType = 'image/jpeg';
try {
insert attachment;
} catch (DMLException e) {
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading attachment'));
return null;
} finally {
attachment = new Attachment();
}
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Attachment uploaded successfully'));
return null;
}
}
- devloper sfdc
- November 16, 2018
- Like
- 0
I need to write test class for casecomment trigger
trigger UpdLstMdfyDtFrmComt on CaseComment (before insert , before update) {
Map<Id, Case> cases = new Map<Id, Case>();
DateTime dT = System.now();
Date myDate = date.newinstance(dT.year(), dT.month(), dT.day());
for(CaseComment record:Trigger.new)
{
if (record.ParentId != null)
{
cases.put(record.ParentId, new Case(Id=record.ParentId, LastModifyDateCmtCas__c=myDate));
}
}
update cases.values();
}
Map<Id, Case> cases = new Map<Id, Case>();
DateTime dT = System.now();
Date myDate = date.newinstance(dT.year(), dT.month(), dT.day());
for(CaseComment record:Trigger.new)
{
if (record.ParentId != null)
{
cases.put(record.ParentId, new Case(Id=record.ParentId, LastModifyDateCmtCas__c=myDate));
}
}
update cases.values();
}
- devloper sfdc
- October 16, 2018
- Like
- 0
Error Display "Attempt to de-reference a null object"
Hello All ,
I am getting error Message "Attempt to de-reference a null object" when we run "permissionSett()" this method .
My Apex code is here please help me .
public class DeepcloneUser {
Public String fName {set;get;}
Public String lName {set;get;}
Public static String eMail {set;get;}
public static Id conId {set;get;}
Public Contact c;
Public static User u;
public Static User[] uid;
Public set<Id> CloneId;
Public static Set<Id> permiId;
public static PermissionSetAssignment[] Listperm;
public static list<PermissionSetAssignment> Listpermission;
public DeepcloneUser(ApexPages.StandardController stdController) {
// conId=apexpages.currentpage().getparameters().get('id');
CloneId=new Set<Id>();
permiId=new Set<Id>();
Listpermission=new List<PermissionSetAssignment>();
}
@future
Public static void CreateUser(String fname,String LName,String Email,Id Cid,String Pid ,String nickname)
{
u=new user();
// String alias = 'aaa';
u.FirstName=fname;
u.LastName=lName;
u.Email=eMail;
u.Username=email;
u.ProfileId=Pid;
u.ContactId=cid;
//u.CommunityNickname=attributes.get('u.CommunityNickname');
u.CommunityNickname=nickname;
u.EmailEncodingKey='UTF-8';
u.LocaleSidKey='en_US';
u.Alias='snsa';
u.LanguageLocaleKey='en_US';
u.TimeZoneSidKey='GMT';
insert u;
}
@InvocableMethod
public static void GetDetail()
{
conId=apexpages.currentpage().getparameters().get('id');
Contact[] co=[select id,firstName,Community_Nickname__c, Clone_Contact__c,LastName, Email from contact where id=:conId limit 1];
//String cCid=co[0].id;
String ffname=co[0].firstName;
String llname=co[0].lastName;
String eemail=co[0].email;
String nnickname=co[0].Community_Nickname__c;
// String pfid='00ed00000019frTAAQ';
String Clone=co[0].Clone_Contact__c;
uid=[select id, profileid from user where contactid=:Clone limit 1];
String pfid=uid[0].profileid;
CreateUser(ffname,ffname,eemail,conId,pfid,nnickname);
//Listperm=[SELECT Id FROM PermissionSetAssignment WHERE AssigneeId=:uid[0].id];
}
public void permissionSett()
{
List<PermissionSetAssignment> lstp=new list<PermissionSetAssignment>();
List<PermissionSetAssignment> lstcloUserpert=[SELECT Id, PermissionSet.Name,AssigneeId
FROM PermissionSetAssignment
WHERE AssigneeId = :uid[0].id];
conId=apexpages.currentpage().getparameters().get('id');
User Userid=[select id from user where contactId=:ConId limit 1];
for(PermissionSetAssignment p:lstcloUserpert)
{
PermissionSetAssignment pmr=new PermissionSetAssignment();
pmr.AssigneeId=userId.id;
pmr.PermissionSetId=p.id;
lstp.add(pmr);
}
upsert lstp;
}
}
I am getting error Message "Attempt to de-reference a null object" when we run "permissionSett()" this method .
My Apex code is here please help me .
public class DeepcloneUser {
Public String fName {set;get;}
Public String lName {set;get;}
Public static String eMail {set;get;}
public static Id conId {set;get;}
Public Contact c;
Public static User u;
public Static User[] uid;
Public set<Id> CloneId;
Public static Set<Id> permiId;
public static PermissionSetAssignment[] Listperm;
public static list<PermissionSetAssignment> Listpermission;
public DeepcloneUser(ApexPages.StandardController stdController) {
// conId=apexpages.currentpage().getparameters().get('id');
CloneId=new Set<Id>();
permiId=new Set<Id>();
Listpermission=new List<PermissionSetAssignment>();
}
@future
Public static void CreateUser(String fname,String LName,String Email,Id Cid,String Pid ,String nickname)
{
u=new user();
// String alias = 'aaa';
u.FirstName=fname;
u.LastName=lName;
u.Email=eMail;
u.Username=email;
u.ProfileId=Pid;
u.ContactId=cid;
//u.CommunityNickname=attributes.get('u.CommunityNickname');
u.CommunityNickname=nickname;
u.EmailEncodingKey='UTF-8';
u.LocaleSidKey='en_US';
u.Alias='snsa';
u.LanguageLocaleKey='en_US';
u.TimeZoneSidKey='GMT';
insert u;
}
@InvocableMethod
public static void GetDetail()
{
conId=apexpages.currentpage().getparameters().get('id');
Contact[] co=[select id,firstName,Community_Nickname__c, Clone_Contact__c,LastName, Email from contact where id=:conId limit 1];
//String cCid=co[0].id;
String ffname=co[0].firstName;
String llname=co[0].lastName;
String eemail=co[0].email;
String nnickname=co[0].Community_Nickname__c;
// String pfid='00ed00000019frTAAQ';
String Clone=co[0].Clone_Contact__c;
uid=[select id, profileid from user where contactid=:Clone limit 1];
String pfid=uid[0].profileid;
CreateUser(ffname,ffname,eemail,conId,pfid,nnickname);
//Listperm=[SELECT Id FROM PermissionSetAssignment WHERE AssigneeId=:uid[0].id];
}
public void permissionSett()
{
List<PermissionSetAssignment> lstp=new list<PermissionSetAssignment>();
List<PermissionSetAssignment> lstcloUserpert=[SELECT Id, PermissionSet.Name,AssigneeId
FROM PermissionSetAssignment
WHERE AssigneeId = :uid[0].id];
conId=apexpages.currentpage().getparameters().get('id');
User Userid=[select id from user where contactId=:ConId limit 1];
for(PermissionSetAssignment p:lstcloUserpert)
{
PermissionSetAssignment pmr=new PermissionSetAssignment();
pmr.AssigneeId=userId.id;
pmr.PermissionSetId=p.id;
lstp.add(pmr);
}
upsert lstp;
}
}
- devloper sfdc
- September 06, 2018
- Like
- 0
I am getting DML operation error in SamlJitHandler
Hi All,
I am getting DML opration error In SamlJitHandler During parameter passing from identity provider (3rd Party) .
include parameter here(UserName,AccountOwner,ContactLastName,ContactFirstName,ContactEmail,userLastName,userFirstName,UserFederationidentyfier,AccountNumber,userCommunityNickName)
I am using Controller is
global class StandardUserHandler implements Auth.SamlJitHandler {
private class JitException extends Exception{}
private void handleUser(boolean create, User u, Map<String, String> attributes, String federationIdentifier, boolean isStandard)
{
if(create && attributes.containsKey('User.Username'))
{
u.Username = attributes.get('User.Username');
}
if(create)
{
if(attributes.containsKey('User.FederationIdentifier'))
{
u.FederationIdentifier = attributes.get('User.FederationIdentifier');
} else
{
u.FederationIdentifier = federationIdentifier;
}
}
if(attributes.containsKey('User.ProfileId'))
{
String profileId = attributes.get('User.ProfileId');
Profile p = [SELECT Id FROM Profile WHERE Id=:profileId]; u.ProfileId = p.Id;
}
if(attributes.containsKey('User.UserRoleId'))
{
String userRole = attributes.get('User.UserRoleId');
UserRole r = [SELECT Id FROM UserRole WHERE Id=:userRole];
u.UserRoleId = r.Id; } if(attributes.containsKey('User.Phone'))
{
u.Phone = attributes.get('User.Phone');
}
if(attributes.containsKey('User.Email'))
{
u.Email = attributes.get('User.Email');
}
if(!create)
{
update(u);
}
}
private void handleJit(boolean create, User u, Id samlSsoProviderId, Id communityId, Id portalId, String federationIdentifier, Map<String, String> attributes, String assertion) {
if(communityId != null || portalId != null)
{
String account = handleAccount(create, u, attributes); handleContact(create, account, u, attributes); handleUser(create, u, attributes, federationIdentifier, false);
} else
{
handleUser(create, u, attributes, federationIdentifier, true);
}
}
global User createUser(Id samlSsoProviderId, Id communityId, Id portalId, String federationIdentifier, Map<String, String> attributes, String assertion) {
User u = new User(); handleJit(true, u, samlSsoProviderId, communityId, portalId, federationIdentifier, attributes, assertion); return u;
}
global void updateUser(Id userId, Id samlSsoProviderId, Id communityId, Id portalId, String federationIdentifier, Map<String, String> attributes, String assertion)
{
User u = [SELECT Id FROM User WHERE Id=:userId]; handleJit(false, u, samlSsoProviderId, communityId, portalId, federationIdentifier, attributes, assertion);
}
}
Please suggest what to be changes needed in this controller ;
I am getting DML opration error In SamlJitHandler During parameter passing from identity provider (3rd Party) .
include parameter here(UserName,AccountOwner,ContactLastName,ContactFirstName,ContactEmail,userLastName,userFirstName,UserFederationidentyfier,AccountNumber,userCommunityNickName)
I am using Controller is
global class StandardUserHandler implements Auth.SamlJitHandler {
private class JitException extends Exception{}
private void handleUser(boolean create, User u, Map<String, String> attributes, String federationIdentifier, boolean isStandard)
{
if(create && attributes.containsKey('User.Username'))
{
u.Username = attributes.get('User.Username');
}
if(create)
{
if(attributes.containsKey('User.FederationIdentifier'))
{
u.FederationIdentifier = attributes.get('User.FederationIdentifier');
} else
{
u.FederationIdentifier = federationIdentifier;
}
}
if(attributes.containsKey('User.ProfileId'))
{
String profileId = attributes.get('User.ProfileId');
Profile p = [SELECT Id FROM Profile WHERE Id=:profileId]; u.ProfileId = p.Id;
}
if(attributes.containsKey('User.UserRoleId'))
{
String userRole = attributes.get('User.UserRoleId');
UserRole r = [SELECT Id FROM UserRole WHERE Id=:userRole];
u.UserRoleId = r.Id; } if(attributes.containsKey('User.Phone'))
{
u.Phone = attributes.get('User.Phone');
}
if(attributes.containsKey('User.Email'))
{
u.Email = attributes.get('User.Email');
}
if(!create)
{
update(u);
}
}
private void handleJit(boolean create, User u, Id samlSsoProviderId, Id communityId, Id portalId, String federationIdentifier, Map<String, String> attributes, String assertion) {
if(communityId != null || portalId != null)
{
String account = handleAccount(create, u, attributes); handleContact(create, account, u, attributes); handleUser(create, u, attributes, federationIdentifier, false);
} else
{
handleUser(create, u, attributes, federationIdentifier, true);
}
}
global User createUser(Id samlSsoProviderId, Id communityId, Id portalId, String federationIdentifier, Map<String, String> attributes, String assertion) {
User u = new User(); handleJit(true, u, samlSsoProviderId, communityId, portalId, federationIdentifier, attributes, assertion); return u;
}
global void updateUser(Id userId, Id samlSsoProviderId, Id communityId, Id portalId, String federationIdentifier, Map<String, String> attributes, String assertion)
{
User u = [SELECT Id FROM User WHERE Id=:userId]; handleJit(false, u, samlSsoProviderId, communityId, portalId, federationIdentifier, attributes, assertion);
}
}
Please suggest what to be changes needed in this controller ;
- devloper sfdc
- June 26, 2018
- Like
- 0
issue in test class please help
Hello Frinds ,
please help me to wirte test class for below code .
public class ProductEntry{
public List<sObjectWrapper> wrappers{get;set;}
Public string selectedname{get;set;}
public String descr{get;set;}
public Decimal Qty{get;set;}
public Integer rowNo {set;get;}
public boolean isSelected{get;set;}
public boolean flag=true;
public boolean Oppflag=true;
public boolean flag1{get;set;}
public id Oppid {get;set;}
public string bundle{get;set;}
public Map<String,String> Bundleprice {get;set;}
public List<PricebookEntry> PriceEntry{get;set;}
public List<OpportunityLineItem>Optyline{get;set;}
public ProductEntry(ApexPages.StandardController stdController) {
PriceEntry=new List<PricebookEntry>();
wrappers=new List<sObjectWrapper>();
Bundleprice=new map<String,String>();
Optyline=new List<OpportunityLineItem>();
// Unit_of_Measure=new List<String>();
flag1=true;
}
public void hideSection()
{
if(flag1==true)
{
flag1=false;
}
else {flag1=true;}
}
public List<sObjectWrapper> getData()
{
flag=true;
wrappers.clear();
Set<Id> productIds = New Set<Id>();
Set<Id> PriceEntryIds= new Set<Id>();
Set<Id> PriceBookIds= new Set<Id>();
List<sObjectWrapper> wrapper = new List<sObjectWrapper>();
for(Product2 p : [select id,name,Units_of_Measure__c from product2 where Bundle_Type__c=:selectedname]){
productIds.add(p.Id);
}
for(PriceBook2 pb:[select id from pricebook2 where name In('One Stop Shop')])
{
PriceBookIds.add(pb.id);
}
for(PriceBookEntry pp:[SELECT id,Name,FFUnit_of_measure__c,Qty__c,Pricebook2Id,Product2Id,ProductCode,UnitPrice,UseStandardPrice FROM PricebookEntry WHERE Pricebook2Id=:PriceBookIds and product2Id=:productIds])
{
wrappers.add(new sObjectWrapper(pp,true));
}
return null;
}
public void addlist()
{
PriceEntry.clear();
for(sObjectWrapper wrap : wrappers){
/*Check if record is selected*/
if(wrap.isSelected){
PriceEntry.add(wrap.prod);
}
}
}
public void AddtoOpty()
{
addlist();
if(flag==true)
{
for(PricebookEntry prc:PriceEntry)
{
OpportunityLineItem opt=new OpportunityLineItem();
Oppid = apexpages.currentpage().getparameters().get('id');
opt.OpportunityId=Oppid;
opt.PricebookEntryId=prc.id;
opt.Unit_of_measure__c=prc.FFUnit_of_measure__c;
opt.Product2Id=prc.product2id;
opt.UnitPrice=prc.UnitPrice;
opt.Quantity=prc.Qty__c;
opt.Description=descr;
Optyline.add(opt);
}
// insert optyline;
PriceEntry.clear();
flag=false;
}
}
public void addtOpp()
{
if(Oppflag==true)
{
if(Optyline.size()>0)
{
insert Optyline;
}
} Oppflag=false;
}
//
public pagereference urlre()
{
Oppid = apexpages.currentpage().getparameters().get('id');
pagereference pg =new pagereference('/'+Oppid);
//pg.setRedirect(true);
return pg;
}
//
Public List<string> optionList=new List<String>{'Basic','Advanced','Premium','Add-Ons'};
Public List<Selectoption> getselectedaccnamefields(){
List<Selectoption> lstnamesel = new List<selectoption>();
lstnamesel.add(new selectOption('', '-All Products-'));
for(String s :optionList){
lstnamesel.add(new selectoption(s,s));
}
return lstnamesel;
}
public class sObjectWrapper
{
public boolean isSelected{get;set;}
public PricebookEntry prod{get;set;}
public sObjectWrapper(PricebookEntry prod,Boolean isSelected){
this.prod = prod;
this.isSelected = isSelected;
}
}
}
please help me to wirte test class for below code .
public class ProductEntry{
public List<sObjectWrapper> wrappers{get;set;}
Public string selectedname{get;set;}
public String descr{get;set;}
public Decimal Qty{get;set;}
public Integer rowNo {set;get;}
public boolean isSelected{get;set;}
public boolean flag=true;
public boolean Oppflag=true;
public boolean flag1{get;set;}
public id Oppid {get;set;}
public string bundle{get;set;}
public Map<String,String> Bundleprice {get;set;}
public List<PricebookEntry> PriceEntry{get;set;}
public List<OpportunityLineItem>Optyline{get;set;}
public ProductEntry(ApexPages.StandardController stdController) {
PriceEntry=new List<PricebookEntry>();
wrappers=new List<sObjectWrapper>();
Bundleprice=new map<String,String>();
Optyline=new List<OpportunityLineItem>();
// Unit_of_Measure=new List<String>();
flag1=true;
}
public void hideSection()
{
if(flag1==true)
{
flag1=false;
}
else {flag1=true;}
}
public List<sObjectWrapper> getData()
{
flag=true;
wrappers.clear();
Set<Id> productIds = New Set<Id>();
Set<Id> PriceEntryIds= new Set<Id>();
Set<Id> PriceBookIds= new Set<Id>();
List<sObjectWrapper> wrapper = new List<sObjectWrapper>();
for(Product2 p : [select id,name,Units_of_Measure__c from product2 where Bundle_Type__c=:selectedname]){
productIds.add(p.Id);
}
for(PriceBook2 pb:[select id from pricebook2 where name In('One Stop Shop')])
{
PriceBookIds.add(pb.id);
}
for(PriceBookEntry pp:[SELECT id,Name,FFUnit_of_measure__c,Qty__c,Pricebook2Id,Product2Id,ProductCode,UnitPrice,UseStandardPrice FROM PricebookEntry WHERE Pricebook2Id=:PriceBookIds and product2Id=:productIds])
{
wrappers.add(new sObjectWrapper(pp,true));
}
return null;
}
public void addlist()
{
PriceEntry.clear();
for(sObjectWrapper wrap : wrappers){
/*Check if record is selected*/
if(wrap.isSelected){
PriceEntry.add(wrap.prod);
}
}
}
public void AddtoOpty()
{
addlist();
if(flag==true)
{
for(PricebookEntry prc:PriceEntry)
{
OpportunityLineItem opt=new OpportunityLineItem();
Oppid = apexpages.currentpage().getparameters().get('id');
opt.OpportunityId=Oppid;
opt.PricebookEntryId=prc.id;
opt.Unit_of_measure__c=prc.FFUnit_of_measure__c;
opt.Product2Id=prc.product2id;
opt.UnitPrice=prc.UnitPrice;
opt.Quantity=prc.Qty__c;
opt.Description=descr;
Optyline.add(opt);
}
// insert optyline;
PriceEntry.clear();
flag=false;
}
}
public void addtOpp()
{
if(Oppflag==true)
{
if(Optyline.size()>0)
{
insert Optyline;
}
} Oppflag=false;
}
//
public pagereference urlre()
{
Oppid = apexpages.currentpage().getparameters().get('id');
pagereference pg =new pagereference('/'+Oppid);
//pg.setRedirect(true);
return pg;
}
//
Public List<string> optionList=new List<String>{'Basic','Advanced','Premium','Add-Ons'};
Public List<Selectoption> getselectedaccnamefields(){
List<Selectoption> lstnamesel = new List<selectoption>();
lstnamesel.add(new selectOption('', '-All Products-'));
for(String s :optionList){
lstnamesel.add(new selectoption(s,s));
}
return lstnamesel;
}
public class sObjectWrapper
{
public boolean isSelected{get;set;}
public PricebookEntry prod{get;set;}
public sObjectWrapper(PricebookEntry prod,Boolean isSelected){
this.prod = prod;
this.isSelected = isSelected;
}
}
}
- devloper sfdc
- June 04, 2018
- Like
- 0