• Foram Rana R
  • NEWBIE
  • 465 Points
  • Member since 2019
  • Salesforce Developer
  • Resonant Cloud Solution


  • Chatter
    Feed
  • 14
    Best Answers
  • 2
    Likes Received
  • 5
    Likes Given
  • 4
    Questions
  • 100
    Replies
I am copying contentdocumentlink to another object
cdl.ShareType = 'I';
cdl.Visibility = 'InternalUsers';

But the visibilty when I look at the fileis 'All Users', why is that?  I need it to be private.
P

 
Hi can any one help for writing a test class for ths:

public class LoanDocumentGenrate{

    private final LLC_BI__Loan__c ln;    
   

    public LoanDocumentGenrate(ApexPages.StandardController stdController) {
        
                this.ln = (LLC_BI__Loan__c)stdController.getRecord(); 

    }

    public PageReference pgclose() {
            
        PageReference pgref = new PageReference('/' + ln.Id);
        pgref.setRedirect(true);
        return pgref;  
    }


}
Hello, I've tried all the ways but I'm not getting it, I need that when I put the start date and end date they separate the working days and learn in the DiasTrabalhados__c field. I am not able to develop the necessary validation rule for such an action,
Thanks
 I have a problem test coverage covers only 34%,the below apex class method 'importCSVFile' in the for loop not covering the run the test class,please suggest 
Apex class merge accounts
----------------
public class MergeAccountsController {
    public Blob csvFileBody{get;set;}
    public string csvAsString{get;set;}
    public String[] csvFileLines{get;set;}
    public List<account> acclist{get;set;}
    public Boolean isChecked{ get; set;}
    public boolean hide {get;set;}
    List<Account> accDup = new List<Account>();
    String[] csvRecordData;
    String priID, secID, terID;
    
  public MergeAccountsController(){
      csvFileLines = new String[]{};
      acclist = New List<Account>();
      hide = true;
    }
    
  public void click(){
      if(isChecked == true){
          importCSVFile();
          restore(secID);
      }
      else{
          importCSVFile();
      }
  }

  public void importCSVFile(){
        hide = false;
        try{
            csvAsString = csvFileBody.toString();
            csvFileLines = csvAsString.split('\r\n');
        }
        catch(Exception e){
            ApexPages.Message csvError = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured while importing data. Please make sure input csv file is correct');
            ApexPages.addMessage(csvError);
        }
        
        for(Integer i=1; i<csvFileLines.size(); i++){
            csvRecordData = csvFileLines[i].split(',');
            Integer row = i+1;
            try{
            if(csvRecordData.size() == 2) {
                  priID = csvRecordData[0];
                  secID = csvRecordData[1];
                  Account pri, sec;
                
                  try{
                    pri = [SELECT ID from Account Where ID = :priID];
                  }
                  catch(QueryException qe){
                  ApexPages.Message recordError = new ApexPages.Message(ApexPages.severity.ERROR,'Account ' +priID+ ' in Row ' +row+ ' not found');
                  ApexPages.addMessage(recordError);
                  }
                  try{
                    sec = [SELECT ID from Account Where ID = :secID];
                    }
                  catch(QueryException qe){         
                    ApexPages.Message recordError = new ApexPages.Message(ApexPages.severity.ERROR,'Account ' +secID+ ' in Row ' +row+ ' not found');
                    ApexPages.addMessage(recordError);
                  }
                
                merge pri sec;
                }
            
              else if(csvRecordData.size() == 3) {
                  priID = csvRecordData[0];
                  secID = csvRecordData[1];
                  terID = csvRecordData[2];
                  Account pri, sec, ter;
                    
                  try{
                    pri = [SELECT ID from Account Where ID = :priID];
                  }
                  catch(QueryException qe){
                    ApexPages.Message recordError = new ApexPages.Message(ApexPages.severity.ERROR,'Account ' +priID+ ' in Row ' +row+ ' not found');
                    ApexPages.addMessage(recordError);
                  }
                  try{
                    sec = [SELECT ID from Account Where ID = :secID];
                  }
                  catch(QueryException qe){
                    ApexPages.Message recordError = new ApexPages.Message(ApexPages.severity.ERROR,'Account ' +secID+ ' in Row ' +row+ ' not found');
                    ApexPages.addMessage(recordError);
                    }
                  try{
                    ter = [SELECT ID from Account Where ID = :terID];
                  }
                  catch(QueryException qe){
                    ApexPages.Message recordError = new ApexPages.Message(ApexPages.severity.ERROR,'Account ' +terID+ ' in Row ' +row+ ' not found');
                    ApexPages.addMessage(recordError);
                  }
                                    
            accDup.add(sec);
            accDup.add(ter);
                    
                  try{
                     merge pri accDup;  
                  }
                  catch(DmlException e){
                      continue;
                  }  
              }
            }
            catch(NullPointerException npe){
                continue;
            }
        }
        ApexPages.Message complete = new ApexPages.Message(ApexPages.severity.INFO,'Process Complete');
        ApexPages.addMessage(complete);
    }
    public void restore(String acc){
        Account[] sec = [SELECT Id FROM Account WHERE ID = :secID ALL ROWS];
        undelete sec;
    }
}

test class : 
@isTest
Public class MergeAccountstest{
static String str = 'Name,BillingCountry,BillingCity,BillingStreet,BillingState,BillingPostalCode\n test22,india,Chennai,test,Tamil Nadu,588543 \n test222,india,Chennai,test2,Tamil Nadu,588544';       

//system.debug('------str ------'+str );
    public static String[] csvFileLines;
    public static Blob csvFileBody;
    public static String[] csvRecordData;
    public static Boolean isChecked =true;
    public static  testMethod void importCSVFile() {
        Account a = new Account(name='test',BillingCountry='india',BillingCity='Chennai',BillingStreet='test',BillingState='Tamil Nadu',BillingPostalCode='588543');
        insert a;
        Account a1 = new Account(name='test1',BillingCountry='india',BillingCity='Chennai',BillingStreet='test',BillingState='Tamil Nadu',BillingPostalCode='588543');
        insert a1;
        test.startTest();
        //merge a a1;
        MergeAccountsController m1=new MergeAccountsController();
         if(isChecked == true){
          m1.importCSVFile();
          //m1.restore(a1);
      }
      else{
          m1.importCSVFile();
      }
        //m1.importCSVFile();
        m1.click();
        m1.restore('a');
        test.stopTest();
        
    }

    static testmethod void testfileupload(){
        Test.startTest();       
        List<sObject> acct = Test.loadData(Account.sObjectType, 'mergeaccount');
        System.debug( '----acct ---' +acct );
        System.assert(acct.size() == 5);   
        csvFileBody = Blob.valueOf(str );
        System.debug( '----csvFileBody ---' +csvFileBody );
        String csvAsString = acct.toString();
        System.debug( '----csvAsString ---' +csvAsString ); 
        csvFileLines = csvAsString.split('\n');
        
        System.debug( '----csvFileLines---' +csvFileLines );
        
         for(Integer i=1; i<csvFileLines.size(); i++){
            csvRecordData = csvFileLines[i].split(',');
           }
           

        MergeAccountsController importData = new MergeAccountsController();
        importData.csvFileBody = csvFileBody;
        importData.importCSVFile();
        Test.stopTest();
    } 

    static testmethod void testfileuploadNegative(){
        Test.startTest();       
        csvFileBody = Blob.valueOf(str);
        String csvAsString = csvFileBody.toString();
        csvFileLines = csvAsString.split('\n'); 

        MergeAccountsController  importData = new MergeAccountsController();
        importData.importCSVFile();
        Test.stopTest();
    }
}
Hello,

I have a validation rule setup to check if a given picklist value is empty. I have tried following ways but the rule does not trigger:

#Type 1:
NOT(ISBLANK(TEXT(text_field))) 
&& 
ISBLANK(TEXT(picklist ))
&& 
(RecordType.Name = "name1" 
|| 
RecordType.Name = "name2" 
|| 
RecordType.Name = "name3" 
)

#Type 2:

AND(ISPICKVAL(Picklist , ""), NOT(ISBLANK(TEXT(Text_Field))),OR(RecordType.Name = "name1", RecordType.Name = "name2", RecordType.Name = "name3" ))

Please let me know why this doesn't work. Thanks a lot
V.f page:
<apex:page controller="Passingvaluestocntroller">
<apex:form >

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
  
  $(document).ready(function(){
  
 $("#click").click(function(){
 
 debugger;
   alert("hello");
     var name ="Deepika";
   alert(name);
   var branch="Salesforce";
   alert(branch);
   debugger;
   var test = {"Empname":name,"Empbranch":branch};
   alert(test);
   method1();
  });
  
  });
  </script>

 
  <apex:actionFunction name="method1" action="{!method1()}"/>

<input type="button" value="test" id="click"/>
</apex:form>
</apex:page>

Controller:

 
public class Passingvaluestocntroller {


  public void method1(string name, string branch){
   system.debug('salesforce testing');
   system.debug(name);
   system.debug(branch);
  }
  
  
 
  
}

​​​​​​need to pass the javascript varible to the Apex method in salesforce.. 

Thanks D
Deepika
"lookup relationship can to span multiple layer deep" - What it means?

Hi there!

I'm very new to visualforce / apex and there's one thing I can't get to work:

I have a simple vf page with two columns of checkboxes and I have to create a button which once being clicked ticks all the checkboxes from unchecked to checked or vise versa.

This is my current code:
<apex:page standardController="Rahmenvertrag_OptIn__c" recordSetVar="rv" standardStylesheets="true">
    
    
    <div class="container1">
        <apex:pageBlock >
        <h1>Rahmenvertrag Teilnehmer-Liste</h1>
        <apex:form id="form1">
            
            
            
            <apex:pageBlockTable value="{! rv }" var="rvt" id="table1">
                
                <apex:column value="{! rvt.KD_TN_EKP__c}" headerClass="tableheader" headerValue="EKP"/>
                <apex:column value="{! rvt.KD_TN_Name__c}" headerClass="tableheader" headerValue="Rahmenvertrag Teilnehmer"/>
                <apex:column value="{! rvt.KD_TN_Adresse__c}" headerClass="tableheader" headerValue="Adresse"/>
                <apex:column>
                    <apex:facet name="header"><span class="tableheader">Einwilligung<br/>Datenaustausch</span></apex:facet>
                    <apex:inputCheckbox value="{! rvt.Datenaustausch__c}"  />
                </apex:column>
                <apex:column >
                    <apex:facet name="header"><span class="tableheader">Einwilligung<br/>Werbliche Ansprache</span></apex:facet>
                    <apex:inputField value="{! rvt.Werbeansprache__c}"  />
                </apex:column>
            </apex:pageBlockTable>
            
            
            
            <br/>
            <table>
                <tr>
                <td ><apex:commandButton action="{!save}" value="Zwischenspeichern"/></td>
                <td><apex:commandButton action="{!save}" value="Änderungen bestätigen" /></td>
                </tr>                    
            </table>
        </apex:form>
    </apex:pageBlock>
        </div>
</apex:page>

Any help would be much appreciated! 
Thanks in advance

I have created a class that links a case with the case comment for a visualforce page but for the life of me I cannot remember how I write a test class for the apex class.

The class I require tests for is:

public class Caselinktocomment
{
    public CaseComment comment { get; set; }
    public String commentText {get; set;}
    public String PublicPrivateAction {get; set;}


    public Caselinktocomment(ApexPages.StandardController stdController) 
    {
        this.comment = new CaseComment(ParentId = stdController.getId());
    }

    public PageReference saveComment()
    {
        insert comment;
        return null;
    }
}

The test Class I have written is:
@istest

Private class Caselinktocommenttests {
    

    static testmethod void createtestdata() {
    Id RecordId = Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get('Service_Desk').getRecordTypeId();
        Case tcase = new Case();
        tCase.Status = 'New';
        tCase.Description = 'This ticket has been created as a test';
        tCase.Subject = 'Test Case';
        tCase.RecordTypeId = RecordId;
        tCase.Reason = 'Access Requests';
        tCase.Origin = '';Phone
        
        INSERT tCase;
        
        CaseComment tComment = new CaseComment();
        tComment.ParentId = tCase.Id;
        tComment.CommentBody = 'Test Comment';
        tComment.IsPublished = FALSE;
        tComment.IsNotificationSelected= FALSE;
        Test.startTest();
        INSERT tComment;
        Test.stopTest();
        system.assertEquals(1, [SELECT count() From CaseComment], 'Test Comment');
        }   
}

The code coverage does not seem to increase. Can anyone advise where I have gone wrong. 
Im getting the Error : System.ListException: List index out of bounds: 0
Candidate__c(Master object) and Job_Application__c(child object). 
I want to fetch child records.

List<Candidate__c> candList=[Select id,name,City__c, (select Position__c,Status__c from Job_Applications__r) from Candidate__c Where Name='Shaun smith'];
System.debug('List is' +candList);
List<Job_Application__c> jobList=candList[0].Job_Applications__r;
System.debug('List of job are' +jobList);

Please help with this.

 
Hello All,
Hopeone someone can steer me in the right direction here.  I am saving a record from a user entered VF page. What I need to do is generate a PDF of the newly created record and attach it to the record.  I have a new VF page using (renderAs= PDF) and an Apex Class to grab the data to populate the VF but I need to make sure that the data has been saved first  before generating the PDF.  Also, how can I save it to the new record?  Is there a better way to do do this or am I on the right track?
Thanks,
P
Dear Team ,

Please clarify me about Sandbox , Roles and Profile , Batch APEX Class in easy words . These are the most frequently asked question in interviews .

Thanks & Regards
Sachin Bhalerao
Hi,

I have to perform Excel IRR Function Calculation in Apex class.
https://exceljet.net/excel-functions/excel-irr-function

Thanks,
Foram Rana
User-added image
While clicking on button called Visualforce page.
Hello Everyone,

I want to extract the Zip file in the Apex class.
Zip may contain at least 20 doc or pdf files.
Let me know the solution.

Thanks,
Foram Rana
Got Issue In Below Code.
if((
                   Schema.SObjectType.Custom_Setting__c.isCreateable() &&
                   Schema.SObjectType.Custom_Setting__c.fields.Name.isCreateable() &&
                   Schema.SObjectType.Custom_Setting__c.fields.UserName__c.isCreateable() &&
                   Schema.SObjectType.Custom_Setting__c.fields.Password__c.isCreateable() ) ||
                                      
                   (Schema.sObjectType.Custom_Setting__c.isUpdateable() &&
                   Schema.SObjectType.Custom_Setting__c.fields.Name.isUpdateable()  ) {
                   
                   
                    Custom_Setting__c cs = new Custom_Setting__c(UserName__c = username, Password__c = password, Name = usr.Name);
                    upsert cs Name;
                   
                   }
User-added image
While clicking on button called Visualforce page.
Got Issue In Below Code.
if((
                   Schema.SObjectType.Custom_Setting__c.isCreateable() &&
                   Schema.SObjectType.Custom_Setting__c.fields.Name.isCreateable() &&
                   Schema.SObjectType.Custom_Setting__c.fields.UserName__c.isCreateable() &&
                   Schema.SObjectType.Custom_Setting__c.fields.Password__c.isCreateable() ) ||
                                      
                   (Schema.sObjectType.Custom_Setting__c.isUpdateable() &&
                   Schema.SObjectType.Custom_Setting__c.fields.Name.isUpdateable()  ) {
                   
                   
                    Custom_Setting__c cs = new Custom_Setting__c(UserName__c = username, Password__c = password, Name = usr.Name);
                    upsert cs Name;
                   
                   }
I am creating a test class for Attachment trigger, but not able to cover  this filter Parent.Type = 'Task' mentioned in where cluase so that my test class covering is not increasing.

 //this SOQL query in trigger 
List<Attachment> lstAttachments = [SELECT Id, Name, Body, ContentType, ParentId, OwnerId From Attachment
WHERE Id = : lstAttIds AND Parent.Type = 'Task' ];


Please suggest how can i cover Parent.Type = 'Task' in test class.

Test class code: 
 @isTest
    public static void attachment_Test(){
   Test.startTest(); 
   Task taskObj = new    Task(ownerID=userRec.id,ActivityDate=Date.today(),TaskSubtype='Task',Subject='Test subject',Status='Not Started',Priority='Medium',RecordTypeId=TaskRtID,Type='To Do');
           
             insert taskObj;
            
            Attachment attach=new Attachment();     
            attach.Name='Unit Test Attachment';
            Blob bodyBlob=Blob.valueOf('Unit Test Attachment Body');
            attach.body=bodyBlob;
            attach.parentId=taskObj.id;
            attach.OwnerId = taskObj.OwnerId;
            attach.ContentType='text/plain';
            
            attach.IsPrivate=false;
            
            insert attach;

 Test.stopTest(); 
}
I am wanting a checkbox formula to checkmark when the record CreatedDate is either Saturday or Sunday (Weekend).

I have tried searching around however all I am finding is comparing two dates and not counting weekend days which is not what I am needed.

Any help would be appreciated!
I am copying contentdocumentlink to another object
cdl.ShareType = 'I';
cdl.Visibility = 'InternalUsers';

But the visibilty when I look at the fileis 'All Users', why is that?  I need it to be private.
P

 
"statusList":[
"BEINGPICKED"
],
"fulfilmentType":"HWD",
"productLineStatus":"{\"BEINGPICKED\":1}",
"productLineStatuses":{
"BEINGPICKED":1
}
},
{
"id":"445734",
"productName":"Kids Bike Build HWD",
"productType":"standard",
"brand":null,
"price":{
"sales":{
"currency":"GBP",
"symbol":"£",
"value":15,
"formatted":"£15.00",
"decimalPrice":"15.00"
}
},
"status":"In progress",
"statusList":[

],
"fulfilmentType":"HWD",
"productLineStatus":null,
"productLineStatuses":{

}
}
],
"totalQuantity":1
}
}
}
Hi can any one help for writing a test class for ths:

public class LoanDocumentGenrate{

    private final LLC_BI__Loan__c ln;    
   

    public LoanDocumentGenrate(ApexPages.StandardController stdController) {
        
                this.ln = (LLC_BI__Loan__c)stdController.getRecord(); 

    }

    public PageReference pgclose() {
            
        PageReference pgref = new PageReference('/' + ln.Id);
        pgref.setRedirect(true);
        return pgref;  
    }


}
1=list<String> firstcolourlist=new list<String>{'red','blue','yellow','orange','blue','red'};
    2=  list<String>secondcolourlist=new list<String>{'blue','black','yellow','green','blue'};

print the common values
            
Hi Team,

Please help to write a test class for a after delete trigger.

TRIGGER

trigger MaketheCheckboxUnused on Order_Line_Item_Serials__c (after delete) {
     //Serial_Number__c    
    List<Serial_Number__c> snumlist = New List<Serial_Number__c>();
    List<Id> orderitemlist = New List<Id>();
    For(Order_Line_Item_Serials__c oli : Trigger.Old){
        orderitemlist.add(oli.Serial_Number__c);
    }
    List<Serial_Number__c> Olis = 
        [Select Id, Name,Serial_Number__c,  
         Product__r.Id,Status__c
         From Serial_Number__c Where
         Status__c = TRUE AND
         ID IN : orderitemlist];
    
    For(Order_Line_Item_Serials__c orim : Trigger.Old){
        For(Serial_Number__c olisn : Olis){
            If(Trigger.IsDelete){
                olisn.Status__c = FALSE;
                snumlist.add(olisn);
            }
        }
    }
    update snumlist; 
}

Thanks in Advance,
Mahesh


 
Hi,

I have to perform Excel IRR Function Calculation in Apex class.
https://exceljet.net/excel-functions/excel-irr-function

Thanks,
Foram Rana
acount record has child contact record, if status__c(picklist) field of contact record is 'open' update account description field of account record.
trigger x4 on Account (before update) {
    list<account> accList = new list<account>();
    set<id> idSet = new set<id>();
    for(account acc : trigger.new){
        idSet.add(acc.id);
    }
    list<contact> conList = [Select id, accountid, Status__c from contact where accountId in: idSet];
    map<id,contact> conMap = new map<id,contact>();
    for(contact con : conList){
        conMap.put(con.accountId, con);
    }
    for(account a : trigger.new){
        if(conmap.containsKey(a.id) || conmap.get(a.id).Status__c=='open'){
            a.description = 'account is updated from contact';
            accList.add(a);
        }
    }
    update acclist;
}


 
Example : String str = ' SELECT Name,Id FROM Account LIMIT 10';
Now i want to retrieve "Account" from this query for further use.
Hi,
Need to resolve the XSRF  issues from Code security review report of Product

When i preview the vf page i got the below error (In the page call only the controller and action)
"The link you followed isn’t valid. This page requires a CSRF confirmation token. Report this error to your Salesforce administrator."
Case 1.
when disable this checkbox for Vf page (Require CSRF protection on GET requests) - the error is not getting. But when i pull the report from Salesforce checkmarx i got the XSRF errors.

Case2:
or we can achive through the possible to disable the 'Cross-Site Request Forgery (CSRF) Protection'
Security controls -->session settings-->'Cross-Site Request Forgery (CSRF) Protection'

Please help
Hello, I've tried all the ways but I'm not getting it, I need that when I put the start date and end date they separate the working days and learn in the DiasTrabalhados__c field. I am not able to develop the necessary validation rule for such an action,
Thanks
public with sharing class OpportunitylistViewCom {
    @AuraEnabled
    public static List<OpportunityLineItem> getOpportunityLineItem(Id accountId,String sortField, boolean isAsc){
        String query = 'Select id,Opportunity.Name,Opportunity.Account.name,Opportunity.RecordType.Name,Opportunity.type,Opportunity.Amount,Opportunity.StageName,Opportunity.Parent_Asset__r.InstallDate,Product_Name__c,UnitPrice,TotalPrice,ListPrice,End_Date__c,Related_To__c ';
            query += 'From OpportunityLineItem where Opportunity.AccountId =:accountId';
        if (sortField != '') {
            query += ' order by ' + sortField;
            if (isAsc) {
                query += ' asc';
            } else {
                query += ' desc';
            }
        }
        list <OpportunityLineItem> oppList1;
        try {
            oppList1 = Database.query(query);
            List < OpportunityLineItem > oppList = new List < OpportunityLineItem > ();
            for (OpportunityLineItem c: oppList1) {
                oppList.add(c);
            }
            return oppList;
        } 
        catch (Exception ex) {
            // for handle Exception
            return null;
        }
    }
   
    @AuraEnabled
    public static list < Attachment > fetchopportunity(Id accountId) {
        set<ID> oppIDs = new set<ID>();
        for(Opportunity opp :[Select id from opportunity where AccountId=:accountId]){
            oppIDs.add(opp.id);
        }
        list < Attachment > returnoppList = new List <Attachment> ();
        List < Attachment > lstopp = [select id,name,LastModifiedDate,CreatedBy.name,Parent.Name, Owner.Name, BodyLength from Attachment where ParentId IN:oppIDs];
        for (Attachment c: lstopp) {
            returnoppList.add(c);
        }
        return returnoppList;
    }
}

 
Hi, I have an apex trigger which displays total tasks related to opportunity, but my trigger is not working even it doesn't have any errors. Can someone help me with this trigger?

//Apex Trigger

trigger OpportunityTaskCount on Task (after insert, after update, after delete, after undelete) {
    Set<Id> oppList = new Set<Id>();
    Set<Id> tskList = new Set<Id>();
    List<Opportunity> updateList = new List<Opportunity>();
    if(trigger.isInsert) {
        for(Task tsk : trigger.new) {
            if(tsk.WhatId != NULL) {
                oppList.add(tsk.Id);
                tskList.add(tsk.WhatId);
            }
        }
        system.debug('Opportunities'+oppList);
    }
    if(trigger.isDelete || trigger.isUpdate ) {
        for(Task tsk : trigger.old) {
            if(tsk.WhatId != NULL) {
                oppList.add(tsk.Id);
                tskList.add(tsk.WhatId);
            }
        }
    }
    if(trigger.isUndelete) {
        for(Task tsk : trigger.new) {
            if(tsk.WhatId != NULL) {
                tskList.add(tsk.WhatId);
            }
        }
    }
    for (Opportunity opp : [SELECT Id, Name, Total_Tasks__c ,(SELECT Id, Status FROM Tasks) 
                           FROM Opportunity 
                           WHERE Id in : oppList]) {
                               opp.Total_Tasks__c = opp.Tasks.size();
                               updateList.add(opp);
                           }
    update updateList;
}
  • March 15, 2020
  • Like
  • 0
Hi all,

i wrote an email handler to create emailMessage with attachements and Lead with files for a recruiting process to work as Email2Lead.
I use Lead Object for Candidates-

Here is my email handler class:
/**
 * Email services are automated processes that use Apex classes
 * to process the contents, headers, and attachments of inbound
 * email.
 */
global class CreateLeadFrmEmail implements Messaging.InboundEmailHandler {

    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email,
    Messaging.InboundEnvelope envelope) {

        Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
        
        String EmailFromName= email.fromName;


            // Create Lead
            Lead c = new Lead();
            c.Email = email.fromAddress;
            c.FirstName = EmailFromName.substring(0,EmailFromName.indexOf(' '));
            c.LastName = EmailFromName.substring(EmailFromName.indexOf(' ')+1);
            c.Company = '';
            insert c;
            
            Id LeadOwner = [SELECT OwnerId FROM Lead WHERE Id =:c.Id].OwnerId;          
            
            // Create Email-Message
            EmailMessage e = new EmailMessage();
            e.FromAddress = email.fromAddress;
            e.Status = '0';
            e.FromName = email.fromName;
            e.Incoming = true;
            e.Subject = email.Subject;
            e.htmlBody = email.htmlBody;
            insert e;
             // Save attachments, if any
      List<Attachment> attachments = new List<Attachment>();

      if(email.textAttachments != null)
      {
        for (Messaging.Inboundemail.TextAttachment tAttachment : email.textAttachments) {
          Attachment attachment = new Attachment();
          attachment.Name = tAttachment.fileName;
          attachment.Body = Blob.valueOf(tAttachment.body);
          attachment.ParentId = e.Id;
          attachments.add(attachment);
          
          ContentVersion cVersion = new contentVersion();
          cVersion.ContentLocation = 'S'; //S-Document is in Salesforce. E-Document is outside of Salesforce. L-Document is on a Social Netork.
          cVersion.PathOnClient = tAttachment.fileName; //File name with extention
          cVersion.Origin = 'H'; //C-Content Origin. H-Chatter Origin.
          cVersion.OwnerId = LeadOwner; //Owner of the file
          cVersion.Title = tAttachment.fileName; //Name of the file
          cVersion.VersionData = Blob.valueOf(tAttachment.body);//File content
          cVersion.SharingOption = 'R';
          insert cVersion;
         
          //After saved the Content Version, get the ContentDocumentId 
          Id conDocument = [SELECT ContentDocumentId FROM ContentVersion WHERE Id =:cVersion.Id].ContentDocumentId;          
         
          //Insert ContentDocumentLink
          ContentDocumentLink cDocLink = new ContentDocumentLink();
          cDocLink.ContentDocumentId = conDocument; //Add ContentDocumentId
          cDocLink.LinkedEntityId = c.Id; //Add attachment parentId
          cDocLink.ShareType = 'I'; //V - Viewer permission. C - Collaborator permission. I - Inferred permission.
          //cDocLink.Visibility = 'SharedUsers';//AllUsers, InternalUsers, SharedUsers
          Insert cDocLink;         

        }
      }
      if(email.binaryAttachments != null)
      {
        for (Messaging.Inboundemail.BinaryAttachment bAttachment : email.binaryAttachments) {
          Attachment attachment = new Attachment();
        
          attachment.Name = bAttachment.fileName;
          attachment.Body = bAttachment.body;
          attachment.ParentId = e.Id;
          attachments.add(attachment);
          
          ContentVersion cVersion = new contentVersion();
          cVersion.ContentLocation = 'S'; //S-Document is in Salesforce. E-Document is outside of Salesforce. L-Document is on a Social Netork.
          cVersion.PathOnClient = bAttachment.fileName; //File name with extention
          cVersion.Origin = 'H'; //C-Content Origin. H-Chatter Origin.
          cVersion.OwnerId = LeadOwner; //Owner of the file
          cVersion.Title = bAttachment.fileName; //Name of the file
          cVersion.VersionData = bAttachment.body;//File content
          cVersion.SharingOption = 'R';
          insert cVersion;

          //After saved the Content Version, get the ContentDocumentId 
          Id conDocument = [SELECT ContentDocumentId FROM ContentVersion WHERE Id =:cVersion.Id].ContentDocumentId;          
         
          //Insert ContentDocumentLink
          ContentDocumentLink cDocLink = new ContentDocumentLink();
          cDocLink.ContentDocumentId = conDocument; //Add ContentDocumentId
          cDocLink.LinkedEntityId = c.Id; //Add attachment parentId
          cDocLink.ShareType = 'I'; //V - Viewer permission. C - Collaborator permission. I - Inferred permission.
          //cDocLink.Visibility = 'InternalUsers';//AllUsers, InternalUsers, SharedUsers
          Insert cDocLink;
          

        }
      }
      // insert attachments
      if(attachments.size() > 0)
      {
        insert attachments;
      }
    
            
      // Add Email Message Relation for id of the sender
      EmailMessageRelation emr = new EmailMessageRelation();
      emr.emailMessageId = e.Id;
      emr.relationId = c.Id; // Lead id of the sender
      emr.relationType = 'FromAddress';
      insert emr;

    result.success = true;
        return result;
    }

}

I'm no developing expert and my testclass has only  43% coverage. How can i extend testing to cover ContentVrsion, Attachements and the created lead record?
Here is my testclass:
@isTest
public class CreateLeadFrmEmailTest
{
 //Test Method for main class
   
   static testMethod void CreateLeadFrmEmail()
   {
       // create a new email and envelope object
       Messaging.InboundEmail email = new Messaging.InboundEmail() ;
       Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
       
       // setup the data for the email
      email.subject = 'Test Email';
      email.fromAddress = 'someaddress@email.com';
      email.plainTextBody = 'email body\n2225256325\nTitle';
      email.fromName = 'Test Candidate';
      
      // add an Binary attachment
      Messaging.InboundEmail.BinaryAttachment attachment = new Messaging.InboundEmail.BinaryAttachment();
      attachment.body = blob.valueOf('my attachment text');
      attachment.fileName = 'textfileone.txt';
      attachment.mimeTypeSubType = 'text/plain';
      email.binaryAttachments = new Messaging.inboundEmail.BinaryAttachment[] { attachment };
      
      
  
      // add an Text attachment
  
      Messaging.InboundEmail.TextAttachment attachmenttext = new Messaging.InboundEmail.TextAttachment();
      attachmenttext.body = 'my attachment text';
      attachmenttext.fileName = 'textfiletwo3.txt';
      attachmenttext.mimeTypeSubType = 'texttwo/plain';
      email.textAttachments =   new Messaging.inboundEmail.TextAttachment[] { attachmenttext };
      
      
      // call the email service class and test it with the data in the testMethod
      CreateLeadFrmEmail  testInbound=new CreateLeadFrmEmail ();
      testInbound.handleInboundEmail(email, env);
    
     
   
   }
 
 
}

Many thanks in advance!
Timo
Hi Everyone,

When i am writting Pd1 maintance exam i got error 


When executed, the BatchLeadConvertTest test class has test failures. All tests should pass.

Thank you
For me if I go to settings it is showing like below how to create a namespace there is no edit 

Please check below image help me how I can create it 
User-added image
There is no Edit option that is what is showing for me in my org account
Hi folks,
How to send email alert / notificaiton from Case object to '''SLA Custom object ---> Peer reviwer ''' through APex class.
Can you some one pls provide code for this requirement 
Thanks
Sekhar
 
  • November 07, 2019
  • Like
  • 1
I have case object firstname and lastname and city multiselect picklist i need to auto populate combination of above 3 fields.