• Sandeep TechAffinity
  • NEWBIE
  • 25 Points
  • Member since 2021

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 17
    Questions
  • 9
    Replies
Hello Guys,

I have a Test class on InboundEmail Service Class and it includes sObjects Like Lead, EmailMessage, Task, User, and Attachments Can anyone please help me with the Test class.
global class captureEmailResponses implements Messaging.InboundEmailHandler {
    //  Handles inbound email replies from leads and puts the details into Email Messages which creates a
    //  Activity Entry. This will also update the lead status to patient replied.
    global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email, Messaging.InboundEnvelope env){
        // Create an InboundEmailResult object for returning the result of the
        // Apex Email Service
        Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
        // Set the activity name to the email from name
        String Activityname = email.fromname;
        // Find the lead by the from address
        String fromemailaddresss = email.fromAddress;
        String des = email.plainTextBody;
        String tasksubject = email.subject;
        try {
            // Lets get the original message
            EmailMessage originalMessage = [SELECT ReplyToEmailMessageId, MessageIdentifier, ThreadIdentifier, CreatedById, ActivityId FROM EmailMessage WHERE MessageIdentifier = :email.inReplyTo LIMIT 1];
            
            // Get Task from original Message
            Task linkedTask = [SELECT Id, WhoId FROM Task WHERE Id = :originalMessage.ActivityId LIMIT 1];
            // Get lead from WhoId
            Lead lead = [SELECT Id, Name, Email, ShareGroupId__c, LastModifiedById, Status FROM Lead 
                         WHERE Id = :linkedTask.WhoId LIMIT 1];
            User lastUser = [SELECT Id, Email FROM User
                             WHERE Id = :originalMessage.CreatedById LIMIT 1];
            // Create a email message because we use enhanced emails and it creates the activity automatically.
            EmailMessage[] newEmail = new EmailMessage[0];
            String[] toUsers = new String[]{lead.LastModifiedById};
                newEmail.add(new EmailMessage(FromAddress = email.fromAddress,
                                              FromName = email.fromName,
                                              Incoming = True,
                                              ToAddress = lastUser.Email,
                                              //ToAddress = email.toAddresses[0],
                                              Subject = email.subject,
                                              //RelatedToId = lead.Id, // This throws error about not the expected type???
                                              TextBody = email.plainTextBody,
                                              HtmlBody = email.htmlBody,
                                              MessageIdentifier = email.messageId,
                                              ReplyToEmailMessageId = originalMessage.Id,
                                              ThreadIdentifier = originalMessage.ThreadIdentifier,
                                              Status = '3')); // Sets to replied.
            
            insert newEmail;
            // Add Email Message Relation to the lead because they sent it...
            EmailMessageRelation emr = new EmailMessageRelation();
            emr.emailMessageId = newEmail[0].Id;
            emr.relationAddress = email.fromAddress;
            emr.relationId = lead.id; // Lead Id
            emr.relationType = 'FromAddress';
            insert emr;
            
            EmailMessageRelation toEmr = new EmailMessageRelation();
            toEmr.emailMessageId = newEmail[0].Id;
            toEmr.relationAddress = lastUser.Email;
            toEmr.relationId = lastUser.Id; // User Id
            toEmr.relationType = 'ToAddress';
            insert toEmr;
            
            // Update the lead status to Patient Replied
            lead.status = 'Patient Replied';
            update lead;
            // The below was ripped from a forum https://developer.salesforce.com/forums/?id=906F00000008um5IAA, but I dont know if it works?
            // Add any binary attachments to the lead
            
            if(email.textAttachments != null)
            {
                // Save attachments, if any
                for (Messaging.Inboundemail.TextAttachment tAttachment : email.textAttachments) {
                    Attachment attachment = new Attachment();
                    
                    attachment.Name = tAttachment.fileName;
                    attachment.Body = Blob.valueOf(tAttachment.body);
                    attachment.ParentId = lead.Id;
                    insert attachment;
                }
            }
            if(email.binaryAttachments != null && email.binaryAttachments.size() > 0){
                for(Messaging.InboundEmail.BinaryAttachment att : email.binaryAttachments){
                    system.debug('attachmentsList -> '+email.binaryAttachments);
                }
                List<ContentVersion>cvList = new List<ContentVersion>();
                List<ContentDocumentLink> cdlList = new List<ContentDocumentLink>();
                for (Messaging.InboundEmail.BinaryAttachment binAttach : email.binaryAttachments) {
                    ContentVersion testContentInsert = new ContentVersion();
                    testContentInsert.Title = binAttach.fileName;
                    testContentInsert.VersionData = binAttach.body;
                    testContentInsert.PathOnClient = '/' + binAttach.fileName ;
                    cvList.add(testContentInsert);
                    
                }
                insert cvList;
                cvList = [select id, ContentDocumentId from ContentVersion WHERE Id in :cvList];
                for (ContentVersion cv : cvList) {
                    ContentDocumentLink cl = new ContentDocumentLink();
                    cl.ContentDocumentId = cv.ContentDocumentId;
                    cl.LinkedEntityId = lead.id; //Shared with record ID
                    cl.ShareType = 'I';
                    cl.Visibility = 'AllUsers';
                    cdlList.add(cl);
                }
                insert cdlList;
            }else{
                system.debug('attachmentsList -> '+email.binaryAttachments);
            }
            
        }
        // If an exception occurs when the query accesses
        // the contact record, a QueryException is called.
        // The exception is written to the Apex debug log.
        catch (QueryException e) {
            System.debug('Query Issue: ' + e);
            System.debug('Query Issue: ' + e.getLineNumber());
            System.debug('Query Issue: ' + e.getCause());
            System.debug('Query Issue: ' + e.getTypeName());
            System.debug('Query Issue: ' + e.getMessage());
        }
        result.success = true;
        // return nothing...
        return result;
    }
}



Thank you
Sandeep. 
Hi Guys,

I have created an Inbound Email service. But I am not sure how to create a Test class. Help me.
 
global class captureEmailResponses implements Messaging.InboundEmailHandler {
    global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email, Messaging.InboundEnvelope env){
        Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
        String Activityname = email.fromname;
        String fromemailaddresss = email.fromAddress;
        String des = email.plainTextBody;
        String tasksubject = email.subject;
        try {
            system.debug('Reply To '+email.inReplyTo);
            EmailMessage originalMessage = [SELECT ReplyToEmailMessageId, MessageIdentifier, ThreadIdentifier, CreatedById, ActivityId FROM EmailMessage WHERE MessageIdentifier = :email.inReplyTo LIMIT 1];

            Task linkedTask = [SELECT Id, WhoId FROM Task WHERE Id = :originalMessage.ActivityId LIMIT 1];

            Lead lead = [SELECT Id, Name, Email, ShareGroupId__c, LastModifiedById, Status
                         FROM Lead
                         WHERE Id = :linkedTask.WhoId
                         LIMIT 1];
            User lastUser = [SELECT Id, Email
                             FROM User
                             WHERE Id = :originalMessage.CreatedById
                             LIMIT 1];
            EmailMessage[] newEmail = new EmailMessage[0];
            String[] toUsers = new String[]{lead.LastModifiedById};
                newEmail.add(new EmailMessage(FromAddress = email.fromAddress,
                                              FromName = email.fromName,
                                              Incoming = True,
                                              ToAddress = lastUser.Email,
                                              //ToAddress = email.toAddresses[0],
                                              Subject = email.subject,
                                              //RelatedToId = lead.Id, // This throws error about not the expected type???
                                              TextBody = email.plainTextBody,
                                              HtmlBody = email.htmlBody,
                                              MessageIdentifier = email.messageId,
                                              ReplyToEmailMessageId = originalMessage.Id,
                                              ThreadIdentifier = originalMessage.ThreadIdentifier,
                                              Status = '3')); // Sets to replied.
            
            insert newEmail;

            EmailMessageRelation emr = new EmailMessageRelation();
            emr.emailMessageId = newEmail[0].Id;
            emr.relationAddress = email.fromAddress;
            emr.relationId = lead.id; // Lead Id
            emr.relationType = 'FromAddress';
            insert emr;
            
            EmailMessageRelation toEmr = new EmailMessageRelation();
            toEmr.emailMessageId = newEmail[0].Id;
            toEmr.relationAddress = lastUser.Email;
            toEmr.relationId = lastUser.Id; // User Id
            toEmr.relationType = 'ToAddress';
            insert toEmr;
            
            lead.status = 'Patient Replied';
            update lead;
            
            if(email.textAttachments != null)
            {
                system.debug('email.textAttachments '+ email.textAttachments);

                for (Messaging.Inboundemail.TextAttachment tAttachment : email.textAttachments) {
                    Attachment attachment = new Attachment();
                    
                    attachment.Name = tAttachment.fileName;
                    attachment.Body = Blob.valueOf(tAttachment.body);
                    attachment.ParentId = lead.Id;
                    insert attachment;
                }
            }
            if(email.binaryAttachments != null && email.binaryAttachments.size() > 0){
                for(Messaging.InboundEmail.BinaryAttachment att : email.binaryAttachments){
                    system.debug('attachmentsList -> '+email.binaryAttachments);
                }
                List<ContentVersion>cvList = new List<ContentVersion>();
                List<ContentDocumentLink> cdlList = new List<ContentDocumentLink>();
                for (Messaging.InboundEmail.BinaryAttachment binAttach : email.binaryAttachments) {
                    system.debug('@@@ binAttach.fileName '+binAttach.fileName);
                    system.debug('@@@ binAttach.fileName '+binAttach.body);
                    system.debug('@@@ binAttach.fileName '+binAttach.fileName);
                    
                    ContentVersion testContentInsert = new ContentVersion();
                    testContentInsert.Title = binAttach.fileName;
                    testContentInsert.VersionData = binAttach.body;
                    testContentInsert.PathOnClient = '/' + binAttach.fileName ;
                    cvList.add(testContentInsert);
                    
                }
                insert cvList;
                cvList = [select id, ContentDocumentId from ContentVersion WHERE Id in :cvList];
                for (ContentVersion cv : cvList) {
                    ContentDocumentLink cl = new ContentDocumentLink();
                    cl.ContentDocumentId = cv.ContentDocumentId;
                    cl.LinkedEntityId = lead.id; //Shared with record ID
                    cl.ShareType = 'I';
                    cl.Visibility = 'AllUsers';
                    cdlList.add(cl);

                }
                insert cdlList;
  
            }else{
                system.debug('attachmentsList -> '+email.binaryAttachments);
            }
            
        }

        catch (QueryException e) {
            System.debug('Query Issue: ' + e);
            System.debug('Query Issue: ' + e.getLineNumber());
            System.debug('Query Issue: ' + e.getCause());
            System.debug('Query Issue: ' + e.getTypeName());
            System.debug('Query Issue: ' + e.getMessage());
        }
        result.success = true;
        return result;
    }
}




Thank You
Sandeep
Hi Guys,

I have configured a SAML. Now I want to change the Login URL ID. If it is possible let me know.
User-added image
We have an email service to send emails to a Lead but all emails are bounced back can anyone help me on this. Email also correct.

User-added imageUser-added imagehttp://​​​​​​​https://help.salesforce.com/s/articleView?id=000331521&type=1 (http://https://help.salesforce.com/s/articleView?id=000331521&type=1)

Hi Guys,

We have a "Related Accounts" related list on the Contact object. It Seems it is Standard. How can we add related accounts to each contact using Apex.

User-added imageThanks

Hi Guys,

In the Test Class when I am trying to insert CampaignMember Record with Type "Lead" It is getting an error Like
System.DmlException: Upsert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Account__c]: [Account__c]
But I Need CampaignMember record with Lead Id only.
Can Anyone help me with this?

Thanks
Sandeep.

 
Hi Guys,
I have a Test Class issue can anyone tell me the mistake. I have custom filed "ClinicCode" in the Lead object. I am not passing the code in the test class but the lead is stored under the "leadsWithClinicsList" list. It should be in "leadsWithOutClinicsList"
User-added imageUser-added image

Hi Guys,

I have a Batch Class and the Test class. Test coverage is 100% but deployment got validation error.

 

System.UnexpectedException: No more than one executeBatch can be called from within a test method. Please make sure the iterable returned from your start method matches the batch size, resulting in one executeBatch invocation.
Stack Trace: External entry point


The code is

global class addTaskObjectToQueues implements Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext bc){
        Set<String> queueSet = new Set<String>();
        List<QueueSobject> lstQueueSobject = [SELECT QueueId FROM QueueSobject where SobjectType = 'Task'];
        for(QueueSobject qs : lstQueueSobject){
            queueSet.add(qs.QueueId);
        }
        string query = 'SELECT Id FROM Group where Type = \'queue\' AND Id NOT IN : queueSet'+(Test.isRunningTest()?' LIMIT 200':'');
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext bc, List<Group> scope){
        List<QueueSobject> supportedObjList = new List<QueueSobject>();
       for(Group gp : scope) {
            QueueSobject qs = new QueueSobject();
            qs.QueueId = gp.id;
            qs.SobjectType = 'Task';
            supportedObjList.add(qs);
        }
        if(!supportedObjList.isEmpty()) {
            insert supportedObjList;
        }
        
    }
    global void finish(Database.BatchableContext bc){
        
    }
    
}
Test Class
=========
@isTest 
public class addTaskObjectToQueuesTest {
    
    static testMethod void testMethod1() 
    {
        test.startTest();
        List<Group> lstGroup = new List<Group>();
        for(Integer i=0 ;i <50;i++)
        {
            Group grp = new Group();
            grp.name = 'test'+i;
            grp.type = 'Queue';
            lstGroup.add(grp);
        }
        
        insert lstGroup;
        
        List<QueuesObject> qsobj = new List<QueuesObject>();
        integer counter = 0;
        for(Group g : lstGroup){
            QueuesObject q = new QueueSObject();
            q.QueueID = g.Id;
            q.SobjectType = 'Lead';
            
        }
        insert qsobj;
        
        
        DataBase.executeBatch(new addTaskObjectToQueues(),150);
        test.stopTest();
    }
    
}

​​​​​​​
 

Hello guys,
 
I am trying to create a Task and want to assign it to Queue but it shows double values and only one is correct how to avoid this.  

Thanks.

User-added image

Hi Guys,

I am trying to create ListViews using Metadata API, according to this Link
https://developer.salesforce.com/docs/atlas.en-us.232.0.api_meta.meta/api_meta/meta_listview.htm

Field names in the ListView columns don’t always match their API name counterparts. If person accounts are enabled in your organization, standard fields merged from a contact into an account start with the PC_ prefix, while the corresponding API name starts with the Person prefix. For example, the ListView column name is PC_Email for a corresponding API field name of PersonEmail.

API names are not forking for example the Contact name API name is "FirstName" but in metadata, it takes like "FULL_NAME" (I just took randomly it is not working for other fileds)
Can anyone help me how to find out the field API NAme?
Hi Guys,
I wrote a test class for Mock Test which covers when if the status code is 200, now I want to cover else part which is other than 200.
 
@isTest
public class ChatMessageTrigger_Test {
    private class RestMock implements HttpCalloutMock {
        
        public HTTPResponse respond(HTTPRequest req) {
            String fullJson = '{data={"Event":"ChatMessageRecieved","Timestamp":"2021-10-26 06:40:10","attemptNumber":1,"ChatThread":{"ChatThreadId":"1537903","WithNumber":"+14074610978","DateCreated":"2021-10-05 06:47:02"},"}]}}';
            
            HTTPResponse res = new HTTPResponse();
            res.setHeader('Content-Type', 'text/json');
            res.setBody(fullJson);
            res.setStatusCode(200);
            return res;
        }
    }
}

 

Hi Guys,

I am getting stuck while using MetadateService Class. Please help me.

public class LeadReprtFolderShareToGroups {
    public static void ShareToGroup(){
        MetadataService.MetadataPort service =  MetadataServiceExamples.createService();
        MetadataService.ReportFolder rFolder = new MetadataService.ReportFolder();
        MetadataService.SharedTo shareToGroup = new metadataService.SharedTo();
        rFolder.fullName = 'Test  Folder two';
        rFolder.name = 'Folder matadat';
    

        system.debug(rFolder);
        MetadataService.SaveResult[] metadasave = service.createMetadata(new MetadataService.Metadata[] {rFolder});
        system.debug(metadasave);
    }
}


Error
====
ReportFolder:
------------------
[Folder.accessType=null, Folder.folderShares=null, Folder.name=null, Folder.publicFolderAccess=null, Folder.sharedTo=null, Folder.testDemo=Test DEMO, Metadata.fullName=null, accessType=null, accessType_type_info=(accessType, http://soap.sforce.com/2006/04/metadata, null, 0, 1, false), apex_schema_type_info=(http://soap.sforce.com/2006/04/metadata, true, false), field_order_type_info=(fullName, accessType, folderShares, name, publicFolderAccess, sharedTo), folderShares=null, folderSha

(SaveResult:
------------------
[apex_schema_type_info=(http://soap.sforce.com/2006/04/metadata, true, false), errors=(Error:[apex_schema_type_info=(http://soap.sforce.com/2006/04/metadata, true, false), extendedErrorDetails=null, extendedErrorDetails_type_info=(extendedErrorDetails, http://soap.sforce.com/2006/04/metadata, null, 0, -1, false), field_order_type_info=(extendedErrorDetails, fields, message, statusCode), fields=(DeveloperName), fields_type_info=(fields, http://soap.sforce.com/2006/04/metadata, null, 0,
 

Thank you
Sandeep

Hi Guys,

I have created an Aura component and Toast message which is completely working in salesforce org but it is not working in the Partner community even though it is visible in the partner community. The component will be fired and refreshed automatically after the record is saved, but in Partner community, i need to refresh the page everytime. can you anyone help me.

Thanks
Sandeep.
 
Hi Guys,

We have a Webservices which call every day but the time is not guaranteed, Now I want to show a toast message whenever got a response. Please help me with the code.

Thank You
Sandeep

 
Hi Guys,
 
I have developed one Aura component which is like the Input text and "Send" button. Now I want to place SEND button beside the input text.  
Like this
<aura:component controller="ChatThreadHelper" implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes" access="global" >
    <aura:attribute name="Send" type="String" default="SEND"/>
    <aura:attribute name="textvalue" type="String"  default="" />
    <aura:attribute name="messageList" type="List"/>
    <aura:attribute name="recordId" type="string"/>
    <!--<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>-->
    <!--<lightning:card>-->
    <div class="slds-form-element">
        <label class="slds-form-element__label" for="textarea-id-01"></label>
        <div class="slds-form-element__control">
            <span onkeypress="{!c.keyCheck}">
                <lightning:input name="input8" value="{! v.textvalue }" placeholder="type here" label="Message" />
            </span>
        </div>
        <div>
           <div class="slds-clearfix">
                <lightning:buttonIcon iconName="utility:send" variant="bare" iconClass="dark" size="large" onclick="{! c.handleClick }" alternativeText="Send" title="Send" class="slds-float_right"/>
            </div>
        </div>
    </div>
    
    <!--</lightning:card>-->
</aura:component>

Please Help me.

Thank you
Sandeep.

 
Hi Guys, This is my class can you help me to write a test class please.

@RestResource(urlMapping='/ChatMessages/*')
global class SlicktextWebhook {
    
    @HttpPost
    global static String doPost(){
        
        List<string> responseObjList = new List<string>();
        String MessVal;
        string myString ;
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        if (req.headers.get('X-Slicktext-Signature') != 'ed290b9b5391112c7825deb6244f7972') {
            // If the webhook secret doesnt match what slicktext has, then dont do anything
            
        }
        ChatMessageParse responseObj = ChatMessageParse.parse(req.params.get('data'));
        // Get phone number from chat thread
        String phoneNumber = responseObj.ChatMessage.FromNumber;
        String ChatTrheadId = responseObj.ChatThread.ChatThreadId;
        String ChatMessageId = responseObj.ChatMessage.ChatMessageId;
        String MessageBody = responseObj.ChatMessage.Body;
        String TextwordId = responseObj.Textwords.get(0).TextwordId;
        String Textword = responseObj.Textwords.get(0).Textword;
        
        String sObjId;
        // Remove prefix
        phoneNumber = phoneNumber.replace('+1', '');
        List<Lead> listLead = [Select id, Name, Phone, isConverted from lead where isConverted = false and Phone =: phoneNumber LIMIT 1];
        If(listLead.size() > 0){
            sObjId = listLead.get(0).id;
        }else{
            List<contact> listContact = [Select id, Name, Phone from contact where Phone =: phoneNumber LIMIT 1];
            If(listContact.size() > 0){
                sObjId = listContact.get(0).id;
            }
            
        }
        
        responseObjList.add(ChatTrheadId);
        responseObjList.add(ChatMessageId);
        responseObjList.add(phoneNumber);
        responseObjList.add(MessageBody);
        responseObjList.add(TextwordId);
        responseObjList.add(Textword);
        responseObjList.add(sObjId);
        
        String SoId = String.valueOf(sObjId);
        String sub = SoId.substring(0, 3);
        List<ChatThread__c> chatThrd = [select id, Lead__c,Lead__r.Phone, WithNumber__c 
                                        from ChatThread__c 
                                        where WithNumber__c != null and name =: ChatTrheadId LIMIT 1];
        If(chatThrd.size() > 0){
            ChatMessage__c newMessage = new ChatMessage__c();
            If(sub == '00Q'){newMessage.Lead__c = sObjId;}
            else If(sub == '003'){newMessage.Contact__c = sObjId;}
            newMessage.FromNumber__c = phoneNumber;
            newMessage.Name = ChatMessageId;
            newMessage.ChatThread__c = chatThrd.get(0).id;
            newMessage.Body__c = MessageBody;
            newMessage.Action__c = 'RECEIVED';
            //newMessage.Lead__c = sObjId;
            insert newMessage;
        }else{
            If(sub == '00Q'){
                ChatMessage__c cm = new ChatMessage__c(Name = ChatMessageId, Action__c = 'RECEIVED', 
                                                       Body__c = MessageBody, Lead__c = sObjId,
                                                       FromNumber__c = phoneNumber);
                ChatThread__c ct = new ChatThread__c(Name = ChatTrheadId);
                cm.ChatThread__r = ct;
                ChatThread__c ctp = new ChatThread__c(Name = ChatTrheadId, WithNumber__c = phoneNumber, Lead__c = sObjId);
                Database.SaveResult[] results = Database.insert(new SObject[] {
                    ctp, cm });
            }
            
        }
        return ChatTrheadId;
        
    }
    
}

Thank you
Sandeep.
Hi Guys,

I have two custom objects with a lookup relationship, I want to create parent and it's child records at once. Please help me if there is a way.

I have tried this but not worked for me:
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_dml_foreign_keys.htm

 

Hi Guys,

I am getting stuck while using MetadateService Class. Please help me.

public class LeadReprtFolderShareToGroups {
    public static void ShareToGroup(){
        MetadataService.MetadataPort service =  MetadataServiceExamples.createService();
        MetadataService.ReportFolder rFolder = new MetadataService.ReportFolder();
        MetadataService.SharedTo shareToGroup = new metadataService.SharedTo();
        rFolder.fullName = 'Test  Folder two';
        rFolder.name = 'Folder matadat';
    

        system.debug(rFolder);
        MetadataService.SaveResult[] metadasave = service.createMetadata(new MetadataService.Metadata[] {rFolder});
        system.debug(metadasave);
    }
}


Error
====
ReportFolder:
------------------
[Folder.accessType=null, Folder.folderShares=null, Folder.name=null, Folder.publicFolderAccess=null, Folder.sharedTo=null, Folder.testDemo=Test DEMO, Metadata.fullName=null, accessType=null, accessType_type_info=(accessType, http://soap.sforce.com/2006/04/metadata, null, 0, 1, false), apex_schema_type_info=(http://soap.sforce.com/2006/04/metadata, true, false), field_order_type_info=(fullName, accessType, folderShares, name, publicFolderAccess, sharedTo), folderShares=null, folderSha

(SaveResult:
------------------
[apex_schema_type_info=(http://soap.sforce.com/2006/04/metadata, true, false), errors=(Error:[apex_schema_type_info=(http://soap.sforce.com/2006/04/metadata, true, false), extendedErrorDetails=null, extendedErrorDetails_type_info=(extendedErrorDetails, http://soap.sforce.com/2006/04/metadata, null, 0, -1, false), field_order_type_info=(extendedErrorDetails, fields, message, statusCode), fields=(DeveloperName), fields_type_info=(fields, http://soap.sforce.com/2006/04/metadata, null, 0,
 

Thank you
Sandeep

Hello Guys,

I have a Test class on InboundEmail Service Class and it includes sObjects Like Lead, EmailMessage, Task, User, and Attachments Can anyone please help me with the Test class.
global class captureEmailResponses implements Messaging.InboundEmailHandler {
    //  Handles inbound email replies from leads and puts the details into Email Messages which creates a
    //  Activity Entry. This will also update the lead status to patient replied.
    global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email, Messaging.InboundEnvelope env){
        // Create an InboundEmailResult object for returning the result of the
        // Apex Email Service
        Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
        // Set the activity name to the email from name
        String Activityname = email.fromname;
        // Find the lead by the from address
        String fromemailaddresss = email.fromAddress;
        String des = email.plainTextBody;
        String tasksubject = email.subject;
        try {
            // Lets get the original message
            EmailMessage originalMessage = [SELECT ReplyToEmailMessageId, MessageIdentifier, ThreadIdentifier, CreatedById, ActivityId FROM EmailMessage WHERE MessageIdentifier = :email.inReplyTo LIMIT 1];
            
            // Get Task from original Message
            Task linkedTask = [SELECT Id, WhoId FROM Task WHERE Id = :originalMessage.ActivityId LIMIT 1];
            // Get lead from WhoId
            Lead lead = [SELECT Id, Name, Email, ShareGroupId__c, LastModifiedById, Status FROM Lead 
                         WHERE Id = :linkedTask.WhoId LIMIT 1];
            User lastUser = [SELECT Id, Email FROM User
                             WHERE Id = :originalMessage.CreatedById LIMIT 1];
            // Create a email message because we use enhanced emails and it creates the activity automatically.
            EmailMessage[] newEmail = new EmailMessage[0];
            String[] toUsers = new String[]{lead.LastModifiedById};
                newEmail.add(new EmailMessage(FromAddress = email.fromAddress,
                                              FromName = email.fromName,
                                              Incoming = True,
                                              ToAddress = lastUser.Email,
                                              //ToAddress = email.toAddresses[0],
                                              Subject = email.subject,
                                              //RelatedToId = lead.Id, // This throws error about not the expected type???
                                              TextBody = email.plainTextBody,
                                              HtmlBody = email.htmlBody,
                                              MessageIdentifier = email.messageId,
                                              ReplyToEmailMessageId = originalMessage.Id,
                                              ThreadIdentifier = originalMessage.ThreadIdentifier,
                                              Status = '3')); // Sets to replied.
            
            insert newEmail;
            // Add Email Message Relation to the lead because they sent it...
            EmailMessageRelation emr = new EmailMessageRelation();
            emr.emailMessageId = newEmail[0].Id;
            emr.relationAddress = email.fromAddress;
            emr.relationId = lead.id; // Lead Id
            emr.relationType = 'FromAddress';
            insert emr;
            
            EmailMessageRelation toEmr = new EmailMessageRelation();
            toEmr.emailMessageId = newEmail[0].Id;
            toEmr.relationAddress = lastUser.Email;
            toEmr.relationId = lastUser.Id; // User Id
            toEmr.relationType = 'ToAddress';
            insert toEmr;
            
            // Update the lead status to Patient Replied
            lead.status = 'Patient Replied';
            update lead;
            // The below was ripped from a forum https://developer.salesforce.com/forums/?id=906F00000008um5IAA, but I dont know if it works?
            // Add any binary attachments to the lead
            
            if(email.textAttachments != null)
            {
                // Save attachments, if any
                for (Messaging.Inboundemail.TextAttachment tAttachment : email.textAttachments) {
                    Attachment attachment = new Attachment();
                    
                    attachment.Name = tAttachment.fileName;
                    attachment.Body = Blob.valueOf(tAttachment.body);
                    attachment.ParentId = lead.Id;
                    insert attachment;
                }
            }
            if(email.binaryAttachments != null && email.binaryAttachments.size() > 0){
                for(Messaging.InboundEmail.BinaryAttachment att : email.binaryAttachments){
                    system.debug('attachmentsList -> '+email.binaryAttachments);
                }
                List<ContentVersion>cvList = new List<ContentVersion>();
                List<ContentDocumentLink> cdlList = new List<ContentDocumentLink>();
                for (Messaging.InboundEmail.BinaryAttachment binAttach : email.binaryAttachments) {
                    ContentVersion testContentInsert = new ContentVersion();
                    testContentInsert.Title = binAttach.fileName;
                    testContentInsert.VersionData = binAttach.body;
                    testContentInsert.PathOnClient = '/' + binAttach.fileName ;
                    cvList.add(testContentInsert);
                    
                }
                insert cvList;
                cvList = [select id, ContentDocumentId from ContentVersion WHERE Id in :cvList];
                for (ContentVersion cv : cvList) {
                    ContentDocumentLink cl = new ContentDocumentLink();
                    cl.ContentDocumentId = cv.ContentDocumentId;
                    cl.LinkedEntityId = lead.id; //Shared with record ID
                    cl.ShareType = 'I';
                    cl.Visibility = 'AllUsers';
                    cdlList.add(cl);
                }
                insert cdlList;
            }else{
                system.debug('attachmentsList -> '+email.binaryAttachments);
            }
            
        }
        // If an exception occurs when the query accesses
        // the contact record, a QueryException is called.
        // The exception is written to the Apex debug log.
        catch (QueryException e) {
            System.debug('Query Issue: ' + e);
            System.debug('Query Issue: ' + e.getLineNumber());
            System.debug('Query Issue: ' + e.getCause());
            System.debug('Query Issue: ' + e.getTypeName());
            System.debug('Query Issue: ' + e.getMessage());
        }
        result.success = true;
        // return nothing...
        return result;
    }
}



Thank you
Sandeep. 
Hi Guys,

I have created an Inbound Email service. But I am not sure how to create a Test class. Help me.
 
global class captureEmailResponses implements Messaging.InboundEmailHandler {
    global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email, Messaging.InboundEnvelope env){
        Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
        String Activityname = email.fromname;
        String fromemailaddresss = email.fromAddress;
        String des = email.plainTextBody;
        String tasksubject = email.subject;
        try {
            system.debug('Reply To '+email.inReplyTo);
            EmailMessage originalMessage = [SELECT ReplyToEmailMessageId, MessageIdentifier, ThreadIdentifier, CreatedById, ActivityId FROM EmailMessage WHERE MessageIdentifier = :email.inReplyTo LIMIT 1];

            Task linkedTask = [SELECT Id, WhoId FROM Task WHERE Id = :originalMessage.ActivityId LIMIT 1];

            Lead lead = [SELECT Id, Name, Email, ShareGroupId__c, LastModifiedById, Status
                         FROM Lead
                         WHERE Id = :linkedTask.WhoId
                         LIMIT 1];
            User lastUser = [SELECT Id, Email
                             FROM User
                             WHERE Id = :originalMessage.CreatedById
                             LIMIT 1];
            EmailMessage[] newEmail = new EmailMessage[0];
            String[] toUsers = new String[]{lead.LastModifiedById};
                newEmail.add(new EmailMessage(FromAddress = email.fromAddress,
                                              FromName = email.fromName,
                                              Incoming = True,
                                              ToAddress = lastUser.Email,
                                              //ToAddress = email.toAddresses[0],
                                              Subject = email.subject,
                                              //RelatedToId = lead.Id, // This throws error about not the expected type???
                                              TextBody = email.plainTextBody,
                                              HtmlBody = email.htmlBody,
                                              MessageIdentifier = email.messageId,
                                              ReplyToEmailMessageId = originalMessage.Id,
                                              ThreadIdentifier = originalMessage.ThreadIdentifier,
                                              Status = '3')); // Sets to replied.
            
            insert newEmail;

            EmailMessageRelation emr = new EmailMessageRelation();
            emr.emailMessageId = newEmail[0].Id;
            emr.relationAddress = email.fromAddress;
            emr.relationId = lead.id; // Lead Id
            emr.relationType = 'FromAddress';
            insert emr;
            
            EmailMessageRelation toEmr = new EmailMessageRelation();
            toEmr.emailMessageId = newEmail[0].Id;
            toEmr.relationAddress = lastUser.Email;
            toEmr.relationId = lastUser.Id; // User Id
            toEmr.relationType = 'ToAddress';
            insert toEmr;
            
            lead.status = 'Patient Replied';
            update lead;
            
            if(email.textAttachments != null)
            {
                system.debug('email.textAttachments '+ email.textAttachments);

                for (Messaging.Inboundemail.TextAttachment tAttachment : email.textAttachments) {
                    Attachment attachment = new Attachment();
                    
                    attachment.Name = tAttachment.fileName;
                    attachment.Body = Blob.valueOf(tAttachment.body);
                    attachment.ParentId = lead.Id;
                    insert attachment;
                }
            }
            if(email.binaryAttachments != null && email.binaryAttachments.size() > 0){
                for(Messaging.InboundEmail.BinaryAttachment att : email.binaryAttachments){
                    system.debug('attachmentsList -> '+email.binaryAttachments);
                }
                List<ContentVersion>cvList = new List<ContentVersion>();
                List<ContentDocumentLink> cdlList = new List<ContentDocumentLink>();
                for (Messaging.InboundEmail.BinaryAttachment binAttach : email.binaryAttachments) {
                    system.debug('@@@ binAttach.fileName '+binAttach.fileName);
                    system.debug('@@@ binAttach.fileName '+binAttach.body);
                    system.debug('@@@ binAttach.fileName '+binAttach.fileName);
                    
                    ContentVersion testContentInsert = new ContentVersion();
                    testContentInsert.Title = binAttach.fileName;
                    testContentInsert.VersionData = binAttach.body;
                    testContentInsert.PathOnClient = '/' + binAttach.fileName ;
                    cvList.add(testContentInsert);
                    
                }
                insert cvList;
                cvList = [select id, ContentDocumentId from ContentVersion WHERE Id in :cvList];
                for (ContentVersion cv : cvList) {
                    ContentDocumentLink cl = new ContentDocumentLink();
                    cl.ContentDocumentId = cv.ContentDocumentId;
                    cl.LinkedEntityId = lead.id; //Shared with record ID
                    cl.ShareType = 'I';
                    cl.Visibility = 'AllUsers';
                    cdlList.add(cl);

                }
                insert cdlList;
  
            }else{
                system.debug('attachmentsList -> '+email.binaryAttachments);
            }
            
        }

        catch (QueryException e) {
            System.debug('Query Issue: ' + e);
            System.debug('Query Issue: ' + e.getLineNumber());
            System.debug('Query Issue: ' + e.getCause());
            System.debug('Query Issue: ' + e.getTypeName());
            System.debug('Query Issue: ' + e.getMessage());
        }
        result.success = true;
        return result;
    }
}




Thank You
Sandeep
Hi Guys,

I have configured a SAML. Now I want to change the Login URL ID. If it is possible let me know.
User-added image

Hi Guys,

We have a "Related Accounts" related list on the Contact object. It Seems it is Standard. How can we add related accounts to each contact using Apex.

User-added imageThanks

Hi Guys,

In the Test Class when I am trying to insert CampaignMember Record with Type "Lead" It is getting an error Like
System.DmlException: Upsert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Account__c]: [Account__c]
But I Need CampaignMember record with Lead Id only.
Can Anyone help me with this?

Thanks
Sandeep.

 
Hi Guys,
I have a Test Class issue can anyone tell me the mistake. I have custom filed "ClinicCode" in the Lead object. I am not passing the code in the test class but the lead is stored under the "leadsWithClinicsList" list. It should be in "leadsWithOutClinicsList"
User-added imageUser-added image
Hi Guys,

I have created an Aura component and Toast message which is completely working in salesforce org but it is not working in the Partner community even though it is visible in the partner community. The component will be fired and refreshed automatically after the record is saved, but in Partner community, i need to refresh the page everytime. can you anyone help me.

Thanks
Sandeep.
 
Hi Guys,
 
I have developed one Aura component which is like the Input text and "Send" button. Now I want to place SEND button beside the input text.  
Like this
<aura:component controller="ChatThreadHelper" implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes" access="global" >
    <aura:attribute name="Send" type="String" default="SEND"/>
    <aura:attribute name="textvalue" type="String"  default="" />
    <aura:attribute name="messageList" type="List"/>
    <aura:attribute name="recordId" type="string"/>
    <!--<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>-->
    <!--<lightning:card>-->
    <div class="slds-form-element">
        <label class="slds-form-element__label" for="textarea-id-01"></label>
        <div class="slds-form-element__control">
            <span onkeypress="{!c.keyCheck}">
                <lightning:input name="input8" value="{! v.textvalue }" placeholder="type here" label="Message" />
            </span>
        </div>
        <div>
           <div class="slds-clearfix">
                <lightning:buttonIcon iconName="utility:send" variant="bare" iconClass="dark" size="large" onclick="{! c.handleClick }" alternativeText="Send" title="Send" class="slds-float_right"/>
            </div>
        </div>
    </div>
    
    <!--</lightning:card>-->
</aura:component>

Please Help me.

Thank you
Sandeep.

 
Hi Guys, This is my class can you help me to write a test class please.

@RestResource(urlMapping='/ChatMessages/*')
global class SlicktextWebhook {
    
    @HttpPost
    global static String doPost(){
        
        List<string> responseObjList = new List<string>();
        String MessVal;
        string myString ;
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        if (req.headers.get('X-Slicktext-Signature') != 'ed290b9b5391112c7825deb6244f7972') {
            // If the webhook secret doesnt match what slicktext has, then dont do anything
            
        }
        ChatMessageParse responseObj = ChatMessageParse.parse(req.params.get('data'));
        // Get phone number from chat thread
        String phoneNumber = responseObj.ChatMessage.FromNumber;
        String ChatTrheadId = responseObj.ChatThread.ChatThreadId;
        String ChatMessageId = responseObj.ChatMessage.ChatMessageId;
        String MessageBody = responseObj.ChatMessage.Body;
        String TextwordId = responseObj.Textwords.get(0).TextwordId;
        String Textword = responseObj.Textwords.get(0).Textword;
        
        String sObjId;
        // Remove prefix
        phoneNumber = phoneNumber.replace('+1', '');
        List<Lead> listLead = [Select id, Name, Phone, isConverted from lead where isConverted = false and Phone =: phoneNumber LIMIT 1];
        If(listLead.size() > 0){
            sObjId = listLead.get(0).id;
        }else{
            List<contact> listContact = [Select id, Name, Phone from contact where Phone =: phoneNumber LIMIT 1];
            If(listContact.size() > 0){
                sObjId = listContact.get(0).id;
            }
            
        }
        
        responseObjList.add(ChatTrheadId);
        responseObjList.add(ChatMessageId);
        responseObjList.add(phoneNumber);
        responseObjList.add(MessageBody);
        responseObjList.add(TextwordId);
        responseObjList.add(Textword);
        responseObjList.add(sObjId);
        
        String SoId = String.valueOf(sObjId);
        String sub = SoId.substring(0, 3);
        List<ChatThread__c> chatThrd = [select id, Lead__c,Lead__r.Phone, WithNumber__c 
                                        from ChatThread__c 
                                        where WithNumber__c != null and name =: ChatTrheadId LIMIT 1];
        If(chatThrd.size() > 0){
            ChatMessage__c newMessage = new ChatMessage__c();
            If(sub == '00Q'){newMessage.Lead__c = sObjId;}
            else If(sub == '003'){newMessage.Contact__c = sObjId;}
            newMessage.FromNumber__c = phoneNumber;
            newMessage.Name = ChatMessageId;
            newMessage.ChatThread__c = chatThrd.get(0).id;
            newMessage.Body__c = MessageBody;
            newMessage.Action__c = 'RECEIVED';
            //newMessage.Lead__c = sObjId;
            insert newMessage;
        }else{
            If(sub == '00Q'){
                ChatMessage__c cm = new ChatMessage__c(Name = ChatMessageId, Action__c = 'RECEIVED', 
                                                       Body__c = MessageBody, Lead__c = sObjId,
                                                       FromNumber__c = phoneNumber);
                ChatThread__c ct = new ChatThread__c(Name = ChatTrheadId);
                cm.ChatThread__r = ct;
                ChatThread__c ctp = new ChatThread__c(Name = ChatTrheadId, WithNumber__c = phoneNumber, Lead__c = sObjId);
                Database.SaveResult[] results = Database.insert(new SObject[] {
                    ctp, cm });
            }
            
        }
        return ChatTrheadId;
        
    }
    
}

Thank you
Sandeep.