• Niraj Kr Singh
  • SMARTIE
  • 863 Points
  • Member since 2015


  • Chatter
    Feed
  • 27
    Best Answers
  • 1
    Likes Received
  • 2
    Likes Given
  • 3
    Questions
  • 150
    Replies
What I have so far covers 26% of the batch class. I'm not able to cover the execute portion of the batch class.

batch.cls
public class Batch implements Database.Batchable<sObject> {

	public Database.QueryLocator start(Database.BatchableContext bc) {
        String query = 'SELECT Id, jstcl__Consultant__r.Previous_Timesheet_Status__c FROM jstcl__TG_Timesheet__c WHERE jstcl__Placement__r.ts2__Status__c =\'Active\' AND jstcl__Placement__r.VMS__c = \'\' AND jstcl__Week_Ending__c = LAST_N_DAYS:4 AND jstcl__Status__c = \'Pending\'';
          return Database.getQueryLocator(query);
    }
   public void execute(Database.BatchableContext BC, List<jstcl__TG_Timesheet__c> timesheets){
       List<Contact> consultants = new List<Contact>();
       List<Contact> consultants2 = new List<Contact>();

       for(jstcl__TG_Timesheet__c timesheet : timesheets){
           Contact consultant = timesheet.jstcl__Consultant__r; 
           if (consultant == null) continue;
           consultant.Previous_Timesheet_Status__c = 'Pending';
           if(consultants.contains(consultant)){
               consultants2.add(consultant);
           }else{consultants.add(consultant);}
           }
           update consultants;
        }
   public void finish(Database.BatchableContext BC){}
}
test.cls
@istest 
private class Test {

static TestMethod void hfTest() {
     Profile prof = [select id from profile where name='system Administrator'];
     User usr = new User(alias = 'usr', email='us.name@vmail.com',
                emailencodingkey='UTF-8', lastname='lstname',
                timezonesidkey='America/Los_Angeles',
                languagelocalekey='en_US',
                localesidkey='en_US', profileid = prof.Id,
                username='testuser128@testorg.com');
                insert usr;
    Id idRecordId = Schema.SObjectType.Contact.getRecordTypeInfosByDeveloperName().get('Candidate').getRecordTypeId();

    	ts2__Source__c source = new ts2__Source__c(Name = 'LinkedIn.com - Resume Search');
    	Account acc = new Account(Name = 'Express Scripts Holding Company');
        insert acc;
  		Account acc2 = new Account(Name = 'Candidates- 10-2018');
        insert acc2;
    	Contact con = new Contact(FirstName='fnadmes', LastName = 'lnamdes', Email = 'emadils@gmail.com', Phone = '9744800300', AccountId = acc2.Id, ts2__Source__c = source.Id, ts2__People_Status__c = 'Placed');
        Contact con2=new Contact(FirstName='fnames', LastName = 'lnames', Email = 'emails@gmail.com', Phone = '9743800300', AccountId=acc.Id, Relationship_Status__c = 'Lunch'); 
    	insert con; insert con2;
        ADP_Department__c adp = new ADP_Department__c(Name = 'Georgia');
        insert adp;
        ts2__Job__c job = new ts2__Job__c(Name = 'Software Engineer',Hiring_Manager_Contact__c = con2.Id);
        insert job;
        ts2__HolidayCalendar__c hcal = new ts2__HolidayCalendar__c(Name= 'Holiday Calendar');
        insert hcal;
        Labor_Category__c lcat = new Labor_Category__c(Name='Software Engineer 1');  
        insert lcat;
        ts2__Placement__c plc = new ts2__Placement__c(ts2__Job__c = job.Id, Contractor_Type__c = 'Technical Youth', Onboarding_Method__c= 'Staff Augmentation', ts2__Start_Date__c= Date.newInstance(2019, 1, 7), ts2__End_Date__c= Date.newInstance(2019, 2, 15),
        jstcl__HireType__c= 'W2', ADP_Department__c= adp.Id, ts2__Bill_Rate__c= 60.00, ts2__Pay_Rate__c= 30.00, jstcl__Invoice_Batch__c= 'Placement', ts2__Client__c= acc.Id, ts2__Hiring_Manager__c= con2.Id, jstcl__TimecardApprover__c= con2.Id, jstcl__HolidayCalendar__c= hcal.Id,
		State_Worked_In_Non_TFI_Placements__c= 'GA - Georgia', jstcl__Overtime_Bill_Rate__c= 60, jstcl__Burden__c= 0.20, jstcl__Accounts_Receivable_U__c= '00537000005d7F2AAI', jstcl__Terms__c= 'Net 60', ts2__Employee__c= con.Id, Labor_Category__c= lcat.Id);
		insert plc;
     	List<jstcl__TG_Timesheet__c> tsList = new List<jstcl__TG_Timesheet__c>();
    	 jstcl__TG_Timesheet__c ts = new jstcl__TG_Timesheet__c(jstcl__Consultant__c = con2.Id, jstcl__Placement__c = plc.Id, jstcl__Week_Ending__c = Date.newInstance(2019, 2, 15));
    tsList.add(ts);

	Test.startTest(); 
     Batch abcd = new Batch();
     ID batchprocessid = Database.executeBatch(abcd);
	Test.stopTest();
 }    
}

 
I've created a formula for a Workflow Rule to Update a field value. But I get and error message: Error: Incorrect number of parameters for function 'ISPICKVAL()' Expected 2, received 3

I don't seem able to correct this. Anyone have any ideas?

User-added image

 
Hi All, 

I am getting following error message: 

Challenge not yet complete... here's what's wrong:
A field with an API Name 'Match_Billing_Address__c' does not exist on the Account object

my code is as follows:


trigger AccountAddressTrigger on Account (before insert, before update) {
     for(Account a : Trigger.New) {
        if(a.Match_Billing_Address__c==true){a.ShippingPostalCode=a.BillingPostalCode;}
    }
}

 Thanks in Advance
Dear Developers,

I would like to send notification of public group users by using batch class(weekly based). can anyone please advise me how can i change my code for accurate requirement.

Batch Class 
global class PSO_etmfErrorLogBatch implements database.batchable<SObject>{

global database.querylocator start(database.batchableContext bc){
    system.debug('Start Method Running');
    return Database.getQueryLocator('Select Id,name from eTMF_Files_Error_Log__c');
}

global void execute(database.batchableContext bc, List<eTMF_Files_Error_Log__c> errlogList){
    system.debug('Execute Method Running');
    List<String> toAddresses = new List<String>();
    List<User> userList = [select id, name, email, isactive, profile.name, userrole.name, usertype 
                           from user 
                           where id in (select userorgroupid from groupmember where group.name = 'Document Tracking Admin')];
    for(User u : userList){           
        toAddresses.add(u.email);
    }  
    List < Messaging.SingleEmailMessage > emails = new List < Messaging.SingleEmailMessage > ();
    for (eTMF_Files_Error_Log__c irow_erLog : errlogList) {
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        email.setToAddresses(toAddresses});
        email.setSubject('Last Week ETMF Error Log'); 
        email.setPlainTextBody('Dear user, Please Check Last Week ETMF Error Log');
        emails.add(email);
    }
    Messaging.sendEmail(emails);
}

global void finish(database.batchableContext bc){}

}

Hearty Thanks In Advance !!

Regards,
Soundar P
Hello Guys,

I am working on custom metadata, I have custom meta data "Org_Email_Signature__mdt" and is having field type Long text Area "Email_Signature__c".

Now, when I create a new user, I need to fetch that custom meta data to a field "Signature" in user object. I need to write a trigger for this.

Please help me to achieve this functionality.
Hello Group Members,

I just have a qauestion about apex trigger which is used to create a record. This trirgger currently sets the created by user to current user who has doen the transaction. Is there any way to make sure that I set the user to run the apex trigger in a saingle user context so that the record created by field is always same user irrespective of who did the transaction?
Hi All

How can i create child based on multi picklist value selectio on parent.I will select 1 value in multi picklist then it will create 1 child .i will select 2 value then it will create 2 child and so on.


 
I have a date field in Account . I need to find the date 365 days before the mentioned date in SOQL query
Hi,

Can you please help me with test  class
Class:
global class CDPWeeklyDigestBatchScheduler implements Schedulable {

    global void execute(SchedulableContext sc) {
        String query = 'SELECT Id, Deal_Id__c, Deal_Name__c, Deal_Stage__c, Type__c, Region_Type__c, Market__c, Deal_Owner__c, Latest_Change__c, Deal_Lost_Reason__c, Number_Of_Updates__c FROM CDP_Notification__c WHERE LastModifiedDate = LAST_N_DAYS:7 ';
        List<SObject> records = Database.query(query);    
        NotificationHelper.getNotificationHelperInstance().notifyUsersAboutWeeklyDigest(records);
    }








 
Hi,
Can you please help me with test class


Class:

global with sharing class BatchToEndCarouselAnnouncementsScheduler extends BatchScheduler implements Schedulable
{
    global BatchToEndCarouselAnnouncementsScheduler()
    {
        super(10 /*minutes between attempts */, 'End Carousel Announcements');
    }
    
    global void execute(SchedulableContext sc)
    {
        schedule(new BatchToEndCarouselAnnouncements());
    }
}


Extended Class:

public with sharing abstract class BatchScheduler implements Schedulable
{
    @TestVisible static final Integer MAX_CONCURRENT_BATCH = 5;
    @TestVisible Integer minutesBeforeReschedule;
    @TestVisible String title;
    public BatchScheduler( Integer minutes, String title )
    {
        this.minutesBeforeReschedule = minutes;
        this.title = title;
    } 
    public void schedule( IBatchHelper helper, Integer batchSize )
    {
        Integer currentlyRunningBatches = [SELECT count() FROM AsyncApexJob WHERE JobType='BatchApex'
                                           AND (Status = 'Processing' OR Status = 'Preparing')];
        if( currentlyRunningBatches < MAX_CONCURRENT_BATCH )
        {
            BatchHandler batch = new BatchHandler( helper );
            Database.executeBatch( batch, batchSize );
        }
        else
        {
            scheduleRetry();
        }
    }

    public void schedule( IBatchHelper helper )
    {
        schedule( helper, 200 );
    }

    @TestVisible void scheduleRetry() 
    { 
        Datetime rescheduleDateTime = Datetime.now().addMinutes(minutesBeforeReschedule); 
        String timeForScheduler = rescheduleDateTime.format('s m H d M \'?\' yyyy'); 
        System.schedule(title + ' ' + timeForScheduler, timeForScheduler, this); 
    } 
}
Hi, I have created a detail custom button of url type and passing Opportunity Date as shown below.

/apex/vfpage?oliId={!OpportunityLineItem.Id} && oppDate={!Opportunity.customDate__c}

And in apex constructor i am receiving the custom date value as below.

customDate = Date.valueOf(ApexPages.currentPage().getParameters().get('oppDate'));
But I am receiving error as
"Argument cannot be null. An unexpected error has occurred. Your development organization has been notified. "

How to pass the oppDate from url to constructor.
 
Hello,

I am doing Upsert Operation....
Below is my code.
I have a problem while performing Upsert operation:
Scenirio:
Firstly i have to insert a records
then perform Upsert Operation.
I am using external Id while performing DML (Non Atomic)
The records in inserted insted of upsert .




public class upsertDatabase {
    
    public list<Customer_Project__c> cPlist;
    
    public upsertDatabase(){
        cPlist=new list<Customer_Project__c>();
        list<Opportunity> opList=[select id,name from Opportunity where name='Sapna'];
        // insert the new Records
        for(Opportunity ops:opList){
            Customer_Project__c c1=new Customer_Project__c();
            c1.Name='Timakshi';
            c1.ExternalID__c=111;
           c1.Opportunity__c=ops.id;
            c1.Payment__c=78787;
            cPlist.add(c1);
        }
        database.SaveResult[] sr=database.insert(cpList,false);
        for(database.SaveResult s:sr){
            if(s.isSUCCESS()){
                system.debug('success Message' +s.getID());
            }
            else{
                database.Error[] myError=s.getErrors();
                for(database.Error er:myError){
                    system.debug('Error Mesaage for Inserting the records' +er.getMessage());    
                }
            }
        }
// upsert the Records 
        for(Opportunity oops:opList){
            Customer_Project__c c2=new Customer_Project__c();
            c2.Name='Taniya';
            c2.Opportunity__c=oops.id;
            c2.Payment__c=8888855;
            c2.ExternalID__c=989;
            cPlist.add(c2);
        }
        for(Opportunity oops:opList){
            Customer_Project__c c3=new Customer_Project__c();
            c3.Name='Geta';
            c3.Opportunity__c=oops.id;
            c3.Payment__c=8744;
            c3.ExternalID__c=99;
            cPlist.add(c3);
        }
        database.UpsertResult[] UpResult=database.upsert(cPlist,false);
        
        for(database.UpsertResult uR:UpResult){
            if(uR.isSUCCESS()){
                system.debug('Success for Upserting the records' +uR.getId());
            }
            else{
                database.Error[] myUpsertError=uR.getErrors();
                for(database.Error ero:myUpsertError){
                    system.debug('My upsert Errors Message' +ero.getMessage());
                }
                }
            }
        }
        
    }
If((LeadList[0].OwnerId != '005User1') || (LeadList[0].OwnerId != '005User2) || (LeadList[0].OwnerId != '005User3'))

Need help writing this line better
Hi Team,

We have updated the field in same object using before insert & Update triggers, Is it necessary to use Recursive class for this trigger.

Please let me know.

Thanks,
Lakshmi.
list<HCP_User_BMS_CN__c> hcplist =[SELECT ,Hospital_Name_BMS_CN__c, Id, User_BMS_CN__r.name, Status_BMS_CN__c FROM HCP_User_BMS_CN__c  ];
for(HCP_User_BMS_CN__c hcp : hcplist){
    String hco = hcp.Hospital_Name_BMS_CN__c;
    String temp='';
    for (integer i = 0; i < hco.length(); i++) {
        temp += hco.substring(i, i+1) + '%';
    }
    String hcolike ='%'+temp ;
    
    list<Account> hcos = [SELECT Name FROM Account where  Name like: hcolike];
    list<String> hcolist = new list<String>();
    for (integer i = 0; i < hcos.size(); i++) {
        hcolist.add(hcos[i].Name);
    }
    //System.debug('hcolist'+'   '+hco+' '+hcolist.size());
    
    if(hcolist.size()>0){
        list<Account> acclist = [select id ,Name,Primary_Parent_vod__r.Name FROM Account where Primary_Parent_vod__r.Name in :hcolist and Name=:hcp.User_BMS_CN__r.name];
        if(acclist.size()>0){
           System.debug('acclist'+acclist); 
        }
    }
}

Because soql inside a for loop ,I am Getting This Below Error:System.LimitException: Too many SOQL queries: 101 . How to deal with it?
 Map<String,String> resultMap = new Map<String,String>();
Can any onecan help me with test class

public with sharing class OpportunityQuickCreateExt
{
    public OpportunityQuickCreateExt( QuickCreateController quickCreateCont )
    {
        User currentUser = [ SELECT Default_Continent__c, Default_Market__c, Default_Region__c
                             FROM User WHERE Id = :UserInfo.getUserId() ];
        quickCreateCont.quickCreateObject.put( 'Name', 'Dummy Name' );
        quickCreateCont.quickCreateObject.put( 'StageName', 'E Qualify / Suspect-No RFP' );
        quickCreateCont.quickCreateObject.put( 'Continent__c', currentUser.Default_Continent__c );
        
        if( !String.isEmpty( currentUser.Default_Region__c ) )
        {
            List<Region__c> defaultRegion = [SELECT Id FROM Region__c WHERE Name = :currentUser.Default_Region__c LIMIT 1 ];
            quickCreateCont.quickCreateObject.put( 'Region__c', defaultRegion.isEmpty() ? NULL : defaultRegion[0].Id );
        }
        if( !String.isEmpty( currentUser.Default_Market__c ) )
        {
            List<Market__c> defaultMarket = [SELECT Id FROM Market__c WHERE Name = :currentUser.Default_Market__c LIMIT 1 ];
            quickCreateCont.quickCreateObject.put( 'Market__c', defaultMarket.isEmpty() ? NULL : defaultMarket[0].Id );
        }
    }
}
While inserting new account records before update account trigger is firing. I don't want to execute update trigger how to stop these update trigger execution. Please assist me.

Thanks!
I am working on writing a service which is expected to monitor Scheduled batch jobs. I am querying CronTrigger to get list of all scheduled classes but could not find a direct way to find out which ApexClass is scheduled. 

Is there a way in recent releases to find out which apex class is scheduled in particular CronTrigger record in Apex ?