• Hanna Bergsma
  • NEWBIE
  • 10 Points
  • Member since 2020

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 24
    Questions
  • 14
    Replies
I have a trigger than goes through each email on a case and creates a contentdocumentlink between any file on the email and the case

If two or more different emails on the case have the same file attached (aka same contentdocumentid) my trigger errors out.

How can I only select unique contentdocumentlinks in my DocLinks list? I did try to make the docLinks list an <AggregateResult> but then ContentDocumentId "didnt exist" in my

for (AggregateResult doclink : doclinks)
 
trigger shareFilesWithCaseWhenClosed on Case (after update) {
    List <ContentDocumentLink> linksToInsert = new List<ContentDocumentLink>();
    for(Case myCase : trigger.new){
        Case oldCase = Trigger.oldMap.get(myCase.Id);
           if(myCase.RecordTypeName__c=='Order' && myCase.Type == 'Filings' && myCase.IsClosed==True
              && myCase.IsClosed != oldCase.IsClosed){ 
            	
                List<EmailMessage> EM = [SELECT Id, ParentID from EmailMessage where ParentID=: myCase.Id];
                for(EmailMessage email :EM) {
                list<ContentDocumentLink > docLinks = [Select Id, ContentDocumentId from ContentDocumentLink where 
                                                        LinkedEntityId = :email.id ];

                    
                for(ContentDocumentLink docLink : docLinks){
                   doclink.get('ContentDocumentId');
                   list<ContentDocumentLink> existingCaseLinks = [Select Id, ContentDocumentId from ContentDocumentLink 
                                                                 where LinkedEntityId = :myCase.id 
                                                                 and ContentDocumentId= :doclink.ContentDocumentId];
                    if(existingCaseLinks.isEmpty()) { 
                    ContentDocumentLink cdl = new ContentDocumentLink();
                    cdl.Visibility = 'AllUsers';
                    cdl.LinkedEntityId = myCase.Id;
                    cdl.ShareType = 'V';
                    cdl.ContentDocumentId = docLink.ContentDocumentId;
                    linksToInsert.add(cdl); 
                    }
                }
            }
        }
        if(!linksToInsert.isEmpty())
        insert linksToInsert;
    }
}

 
Hello,

I have the following trigger that i thought should check if the CDL already exists so it doesnt try to create something already there, but I am getting this error. Does anyone know why this is happening?
shareFilesWithCaseWhenClosed: execution of AfterUpdate caused by: System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_VALUE, Document with ID: 069f0000000hvOq is already linked with the entity with ID: 500f000000AYq58: [LinkedEntityId] Trigger.shareFilesWithCaseWhenClosed: line 28, column 1

trigger shareFilesWithCaseWhenClosed on Case (after update) {
    List <ContentDocumentLink> linksToInsert = new List<ContentDocumentLink>();
    for(Case myCase : trigger.new){
        Case oldCase = Trigger.oldMap.get(myCase.Id);
           if(myCase.RecordTypeName__c=='Order' && myCase.Type == 'Filings' && myCase.IsClosed==True
              && myCase.IsClosed != oldCase.IsClosed){ 
            	
                List<EmailMessage> EM = [SELECT Id, ParentID from EmailMessage where ParentID=: myCase.Id];
                for(EmailMessage email :EM) {
                list<ContentDocumentLink> existingCaseLinks = [Select Id from ContentDocumentLink 
                                                                 where LinkedEntityId = :myCase.id];
                list<ContentDocumentLink> docLinks = [Select Id, ContentDocumentId from ContentDocumentLink where 
                                                        LinkedEntityId = :email.id and Id NOT IN :existingCaseLinks];

                    
                for(ContentDocumentLink docLink : docLinks){
                    ContentDocumentLink cdl = new ContentDocumentLink();
                    cdl.Visibility = 'AllUsers';
                    cdl.LinkedEntityId = myCase.Id;
                    cdl.ShareType = 'V';
                    cdl.ContentDocumentId = docLink.ContentDocumentId;
                    linksToInsert.add(cdl); 
                }
            }
        }
        if(!linksToInsert.isEmpty())
        insert linksToInsert;
    }
}

 
I have a (simple i thought???) trigger that creates a contentdocumentlink between an email attachment and the parent case of the email.

The CDL is not being created, thus the caseid is not a linkedentityid on that contentdocumentId. where am I going wrong?

Im thinking maybe this is actually trying to update/insert on a link that already exists and im not actually creating a new link??
trigger relateEmailFileToParentCase on EmailMessage (after insert) {
 	for (EmailMessage EM : Trigger.new){
        if (EM.HasAttachment == TRUE )  {
         
	list<ContentDocumentLink> docLinks = [Select Id, ContentDocumentId  from ContentDocumentLink where LinkedEntityId = :EM.id ];
    List<ContentDocumentLink> listLinks = new List<ContentDocumentLink>();
    Case parentCase = [SELECT Id from Case where Id=: EM.ParentId];

            for(ContentDocumentLink docLink : doclinks){
            docLink.Visibility = 'AllUsers';
            docLink.LinkedEntityId = parentCase.id;
            docLink.ShareType = 'V';
            docLink.ContentDocumentId = doclinks[0].ContentDocumentId;
            listLinks.add(docLink);          
        }
            insert listLinks;
      }
	}
}

 
I am deploying new code to my prod and relized that in 2014 way before my time someone created 10+ classes with ZERO code coverage. 

Im not a developer, so i cant just write test classes for all these. I tried. I will never be able to. 

I tried using workbench to remove these steps https://www.salesforceben.com/way-to-delete-apex-classes-from-production/ and only ever got failures

I'm out of options. Totally defeated. How can I remove these classes and triggers with no test coverage?
I am short coverage when I deploy to production by 5%. Im at 88% total for this trigger, please, can anyone help?

Here is my trigger 
trigger filingSuccessfulEmailWithDocs on Case (after update) {
//still need text in body of email, template, criteria for trigger
    OrgWideEmailAddress owa = [select id, DisplayName, Address from OrgWideEmailAddress where Displayname='Name' limit 1];
    String subject = 'Subject';
    String plainTextBody ='Email text here';

    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); 
    for(Case myCase : trigger.new){
        Case oldCase = Trigger.oldMap.get(myCase.Id);
           if(myCase.RecordTypeName__c=='Order' && myCase.Type == 'Filings' && myCase.Email_Client_Attached_Docs__c==True
              && myCase.Email_Client_Attached_Docs__c != oldCase.Email_Client_Attached_Docs__c){ 
    String requirements = myCase.Report_Requirements__c;            
    String plainTextBody ='';
        plainTextBody +=
             
    // Get ContentVersion
    List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
    for (ContentDocumentLink docLinks : [Select Id, ContentDocumentId  from ContentDocumentLink where LinkedEntityId = :myCase.id ]) { 
       for (ContentDocument docs : [Select Id, FileType, Title, FileExtension from ContentDocument where Id= :docLinks.ContentDocumentId]) {
           for (ContentVersion docVersion : [Select Id, VersionData from ContentVersion where ContentDocumentId =:docLinks.ContentDocumentId ]) {

               Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();

               string fileName = docs.Title.Trim() + '.' + docs.FileExtension.Trim();
               efa.setFileName(fileName); //Title of the PDF
               efa.setBody(docVersion.VersionData); //Body of the PDF,need to do transfer into blob
               fileAttachments.add(efa);

           }
               email.setFileAttachments(fileAttachments);
       }
    }
    //add address's that you are sending the email to
    List<String> sendTo = new List<String>();
    String owneremail = [select Email from User where Id = :myCase.OwnerId].Email;
    sendTo.add(myCase.ContactEmail);
    //sendTo.add(owneremail);

    email.setSubject(subject);
    String[] toAddresses = (sendto);  
    email.setPlainTextBody(plainTextBody);  
    email.setToAddresses( toAddresses );
    email.setReplyTo('DoNotReply@xxx.com');           
    email.setOrgWideEmailAddressId(owa.id);
    email.setSaveAsActivity(true);   
    
    // Sends the email  
    Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
       
       EmailMessage em = new EmailMessage();
        em.FromAddress = owa.Address;
        em.FromName = 'DoNotReply';
        em.HtmlBody = email.getHtmlBody();
        em.Subject = email.Subject;
        em.Incoming = false;
        em.Status = '3';
        em.ParentId = myCase.id;
        em.TextBody = email.getPlainTextBody();
        em.FromAddress = owa.address;
        em.ToAddress = myCase.ContactEmail;
        em.ValidatedFromAddress = owa.Address;

        insert em;

        EmailMessageRelation emr = new EmailMessageRelation();
        emr.emailMessageId = em.Id;
        emr.relationId = myCase.ContactId; 
        emr.relationType = 'ToAddress'; // OtherAddress, FromAddress,....
        insert emr;
    }
    }

This is what isnt covered currently 
List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
    for (ContentDocumentLink docLinks : [Select Id, ContentDocumentId  from ContentDocumentLink where LinkedEntityId = :myCase.id ]) { 
       for (ContentDocument docs : [Select Id, FileType, Title, FileExtension from ContentDocument where Id= :docLinks.ContentDocumentId]) {
           for (ContentVersion docVersion : [Select Id, VersionData from ContentVersion where ContentDocumentId =:docLinks.ContentDocumentId ]) {

               Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();

               string fileName = docs.Title.Trim() + '.' + docs.FileExtension.Trim();
               efa.setFileName(fileName); //Title of the PDF
               efa.setBody(docVersion.VersionData); //Body of the PDF,need to do transfer into blob
               fileAttachments.add(efa);

           }
               email.setFileAttachments(fileAttachments);
       }

Here is my test class with 88% Coverage
 
@isTest
private class filingEmailWithDocsTest {
    @isTest static void createTest() {
        Contact con = New Contact();
        con.FirstName = 'Hanna';
        con.LastName = 'Banana';
        con.Email = 'hbanana@aol.com';
        insert con;
        
        State_Information__c state = New State_Information__c();
        state.state_code__c = 'MI';
        state.Name = 'Michigan';
        insert state;

        Case myCase = new Case();
        myCase.Subject = 'Hanna';
        myCase.ContactId=con.id;
        myCase.State_Filed_In1__c= state.Id;
        myCase.Status='Closed - Resolved';
        myCase.Type='Filings';
        myCase.Email_Client_Attached_Docs__c=False;
        myCase.RecordTypeId='012F0000000WjvwIAC';
        insert myCase;
        
        Case caseToUpdate;
        caseToUpdate=[SELECT id from Case where id=: myCase.Id];
        CaseToUpdate.Email_Client_Attached_Docs__c=TRUE;
        update caseToUpdate;

        //Create Attachment for testing
        Attachment Attachment =new Attachment();
        Attachment.Name='Unit Test Attachment';
        Blob bodyBlob=Blob.valueOf('Unit Test Attachment Body');
        Attachment.body=bodyBlob;
        Attachment.parentId=myCase.id;
        insert Attachment ;
        
        ContentVersion contentVersion = new ContentVersion(
            Title = 'Penguins',
            PathOnClient = 'Penguins.jpg',
            VersionData = Blob.valueOf('Test Content'),
            IsMajorVersion = true
        );
        insert contentVersion;    
        List<ContentDocument> documents = [SELECT Id, Title, LatestPublishedVersionId FROM ContentDocument];
        
        //create ContentDocumentLink  record 
        ContentDocumentLink cdl = New ContentDocumentLink();
        cdl.LinkedEntityId = myCase.id;
        cdl.ContentDocumentId = documents[0].Id;
        cdl.shareType = 'V';
        insert cdl;
        

		}
    }

 
I have orders that are created via API where the State Code field is populated but the lookup field to State Information Object is not.

Id like to look up the ID of the State information record that corresponds with the state code. The state information object has a state code field on it as well to match with the order state code

Here is what I have so far, getting a "DML requires SObject or SObject list type: Id" error
trigger fillStateRelationship on Order (before insert, before update) {
    
    for (Order myOrder : Trigger.new){
        if (myOrder.State_Filed_In__c == null && myOrder.State_Code__c != null)  {
        
        String stateCode = myOrder.State_Code__c;
        }   
    	State_Information__c state = [select Id from state_information__c where state_code__c =: myOrder.State_Code__c limit 1];
    	String stateId = state.id;
   		update myOrder.State_Filed_In__c  = stateId;
		}
      }

 
I have the working trigger below that attaches whatever document that is in the Files related list to an email and sends it the contact on a case.

If there is more than one doc in the Files realted list, I get an error. Can anyone advise on how to modify the code to add all related list docs to the email?
 
trigger SendContentVersion on Case (after update) {

    String subject = 'Placeholder';
    String body = 'Placeholder';

    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); 
    for(Case myCase : trigger.new){
        Case oldCase = Trigger.oldMap.get(myCase.Id);
    // Get ContentVersion
    ContentDocumentLink a = [SELECT Id, LinkedEntityId, ContentDocumentId, Visibility, IsDeleted, ShareType,
                            ContentDocument.Title, ContentDocument.createdDate, ContentDocument.FileType
                            FROM ContentDocumentLink 
                            WHERE LinkedEntityId =: myCase.id];
    Id contentDocumentId = a.ContentDocumentId;

    ContentVersion[] cv_list = [select VersionData, PathOnClient from ContentVersion where ContentDocumentId =: contentDocumentId];
    ContentVersion cv = new ContentVersion();
    
    if(cv_list.size() != 0) {
        cv = cv_list[0];
    
        // Create the email attachment
        Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
        efa.setFileName(cv.pathOnClient); 
        efa.setBody(cv.versionData);
        email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
    }
    //add address's that you are sending the email to
    List<String> sendTo = new List<String>();
    String owneremail = [select Email from User where Id = :myCase.OwnerId].Email;
    sendTo.add(myCase.ContactEmail);
    sendTo.add(owneremail);

    email.setSubject(subject);
    String[] toAddresses = (sendto);
    email.setToAddresses( toAddresses );
    email.setPlainTextBody(body);
    
    
    // Sends the email  
    Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
}
    }
}

 
I am working on a trigger that updates a field on an account when the formula field on the account hit 0 days remaining for the subscription. Some contacts are related to multiple accounts, so I need to look for Contact emails as well as contact emails via AccountContactRelations. 
I have the SOQL query for this. I now need to, at the end of my trigger, reference the contact.email field from the soql query. How do I do this?

 
trigger Renewal on Account (before update) { for(Account acc : Trigger.new) { if (acc.Active_Subscription__c = True && acc.Subscription_Days_Remaining__c = 0) { // Get a list of all records that are expiring List<Account> matchingRecords = [SELECT Id, Name, Subscription_Days_Remaining__c , (Select email FROM Contacts), (SELECT Contact.Email FROM AccountContactRelations) FROM Account WHERE Active = True and Subscription_Days_Remaining__c < 0 and Id = :acc.ID]; //update the account email to the contact email //update to relation email if role is forwarding contact, if that is null, contact email, add one to trigger field String matchingRecordDescription = 'Email this person: \n'; for (Account matchingRecord : matchingRecords){ matchingRecordDescription += matchingRecord.Contacts.Email; } } }
We have multiple email-to-case addresses in our org. Client's frequently email multiple of them to 'make sure their email gets read'. Okay. Anyways, cutting it down to only one email-to-case address isn't an option for us, and clients will continue to email multiple no matter if we ask politely or threaten their loved ones. 

When this happens, we get one case for every address the email is sent to. I tried creating a flow that, after creating a case, looks for other  'Gets' cases with matching subject, and supplied email, and created time/date. Then I'd like to update the subject line to 'Duplicate Case'- [Subject]

Below is my flow and Get Records detail. When testing it puts 'Duplicate Case' on every single E2C coming in. What did I do wrong? I tried adding in "id does not equal Record.id" and then it didnt add the text to ANY of the emails, even the duplicated.
User-added imageUser-added image


 
I've been at this for three days, I've read 300 blogs, nothing at all has gotten me even 1% test coverage on my simple trigger that updates ownerid on content version insert.

I am totally defeated. 
 
trigger ConDoc on ContentVersion (after insert) {

    List<ContentVersion> conver = [SELECT Id, Title, OwnerId FROM ContentVersion WHERE Id IN: Trigger.newMap.keySet()];

    for (ContentVersion CV: conver){
        CV.OwnerId= '005F0000002QTR2';
    }

    update conver;

}

The closest i've got is below, its giving me a "
System.InvalidParameterValueException: Provide the ID of a test-context sObject as the first parameter for setCreatedDate()." error
@isTest
public class Test_ConDocTrigger{
    static testMethod void contentDoc() {
    list<ContentVersion>conver = new list<ContentVersion>();

     //ContentDocument cd = [SELECT Id FROM ContentDocument ];


     ContentVersion cv = new ContentVersion();
     //cv.ContentDocumentId = '069M0000000Tpig';
     cv.Title ='con';
     conver.add(cv);
     test.setCreatedDate(cv.Id, DateTime.now());
     insert cv;

    }
}

 
I am not a coder and am looking to write test coverage for this simple trigger:
trigger ConDoc on ContentVersion (after insert) {

    List<ContentVersion> conver = [SELECT Id, Title, OwnerId FROM ContentVersion WHERE Id IN: Trigger.newMap.keySet()];

    for (ContentVersion CV: conver){
        CV.OwnerId= '005F0000002QTR2IAO';
        CV.Title = 'HannaTest';
    }

    update conver;

}
Right now this is where I am at, I have no idea what I am doing. I appreciate any help. Im getting an Insert Failed when I run the Test
@isTest public class Test_ConDocTrigger {
static testMethod void TestData(){
	
    ContentVersion CV = new ContentVersion();       
	CV.OwnerId = '005F0000002QTR2IAO';
	CV.Title ='Test Name';
    
    insert CV;
    
  								}
}


 
Is there a way to set the ownerId = Content version> email> Case>Last Modified By?

I want to set the owner of the file to whoever has been working the case. These files are created via email-to-case. Please help with actual suggestions, not links. I have been reading blogs for days and nothing has worked. I'm at wits end on how to allow my users to delete Files on emails.

trigger ConDoc on ContentVersion (after insert) {

    List<ContentVersion> conver = [SELECT Id, Title, OwnerId FROM ContentVersion WHERE Id IN: Trigger.newMap.keySet()];

    for (ContentVersion CV: conver){
        CV.OwnerId= '3D00GF0000007fwJR';
        CV.Title = 'HannaTest';
    }

    update conver;

}
I want to change the ownership of a file (ContentDocument) on insert.
When I wrote my test class im getting the error:DML operation Insert not allowed on ContentDocument. Trigger is below test class

@isTest(seeAllData=true)
private class Test_File_OwnershipTrigger
{
    static testMethod void TestContentDocument()
    { 
       ContentDocument testContentDocument = new ContentDocument();
       testContentDocument.Title ='Test Name';
       testContentDocument.ParentId = '02sf0000002WKN7AAO';
       insert testContentDocument;
    }
}


Trigger: 
trigger File_Ownership on ContentDocument (before insert) 
{
    for(ContentDocument CD: Trigger.New)
    {
        if(CD.ParentId != '')
        {
            CD.Ownerid='[my id is placed here]';
        }
    }
}
 
I am setting up a scheduled flow that deletes emails older than 3 years old. I have a formula field that calculates age in days that I am using for criteria.

I am gettting "The flow tried to delete these records: null. This error occurred: INVALID_CROSS_REFERENCE_KEY: invalid cross reference id. " but I can see that its grabbing at least one Email Messgae Id in Debug Details. Help!
User-added imageUser-added image
On classic there used to be a button at the top of the record to return to the list view you were on when you clicked to view that record

My users are asking for that same functionality in Lightning, but it doesnt seem like an easy solution exists. We are having a really hard time getting users to adapt to Lightning, so i was hoping to deliver on this. I have pointed out that there is the drop down on the object tab, so please do not suggest that as a solution
I am our orgs admin and I am trying to fix code set up in 2016 by a previous employee. I know very little about apex but I understand my SOQL query is pulling 0 records and I need to solve for that. I am recieving the following emails. Thank you in advance, Ive been working on this for days! 
"OrderTrigger: execution of AfterInsert

caused by: System.NullPointerException: Attempt to de-reference a null object
Class.OrderTriggerHandler.insertOrder: line 21, column 1
Trigger.OrderTrigger: line 4, column 1"


My trigger is very short, i have bolded line 4 per the email error:

trigger OrderTrigger on Order (after insert) {

    if(Trigger.isInsert){
       OrderTriggerHandler.insertOrder(Trigger.new);  
     }

}

My handler is as follows, i have bolded line 21 per error email:
public with sharing class OrderTriggerHandler{

    public Static void insertOrder(List<Order> objOrder)
    {
        
         Set<Id> objAcc = new Set<Id>();
         for(Order objOr : objOrder){
             objAcc.add(objOr.AccountId);
         }
         
         
         List<Contact> objCon = [select id,name,Email,AccountId,Account.Parent.ParentId, Account.Parent.Parent.Name from Contact where AccountId IN : objAcc];
         String partnerName;
         Id wideEmailAddressId;
         if(objCon.size() > 0){
             List<String> objMail = new List<String>();
             Set<String> objSetAcc = new Set<String>();
             for(Contact objContact : objCon){
                 objMail.add(objContact.Email);
                 partnerName = objContact.Account.Parent.Parent.Name;
                 String accId = String.valueOf(objContact.Account.Parent.ParentId).substring(0, 15);
                 objSetAcc.add('New Order Notification'+accId);
             }
             
        for(OrgWideEmailAddress owa : [select id, Address, DisplayName from OrgWideEmailAddress where DisplayName='EvoLaw, LLC']) {
             if(owa.Address.contains('CSR')) wideEmailAddressId = owa.id; 
        } 
        System.debug('&&&&&&&objSetAcc&&&&&& '+objSetAcc);
        
        
       List<EmailTemplate> templateId = [Select id,Subject, HtmlValue, Body from EmailTemplate where name IN : objSetAcc];
       System.debug('&&&&&&&templateId&&&&&& '+templateId);
       if(templateId.size() > 0){ 
       
            System.debug('&&&&&&&templateId &&&&& '+templateId[0]); 
           String [] emailsAsArray = new String [objMail.size()];
            Integer i = 0;
            for (String singleCCEmail: objMail) {
                emailsAsArray[i++] = singleCCEmail;
            }  
             
           
           String subject =templateId[0].Subject ;
           String htmlBody = templateId[0].HtmlValue ;
           String plainBody = templateId[0].Body;
         
          
          // Messaging.sendEmail(new Messaging.Singleemailmessage[] {mail});
     @TestVisible Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
            message.toAddresses = emailsAsArray;
            message.optOutPolicy = 'FILTER';
            message.subject = 'Opt Out Test Message';
            //message.plainTextBody = 'This is the message body.';
             if(templateId[0].id != null)
             message.setTemplateId(templateId[0].id);
             if(wideEmailAddressId!=Null)
             message.setOrgWideEmailAddressID(wideEmailAddressId);
             message.setSubject(subject);
             message.setHtmlBody(htmlBody);
             message.setPlainTextBody(plainBody);
            // message.setTreatBodiesAsTemplate(true);
            Messaging.SingleEmailMessage[] messages =  new List<Messaging.SingleEmailMessage> {message};
            System.debug('___________msg____' +messages );
            Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
            if (results[0].success) {
                System.debug('The email was sent successfully.');
            } else {
                System.debug('The email failed to send: '+ results[0].errors[0].message);
            } 
             
           }
         }
    }

}
I'll start this out by disclosing I am an admin not a developer for my org. We do not have a developer on staff and last week I started getting this email for a Apex Class failing.

So, I opened the Class.OrderTriggerHandler in my sandbox and updated the Class and the Trigger to API 50.0 (it was on V 38). I ran the test class and got this error:

Error: System.QueryException: List has no rows for assignment to SObject
Stack Trace: Class.OrderTriggerHandlerTest.unitTest1: line 12, column 1

I understand that the SOQL is returning 0 rows, when it is expecting 1, but I am not sure where to add the code to solve for this 

Here is the testclass, I bolded line 12

@isTest(SeeAllData=True)

public class OrderTriggerHandlerTest{

  public static testMethod void unitTest1(){
     List<Order>  od1=[Select AccountId from Order Limit 1];
     Set<Id> objAcc = new Set<Id>();
           for(Order objOr : od1){
               objAcc.add(objOr.AccountId);
           }
     List<Account>accountlist =[select id,name,ParentId,Parent.ParentId,(select id,LastName,Account.Parent.ParentId from Contacts where id!=null and Account.Parent.ParentId!=null  Limit 1) from Account where ParentId!=null and Parent.ParentId!=null Limit 1];      
     Contact c1=[Select id,name,Email,AccountId,Account.Parent.ParentId from Contact  where AccountId IN :accountlist Limit 1];
      String accId = String.valueOf(c1.Account.Parent.ParentId).substring(0, 15);
      String stte='New Order Notification'+ accId;
     EmailTemplate templateId = [Select id,Subject, HtmlValue, Body from EmailTemplate where name =:stte];
     List<Order> od = [Select id,AccountId from Order where AccountId =: c1.AccountId];
     OrderTriggerHandler.insertOrder(od);
    } 
    
    public static testMethod void unitTest2(){
      
    Account objAccount2 = new Account();
    objAccount2.Name = 'test2';
    insert objAccount2;
    
    Order objOrder = new Order();
    objOrder.AccountId = objAccount2.Id;
    objOrder.EffectiveDate = Date.today().addDays(+6);
    objOrder.Status = 'Draft';
    insert objOrder;
    } 
 
}
I have a Case list view where
  • the record type is filted to one type
  • Inline Editing and Enhanced Lists are enabled
  • Mass edits from lists is checked on my profile
  • I have no custom buttons or global actions on case list views

I do not get a pencil or a lock when I hover over any of the fields displayed in my list view. Any ideas as to what is going on here?
Hello,
I have a trigger that if a email-to-case is created without a contact, a contact will be created and associated with that case based on the supplied email info.

I am just not a developer and have tried so hard to write a test class and not getting anywhere close. Please help I will never get this alone.

Here is my trigger:

trigger TriggertoCreateContactformCase on Case (before insert) {
    List<String> UseremailAddresses = new List<String>();
    //First exclude any cases where the contact is set
    for (Case c:Trigger.new) {
        if (c.ContactId==null &&
            c.SuppliedEmail!=''|| c.SuppliedEmail==null)
        {
            UseremailAddresses.add(c.SuppliedEmail);
        }
    }

    //Now we have a nice list of all the email addresses.  Let's query on it and see how many contacts already exist.
    List<Contact> listofallContacts = [Select Id,Email From Contact Where Email in:UseremailAddresses];
    Set<String> ExstingEmails = new Set<String>();
    for (Contact c:listofallContacts) {
        ExstingEmails.add(c.Email);
    }
    
    Map<String,Contact> emailToContactMap = new Map<String,Contact>();
    List<Case> casesToUpdate = new List<Case>();

    for (Case c:Trigger.new) {
        if (c.ContactId==null &&
            c.SuppliedName!=null &&
            c.SuppliedEmail!=null &&
            c.SuppliedName!='' &&
           !c.SuppliedName.contains('@') &&
            c.SuppliedEmail!='' &&
           !ExstingEmails.contains(c.SuppliedEmail))
        {
            //The case was created with a null contact
            //Let's make a contact for it
            String[] Emailheader = c.SuppliedName.split(' ',2);
            if (Emailheader.size() == 2)
            {
                Contact conts = new Contact(FirstName=Emailheader[0],
                                            LastName=Emailheader[1],
                                            Email=c.SuppliedEmail
                                            );
                emailToContactMap.put(c.SuppliedEmail,conts);
                casesToUpdate.add(c);
            }
        }
    }
    
    List<Contact> newContacts = emailToContactMap.values();
    insert newContacts;
    
    for (Case c:casesToUpdate) {
        Contact newContact = emailToContactMap.get(c.SuppliedEmail);
        
        c.ContactId = newContact.Id;
    }
}

My Test Class pitiful, please help:
@isTest
private class CreateContactTest{
    @isTest static void TriggertoCreateContactformCase () {
        Case c = new Case(c.ContactId=='';
            c.SuppliedName= 'Joan Ansderson';
            c.SuppliedEmail= 'Anderson@gmail.com';

         System.assertEquals(True, str.isSuccess());

    }

}
I am getting an error referencing the third line here "static can only be used on methods of a top level type "

Anyone have any ideas? I reworked this code from someone I found online, I'm not an experienced developer so any help is greatly appreciated!!

'm trying to create an email handler that creates a contact from incoming emails where the contact doesnt exist already

}

@isTest
private class testCreateContactFrmEmail
{static testMethod void testCreateContactFrmEmail() {
Messaging.InboundEmail email = new Messaging.InboundEmail() ;
Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();

email.subject = 'Create Contact';
email.plainTextBody = 'FromEmail';
env.fromAddress = 'testemail@gmail.com';

CreateContactFrmEmail creatC = new CreateContactFrmEmail();
creatC.handleInboundEmail(email, env );
}
}
}
I have a (simple i thought???) trigger that creates a contentdocumentlink between an email attachment and the parent case of the email.

The CDL is not being created, thus the caseid is not a linkedentityid on that contentdocumentId. where am I going wrong?

Im thinking maybe this is actually trying to update/insert on a link that already exists and im not actually creating a new link??
trigger relateEmailFileToParentCase on EmailMessage (after insert) {
 	for (EmailMessage EM : Trigger.new){
        if (EM.HasAttachment == TRUE )  {
         
	list<ContentDocumentLink> docLinks = [Select Id, ContentDocumentId  from ContentDocumentLink where LinkedEntityId = :EM.id ];
    List<ContentDocumentLink> listLinks = new List<ContentDocumentLink>();
    Case parentCase = [SELECT Id from Case where Id=: EM.ParentId];

            for(ContentDocumentLink docLink : doclinks){
            docLink.Visibility = 'AllUsers';
            docLink.LinkedEntityId = parentCase.id;
            docLink.ShareType = 'V';
            docLink.ContentDocumentId = doclinks[0].ContentDocumentId;
            listLinks.add(docLink);          
        }
            insert listLinks;
      }
	}
}

 
I am short coverage when I deploy to production by 5%. Im at 88% total for this trigger, please, can anyone help?

Here is my trigger 
trigger filingSuccessfulEmailWithDocs on Case (after update) {
//still need text in body of email, template, criteria for trigger
    OrgWideEmailAddress owa = [select id, DisplayName, Address from OrgWideEmailAddress where Displayname='Name' limit 1];
    String subject = 'Subject';
    String plainTextBody ='Email text here';

    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); 
    for(Case myCase : trigger.new){
        Case oldCase = Trigger.oldMap.get(myCase.Id);
           if(myCase.RecordTypeName__c=='Order' && myCase.Type == 'Filings' && myCase.Email_Client_Attached_Docs__c==True
              && myCase.Email_Client_Attached_Docs__c != oldCase.Email_Client_Attached_Docs__c){ 
    String requirements = myCase.Report_Requirements__c;            
    String plainTextBody ='';
        plainTextBody +=
             
    // Get ContentVersion
    List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
    for (ContentDocumentLink docLinks : [Select Id, ContentDocumentId  from ContentDocumentLink where LinkedEntityId = :myCase.id ]) { 
       for (ContentDocument docs : [Select Id, FileType, Title, FileExtension from ContentDocument where Id= :docLinks.ContentDocumentId]) {
           for (ContentVersion docVersion : [Select Id, VersionData from ContentVersion where ContentDocumentId =:docLinks.ContentDocumentId ]) {

               Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();

               string fileName = docs.Title.Trim() + '.' + docs.FileExtension.Trim();
               efa.setFileName(fileName); //Title of the PDF
               efa.setBody(docVersion.VersionData); //Body of the PDF,need to do transfer into blob
               fileAttachments.add(efa);

           }
               email.setFileAttachments(fileAttachments);
       }
    }
    //add address's that you are sending the email to
    List<String> sendTo = new List<String>();
    String owneremail = [select Email from User where Id = :myCase.OwnerId].Email;
    sendTo.add(myCase.ContactEmail);
    //sendTo.add(owneremail);

    email.setSubject(subject);
    String[] toAddresses = (sendto);  
    email.setPlainTextBody(plainTextBody);  
    email.setToAddresses( toAddresses );
    email.setReplyTo('DoNotReply@xxx.com');           
    email.setOrgWideEmailAddressId(owa.id);
    email.setSaveAsActivity(true);   
    
    // Sends the email  
    Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
       
       EmailMessage em = new EmailMessage();
        em.FromAddress = owa.Address;
        em.FromName = 'DoNotReply';
        em.HtmlBody = email.getHtmlBody();
        em.Subject = email.Subject;
        em.Incoming = false;
        em.Status = '3';
        em.ParentId = myCase.id;
        em.TextBody = email.getPlainTextBody();
        em.FromAddress = owa.address;
        em.ToAddress = myCase.ContactEmail;
        em.ValidatedFromAddress = owa.Address;

        insert em;

        EmailMessageRelation emr = new EmailMessageRelation();
        emr.emailMessageId = em.Id;
        emr.relationId = myCase.ContactId; 
        emr.relationType = 'ToAddress'; // OtherAddress, FromAddress,....
        insert emr;
    }
    }

This is what isnt covered currently 
List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
    for (ContentDocumentLink docLinks : [Select Id, ContentDocumentId  from ContentDocumentLink where LinkedEntityId = :myCase.id ]) { 
       for (ContentDocument docs : [Select Id, FileType, Title, FileExtension from ContentDocument where Id= :docLinks.ContentDocumentId]) {
           for (ContentVersion docVersion : [Select Id, VersionData from ContentVersion where ContentDocumentId =:docLinks.ContentDocumentId ]) {

               Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();

               string fileName = docs.Title.Trim() + '.' + docs.FileExtension.Trim();
               efa.setFileName(fileName); //Title of the PDF
               efa.setBody(docVersion.VersionData); //Body of the PDF,need to do transfer into blob
               fileAttachments.add(efa);

           }
               email.setFileAttachments(fileAttachments);
       }

Here is my test class with 88% Coverage
 
@isTest
private class filingEmailWithDocsTest {
    @isTest static void createTest() {
        Contact con = New Contact();
        con.FirstName = 'Hanna';
        con.LastName = 'Banana';
        con.Email = 'hbanana@aol.com';
        insert con;
        
        State_Information__c state = New State_Information__c();
        state.state_code__c = 'MI';
        state.Name = 'Michigan';
        insert state;

        Case myCase = new Case();
        myCase.Subject = 'Hanna';
        myCase.ContactId=con.id;
        myCase.State_Filed_In1__c= state.Id;
        myCase.Status='Closed - Resolved';
        myCase.Type='Filings';
        myCase.Email_Client_Attached_Docs__c=False;
        myCase.RecordTypeId='012F0000000WjvwIAC';
        insert myCase;
        
        Case caseToUpdate;
        caseToUpdate=[SELECT id from Case where id=: myCase.Id];
        CaseToUpdate.Email_Client_Attached_Docs__c=TRUE;
        update caseToUpdate;

        //Create Attachment for testing
        Attachment Attachment =new Attachment();
        Attachment.Name='Unit Test Attachment';
        Blob bodyBlob=Blob.valueOf('Unit Test Attachment Body');
        Attachment.body=bodyBlob;
        Attachment.parentId=myCase.id;
        insert Attachment ;
        
        ContentVersion contentVersion = new ContentVersion(
            Title = 'Penguins',
            PathOnClient = 'Penguins.jpg',
            VersionData = Blob.valueOf('Test Content'),
            IsMajorVersion = true
        );
        insert contentVersion;    
        List<ContentDocument> documents = [SELECT Id, Title, LatestPublishedVersionId FROM ContentDocument];
        
        //create ContentDocumentLink  record 
        ContentDocumentLink cdl = New ContentDocumentLink();
        cdl.LinkedEntityId = myCase.id;
        cdl.ContentDocumentId = documents[0].Id;
        cdl.shareType = 'V';
        insert cdl;
        

		}
    }

 
I have orders that are created via API where the State Code field is populated but the lookup field to State Information Object is not.

Id like to look up the ID of the State information record that corresponds with the state code. The state information object has a state code field on it as well to match with the order state code

Here is what I have so far, getting a "DML requires SObject or SObject list type: Id" error
trigger fillStateRelationship on Order (before insert, before update) {
    
    for (Order myOrder : Trigger.new){
        if (myOrder.State_Filed_In__c == null && myOrder.State_Code__c != null)  {
        
        String stateCode = myOrder.State_Code__c;
        }   
    	State_Information__c state = [select Id from state_information__c where state_code__c =: myOrder.State_Code__c limit 1];
    	String stateId = state.id;
   		update myOrder.State_Filed_In__c  = stateId;
		}
      }

 
We have multiple email-to-case addresses in our org. Client's frequently email multiple of them to 'make sure their email gets read'. Okay. Anyways, cutting it down to only one email-to-case address isn't an option for us, and clients will continue to email multiple no matter if we ask politely or threaten their loved ones. 

When this happens, we get one case for every address the email is sent to. I tried creating a flow that, after creating a case, looks for other  'Gets' cases with matching subject, and supplied email, and created time/date. Then I'd like to update the subject line to 'Duplicate Case'- [Subject]

Below is my flow and Get Records detail. When testing it puts 'Duplicate Case' on every single E2C coming in. What did I do wrong? I tried adding in "id does not equal Record.id" and then it didnt add the text to ANY of the emails, even the duplicated.
User-added imageUser-added image


 
I am not a coder and am looking to write test coverage for this simple trigger:
trigger ConDoc on ContentVersion (after insert) {

    List<ContentVersion> conver = [SELECT Id, Title, OwnerId FROM ContentVersion WHERE Id IN: Trigger.newMap.keySet()];

    for (ContentVersion CV: conver){
        CV.OwnerId= '005F0000002QTR2IAO';
        CV.Title = 'HannaTest';
    }

    update conver;

}
Right now this is where I am at, I have no idea what I am doing. I appreciate any help. Im getting an Insert Failed when I run the Test
@isTest public class Test_ConDocTrigger {
static testMethod void TestData(){
	
    ContentVersion CV = new ContentVersion();       
	CV.OwnerId = '005F0000002QTR2IAO';
	CV.Title ='Test Name';
    
    insert CV;
    
  								}
}


 
Is there a way to set the ownerId = Content version> email> Case>Last Modified By?

I want to set the owner of the file to whoever has been working the case. These files are created via email-to-case. Please help with actual suggestions, not links. I have been reading blogs for days and nothing has worked. I'm at wits end on how to allow my users to delete Files on emails.

trigger ConDoc on ContentVersion (after insert) {

    List<ContentVersion> conver = [SELECT Id, Title, OwnerId FROM ContentVersion WHERE Id IN: Trigger.newMap.keySet()];

    for (ContentVersion CV: conver){
        CV.OwnerId= '3D00GF0000007fwJR';
        CV.Title = 'HannaTest';
    }

    update conver;

}
I want to change the ownership of a file (ContentDocument) on insert.
When I wrote my test class im getting the error:DML operation Insert not allowed on ContentDocument. Trigger is below test class

@isTest(seeAllData=true)
private class Test_File_OwnershipTrigger
{
    static testMethod void TestContentDocument()
    { 
       ContentDocument testContentDocument = new ContentDocument();
       testContentDocument.Title ='Test Name';
       testContentDocument.ParentId = '02sf0000002WKN7AAO';
       insert testContentDocument;
    }
}


Trigger: 
trigger File_Ownership on ContentDocument (before insert) 
{
    for(ContentDocument CD: Trigger.New)
    {
        if(CD.ParentId != '')
        {
            CD.Ownerid='[my id is placed here]';
        }
    }
}
 
I am setting up a scheduled flow that deletes emails older than 3 years old. I have a formula field that calculates age in days that I am using for criteria.

I am gettting "The flow tried to delete these records: null. This error occurred: INVALID_CROSS_REFERENCE_KEY: invalid cross reference id. " but I can see that its grabbing at least one Email Messgae Id in Debug Details. Help!
User-added imageUser-added image
I am our orgs admin and I am trying to fix code set up in 2016 by a previous employee. I know very little about apex but I understand my SOQL query is pulling 0 records and I need to solve for that. I am recieving the following emails. Thank you in advance, Ive been working on this for days! 
"OrderTrigger: execution of AfterInsert

caused by: System.NullPointerException: Attempt to de-reference a null object
Class.OrderTriggerHandler.insertOrder: line 21, column 1
Trigger.OrderTrigger: line 4, column 1"


My trigger is very short, i have bolded line 4 per the email error:

trigger OrderTrigger on Order (after insert) {

    if(Trigger.isInsert){
       OrderTriggerHandler.insertOrder(Trigger.new);  
     }

}

My handler is as follows, i have bolded line 21 per error email:
public with sharing class OrderTriggerHandler{

    public Static void insertOrder(List<Order> objOrder)
    {
        
         Set<Id> objAcc = new Set<Id>();
         for(Order objOr : objOrder){
             objAcc.add(objOr.AccountId);
         }
         
         
         List<Contact> objCon = [select id,name,Email,AccountId,Account.Parent.ParentId, Account.Parent.Parent.Name from Contact where AccountId IN : objAcc];
         String partnerName;
         Id wideEmailAddressId;
         if(objCon.size() > 0){
             List<String> objMail = new List<String>();
             Set<String> objSetAcc = new Set<String>();
             for(Contact objContact : objCon){
                 objMail.add(objContact.Email);
                 partnerName = objContact.Account.Parent.Parent.Name;
                 String accId = String.valueOf(objContact.Account.Parent.ParentId).substring(0, 15);
                 objSetAcc.add('New Order Notification'+accId);
             }
             
        for(OrgWideEmailAddress owa : [select id, Address, DisplayName from OrgWideEmailAddress where DisplayName='EvoLaw, LLC']) {
             if(owa.Address.contains('CSR')) wideEmailAddressId = owa.id; 
        } 
        System.debug('&&&&&&&objSetAcc&&&&&& '+objSetAcc);
        
        
       List<EmailTemplate> templateId = [Select id,Subject, HtmlValue, Body from EmailTemplate where name IN : objSetAcc];
       System.debug('&&&&&&&templateId&&&&&& '+templateId);
       if(templateId.size() > 0){ 
       
            System.debug('&&&&&&&templateId &&&&& '+templateId[0]); 
           String [] emailsAsArray = new String [objMail.size()];
            Integer i = 0;
            for (String singleCCEmail: objMail) {
                emailsAsArray[i++] = singleCCEmail;
            }  
             
           
           String subject =templateId[0].Subject ;
           String htmlBody = templateId[0].HtmlValue ;
           String plainBody = templateId[0].Body;
         
          
          // Messaging.sendEmail(new Messaging.Singleemailmessage[] {mail});
     @TestVisible Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
            message.toAddresses = emailsAsArray;
            message.optOutPolicy = 'FILTER';
            message.subject = 'Opt Out Test Message';
            //message.plainTextBody = 'This is the message body.';
             if(templateId[0].id != null)
             message.setTemplateId(templateId[0].id);
             if(wideEmailAddressId!=Null)
             message.setOrgWideEmailAddressID(wideEmailAddressId);
             message.setSubject(subject);
             message.setHtmlBody(htmlBody);
             message.setPlainTextBody(plainBody);
            // message.setTreatBodiesAsTemplate(true);
            Messaging.SingleEmailMessage[] messages =  new List<Messaging.SingleEmailMessage> {message};
            System.debug('___________msg____' +messages );
            Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
            if (results[0].success) {
                System.debug('The email was sent successfully.');
            } else {
                System.debug('The email failed to send: '+ results[0].errors[0].message);
            } 
             
           }
         }
    }

}
I'll start this out by disclosing I am an admin not a developer for my org. We do not have a developer on staff and last week I started getting this email for a Apex Class failing.

So, I opened the Class.OrderTriggerHandler in my sandbox and updated the Class and the Trigger to API 50.0 (it was on V 38). I ran the test class and got this error:

Error: System.QueryException: List has no rows for assignment to SObject
Stack Trace: Class.OrderTriggerHandlerTest.unitTest1: line 12, column 1

I understand that the SOQL is returning 0 rows, when it is expecting 1, but I am not sure where to add the code to solve for this 

Here is the testclass, I bolded line 12

@isTest(SeeAllData=True)

public class OrderTriggerHandlerTest{

  public static testMethod void unitTest1(){
     List<Order>  od1=[Select AccountId from Order Limit 1];
     Set<Id> objAcc = new Set<Id>();
           for(Order objOr : od1){
               objAcc.add(objOr.AccountId);
           }
     List<Account>accountlist =[select id,name,ParentId,Parent.ParentId,(select id,LastName,Account.Parent.ParentId from Contacts where id!=null and Account.Parent.ParentId!=null  Limit 1) from Account where ParentId!=null and Parent.ParentId!=null Limit 1];      
     Contact c1=[Select id,name,Email,AccountId,Account.Parent.ParentId from Contact  where AccountId IN :accountlist Limit 1];
      String accId = String.valueOf(c1.Account.Parent.ParentId).substring(0, 15);
      String stte='New Order Notification'+ accId;
     EmailTemplate templateId = [Select id,Subject, HtmlValue, Body from EmailTemplate where name =:stte];
     List<Order> od = [Select id,AccountId from Order where AccountId =: c1.AccountId];
     OrderTriggerHandler.insertOrder(od);
    } 
    
    public static testMethod void unitTest2(){
      
    Account objAccount2 = new Account();
    objAccount2.Name = 'test2';
    insert objAccount2;
    
    Order objOrder = new Order();
    objOrder.AccountId = objAccount2.Id;
    objOrder.EffectiveDate = Date.today().addDays(+6);
    objOrder.Status = 'Draft';
    insert objOrder;
    } 
 
}
I am getting an error referencing the third line here "static can only be used on methods of a top level type "

Anyone have any ideas? I reworked this code from someone I found online, I'm not an experienced developer so any help is greatly appreciated!!

'm trying to create an email handler that creates a contact from incoming emails where the contact doesnt exist already

}

@isTest
private class testCreateContactFrmEmail
{static testMethod void testCreateContactFrmEmail() {
Messaging.InboundEmail email = new Messaging.InboundEmail() ;
Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();

email.subject = 'Create Contact';
email.plainTextBody = 'FromEmail';
env.fromAddress = 'testemail@gmail.com';

CreateContactFrmEmail creatC = new CreateContactFrmEmail();
creatC.handleInboundEmail(email, env );
}
}
}
Here is my SFDC query in Jitterbit: 
SELECT Id, ContentType, CreatedDate, Description, Name, ParentId,
Parent.Id, Parent.Name, Parent.Email FROM Attachment  WHERE ((
Parent.Name LIKE 'Congratulations%') OR (Parent.Name
LIKE 'Approval - eForms%')) AND CreatedDate>=TODAY 

When I execute, I get a "No records found". This happens for CreatedDate= YESTERDAY and THIS_MONTH as well. The earliest I can get it to pull records from is =LAST_MONTH and it pulls from October 2020 no problem. I have about 45 records that meet this criteria every day. There are 100p records in the org. I would like to pull these attachments every day into a folder, the purpose behind the query.  
 
I am trying to create a flow that deletes email messages over 2 years old. When I run the flow, however, I get a "Failed to delete records that meet the filter criteria." I've included screenshots of this very simple flow. I'm only filtering on status and LastModifiedDate so no records should have null values for either of those.

thank you!
User-added image
User-added imageUser-added imageUser-added image