• nnewbold-sfdc
  • NEWBIE
  • 100 Points
  • Member since 2009

  • Chatter
    Feed
  • 4
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 28
    Replies

I have achieved 100% testing on my classes and trigger, but 0% for the system provided classes XMLDom and StartHere.  I have seen some ambiguous posts about this, but have not found source code I can download to simply test these classes.  Is there a simple solution to this issue.  This problem must come up for everyone who goes to deploy their first application; it seems logical for SalesForce to provide the test code if the classes are automatically included, so everyone doesn't have to solve the same problem over and over again.  Thanks for your help.

  • July 12, 2010
  • Like
  • 0

I am getting this error when this method is run.Specifically the remove(). I tried deepcloning a copy, and removing that. Doesn't work. Any solutions ???

 

System.FinalException: Collection is read-only

 

private void createExcludeList(){
            
            Map<String, Schema.SObjectField> fieldmap1 = Schema.SObjectType.Account.fields.getMap();

            List<String> fieldExcludeList = new List<String> {
                'LastModifiedDate', 'LastActivityDate', 'SystemModstamp'};
    
            for(integer i=0; i<(fieldmap1.size()-fieldExcludeList.size()); i++)
                fieldmap1.remove(fieldExcludeList[i]);      //LINE THAT IS CAUSING THE ERROR

}

 

 

This code: 

 

 

		  String s = (String) myValueHolder;
		  System.debug('val: ' + s );
		  if (s != null) {
			  String[] frontBack = s.split('.');
			  System.debug('FB:' + frontBack.size());
			  if(frontBack.size() > 1)
			  {
		  		System.debug('WOO I made it');
			  }

 

 

Works fine the first time I run it on a page. However, every subsequent time the split returns a list with 0 elements.

 

For instance, here is a selection from the debug log:

 

 

12:53:26.175|USER_DEBUG|[16,5]|DEBUG|val: 920.0  <===  has a period!
12:53:26.175|METHOD_EXIT|[16,5]|debug(ANY)
12:53:26.175|METHOD_ENTRY|[18,18]|String.split(String)
12:53:26.175|METHOD_EXIT|[18,18]|split(String)
12:53:26.175|METHOD_ENTRY|[20,6]|System.debug(String)
12:53:26.175|METHOD_ENTRY|[20,27]|LIST:String.size()
12:53:26.175|METHOD_EXIT|[20,27]|size() 
12:53:26.175|USER_DEBUG|[20,6]|DEBUG|FB:0  <=== but zero elements in the resulting list
12:53:26.175|METHOD_EXIT|[20,6]|debug(ANY)
12:53:26.175|METHOD_ENTRY|[21,9]|LIST:String.size()

 

Any ideas?  I've tried saving it to a list, array, initializing the list elsewhere but nothing seems to change the simple fact that the split method doesn't work. 

 

 

 

global BatchUpdateAdmissionsGoals(String q, String e, String f, String v){
		Query=q; Entity=e; Field=f;Value=v;
		opportunityList = new List <Opportunity> ();
global Database.QueryLocator start(Database.BatchableContext BC){		
		
		return Database.getQueryLocator(query);		
	} 
	
	global void execute(Database.BatchableContext BC, List<sObject> scope){
		//List <Admissions_Goal__c> goalsToUpdate = new List<Admissions_Goal__c>();
		Integer totalLeads, weeklyLeads;
		for(sObject s : scope){
				if(s.getsObjectType() == Opportunity.sObjectType) {
			 	
				 	Opportunity o = (Opportunity)s;
				 	opportunityList.add(o);		
				}
		}
		System.debug('*** Opp list size ' + opportunityList.size());
}


global void finish(Database.BatchableContext BC){
System.debug('*** Opp list size ' + opportunityList.size());
}

 

I am trying to write some batch Apex. When the following anonymous code block

 string query = 
            'SELECT Id, OwnerID, Academic_Start_Date__c, Date_Booked__c  ' +
            'FROM Opportunity WHERE ID=\'006S0000003imhy\''; 
             
         
        BatchUpdateAdmissionsGoals updateAdmissionsGoalsJob = new BatchUpdateAdmissionsGoals (query, '', '', '');
        ID admissionsGoalsBatchJobID = Database.executeBatch(updateAdmissionsGoalsJob); 

 

:

 

When I call the the debug statement that gets the opportunityList.size() the first time and I get 1 as expected. But when I call it in the Finish() method again, I get 0. It doesn't seem to keep the the items in opportunityList when it gets to the Finish() method

I just installed the Version: Winter '11 (20.0.0) Force.com plug-in this morning.

Now I can't see and debug logs when running Unit Tests. The window in the bottom right only contains "No Debug Logs"

 

The debog log does show up when running in the browser.

 

My other developers are having this same problem. Is there a setting I'm missing? Has anyone else experienced this?

 

Thanks

I updated my IDE plugin this morning and attempted running my unit tests.  The debug log window is empty.  I then attempted installing Eclipse 3.6 (x86 and x64), with the new plugin and they both acted the same.  Is there some obscure setting I am missing?  I sure wish I could see my debug logs through the IDE.

 

PS - yes I attempted to use the standalone installer for both x86 and x64 before posting here.

i am using apex class like this..follows

 

global class YodleeLoginService {
webservice static List<object> cobrandLoginContext(string username) {
    List<object> cobrandRespInfo = new List<object>();  
     
   yintegDomyexpensesCom.CobrandLoginServiceHttpSoap11Endpoint serviceobj=new yintegDomyexpensesCom.CobrandLoginServiceHttpSoap11Endpoint();
   
    serviceobj.endpoint_x='http://171.16.44.40:8081/YodleeIntegration/services/CobrandLoginService';
    
  
    yintegDomyexpensesComXsd.CobrandLoginResponse responseObj=new yintegDomyexpensesComXsd.CobrandLoginResponse();
     
     responseObj=serviceobj.loginCobrand(cobrandId, appId, cobrandLogin, cobrandPassword);
 
     //cobrandRespInfo.add(responseObj);
     
      String language=responseObj.language;
  
        return cobrandRespInfo;
   
}
    
}

 

/// Here how to return the object from the response or how to get the fileds value present in tne response

 

 

I am getting error like this...

 


 

(com.salesforce.results::Fault)#0
  context = (null)
  detail = (null)
  faultcode = "soapenv:Client"
  faultstring = "System.CalloutException: IO Exception: Read timed out

Class.yintegDomyexpensesCom.CobrandLoginServiceHttpSoap11Endpoint.loginCobrand: line 46, column 13
Class.YodleeLoginService.cobrandLoginContext: line 25, column 17
External entry point"

 

in an Alert box showing the above details .How to solve this ...please

I am running into the governor limit issue since I have the SQls inside the for loop. I am trying to optimize the code to get the case and owner information outside the for loop.

 

New to Apex development. Would appreciate some pointers on writing efficient SOQls outside the For loop in a trigger.

 

/* Trigger logic.. If transportation case type, and status = "awaiting internal response, case creator alias = "CS agents" and case owner = regional call center, MVC agent field = TASR agent, then assign then case back to the MVC agent *./

'

 

trigger TR_2 on Case (before update) {
   Case[] cases = Trigger.new;
   for (Case a:cases){ 
    string creatorid;
    string casecreatoriwdalias;
      String caseowner;
    string iWdAliasCaseOwner;
    String caseno;
    String err_msg = '';
    String MVCowner;
      String iWDMVCOwner;
                     
             creatorid = a.CreatedById;
          caseno = a.CaseNumber;
          
          case c = [select ownerid from case where casenumber = :caseno limit 1];
           caseowner = a.ownerid;
          MVCowner  = a.MVC_Owner__c;
    
         // get user alias information for the case creator   
    User userinfor = [select alias, iWD_Alias_Case_Owner__c, Iwd_Case_Creator__c from User where id = :creatorid];
    casecreatoriwdalias = userinfor.Iwd_Case_Creator__c;
    
      if (caseowner.substring(0,3) == '005'){
    // get case owner alias information
    User caseowneruserinfor = [select alias, iWD_Alias_Case_Owner__c, Iwd_Case_Creator__c from User where id = :caseowner limit 1];
    iWdAliasCaseOwner = caseowneruserinfor.iWD_Alias_Case_Owner__c;
     
     // check for status and SRCL Transportation record type and case owner and case creator alias
        if ((a.STATUS == 'Awaiting Internal Response'&& a.RecordTypeID == '012300000004rDZ')&& 
            (casecreatoriwdalias =='CAS' ||casecreatoriwdalias =='TASR/P1')&& 
                 (iWdAliasCaseOwner == 'DISP'|| iWdAliasCaseOwner == 'RCC'))  {
       a.IWD_Testing__c = 'trigger 2 enter the loop'; 
          }// status 'internal response'
                   
   if ((a.STATUS == 'Closed'&& a.RecordTypeID == '012300000004rDZ')&& 
            (MVCowner =='CAS' ||MVCowner =='TASR/P1')&& 
                 (iWdAliasCaseOwner == 'DISP'|| iWdAliasCaseOwner == 'RCC'))  {
       a.IWD_Testing__c = 'trigger2 working!!'; 
       a.ownerid = creatorid;  
       a.status = 'Awaiting internal response';   
        }// status 'closed'
                    } //if case owner 
      }// FOR LOOP
} // EOF

  • September 29, 2010
  • Like
  • 0

Field is not writeable:Invoice__c.Id

 

public class SampleAcc {

   static testMethod void testAccTrigger(){
  
 Pricebook2 s = [select id from Pricebook2 where IsStandard = true];  
  
 // create the product
    Product2 p1 = new Product2(
        name='Test Product 1',
        IsActive=true,
        Description='My Product',
        ProductCode='12345'
    );
    insert p1; 
   
    PricebookEntry pbe1 = new PricebookEntry(
        Pricebook2Id=s.id,
        Product2Id=p1.id,
        UnitPrice=0.00,
        IsActive=true,
        UseStandardPrice=false
    );
    insert pbe1;  
   
 Opportunity opp1 = new Opportunity(Name='ww',StageName='Qualification',CloseDate=date.today());
 insert opp1;
  
 OpportunityLineItem oli = new OpportunityLineItem();
 oli.Quantity = 1;
    oli.TotalPrice = 1;
    oli.PricebookEntryId = pbe1.id;
    oli.OpportunityId = opp1.id;   
    insert oli; 
 
 Invoice__c inv =new Invoice__c();
 inv.Id=opp1.id;
 inv.name = 'ww';
 insert inv;
  
   Accomodation__C acc = new Accomodation__C();
   acc.name='ww';

   Test.startTest();
   insert acc;
   Test.stopTest();
 }
}

 

shows error in this line

inv.Id=opp1.id;

Field is not writeable:Invoice__c.Id

 

am new to apex .please solve it

Hi

 

I was looking at if there are any good practices in using triggers.

 

Say, should I slice down all the code in a trigger and move it across into a class/controller ?

 

If I were to use more of the trigger's features like trigger.oldmap or trigger.newmap or trigger.new or trigger.old.  Is it still a good practice to still move these into the controllers (through assignments) to functions?

 

If you think that those are not good practices, please do let me know.

 

This question is in regard with long term maintenance perspective. 

There is a very important use case that requires callouts in triggers. The ideal way to validate data entery with an external service would be in a trigger. This requires a callout that is not async. It would be great if salesforce could support this use case!!

 

 

  • September 10, 2010
  • Like
  • 0

Hi Sir,

 

I have created an apex test class the covers four trigger named: (1) updaterequestowner (2) change_opps (3) initialstage (4) previousstage . After doing Run All Test i have the following code coverage for the following trigger. Although all of them are more than 1%.

 

Trigger Name                           Coverage %

UpdateResourceReqDates  75

DefaultTitle                               50

updaterequestowner             100

AccountDuplicateTrigger       80

ContactDuplicateTrigger      100

change_opps                          66

initialstage                              100

previousstage                         75

 

 

 

 

But when i try deploying them in production an error appears for each of the trigger. However in sandbox it shows more than 1%.

 

 

previousstage   Test coverage of selected Apex Trigger is 0%, at least 1% test coverage is required
updaterequestowner   Test coverage of selected Apex Trigger is 0%, at least 1% test coverage is required
initialstage   Test coverage of selected Apex Trigger is 0%, at least 1% test coverage is required

 

Here, is the test class:

 

@isTest

private class TriggerTests {
            
    public static testmethod void testTrigger() {
       Pre_Sales_Request__c psrc=new Pre_Sales_Request__c( name = 'a' );
       insert psrc;
       psrc.name = 'b';
       update psrc;  

    }
}

 

 

am i missing something else?? please help...its very urgent...

  • September 09, 2010
  • Like
  • 0

I'm trying to catch a soql query governor limit and display using ApexPages.Message, but it doesn't display the message correctly in my VF page.

 

Here is my code:

 

<apex:page standardController="Project_Request__c" extensions="ProjectRequestExceptionsExtensionVF" tabStyle="Project_Updates__tab">
	<apex:sectionHeader title="Project Request Exceptions:" subtitle="{!UserName}" />
	<apex:pageMessages />
	<apex:pageMessage title="Q: What is the purpose of this page?" severity="info" strength="2" >
		<apex:outputPanel layout="block">A: This page will alert you to any of your Projects that need reviewing and updating.  In addition to routinely monitoring your Projects in Salesforce, this page should make it easier to quickly identify Projects that need attention.</apex:outputPanel>
	</apex:pageMessage>
	<apex:form id="pageForm">
    	<apex:pageBlock >
    		<apex:pageBlockTable value="{!Projects}" var="prj" id="theTable1" rowClasses="odd,even">
    			<apex:column >
    				<apex:facet name="header">
    				
    				</apex:facet>
    				<apex:commandLink action="{!URLFOR($Action.Project_Request__c.Edit, prj.Id, [retURL=URLFOR('/apex/vfProjectRequestExceptions')],true)}" value="Edit" />
    			</apex:column>
    			<apex:column >
                	<apex:facet name="header">
                    	Project Request #
                	</apex:facet>
                	<apex:outputLink value="/{!prj.Id}" >{!prj.Name}</apex:outputLink>
            	</apex:column>
            	<apex:column >
            		<apex:facet name="header">
            			Opportunity Name
            		</apex:facet>
            		<apex:outputLink value="/{!prj.Opportunity__r.Id}" >{!prj.Opportunity__r.Name}</apex:outputLink>
            	</apex:column>
            	<apex:column >
            		<apex:facet name="header">
            			Exception Report - Message 1
            		</apex:facet>
            		<apex:outputText value="{!prj.Exception_Report_Message_1__c}" />
            	</apex:column>
            	<apex:column >
            		<apex:facet name="header">
            			Exception Report - Message 2
            		</apex:facet>
            		<apex:outputText value="{!prj.Exception_Report_Message_2__c}" />
            	</apex:column>
    		</apex:pageBlockTable>
    	</apex:pageBlock>
    </apex:form> 
</apex:page>

 

public class ProjectRequestExceptionsExtensionVF {
	
	private List<Project_Request__c> projs;
	private String userFirstName;
	private String userLastName;

	public ProjectRequestExceptionsExtensionVF(ApexPages.StandardController stdController) {
		userFirstName = userinfo.getFirstName();
		userLastName = userinfo.getLastName();
	}
	
	public List<Project_Request__c> getProjects() {
			try {
				projs = [Select Id, Name, Opportunity__r.Id, Opportunity__r.Name, Exception_Report_Message_1__c, Exception_Report_Message_2__c,
							Exception_Report_Actual_Start_Date__c, Exception_Report_Opp_Exp_Start_Date__c From Project_Request__c Where 
							(Exception_Report_Actual_Start_Date__c = 1 OR Exception_Report_Opp_Exp_Start_Date__c = 1 OR 
							Exception_Report_Post_Consulting_Call__c = 1 OR Exception_Report_Pricing_Required__c = 1 OR 
							Exception_Report_Report_Due_Date__c = 1 OR Exception_Report_Survey_Sent__c = 1) AND (Opportunity__r.StageName != 'Closed Lost' OR
							Opportunity__r.StageName != 'Rejected' OR Opportunity__r.StageName != 'Cancelled') AND Project_Status__c != 'Cancelled' AND 
							My_Project__c = 1 AND Opportunity__r.CreatedDate > 2009-11-01T23:01:01+01:00];
						
				return projs;
			}
			catch (Exception ex) {
				ApexPages.Message errMsg = new ApexPages.Message(ApexPages.Severity.ERROR, ex.getMessage());
				ApexPages.addMessage(errMsg);
				return null;	
			}
	}
	
	public String getUserName() {
		
		String strName = 'User - ' + userFirstName + ' ' + userLastName;
		
		return strName;
	}

	static testMethod void test() 
    {	
    	RecordType testRecordType = [SELECT	id, Name, DeveloperName FROM RecordType WHERE	Name = 'Billable Project'];

		Opportunity opp = new Opportunity(Name = 'Acct Name - Test Opportunity A2', CloseDate = System.today(), Clients_Expected_Start_Date__c = system.today() + 1, StageName = 'Project Request', RecordType = testRecordType, Probability = 10);
		insert opp;
		
		Project_Request__c pr = new Project_Request__c(Opportunity__c = opp.Id, Department__c = 'Information Technology');
		insert pr;
		
        ApexPages.StandardController ctl = new ApexPages.StandardController(pr);
        ProjectRequestExceptionsExtensionVF Ctrl = new ProjectRequestExceptionsExtensionVF(ctl);
        Ctrl.getProjects();
        Ctrl.getUserName();
    }
}

 

If the query returns more than 1000 records, I want to catch the error and display at the top of the VF page that the query limit has been exceeded.  I can put in a limit clause on the query to a 1000, but can't I catch the error?

Hello,

 

I have to make a comparison in an if statement that takes two date time field values (Say , createdDate and LastModifiedDate) from two different records. These are values from Historical tables taht track field changes so in essence I am trying to see if tw ofield changes on these two records were made in the same minute.

 

So need a way to take these two date times from these records and see if they have been edited/created within the same minute. 

 

May be an easy fix but I cannot find anything in DateTime documentation.

 

Thank You.!

  • September 07, 2010
  • Like
  • 0

As far as I can tell, there is no way to natively iterate through more than 10,000 records without using an @future method or an action poller from a Visualforce page. There is a page documenting a for loop which uses QueryMore but as far as I can tell that does not actually work with > 10,000 records.

 

So, if I want to construct a json String including my 40,000 records what should do and output it to a Visualforce page what should I do?

 

It seems I have the following options;

 

(1) Asynchronously construct a Blob with a list of Strings as each reaches the maximum String size. The problem then? No way to save the blob...

 

(2) Create a text file via APEX that is not dependent on a VF page to store the data? But I don't think you can do this via a VF page (cannot be generated asyncronously) or text file (no idea how to do this)...

 

(3) Export the information to another webservice, convert it into a text file, bring it back in as a Static Resource, read the contents, in from the text file (seems possible).

 

(4) Create an action poller which gradually brings in the information I need for my page (will not be available on load and probably will require multiple rerenders which could make things ugly).

 

 

Anyone have more and/or better ideas or care to recommend one of the above?  Sample code also greately aprpeciated....

 

I have achieved 100% testing on my classes and trigger, but 0% for the system provided classes XMLDom and StartHere.  I have seen some ambiguous posts about this, but have not found source code I can download to simply test these classes.  Is there a simple solution to this issue.  This problem must come up for everyone who goes to deploy their first application; it seems logical for SalesForce to provide the test code if the classes are automatically included, so everyone doesn't have to solve the same problem over and over again.  Thanks for your help.

  • July 12, 2010
  • Like
  • 0

is there select *  from object in SOQL?  "*" is what I am looking for. I dont want to write out every column.

I am getting this error when this method is run.Specifically the remove(). I tried deepcloning a copy, and removing that. Doesn't work. Any solutions ???

 

System.FinalException: Collection is read-only

 

private void createExcludeList(){
            
            Map<String, Schema.SObjectField> fieldmap1 = Schema.SObjectType.Account.fields.getMap();

            List<String> fieldExcludeList = new List<String> {
                'LastModifiedDate', 'LastActivityDate', 'SystemModstamp'};
    
            for(integer i=0; i<(fieldmap1.size()-fieldExcludeList.size()); i++)
                fieldmap1.remove(fieldExcludeList[i]);      //LINE THAT IS CAUSING THE ERROR

}

 

 

This code: 

 

 

		  String s = (String) myValueHolder;
		  System.debug('val: ' + s );
		  if (s != null) {
			  String[] frontBack = s.split('.');
			  System.debug('FB:' + frontBack.size());
			  if(frontBack.size() > 1)
			  {
		  		System.debug('WOO I made it');
			  }

 

 

Works fine the first time I run it on a page. However, every subsequent time the split returns a list with 0 elements.

 

For instance, here is a selection from the debug log:

 

 

12:53:26.175|USER_DEBUG|[16,5]|DEBUG|val: 920.0  <===  has a period!
12:53:26.175|METHOD_EXIT|[16,5]|debug(ANY)
12:53:26.175|METHOD_ENTRY|[18,18]|String.split(String)
12:53:26.175|METHOD_EXIT|[18,18]|split(String)
12:53:26.175|METHOD_ENTRY|[20,6]|System.debug(String)
12:53:26.175|METHOD_ENTRY|[20,27]|LIST:String.size()
12:53:26.175|METHOD_EXIT|[20,27]|size() 
12:53:26.175|USER_DEBUG|[20,6]|DEBUG|FB:0  <=== but zero elements in the resulting list
12:53:26.175|METHOD_EXIT|[20,6]|debug(ANY)
12:53:26.175|METHOD_ENTRY|[21,9]|LIST:String.size()

 

Any ideas?  I've tried saving it to a list, array, initializing the list elsewhere but nothing seems to change the simple fact that the split method doesn't work.