• Michael M
  • SMARTIE
  • 1730 Points
  • Member since 2019

  • Chatter
    Feed
  • 1
    Best Answers
  • 4
    Likes Received
  • 0
    Likes Given
  • 207
    Questions
  • 397
    Replies
This code doesnt work.



trigger CreateCase on Contact (before insert) {
 
    List<Case> listCase = new List<Case>();
     for(Contact a : Trigger.New) {  
          listCase.add(new Case(
          AccountID=a.AccountID,        
          ContactID = a.Name,
          Priority ='High',
          Origin = 'Phone',
          Status = 'Working')); 
          }
       
     if(listCase.size() > 0)
  {
        insert listCase;
    }
}
Hello, I am building a force.com site through our salesforce org. Right now, the URL is the domain name / the page name. I want to make it so that the URL is a custom URL of my choosing. Is that possible? And is it free?
Hello, one of our users wants to be able to see all of the chatter messages that she sent, all in one place. Is there a way to do that?
Hello, we just wrote a trigger to prevent one of our users from deleting files that were not created by him. This is the trigger, below. I tried writing test code, but it is covering 0% of the trigger. Any idea why, or how I can get the test code to work? 

Trigger and test below.


Trigger:
trigger FileDeletionPrevention on ContentDocument (before delete) {
    if (trigger.isBefore){
    for (ContentDocument cd : trigger.old){
            Id deleter = UserInfo.getUserId();
            Id uploader = cd.CreatedById;
        if (deleter == '0051N000006BSeyQAG'){
            if (deleter != uploader){
                cd.adderror('File cannot be deleted');
            }
        }
    }
}
}


Test:
@isTest(seealldata = true)
public class FileDeletionPreventionTest {

   @isTest
    public static void fileDeleter(){

        
        user u = [select id, name from user where name = 'Integration User'];
        
        Test.startTest();
        
      ContentVersion cv=new Contentversion();
        cv.title='ABC';
        cv.PathOnClient ='test';
        Blob b=Blob.valueOf('Unit Test Attachment Body');
        cv.versiondata=EncodingUtil.base64Decode('Unit Test Attachment Body');
        insert cv;
        
        System.runas(u){
            id cvDocId = cv.ContentDocumentId;
          list<contentDocument> cd = [select id from contentdocument where id =:cvDocId];
            delete cd;
        }
        Test.stopTest();
        
    }
}
Hello, I am using a lightning component to create new records. In sandbox it works fine, but in Production, when I click save, it is giving an error response. When I print the error message, it just says "undefined". Any idea what the issue could be?
Hello, I have a VF page that has a commandbutton that triggers an action to send an email. I am testing this in sandbox, and it works whenever I click the button, but if I login as another user, it does not work. There is no error message displayed, it just simply does not work. Why would that be? 
We need to import a number of Leads and Opportunities, but we want to link them to make it as if the Lead was "Converted" into that opportunity. Is there any way to do so, without needing to import them as leads and then manually converting every lead?
Hello, I need to create a custom button that opens a visualforce page. However, I don't want the user to be redirected to a new page. Rather, I want the visualforce page to appear in a small modal window, popped up over the record page that the user is already on. Is that possible?
Hello, I would like to set up an apex trigger after a ListEmail is sent. However, i am seeing that ListEmail object is not a choice in the list of trigger objects. There is only "ListEmailChangeEvent". I am not familiar with that trigger. What would be an example of how I could use the ListEmailChangeEvent object trigger to fire after a ListEmail is sent?
I am displaying a createddate in my VF page. However the time is showing in GMT time. How can I change that to eastern time zone? 

      <apex:column >
       <apex:facet name="header">Date Sent</apex:facet>
             <apex:outputText value="{0, date, MMMM d','  yyyy  'at' HH:mm:ss a}">
    <apex:param value="{!noteslist.createddate}" /> 
     </apex:outputText>
     </apex:column>
Hello, I am getting this error when trying to run my test class: System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, There exists no recipient to which you can send this List Email to.: []   Class.CampaignEmailHistoryTest.testNotesExtension: line 10, column 1


How can I fix this? 

Here is the test class:
@isTest
public class CampaignEmailHistoryTest {
    @isTest
    static void testNotesExtension(){

Campaign testCampaign= new Campaign(Name= 'Test');
insert testCampaign;
        
ListEmail le = new ListEmail(campaignId=testCampaign.id, subject= 'hey there',Status= 'Scheduled'); 
    insert le;
   
  ApexPages.StandardController con = new ApexPages.StandardController(testCampaign);
  CampaignEmailHistoryExtension  dce = new CampaignEmailHistoryExtension(con);
         
    }
    
}


And the real class:
public class CampaignEmailHistoryExtension {
public final Campaign thisCampaign;
 
    Public List<ListEmail> listEmails {get; set;}
 
    Public CampaignEmailHistoryExtension(ApexPages.StandardController stdController){
        this.thisCampaign = (Campaign)stdController.getRecord();

        try{
  
            Campaign camp=[Select Id, Name from Campaign where Id = :this.thisCampaign.id];
        
        listEmails = [SELECT ID, campaignId, CreatedDate, CreatedById, CreatedBy.FirstName, CreatedBy.LastName, subject, LastViewedDate
                      FROM ListEmail 
                      WHERE  campaignId IN (Select id from Campaign where Id = :this.thisCampaign.id)];
        }
        catch(exception e){
            Apexpages.addMessage(new ApexPages.Message(ApexPages.SEVERITY.FATAL, 'No old records'));
        }       
}
}
Are there any common ID's on ListEmail and EmailStatus classes? 

My task is to get the emailstatuses of list emails sent through a campaign. I know that ListEmail class can get the CampaignID. But now I need to get the Email Statuses of those emails. Is that possible? I would be able to do it by the ownerid of the listemail or by the campaignid.  Are there any common fields between listemail and emailstatus?
Hello, would someone be able to show me how to write test code for this basic controller extension:

public class CampaignEmailHistoryExtension {
public final Campaign thisCampaign;
 
    Public List<ListEmail> listEmails {get; set;}
 
    Public CampaignEmailHistoryExtension(ApexPages.StandardController stdController){
        this.thisCampaign = (Campaign)stdController.getRecord();

        try{
  
            Campaign camp=[Select Id, Name from Campaign where Id = :this.thisCampaign.id];
        
        listEmails = [SELECT ID, campaignId, CreatedDate, CreatedById, CreatedBy.FirstName, CreatedBy.LastName, subject, LastViewedDate
                      FROM ListEmail 
                      WHERE  campaignId IN (Select id from Campaign where Id = :this.thisCampaign.id)];
        }
        catch(exception e){
            Apexpages.addMessage(new ApexPages.Message(ApexPages.SEVERITY.FATAL, 'No old records'));
        }       
}
}
Hello, I have written some apex code that currently does 3 things:
1) fetches the results of EmailStatuses for listemails 
2) puts that into a csv
3) emails that csv

I need to do a 4th thing: I need to summarize the results on the body of the email itself. In other words, I need to organize the queried data by "emailstatus.task.subject", and for each different subject, I need to show a summary of: 
1. number of contacts it was sent to
2. number of contacts who opened the email

Is this possible, and can you please show me how to do so. Here is my code so far:

// fetch Data using SOQL from Salesforce
List<Contact> contList = [Select id, name, CreatedDate, lastModifiedDate, email,
                           (SELECT  id, taskId, createdDate, firstOpenDate, lastOpenDate, timesOpened, emailTemplateName, task.subject, task.TaskSubtype
                          FROM EmailStatuses where createddate = last_month and task.tasksubtype = 'ListEmail')
                          from Contact where email != null ];
//Set Header values of the file
string csvHeader = 'Contact Name, Contact Email    , Subject, Date Sent, Times Opened, Task Subtype \n';
string mainContent = csvHeader;
for (Contact cnt: contList){
    for (emailstatus es : cnt.EmailStatuses){
        integer month = es.createddate.month();
        integer year = es.createddate.year();
    integer day = es.createddate.day();
        if (month == 12 && year == 2020 && day == 8){
      //Adding records in a string
       string recordString = cnt.name+','+cnt.email +','+es.task.subject +','+es.CreatedDate+','+es.timesOpened +','+es.task.tasksubtype +'\n';
       mainContent += recordString;
        }}}
Messaging.EmailFileAttachment csvAttcmnt = new Messaging.EmailFileAttachment ();

//Create CSV file using Blob
blob csvBlob = Blob.valueOf (mainContent);
string csvname= 'Contact.csv';
csvAttcmnt.setFileName (csvname);
csvAttcmnt.setBody (csvBlob);
Messaging.SingleEmailMessage singEmail = new Messaging.SingleEmailMessage ();
String [] toAddresses = new list<string> {'test@test.org'};
//Set recipient list
singEmail.setToAddresses (toAddresses);
String subject ='Contact CSV';
singEmail.setSubject (subject);
singEmail.setPlainTextBody ('Contact CSV');

//Set blob as CSV file attachment
singEmail.setFileAttachments (new Messaging.EmailFileAttachment []{csvAttcmnt});
Messaging.SendEmailResult [] r = Messaging.sendEmail (new Messaging.SingleEmailMessage [] {singEmail});
Hello, I have apex code that collects the EmailStatus for listemails tha thave been sent. I would like to trigger this to send 3 days after a ListEmail is sent. Is that possible, and if so how?

Here is my code, if this helps to visualize what I am talking about:
// fetch Data using SOQL from Salesforce
List<Contact> contList = [Select id, name, CreatedDate, lastModifiedDate, email,
                           (SELECT  id, taskId, createdDate, firstOpenDate, lastOpenDate, timesOpened, emailTemplateName, task.subject, task.TaskSubtype
                          FROM EmailStatuses where createddate = last_month and task.tasksubtype = 'ListEmail')
                          from Contact where email != null ];
//Set Header values of the file
string csvHeader = 'Contact Name, Contact Email    , Subject, Date Sent, Times Opened, Task Subtype \n';
string mainContent = csvHeader;
for (Contact cnt: contList){
    for (emailstatus es : cnt.EmailStatuses){
        integer month = es.createddate.month();
        integer year = es.createddate.year();
    integer day = es.createddate.day();
        if (month == 12 && year == 2020 && day == 8){
      //Adding records in a string
       string recordString = cnt.name+','+cnt.email +','+es.task.subject +','+es.CreatedDate+','+es.timesOpened +','+es.task.tasksubtype +'\n';
       mainContent += recordString;
        }}}
Messaging.EmailFileAttachment csvAttcmnt = new Messaging.EmailFileAttachment ();

//Create CSV file using Blob
blob csvBlob = Blob.valueOf (mainContent);
string csvname= 'Contact.csv';
csvAttcmnt.setFileName (csvname);
csvAttcmnt.setBody (csvBlob);
Messaging.SingleEmailMessage singEmail = new Messaging.SingleEmailMessage ();
String [] toAddresses = new list<string> {'me@comp.org'};
//Set recipient list
singEmail.setToAddresses (toAddresses);
String subject ='Contact CSV';
singEmail.setSubject (subject);
singEmail.setPlainTextBody ('Contact CSV');

//Set blob as CSV file attachment
singEmail.setFileAttachments (new Messaging.EmailFileAttachment []{csvAttcmnt});
Messaging.SendEmailResult [] r = Messaging.sendEmail (new Messaging.SingleEmailMessage [] {singEmail});
Does Salesforce have cPanel access? Or the equivalent? 
Hello, would someone be able to show me how to write test code for this class of mine: 

public with sharing class FetchCurrentURL {

 public class VisitorUrlOutput {
    @InvocableVariable(required=false)
    public String urlOfMostRecentPage;
  }

 @InvocableMethod(label='Get Current URL' description='Returns Current URL')
 public static List<String> getcurrentURL() {
   System.debug(URL.getSalesforceBaseUrl().toExternalForm());
   return new List<String>{URL.getSalesforceBaseUrl().toExternalForm()};
   }
 }
Hello, I am building an einstein bot, and I want to get the url (window.location.href) of the chatbot in the MIDDLE of the einstein bot dialogue (and therefore extraprechatformdetails won't do the job here.) Einstein bots allow invoking either apex or a flow in the middle of a dialogue. My question is: can I run javascript from a flow or apex class, so that I can get the window.location.href and save it as a variable that I can reference in my bot dialogue?
Hello, is there a way to integrate a live google spreadsheet with salesforce? So that the live updates show up in SF?
Hello, I am trying to invoke an apex class to get the current user's URL, from my chatbot dialogue. Here is my apex class. It does not seem to work- when it gets to that point in the chatbot, the bot sort of shuts down and says no agent is available. Am I doing this correctly?
public with sharing class BotUrlClass {
public class TranscriptInput {
    @InvocableVariable(required=true)
    public ID routableID;
    
  }
  
  public class VisitorUrlOutput {
    @InvocableVariable(required=true)
    public String urlOfMostRecentPage;
      
  }
 
  @InvocableMethod(label='Get User URL')
  public static List<VisitorUrlOutput> getUrlName(List<TranscriptInput> transcripts) {
 
    List<VisitorUrlOutput> urls = new List<VisitorUrlOutput>();
  
    for (TranscriptInput transcript : transcripts) {
    
      // Query for the transcript record based on the ID
      LiveChatTranscript transcriptRecord = [SELECT Name, URL__c
                                             FROM LiveChatTranscript 
                                             WHERE Id = :transcript.routableID 
                                             LIMIT 1];
        
        string headerdata2= ApexPages.currentPage().getHeaders().get('Host');
        string urlvalue2=Apexpages.currentPage().getUrl();
        string url2='https://' + headerdata2+ urlvalue2;  
        
      
      // Store the url in an output variable
      VisitorUrlOutput urlData = new VisitorUrlOutput();
      urlData.urlOfMostRecentPage = url2;
      
      // Add the url to the list of outputs
      urls.add(urlData);
    }
    
    return urls;
  }
}
Hello, I am setting up my first einstein bot... We have a dialogue that presents a menu. When the user clicks on one of the menu items (also a dialogue) we want it to automatically redirect the user to a new webpage. How can I build this into the bot/dialogue?
I am parsing JSON that is coming back from  REST callout, and when running, it is throwing this error: attempt to de-reference null object. The issue seems to be with how I am parsing the JSON, but I am not sure where I am going wrong. Can someone help?

Here is the snippet of the JSON I am parsing:
"result": {
"first_name": "JOHN",
"last_name": "SMITH",
"id_type": "MI",
"subscriber_id": "1234567",
"gender": "M",
"birthdate": "19601119",
"address": {
"info": "123 Main St.",
"city": "New York",
"state": "NY",
"zip_code": "100000"
},
"county:": {
"value": "14"
},
"office": {
"value": "H78"
},
"recert_month": {
"value": "12",
"name": "December"
},
"dates": [
{
"name": "Service",
"qualifier": "472",
"date": "2020-09-29"
},
{
"name": "Plan Begin",
"qualifier": "346",
"date": "2020-09-01"
},
{
"name": "Issue",
"qualifier": "102",
"date": "2020-06-01"
}
],


Here is how I am parsing it (bold part is causing error):
  
        Map<String, Object> wholeResponse = (Map<String, Object>) JSON.deserializeUntyped(response2.getBody());
            Map<String, Object> result = (Map<String, Object>) wholeResponse.get('result');
                Map<String, Object> residentAddress = (Map<String, Object>) result.get('address');
                   Map<String, Object> county = (Map<String, Object>) result.get('county');
                  Map<String, Object> office = (Map<String, Object>) result.get('office');
                 Map<String, Object> recert_month = (Map<String, Object>) result.get('recert_month');
        
       Eligibility__c newEligRec = new Eligibility__c(); 
        newEligRec.Referral_Name__c = ref.id;
        newEligRec.First_Name__c = string.valueof(result.get('first_name'));
        newEligRec.Last_Name__c = string.valueof(result.get('last_name'));
        newEligRec.Name_Id_Type__c = string.valueof(result.get('id_type'));
        newEligRec.Client_ID__c = string.valueOf(result.get('subscriber_id'));
        newEligRec.Gender__c = string.valueOf(result.get('gender'));
        string birthdate;
              if (string.valueof(result.get('birthdate')) != null){
                  birthdate = string.valueof(result.get('birthdate')).remove('-');
                  string year = birthdate.substring(0,4);
                  string month = birthdate.substring(4,6);
                  string day = birthdate.substring(6,8);
                 birthdate = month + '/' + day + '/' + year;
                    }
        newEligRec.Date_of_Birth__c = birthdate;
        newEligRec.Address_Number_and_Street__c = string.valueOf(residentAddress.get('info')); 
        newEligRec.City__c =  string.valueOf(residentAddress.get('city'));    
        newEligRec.State__c =  string.valueOf(residentAddress.get('state'));    
        newEligRec.Zip_Code__c = string.valueOf(residentAddress.get('zip_code'));
        newEligRec.County__c = string.valueOf(county.get('value'));
        newEligRec.Office__c = string.valueOf(office.get('value'));
        newEligRec.Recertification_Month_value__c = string.valueOf(recert_month.get('value'));
        newEligRec.Recertification_Month__c = string.valueOf(recert_month.get('name'));
Hello, Would someone be able to assist in writing a test class for the following apex class:
global class purgeFiles implements Schedulable{
    
    global void execute(SchedulableContext SC) {
        
    List<ContentDocumentLink > docs;
        docs = [SELECT Id, Linkedentity.name, Linkedentity.id,ContentDocument.CreatedDate  
                FROM contentDocumentLink 
                WHERE Linkedentityid 
                IN (SELECT Id FROM lead where createddate < Last_N_Days:7 and isconverted = false) ];  
                //may want to change to include ALL leads
                //AND ContentDocument.CreatedDate < Last_N_Days:7];
                if(!docs.isEmpty())
            delete docs;
    }
}

Thank you very much
When I try to drag my VF page to the lightning record page, and try to save, it gives this error: "Component 'Visualforce' has an invalid value for property 'Visualforce Page Name'."  What is the problem?
Hello, I am building a force.com site through our salesforce org. Right now, the URL is the domain name / the page name. I want to make it so that the URL is a custom URL of my choosing. Is that possible? And is it free?
Hello, one of our users wants to be able to see all of the chatter messages that she sent, all in one place. Is there a way to do that?
Hello, I am using a lightning component to create new records. In sandbox it works fine, but in Production, when I click save, it is giving an error response. When I print the error message, it just says "undefined". Any idea what the issue could be?
Hello, I have a VF page that has a commandbutton that triggers an action to send an email. I am testing this in sandbox, and it works whenever I click the button, but if I login as another user, it does not work. There is no error message displayed, it just simply does not work. Why would that be? 
We need to import a number of Leads and Opportunities, but we want to link them to make it as if the Lead was "Converted" into that opportunity. Is there any way to do so, without needing to import them as leads and then manually converting every lead?
Hello, I would like to set up an apex trigger after a ListEmail is sent. However, i am seeing that ListEmail object is not a choice in the list of trigger objects. There is only "ListEmailChangeEvent". I am not familiar with that trigger. What would be an example of how I could use the ListEmailChangeEvent object trigger to fire after a ListEmail is sent?
I am displaying a createddate in my VF page. However the time is showing in GMT time. How can I change that to eastern time zone? 

      <apex:column >
       <apex:facet name="header">Date Sent</apex:facet>
             <apex:outputText value="{0, date, MMMM d','  yyyy  'at' HH:mm:ss a}">
    <apex:param value="{!noteslist.createddate}" /> 
     </apex:outputText>
     </apex:column>
Hello, I am getting this error when trying to run my test class: System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, There exists no recipient to which you can send this List Email to.: []   Class.CampaignEmailHistoryTest.testNotesExtension: line 10, column 1


How can I fix this? 

Here is the test class:
@isTest
public class CampaignEmailHistoryTest {
    @isTest
    static void testNotesExtension(){

Campaign testCampaign= new Campaign(Name= 'Test');
insert testCampaign;
        
ListEmail le = new ListEmail(campaignId=testCampaign.id, subject= 'hey there',Status= 'Scheduled'); 
    insert le;
   
  ApexPages.StandardController con = new ApexPages.StandardController(testCampaign);
  CampaignEmailHistoryExtension  dce = new CampaignEmailHistoryExtension(con);
         
    }
    
}


And the real class:
public class CampaignEmailHistoryExtension {
public final Campaign thisCampaign;
 
    Public List<ListEmail> listEmails {get; set;}
 
    Public CampaignEmailHistoryExtension(ApexPages.StandardController stdController){
        this.thisCampaign = (Campaign)stdController.getRecord();

        try{
  
            Campaign camp=[Select Id, Name from Campaign where Id = :this.thisCampaign.id];
        
        listEmails = [SELECT ID, campaignId, CreatedDate, CreatedById, CreatedBy.FirstName, CreatedBy.LastName, subject, LastViewedDate
                      FROM ListEmail 
                      WHERE  campaignId IN (Select id from Campaign where Id = :this.thisCampaign.id)];
        }
        catch(exception e){
            Apexpages.addMessage(new ApexPages.Message(ApexPages.SEVERITY.FATAL, 'No old records'));
        }       
}
}
Are there any common ID's on ListEmail and EmailStatus classes? 

My task is to get the emailstatuses of list emails sent through a campaign. I know that ListEmail class can get the CampaignID. But now I need to get the Email Statuses of those emails. Is that possible? I would be able to do it by the ownerid of the listemail or by the campaignid.  Are there any common fields between listemail and emailstatus?
Hello, would someone be able to show me how to write test code for this basic controller extension:

public class CampaignEmailHistoryExtension {
public final Campaign thisCampaign;
 
    Public List<ListEmail> listEmails {get; set;}
 
    Public CampaignEmailHistoryExtension(ApexPages.StandardController stdController){
        this.thisCampaign = (Campaign)stdController.getRecord();

        try{
  
            Campaign camp=[Select Id, Name from Campaign where Id = :this.thisCampaign.id];
        
        listEmails = [SELECT ID, campaignId, CreatedDate, CreatedById, CreatedBy.FirstName, CreatedBy.LastName, subject, LastViewedDate
                      FROM ListEmail 
                      WHERE  campaignId IN (Select id from Campaign where Id = :this.thisCampaign.id)];
        }
        catch(exception e){
            Apexpages.addMessage(new ApexPages.Message(ApexPages.SEVERITY.FATAL, 'No old records'));
        }       
}
}
Hello, I am need to send one of our reports via csv. I am trying through apex with this code:

global class ReportEmailCharles implements system.Schedulable {
 global void execute(SchedulableContext sc) {
        ApexPages.PageReference report = new ApexPages.PageReference('/00O63000000uP8GEAU?csv=1');
        Messaging.EmailFileAttachment attachment = new Messaging.EmailFileAttachment();
        attachment.setFileName('report.csv');
      attachment.setBody(Blob.valueof(report.getContent().toString()));
        attachment.setContentType('text/csv');
        Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
        message.setFileAttachments(new Messaging.EmailFileAttachment[] { attachment } );
        message.setSubject('Overall Pull- 2 All');
        message.setPlainTextBody('Overall Pull- 2 All');
        message.setToAddresses( new String[] { 'mm@abc.org' } );
        Messaging.sendEmail( new Messaging.SingleEmailMessage[] { message } );
        
    }
}

The 18 character id of the report I'm testing is 00O63000000uP8GEAU

However the "csv" excel doc of the email I receive looks like this:

User-added image
Anything I can change in my code to make this work?