• Krish N
  • NEWBIE
  • 70 Points
  • Member since 2018

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 43
    Questions
  • 31
    Replies
Hello Guys, I'm new to Apex Triggers. I need help in writing a test class for the below Trigger. Whenever a platform event message (unique Id) is published from a lightning flow, the trigger updates the Service Appoinmtment record whose Id is the event message. Please let me know if I should make any changes to the trigger. 
trigger platformtrigger on Notification__e (after insert) {
    for(notification__e ev: Trigger.new)
        
    {
        
        ServiceAppointment SADispatched = [SELECT Id, ParentRecordId FROM ServiceAppointment WHERE Id = :ev.message__c];
        SADispatched.description = 'Automate Process';
        SADispatched.FSL__Auto_Schedule__c = true;
        
        update SADispatched;    

        
    }
}
Hello All, When ever I create a Service Report on the WO in the FSL mobile app, its getting created on the Service Appointment related list but on the WO. Our requirement is to create it on the WO. I tried the standard Create Service Request button and also tried through a flow with an app extension (Scoped to WorkOrder) but none of them generates a Service report on the Work Order. Any suggestion is appreciated.
  • September 23, 2019
  • Like
  • 0
Hello, We have a requirement in our FSL mobile flow that on screen elements (text variables) should only be displayed if certain fields are checked which is similar to rendered in vfpages.
For ex: We have eleven product checkbox fields (each on screen variable representing each field), we want to display elements only if the product fields are checked. If four of the eleven fields are checked, we want to display only four of variables on screen. If it is only one or two fields instead of eleven, we would've used decision element but since it is 11 fields, that is not a possible option. I can use aura components but components are not supported on the FSL app yet. Any suggestions?
We are implementing Field service Lightning. We have a requirement in our FSL mobile flow that on screen elements (text variables) should only be displayed if certain fields are checked which is similar to rendered in vfpages.
For ex: We have eleven product checkbox fields (each on screen variable representing each field), we want to display elements only if the product fields are checked. If four of the eleven fields are checked, we want to display only four of variables on screen. If it is only one or two fields instead of eleven, we would've used decision element but since it is 11 fields, that is not a possible option. I can use aura components but components are not supported on the FSL app yet. Any suggestions?
Hello all, I have a multi-level approval process which locks the record from editing when it is initially submitted and locks the record as a final approval action (except for current approver and sys admin). We have a visual force page to create the cases. When I log in as a test user who has no association with the created record which is middle of an approval process, I was unable to edit the record in standard/layout view as expected. However, when I open the record in visual force page, I was able to edit the record even though I'm not the current approver or an admin. He doesn't have modify all permission either. I don't get the 'record is locked' message, it just saves with the changes. How do I fix it? Wouldn’t the vf page respect approval process locked action. 
We are currently moving to Field service lightning, we have Apex email services which uses Messaging.InboundEmailHandler instance to auto creates service cases from incoming emails from our customers. I tried creating cases through email in FSL sandbox but it won't create any cases, I don't even see any trace in the debug logs and the surprising part is, when ever I try to create a case, it is actually trying to create cases in our old classic sandbox (based on debug logs). How do I tackle it? 80% of our cases are created currently through through Apex email services.
Hello Guys, We have around 10 case record types. We have one specific record type for our service cases. We want the cases to be assigned an auto case number whenever a new case is created. Auto case number shouldn't be assigned when cases are created in other record types. For ex: If there are 8 cases under this record type, I want the 9th case to to have SR-009 as the custom case number isntead of SR-020, assuming other recordtype cases are created. How do I acheive it?
We have a multi level approval process involving different users for our service cases. The record would be locked from editing for all the users except the current approver and the admin of course. However, duirng the approval process, for some cases, we may have to create parent-child reference to an old service case which would change the status of the current case to "Reference". I want the record to be unlocked for users when the status is in "Reference". How do I achieve it? I have few VRs set up which would lock the record during this status but no can edit the record at the moment as the record is locked. Can any one please suggest what needs to be done. Thank you!
Hello Guys, We have recently moved to Salesforce Field Service Lightning. Our requirement is to create location records from accounts. We also want to use the Google search address funictionality (available in the address object) while the location record is being created. We want to use the lightning flows to address the requirement. How do we acheive it? Could someone please guide.  
I've a VF page to create cases. It has lot of workflows and VRs associated with it. While saving a record, if there's a VR error, the message shows at the top of page, however, I'm also able to see Save success message beneath the VR message. How do I restrict save success message to be displayed only when the record is actually saved? Please refer the attached screenshot and controller. 
User-added image
public class QRreportController

/* --------------------- variable for the standard controller ------------------------------- */ 
{
    private ApexPages.StandardController std;        
/* --------------------- variable for this case ------------------------------- */     
    public Case c {get; set;}

/*  -------------------- standard work order controller  ----------------------------  */            
    public QRreportController (ApexPages.StandardController stdCtrl)
    {
        // prepopulates some fields on page load
        this.c = (Case)stdCtrl.getRecord();
        Map<ID,Schema.RecordTypeInfo> rt_Map = Case.sObjectType.getDescribe().getRecordTypeInfosById();
        Id RecordTypeIdCase = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Quality Report Case').getRecordTypeId();
        Id rtId = RecordTypeIdCase;
        c.RecordTypeId=rtId;
        c.AccountId=System.currentPageReference().getParameters().get('AccountId');
        std=stdCtrl;
    }

/* --------------------- Get Case ------------------------------- */     
    public Case getCase()
    {       
     return (Case) std.getRecord(); 
    }

  public Attachment attachment {
  get {
      if (attachment == null)
        attachment = new Attachment();
      return attachment;
    }
  set;
  }

/* --------------------- Save and Exit method ------------------------------- */
    public PageReference saveAndExit()
    {
        std.save();
        PageReference pageRef1 = new PageReference('/' + getCase().id);
        return pageRef1;

    }
/* --------------------- Edit method ------------------------------- */
    public PageReference edit1()
    {
        PageReference pageRef2 = Page.QRcaseEdit;
        pageRef2.getParameters().put('id', getCase().id);
        pageRef2.getParameters().put('AccountId', getCase().AccountId);
        return pageRef2;
    }


/* --------------------- Quick Save method ------------------------------- */
public PageReference save()
    {
        std.save();
        PageReference pageRef3 = Page.QRcase;
       ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'SUCCESS!  Changes saved.'));

        pageRef3.getParameters().put('id', getCase().id);
        pageRef3.getParameters().put('AccountId',getCase().AccountId);
        return PageRef3;

    }


     public PageReference upload() {

    attachment.OwnerId = UserInfo.getUserId();
    attachment.ParentId = getCase().Id ; // 
    attachment.IsPrivate = true;

    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;
  }

}

ease refer to the below screenshot. 
We have a self related parent-child lookup realtionship on the case object. One child can have only one parent and one parent can have many child records. I want to create a process builder which will update the child records status (update to parent status) and sends an email to child record creator when parent record status is updated. I'm having trouble creating the logic. I get can't save record errors or saves the record but won't update the child or sends an email. The child relationship name is: Associatedcases and is related to cases. 
Hello, I've a parent-child relationship for case object. When a new case is created, if the problem type is similar to that of already created case, the old case has to be used as a reference (parent) and the new case will be an associate case (child) of the old case. Once the reference is made, the child case will be locked from editing, the child case status has to be auto updated whenever the parent case status changes, the child case has to be set the same status as of parent until the parent case is closed, which obviously closes the child case. I've tried using Process builder but I'm getting errors. Is there any declarative approach to achieve the requriement. I don't want to use trigger.  
I've set up Apex email services to automate case creation from emails. We have around 25 customers with different locations who sends emails for service request.
Our current process is such that our CSRs have access to service request email address. From that address they create cases from the inbox. Then they move the email to another folder once case is created (to ensure duplicate cases are not created by other users).
With the Email services being set up for the same email address, how do I ensure there are no duplicate cases created by the users for emails processed by Apex? Email service has only been enabled for 10 of our customers.
Hello all, We have a location object based our customer accounts. There are thousands of location records for a single account. I've to mass update a text field in those location records based on the location name.
For ex:
If the location name for account "Sample Coorporation" is Sample T0274, I want to update a text field to T0274. Lets say this account has 1500 locations with names such as Sample T0001, Sample T0002, Sample T0003 .......... Sample T1500. I want to update a text field with values T0001 for Sample T0001, T0002 for Sample T0002 ........ T1500 for Sample T1500 location. What is an effective way to acheive this?
 
Hello Guys, Our requirement is to process incoming email from a particular email address and create a case. My class is working fine but the test class is failing with the List has no rows to assignment error. Can any one please help me. Thank you!
*** Apex Email services class***
global Class EtoCkroger implements Messaging.InboundEmailHandler {

// Instantiate variables that we will need for handling this email
   
String location;
String problem;
Integer locationIdx;
Integer problemIdx;
String locationFinal;
String needFinal;
String serviceFinal;
String tradeFinal;
String InboxFinal;
String initiatorFinal;
String TimeFinal;
String poFinal;
String phoneFinal;
String warrantyFinal;
String descriptionFinal;
String orderFinal;
String criticalFinal;
String productFinal;   
String problemFinal;
String machineFinal;
String krogerFinal;
String siteFinal;
global Messaging.InboundEmailResult handleInboundEmail
           (Messaging.InboundEmail email, Messaging.InboundEnvelope envelope){  
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
 if (email.fromaddress =='shashank.sfdev@gmail.com') //// Kroger locations 
               {
         
String[] bodySplitted = email.PlainTextBody.split('\n');


krogerFinal = email.subject.substringAfter(')').normalizespace();
poFinal = email.plainTextBody.substringBetween('Call/Action #' , 'Call/Action Type/Status').remove('*').remove('(Include this # on Invoice)').normalizespace();
initiatorFinal = email.plainTextBody.substringBetween('Point of Contact', 'Billing Address').remove('*').normalizespace(); 
tradeFinal = email.plainTextBody.substringBetween('Symptom' , 'Notes').remove('*').normalizespace();
problemFinal = email.plainTextBody.substringBetween('Notes' , 'Service Window').remove('*').remove('Service Requirements:').normalizespace(); 
criticalFinal = email.plainTextBody.substringBetween('Severity' , 'Service').remove('*').normalizespace();
productFinal = email.plainTextBody.substringBetween('Product' , 'Symptom').remove('*').trim();
orderFinal = email.plainTextBody.substringBetween('Service Window' , 'Start Date/Time').remove('*').normalizespace();
inboxFinal = email.plainTextBody.substringBetween('Start Date/Time' , 'Respond By').remove('*').normalizespace();
timeFinal = email.plainTextBody.substringBetween('Respond By' , 'Complete By').remove('*').normalizespace();
needFinal = email.plainTextBody.substringBetween('Complete By' , 'Please open').remove('*').remove('Special Instructions:').remove('-').normalizespace();                   
descriptionfinal = 'Product: ' + productFinal + '\n' + 'Service Window: ' + orderFinal + '\n' + 'Start Date/Time: ' + inboxFinal + '\n' + 'Respond By: ' + timeFinal + '\n' + 'Complete By: ' + needFinal;                    
                   
Map<ID,Schema.RecordTypeInfo> rt_Map = Case.sObjectType.getDescribe().getRecordTypeInfosById();
Id RecordTypeIdCase = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Service - Managed Service Case').getRecordTypeId();
Id rtId = RecordTypeIdCase;                
 
system.debug('productFinal: ' +productFinal);
system.debug('tradeFinal: ' +tradeFinal);
system.debug('poFinal: ' +poFinal);
system.debug('orderFinal: ' +orderFinal);
system.debug('krogerFinal: ' +krogerFinal);
system.debug('problemFinal: ' +problemFinal);
system.debug('initiatorFinal: ' +initiatorFinal);
system.debug('descriptionfinal: ' +descriptionfinal);
if (krogerFinal != NULL) {
    SVMXC__Site__c [] locArray = [Select Id, Name, SVMXC__Site_Phone__c, SVMXC__Account__r.Id from SVMXC__Site__c where NTT_Legacy_Location_ID__c = :krogerFinal];
            try{      
              
case c= new case();
c.subject= 'BUNNSERVE REQUEST';
c.Case_Type__c= 'Service Request';
c.Origin='Email';
c.Status='new';
c.AccountId = locArray[0].SVMXC__Account__r.Id;
c.SVMXC__Site__c = locArray[0].Id;  
c.RecordTypeId = rtId;    
c.Description= 'Symptom: ' + tradeFinal + '\n' + 'Notes: ' + problemFinal + '\n' + 'Severity: ' + criticalFinal +  + '\n' + descriptionfinal; 
c.KA_PO__c= poFinal;
c.Location_Contact_Name__c = InitiatorFinal; 
c.BSP_Location_Contact_Phone__c = locArray[0].SVMXC__Site_Phone__c;
c.OwnerId = '00G0x000000K0J3';

insert c; 
}
catch(System.dmlException e)
     {System.debug('Error: Unable to create new Case: ' + e);
     }         
      
              }
        else if (krogerFinal == null){
              System.debug('No location was found');    
        }
      
    }   
         
               
return result;

      } // Close handleInboundEmail ()
}
*** TEST CLASS***

@istest (SeeAllData=true)
public class TestEtoCKroger {
    static testMethod void TestEtoCKroger () {
  

       // create a new email and envelope object
Messaging.InboundEmail email = new Messaging.InboundEmail() ;
Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();           
        
   Account acc = new Account();
        acc.Name = 'Test Account';
        acc.BillingStreet = '123  St.';
        acc.BillingCity = 'Springfield';
        acc.BillingState = 'IL';
        acc.BillingPostalCode = '62704';
        insert acc;
        
    SVMXC__Site__c loc = new SVMXC__Site__c();
       loc.Name = 'Test Loc';
       loc.NTT_Metro_Remote__c = 'Zone A';
       loc.SVMXC__Street__c = '123 E Main St.';
       loc.SVMXC__City__c = 'Springfield';
       loc.SVMXC__State__c = 'ILLINOIS';
       loc.SVMXC__Zip__c = '62511';
       loc.SVMXC__Country__c = 'United States';
       loc.NTT_Legacy_Location_ID__c = 'Sample Test';	
       insert loc;

       // setup the data for the email
     email.subject = 'Kroger Service Call Notification 10935174/1 (HIGH) Sample Test';
     env.fromAddress = 'someaddress@email.com';
     email.plainTextBody = 'Test for Kroger template';

      EtoCKroger test=new EtoCKroger ();
      test.handleInboundEmail(email, env);
    Messaging.InboundEmailResult result = test.handleInboundEmail(email, env);
System.assertEquals( result.success , true);
Map<ID,Schema.RecordTypeInfo> rt_Map = Case.sObjectType.getDescribe().getRecordTypeInfosById();
        Id RecordTypeIdCase = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Service - Managed Service Case').getRecordTypeId();
Case c = [select id, SVMXC__Site__r.id, recordtypeId, KA_PO__c, Location_Contact_Name__c, description, BSP_Location_Contact_Phone__c, subject, Case_Type__c, Origin, Status, AccountId from Case where SVMXC__Site__r.Id = :loc.Id ]; 
      

System.assertEquals(c.SVMXC__Site__c, loc.Name);
System.assertEquals(c.SVMXC__Site__r.Id, loc.Id);        
System.assertEquals(c.AccountId, acc.Id);
System.assertEquals(c.subject, 'Test Request');
System.assertEquals(c.recordtypeId, 'RecordTypeIdCase');
System.assertEquals(c.KA_PO__c, '10010101');
System.assertEquals(c.Location_Contact_Name__c, 'Test Man');       
System.assertEquals(c.BSP_Location_Contact_Phone__c, '111 222 3443');
System.assertEquals(c.subject, 'Test Request');
System.assertEquals(c.Case_Type__c, 'Service Test'); 
System.assertEquals(c.Origin, 'Email');
System.assertEquals(c.Status, 'New');  
System.assertEquals(c.description, 'Test description');  
 update c;      

  
    }     
 
}

Here's the email template. I've to query based on the value from the subject and create a case. 

Service Call Notification

Facility Services

Assignment Information:

Call/Action #00035174 / 1 (Include this # on Invoice)
Call/Action Type/StatusTest data
Service Center021 - Central 
AttentionTEST CORP

Customer Details:

LocationStore 990
Street Address1111 Lane; Ft. Wayne, CA 46804
Point of ContactStore Manager
  
Billing Address5960 S Drive;Indianapolis,IN 46100
Billing Phone111-523-4601

Service Call Details:

SeverityHIGH
ServiceProduct 
ProductPREP EQUIPMENT 
EquipNo: N/A
SerialNo: N/A
AssetNo: N/A
SymptomPoor performance
NotesTest notes.

Service Requirements:

Service WindowNo Service window define
Start Date/Time26 JUL 2018 16:07
Respond ByN/A
Complete By23 AUG 2018 16:07

Special Instructions:

  • Please open the attached Acknowledge.html attachment and accept the service call with an ETA or reject with the appropriate reason.
  • Before beginning any work in our store please check in at CUSTOMER SERVICE.
  • Please present company identification and the Service Hub call number to which this visit is in response.
I'm using Apex Email services to create cases. The email subject contains the account name on which, the case has to be created. The first two values of the subject is the account name, How do I extract it from the email subject using strings. Here's how it looks like:

Email Subject: Account P642484 2520 E Avenue S, Work Order 49878979 has a new note. In this subject, Account P642484 is the account name and I want to grab it to use it in my SOQL query. How do I do that?
Hello everyone, I'm having trouble writing the test class for email services class. The functionality is we get automated emails in a particular format for service requests. Incoming email will be parsed through Apex email services and a case will be created. The Apex class is working very well, but I'm unable to succeed in test class. I've looked at various documents and resources online, but it only increased my confusion. Can any one please help me? Thank you!
** This is how the incoming email looks like**

Service Request #: 1-3747513422

RFS State: Waiting for ETA

Vendor: Sample vendor

Vendor Phone: (222) 943-1601

Trade: Sample Equipment

Not to Exceed: $300

Service Need: Replacment

Service Level: Critical - P1

Root Cause: Call Back

Service Requested: 07/26/2018 02:58 PM

Required Arrival Time: 07/26/2018 06:58 PM

Target Completion Date: 07/27/2018 02:58 AM

Email Delivery Time: 07/26/2018 02:58 PM

Client: Test client #230

Address: 1490 S Main
Jefferson, CA 11111

RFS Initiator Name: Test Manager

Client Contact Phone: (111) 451-1686

Client Contact Fax: 

Store Contact: 333-928-3276

Store Number: 230

Below is the Apex class, it's working fine with no errors.
global Class EtoCaseservices implements Messaging.InboundEmailHandler {

// Instantiate variables that we will need for handling this email

String location;
Integer locationIdx;
String locationFinal;
String need;
String Inbox;
String initiator;
String Time;
String po;
String phone;
String order;
String critical;


global Messaging.InboundEmailResult handleInboundEmail
           (Messaging.InboundEmail email, Messaging.InboundEnvelope envelope){  
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
 if (email.fromaddress =='test@gmail.com')
               {


loc = 'Client: ';   
locationIdx = email.plainTextBody.indexOf(location);
String[] bodySplitted = email.PlainTextBody.split('\n');
locationFinal = email.plainTextBody.substring(
                              locationIdx + location.length(), email.plainTextBody.indexOf('\n', locationIdx + location.length()));
String[] locNme = locationFinal.split(' ', 3);
phone = email.plainTextBody.substringBetween('Client Contact Phone: ' , 'Client Contact Fax: ');
Inbox = email.plainTextBody.substringBetween('Email Delivery Time: ', 'Client: ');                
initiator = email.plainTextBody.substringBetween('RFS Initiator Name: ' , 'Client Contact Phone: ');          
Time = email.plainTextBody.substringBetween('Service Requested: ' , 'Email Delivery Time: ');
po = email.plainTextBody.substringBetween('Service Request #: ' , 'RFS State: ');                   
critical = email.plaintextbody.substringBetween('Service Level: ' , 'Root Cause: ');
need = email.plaintextbody.substringBetween('Service Need: ' , 'Service Level: ');
order = email.plaintextbody.substringBetween('Not to Exceed: ' , 'Service Need: '); 
system.debug('locationFinal: ' +locationFinal);
if (locationFinal != NULL) {
    SVMXC__Site__c [] locArray = [Select Id, Name, SVMXC__Account__r.Id from SVMXC__Site__c where Name = :locationFinal];

      try{                   
case c= new case();
c.subject= 'TEST REQUEST';
c.Case_Type__c= 'Service Request';
c.Origin='Email';
c.Status='new';
c.AccountId = locArray[0].SVMXC__Account__r.Id;
c.SVMXC__Site__c = locArray[0].Id;  
c.recordtypeId = '012E0000000oRWX';                
c.Description= critical +  '\n' +  need + '\n' + orderFinal + '\n'  + timeFinal ;
c.KA_PO__c= po;
c.Location_Contact_Name__c = Initiator; 
c.BSP_Location_Contact_Phone__c = phone;
insert c; 
}
catch(System.dmlException e)
     {System.debug('Error: Unable to create new Case: ' + e);
     }         
                    }
        else if (locationFinal == null){
              System.debug('No Location was found');    
        }

    }

return result;

      } // Close handleInboundEmail ()
}

Please check the test class. Resulting in "System.QueryException: List has no rows for assignment to SObject" error.
@istest

public class TestEtoCaseservices {
    static testMethod void TestEtoCaseservices () {

       // create a new email and envelope object
Messaging.InboundEmail email = new Messaging.InboundEmail() ;
Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();           


    Account acc = new Account();
    acc.Name = 'Test Smith';
    insert acc;

    SVMXC__Site__c l = new SVMXC__Site__c(Name='Test Loc', SVMXC__City__c='Detroit', NTT_State__c='MI', SVMXC__Site_Phone__c='313 111 1231', SVMXC__Country__c='United States', NTT_Metro_Remote__c='ZONE A');
    insert l;

       // setup the data for the email
     email.subject = 'Test Loc';
     env.fromAddress = 'someaddress@email.com';
     email.plainTextBody = 'This is just a test email for test class';


      // call the email service class and test it with the data in the testMethod
      EtoCaseservices  testInbound=new EtoCaseservices ();
      testInbound.handleInboundEmail(email, env);
    Messaging.InboundEmailResult result = testInbound.handleInboundEmail(email, env);
System.assertEquals( result.success  ,true);

Case c = [select id, account.id, SVMXC__Site__c, recordtypeId, KA_PO__c, Location_Contact_Name__c, description, BSP_Location_Contact_Phone__c, subject, Case_Type__c, Origin, Status, AccountId from Case where SVMXC__Site__c = :l.Id];

System.assertEquals(c.SVMXC__Site__c, l.Id);
System.assertEquals(c.account.Id, acc.Id);
System.assertEquals(c.recordtypeId, '012E0000000oRWX');
System.assertEquals(c.KA_PO__c, '10010101');
System.assertEquals(c.Location_Contact_Name__c, 'Test Man');       
System.assertEquals(c.BSP_Location_Contact_Phone__c, '111 222 3443');
System.assertEquals(c.subject, 'Test Request');
System.assertEquals(c.Case_Type__c, 'Service Test'); 
System.assertEquals(c.Origin, 'Email');
System.assertEquals(c.Status, 'New');  
System.assertEquals(c.description, 'Test description');  
update c;
    }     

}


 
Hello, I need help in writing test class for the below InboundemailHandler. The functionality is we get automated emails in a particular format for service requests. Incoming email will be parsed through Apex email services and a case will be created. The Apex class is working very well, but I'm not sure how to write the test class. Can any one help me? Thank you!
** This is how the incoming email looks like**

Service Request #: 1-3747513422

RFS State: Waiting for ETA

Vendor: Sample vendor

Vendor Phone: (222) 943-1601

Trade: Sample Equipment

Not to Exceed: $300

Service Need: Replacment

Service Level: Critical - P1

Root Cause: Call Back

Service Requested: 07/26/2018 02:58 PM

Required Arrival Time: 07/26/2018 06:58 PM

Target Completion Date: 07/27/2018 02:58 AM

Email Delivery Time: 07/26/2018 02:58 PM

Client: Test client #230

Address: 1490 S Main
Jefferson, CA 11111

RFS Initiator Name: Test Manager

Client Contact Phone: (111) 451-1686

Client Contact Fax: 

Store Contact: 333-928-3276

Store Number: 230
 
global Class EtoCaseservices implements Messaging.InboundEmailHandler {

// Instantiate variables that we will need for handling this email
   
String location;
Integer locationIdx;
String locationFinal;
String need;
String Inbox;
String initiator;
String Time;
String po;
String phone;
String order;
String critical;


global Messaging.InboundEmailResult handleInboundEmail
           (Messaging.InboundEmail email, Messaging.InboundEnvelope envelope){  
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
 if (email.fromaddress =='test@gmail.com')
               {
                   
                   
loc = 'Client: ';   
locationIdx = email.plainTextBody.indexOf(location);
String[] bodySplitted = email.PlainTextBody.split('\n');
locationFinal = email.plainTextBody.substring(
                              locationIdx + location.length(), email.plainTextBody.indexOf('\n', locationIdx + location.length()));
String[] locNme = locationFinal.split(' ', 3);
phone = email.plainTextBody.substringBetween('Client Contact Phone: ' , 'Client Contact Fax: ');
Inbox = email.plainTextBody.substringBetween('Email Delivery Time: ', 'Client: ');                
initiator = email.plainTextBody.substringBetween('RFS Initiator Name: ' , 'Client Contact Phone: ');          
Time = email.plainTextBody.substringBetween('Service Requested: ' , 'Email Delivery Time: ');
po = email.plainTextBody.substringBetween('Service Request #: ' , 'RFS State: ');                   
critical = email.plaintextbody.substringBetween('Service Level: ' , 'Root Cause: ');
need = email.plaintextbody.substringBetween('Service Need: ' , 'Service Level: ');
order = email.plaintextbody.substringBetween('Not to Exceed: ' , 'Service Need: '); 
system.debug('locationFinal: ' +locationFinal);
if (locationFinal != NULL) {
    SVMXC__Site__c [] locArray = [Select Id, Name, SVMXC__Account__r.Id from SVMXC__Site__c where Name = :locationFinal];
           
      try{                   
case c= new case();
c.subject= 'TEST REQUEST';
c.Case_Type__c= 'Service Request';
c.Origin='Email';
c.Status='new';
c.AccountId = locArray[0].SVMXC__Account__r.Id;
c.SVMXC__Site__c = locArray[0].Id;  
c.recordtypeId = '012E0000000oRWX';                
c.Description= critical +  '\n' +  need + '\n' + orderFinal + '\n'  + timeFinal ;
c.KA_PO__c= po;
c.Location_Contact_Name__c = Initiator; 
c.BSP_Location_Contact_Phone__c = phone;
insert c; 
}
catch(System.dmlException e)
     {System.debug('Error: Unable to create new Case: ' + e);
     }         
                    }
        else if (locationFinal == null){
              System.debug('No Location was found');    
        }
      
    }
              
return result;

      } // Close handleInboundEmail ()
}
I've two vf pages QRCase (output) and QRCaseEdit(input/Edit) which are used to create cases for a specific record type 'Quality Report Case'. I tried writing the test class for controller, but it's failing. I'm getting an "System.NullPointerException: Attempt to de-reference a null object" error. This is stack trace: Class.QRreportController.upload: line 81, column 1 Class.TestQRcasecontroller.TestQRreportController: line 46, column 1
When I remove line 46 from test class, 'controller.upload();' and run it, I'm getting around 63% code coverage. Line 81 from above error refers to : attachment.OwnerId = UserInfo.getUserId();
What am I doing wrong. This is my first attempt at the test class. Please guide me. Thank you!
**VF PAGE CONTROLLER** 

   public class QRreportController
   {
    private ApexPages.StandardController std;        

    public Case c {get; set;}


    public QRreportController (ApexPages.StandardController stdCtrl)
    {
        // prepopulates some fields on page load
        this.c = (Case)stdCtrl.getRecord();
        Map<ID,Schema.RecordTypeInfo> rt_Map = 
      Case.sObjectType.getDescribe().getRecordTypeInfosById();
        Id RecordTypeIdCase = 
     Schema.SObjectType.Case.getRecordTypeInfosByName().get('Quality Report 
      Case').getRecordTypeId();
        Id rtId = RecordTypeIdCase;
        c.RecordTypeId=rtId;



c.AccountId=System.currentPageReference().getParameters().get('AccountId');
        std=stdCtrl;
    }


/* --------------------- Get Case ------------------------------- */     
    public Case getCase()
    {       
     return (Case) std.getRecord(); 
    }

  public Attachment attachment {
  get {
      if (attachment == null)
        attachment = new Attachment();
      return null;
    }
  set;
  }

/* --------------------- Save and Exit method ------------------------------- */
    public PageReference saveAndExit()
    {
        std.save();
        PageReference pageRef1 = new PageReference('/' + getCase().id);
        return pageRef1;

    }
/* --------------------- Edit method ------------------------------- */
    public PageReference edit1()
    {
        PageReference pageRef2 = Page.QRcaseEdit;
        pageRef2.getParameters().put('id', getCase().id);
        pageRef2.getParameters().put('AccountId', getCase().AccountId);
        return pageRef2;
    }


/* --------------------- Quick Save method ------------------------------- */
public PageReference save()
    {
        std.save();
        PageReference pageRef3 = Page.QRcase;
       ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'SUCCESS!  Changes saved.'));

        pageRef3.getParameters().put('id', getCase().id);
        pageRef3.getParameters().put('AccountId',getCase().AccountId);
        return pageRef3;

    }

    public PageReference upload() {

    attachment.OwnerId = UserInfo.getUserId();
    attachment.ParentId = getCase().Id ;
    attachment.IsPrivate = true;

    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;
  }


   }

Below is the test class:
@isTest

public class TestQRcasecontroller {

static testMethod void TestQRreportController () {


Id rtId = [select Id, name from RecordType where name = 'Quality Report 
Case' and SObjectType = 'Case' limit 1].Id;


//create account
//
Account acc = new Account();
acc.Name = 'Test Account';
insert acc;


Id RecordTypeIdCase = 
Schema.SObjectType.Case.getRecordTypeInfosByName().get('Quality Report 
Case').getRecordTypeId();

//create case
Case c = new Case();
//enter details
c.AccountId = acc.Id;
c.RecordTypeId = RecordTypeIdCase;
c.Site_State__c = 'New York';
c.Product_Serial_Number__c = '91-4154';
c.Description = 'Broken filter';
c.QR_Action_Taken__c = 'Basic troubleshoot';    
c.QR_Problem_Type__c = 'Poor beverage taste';
c.QR_Component_Type__c = 'Filter';
c.QR_Occurrence_Rate__c = 'Daily';
c.QR_Severity__c = 'Operates Intermittently';
insert c;


                PageReference pageRef = Page.QRCaseEdit;
pageRef.getParameters().put('Id',c.Id);
pageRef.getParameters().put('AccountId',acc.Id);
Test.setCurrentPageReference(pageRef);

                PageReference pageRef = Page.QRCase;
pageRef.getParameters().put('Id',c.Id);
pageRef.getParameters().put('AccountId',acc.Id);
Test.setCurrentPageReference(pageRef);
 ApexPages.StandardController sc = new ApexPages.StandardController(c);
                QRreportController controller = new QRreportController(sc);

                controller.getCase();
                controller.saveAndExit();
                controller.upload();
                controller.edit1();
                controller.save();
                controller.getCase();

}

}

​​​​​​​
Hello everyone, I'm new to Salesforce. I would appreciate if any one help me how to write test class for my visualforce pages. Below is the controller. I have two visualforce pages QRcase (output) and QRcaseEdit (input/edit). These pages are used to create cases for service related issues of our customers. Could any one please help me with the logic. Thank you!
public class QRreportController

    
   
   
/* --------------------- variable for the standard controller ------------------------------- */ 
{
    private ApexPages.StandardController std;        
/* --------------------- variable for this case ------------------------------- */     
    public Case c {get; set;}

/*  -------------------- standard work order controller  ----------------------------  */            
    public QRreportController (ApexPages.StandardController stdCtrl)
    {
        // prepopulates some fields on page load
        this.c = (Case)stdCtrl.getRecord();
        Map<ID,Schema.RecordTypeInfo> rt_Map = Case.sObjectType.getDescribe().getRecordTypeInfosById();
        Id RecordTypeIdCase = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Quality Report Case').getRecordTypeId();
        Id rtId = RecordTypeIdCase;
        c.RecordTypeId=rtId;
        c.AccountId=System.currentPageReference().getParameters().get('AccountId');
        std=stdCtrl;
    }
    
    
      
          
    
    
    
/* --------------------- Get Case ------------------------------- */     
    public Case getCase()
    {       
     return (Case) std.getRecord(); 
    }

  public Attachment attachment {
  get {
      if (attachment == null)
        attachment = new Attachment();
      return attachment;
    }
  set;
  }

/* --------------------- Save and Exit method ------------------------------- */
    public PageReference saveAndExit()
    {
        std.save();
        PageReference pageRef1 = new PageReference('/' + getCase().id);
        return pageRef1;
    }
/* --------------------- Edit method ------------------------------- */
    public PageReference edit1()
    {
        PageReference pageRef2 = Page.QRcaseEdit;
        pageRef2.getParameters().put('id', getCase().id);
        pageRef2.getParameters().put('AccountId', getCase().AccountId);
        return pageRef2;
    }
    

/* --------------------- Quick Save method ------------------------------- */
public PageReference save()
    {
        std.save();
        PageReference pageRef2 = Page.QRcase;
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'SUCCESS!  Changes saved.'));
    
        pageRef2.getParameters().put('id', getCase().id);
        pageRef2.getParameters().put('AccountId',getCase().AccountId);
        return pageRef2;

    }
   
  

    public PageReference upload() {

    attachment.OwnerId = UserInfo.getUserId();
    attachment.ParentId = getCase().Id ;// the record the file is attached to
    attachment.IsPrivate = true;

    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've set up Apex email services to automate case creation from emails. We have around 25 customers with different locations who sends emails for service request.
Our current process is such that our CSRs have access to service request email address. From that address they create cases from the inbox. Then they move the email to another folder once case is created (to ensure duplicate cases are not created by other users).
With the Email services being set up for the same email address, how do I ensure there are no duplicate cases created by the users for emails processed by Apex? Email service has only been enabled for 10 of our customers.
Hello all, We have a location object based our customer accounts. There are thousands of location records for a single account. I've to mass update a text field in those location records based on the location name.
For ex:
If the location name for account "Sample Coorporation" is Sample T0274, I want to update a text field to T0274. Lets say this account has 1500 locations with names such as Sample T0001, Sample T0002, Sample T0003 .......... Sample T1500. I want to update a text field with values T0001 for Sample T0001, T0002 for Sample T0002 ........ T1500 for Sample T1500 location. What is an effective way to acheive this?
 
Hello Guys, Our requirement is to process incoming email from a particular email address and create a case. My class is working fine but the test class is failing with the List has no rows to assignment error. Can any one please help me. Thank you!
*** Apex Email services class***
global Class EtoCkroger implements Messaging.InboundEmailHandler {

// Instantiate variables that we will need for handling this email
   
String location;
String problem;
Integer locationIdx;
Integer problemIdx;
String locationFinal;
String needFinal;
String serviceFinal;
String tradeFinal;
String InboxFinal;
String initiatorFinal;
String TimeFinal;
String poFinal;
String phoneFinal;
String warrantyFinal;
String descriptionFinal;
String orderFinal;
String criticalFinal;
String productFinal;   
String problemFinal;
String machineFinal;
String krogerFinal;
String siteFinal;
global Messaging.InboundEmailResult handleInboundEmail
           (Messaging.InboundEmail email, Messaging.InboundEnvelope envelope){  
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
 if (email.fromaddress =='shashank.sfdev@gmail.com') //// Kroger locations 
               {
         
String[] bodySplitted = email.PlainTextBody.split('\n');


krogerFinal = email.subject.substringAfter(')').normalizespace();
poFinal = email.plainTextBody.substringBetween('Call/Action #' , 'Call/Action Type/Status').remove('*').remove('(Include this # on Invoice)').normalizespace();
initiatorFinal = email.plainTextBody.substringBetween('Point of Contact', 'Billing Address').remove('*').normalizespace(); 
tradeFinal = email.plainTextBody.substringBetween('Symptom' , 'Notes').remove('*').normalizespace();
problemFinal = email.plainTextBody.substringBetween('Notes' , 'Service Window').remove('*').remove('Service Requirements:').normalizespace(); 
criticalFinal = email.plainTextBody.substringBetween('Severity' , 'Service').remove('*').normalizespace();
productFinal = email.plainTextBody.substringBetween('Product' , 'Symptom').remove('*').trim();
orderFinal = email.plainTextBody.substringBetween('Service Window' , 'Start Date/Time').remove('*').normalizespace();
inboxFinal = email.plainTextBody.substringBetween('Start Date/Time' , 'Respond By').remove('*').normalizespace();
timeFinal = email.plainTextBody.substringBetween('Respond By' , 'Complete By').remove('*').normalizespace();
needFinal = email.plainTextBody.substringBetween('Complete By' , 'Please open').remove('*').remove('Special Instructions:').remove('-').normalizespace();                   
descriptionfinal = 'Product: ' + productFinal + '\n' + 'Service Window: ' + orderFinal + '\n' + 'Start Date/Time: ' + inboxFinal + '\n' + 'Respond By: ' + timeFinal + '\n' + 'Complete By: ' + needFinal;                    
                   
Map<ID,Schema.RecordTypeInfo> rt_Map = Case.sObjectType.getDescribe().getRecordTypeInfosById();
Id RecordTypeIdCase = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Service - Managed Service Case').getRecordTypeId();
Id rtId = RecordTypeIdCase;                
 
system.debug('productFinal: ' +productFinal);
system.debug('tradeFinal: ' +tradeFinal);
system.debug('poFinal: ' +poFinal);
system.debug('orderFinal: ' +orderFinal);
system.debug('krogerFinal: ' +krogerFinal);
system.debug('problemFinal: ' +problemFinal);
system.debug('initiatorFinal: ' +initiatorFinal);
system.debug('descriptionfinal: ' +descriptionfinal);
if (krogerFinal != NULL) {
    SVMXC__Site__c [] locArray = [Select Id, Name, SVMXC__Site_Phone__c, SVMXC__Account__r.Id from SVMXC__Site__c where NTT_Legacy_Location_ID__c = :krogerFinal];
            try{      
              
case c= new case();
c.subject= 'BUNNSERVE REQUEST';
c.Case_Type__c= 'Service Request';
c.Origin='Email';
c.Status='new';
c.AccountId = locArray[0].SVMXC__Account__r.Id;
c.SVMXC__Site__c = locArray[0].Id;  
c.RecordTypeId = rtId;    
c.Description= 'Symptom: ' + tradeFinal + '\n' + 'Notes: ' + problemFinal + '\n' + 'Severity: ' + criticalFinal +  + '\n' + descriptionfinal; 
c.KA_PO__c= poFinal;
c.Location_Contact_Name__c = InitiatorFinal; 
c.BSP_Location_Contact_Phone__c = locArray[0].SVMXC__Site_Phone__c;
c.OwnerId = '00G0x000000K0J3';

insert c; 
}
catch(System.dmlException e)
     {System.debug('Error: Unable to create new Case: ' + e);
     }         
      
              }
        else if (krogerFinal == null){
              System.debug('No location was found');    
        }
      
    }   
         
               
return result;

      } // Close handleInboundEmail ()
}
*** TEST CLASS***

@istest (SeeAllData=true)
public class TestEtoCKroger {
    static testMethod void TestEtoCKroger () {
  

       // create a new email and envelope object
Messaging.InboundEmail email = new Messaging.InboundEmail() ;
Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();           
        
   Account acc = new Account();
        acc.Name = 'Test Account';
        acc.BillingStreet = '123  St.';
        acc.BillingCity = 'Springfield';
        acc.BillingState = 'IL';
        acc.BillingPostalCode = '62704';
        insert acc;
        
    SVMXC__Site__c loc = new SVMXC__Site__c();
       loc.Name = 'Test Loc';
       loc.NTT_Metro_Remote__c = 'Zone A';
       loc.SVMXC__Street__c = '123 E Main St.';
       loc.SVMXC__City__c = 'Springfield';
       loc.SVMXC__State__c = 'ILLINOIS';
       loc.SVMXC__Zip__c = '62511';
       loc.SVMXC__Country__c = 'United States';
       loc.NTT_Legacy_Location_ID__c = 'Sample Test';	
       insert loc;

       // setup the data for the email
     email.subject = 'Kroger Service Call Notification 10935174/1 (HIGH) Sample Test';
     env.fromAddress = 'someaddress@email.com';
     email.plainTextBody = 'Test for Kroger template';

      EtoCKroger test=new EtoCKroger ();
      test.handleInboundEmail(email, env);
    Messaging.InboundEmailResult result = test.handleInboundEmail(email, env);
System.assertEquals( result.success , true);
Map<ID,Schema.RecordTypeInfo> rt_Map = Case.sObjectType.getDescribe().getRecordTypeInfosById();
        Id RecordTypeIdCase = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Service - Managed Service Case').getRecordTypeId();
Case c = [select id, SVMXC__Site__r.id, recordtypeId, KA_PO__c, Location_Contact_Name__c, description, BSP_Location_Contact_Phone__c, subject, Case_Type__c, Origin, Status, AccountId from Case where SVMXC__Site__r.Id = :loc.Id ]; 
      

System.assertEquals(c.SVMXC__Site__c, loc.Name);
System.assertEquals(c.SVMXC__Site__r.Id, loc.Id);        
System.assertEquals(c.AccountId, acc.Id);
System.assertEquals(c.subject, 'Test Request');
System.assertEquals(c.recordtypeId, 'RecordTypeIdCase');
System.assertEquals(c.KA_PO__c, '10010101');
System.assertEquals(c.Location_Contact_Name__c, 'Test Man');       
System.assertEquals(c.BSP_Location_Contact_Phone__c, '111 222 3443');
System.assertEquals(c.subject, 'Test Request');
System.assertEquals(c.Case_Type__c, 'Service Test'); 
System.assertEquals(c.Origin, 'Email');
System.assertEquals(c.Status, 'New');  
System.assertEquals(c.description, 'Test description');  
 update c;      

  
    }     
 
}

Here's the email template. I've to query based on the value from the subject and create a case. 

Service Call Notification

Facility Services

Assignment Information:

Call/Action #00035174 / 1 (Include this # on Invoice)
Call/Action Type/StatusTest data
Service Center021 - Central 
AttentionTEST CORP

Customer Details:

LocationStore 990
Street Address1111 Lane; Ft. Wayne, CA 46804
Point of ContactStore Manager
  
Billing Address5960 S Drive;Indianapolis,IN 46100
Billing Phone111-523-4601

Service Call Details:

SeverityHIGH
ServiceProduct 
ProductPREP EQUIPMENT 
EquipNo: N/A
SerialNo: N/A
AssetNo: N/A
SymptomPoor performance
NotesTest notes.

Service Requirements:

Service WindowNo Service window define
Start Date/Time26 JUL 2018 16:07
Respond ByN/A
Complete By23 AUG 2018 16:07

Special Instructions:

  • Please open the attached Acknowledge.html attachment and accept the service call with an ETA or reject with the appropriate reason.
  • Before beginning any work in our store please check in at CUSTOMER SERVICE.
  • Please present company identification and the Service Hub call number to which this visit is in response.
Hello everyone, I'm having trouble writing the test class for email services class. The functionality is we get automated emails in a particular format for service requests. Incoming email will be parsed through Apex email services and a case will be created. The Apex class is working very well, but I'm unable to succeed in test class. I've looked at various documents and resources online, but it only increased my confusion. Can any one please help me? Thank you!
** This is how the incoming email looks like**

Service Request #: 1-3747513422

RFS State: Waiting for ETA

Vendor: Sample vendor

Vendor Phone: (222) 943-1601

Trade: Sample Equipment

Not to Exceed: $300

Service Need: Replacment

Service Level: Critical - P1

Root Cause: Call Back

Service Requested: 07/26/2018 02:58 PM

Required Arrival Time: 07/26/2018 06:58 PM

Target Completion Date: 07/27/2018 02:58 AM

Email Delivery Time: 07/26/2018 02:58 PM

Client: Test client #230

Address: 1490 S Main
Jefferson, CA 11111

RFS Initiator Name: Test Manager

Client Contact Phone: (111) 451-1686

Client Contact Fax: 

Store Contact: 333-928-3276

Store Number: 230

Below is the Apex class, it's working fine with no errors.
global Class EtoCaseservices implements Messaging.InboundEmailHandler {

// Instantiate variables that we will need for handling this email

String location;
Integer locationIdx;
String locationFinal;
String need;
String Inbox;
String initiator;
String Time;
String po;
String phone;
String order;
String critical;


global Messaging.InboundEmailResult handleInboundEmail
           (Messaging.InboundEmail email, Messaging.InboundEnvelope envelope){  
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
 if (email.fromaddress =='test@gmail.com')
               {


loc = 'Client: ';   
locationIdx = email.plainTextBody.indexOf(location);
String[] bodySplitted = email.PlainTextBody.split('\n');
locationFinal = email.plainTextBody.substring(
                              locationIdx + location.length(), email.plainTextBody.indexOf('\n', locationIdx + location.length()));
String[] locNme = locationFinal.split(' ', 3);
phone = email.plainTextBody.substringBetween('Client Contact Phone: ' , 'Client Contact Fax: ');
Inbox = email.plainTextBody.substringBetween('Email Delivery Time: ', 'Client: ');                
initiator = email.plainTextBody.substringBetween('RFS Initiator Name: ' , 'Client Contact Phone: ');          
Time = email.plainTextBody.substringBetween('Service Requested: ' , 'Email Delivery Time: ');
po = email.plainTextBody.substringBetween('Service Request #: ' , 'RFS State: ');                   
critical = email.plaintextbody.substringBetween('Service Level: ' , 'Root Cause: ');
need = email.plaintextbody.substringBetween('Service Need: ' , 'Service Level: ');
order = email.plaintextbody.substringBetween('Not to Exceed: ' , 'Service Need: '); 
system.debug('locationFinal: ' +locationFinal);
if (locationFinal != NULL) {
    SVMXC__Site__c [] locArray = [Select Id, Name, SVMXC__Account__r.Id from SVMXC__Site__c where Name = :locationFinal];

      try{                   
case c= new case();
c.subject= 'TEST REQUEST';
c.Case_Type__c= 'Service Request';
c.Origin='Email';
c.Status='new';
c.AccountId = locArray[0].SVMXC__Account__r.Id;
c.SVMXC__Site__c = locArray[0].Id;  
c.recordtypeId = '012E0000000oRWX';                
c.Description= critical +  '\n' +  need + '\n' + orderFinal + '\n'  + timeFinal ;
c.KA_PO__c= po;
c.Location_Contact_Name__c = Initiator; 
c.BSP_Location_Contact_Phone__c = phone;
insert c; 
}
catch(System.dmlException e)
     {System.debug('Error: Unable to create new Case: ' + e);
     }         
                    }
        else if (locationFinal == null){
              System.debug('No Location was found');    
        }

    }

return result;

      } // Close handleInboundEmail ()
}

Please check the test class. Resulting in "System.QueryException: List has no rows for assignment to SObject" error.
@istest

public class TestEtoCaseservices {
    static testMethod void TestEtoCaseservices () {

       // create a new email and envelope object
Messaging.InboundEmail email = new Messaging.InboundEmail() ;
Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();           


    Account acc = new Account();
    acc.Name = 'Test Smith';
    insert acc;

    SVMXC__Site__c l = new SVMXC__Site__c(Name='Test Loc', SVMXC__City__c='Detroit', NTT_State__c='MI', SVMXC__Site_Phone__c='313 111 1231', SVMXC__Country__c='United States', NTT_Metro_Remote__c='ZONE A');
    insert l;

       // setup the data for the email
     email.subject = 'Test Loc';
     env.fromAddress = 'someaddress@email.com';
     email.plainTextBody = 'This is just a test email for test class';


      // call the email service class and test it with the data in the testMethod
      EtoCaseservices  testInbound=new EtoCaseservices ();
      testInbound.handleInboundEmail(email, env);
    Messaging.InboundEmailResult result = testInbound.handleInboundEmail(email, env);
System.assertEquals( result.success  ,true);

Case c = [select id, account.id, SVMXC__Site__c, recordtypeId, KA_PO__c, Location_Contact_Name__c, description, BSP_Location_Contact_Phone__c, subject, Case_Type__c, Origin, Status, AccountId from Case where SVMXC__Site__c = :l.Id];

System.assertEquals(c.SVMXC__Site__c, l.Id);
System.assertEquals(c.account.Id, acc.Id);
System.assertEquals(c.recordtypeId, '012E0000000oRWX');
System.assertEquals(c.KA_PO__c, '10010101');
System.assertEquals(c.Location_Contact_Name__c, 'Test Man');       
System.assertEquals(c.BSP_Location_Contact_Phone__c, '111 222 3443');
System.assertEquals(c.subject, 'Test Request');
System.assertEquals(c.Case_Type__c, 'Service Test'); 
System.assertEquals(c.Origin, 'Email');
System.assertEquals(c.Status, 'New');  
System.assertEquals(c.description, 'Test description');  
update c;
    }     

}


 
Hello, I need help in writing test class for the below InboundemailHandler. The functionality is we get automated emails in a particular format for service requests. Incoming email will be parsed through Apex email services and a case will be created. The Apex class is working very well, but I'm not sure how to write the test class. Can any one help me? Thank you!
** This is how the incoming email looks like**

Service Request #: 1-3747513422

RFS State: Waiting for ETA

Vendor: Sample vendor

Vendor Phone: (222) 943-1601

Trade: Sample Equipment

Not to Exceed: $300

Service Need: Replacment

Service Level: Critical - P1

Root Cause: Call Back

Service Requested: 07/26/2018 02:58 PM

Required Arrival Time: 07/26/2018 06:58 PM

Target Completion Date: 07/27/2018 02:58 AM

Email Delivery Time: 07/26/2018 02:58 PM

Client: Test client #230

Address: 1490 S Main
Jefferson, CA 11111

RFS Initiator Name: Test Manager

Client Contact Phone: (111) 451-1686

Client Contact Fax: 

Store Contact: 333-928-3276

Store Number: 230
 
global Class EtoCaseservices implements Messaging.InboundEmailHandler {

// Instantiate variables that we will need for handling this email
   
String location;
Integer locationIdx;
String locationFinal;
String need;
String Inbox;
String initiator;
String Time;
String po;
String phone;
String order;
String critical;


global Messaging.InboundEmailResult handleInboundEmail
           (Messaging.InboundEmail email, Messaging.InboundEnvelope envelope){  
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
 if (email.fromaddress =='test@gmail.com')
               {
                   
                   
loc = 'Client: ';   
locationIdx = email.plainTextBody.indexOf(location);
String[] bodySplitted = email.PlainTextBody.split('\n');
locationFinal = email.plainTextBody.substring(
                              locationIdx + location.length(), email.plainTextBody.indexOf('\n', locationIdx + location.length()));
String[] locNme = locationFinal.split(' ', 3);
phone = email.plainTextBody.substringBetween('Client Contact Phone: ' , 'Client Contact Fax: ');
Inbox = email.plainTextBody.substringBetween('Email Delivery Time: ', 'Client: ');                
initiator = email.plainTextBody.substringBetween('RFS Initiator Name: ' , 'Client Contact Phone: ');          
Time = email.plainTextBody.substringBetween('Service Requested: ' , 'Email Delivery Time: ');
po = email.plainTextBody.substringBetween('Service Request #: ' , 'RFS State: ');                   
critical = email.plaintextbody.substringBetween('Service Level: ' , 'Root Cause: ');
need = email.plaintextbody.substringBetween('Service Need: ' , 'Service Level: ');
order = email.plaintextbody.substringBetween('Not to Exceed: ' , 'Service Need: '); 
system.debug('locationFinal: ' +locationFinal);
if (locationFinal != NULL) {
    SVMXC__Site__c [] locArray = [Select Id, Name, SVMXC__Account__r.Id from SVMXC__Site__c where Name = :locationFinal];
           
      try{                   
case c= new case();
c.subject= 'TEST REQUEST';
c.Case_Type__c= 'Service Request';
c.Origin='Email';
c.Status='new';
c.AccountId = locArray[0].SVMXC__Account__r.Id;
c.SVMXC__Site__c = locArray[0].Id;  
c.recordtypeId = '012E0000000oRWX';                
c.Description= critical +  '\n' +  need + '\n' + orderFinal + '\n'  + timeFinal ;
c.KA_PO__c= po;
c.Location_Contact_Name__c = Initiator; 
c.BSP_Location_Contact_Phone__c = phone;
insert c; 
}
catch(System.dmlException e)
     {System.debug('Error: Unable to create new Case: ' + e);
     }         
                    }
        else if (locationFinal == null){
              System.debug('No Location was found');    
        }
      
    }
              
return result;

      } // Close handleInboundEmail ()
}
I've two vf pages QRCase (output) and QRCaseEdit(input/Edit) which are used to create cases for a specific record type 'Quality Report Case'. I tried writing the test class for controller, but it's failing. I'm getting an "System.NullPointerException: Attempt to de-reference a null object" error. This is stack trace: Class.QRreportController.upload: line 81, column 1 Class.TestQRcasecontroller.TestQRreportController: line 46, column 1
When I remove line 46 from test class, 'controller.upload();' and run it, I'm getting around 63% code coverage. Line 81 from above error refers to : attachment.OwnerId = UserInfo.getUserId();
What am I doing wrong. This is my first attempt at the test class. Please guide me. Thank you!
**VF PAGE CONTROLLER** 

   public class QRreportController
   {
    private ApexPages.StandardController std;        

    public Case c {get; set;}


    public QRreportController (ApexPages.StandardController stdCtrl)
    {
        // prepopulates some fields on page load
        this.c = (Case)stdCtrl.getRecord();
        Map<ID,Schema.RecordTypeInfo> rt_Map = 
      Case.sObjectType.getDescribe().getRecordTypeInfosById();
        Id RecordTypeIdCase = 
     Schema.SObjectType.Case.getRecordTypeInfosByName().get('Quality Report 
      Case').getRecordTypeId();
        Id rtId = RecordTypeIdCase;
        c.RecordTypeId=rtId;



c.AccountId=System.currentPageReference().getParameters().get('AccountId');
        std=stdCtrl;
    }


/* --------------------- Get Case ------------------------------- */     
    public Case getCase()
    {       
     return (Case) std.getRecord(); 
    }

  public Attachment attachment {
  get {
      if (attachment == null)
        attachment = new Attachment();
      return null;
    }
  set;
  }

/* --------------------- Save and Exit method ------------------------------- */
    public PageReference saveAndExit()
    {
        std.save();
        PageReference pageRef1 = new PageReference('/' + getCase().id);
        return pageRef1;

    }
/* --------------------- Edit method ------------------------------- */
    public PageReference edit1()
    {
        PageReference pageRef2 = Page.QRcaseEdit;
        pageRef2.getParameters().put('id', getCase().id);
        pageRef2.getParameters().put('AccountId', getCase().AccountId);
        return pageRef2;
    }


/* --------------------- Quick Save method ------------------------------- */
public PageReference save()
    {
        std.save();
        PageReference pageRef3 = Page.QRcase;
       ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'SUCCESS!  Changes saved.'));

        pageRef3.getParameters().put('id', getCase().id);
        pageRef3.getParameters().put('AccountId',getCase().AccountId);
        return pageRef3;

    }

    public PageReference upload() {

    attachment.OwnerId = UserInfo.getUserId();
    attachment.ParentId = getCase().Id ;
    attachment.IsPrivate = true;

    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;
  }


   }

Below is the test class:
@isTest

public class TestQRcasecontroller {

static testMethod void TestQRreportController () {


Id rtId = [select Id, name from RecordType where name = 'Quality Report 
Case' and SObjectType = 'Case' limit 1].Id;


//create account
//
Account acc = new Account();
acc.Name = 'Test Account';
insert acc;


Id RecordTypeIdCase = 
Schema.SObjectType.Case.getRecordTypeInfosByName().get('Quality Report 
Case').getRecordTypeId();

//create case
Case c = new Case();
//enter details
c.AccountId = acc.Id;
c.RecordTypeId = RecordTypeIdCase;
c.Site_State__c = 'New York';
c.Product_Serial_Number__c = '91-4154';
c.Description = 'Broken filter';
c.QR_Action_Taken__c = 'Basic troubleshoot';    
c.QR_Problem_Type__c = 'Poor beverage taste';
c.QR_Component_Type__c = 'Filter';
c.QR_Occurrence_Rate__c = 'Daily';
c.QR_Severity__c = 'Operates Intermittently';
insert c;


                PageReference pageRef = Page.QRCaseEdit;
pageRef.getParameters().put('Id',c.Id);
pageRef.getParameters().put('AccountId',acc.Id);
Test.setCurrentPageReference(pageRef);

                PageReference pageRef = Page.QRCase;
pageRef.getParameters().put('Id',c.Id);
pageRef.getParameters().put('AccountId',acc.Id);
Test.setCurrentPageReference(pageRef);
 ApexPages.StandardController sc = new ApexPages.StandardController(c);
                QRreportController controller = new QRreportController(sc);

                controller.getCase();
                controller.saveAndExit();
                controller.upload();
                controller.edit1();
                controller.save();
                controller.getCase();

}

}

​​​​​​​
Hello everyone, I'm new to Salesforce. I would appreciate if any one help me how to write test class for my visualforce pages. Below is the controller. I have two visualforce pages QRcase (output) and QRcaseEdit (input/edit). These pages are used to create cases for service related issues of our customers. Could any one please help me with the logic. Thank you!
public class QRreportController

    
   
   
/* --------------------- variable for the standard controller ------------------------------- */ 
{
    private ApexPages.StandardController std;        
/* --------------------- variable for this case ------------------------------- */     
    public Case c {get; set;}

/*  -------------------- standard work order controller  ----------------------------  */            
    public QRreportController (ApexPages.StandardController stdCtrl)
    {
        // prepopulates some fields on page load
        this.c = (Case)stdCtrl.getRecord();
        Map<ID,Schema.RecordTypeInfo> rt_Map = Case.sObjectType.getDescribe().getRecordTypeInfosById();
        Id RecordTypeIdCase = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Quality Report Case').getRecordTypeId();
        Id rtId = RecordTypeIdCase;
        c.RecordTypeId=rtId;
        c.AccountId=System.currentPageReference().getParameters().get('AccountId');
        std=stdCtrl;
    }
    
    
      
          
    
    
    
/* --------------------- Get Case ------------------------------- */     
    public Case getCase()
    {       
     return (Case) std.getRecord(); 
    }

  public Attachment attachment {
  get {
      if (attachment == null)
        attachment = new Attachment();
      return attachment;
    }
  set;
  }

/* --------------------- Save and Exit method ------------------------------- */
    public PageReference saveAndExit()
    {
        std.save();
        PageReference pageRef1 = new PageReference('/' + getCase().id);
        return pageRef1;
    }
/* --------------------- Edit method ------------------------------- */
    public PageReference edit1()
    {
        PageReference pageRef2 = Page.QRcaseEdit;
        pageRef2.getParameters().put('id', getCase().id);
        pageRef2.getParameters().put('AccountId', getCase().AccountId);
        return pageRef2;
    }
    

/* --------------------- Quick Save method ------------------------------- */
public PageReference save()
    {
        std.save();
        PageReference pageRef2 = Page.QRcase;
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'SUCCESS!  Changes saved.'));
    
        pageRef2.getParameters().put('id', getCase().id);
        pageRef2.getParameters().put('AccountId',getCase().AccountId);
        return pageRef2;

    }
   
  

    public PageReference upload() {

    attachment.OwnerId = UserInfo.getUserId();
    attachment.ParentId = getCase().Id ;// the record the file is attached to
    attachment.IsPrivate = true;

    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;
  }
  
}
Hello, Our requirement is to create cases from incoming emails. We have around 25 customers and each of them have a specific service request template email format. We have to parse the incoming mail and create case and assign the values to fields. I know how to create the Apex class. I've tested for two customers and it's working great.  
My question is how do I create an Apex class for all the 25 templates at once. Is that even possible? All these emails come to the same email address. I cannot create multiple email services/classes  (as the forwarding address can only be one).This is my current class. I'm using "if else" based on the incoming email address and parsing the data. But how do I do it for 25 email addresses? I'm new to Apex and having a hard time dealing with it. Please help. This code is working fine, but it only deals with two customers. How do I do it for 25 customers?
global Class EtoCaseservices implements Messaging.InboundEmailHandler {

// Instantiate variables that we will need for handling this email
   
String location;
String need;
String service;
String phone;
String warranty;
String po;
String description;
String initiator;
String order;
Integer locationIdx;
Integer needIdx;
Integer serviceIdx;
Integer phoneIdx;
Integer warrantyIdx;
Integer poIdx;
Integer descriptionIdx;
Integer initiatorIdx;
Integer orderIdx;
String locationFinal;
String needFinal;
String serviceFinal;
String tradeFinal;
String InboxFinal;
String InitiatorFinal;
String TimeFinal;
String poFinal;
String phoneFinal;
String servicenofinal;
String warrantyFinal;
String descriptionFinal;
String orderFinal;

    
global Messaging.InboundEmailResult handleInboundEmail
           (Messaging.InboundEmail email, Messaging.InboundEnvelope envelope){  
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
 if (email.fromaddress =='customerone@testl.com')
               {
                   
                   
location = 'Client: ';   
need = 'Need: '; 
service = 'Service Request #: '; 
phone = 'Client Contact Phone: ';

locationIdx = email.plainTextBody.indexOf(location);
needIdx = email.plainTextBody.indexOf(need);
serviceIdx = email.plainTextBody.indexOf(service);
phoneIdx = email.plainTextBody.indexOf(phone);
String[] bodySplitted = email.PlainTextBody.split('\n');
String descriptionFinal = email.plainTextBody.substringBetween('-----------------------------------------------------------------------------------' , '---------------------------------------------------------------------------------------------' ).normalizeSpace();                  
locationFinal = email.plainTextBody.substring(
                              locationIdx + location.length(), email.plainTextBody.indexOf('\n', locationIdx + location.length()));
String[] locNme = locationFinal.split(' ', 3);

needFinal = email.plainTextBody.substring(
                             needIdx + need.length(), email.plainTextBody.indexOf('\n', needIdx + need.length()));
serviceFinal = email.plainTextBody.substring(
                              serviceIdx + service.length(), email.plainTextBody.indexOf('\n', serviceIdx + serrvice.length()));
phoneFinal = email.plainTextBody.substring(
                              phoneIdx + phone.length(), email.plainTextBody.indexOf('\n',phoneIdx + phone.length()));
  
tradeFinal = email.plainTextBody.substringBetween('Not to Exceed: ', 'Service Level: ');
InboxFinal = email.plainTextBody.substringBetween('Email Delivery Time: ', 'Client: ');                   
InitiatorFinal = email.plainTextBody.substringBetween('RFS Initiator Name: ' , 'Client Contact Phone: ');           
TimeFinal = email.plainTextBody.substringBetween('Service Requested: ' , 'Email Delivery Time: ');    
poFinal = email.plainTextBody.substringBetween('Service Request #: ' , 'RFS State: ');                   
servicenoFinal = email.plainTextBody.substringBetween('Service Request #: ' , '(Include this # on Invoice)');              
system.debug('locationFinal: ' +locationFinal);
if (locationFinal != NULL) {
    SVMXC__Site__c [] locArray = [Select Id, Name, SVMXC__Account__r.Id from SVMXC__Site__c where Name = :locationFinal];
           
 
     try{      
               
case c= new case();
c.subject= 'BUNNSERVE REQUEST';
c.Case_Type__c= 'Service Request';
c.Priority='High';
c.Origin='Email';
c.Status='new';
c.AccountId = locArray[0].SVMXC__Account__r.Id;
c.SVMXC__Site__c = locArray[0].Id;  
c.recordtypeId = '012E0000000oRWX';                
c.Description= descriptionFinal  + '\n' +  'Not to Exceed:  ' + tradeFinal + '\n' +  'Service Requested: ' + TimeFinal;
c.KA_PO__c= poFinal;
c.Location_Contact_Name__c = InitiatorFinal; 
c.BSP_Location_Contact_Phone__c = phoneFinal;
upsert c; 
}
catch(System.dmlException e)
     {System.debug('Error: Unable to create new Case: ' + e);
     }         
      
              }
        else if (locationFinal == null){
              System.debug('No Location was found');    
        }
      
    }
           
  else if (email.fromaddress =='customertwo@sample.com')
              
{
         
location = 'Site: ';   
Warranty = 'Warranty: '; 
phone = 'Caller Phone: ';
po = 'The referenced work order number is ';
description = 'Problem Description: ';
initiator = 'Caller name: ';
phone = 'Caller phone: ';
locationIdx = email.plainTextBody.indexOf(location);
WarrantyIdx = email.plainTextBody.indexOf(Warranty);
phoneIdx = email.plainTextBody.indexOf(phone);
poIdx = email.plainTextBody.indexOf(po);
descriptionIdx = email.plainTextBody.indexOf(description);
initiatorIdx = email.plainTextBody.indexOf(initiator);
phoneIdx = email.plainTextBody.indexOf(phone);
                   
String[] bodySplitted = email.PlainTextBody.split('\n');
locationFinal = email.plainTextBody.substring(
                              locationIdx + location.length(), email.plainTextBody.indexOf('\n', locationIdx + location.length()));
String[] locNme = locationFinal.split(' ', 3);

WarrantyFinal = email.plainTextBody.substring(
                              WarrantyIdx + Warranty.length(), email.plainTextBody.indexOf('\n', WarrantyIdx + Warranty.length()));
poFinal = email.plainTextBody.substring(
                              poIdx + po.length(), email.plainTextBody.indexOf('\n',poIdx + po.length()));
descriptionFinal = email.plainTextBody.substring(
                              descriptionIdx + description.length(), email.plainTextBody.indexOf('\n', descriptionIdx + description.length()));
initiatorFinal = email.plainTextBody.substring(
                              initiatorIdx + initiator.length(), email.plainTextBody.indexOf('\n', initiatorIdx + initiator.length()));
phoneFinal = email.plainTextBody.substring(
                              phoneIdx + phone.length(), email.plainTextBody.indexOf('\n',phoneIdx + phone.length()));  

orderFinal = email.plainTextBody.substringBetween('Date Entered: ', 'Region: ');
system.debug('locationFinal: ' +locationFinal);
if (locationFinal != NULL) {
    SVMXC__Site__c [] locArray = [Select Id, Name, SVMXC__Account__r.Id from SVMXC__Site__c where Name = :locationFinal];
           
 
     try{      
               
case c= new case();
c.subject= 'BUNNSERVE REQUEST';
c.Case_Type__c= 'Service Request';
c.Priority='High';
c.Origin='Email';
c.Status='new';
c.AccountId = locArray[0].SVMXC__Account__r.Id;
c.SVMXC__Site__c = locArray[0].Id;  
c.recordtypeId = '012E0000000oRWX';                
c.Description= descriptionFinal + '\n' +'\n' + 'Warranty: ' + WarrantyFinal + '\n' + '\n' + 'Date Entered: ' + orderFinal;
c.KA_PO__c= poFinal;
c.Location_Contact_Name__c = InitiatorFinal; 
c.BSP_Location_Contact_Phone__c = phoneFinal;
upsert c; 
}
catch(System.dmlException e)
     {System.debug('Error: Unable to create new Case: ' + e);
     }         
      
              }
        else if (locationFinal == null){
              System.debug('No Location was found');    
        }
      
    }    
return result;

      } // Close handleInboundEmail ()
}

 
I'm having trouble processing incoming email to create cases. We have a same template format of incoming emails. I'm using substring to parse the data and create a case record. However, I'm unable to parse the data. I had no trouble creating cases for other template (other vendor) by using substrings. But for that, incoming email template looks like this (this is only certain section of the email):
Location: TEST #23880 @ SAMPLE#990
Street Address: 1111 Street, Test city, MI 48211
Point of Contact: Manager
For ex: To grab location from the email, I use:
String locationFinal = email.plainTextBody.substringBetween('Location: ', 'Street Address: '); // working fine 
For the above template email, I can easily parse using the substrings. How do I parse for the below email template. I think the reason is because of the white space between the location and it's value 'TEST #23880 @ SAMPLE#990'. When I test it by getting rid of the white space it's creating cases. I tried using trim() and deletewhitespace() but nothing works. I'm getting null in the debug log. How do I make it work out with the presence of whitespaces?
                     Service Call Notification                                                
                      Test Facility Services

Assignment Information:
Call/Action                #10935174 / 1 (Include this # on Invoice)                                                              
Call/Action Type/Status    Repair Service/SITE VISIT FIELD REPAIR/Received
Service Center             021 - Central 1
Attention                  TEST SAMPLE
Location                   TEST#23880 @ SAMPLE#990          
Street Address             1111 Test Lane; Ft. Wayne, IN 46110
Point of Contact           Manager
Billing Address            Test Street, Test city, IN 46500
Billing Phone              317-222-1111

Service Call Details:
Severity                   HIGH
Service                    Product Repair
Product                    PREP EQUIPMENT 
Symptom                    Some problem
Notes                      Test machine is not working, requires attention.

 
Hello all, 
I'm trying to create cases through incoming email by using Apex Inbound Emailhandler. It worked very well for a sample class which pulls the contact id based on incoming email address and creates case. However, when I try to create case based on our requirement, it wouldn't create. Please have a look at the below code. We receive emails in a particular template, we have to parse the emailbody to assign certain information to certain fields. We don't want the email body to be dumped in description field. Parsing is working fine, as I tested for the sample class. However, I'm unable to pull the location id (object of a managed package) for the incoming email. Can any one help me? There seems to be an issue with the query I think.  

Every incoming email has a location name, we have to use it to pull the location id and create a case. 
SVMXC__Site__c is the API name for the custom object Location from which I have to pull the location name and create case. 
 
global Class EtoCase implements Messaging.InboundEmailHandler {

// Instantiate variables that we will need for handling this email
public String location;
public String notes;
public Integer locationIdx;
public Integer notesIdx;
public String locationFinal;
public String notesFinal;

global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope env){  
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
          
if (email.fromaddress =='example@test.com') {

location = 'Location: ';   
notes = 'Notes ';      

    
locationIdx = email.plainTextBody.indexOf(location);
notesIdx = email.plainTextBody.indexOf(notes);

locationFinal = email.plainTextBody.substring(
                              locationIdx + location.length(), email.plainTextBody.indexOf('\n', locationIdx + location.length()));
          String[] locNme = locationFinal.split(' ', 3);
notesFinal = email.plainTextBody.substring(
                              notesIdx + notes.length(), email.plainTextBody.indexOf('\n', notesIdx + notes.length()));
         
    
     try{      
               
case c= new case();
c.subject= 'PRODUCT SERVICE REQUEST';
c.Case_Type__c= 'Service Request';
c.Priority='High';
c.Origin='Email';
c.Status='new';
string location = locationFinal;   
SVMXC__Site__c[] locArray = [SELECT Id, Name, NTT_Location_Name__c, SVMXC__Account__r.Id FROM SVMXC__Site__c where Name = 'locationFinal'  limit 1];
c.SVMXC__Site__r.Id = locArray[0].Id;           
c.AccountId = locArray[0].SVMXC__Account__r.Id;
c.recordtypeId = '012E0000000oRWX';         
c.Description= notesFinal;
 insert c;
     } catch (System.Dmlexception e)
                     {System.debug('Error: Not able to create new Case: ' + e);
        

            // If no email address is gathered from the email body, write to the debug log, and no actions
            // will be performed.
}
}
return result;

      } 
}

 
Hello Everyone,
Need a help with email services. I'm trying to create cases throgh emails by using InboundEmailHandler. Our customers have a predefined email format (please check the screenshot). Once the email is sent to our organization, a case has to be created but it shouldn't just dump the email body in the description field. Each of the value in the email belongs to a particular field of case object. I've researched online and found out that String.Split is the way to go. However, I'm having trouble to write the code (still an amateur at Apex). Can any one please help me how to split the lines of email body and assign them to fields in the case object. Please explain it through w.r.t to the email body provided. Thank you!

For ex:  Problem Description infromation should be popualted in case descriton field
             Warranty information should be populated in product_warranty__c custom field. 

P.S: We only get emails in text format. No html is involved.
User-added image
  • September 24, 2018
  • Like
  • 0
Hello,
I've a custom auto case-number field for one of my case record type (Quality Report). Every time a new case is created, the auto case number is generated (ex: QR-1287). However, the autonumber is generated even when a case is created in other record types (QR-1288, QR-1289....) . How do I avoid it? I want the auto casenumber field to update only on a single case record type, the cas enumber should QR-1288 only if the recordtype is of Quality Report. Please help. 
  • September 17, 2018
  • Like
  • 0

Hello,
I've a juntion object "Affected product" which relates to "Case" and "Installed product" objects. Whenever a service case is created, the product information must be entered. I've the Affected product related list on case layout, clicking on new affected product will let me enter the product number, which looks up to the installed product object and fills the details in the related list. I want few fields on my case record to be populated based on the information present in the related list. How do I do that? From the below screenshot, I want the Installed product ID, Model Number, Product Name fields to be populated on the case record.


User-added image
 
  • September 14, 2018
  • Like
  • 0