• Bablu Kumar Pandit
  • NEWBIE
  • 85 Points
  • Member since 2019
  • Developer
  • 360 Degree Cloud Technology pvt Ltd.

  • Chatter
    Feed
  • 1
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 29
    Questions
  • 28
    Replies
Hi, I am trying to write a batch class which will delete the opportunities whose CloseDate is last month and update checkbox in related account.

//Batch Class

global class DeleteOppsBatch implements Database.Batchable<SObject> {
    List<Account> newList = new List<Account>();
    global Database.QueryLocator start (Database.BatchableContext BC) {
        return Database.getQueryLocator([Select Id, DeletedOpp__c, (SELECT Id, CloseDate FROM Opportunities WHERE CloseDate = LAST_N_DAYS:30) FROM Account]);
    }
    global void execute(Database.BatchableContext BC, List<Account> accList) {
        for(Account acc : accList) {
            acc.DeletedOpp__c = TRUE;
            newList.add(acc);
        }
        //update newList;
    }
    global void finish(Database.BatchableContext BC) {
        System.debug('listsize:'+newList.size());
        delete newList;
    }
}

I didn't understand why this class is not working. Can someone help me achieve this functionality.

Thanks in advance.
-----My class cover 64 % how to increase covarge----
global class OnDemandSandboxSchedulerV3 implements Schedulable,Database.AllowsCallouts{

    global void execute(SchedulableContext sc){
        expiredDate();
        dailyCtrlOpr();
    }

    global void expiredDate(){
        List<ManageOnDemandS__c> lstmanagedemand = [Select Id,Sandbox_Id__c,Name,Expire_Date__c,OnDemandRealms__c from ManageOnDemandS__c where Expire_Date__c = today AND Status__c != 'Deleted Sandbox'];
        System.debug('----lstmanagedemand--'+lstmanagedemand);
        if(!lstmanagedemand.isEmpty()){
            //Using JSON.Serialize method we can convert the account list to Json
            String sandboxData = JSON.Serialize(lstmanagedemand);
            System.debug('sandboxData---'+sandboxData);
            //Calling the handler to delete the Sandbox
            OnDemandSandboxIntegrationClass.deleteSandbox(sandboxData);
        }  
    }

    global void dailyCtrlOpr(){
        DateTime now = DateTime.now();
        System.debug('---now'+now);
        String dayOfWeek;
        String hour;
        if(test.isRunningTest()){
            dayOfWeek = 'Saturday';
        }else{
          dayOfWeek = now.format('EEEEE');
        }
         //String dayOfWeek = 'Saturday';
        System.debug('---dayOfWeek'+dayOfWeek);
        if(test.isRunningTest()){
            hour = '2';
        }else{
          hour = String.valueOf(now.hour());
        }
        System.debug('---hour'+hour);
        
        List<ManageOnDemandS__c> lstToStop = new List<ManageOnDemandS__c>();
        List<ManageOnDemandS__c> lstToStart = new List<ManageOnDemandS__c>();
        for(ManageOnDemandS__c mngSndBox:[Select Id, Action__c, Sandbox_Id__c, Status__c, DailyStart__c, DailyStop__c, Friday_Start__c, Friday_Stop__c, Monday_Start__c, Monday_Stop__c, Saturday_Start__c, Saturday_Stop__c, Sunday_Start__c, Sunday_Stop__c, Thrusday_Start__c, Thrusday_Stop__c, Tuesday_Start__c, Tuesday_Stop__c, Wednesday_Start__c, Wednesday_Stop__c, Weekend_Stop_Re_Start__c, Monday_Checkbox__c, Tuesday_Checkbox__c, Wednesday_Checkbox__c, Thrusday_Checkbox__c, Friday_checkbox__c, Saturday_Checkbox__c, Sunday_Checkbox__c, OnDemandRealms__c FROM ManageOnDemandS__c WHERE (Action__c IN ('start','stop','Create Sandbox')) LIMIT 50000]){
        System.debug('---mngSndBox'+mngSndBox);
		
            if(mngSndBox.Action__c == 'start' || mngSndBox.Action__c == 'Create Sandbox'){
                if(dayOfWeek == 'Monday' && mngSndBox.Monday_Checkbox__c == true && mngSndBox.Monday_Start__c == hour){
                    lstToStop.add(mngSndBox);
                }else if(dayOfWeek == 'Tuesday' && mngSndBox.Tuesday_Checkbox__c == true && mngSndBox.Tuesday_Start__c == hour){
                    lstToStop.add(mngSndBox);
                }else if(dayOfWeek == 'Wednesday' && mngSndBox.Wednesday_Checkbox__c == true && mngSndBox.Wednesday_Start__c == hour){
                    lstToStop.add(mngSndBox);
                }else if(dayOfWeek == 'Thursday' && mngSndBox.Thrusday_Checkbox__c == true && mngSndBox.Thrusday_Start__c == hour){
                    lstToStop.add(mngSndBox);  
                }else if(dayOfWeek == 'Friday' && mngSndBox.Friday_checkbox__c == true && mngSndBox.Friday_Start__c == hour){
                    lstToStop.add(mngSndBox);
                }else if(dayOfWeek == 'Saturday' && mngSndBox.Saturday_Checkbox__c == true && mngSndBox.Saturday_Start__c == hour){
                    lstToStop.add(mngSndBox);
                }else if(dayOfWeek == 'Sunday' && mngSndBox.Sunday_Checkbox__c == true && mngSndBox.Sunday_Start__c == hour){
                    lstToStop.add(mngSndBox);
                }
            }else if(mngSndBox.Action__c == 'stop'){
                if(dayOfWeek == 'Monday' && mngSndBox.Monday_Checkbox__c == true && mngSndBox.Monday_Stop__c == hour){
                    lstToStart.add(mngSndBox);
                }else if(dayOfWeek == 'Tuesday' && mngSndBox.Tuesday_Checkbox__c == true && mngSndBox.Tuesday_Stop__c == hour){
                    lstToStart.add(mngSndBox);
                }else if(dayOfWeek == 'Wednesday' && mngSndBox.Wednesday_Checkbox__c == true && mngSndBox.Wednesday_Stop__c == hour){
                    lstToStart.add(mngSndBox);
                }else if(dayOfWeek == 'Thursday' && mngSndBox.Thrusday_Checkbox__c == true && mngSndBox.Thrusday_Stop__c == hour){
                    lstToStart.add(mngSndBox);
                }else if(dayOfWeek == 'Friday' && mngSndBox.Friday_checkbox__c == true && mngSndBox.Friday_Stop__c == hour){
                    lstToStart.add(mngSndBox);
                }else if(dayOfWeek == 'Saturday' && mngSndBox.Saturday_Checkbox__c == true && mngSndBox.Saturday_Stop__c == hour){
                    lstToStart.add(mngSndBox);
                }else if(dayOfWeek == 'Sunday' && mngSndBox.Sunday_Checkbox__c == true && mngSndBox.Sunday_Stop__c == hour){
                    lstToStart.add(mngSndBox);
                }
            }
        }
        System.debug('---lstToStop'+lstToStop);
        System.debug('---lstToStart'+lstToStart);
        //System.debug('---lstMngSndBox'+lstMngSndBox);
        if(!lstToStart.isEmpty()){
            String sndBoxStart = JSON.Serialize(lstToStart);
            OnDemandSandboxIntegrationClass.controlSandbox(sndBoxStart,'daily-start');
        }if(!lstToStop.isEmpty()){
            String sndBoxStop = JSON.Serialize(lstToStop);
            OnDemandSandboxIntegrationClass.controlSandbox(sndBoxStop,'daily-stop');
        }
    }
}

///------My Test Class-----///
@isTest
public class OnDemandSandboxSchedulerV2Test {
    static testmethod void Testscheduledmethod(){
        String CRON_EXP = '0 0 2 * * ? *';
        DateTime now = DateTime.now();
        String  status = 'weekend-stop';
        OnDemandRealms__c objdem = New OnDemandRealms__c();
        objdem.RealmID__c = 'bdtv';
        objdem.Key__c = '6776c02b-6981-4234-a73a-6528a04cd30e';
        objdem.keypassword__c ='87900';
        insert objdem;
        
        ManageOnDemandS__c managdemand = New ManageOnDemandS__c();
        managdemand.Expire_Date__c = System.today();
        managdemand.Status__c = 'Sandbox';
        managdemand.Action__c = 'Create Sandbox';
        managdemand.Weekend_Stop_Re_Start__c = true;
        managdemand.DailyStop__c = '2';
        managdemand.DailyStart__c = '2';
        managdemand.OnDemandRealms__c = objdem.Id;
        insert managdemand;
      
        Test.setMock(HttpCalloutMock.class, new RestMock());
        test.startTest();  
        OnDemandSandboxSchedulerV3 obj = New OnDemandSandboxSchedulerV3();
        String jobId = System.schedule('ScheduleApexClassTest',  CRON_EXP, obj);
        CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobId];
        System.assertEquals(CRON_EXP, ct.CronExpression);
        System.assertEquals(0, ct.TimesTriggered);
        test.stopTest();
    }
    
    static testmethod void Testscheduledmethod1(){
        String CRON_EXP = '0 0 2 * * ? *';
        DateTime now = DateTime.now();
        String  status = 'weekend-stop';
        OnDemandRealms__c objdem = New OnDemandRealms__c();
        objdem.RealmID__c = 'bdtv';
        objdem.Key__c = '6776c02b-6981-4234-a73a-6528a04cd30e';
        objdem.keypassword__c ='87900';
        insert objdem;
        
        ManageOnDemandS__c managdemand = New ManageOnDemandS__c();
        managdemand.Expire_Date__c = System.today();
        managdemand.Status__c = 'Sandbox';
        managdemand.Action__c = 'Create Sandbox';
        managdemand.Weekend_Stop_Re_Start__c = true;
        managdemand.DailyStop__c = '2';
        managdemand.DailyStart__c = '2';
        managdemand.OnDemandRealms__c = objdem.Id;
        insert managdemand;
        
        managdemand.Action__c = 'Stop';
        update managdemand;
      
        Test.setMock(HttpCalloutMock.class, new RestMock());
        test.startTest();  
        OnDemandSandboxSchedulerV3 obj = New OnDemandSandboxSchedulerV3();
        String jobId = System.schedule('ScheduleApexClassTest',  CRON_EXP, obj);
        CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobId];
        System.assertEquals(CRON_EXP, ct.CronExpression);
        System.assertEquals(0, ct.TimesTriggered);
        test.stopTest();
    }
    
    public class RestMock implements HttpCalloutMock {
        public HTTPResponse respond(HTTPRequest req) {
            String json = '{"operation":"test"}';
            HTTPResponse res = new HTTPResponse();
            res.setHeader('accept','application/json');
            res.setBody(json);
            res.setStatusCode(200);
            return res;
        }
    }
}

 
Challenge Not yet complete... here's what's wrong:
Could not find your org in the Square Peg registry. Ensure that you have registered your connected app and tested the connection successfully.
Close errors
Please Help me i get the Error
//-----Handler Class------//
public class OppPrintCampaign{
    public static void InsertOpp(List<Opportunity> lstopp,Map<Id,Opportunity> mapIdToSatge){
        Set<Id> setOfAccId = New Set<Id>();
        List<Account> lstupdateacc = New List<Account>();
        List<Opportunity> lstofClosedLostOpp = New List<Opportunity>();
        Campaign objcamp = [Select Id,name from campaign where Id = '7012v000002KBp9'];
        for(Opportunity objopp:lstopp){
            if(objopp.accountId != null && objopp.stageName == 'Closed Lost' && objopp.StageName != mapIdToSatge.get(objopp.Id).stageName){
                setOfAccId.add(objopp.accountId);
            }
		}
        System.debug('-----setOfAccId-----'+setOfAccId);
         for(Opportunity objopp :[Select Id,Name ,Stagename ,AccountId from Opportunity where AccountId IN:setOfAccId]){        
             if(objopp.StageName != 'Closed Lost'){
                 lstofClosedLostOpp.add(objopp);
                 break;
             }
        }
        System.debug('----lstofClosedLostOpp----'+lstofClosedLostOpp.size());
        if(lstofClosedLostOpp.size() == 0){
          	 for(Account objacc:[Select Id,Name from Account where Id IN:setOfAccId]){
             	objacc.Assign_Engments__c = objcamp.name;
             	lstupdateacc.add(objacc);
             } 
        }
        
        System.debug('-----lstupdateacc-----'+lstupdateacc);
        update lstupdateacc;
	}
}

//------Test Class-----//
@isTest
public class OppPrintCampaignTest {
    static testmethod void method1(){
        
        Account objacc = new Account();
        objacc.name = 'Test';
        objacc.Rating = 'Cold';
        insert objacc;
        
        Opportunity objopp = New Opportunity();
        objopp.name = 'Test opp';
        objopp.CloseDate = System.today();
        objopp.AccountId = objacc.Id;
        objopp.StageName = 'Closed Lost';
        insert objopp;       
    }
}

 
can any one help me how to find average value of any filed per month for past 12 month in reort
Hii Every One,

i have a custom filed on Account Name(AssignCheckBox) ,write a Trigger on Opportunity when i update Stage of Opportunity is closed Lost and AccountId not Null and if Selected Account (Might be possible selected Account have more than one Opportunity) of all opportunity will be Closed Lost then Account CheckBox will be true
How to delete Dupliate Recode from flow match on email address
for exapmle if user enter details in search box and click on search button then if any name realed to account are avilable then ll the details of that Account
how to i impiment guide me
When New lead created with email address already present as a existing lead.Lead should get merged with the existing lead record 
Can anyone guide me
Hii Every one,
I am create a flow and add it into the Opportunity recode page but my flow not show on the Recode page .am i missing anything?
Bwlow code of my class we we not cover content documt link area
public class BookingTriggerHandler{
    public static void AddNotes(List<Booking__c> lstbook){
        
        List<ContentDocumentLink> insertlst = New List<ContentDocumentLink>();
        Map<id,Booking__c> mapIdtoBooking = New Map<Id,Booking__c>();
        for(Booking__c objbook :lstbook){
            if(objbook.opportunity__c != null){
                mapIdtoBooking.put(objbook.opportunity__c, objbook);
            }
        }
        system.debug('----mapIdtoBooking----'+mapIdtoBooking);
       
        for(ContentDocumentLink objlink:[SELECT Id,LinkedEntityId ,contentDocumentId FROM ContentDocumentLink where LinkedEntityId IN: mapIdtoBooking.keySet()]){
    		ContentDocumentLink obj = New ContentDocumentLink();
    		obj = objlink.clone(false,true);
    		obj.LinkedEntityId = mapIdtoBooking.get(objlink.LinkedEntityId).id;
    		insertlst.add(obj);            
		}
        system.debug('----insertlst----'+insertlst);
        
        if(!insertlst.isEmpty()){
           insert insertlst; 
        }
    }
}
@isTest
public class BookingTriggerHandlerTest{
    static testMethod void Testdata(){
        List<ContentDocumentLink> lstcon = New List<ContentDocumentLink>();
        List<Booking__c> lstbooking = New List<Booking__c>();
        Account objacc = New Account();
        objacc.name = 'Test';
        objacc.Type = 'Press';
        insert objacc;
        
        Opportunity objopp = new Opportunity();
        objopp.name ='Test';
        objopp.StageName ='Closed Won';
        objopp.CloseDate = system.today();
        objopp.Mode_of_Contact__c = 'Telephone';
        objopp.AccountId = objacc.Id;
        insert objopp;
        
        Booking__c objbook = New Booking__c();
        objbook.Name = 'Test';
        objbook.Opportunity__c = objopp.Id;
        lstbooking.add(objbook);
        insert lstbooking;
        List<contentNote> lstnote = New List<contentNote>();
        contentNote objnote = New contentNote();
        objnote.title = 'Test';
        lstnote.add(objnote);
        insert lstnote;
        
        List<ContentDocument> documents = [SELECT Id, Title, LatestPublishedVersionId FROM ContentDocument where Id =:objopp.Id]; 
        if(!documents.isEmpty()){
           ContentDocumentLink contentlink=new ContentDocumentLink();
		   contentlink.ShareType= 'C';
		   contentlink.LinkedEntityId = objopp.Id; 
		   contentlink.ContentDocumentId=documents[0].Id;
		   contentlink.Visibility = 'AllUsers'; 
           lstcon.add(contentlink); 
           System.assertEquals(documents.size(), 1);
        }		
		insert lstcon;
    }
}
We can't save this record because the “Opportunity Updates” process failed. Give your Salesforce admin these details. This error occurred when the flow tried to update records: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY: insufficient access rights on cross-reference id: a0G1U000003g8cd. You can look up ExceptionCode values in the SOAP API Developer Guide. Error ID: 1328276966-63986 (-2109863242)
//Controller Class
Please Any one Help
Pardot_Credential_Setting__c is Custom Setting
public class pardotActivityController{

        public static Pardot_Credential_Setting__c customSetting(){
            Pardot_Credential_Setting__c objSetting = Pardot_Credential_Setting__c.getValues('Pardot Access');
            if(objSetting != null && objSetting.Sync_disabled__c == false){
                return objSetting;
            }
            return null;
        }
        public static String authMethod(){
            
            Pardot_Credential_Setting__c objSetting = customSetting();

            if(objSetting != null){    <----Not Covering -------->
                String email = objSetting.Pardot_Email__c;
                String password = objSetting.Pardot_Password__c;
                String userKey = objSetting.User_Api_Key__c;

                HttpRequest req = new HttpRequest();
                req.setEndpoint( objSetting.Pardot_BaseUrl__c+'/api/login/version/4' );
                req.setMethod( 'POST' );
                req.setBody( 'email=' + email + '&password=' + password + '&user_key=' + userKey );

                HttpResponse res = new Http().send( req );

                System.debug('>>>>>>>>res'+ res );
                System.debug('>>>>>>>>>res.getStatus()'+ res.getStatus() );
                System.debug('>>>>>>res.getBody()'+ res.getBody() );

                String response = res.getBody();
                
                Integer startIdx;
                Integer endIdx;
                String apiKey;
                if(response.contains('<api_key>')){
                    startIdx = response.indexOf( '<api_key>' ) + 9;
                    endIdx = response.indexOf( '</api_key>' );
                    apiKey = response.substring( startIdx, endIdx );
                    System.debug( '>>>>>>>apiKey'+ apiKey );
                    return apiKey;
                }
            }
            
            return null;
        }
}

<------Test class------->
 static Testmethod void authMethodTest(){ 
        Pardot_Credential_Setting__c objSetting = New Pardot_Credential_Setting__c();
         objSetting.Name = 'Test';
         objSetting.Pardot_Email__c = 'abc@gmail.com';
         objSetting.User_Api_Key__c = '<api_key>';
         objSetting.Pardot_BaseUrl__c = 'https://pi.pardot.com/api/login/version/4';
         objSetting.Pardot_Password__c = 'test12';
         objSetting.Sync_disabled__c = false;
         insert objsetting;
        	Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
        	test.startTest();
        		pardotActivityController.authMethod();
        	test.stopTest();
    	}
 public class MockHttpResponseGenerator implements HttpCalloutMock{ //Http callout class for authmothod
            public HTTPResponse respond(HTTPRequest req){               
            String json=        '{'+
            '        "EMail": "leadsscotia@culliganwaterco.com",'+
            '        "Password": "<api_key>,'+
            '        "Userkey": "</api_key>",'+
            '}';
                   
            	System.assertEquals('https://pi.pardot.com/api/login/version/4', req.getEndpoint());
            	System.assertEquals('POST', req.getMethod());
                
                //make a fake responce
                 HttpResponse res = new HttpResponse();
                 res.setBody(json);
                 res.setStatusCode(200);
                 return res;
            }
        }

 
In Test class When we Insert Custom setting Value then It Does Not Cover But When we use seeAllData = true Then It Cover
use seeAllData =true is not Best Practice so How we Do
Please AnyOne help
Hii Every One My Test Class cover 75% covrrage But not coveer Execete Method Please help me
// Handler Class
public class PardotIdsSyncBatch implements Schedulable,Database.Batchable<sObject>,Database.Stateful
{
    String sObjectName = '' ;
    public PardotIdsSyncBatch(String sObjectName)
    {
        this.sObjectName = sObjectName ;
    }
    public void execute(SchedulableContext sc)
    {
        Database.executeBatch(new PardotIdsSyncBatch(sObjectName)) ;
    }
    public Database.QueryLocator start(Database.BatchableContext bc)
    {
        String query = 'select Id,pi__url__c,Pardot_Id__c  from '  + sObjectName + ' where pi__url__c != null AND Pardot_Id__c = null' ;
        return Database.getQueryLocator(query) ;
    }
    public void execute(Database.BatchableContext bc, List<sObject> scope)
    {
        PardotIdsSync sync1 = new PardotIdsSync() ;
        sync1.isAsync = true ;
        sync1.sync(scope) ;     
    }
    public void finish(Database.BatchableContext bc)
    {
        if(this.sObjectName == 'Contact')
            Database.executeBatch(new PardotIdsSyncBatch('Lead') ) ;
        else
            Database.executeBatch(new ActivitySyncBatch(0,null,0));        
    }
}

<========Test Classs=========>
@isTest
public class PardotIdsSyncBatchTest {

    static testMethod void TestData(){
        String CRON_EXP = '0 0 0 15 3 ? *';
        List<contact> lstcon = New List<Contact>(); 
        String sobjectname ='contact';
        Account objacc = New Account();
        objacc.Name ='Test';
        objacc.Type = 'Traveler';
        insert objacc;
        
        contact objcon = New contact();
        objcon.LastName = 'Data';
        objcon.Type__c = 'Traveler';
        objcon.pi__url__c = 'ww.google.com';
        objcon.Pardot_Id__c = 'F003';
        objcon.AccountId = objacc.Id;
        lstcon.add(objcon);
        
        test.startTest();
        	PardotIdsSyncBatch obj = New PardotIdsSyncBatch(sobjectname);
            Database.executeBatch(obj);
           
            String jobId = System.schedule('ScheduleApexClassTest',  CRON_EXP, obj);
            CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobId];
            System.assertEquals(CRON_EXP, ct.CronExpression);
            System.assertEquals(0, ct.TimesTriggered);

            
        test.stopTest();
    }
}
Can Anyone Help I am first Time To write test Class of Vf controller so I have no idea How to write test class

Thanks Help Me
public class CancelProposalProtection {
    String caseId;
    Attachment attSign;
    public String source;
    public Boolean isPreveiew{set;get;}
    public String ipAddress{set;get;}
    public Case objCase{set;get;}
    public Account objAcc{set;get;}
    public String dateToday{set;get;}
    public String Sign1{set;get;}
    public String Sign2{set;get;}
    public String Sign3{set;get;}
    public String climbSignature{set;get;}
    public String applicantSignature{set;get;}
    public String coApplicantSignature{set;get;}
    public List<Attachment> lstSignatures;
    
    public CancelProposalProtection(){
        isPreveiew = false;
        attSign = new Attachment();
        dateToday = System.today().format();
        caseId = ApexPages.currentPage().getParameters().get('id');
        source = ApexPages.currentPage().getParameters().get('source');
        if(source == 'email')
            isPreveiew = true;
        
        try{
            if(!String.isBlank(caseId)){
                objCase = [Select Id,AccountId,CaseNumber,Status,Type,Contact.Name,CO_APPLICANT_NAME__c,Certificate_Number__c,Date_Purchased__c,
                             Creditor__c,Life__c,Disability__c,Acc_Dis_IIII__c,Reason_For_Cancellation__c FROM Case WHERE Id =: caseId ORDER BY LastModifiedDate DESC Limit 1];
                objAcc = [Select Id,PersonMailingstreet,PersonMailingCountry,PersonMailingPostalCode,PersonMailingState,PersonMailingCity,
                              Name,IsPersonAccount FROM Account WHERE Id =: objCase.AccountId ORDER BY LastModifiedDate DESC Limit 1];
                for(Attachment attSign : [Select Id,Name FROM Attachment WHERE Name LIKE '%Signature%' AND ParentId =: caseId ORDER BY LastModifiedDate DESC LIMIT 3]){
                    if(attSign.Name == 'ApplicantSignature.png'){
                        Sign1 = attSign.Id;
                    }if(attSign.Name == 'CoApplicantSignature.png'){
                        Sign2 = attSign.Id;
                    }if(attSign.Name == 'ClimbSignature.png'){
                        Sign3 = attSign.Id;
                    }
                }
                System.debug('----Signatures'+Sign1+'-------------Sign2'+Sign2);
            }
        }catch(Exception e){
            System.debug('----Exception'+e.getMessage());
        }
    }
    
    public void saveForm(){
        try{
            if(source == 'email'){
                //Case cs = new Case(Id=caseId,Agreement_Status__c='Signed',IP_Address__c=ipAddress,Cancellation_Form='In Progress');
                objCase.Agreement_Status__c = 'Signed';
                objCase.IP_Address__c = ipAddress;
                objCase.Cancellation_Form__c = 'Received';
                update objCase;
                System.debug('---------Signed case'+objCase);
                //If Signature already exist then delete it
                delete[Select Id FROM Attachment WHERE Name LIKE '%Signature%' AND ParentId =: caseId];
                //Checking if the Attachment already exist then delete it
                delete[Select Id FROM Attachment WHERE Name = 'Cancel Proposal Protection.pdf' AND ParentId =: caseId];
            
                //Inserting the Signatures
                lstSignatures = new List<Attachment>();
                if(String.isNotBlank(applicantSignature)){
                    Attachment signature1 = new Attachment(ParentId=objCase.Id, Name='ApplicantSignature.png', ContentType='image/png', Body=EncodingUtil.base64Decode(applicantSignature));
                    lstSignatures.add(signature1);
                }
                if(String.isNotBlank(coApplicantSignature)){
                    Attachment signature2 = new Attachment(ParentId=objCase.Id, Name='CoApplicantSignature.png', ContentType='image/png', Body=EncodingUtil.base64Decode(coApplicantSignature));
                    lstSignatures.add(signature2);
                }
                if(String.isNotBlank(climbSignature)){
                    Attachment signature3 = new Attachment(ParentId=objCase.Id, Name='ClimbSignature.png', ContentType='image/png', Body=EncodingUtil.base64Decode(climbSignature));
                    lstSignatures.add(signature3);
                }
                System.debug('---List Attachments'+lstSignatures);
                if(!lstSignatures.isEmpty())
                    insert lstSignatures;
                    
                saveAgreement(caseId);
            }else if(source == 'preview'){
                objCase.Agreement_Status__c = 'Send';
                objCase.Cancellation_Form__c = 'In Progress';
                update objCase;
                System.debug('---------Signed case'+objCase);
            }  
        }catch(Exception e){
            objCase.Exception_Log__c = e.getMessage()+'\n\n'+ e.getLineNumber() + '\n\n'+ String.valueof(e.getCause()); 
            update objCase;
        }
    }

    
    //Saving the VF Page as an Attachment
    @Future(callout=true)
    private static void saveAgreement(String caseId){
        try{
            if(String.isNotBlank(caseId)){
                System.debug('------Inside SaveForm');
                PageReference pg = new PageReference('https://climbcredit--360dcex--c.visualforce.com/apex/CancelProposalProtectionPdf?id='+caseId);
                //PageReference pg = new PageReference(Label.Site_Url+'/CancelProposalProtectionPdf?id='+caseId);
                Attachment att = new Attachment();
                att.Name = 'Cancel Proposal Protection.pdf';
                att.Body = pg.getContent();
                att.ParentId = caseId;
                insert att;
                System.debug('--att--'+att);
            }
        }catch(Exception e){
            Case cs = new Case();
            cs.Id = caseId;
            cs.Exception_Log__c = e.getMessage()+'\n\n'+ e.getLineNumber() + '\n\n'+ String.valueof(e.getCause()); 
            update cs;
        }
    }
}
Hii Everyone,
I uses Community In our Production Org,I want to Remove Dependency of Community from Our Org. for Example what are the Profile,user,Role And What other Things are dependent on community
Please can AnyOne Explain 

Thanks Bablu
//-----Handler Class------//
public class OppPrintCampaign{
    public static void InsertOpp(List<Opportunity> lstopp,Map<Id,Opportunity> mapIdToSatge){
        Set<Id> setOfAccId = New Set<Id>();
        List<Account> lstupdateacc = New List<Account>();
        List<Opportunity> lstofClosedLostOpp = New List<Opportunity>();
        Campaign objcamp = [Select Id,name from campaign where Id = '7012v000002KBp9'];
        for(Opportunity objopp:lstopp){
            if(objopp.accountId != null && objopp.stageName == 'Closed Lost' && objopp.StageName != mapIdToSatge.get(objopp.Id).stageName){
                setOfAccId.add(objopp.accountId);
            }
		}
        System.debug('-----setOfAccId-----'+setOfAccId);
         for(Opportunity objopp :[Select Id,Name ,Stagename ,AccountId from Opportunity where AccountId IN:setOfAccId]){        
             if(objopp.StageName != 'Closed Lost'){
                 lstofClosedLostOpp.add(objopp);
                 break;
             }
        }
        System.debug('----lstofClosedLostOpp----'+lstofClosedLostOpp.size());
        if(lstofClosedLostOpp.size() == 0){
          	 for(Account objacc:[Select Id,Name from Account where Id IN:setOfAccId]){
             	objacc.Assign_Engments__c = objcamp.name;
             	lstupdateacc.add(objacc);
             } 
        }
        
        System.debug('-----lstupdateacc-----'+lstupdateacc);
        update lstupdateacc;
	}
}

//------Test Class-----//
@isTest
public class OppPrintCampaignTest {
    static testmethod void method1(){
        
        Account objacc = new Account();
        objacc.name = 'Test';
        objacc.Rating = 'Cold';
        insert objacc;
        
        Opportunity objopp = New Opportunity();
        objopp.name = 'Test opp';
        objopp.CloseDate = System.today();
        objopp.AccountId = objacc.Id;
        objopp.StageName = 'Closed Lost';
        insert objopp;       
    }
}

 

My requirment is - Junction Object (Junction1__c) record should get created when user create new record on "Account"/"Location" object

Data model -
Account Obj 
M_number__c field

Location object
M_number__c field


Junction1 Object
Account__c (M-D Rel with Account)
location__c (M-D rel with location)

When user create new recrod on Account Or Location object, it should automatically create new Rec on Junction Obj

Hi

I am not able to select the loop variable in the loop element.

To query the record collection varibale and store in single variable it is not popping up.

Am I missing some setup options??
What Could be the issue ?????Attaching screenshot

 Loop element

Hi, I am trying to write a batch class which will delete the opportunities whose CloseDate is last month and update checkbox in related account.

//Batch Class

global class DeleteOppsBatch implements Database.Batchable<SObject> {
    List<Account> newList = new List<Account>();
    global Database.QueryLocator start (Database.BatchableContext BC) {
        return Database.getQueryLocator([Select Id, DeletedOpp__c, (SELECT Id, CloseDate FROM Opportunities WHERE CloseDate = LAST_N_DAYS:30) FROM Account]);
    }
    global void execute(Database.BatchableContext BC, List<Account> accList) {
        for(Account acc : accList) {
            acc.DeletedOpp__c = TRUE;
            newList.add(acc);
        }
        //update newList;
    }
    global void finish(Database.BatchableContext BC) {
        System.debug('listsize:'+newList.size());
        delete newList;
    }
}

I didn't understand why this class is not working. Can someone help me achieve this functionality.

Thanks in advance.
can any one help me how to find average value of any filed per month for past 12 month in reort
Hii Every One,

i have a custom filed on Account Name(AssignCheckBox) ,write a Trigger on Opportunity when i update Stage of Opportunity is closed Lost and AccountId not Null and if Selected Account (Might be possible selected Account have more than one Opportunity) of all opportunity will be Closed Lost then Account CheckBox will be true
for exapmle if user enter details in search box and click on search button then if any name realed to account are avilable then ll the details of that Account
how to i impiment guide me
Hii Every one,
I am create a flow and add it into the Opportunity recode page but my flow not show on the Recode page .am i missing anything?
Bwlow code of my class we we not cover content documt link area
public class BookingTriggerHandler{
    public static void AddNotes(List<Booking__c> lstbook){
        
        List<ContentDocumentLink> insertlst = New List<ContentDocumentLink>();
        Map<id,Booking__c> mapIdtoBooking = New Map<Id,Booking__c>();
        for(Booking__c objbook :lstbook){
            if(objbook.opportunity__c != null){
                mapIdtoBooking.put(objbook.opportunity__c, objbook);
            }
        }
        system.debug('----mapIdtoBooking----'+mapIdtoBooking);
       
        for(ContentDocumentLink objlink:[SELECT Id,LinkedEntityId ,contentDocumentId FROM ContentDocumentLink where LinkedEntityId IN: mapIdtoBooking.keySet()]){
    		ContentDocumentLink obj = New ContentDocumentLink();
    		obj = objlink.clone(false,true);
    		obj.LinkedEntityId = mapIdtoBooking.get(objlink.LinkedEntityId).id;
    		insertlst.add(obj);            
		}
        system.debug('----insertlst----'+insertlst);
        
        if(!insertlst.isEmpty()){
           insert insertlst; 
        }
    }
}
@isTest
public class BookingTriggerHandlerTest{
    static testMethod void Testdata(){
        List<ContentDocumentLink> lstcon = New List<ContentDocumentLink>();
        List<Booking__c> lstbooking = New List<Booking__c>();
        Account objacc = New Account();
        objacc.name = 'Test';
        objacc.Type = 'Press';
        insert objacc;
        
        Opportunity objopp = new Opportunity();
        objopp.name ='Test';
        objopp.StageName ='Closed Won';
        objopp.CloseDate = system.today();
        objopp.Mode_of_Contact__c = 'Telephone';
        objopp.AccountId = objacc.Id;
        insert objopp;
        
        Booking__c objbook = New Booking__c();
        objbook.Name = 'Test';
        objbook.Opportunity__c = objopp.Id;
        lstbooking.add(objbook);
        insert lstbooking;
        List<contentNote> lstnote = New List<contentNote>();
        contentNote objnote = New contentNote();
        objnote.title = 'Test';
        lstnote.add(objnote);
        insert lstnote;
        
        List<ContentDocument> documents = [SELECT Id, Title, LatestPublishedVersionId FROM ContentDocument where Id =:objopp.Id]; 
        if(!documents.isEmpty()){
           ContentDocumentLink contentlink=new ContentDocumentLink();
		   contentlink.ShareType= 'C';
		   contentlink.LinkedEntityId = objopp.Id; 
		   contentlink.ContentDocumentId=documents[0].Id;
		   contentlink.Visibility = 'AllUsers'; 
           lstcon.add(contentlink); 
           System.assertEquals(documents.size(), 1);
        }		
		insert lstcon;
    }
}
We can't save this record because the “Opportunity Updates” process failed. Give your Salesforce admin these details. This error occurred when the flow tried to update records: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY: insufficient access rights on cross-reference id: a0G1U000003g8cd. You can look up ExceptionCode values in the SOAP API Developer Guide. Error ID: 1328276966-63986 (-2109863242)
//Controller Class
Please Any one Help
Pardot_Credential_Setting__c is Custom Setting
public class pardotActivityController{

        public static Pardot_Credential_Setting__c customSetting(){
            Pardot_Credential_Setting__c objSetting = Pardot_Credential_Setting__c.getValues('Pardot Access');
            if(objSetting != null && objSetting.Sync_disabled__c == false){
                return objSetting;
            }
            return null;
        }
        public static String authMethod(){
            
            Pardot_Credential_Setting__c objSetting = customSetting();

            if(objSetting != null){    <----Not Covering -------->
                String email = objSetting.Pardot_Email__c;
                String password = objSetting.Pardot_Password__c;
                String userKey = objSetting.User_Api_Key__c;

                HttpRequest req = new HttpRequest();
                req.setEndpoint( objSetting.Pardot_BaseUrl__c+'/api/login/version/4' );
                req.setMethod( 'POST' );
                req.setBody( 'email=' + email + '&password=' + password + '&user_key=' + userKey );

                HttpResponse res = new Http().send( req );

                System.debug('>>>>>>>>res'+ res );
                System.debug('>>>>>>>>>res.getStatus()'+ res.getStatus() );
                System.debug('>>>>>>res.getBody()'+ res.getBody() );

                String response = res.getBody();
                
                Integer startIdx;
                Integer endIdx;
                String apiKey;
                if(response.contains('<api_key>')){
                    startIdx = response.indexOf( '<api_key>' ) + 9;
                    endIdx = response.indexOf( '</api_key>' );
                    apiKey = response.substring( startIdx, endIdx );
                    System.debug( '>>>>>>>apiKey'+ apiKey );
                    return apiKey;
                }
            }
            
            return null;
        }
}

<------Test class------->
 static Testmethod void authMethodTest(){ 
        Pardot_Credential_Setting__c objSetting = New Pardot_Credential_Setting__c();
         objSetting.Name = 'Test';
         objSetting.Pardot_Email__c = 'abc@gmail.com';
         objSetting.User_Api_Key__c = '<api_key>';
         objSetting.Pardot_BaseUrl__c = 'https://pi.pardot.com/api/login/version/4';
         objSetting.Pardot_Password__c = 'test12';
         objSetting.Sync_disabled__c = false;
         insert objsetting;
        	Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
        	test.startTest();
        		pardotActivityController.authMethod();
        	test.stopTest();
    	}
 public class MockHttpResponseGenerator implements HttpCalloutMock{ //Http callout class for authmothod
            public HTTPResponse respond(HTTPRequest req){               
            String json=        '{'+
            '        "EMail": "leadsscotia@culliganwaterco.com",'+
            '        "Password": "<api_key>,'+
            '        "Userkey": "</api_key>",'+
            '}';
                   
            	System.assertEquals('https://pi.pardot.com/api/login/version/4', req.getEndpoint());
            	System.assertEquals('POST', req.getMethod());
                
                //make a fake responce
                 HttpResponse res = new HttpResponse();
                 res.setBody(json);
                 res.setStatusCode(200);
                 return res;
            }
        }

 
In Test class When we Insert Custom setting Value then It Does Not Cover But When we use seeAllData = true Then It Cover
use seeAllData =true is not Best Practice so How we Do
Please AnyOne help
public void getContactDetails(){
    List<Opportunity> opportunityList;
    this.Id = ApexPages.currentPage().getParameters().get('Id');
    opportunityList= [Select AccountId,ContactId From Opportunity Where Id =: this.Id ];
    List<Contact> contactList = new List<Contact>();
    List<Account> AccountList = new List<Account>();
    List<Contact> ContactAccountList = new List<Contact>();
    for(Opportunity oppObj:opportunityList) {
      contactList = [Select Name, Phone, Zip_code__c,Email From Contact Where Id =:oppObj.ContactId ];
      AccountList = [Select BillingStreet,BillingCity From Account Where Id =:oppObj.AccountId];
      for(Contact contactobj:contactList){
          contName = contactobj.Name;
          contPhone = contactobj.Phone;
          contZipcode = contactobj.Zip_code__c;
          contEmail = contactobj.Email;
        system.debug('name '+contName);
        system.debug('phone '+contPhone);
        system.debug('zip '+contZipcode); 
        system.debug('Email '+contEmail); 
        for(Account accountobj:AccountList){
          acctCity = accountobj.BillingStreet;
          acctStreet = accountobj.BillingCity;
        }
      }
      if(oppObj.ContactId == null){
        ContactAccountList =  [Select Name, Phone, Zip_code__c,Email From Contact Where AccountId =:oppObj.AccountId ];
        for(Contact contactaccountobj:contactaccountList){
          contName = contactaccountobj.Name;
          contPhone = contactaccountobj.Phone;
          contZipcode = contactaccountobj.Zip_code__c;
          contEmail = contactaccountobj.Email;
          system.debug('name '+contName);
          system.debug('phone '+contPhone);
          system.debug('zip '+contZipcode); 
          system.debug('Email '+contEmail); 
          for(Account accountobj:AccountList){
            acctCity = accountobj.BillingStreet;
            acctStreet = accountobj.BillingCity;
          }
        }
      }
    }
}