• Foram Rana R
  • NEWBIE
  • 410 Points
  • Member since 2019


  • Chatter
    Feed
  • 12
    Best Answers
  • 2
    Likes Received
  • 5
    Likes Given
  • 4
    Questions
  • 92
    Replies
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;
                   
                   }
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;
}
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
I have 2 picklist Department & product which are dependent.
On a visualforce page i want to show the product picklist but want to show only those products in which department is 'Warehouse'
Hi Developers

i am working on  the test class for Emailalertbatclass, but i am not able to cover the excute method, it is only showing 27%, could anyone please help in the covering 100%
 
global class Emailalertbatchclass implements Database.Batchable<sObject>, Schedulable, Database.Stateful {
    
    //Variable Section
    global FINAL String strQuery;
    global FINAL String leadid;
    global List<String> errorMessages = new List<String>();
    
    global Emailalertbatchclass() { 
        this.strQuery = getBatchQuery();
    }
    
    //Returns the Query String to Batch constructor to fetch right records.
    private String getBatchQuery() {
        String strQuery = 'SELECT Id,Name,Status,Email,owner.email,owner.name,ownerid,No_Enquiry_Email_Sent__c,Manager_Email__c,recordtype.name FROM Lead where No_Enquiry_Email_Sent__c=false AND recordtype.name=\'Lead Registration\' AND Lead_Intent_Type__c=\'High Intent Lead\' AND Status=\'Enquiry\' And ((DaysSinceLastActivityDone__c>=0) OR (DayssinceEnquirystage__c >= 0))';
        return strQuery;
    }
    
    //Batch Start method
    global Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator(strQuery);
    }
    
    //Batch Execute method calls findCostForWoD method
    global void execute(Database.BatchableContext BC, List<sObject> scopeList) {
        System.debug(LoggingLevel.INFO, '== scopeList size ==' + scopeList.size());
        
        List<Lead> ld = (List<Lead>) scopeList;
        List<Lead> updatedld = new List<Lead>();
        if(!ld.isEmpty()) { 
            List<Messaging.SingleEmailMessage> mailList = new List<Messaging.SingleEmailMessage>();
            for (Lead prod : ld)
            {               
                // Step 1: Create a new Email
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                System.debug( 'prod.owner.Email ' + prod.owner.Email);
                String[] toAddresses = new String[] {prod.owner.Email};
                    // Step 2: Set list of people who should get the email
                    if(prod.Manager_Email__c!=null && prod.Manager_Email__c==''){
                        toAddresses.add(prod.Manager_Email__c);
                    }
                mail.setToAddresses(toAddresses);
                System.debug( 'toAddresses ' + toAddresses);
                
                // Step 3: Set who the email is sent from
                mail.setReplyTo(prod.owner.Email);
                mail.setSenderDisplayName('No Activity on Leads for 24hrs');
                
                // (Optional) Set list of people who should be CC'ed
                List<String> ccTo = new List<String>();
                mail.setCcAddresses(ccTo);
                
                // Step 4. Set email contents - you can use variables!
                mail.setSubject('No Activity on Lead for 24hrs');
                String body = 'Dear ' + prod.owner.name + ', <br><br>';
                body += 'This is to notify you that there is no activity done on the respective <b> Lead Name: ';
                body +=prod.Name+'</b>  please find the link below..<br><br>';
                body += 'link to file: '+URL.getSalesforceBaseUrl().toExternalForm()+'/'+prod.id+'<br><br><br> Thanks,<br>Moengage Team</body></html>';
                mail.setHtmlBody(body);
                System.debug( 'body ' + body);
                
                // Step 5. Add your email to the master list
                mailList.add(mail);
                prod.No_Enquiry_Email_Sent__c = true;
                updatedld.add(prod);
                System.debug( 'prod ' + prod);
                
            }
            if(!mailList.isEmpty()) {
                try{
                    Messaging.sendEmail(mailList);
                    update updatedld;
                    system.debug('mailList '+mailList);
                }
                catch (Exception ex) {
                    errorMessages.add('Unable to send email to Tech: '+ ex.getStackTraceString());
                }
            }
        }
    }  
    
    //Batch Finish method for after execution of batch work
    global void finish(Database.BatchableContext BC) { 
        
    }
    
    //Method which schedules the ProductDownloadBatch
    global void execute(SchedulableContext sc) {        
        Emailalertbatchclass snInstance = new Emailalertbatchclass();
        ID batchprocessid = Database.executeBatch(snInstance);
    }
}

Test Class
 
@isTest
public class EmailalertbatchclassTestclass
{
    static testMethod void testmethod1()
    {
        
        Id rcdTypeId = Schema.SObjectType.Lead.getRecordTypeInfosByName().get('Lead Registration').getRecordTypeId();
        List<Lead> Leadld = new List<Lead>();
        lead ld = new lead();
        ld.FirstName= 'test';
        ld.LastName='Test2';
        ld.status='Enquiry';
        ld.Company = 'fgfh';
        ld.Email = 'Nilu112@gmail.com';
        ld.Manager_Email__c = 'rakeshkumar1998@gmail.com';
        ld.RecordTypeId = rcdTypeId;//added here
        ld.No_Enquiry_Email_Sent__c = false;  //changed true to false
        
        Insert ld;
        Leadld.add(ld); 
        
        Test.startTest();
        ld.FirstName = 'test1';
        update ld;
        
        Emailalertbatchclass snInstance = new Emailalertbatchclass();
        ID batchprocessid = Database.executeBatch(snInstance);
        
        Test.stopTest();
    }
    public static testMethod void testschedule() {
        Test.StartTest();
        Emailalertbatchclass sh1 = new Emailalertbatchclass();
        String sch = '0 00 01 * * ?'; 
        ID batchprocessid = Database.executeBatch(sh1);
        String jobId = system.schedule('Emailalertbatchclass', sch, sh1);
        System.assert(jobId != null);
        Test.stopTest(); 
    }
}

 
 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();
    }
}
Hi,

I would like to retrieve the contacts related to each account using the apex class. I tried but I am getting the list of accounts on page. Can someone tell me how to achieve this?

//Apex Class

public class operations_class
{
    public List<Contact> result{get;set;}
    public List<Account> accList = [Select Id from Account];
    public operations_class()
    {
        result=new List<Contact>();
    }
    public void search()
    {
        result=[Select FirstName, LastName, Email from Contact Where account.Id=:accList];
    }
}


//VF Page

<apex:page controller="operations_class">
    <script>
        window.onloadstart = function()
        {
            hello()
            {

            }
        }
    </script>
    <apex:form>
        <apex:actionFunction name="hello" action="{!search}">
        <apex:pageBlock>
            <apex:pageBlockTable value="{!result}" var="con">
                <apex:column value="{!con.FirstName}"/>
                <apex:column value="{!con.LastName}"/>
                <apex:column value="{!con.Email}"/>
            </apex:pageBlockTable>
        </apex:pageBlock>
        </apex:actionFunction>
    </apex:form>
</apex:page>
public class notes2 {

 public string SelectedValue{get;set;}
 
 public list<selectoption> Alloptions{get;set;}
 
 public list<selectoption> Selectedoptions{get;set;}
 
  
   public notes2(){
   getnames(); 
    }
 
  public void getnames(){
  Alloptions= new list<selectoption>();
  
  selectoption s1 = new selectoption('Ban' ,'Banglore');
  selectoption s2 = new selectoption('Hyd' ,'Hyderbad');
  selectoption s3 = new selectoption('Che' ,'Chennai');
  selectoption s4 = new selectoption('Ap' ,'Andhrapradesh');
  Alloptions.add(s1);
  Alloptions.add(s2);
  Alloptions.add(s3);
  Alloptions.add(s4);
  }
  
   public void addtolist(){
   
    system.debug('the selected values are::'+ selectedvalue);
    
   }
}

Visualforcepage:
 
<apex:page controller="notes2" >
  <apex:form id="fm">
  
  
   
   <apex:outputPanel id="test1" >
    <apex:selectList value="{!SelectedValue}"  id="slctedval" multiselect="true" size="5">
      <apex:selectOptions value="{!Alloptions}"/>
     </apex:selectList>
     
     
      
     &nbsp; &nbsp;
     <apex:commandButton value="Addtolist" />
       &nbsp; &nbsp;
       <apex:selectList id="Hydlist" multiselect="true" size="5" style="width:100px;" >
      <apex:selectOptions value="{!Selectedoptions}"/>
       </apex:selectList>
       
       <br/><br/>
      
     
       
        
         
       
  </apex:outputPanel>
   
   </apex:form>
</apex:page>

 
how to add the selected values of onepicklist to other picklist of multislect, please provide usefull links
note: Duplicates cannot be added further.
User-added image

thank you.. !
Deepika chowdary
 
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.