• Dagny Fernandes
  • NEWBIE
  • 69 Points
  • Member since 2014
  • Developer


  • Chatter
    Feed
  • 1
    Best Answers
  • 2
    Likes Received
  • 0
    Likes Given
  • 14
    Questions
  • 19
    Replies
I have set a Custom Field ('Priority_Flags__c') on the Case object, to represent priority flags as follows:
 
IMAGE( 
CASE( Priority, 
"Low", "/img/samples/flag_green.gif", 
"Medium", "/img/samples/flag_yellow.gif", 
"High", "/img/samples/flag_red.gif", 
"Critical", "/img/samples/flag_red.gif", 
"/s.gif"), 
"Priority Flag")
I included this custom field to be merged in a VisualForce Email Template as follows:
<messaging:emailTemplate subject="[Assignment] Case #{!relatedTo.CaseNumber}: {!relatedTo.Subject}" recipientType="User" relatedToType="Case">
    <messaging:htmlEmailBody >
    <html>
    <style type="text/css">
            body {font-family: arial; size: 12pt;}
        </style>
    <body>
        The following case was assigned to <b>{!relatedTo.Owner.Name}</b>:
        <br />------------------------
        <br />• Case #: {!relatedTo.CaseNumber}
        <br />• Account: <apex:outputLink value="https://my.salesforce.com/{!relatedTo.Account}"> {!relatedTo.Account.Name}</apex:outputLink>
        <br />• Contact Name: {!relatedTo.Contact.Name}
        <br />• Case status: {!relatedTo.Status}
        <br />• Priority: {!relatedTo.Priority_Flags__c} {!relatedTo.Priority}
        <br />• Link: https://my.salesforce.com/{!relatedTo.Id} 
        <br />------------------------
        <br />        
</body>
</html>
</messaging:htmlEmailBody>   
</messaging:emailTemplate>
It seems that the rendered Merged Field is not the image as expected, but the img HTML statement:

User-added image

Is there a way to make this work, and render the IMAGE in the VisualForce Email Template? 
I am facing below error: "There's a problem with this country, even though it may appear correct. Please select a country/territory from the list of valid countries."

Senario: I have enalbled te Country/State Picklist and created the Lead record, all the other records are working there is one record with Coutry United States with Code US this is also working when i update Custom filed "Lead Parent" I am getting the above error.

Need urgent help 
 
I Have a Query Which is giveing the below error. below is the sample code and error.
Below veriable are the date values come from VF page which is used in the Query.
Type is date field:
oppStart.Date_Marked_As_Settled1__c
oppEnd.Date_Marked_As_Settled1__c

strQuery = 'select Date_Marked_As_Settled__c,Date_Marked_As_Settled1__c,Opportunity.Name ,Product2.ProductCode,TotalPrice from ';
strQuery = strQuery + 'OpportunityLineItem where Product2.ProductCode!=\'SHIPPING\' and CreatedDate >= '+oppStart.Date_Marked_As_Settled1__c+' and CreatedDate <= '+oppEnd.Date_Marked_As_Settled1__c+' and Mark_As_Settled__c=true order by createdDate desc';
getOppLineList();

public void getOppLineList(){

for(OpportunityLineItem c : Database.query(strQuery)){ //Error in this line

}

Error : System.QueryException: line 1:497 no viable alternative at character ' '
 
Hi All,

I am not able cover single line of code for the batch class am I makeing anything wrong and the batch class is logic is based on Created Date.

Batch Class:
global class BatchClassToCloseAdSalesOpportunitys implements Database.Batchable<sObject> , Schedulable {
	
	private String OppClosedWon		= Constant_PicklistVariables.OPP_CLOSED_WON;
    private String OppClosedLost	= Constant_PicklistVariables.OPP_CLOSED_LOST;
    //Opportunity Ad Sales RecordType ID
    ID AdSalesRecordTypeId 			= Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('AD-Sales').getRecordTypeId();
    private String query 			= 'Select Id,Name,RecordTypeId,StageName,CreatedDate,Extend__c from Opportunity WHERE RecordTypeId =: AdSalesRecordTypeId AND ( StageName !=: OppClosedWon OR StageName !=: OppClosedLost ) ';
   	
	global BatchClassToCloseAdSalesOpportunitys(){
    	// Batch Constructor
    }
    
    global void execute(SchedulableContext sc) {
    	System.debug('DagnyQuery==>'+query);
        Database.executebatch(this); 
    }
    
    // Start Method
    global Database.QueryLocator start(Database.BatchableContext BC){
    	System.debug('Dagny==>Query==>'+query);
    	return Database.getQueryLocator(query);
    }
  
   	// Execute Logic
   	global void execute(Database.BatchableContext BC, List<sObject>scope){
          Set<Id> oppIdSet						= new Set<Id>();
          list<Opportunity> opportunityList = (list<Opportunity>) scope;
          List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
          map<Id,Integer> campMapList	= new map<Id,Integer>();
          String baseUrl = System.URL.getSalesforceBaseUrl().toExternalForm();

          if(opportunityList.size() > 0){
          	 for(Opportunity oppId: opportunityList){
          	 	oppIdSet.add(oppId.Id);	          	 	
          	 }
          	 
          	 for(ADs_Campaign__c camp: [SELECT Id, Opportunity__c FROM ADs_Campaign__c WHERE Opportunity__c IN: oppIdSet]){
          	 	if(camp.Opportunity__c != null){
	          	 	if(campMapList.containsKey(camp.Opportunity__c)){
	          	 		campMapList.put(camp.Opportunity__c,campMapList.get(camp.Opportunity__c)+1 );
	          	 	}else{
	          	 		campMapList.put(camp.Opportunity__c, 1);
	          	 	}
          	 	}
          	 }
          	 
             for(Opportunity oppRec: opportunityList){
             	DateTime sT 			= oppRec.CreatedDate;
				Date sDate 				= date.newinstance(sT.year(), sT.month(), sT.day());
             	Date startDate 			= sDate;
				Date dueDate 			= System.today();
				Integer numberDaysDue 	= startDate.daysBetween(dueDate);
				Integer timeStamp		= Integer.valueOf(System.Label.OpportunityCloseTimeStamp);
				
				if(oppRec.Extend__c == true){
					if(numberDaysDue >= timeStamp+5){
						if( campMapList.get(oppRec.Id) != null && campMapList.get(oppRec.Id) > 0 ){
							oppRec.StageName = Constant_PicklistVariables.OPP_CLOSED_WON;
						}else{
							oppRec.StageName = Constant_PicklistVariables.OPP_CLOSED_LOST;
						}
						
					}
				}else{
					if(numberDaysDue >= timeStamp){
						if( campMapList.get(oppRec.Id) != null && campMapList.get(oppRec.Id) > 0){
							oppRec.StageName = Constant_PicklistVariables.OPP_CLOSED_WON;
						}else{
							oppRec.StageName = Constant_PicklistVariables.OPP_CLOSED_LOST;
						}
					}else{
						if(numberDaysDue >= timeStamp-2){
							messaging.singleEmailMessage mail = new messaging.singleEmailMessage();
     						mail.ToAddresses = new string[]{ oppRec.CreatedBy.Email};
							// mail.setReplyTo('');   // <-----------------------------------Set the ReplyTo---
						    mail.setSubject('Opprtunity Closur Notification'+oppRec.Name);
						    mail.setUseSignature(false);
							string htmlBody = '<div style="border:2px solid green; border-radius:15px;"><p>Hi,</p><p><span style="color:brown; font-weight:bolder;">'+oppRec.Owner.Name+'</span> ,</p>'
						    +'<p>The Opportunity '+oppRec.Name+'aginst the seller '+oppRec.Account+'</br>!</p> will be closed with in 2 days </br>Please confirm, If you want to extend the opportunity closure For 5 days more </p>'
						    +'<p>Please click on the below link and update the value of "Request For Closure Extension" to checked </br></p>'
						    +'<p>'+baseUrl+'/'+oppRec.Id+' </p></div>';
						
						    mail.setHtmlBody(htmlBody);
						    mails.add(mail);
    					    
						}
					}
					
				}
             }
             System.debug('Dagny==>OpportunityList=>'+opportunityList);
             update opportunityList;
             if(mails.size() > 0 ){
             	Messaging.sendEmail(mails);
             }
          }   
 
   	}
 
   	global void finish(Database.BatchableContext BC){
        // Logic to be Executed at finish
   	}
   
}

Test Class:
@isTest(seeAllData=false)
public class BatachClassToCloseAdSalesOppty_Test {
	Static User testUser;
    Static Opportunity testOpp;
    Static Opportunity testOpp2;
    static ADs_Campaign__c adsCampaign;
    static ADs_Campaign__c adsCampaign2;
    public BatachClassToCloseAdSalesOppty_Test(){
        
    }
    
    Static void init(){
        testUser 	= InitialTestData2.createUserRecord();
        insert testUser;  
             
        
        DateTime oppCreatDate = System.now() - 15;
        system.debug('oppCreatDate'+oppCreatDate);
        String OppDate = ''+oppCreatDate.formatGMT('yyyy-MM-dd\'T\'HH:mm:ss.SSS\'Z\''+'');
        String oppCreDateStr = String.valueOf(OppDate);
        system.debug('oppCreDateStr'+oppCreDateStr);
        String oppJSON = '{"attributes":{"type":"Opportunity","url":"/services/data/v25.0/sobjects/Opportunity/006N0000005t0cd"},"Id":"006N0000005t0cd","CreatedDate":"'+oppCreDateStr+'"}';
        testOpp = (Opportunity)JSON.deserialize(oppJSON,Opportunity.class);
        
        /*DateTime oppCreatDate2 = System.now() - 13;
        String OppDate2 = ''+oppCreatDate2.formatGMT('yyyy-MM-dd\'T\'HH:mm:ss.SSS\'Z\''+'');
        String oppCreDateStr2 = String.valueOf(OppDate2);
        String oppJSON2 = '{"attributes":{"type":"Opportunity","url":"/services/data/v25.0/sobjects/Opportunity/006N0000006KDab"},"Id":"006N0000006KDab","CreatedDate":"'+oppCreDateStr2+'"}';
        testOpp2 = (Opportunity)JSON.deserialize(oppJSON2,Opportunity.class);*/
        
        system.debug('oppCreDateStr'+testOpp.Id);
        adsCampaign = InitialTestData2.createAdsCampaign(testOpp.Id);
        //insert adsCampaign;
        
        /*adsCampaign2 = InitialTestData2.createAdsCampaign(testOpp2.Id);
        insert adsCampaign2;*/
        
        
    }
    
    //this method is for the Opportunity Batch auto close status update 
    private static testMethod void batchTest (){
    	test.startTest();
        init();
        Database.QueryLocator QueryLoc;
        Database.BatchableContext BatchCont;
        System.runAs(testUser){
            List<Opportunity> oppList = new List<Opportunity>();
            oppList.add(testOpp);
            //oppList.add(testOpp2);
            
            system.debug('List->'+oppList);
            BatchClassToCloseAdSalesOpportunitys batch12 =new BatchClassToCloseAdSalesOpportunitys();
            ID batchprocessid = Database.executeBatch(batch12,200);
            
            QueryLoc= batch12.start(BatchCont);
            System.debug(BatchCont);
            Database.QueryLocatorIterator QueryIterate = QueryLoc.iterator();
            while (QueryIterate.hasNext()){
                 Opportunity objQueue = (Opportunity)QueryIterate.next();           
                 System.debug(objQueue);
                 oppList.add(objQueue);
            }       
            
            batch12.execute(BatchCont, oppList);
            batch12.finish(BatchCont); 
        }
        Test.stopTest();
    }
}

Need Help ASAP,

Thank you in advance.
Hi all

I have a some partner users where i have to create report and give acces to the partner user to see the report.

->I have created some sample reports and created the folder and given the acces to the parther user to the report folder.
->I have made Standard Report Visibility true in the sharing setting.
->In profile level i have given acces to the report. add the tab to the partner login 

iam able to see the report tab when i logged in to the partner user and when i click on report tab i am not able to see the folder also which was shared with the partner user...

Need help asap.
Thank u in advance.
 
Hi all,
I have an issue. i have Opportunity with inline pages the issue is when i click the opportunity record ad open the record the detail page opens and directly go to inline VF page at the bottom so that every time i need to scroll up to see the opportunity detailes. so i dont want to go to the bottom of the page when i click on the opportunity record it should not move to inline page... 

Need help asap.
Thank u in advance.
Hi Friends,

I have a requirement to Upload List of attachments from VF page in one click but iam getting a view state error on uploading a bulk data. so I tried useing "Remoting" even in remoting there are some limitation in passing the parameters and size. Iam passing the list of attachement each Attacmnent may consists of MB's of file. The challengeing part is there is a option to upload 50 attachments in one go also, there are 5 data points in which each data point may have 10 attachment to upload. based on the values the page rereders, the below is the image of the VF page.
Need Help Asap.
Thanks in Advance.

User-added image

Thanks in advance...
Hi, 

i have custom lookup reseller name to Reseller object in Quote, Reseller is ajunction object to account and Opportunty. In the Quote this lookup has a filter to select only resellars record belongs to opportunity.

This filter is working for editing the record but it is not working while creating the new record. below is the screenshot of filer
 Need Help plz asap.
Thanks in advance.

User-added image
I have a REST service but i am not able to cover this class. 
Below is my code, need help ASAP.

Thanks You in advance.
@RestResource(urlMapping='/AttachPDF/*')
global class ServiceInvoiceRedirectController {
	
	@HttpGet
        global static void AttachPDFtoRecordREST() {
        	List<Id> accId = new List<Id>();
        	List<String> emailList = new List<String>();
            RestRequest req = RestContext.request;
            id recordId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);

            PageReference pdfPage = new PageReference('/apex/ServiceInvoicePDF?Id='+recordId);
            pdfPage.getParameters().put('id',recordId);
            Blob pdf = pdfPage.getContentAsPdf(); //!Test.isRunningTest() ? pdfPage.getContentAsPdf() : Blob.ValueOf('dummy text');
            
			//List of accoutn Id's of related project
            for(Account_Project_Junction__c accPrjJunRec: [SELECT Id,Project__c,Account__c From Account_Project_Junction__c WHERE Project__c =: recordId]){
            	accId.add(accPrjJunRec.Account__c);
            }
            
            //List of email id's of the selected account's
            for(Contact conRec: [SELECT Id,AccountID,Email,Is_Primary_Contact__c From Contact where AccountID IN: accId AND Is_Primary_Contact__c = true]){
            	if(conRec.Email != null){
            		emailList.add(conRec.Email);
            	}
            }
            
            Project__c prjRec = [Select Id,Name from Project__c where Id =: recordId];
            //Insert Invoice record for related project
	        Invoice__c invoRec = new Invoice__c();
	        invoRec.RecordTypeId = Constants_PicklistVariables.serInvoice; 
	        invoRec.Project__c = recordId;
	        
	        try{
	        insert invoRec;
	        }catch(Exception e){
	            System.debug('Invoice=Exception-->'+e);
	        }
	        System.debug('Invoice=invoRec.id-->'+invoRec);
	        
	        //Insert Attacment to the invoice        
	        Attachment a = New Attachment();
	        a.body = pdf;
	        a.parentID = invoRec.id;
	        a.ContentType  = 'application/pdf';
	        a.Name = 'SER-INV-'+invoRec.id+'.pdf';
	        try{
	        insert a;
	        }catch(Exception e){
	            System.debug('Attachment=Exception-->'+e);
	        }
	        
	        //Create the email attachment
	    	Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
	    	efa.setFileName('SER-INV-'+invoRec.id+'.pdf');//Pleace ad pdf name from contact name project and oppty concatinate 
		    efa.setContentType('application/pdf');
		    efa.setBody(pdf);
		    
		    // Create the Singal Email Message
		    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
		    email.setSubject('Service Invoice Notification');
		    String[] CCEmails = emailList;
			email.setToAddresses(CCEmails);
		    //email.setToAddresses(new String[] { 'developer@extentor.com' });//add Contact email id
		    email.setPlainTextBody( 'Dear:Sir/Madam <br/> Please Find Attachment your financial report Attached with this email.');
		    email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
		    
		    // Sends the email
		    Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
            
        }

        // call this method from your Batch Apex
        global static void attachPdfToRecord( Id recordId, String sessionId )
        {
        	System.debug('recordId==>'+recordId);
        	System.debug('sessionId==>'+sessionId);
        	System.debug('Iam in REST API Call method');
            HttpRequest req = new HttpRequest();
            req.setEndpoint(URL.getSalesforceBaseUrl().toExternalForm()+'/services/apexrest/AttachPDF/'+recordId);
            req.setMethod('GET');
            req.setHeader('Authorization', 'OAuth ' + sessionId);

            Http http = new Http();
            HttpResponse response = http.send(req);    
        }
        
}

Test class:
@isTest(seeAllData=false)
global class Test_ServiceInvoiceRedirectController{
   
    static testMethod void testDoGet() {
		Account acc= InitialTestData.createAccount('Raj');
        insert acc;
        
        Contact contact1=InitialTestData.createContact(acc.id,'Sen','raj@gmail.com');
        insert contact1;
        
        Opportunity_Deal__c oppdeal=InitialTestData.createOpportunityDeal('Opp1',acc.id,contact1.id,false,'Quote');
        insert oppdeal;
        
        Project__c project1=InitialTestData.createPlotProject('Pro',acc.id,'Submitted',oppdeal.id);
        insert project1;
        
    RestRequest req = new RestRequest(); 
    RestResponse res = new RestResponse();

    // pass the req and resp objects to the method     
    req.requestURI = URL.getSalesforceBaseUrl().toExternalForm()+'/services/apexrest/AttachPDF/'+project1.Id;  
    req.httpMethod = 'GET';

    ServiceInvoiceRedirectController.attachPdfToRecord results = ServiceInvoiceRedirectController.AttachPDFtoRecordREST(req,res);

    System.assertEquals('true', results.success);
    System.assertEquals(10, results.records.size());
    System.assertEquals('Query executed successfully.', results.message);

  }
	
}
Hi Frends,
Iam getting the bellow error:
TicketStatus: execution of AfterUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id a0AO000000Ak6Y6MAJ; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, This profile cannot edit this escalation the tickets are raised: [] Class.TicketStatusHandler.onAfterUpdate: line 229, column 1 Trigger.TicketStatus: line 37, column 1

There is requirement like i have a parent record and child records, the child record as a self lookup relation to parent record. 
Here the parent record is escaltion and child record is ticket.
The above error is comeing while editing the ticket because There is a validation on the parent record(Escaltion) based on profile. the validation is  
Ex: IF Ticket is raised for the respaective Escalation then the BA profile cannot edit the Escaltion. But can edit the Ticket, based on ticket value from trigger escaltion is updated, here it comes the above mentioned error.

How can i overcome from this problem need help.

Thanks in advance,
Hi Frends,

Iam getting the below error in trigger after Update 
TicketStatus: execution of AfterUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id a0AO000000Ak6Y6MAJ; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, TicketStatus: execution of AfterUpdate caused by: System.DmlException: Update failed. First exception on row 0; first error: MISSING_ARGUMENT, Id not specified in an update call: [] Class.TicketStatusHandler.onAfterUpdate:

this error is in the line number 65 DML operation update. I added the System debug statement in line number 64 and iam getting the ID of the record. Am i missing anything in the below code. need help ASAP 

Thanks in advance.
 
//-- After Update
	 
	 public void onAfterUpdate(final List<Escalation__c> newObjects,final List<Escalation__c> oldObjects,final Map<Id, Escalation__c> newObjectsMap,final Map<Id, Escalation__c> oldObjectsMap){
	 List<Escalation__Share> EscalationShareList 			= new List<Escalation__Share>();
	 List<Escalation__Share> EscalationShareListToDelete 	= new List<Escalation__Share>();
	 List<Followers__c> FollowersList 						= new List<Followers__c>();
	 List<Escalation__c> ParentEscaUpdate 					= new List<Escalation__c>();
	 Map<Id,Id> toDeleteShareMap 							= new Map<Id,Id>();
	 map<Id, Escalation__c> parentEsca 						= new map<Id, Escalation__c>();
	 Escalation__c PrarentRec = new Escalation__c();
	 
		 for(Escalation__c escaParent: [SELECT Id,Name,Sys_Ticket_Count__c,RecordTypeId FROM Escalation__c WHERE RecordTypeId =: Constants_PicklistVariables.ESCALATION_RECORDTYPE_ID]){
		 		parentEsca.put(escaParent.Id, escaParent);
		 }
	 	
		 for(Escalation__c esca: newObjects){
		 	if(esca.RecordTypeId == Constants_PicklistVariables.TICKET_RECORDTYPE_ID && esca.Assigned_To__c != null && esca.Assigned_to__c != oldObjectsMap.get(esca.Id).Assigned_To__c){
	            Escalation__Share expShare = new Escalation__Share(
								              ParentId 		= esca.Id,
								              UserOrGroupId = esca.Assigned_To__c,
								              rowCause 		= Schema.Escalation__Share.rowCause.AssignedTo__c,
								              accessLevel 	= 'Edit'
								            );
	            
	            //Adding Followers
	            Followers__c follRec = new Followers__c();
	            follRec.Follower_Name__c = esca.Assigned_To__c;
	            follRec.Ticket__c 		 = esca.Id;
	            
	            FollowersList.add(follRec);
	            EscalationShareList.add(expShare);
	            toDeleteShareMap.put(esca.Id, oldObjectsMap.get(esca.Id).Assigned_To__c);
	            System.debug('toDeleteShareMap'+toDeleteShareMap);
		 	}
		 	if(esca.Escalation__c != null)
		 	PrarentRec = parentEsca.get(esca.Escalation__c);
		 	
		 }
		 
		 if(PrarentRec != null){
		 	List<Escalation__c> TicketRec = [SELECT Id,Name,RecordTypeId,Escalation__c,Category__c,Ticket_Status_Overall_Ops__c,Ticket_Status_Overall_Finance__c,Ticket_Status_Overall_Mar__c,Ticket_Status_Overall_Service__c,Ticket_Status_Overall_Tech__c FROM Escalation__c WHERE RecordTypeId =: Constants_PicklistVariables.TICKET_RECORDTYPE_ID AND Escalation__c =: PrarentRec.Id];
		 	Integer NonClosedTicketCounter = 0;
		 	System.debug('TicketRec'+TicketRec);
		 	for(Escalation__c tickRec: TicketRec){
		 		if(tickRec.Category__c == null)
		 			NonClosedTicketCounter = NonClosedTicketCounter + 1;
		 		if(tickRec.Category__c == 'Ops' && tickRec.Ticket_Status_Overall_Ops__c != 'Closed')
		 			NonClosedTicketCounter = NonClosedTicketCounter + 1;
		 		if(tickRec.Category__c == 'Finance' && tickRec.Ticket_Status_Overall_Finance__c != 'Closed')
		 			NonClosedTicketCounter = NonClosedTicketCounter + 1;
		 		if(tickRec.Category__c == 'Leads (Marketing)' && tickRec.Ticket_Status_Overall_Mar__c != 'Closed')
		 			NonClosedTicketCounter = NonClosedTicketCounter + 1;
		 		if(tickRec.Category__c == 'Service' && tickRec.Ticket_Status_Overall_Service__c != 'Closed')
		 			NonClosedTicketCounter = NonClosedTicketCounter + 1;
		 		if(tickRec.Category__c == 'Tech' && tickRec.Ticket_Status_Overall_Tech__c != 'Closed')
		 			NonClosedTicketCounter = NonClosedTicketCounter + 1;
		 	}
		 	System.Debug('NonClosedTicketCounter'+NonClosedTicketCounter);
		 	if(NonClosedTicketCounter == 0){
			 	/*Escalation__c parentRecord = parentEsca.get(PrarentRec.Id) ;
			 	parentRecord.Escalation_Status__c = 'Closed';
			 	update parentRecord;*/
			 	PrarentRec.Escalation_Status__c = 'Closed';
			 	System.debug('PrarentRec'+PrarentRec);
			 	update PrarentRec;
		 	}
		 }
		 
		 for(Escalation__Share expShare :[SELECT Id, ParentId, rowCause, UserOrGroupId FROM Escalation__Share WHERE ParentId in :toDeleteShareMap.keySet()]){
	        if(toDeleteShareMap.get(expShare.ParentId) != null && toDeleteShareMap.get(expShare.ParentId) == expShare.UserOrGroupId){
	            EscalationShareListToDelete.add(expShare);
	        }
	     }
	    
	     try{
		 	insert EscalationShareList;
		 	insert FollowersList;
		 	delete EscalationShareListToDelete;
		 }catch(Exception e){
		 	
		 }
		 
	 }

 
I have override the standerd Edit button with VF page this VF page will redirect to other VF page based on the record type, the redirection is working properly but i want to give an error messsage on this this page.
In the below class line number 26 error message is not diplaying if i add "return null" it is redirectiong to standerd page if i remove this line it stay in the page and showes "Attempt to De-reference null object" error. Need help ASAP

Thanks in advance

here c.Sys_Ticket_Count__c is grater than 0 

Apex Class:
public with sharing class escaEditBtnController {
	
	public escaEditBtnController(ApexPages.StandardController controller) {
        this.controller = controller;
    }
    
    public PageReference getredirect() {

        Escalation__c c = [Select id, recordtypeid,Sys_Ticket_Count__c From Escalation__c Where Id = :ApexPages.currentPage().getParameters().get('id')];

        PageReference newPage;

        if (c.recordtypeid == Constants_PicklistVariables.TICKET_RECORDTYPE_ID) {
            newPage = new PageReference('/apex/TicketEdit?retURL=%2F'+c.id);
			newPage.getParameters().put('id', c.id);
	        newPage.getParameters().put('editMode', 'true');
	        
        } else {
        	if(c.Sys_Ticket_Count__c <= 0 ){
        		newPage = new PageReference('/apex/EscalationEdit?retURL=%2F'+c.id);
	            newPage.getParameters().put('id', c.id);
	            newPage.getParameters().put('editMode', 'true');
	            newPage.getParameters().put('nooverride', '1');
        	}else{
        		System.debug('c.Sys_Ticket_Count__c'+c.Sys_Ticket_Count__c);
        		ApexPages.addmessage(new ApexPages.message(ApexPages.Severity.Error,'Ticket has been rised for this escalation you do not have access to edit this Escalation, Please contact the system admin'));
				return null; 
        	}
            
        }
		
        return newPage.setRedirect(true);
    }

    private final ApexPages.StandardController controller;
}
VF page:
<apex:page standardController="Escalation__c" extensions="escaEditBtnController"  
    action="{!nullValue(redirect.url, urlFor($Action.Escalation__c.Edit, Escalation__c.id, null, true))}">
<apex:pageMessages />
</apex:page>


 
Iam getting the null pointer exception while useing the wrapper class my other wrapper class code are working fine not able to understand what went wrrong in this code. need Help ASAP

public list<WrapperClass> wrapper_variable    {get;set;}
Account_Project_Junction__c projRec             = [SELECT Id,Name,Project__c,Project__r.Name from Account_Project_Junction__c WHERE Id = 'a00O000000KWbzsIAD'];
Escalation_Project_Junction__c EscaProjJunRec     = new Escalation_Project_Junction__c();
EscaProjJunRec.Project__c                         = projRec.Id;
EscaProjJunRec.Project_Name__c                     = projRec.Project__r.Name;
wrapper_variable.add(new WrapperClass(EscaProjJunRec));
//wrapper class
public class WrapperClass{
    public Escalation_Project_Junction__c projectEsca_wrapper{get;set;}
    
    public WrapperClass(Escalation_Project_Junction__c EPJ){
        projectEsca_wrapper = EPJ;
    }           
}


Error:
05:29:16:077 FATAL_ERROR System.NullPointerException: Attempt to de-reference a null object
this error is for the line
wrapper_variable.add(new WrapperClass(EscaProjJunRec));
Requirement:- is Generate the PDF and and send email notification and insert new related record to keep track of the pdf and attachment to the record.
I have a REST service but i am not able to cover this class. 
Below is my code, need help ASAP.

Thanks You in advance.
@RestResource(urlMapping='/AttachPDF/*')
global class ServiceInvoiceRedirectController {
	
	@HttpGet
        global static void AttachPDFtoRecordREST() {
        	List<Id> accId = new List<Id>();
        	List<String> emailList = new List<String>();
            RestRequest req = RestContext.request;
            id recordId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);

            PageReference pdfPage = new PageReference('/apex/ServiceInvoicePDF?Id='+recordId);
            pdfPage.getParameters().put('id',recordId);
            Blob pdf = pdfPage.getContentAsPdf(); //!Test.isRunningTest() ? pdfPage.getContentAsPdf() : Blob.ValueOf('dummy text');
            
			//List of accoutn Id's of related project
            for(Account_Project_Junction__c accPrjJunRec: [SELECT Id,Project__c,Account__c From Account_Project_Junction__c WHERE Project__c =: recordId]){
            	accId.add(accPrjJunRec.Account__c);
            }
            
            //List of email id's of the selected account's
            for(Contact conRec: [SELECT Id,AccountID,Email,Is_Primary_Contact__c From Contact where AccountID IN: accId AND Is_Primary_Contact__c = true]){
            	if(conRec.Email != null){
            		emailList.add(conRec.Email);
            	}
            }
            
            Project__c prjRec = [Select Id,Name from Project__c where Id =: recordId];
            //Insert Invoice record for related project
	        Invoice__c invoRec = new Invoice__c();
	        invoRec.RecordTypeId = Constants_PicklistVariables.serInvoice; 
	        invoRec.Project__c = recordId;
	        
	        try{
	        insert invoRec;
	        }catch(Exception e){
	            System.debug('Invoice=Exception-->'+e);
	        }
	        System.debug('Invoice=invoRec.id-->'+invoRec);
	        
	        //Insert Attacment to the invoice        
	        Attachment a = New Attachment();
	        a.body = pdf;
	        a.parentID = invoRec.id;
	        a.ContentType  = 'application/pdf';
	        a.Name = 'SER-INV-'+invoRec.id+'.pdf';
	        try{
	        insert a;
	        }catch(Exception e){
	            System.debug('Attachment=Exception-->'+e);
	        }
	        
	        //Create the email attachment
	    	Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
	    	efa.setFileName('SER-INV-'+invoRec.id+'.pdf');//Pleace ad pdf name from contact name project and oppty concatinate 
		    efa.setContentType('application/pdf');
		    efa.setBody(pdf);
		    
		    // Create the Singal Email Message
		    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
		    email.setSubject('Service Invoice Notification');
		    String[] CCEmails = emailList;
			email.setToAddresses(CCEmails);
		    //email.setToAddresses(new String[] { 'developer@extentor.com' });//add Contact email id
		    email.setPlainTextBody( 'Dear:Sir/Madam <br/> Please Find Attachment your financial report Attached with this email.');
		    email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
		    
		    // Sends the email
		    Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
            
        }

        // call this method from your Batch Apex
        global static void attachPdfToRecord( Id recordId, String sessionId )
        {
        	System.debug('recordId==>'+recordId);
        	System.debug('sessionId==>'+sessionId);
        	System.debug('Iam in REST API Call method');
            HttpRequest req = new HttpRequest();
            req.setEndpoint(URL.getSalesforceBaseUrl().toExternalForm()+'/services/apexrest/AttachPDF/'+recordId);
            req.setMethod('GET');
            req.setHeader('Authorization', 'OAuth ' + sessionId);

            Http http = new Http();
            HttpResponse response = http.send(req);    
        }
        
}

Test class:
@isTest(seeAllData=false)
global class Test_ServiceInvoiceRedirectController{
   
    static testMethod void testDoGet() {
		Account acc= InitialTestData.createAccount('Raj');
        insert acc;
        
        Contact contact1=InitialTestData.createContact(acc.id,'Sen','raj@gmail.com');
        insert contact1;
        
        Opportunity_Deal__c oppdeal=InitialTestData.createOpportunityDeal('Opp1',acc.id,contact1.id,false,'Quote');
        insert oppdeal;
        
        Project__c project1=InitialTestData.createPlotProject('Pro',acc.id,'Submitted',oppdeal.id);
        insert project1;
        
    RestRequest req = new RestRequest(); 
    RestResponse res = new RestResponse();

    // pass the req and resp objects to the method     
    req.requestURI = URL.getSalesforceBaseUrl().toExternalForm()+'/services/apexrest/AttachPDF/'+project1.Id;  
    req.httpMethod = 'GET';

    ServiceInvoiceRedirectController.attachPdfToRecord results = ServiceInvoiceRedirectController.AttachPDFtoRecordREST(req,res);

    System.assertEquals('true', results.success);
    System.assertEquals(10, results.records.size());
    System.assertEquals('Query executed successfully.', results.message);

  }
	
}
Requirement:- is Generate the PDF and and send email notification and insert new related record to keep track of the pdf and attachment to the record.
I Have a Query Which is giveing the below error. below is the sample code and error.
Below veriable are the date values come from VF page which is used in the Query.
Type is date field:
oppStart.Date_Marked_As_Settled1__c
oppEnd.Date_Marked_As_Settled1__c

strQuery = 'select Date_Marked_As_Settled__c,Date_Marked_As_Settled1__c,Opportunity.Name ,Product2.ProductCode,TotalPrice from ';
strQuery = strQuery + 'OpportunityLineItem where Product2.ProductCode!=\'SHIPPING\' and CreatedDate >= '+oppStart.Date_Marked_As_Settled1__c+' and CreatedDate <= '+oppEnd.Date_Marked_As_Settled1__c+' and Mark_As_Settled__c=true order by createdDate desc';
getOppLineList();

public void getOppLineList(){

for(OpportunityLineItem c : Database.query(strQuery)){ //Error in this line

}

Error : System.QueryException: line 1:497 no viable alternative at character ' '
 
OCRtrigger:
trigger OCRtrigger on OCR_Pharmacy__c (after update) {

    OCRTriggerHandler handler = new OCRTriggerHandler();
    
    handler.UpdateAccountOnAddressChange(trigger.new,Trigger.OldMap)

Trigger Handler: 
public class OCRTriggerHandler{

    public void UpdateAccountOnAddressChange(List<OCR_Pharmacy__c> OCRList, Map<Id,OCR_Pharmacy__c> TriggerOldMap){
    
        Set<Id> ocrIdSet = new Set<Id>();
        List<Account> accountToUpdateList = new List<Account>();
    
        for(OCR_Pharmacy__c OCR : OCRList){
            if((OCR.Address__c != TriggerOldMap.get(OCR.id).Address__c || OCR.City__c!= TriggerOldMap.get(OCR.id).City__c|| 
            OCR.State_Province__c != TriggerOldMap.get(OCR.id).State_Province__c ||
            OCR.Zip_Postal_Code__c != TriggerOldMap.get(OCR.id).Zip_Postal_Code__c || 
            OCR.Country__c!= TriggerOldMap.get(OCR.id).Country__c) && OCR.Status__c != 'Inactive'){
                ocrIdSet.add(OCR.Id);
            }
        }
        
        if(!ocrIdSet.isEmpty()){
            List<OCR_Pharmacy__c> ocrAccList = [
                Select Id,Address__c
                     , City__c
                     , State_Province__c
                     , Zip_Postal_Code__c
                     , Country__c
                     , (Select Id
                             , Distance_to_Service_Facility__c 
                          from Accounts__r
                         where (RecordType.Name = 'LTC Prospect Facility'
                         OR
                         RecordType.Name='LTC Customer Facility'
                         OR
                         RecordType.Name='LTC Former Facility'       
                         ) 
                           
                       )
                  from OCR_Pharmacy__c where Id IN : ocrIdSet
            ];
            
            
            for(OCR_Pharmacy__c OCR : ocrAccList){
                //system.assert(false, '(OCR.Accounts__r.size()' + OCR.Accounts__r.size());
                if(OCR.Accounts__r.size()>0){
                    for(Account acc : OCR.Accounts__r){
                        if(acc.Distance_to_Service_Facility__c <= 0 || String.isBlank(String.valueOf(acc.Distance_to_Service_Facility__c))) {
                            if(Schema.SObjectType.Account.fields.Distance_to_Service_Facility__c.isUpdateable() && Schema.SObjectType.Account.fields.Override_Calculate_Miles__c.isUpdateable()){
                                acc.Distance_to_Service_Facility__c = NULL;
                                acc.Override_Calculate_Miles__c = false;
                                accountToUpdateList.add(acc);
                            }
                            
                        }
                    }
                }    
            }
            if(!accountToUpdateList.isEmpty() && Schema.SObjectType.Account.isUpdateable()){
                update accountToUpdateList ;
            }
        }
        
    }

}
Hi, 

I'm wrecking my brain on how to achieve this. So I'm trying to run a child object from an apportunity. Child object may have multiple records. If so I need to find the previous entered record by comparing the recently created date with previous one. 

I'm writing an after insert trigger to achieve this. However, how do I find the previous records? I'm also trying to avoid nested for loops. So far this is what I have and giving me error: BudgetTrigger: execution of AfterInsert caused by: System.FinalException: Record is read-only Class.BudgetPreviousVersion.VersionUpdate: line 27
 
public without sharing class BudgetPreviousVersion {

    public static TriggerStatus__c cfg = TriggerConfig.raw;

    public static void VersionUpdate(list<Budget__c> budget){
        
        Set<Id> opportunityIds = new Set<Id>(); 
                
        for(Budget__c b: budget){
        
            if(b.Job__c != null){ 
                opportunityIds.add(b.Job__c);
                
            }
        }
        
        Map<ID, Budget__c> budmap = new Map<ID, Budget__c>();
        
        for(Budget__c b:[Select id, previous_version__c, CreatedDate From Budget__c WHERE job__c IN: opportunityIds order by createddate DESC limit 1]){
            
            budmap.put(b.id, b);                                 
        }
        
  List<budget__c> listb = new list<budget__c>();
       for(Budget__c b: budget){
           if(budmap.containskey(b.id)){
                 b.previous_version__c = true;                  

           }
           listb.add(b);
        }//for loop for each customer survey and assign them to customer survey.  */
         upsert listb;
    } 
}

Notice that I tried to upsert because upon searching it says the value is not yet commited. So upserting should update the value, right? How can I re-write this so I can avoid the nested loop? 
 
I have set a Custom Field ('Priority_Flags__c') on the Case object, to represent priority flags as follows:
 
IMAGE( 
CASE( Priority, 
"Low", "/img/samples/flag_green.gif", 
"Medium", "/img/samples/flag_yellow.gif", 
"High", "/img/samples/flag_red.gif", 
"Critical", "/img/samples/flag_red.gif", 
"/s.gif"), 
"Priority Flag")
I included this custom field to be merged in a VisualForce Email Template as follows:
<messaging:emailTemplate subject="[Assignment] Case #{!relatedTo.CaseNumber}: {!relatedTo.Subject}" recipientType="User" relatedToType="Case">
    <messaging:htmlEmailBody >
    <html>
    <style type="text/css">
            body {font-family: arial; size: 12pt;}
        </style>
    <body>
        The following case was assigned to <b>{!relatedTo.Owner.Name}</b>:
        <br />------------------------
        <br />• Case #: {!relatedTo.CaseNumber}
        <br />• Account: <apex:outputLink value="https://my.salesforce.com/{!relatedTo.Account}"> {!relatedTo.Account.Name}</apex:outputLink>
        <br />• Contact Name: {!relatedTo.Contact.Name}
        <br />• Case status: {!relatedTo.Status}
        <br />• Priority: {!relatedTo.Priority_Flags__c} {!relatedTo.Priority}
        <br />• Link: https://my.salesforce.com/{!relatedTo.Id} 
        <br />------------------------
        <br />        
</body>
</html>
</messaging:htmlEmailBody>   
</messaging:emailTemplate>
It seems that the rendered Merged Field is not the image as expected, but the img HTML statement:

User-added image

Is there a way to make this work, and render the IMAGE in the VisualForce Email Template? 
Newbie here.  This is giving me the id of the field and I need the name associated with this id in the Accounts object

<apex:column headerValue="DBA Name">
         <apex:outputText value="{!item.DBA_Name__c}"/>
     </apex:column>
Hi All,

I am not able cover single line of code for the batch class am I makeing anything wrong and the batch class is logic is based on Created Date.

Batch Class:
global class BatchClassToCloseAdSalesOpportunitys implements Database.Batchable<sObject> , Schedulable {
	
	private String OppClosedWon		= Constant_PicklistVariables.OPP_CLOSED_WON;
    private String OppClosedLost	= Constant_PicklistVariables.OPP_CLOSED_LOST;
    //Opportunity Ad Sales RecordType ID
    ID AdSalesRecordTypeId 			= Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('AD-Sales').getRecordTypeId();
    private String query 			= 'Select Id,Name,RecordTypeId,StageName,CreatedDate,Extend__c from Opportunity WHERE RecordTypeId =: AdSalesRecordTypeId AND ( StageName !=: OppClosedWon OR StageName !=: OppClosedLost ) ';
   	
	global BatchClassToCloseAdSalesOpportunitys(){
    	// Batch Constructor
    }
    
    global void execute(SchedulableContext sc) {
    	System.debug('DagnyQuery==>'+query);
        Database.executebatch(this); 
    }
    
    // Start Method
    global Database.QueryLocator start(Database.BatchableContext BC){
    	System.debug('Dagny==>Query==>'+query);
    	return Database.getQueryLocator(query);
    }
  
   	// Execute Logic
   	global void execute(Database.BatchableContext BC, List<sObject>scope){
          Set<Id> oppIdSet						= new Set<Id>();
          list<Opportunity> opportunityList = (list<Opportunity>) scope;
          List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
          map<Id,Integer> campMapList	= new map<Id,Integer>();
          String baseUrl = System.URL.getSalesforceBaseUrl().toExternalForm();

          if(opportunityList.size() > 0){
          	 for(Opportunity oppId: opportunityList){
          	 	oppIdSet.add(oppId.Id);	          	 	
          	 }
          	 
          	 for(ADs_Campaign__c camp: [SELECT Id, Opportunity__c FROM ADs_Campaign__c WHERE Opportunity__c IN: oppIdSet]){
          	 	if(camp.Opportunity__c != null){
	          	 	if(campMapList.containsKey(camp.Opportunity__c)){
	          	 		campMapList.put(camp.Opportunity__c,campMapList.get(camp.Opportunity__c)+1 );
	          	 	}else{
	          	 		campMapList.put(camp.Opportunity__c, 1);
	          	 	}
          	 	}
          	 }
          	 
             for(Opportunity oppRec: opportunityList){
             	DateTime sT 			= oppRec.CreatedDate;
				Date sDate 				= date.newinstance(sT.year(), sT.month(), sT.day());
             	Date startDate 			= sDate;
				Date dueDate 			= System.today();
				Integer numberDaysDue 	= startDate.daysBetween(dueDate);
				Integer timeStamp		= Integer.valueOf(System.Label.OpportunityCloseTimeStamp);
				
				if(oppRec.Extend__c == true){
					if(numberDaysDue >= timeStamp+5){
						if( campMapList.get(oppRec.Id) != null && campMapList.get(oppRec.Id) > 0 ){
							oppRec.StageName = Constant_PicklistVariables.OPP_CLOSED_WON;
						}else{
							oppRec.StageName = Constant_PicklistVariables.OPP_CLOSED_LOST;
						}
						
					}
				}else{
					if(numberDaysDue >= timeStamp){
						if( campMapList.get(oppRec.Id) != null && campMapList.get(oppRec.Id) > 0){
							oppRec.StageName = Constant_PicklistVariables.OPP_CLOSED_WON;
						}else{
							oppRec.StageName = Constant_PicklistVariables.OPP_CLOSED_LOST;
						}
					}else{
						if(numberDaysDue >= timeStamp-2){
							messaging.singleEmailMessage mail = new messaging.singleEmailMessage();
     						mail.ToAddresses = new string[]{ oppRec.CreatedBy.Email};
							// mail.setReplyTo('');   // <-----------------------------------Set the ReplyTo---
						    mail.setSubject('Opprtunity Closur Notification'+oppRec.Name);
						    mail.setUseSignature(false);
							string htmlBody = '<div style="border:2px solid green; border-radius:15px;"><p>Hi,</p><p><span style="color:brown; font-weight:bolder;">'+oppRec.Owner.Name+'</span> ,</p>'
						    +'<p>The Opportunity '+oppRec.Name+'aginst the seller '+oppRec.Account+'</br>!</p> will be closed with in 2 days </br>Please confirm, If you want to extend the opportunity closure For 5 days more </p>'
						    +'<p>Please click on the below link and update the value of "Request For Closure Extension" to checked </br></p>'
						    +'<p>'+baseUrl+'/'+oppRec.Id+' </p></div>';
						
						    mail.setHtmlBody(htmlBody);
						    mails.add(mail);
    					    
						}
					}
					
				}
             }
             System.debug('Dagny==>OpportunityList=>'+opportunityList);
             update opportunityList;
             if(mails.size() > 0 ){
             	Messaging.sendEmail(mails);
             }
          }   
 
   	}
 
   	global void finish(Database.BatchableContext BC){
        // Logic to be Executed at finish
   	}
   
}

Test Class:
@isTest(seeAllData=false)
public class BatachClassToCloseAdSalesOppty_Test {
	Static User testUser;
    Static Opportunity testOpp;
    Static Opportunity testOpp2;
    static ADs_Campaign__c adsCampaign;
    static ADs_Campaign__c adsCampaign2;
    public BatachClassToCloseAdSalesOppty_Test(){
        
    }
    
    Static void init(){
        testUser 	= InitialTestData2.createUserRecord();
        insert testUser;  
             
        
        DateTime oppCreatDate = System.now() - 15;
        system.debug('oppCreatDate'+oppCreatDate);
        String OppDate = ''+oppCreatDate.formatGMT('yyyy-MM-dd\'T\'HH:mm:ss.SSS\'Z\''+'');
        String oppCreDateStr = String.valueOf(OppDate);
        system.debug('oppCreDateStr'+oppCreDateStr);
        String oppJSON = '{"attributes":{"type":"Opportunity","url":"/services/data/v25.0/sobjects/Opportunity/006N0000005t0cd"},"Id":"006N0000005t0cd","CreatedDate":"'+oppCreDateStr+'"}';
        testOpp = (Opportunity)JSON.deserialize(oppJSON,Opportunity.class);
        
        /*DateTime oppCreatDate2 = System.now() - 13;
        String OppDate2 = ''+oppCreatDate2.formatGMT('yyyy-MM-dd\'T\'HH:mm:ss.SSS\'Z\''+'');
        String oppCreDateStr2 = String.valueOf(OppDate2);
        String oppJSON2 = '{"attributes":{"type":"Opportunity","url":"/services/data/v25.0/sobjects/Opportunity/006N0000006KDab"},"Id":"006N0000006KDab","CreatedDate":"'+oppCreDateStr2+'"}';
        testOpp2 = (Opportunity)JSON.deserialize(oppJSON2,Opportunity.class);*/
        
        system.debug('oppCreDateStr'+testOpp.Id);
        adsCampaign = InitialTestData2.createAdsCampaign(testOpp.Id);
        //insert adsCampaign;
        
        /*adsCampaign2 = InitialTestData2.createAdsCampaign(testOpp2.Id);
        insert adsCampaign2;*/
        
        
    }
    
    //this method is for the Opportunity Batch auto close status update 
    private static testMethod void batchTest (){
    	test.startTest();
        init();
        Database.QueryLocator QueryLoc;
        Database.BatchableContext BatchCont;
        System.runAs(testUser){
            List<Opportunity> oppList = new List<Opportunity>();
            oppList.add(testOpp);
            //oppList.add(testOpp2);
            
            system.debug('List->'+oppList);
            BatchClassToCloseAdSalesOpportunitys batch12 =new BatchClassToCloseAdSalesOpportunitys();
            ID batchprocessid = Database.executeBatch(batch12,200);
            
            QueryLoc= batch12.start(BatchCont);
            System.debug(BatchCont);
            Database.QueryLocatorIterator QueryIterate = QueryLoc.iterator();
            while (QueryIterate.hasNext()){
                 Opportunity objQueue = (Opportunity)QueryIterate.next();           
                 System.debug(objQueue);
                 oppList.add(objQueue);
            }       
            
            batch12.execute(BatchCont, oppList);
            batch12.finish(BatchCont); 
        }
        Test.stopTest();
    }
}

Need Help ASAP,

Thank you in advance.
Hi all

I have a some partner users where i have to create report and give acces to the partner user to see the report.

->I have created some sample reports and created the folder and given the acces to the parther user to the report folder.
->I have made Standard Report Visibility true in the sharing setting.
->In profile level i have given acces to the report. add the tab to the partner login 

iam able to see the report tab when i logged in to the partner user and when i click on report tab i am not able to see the folder also which was shared with the partner user...

Need help asap.
Thank u in advance.
 
Hi, 

i have custom lookup reseller name to Reseller object in Quote, Reseller is ajunction object to account and Opportunty. In the Quote this lookup has a filter to select only resellars record belongs to opportunity.

This filter is working for editing the record but it is not working while creating the new record. below is the screenshot of filer
 Need Help plz asap.
Thanks in advance.

User-added image
I have a REST service but i am not able to cover this class. 
Below is my code, need help ASAP.

Thanks You in advance.
@RestResource(urlMapping='/AttachPDF/*')
global class ServiceInvoiceRedirectController {
	
	@HttpGet
        global static void AttachPDFtoRecordREST() {
        	List<Id> accId = new List<Id>();
        	List<String> emailList = new List<String>();
            RestRequest req = RestContext.request;
            id recordId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);

            PageReference pdfPage = new PageReference('/apex/ServiceInvoicePDF?Id='+recordId);
            pdfPage.getParameters().put('id',recordId);
            Blob pdf = pdfPage.getContentAsPdf(); //!Test.isRunningTest() ? pdfPage.getContentAsPdf() : Blob.ValueOf('dummy text');
            
			//List of accoutn Id's of related project
            for(Account_Project_Junction__c accPrjJunRec: [SELECT Id,Project__c,Account__c From Account_Project_Junction__c WHERE Project__c =: recordId]){
            	accId.add(accPrjJunRec.Account__c);
            }
            
            //List of email id's of the selected account's
            for(Contact conRec: [SELECT Id,AccountID,Email,Is_Primary_Contact__c From Contact where AccountID IN: accId AND Is_Primary_Contact__c = true]){
            	if(conRec.Email != null){
            		emailList.add(conRec.Email);
            	}
            }
            
            Project__c prjRec = [Select Id,Name from Project__c where Id =: recordId];
            //Insert Invoice record for related project
	        Invoice__c invoRec = new Invoice__c();
	        invoRec.RecordTypeId = Constants_PicklistVariables.serInvoice; 
	        invoRec.Project__c = recordId;
	        
	        try{
	        insert invoRec;
	        }catch(Exception e){
	            System.debug('Invoice=Exception-->'+e);
	        }
	        System.debug('Invoice=invoRec.id-->'+invoRec);
	        
	        //Insert Attacment to the invoice        
	        Attachment a = New Attachment();
	        a.body = pdf;
	        a.parentID = invoRec.id;
	        a.ContentType  = 'application/pdf';
	        a.Name = 'SER-INV-'+invoRec.id+'.pdf';
	        try{
	        insert a;
	        }catch(Exception e){
	            System.debug('Attachment=Exception-->'+e);
	        }
	        
	        //Create the email attachment
	    	Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
	    	efa.setFileName('SER-INV-'+invoRec.id+'.pdf');//Pleace ad pdf name from contact name project and oppty concatinate 
		    efa.setContentType('application/pdf');
		    efa.setBody(pdf);
		    
		    // Create the Singal Email Message
		    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
		    email.setSubject('Service Invoice Notification');
		    String[] CCEmails = emailList;
			email.setToAddresses(CCEmails);
		    //email.setToAddresses(new String[] { 'developer@extentor.com' });//add Contact email id
		    email.setPlainTextBody( 'Dear:Sir/Madam <br/> Please Find Attachment your financial report Attached with this email.');
		    email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
		    
		    // Sends the email
		    Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
            
        }

        // call this method from your Batch Apex
        global static void attachPdfToRecord( Id recordId, String sessionId )
        {
        	System.debug('recordId==>'+recordId);
        	System.debug('sessionId==>'+sessionId);
        	System.debug('Iam in REST API Call method');
            HttpRequest req = new HttpRequest();
            req.setEndpoint(URL.getSalesforceBaseUrl().toExternalForm()+'/services/apexrest/AttachPDF/'+recordId);
            req.setMethod('GET');
            req.setHeader('Authorization', 'OAuth ' + sessionId);

            Http http = new Http();
            HttpResponse response = http.send(req);    
        }
        
}

Test class:
@isTest(seeAllData=false)
global class Test_ServiceInvoiceRedirectController{
   
    static testMethod void testDoGet() {
		Account acc= InitialTestData.createAccount('Raj');
        insert acc;
        
        Contact contact1=InitialTestData.createContact(acc.id,'Sen','raj@gmail.com');
        insert contact1;
        
        Opportunity_Deal__c oppdeal=InitialTestData.createOpportunityDeal('Opp1',acc.id,contact1.id,false,'Quote');
        insert oppdeal;
        
        Project__c project1=InitialTestData.createPlotProject('Pro',acc.id,'Submitted',oppdeal.id);
        insert project1;
        
    RestRequest req = new RestRequest(); 
    RestResponse res = new RestResponse();

    // pass the req and resp objects to the method     
    req.requestURI = URL.getSalesforceBaseUrl().toExternalForm()+'/services/apexrest/AttachPDF/'+project1.Id;  
    req.httpMethod = 'GET';

    ServiceInvoiceRedirectController.attachPdfToRecord results = ServiceInvoiceRedirectController.AttachPDFtoRecordREST(req,res);

    System.assertEquals('true', results.success);
    System.assertEquals(10, results.records.size());
    System.assertEquals('Query executed successfully.', results.message);

  }
	
}
Hi Frends,
Iam getting the bellow error:
TicketStatus: execution of AfterUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id a0AO000000Ak6Y6MAJ; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, This profile cannot edit this escalation the tickets are raised: [] Class.TicketStatusHandler.onAfterUpdate: line 229, column 1 Trigger.TicketStatus: line 37, column 1

There is requirement like i have a parent record and child records, the child record as a self lookup relation to parent record. 
Here the parent record is escaltion and child record is ticket.
The above error is comeing while editing the ticket because There is a validation on the parent record(Escaltion) based on profile. the validation is  
Ex: IF Ticket is raised for the respaective Escalation then the BA profile cannot edit the Escaltion. But can edit the Ticket, based on ticket value from trigger escaltion is updated, here it comes the above mentioned error.

How can i overcome from this problem need help.

Thanks in advance,
Hi Frends,

Iam getting the below error in trigger after Update 
TicketStatus: execution of AfterUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id a0AO000000Ak6Y6MAJ; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, TicketStatus: execution of AfterUpdate caused by: System.DmlException: Update failed. First exception on row 0; first error: MISSING_ARGUMENT, Id not specified in an update call: [] Class.TicketStatusHandler.onAfterUpdate:

this error is in the line number 65 DML operation update. I added the System debug statement in line number 64 and iam getting the ID of the record. Am i missing anything in the below code. need help ASAP 

Thanks in advance.
 
//-- After Update
	 
	 public void onAfterUpdate(final List<Escalation__c> newObjects,final List<Escalation__c> oldObjects,final Map<Id, Escalation__c> newObjectsMap,final Map<Id, Escalation__c> oldObjectsMap){
	 List<Escalation__Share> EscalationShareList 			= new List<Escalation__Share>();
	 List<Escalation__Share> EscalationShareListToDelete 	= new List<Escalation__Share>();
	 List<Followers__c> FollowersList 						= new List<Followers__c>();
	 List<Escalation__c> ParentEscaUpdate 					= new List<Escalation__c>();
	 Map<Id,Id> toDeleteShareMap 							= new Map<Id,Id>();
	 map<Id, Escalation__c> parentEsca 						= new map<Id, Escalation__c>();
	 Escalation__c PrarentRec = new Escalation__c();
	 
		 for(Escalation__c escaParent: [SELECT Id,Name,Sys_Ticket_Count__c,RecordTypeId FROM Escalation__c WHERE RecordTypeId =: Constants_PicklistVariables.ESCALATION_RECORDTYPE_ID]){
		 		parentEsca.put(escaParent.Id, escaParent);
		 }
	 	
		 for(Escalation__c esca: newObjects){
		 	if(esca.RecordTypeId == Constants_PicklistVariables.TICKET_RECORDTYPE_ID && esca.Assigned_To__c != null && esca.Assigned_to__c != oldObjectsMap.get(esca.Id).Assigned_To__c){
	            Escalation__Share expShare = new Escalation__Share(
								              ParentId 		= esca.Id,
								              UserOrGroupId = esca.Assigned_To__c,
								              rowCause 		= Schema.Escalation__Share.rowCause.AssignedTo__c,
								              accessLevel 	= 'Edit'
								            );
	            
	            //Adding Followers
	            Followers__c follRec = new Followers__c();
	            follRec.Follower_Name__c = esca.Assigned_To__c;
	            follRec.Ticket__c 		 = esca.Id;
	            
	            FollowersList.add(follRec);
	            EscalationShareList.add(expShare);
	            toDeleteShareMap.put(esca.Id, oldObjectsMap.get(esca.Id).Assigned_To__c);
	            System.debug('toDeleteShareMap'+toDeleteShareMap);
		 	}
		 	if(esca.Escalation__c != null)
		 	PrarentRec = parentEsca.get(esca.Escalation__c);
		 	
		 }
		 
		 if(PrarentRec != null){
		 	List<Escalation__c> TicketRec = [SELECT Id,Name,RecordTypeId,Escalation__c,Category__c,Ticket_Status_Overall_Ops__c,Ticket_Status_Overall_Finance__c,Ticket_Status_Overall_Mar__c,Ticket_Status_Overall_Service__c,Ticket_Status_Overall_Tech__c FROM Escalation__c WHERE RecordTypeId =: Constants_PicklistVariables.TICKET_RECORDTYPE_ID AND Escalation__c =: PrarentRec.Id];
		 	Integer NonClosedTicketCounter = 0;
		 	System.debug('TicketRec'+TicketRec);
		 	for(Escalation__c tickRec: TicketRec){
		 		if(tickRec.Category__c == null)
		 			NonClosedTicketCounter = NonClosedTicketCounter + 1;
		 		if(tickRec.Category__c == 'Ops' && tickRec.Ticket_Status_Overall_Ops__c != 'Closed')
		 			NonClosedTicketCounter = NonClosedTicketCounter + 1;
		 		if(tickRec.Category__c == 'Finance' && tickRec.Ticket_Status_Overall_Finance__c != 'Closed')
		 			NonClosedTicketCounter = NonClosedTicketCounter + 1;
		 		if(tickRec.Category__c == 'Leads (Marketing)' && tickRec.Ticket_Status_Overall_Mar__c != 'Closed')
		 			NonClosedTicketCounter = NonClosedTicketCounter + 1;
		 		if(tickRec.Category__c == 'Service' && tickRec.Ticket_Status_Overall_Service__c != 'Closed')
		 			NonClosedTicketCounter = NonClosedTicketCounter + 1;
		 		if(tickRec.Category__c == 'Tech' && tickRec.Ticket_Status_Overall_Tech__c != 'Closed')
		 			NonClosedTicketCounter = NonClosedTicketCounter + 1;
		 	}
		 	System.Debug('NonClosedTicketCounter'+NonClosedTicketCounter);
		 	if(NonClosedTicketCounter == 0){
			 	/*Escalation__c parentRecord = parentEsca.get(PrarentRec.Id) ;
			 	parentRecord.Escalation_Status__c = 'Closed';
			 	update parentRecord;*/
			 	PrarentRec.Escalation_Status__c = 'Closed';
			 	System.debug('PrarentRec'+PrarentRec);
			 	update PrarentRec;
		 	}
		 }
		 
		 for(Escalation__Share expShare :[SELECT Id, ParentId, rowCause, UserOrGroupId FROM Escalation__Share WHERE ParentId in :toDeleteShareMap.keySet()]){
	        if(toDeleteShareMap.get(expShare.ParentId) != null && toDeleteShareMap.get(expShare.ParentId) == expShare.UserOrGroupId){
	            EscalationShareListToDelete.add(expShare);
	        }
	     }
	    
	     try{
		 	insert EscalationShareList;
		 	insert FollowersList;
		 	delete EscalationShareListToDelete;
		 }catch(Exception e){
		 	
		 }
		 
	 }

 
I have override the standerd Edit button with VF page this VF page will redirect to other VF page based on the record type, the redirection is working properly but i want to give an error messsage on this this page.
In the below class line number 26 error message is not diplaying if i add "return null" it is redirectiong to standerd page if i remove this line it stay in the page and showes "Attempt to De-reference null object" error. Need help ASAP

Thanks in advance

here c.Sys_Ticket_Count__c is grater than 0 

Apex Class:
public with sharing class escaEditBtnController {
	
	public escaEditBtnController(ApexPages.StandardController controller) {
        this.controller = controller;
    }
    
    public PageReference getredirect() {

        Escalation__c c = [Select id, recordtypeid,Sys_Ticket_Count__c From Escalation__c Where Id = :ApexPages.currentPage().getParameters().get('id')];

        PageReference newPage;

        if (c.recordtypeid == Constants_PicklistVariables.TICKET_RECORDTYPE_ID) {
            newPage = new PageReference('/apex/TicketEdit?retURL=%2F'+c.id);
			newPage.getParameters().put('id', c.id);
	        newPage.getParameters().put('editMode', 'true');
	        
        } else {
        	if(c.Sys_Ticket_Count__c <= 0 ){
        		newPage = new PageReference('/apex/EscalationEdit?retURL=%2F'+c.id);
	            newPage.getParameters().put('id', c.id);
	            newPage.getParameters().put('editMode', 'true');
	            newPage.getParameters().put('nooverride', '1');
        	}else{
        		System.debug('c.Sys_Ticket_Count__c'+c.Sys_Ticket_Count__c);
        		ApexPages.addmessage(new ApexPages.message(ApexPages.Severity.Error,'Ticket has been rised for this escalation you do not have access to edit this Escalation, Please contact the system admin'));
				return null; 
        	}
            
        }
		
        return newPage.setRedirect(true);
    }

    private final ApexPages.StandardController controller;
}
VF page:
<apex:page standardController="Escalation__c" extensions="escaEditBtnController"  
    action="{!nullValue(redirect.url, urlFor($Action.Escalation__c.Edit, Escalation__c.id, null, true))}">
<apex:pageMessages />
</apex:page>


 
Iam getting the null pointer exception while useing the wrapper class my other wrapper class code are working fine not able to understand what went wrrong in this code. need Help ASAP

public list<WrapperClass> wrapper_variable    {get;set;}
Account_Project_Junction__c projRec             = [SELECT Id,Name,Project__c,Project__r.Name from Account_Project_Junction__c WHERE Id = 'a00O000000KWbzsIAD'];
Escalation_Project_Junction__c EscaProjJunRec     = new Escalation_Project_Junction__c();
EscaProjJunRec.Project__c                         = projRec.Id;
EscaProjJunRec.Project_Name__c                     = projRec.Project__r.Name;
wrapper_variable.add(new WrapperClass(EscaProjJunRec));
//wrapper class
public class WrapperClass{
    public Escalation_Project_Junction__c projectEsca_wrapper{get;set;}
    
    public WrapperClass(Escalation_Project_Junction__c EPJ){
        projectEsca_wrapper = EPJ;
    }           
}


Error:
05:29:16:077 FATAL_ERROR System.NullPointerException: Attempt to de-reference a null object
this error is for the line
wrapper_variable.add(new WrapperClass(EscaProjJunRec));
Requirement:- is Generate the PDF and and send email notification and insert new related record to keep track of the pdf and attachment to the record.
Hi- I just want to delete the existing records in contructor itself. 
This code is working in action method but its not working in constructor, Please share me idea if any one have. 

List<Forecast_Revenue_Report__c> foreRevRepOutput = [SELECT Forecast_Amount__c, Forecast_Month__c, opp_id__c FROM Forecast_Revenue_Report__c WHERE opp_id__c = :this.oppId];
for(Forecast_Revenue_Report__c frDelete : foreRevRepOutput ) {
                    delete frDelete;
       }

Thanks,
Iam trying to export data from Oracle to SFDC using Command Line .

Iam finding the below error.

ERROR [testProcess] database.DatabaseContext initConnection (DatabaseContext.java:94) - Database error encountered during connecting for database configuration: queryAccount.  Sql error: Cannot create PoolableConnectionFactory (Io exception: The Network Adapter could not establish the connection).
org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Io exception: The Network Adapter could not establish the connection)

PLease find the entire error log,process-conf,database-conf as below.

Your help is highly appreciated.

2007-08-29 09:56:40,722 INFO  [main] controller.Controller initLog (Controller.java:382) - The log has been initialized
2007-08-29 09:56:40,722 INFO  [main] process.ProcessConfig getBeanFactory (ProcessConfig.java:78) - Loading process configuration from config file: c:\test\process-conf.xml
2007-08-29 09:56:40,784 INFO  [main] xml.XmlBeanDefinitionReader loadBeanDefinitions (XmlBeanDefinitionReader.java:163) - Loading XML bean definitions from file [c:\test_hms\process-conf.xml]
2007-08-29 09:56:40,816 INFO  [main] core.CollectionFactory <clinit> (CollectionFactory.java:66) - JDK 1.4+ collections available
2007-08-29 09:56:40,816 INFO  [main] core.CollectionFactory <clinit> (CollectionFactory.java:71) - Commons Collections 3.x available
2007-08-29 09:56:40,878 INFO  [testProcess] controller.Controller initConfig (Controller.java:343) - The controller config has been initialized
2007-08-29 09:56:40,894 INFO  [testProcess] process.ProcessRunner run (ProcessRunner.java:102) - Initializing process engine
2007-08-29 09:56:40,894 INFO  [testProcess] process.ProcessRunner run (ProcessRunner.java:105) - Loading parameters
2007-08-29 09:56:41,942 INFO  [testProcess] process.ProcessRunner run (ProcessRunner.java:116) - Logging in to: https://www.salesforce.com
2007-08-29 09:56:42,741 INFO  [testProcess] dao.DataAccessObjectFactory getDaoInstance (DataAccessObjectFactory.java:51) - Instantiating data access object: queryAccount of type: databaseRead
2007-08-29 09:56:42,741 INFO  [testProcess] xml.XmlBeanDefinitionReader loadBeanDefinitions (XmlBeanDefinitionReader.java:163) - Loading XML bean definitions from file [c:\test_hms\database-conf.xml]
2007-08-29 09:56:42,834 INFO  [testProcess] process.ProcessRunner run (ProcessRunner.java:121) - Checking the data access object connection
2007-08-29 09:56:45,354 ERROR [testProcess] database.DatabaseContext initConnection (DatabaseContext.java:94) - Database error encountered during connecting for database configuration: queryAccount.  Sql error: Cannot create PoolableConnectionFactory (Io exception: The Network Adapter could not establish the connection).
org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Io exception: The Network Adapter could not establish the connection)
    at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:855)
    at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:540)
    at com.salesforce.lexiloader.dao.database.DatabaseContext.initConnection(DatabaseContext.java:87)
    at com.salesforce.lexiloader.dao.database.DatabaseContext.checkConnection(DatabaseContext.java:79)
    at com.salesforce.lexiloader.dao.database.DatabaseReader.checkConnection(DatabaseReader.java:231)
    at com.salesforce.lexiloader.process.ProcessRunner.run(ProcessRunner.java:123)
    at com.salesforce.lexiloader.process.ProcessRunner.main(ProcessRunner.java:230)
Caused by: java.sql.SQLException: Io exception: The Network Adapter could not establish the connection
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:125)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:162)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:274)
    at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:319)
    at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:344)
    at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:148)
    at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:32)
    at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:545)
    at org.apache.commons.dbcp.DriverConnectionFactory.createConnection(DriverConnectionFactory.java:37)
    at org.apache.commons.dbcp.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:290)
    at org.apache.commons.dbcp.BasicDataSource.validateConnectionFactory(BasicDataSource.java:877)
    at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:851)
    ... 6 more
2007-08-29 09:56:45,354 FATAL [testProcess] process.ProcessRunner run (ProcessRunner.java:155) - Database error encountered during connecting for database configuration: queryAccount.  Sql error: Cannot create PoolableConnectionFactory (Io exception: The Network Adapter could not establish the connection).


process-conf.xml
==========
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
    <bean id="testProcess" class="com.salesforce.lexiloader.process.ProcessRunner" singleton="false">
        <description>test from database</description>
        <property name="name" value="testProcess"/>
        <property name="configOverrideMap">
            <map>
                <entry key="sfdc.endpoint" value="https://www.salesforce.com"/>
                <entry key="sfdc.username" value="a@gmail.com"/>
                <entry key="sfdc.password" value="xxxx"/>
                <entry key="sfdc.timeoutSecs" value="600"/>
                <entry key="sfdc.loadBatchSize" value="200"/>
                <entry key="sfdc.entity" value="Account"/>
                <entry key="process.operation" value="insert"/>
                <entry key="process.mappingFile" value="C:\testmap.sdl"/>
                <entry key="dataAccess.name" value="queryAccount"/>
                <entry key="dataAccess.type" value="databaseRead"/>
                </map>
        </property>
    </bean>


database-conf.xml
============
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>

<bean id="queryAccount"
      class="com.salesforce.lexiloader.dao.database.DatabaseConfig"
      singleton="true">
    <property name="sqlConfig" ref="queryAccountSql"/>
    <property name="dataSource" ref="dbDataSource"/>
</bean>

<bean id="dbDataSource"
      class="org.apache.commons.dbcp.BasicDataSource"
      destroy-method="close">
    <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
    <property name="url" value="jdbc:oracle:thin:@my.server.com:1521:orcl"/>
    <property name="username" value="scott"/>
    <property name="password" value="tiger"/>
</bean>



<bean id="queryAccountSql"
      class="com.salesforce.lexiloader.dao.database.SqlConfig" singleton="true">
    <property name="sqlString">
        <value>
            SELECT c1,c2
            FROM test
            </value>
    </property>
    <property name="columnNames">
        <list>
            <value>c1</value>
            <value>c2</value>
            </list>
    </property>
    <property name="sqlParams">
        <map>
            <entry key="process.lastRunDate" value="java.sql.Timestamp"/>
        </map>
    </property>
</bean>

</beans>


Thanks a lot in advance
Ajay

  • August 29, 2007
  • Like
  • 0