• magandrez
  • NEWBIE
  • 75 Points
  • Member since 2011
  • Software Engineer
  • BiiT Oy


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

Hi there,

 

I'm trying to create test coverage for a trigger over User object, soI need to create a User to fire the trigger. I coded a test class following this: http://www.salesforce.com/us/developer/docs/apexcode/index_Left.htm#StartTopic=Content/apex_dml_non_mix_sobjects.htm?SearchType

 

This is how it looks like:

 

public class UserTriggerHandlerTest {
 
        @isTest (seeAllData=true)
        static void testUserCreate(){
               
                // Setup test data
                // This code runs as the system user
                Profile p = [SELECT Id
                             FROM Profile
                             WHERE Name='Portal User'];
 
                Profile p2 = [SELECT Id
                              FROM Profile
                              WHERE Name='System Administrator'];
                 
                User u = new User(Alias = 'custPort', Email='customer@portal.com',
                EmailEncodingKey='UTF-8', LastName='Portal', LanguageLocaleKey='en_US',
                LocaleSidKey='en_US', ProfileId = p.Id,
                TimeZoneSidKey='America/Los_Angeles', UserName='customer@portal.com');
               
                User u2 = new User(Alias = 'admn', Email='admin@test.com',
                EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
                LocaleSidKey='en_US', ProfileId = p2.Id,
                TimeZoneSidKey='America/Los_Angeles', UserName='customer@portal.com');
               
                System.runAs(u2) {
               
                        insert u;
               
                }
       
        }
}

 



The test fails with the following message:

FATAL_ERROR System.DmlException: Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: []
FATAL_ERROR Class.UserTriggerHandlerTest.testUserCreate: line 23, column 1

 

Any ideas? Does anyone know how to avoid this or any workaround to do test coverage for a trigger over User?

 

Thanks.

 

MGA.

Hi,

 

I'm developing a visualforce page where I need to support translations. My approach is to create Custom Labels and use the "language" attribute in apex page to provide the language string.

 

 

<apex:page controller="MyController"  language="{!language}">

...


<apex:pageBlock title="{!$Label.My_Label}" mode="detail"> 

...

 

The language string gets its value in the controller (actually is a value parsed from an XML).

 

My question is:

 

How can I generate the Visualforce page so that the header and sidebar will have the standard language value (the one selected by the user) but the rest of the labels in the VF will be translated according to the parameter passed from the controller?

 

I will appreciate any kind of aproach that is sustainable (not hardcoding the labels in the controller). Many thanks.

 

MGA

Hi all,

 

I need to trim an XML from unnecesary elements before parsing it (due to its size). In order to do that I had the idea of loop over a given list of elements I don't need and using replaceAll() for that.

 

Once I found what I thought is the right regular expression (testing it in regex engines online with a given XML) I use it in my code but Salesforce gives me the error 'Regex too complicated'

 

The regular expression I came up with is this:

 

<(TAG)\b[^>]*>(.*?)</\1>

 

 This regular expression matches an entire XML ELEMENT with its value (it includes ELEMENTS with attributes) and its closing tag. 

 

I tried this regex in this engine: regex online engine tool

 

This is the text I use for testing purposes:

 

<BLOCK_SUMMARY>
     <COUNT>1</COUNT>
     <TOTAL>
	<AMOUNT SIGN="+" VAT="INCLUDED">123</AMOUNT>
     </TOTAL>
     <TEST>Testing</TEST>
</BLOCK_SUMMARY>

 Using the engine above linked with the regex I came up with the engine gives as a result (underlined) the match. This result is what I use in a simple piece of Apex to trim the whole XML. Something like this:

 

...

String[] elementsToDelete = new String[]{'TEST'};
String result = null;
    	
for(String s:elementsToDelete){
    		
   result = xml.replaceAll('<('+s+')\b[^>]*>(.*?)<\\1>','');
} 

...

Notice I had to change the grouping /\1 for \\1 to be able to save this code in Salesforce and following java.util.regex Pattern Class (the one that SF is based in according to the documentation). (More info about groupings here)

 

I know this is a kind of very specific problem, but I tried to provide all information I have here. Can anyone spot what is the problem with the regex? Is it even possible to write a regex like that and Apex regex engine read it?

 

Any help is very welcome.

 

MGA

 

 

 

Hi all,

 

I developed a functionality that makes use of HttpRequest class. In order to test it I used HttpCalloutMock. This functionality is withing a @future (callout=true) method. I developed the test classes following the documentation for HttpCalloutMock. The tests (2) pass in sandbox, but when deploying to production they both give error System.NullPointerException (apparently the HttpResponse is null) in the assertion line. Here is the code for the tests and the implementations for HttpCalloutMock within the same Test class:

 

@isTest
global class TrustCalloutTest {
    
    global class TrustCalloutMockBasicCallout implements HttpCalloutMock {
        
        global HTTPResponse respond(HTTPRequest req) {
            
            HttpResponse res = new HttpResponse();
            res.setBody('TEST');
            res.setStatusCode(200);
            return res;
        }
    }
    
    global class TrustCalloutMockRequestKey implements HttpCalloutMock {
        
        global HTTPResponse respond(HTTPRequest req) {
            
            HttpResponse res = new HttpResponse();
            res.setBody('RECEIVED');
            res.setStatusCode(200);
            return res;
        }
    }
    
    static testmethod void testCalloutRequireKey() {
    	
        HttpResponse res; 
        Test.setMock(HttpCalloutMock.class, new TrustCalloutMockRequestKey());
        res = TrustCallout.requestTransferKey('BLAH','https://beta2.trustpoint.fi/API/requirekey.php');
        System.assertEquals(200, res.getStatusCode());
    }
    static testmethod void testCalloutBasicCallout(){
         
    	HttpResponse res;
        Test.setMock(HttpCalloutMock.class, new TrustCalloutMockBasicCallout()); 
        res = TrustCallout.basicCallout('BLAH','https://beta2.trustpoint.fi/API/committransfer.php');
        System.assertEquals(200, res.getStatusCode());    
    }
}

 

The actual callout works normally, and it also follows the documentation.

 

Endpoints were added at both sides (production and sandbox).

 

Any idea of what is going on?

 

Thanks.

 

MGA.

 

 

Hi,

 

I have a ready made template for a .doc document that creates .doc documents the way the user wants. Now I they want to create many documents following this template, so I decided to create it using Javascript for VF and then retrieving the list of records they need, loop over those records creating the document that will go attached under a certain record. 

 

The code looks like this:

 

...

I retrieve here the list I need...

...

    //Create the attachment
    Attachment attach = new Attachment();
    attach.IsPrivate = false;
    //location contains the Id of the record where I want to attach de       document.
    attach.ParentId = location;
    attach.Name = 'A name.doc';
    Blob b;
    String body;											 
    
    //Loop over the records passing the Id to the template
    //and generating the final document
    for(Service_Reservation__c serv:services){

    	PageReference document = Page.getServiceOrder;
    	document.getParameters().put('id',serv.Id);

    	//Incremental body of the document.
        //for this I need a String, a Blob cannot be used
        //with arithmetics
   
        document.setRedirect(false);

        body += document.getContent().toString();
    	
    }
    //Turn the string into Blob to be attached under the desired record
    b = Blob.valueOf(body);
    attach.body = b;
    insert attach;    

 

The problem is that, given a list of service reservations...it creates a document attached with just the first document on it. I tried using setRedirect as false, but doesn't work. 

 

Any insights on why I cannot get a document with all the documents well created in the attachment?

 

Thanks!

Hi,

 

I have a ready made template for a .doc document that creates .doc documents the way the user wants. Now I they want to create many documents following this template, so I decided to create it using Javascript for VF and then retrieving the list of records they need, loop over those records creating the document that will go attached under a certain record. 

 

The code looks like this:

 

...

I retrieve here the list I need...

...

    //Create the attachment
    Attachment attach = new Attachment();
    attach.IsPrivate = false;
    //location contains the Id of the record where I want to attach de       document.
    attach.ParentId = location;
    attach.Name = 'A name.doc';
    Blob b;
    String body;											 
    
    //Loop over the records passing the Id to the template
    //and generating the final document
    for(Service_Reservation__c serv:services){

    	PageReference document = Page.getServiceOrder;
    	document.getParameters().put('id',serv.Id);

    	//Incremental body of the document.
        //for this I need a String, a Blob cannot be used
        //with arithmetics

        body += document.getContent().toString();
    	
    }
    //Turn the string into Blob to be attached under the desired record
    b = Blob.valueOf(body);
    attach.body = b;
    insert attach;    

 

The problem is that, given a list of service reservations...it creates a document attached with just the first document on it.

 

Any insights on why I cannot get a document with all the documents well created in the attachment?

 

Thanks!

Hi,

 

I got an error when executing the test method I wrote for a trigger. I saw many entries in the discussion boards about this, but no concrete answer and nothing I can make an abstraction and apply it to my problem.

 

 

I have a trigger where I create posts to a a specific group if the Opportunity is closed. The trigger looks like this:

 

trigger chatterUpdateTrigger on Opportunity (before update) {
	
	Id parentPostId = [SELECT Id 
					   FROM CollaborationGroup 
					   WHERE Name=:'All Group'].Id;
					   
	Id RecordType1= [SELECT Id 
								 FROM RecordType 
								 WHERE SOBJECTTYPE=:'Opportunity' 
								 AND DeveloperName=:'Record Type 1'].Id;
								 
	Id RecordType2= [SELECT Id 
						FROM RecordType 
						WHERE SOBJECTTYPE=:'Opportunity' 
						AND DeveloperName=:'Record Type 2'].Id;
	
	List<FeedPost> listPosts = new List<FeedPost>();
	
    for (Opportunity opp: Trigger.new){
    	
    	//List<RecordType> listOppRecordTypes = [SELECT DeveloperName FROM RecordType WHERE Id=:opp.RecordTypeId AND DeveloperName=:'Record Type 2' AND DeveloperName=:'Record Type 2'];
    	Opportunity beforeUpdate = System.Trigger.oldMap.get(opp.Id);

    		if(opp.RecordTypeId == RecordType1){
    			
    			if(beforeUpdate.StageName != opp.StageName && opp.StageName=='We WON!'){
    				
    				FeedPost post = new FeedPost(ParentId= parentPostId,Body='The opportunity ' +beforeUpdate.Name+ ' with a value of '+beforeUpdate.Amount+'€ has been won!');            
	        		listPosts.add(post);
	        		
    			}
    		}else{
    			
    			if(opp.RecordTypeId == RecordType2){
			
					if(beforeUpdate.StageName != opp.StageName && opp.StageName=='We WON!'){
	    				
	    				FeedPost post = new FeedPost(ParentId=parentPostId,Body='The opportunity ' +beforeUpdate.Name+ ' with a value of '+beforeUpdate.Amount_Quotation_Price__c+'€ has been won!');            
		    			listPosts.add(post);
		        		
    				}
			
    			}
    		} 
	}
	
	try{
		
		insert listPosts;
		
	}catch(Exception ex){
		Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(new String[] {'customer.service@myself.me'});
        mail.setSubject('Chatter Trigger ERROR');
        String body = 'This message was sent automatically from chatterUpdateTrigger from SF. \n'+
        'Apparently there was an error on the insertion of the Chatter Message. This is the exception: \n'+ex;  
        mail.setPlainTextBody(body);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
	}
	
}

 

And this is the test class:

 

@IsTest
 public class testChatterUpdateTrigger{
    
    static testMethod void testChatterUpdateTrigger(){

	
	
	Id RecordType1= [SELECT Id 
								 FROM RecordType 
								 WHERE SOBJECTTYPE=:'Account' 
								 AND DeveloperName=:'Record Type 1'].Id;
								 
	Id RecordType2= [SELECT Id 
						FROM RecordType 
						WHERE SOBJECTTYPE=:'Account' 
						AND DeveloperName=:'Record Type 2'].Id;

							
						
	Account ac1 = new Account(RecordTypeId = RecordType1,
							  Name = 'Test Account 1',
							  CurrencyIsoCode = 'EUR',
							  Industry = 'Test',
							  Account_Type__c = 'Agent',
							  BillingCountry = 'UK',
							  BillingCity = 'London',
							  BillingStreet = 'Aleski 123');
	insert ac1;
	
	Account ac2 = new Account(RecordTypeId = RecordType2,
							  Name = 'Test Account 2',
							  CurrencyIsoCode = 'EUR',
							  Industry = 'Test',
							  Account_Type__c = 'Agent',
							  BillingCountry = 'UK',
							  BillingCity = 'London',
							  BillingStreet = 'Aleski 123');
	
	insert ac2;							  
							  	
	
	Account account1= [SELECT Id,
									 Name
							  FROM Account
							  WHERE Name =: 'Test Account 1'
							  LIMIT 1];

	Account account2= [SELECT Id,
								 Name
							  FROM Account
							  WHERE Name =: 'Test Account 2'
							  LIMIT 1];

	Id oppRecordType1= [SELECT Id 
								 FROM RecordType 
								 WHERE SOBJECTTYPE=:'Opportunity' 
								 AND DeveloperName=:'Record Type 1'].Id;
								 
	Id oppRecordType2= [SELECT Id 
						FROM RecordType 
						WHERE SOBJECTTYPE=:'Opportunity' 
						AND DeveloperName=:'Record Type 2'].Id;								  							  
	
	Opportunity oppRecType1= new Opportunity(RecordTypeId = oppRecordType1,
											 Name = 'Test 1',
											 AccountId = account1.Id,
											 CurrencyIsoCode = 'EUR',
											 Amount = 100,
											 CloseDate = system.today(),
											 StageName = 'Pre-Study');

	insert oppRecType1;
	
	Opportunity opRec1= [SELECT StageName
						   FROM Opportunity
						   WHERE Name =:'Test 1'
						   LIMIT 1];

	Opportunity oppRecType2= new Opportunity(RecordTypeId = oppRecordType2,
										 Name = 'Test 2',
										 AccountId = account2.Id,
										 End_Customer_Country__c = 'UK',
										 Industry__c = 'Auto',
										 CurrencyIsoCode = 'EUR',
										 Vehicle_Types_pick_several__c = 'Test',
										 No_of_Vehicles__c = 0,
										 Load_weight__c = 0,
										 Lifting_height_mm__c = 0,
										 Operating_Conditions__c = 'Outside',
										 Quotation_Price__c = 1000,
										 Scope__c = 'Other',
										 StageName = 'Pre-Study',
										 Quotation_valid_until__c = system.today(),
										 CloseDate = system.today(),
										 Navigation__c = 'Other');

	insert oppRecType2;
	
	Opportunity opRec2= [SELECT StageName
						  FROM Opportunity
						  WHERE Name = 'Test 2'
						  LIMIT 1];

	List<Opportunity> listOpp = new List<Opportunity>();
	listOpp.add(opRec1);
	listOpp.add(opRec2);
	
	Integer feedEntriesBefore = [SELECT COUNT() 
					   FROM CollaborationGroup 
					   WHERE Name=:'All Group'];

	test.startTest();					   

	oppKoti.StageName = 'We WON!';
	update opRec1;
	
	AGVopp.StageName = 'We WON!';
	update opRec2;
	
    Integer feedEntriesAfter = [SELECT COUNT()
						   		FROM CollaborationGroup
						   		WHERE Name=:'All Group'];

	system.assertNotEquals(feedEntriesBefore, feedEntriesAfter);
	
	test.stopTest();

	}
	
}

 And I got this error when executing tests:

 

System.DmlException: Update failed. First exception on row ' with id XXXXXXXXXXXXX: first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, chatterUpdateTrigger: excecution of BeforeUpdate ON LINE 115 -> that is the update of opRec1 in the test method.

 

Does anyone know exactly what is happening and why?

Hello,

 

I have a WS that changes the value of one field using Javascript. something like this:

 

WS:

 

global class fromMSStatusAToB{

WebService static void changeStatus(String id, String status) {

    // update a status field.             
}
}

 In the layout I lifted a button with this code that works normally:

 

{!REQUIRESCRIPT("/soap/ajax/15.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/15.0/apex.js")} 
sforce.apex.execute("fromMSStatusAToB","changeStatus",{id: "{!Process_Cost__c.Id}" ,status:"Accepted"}); 
alert('MS Status updated'); 
window.location.reload(true);

 This works normally. But now the requirements changed and I need to put this on a custom VF page. To meet that requirements I put in the VF the following code to call the Apex WS:

 

<script src="/soap/ajax/15.0/connection.js" type="text/javascript"</script>
<script src="/soap/ajax/15.0/apex.js" type="text/javascript"></script>

<script>
function foundryFromCreatedToAccepted(){
sforce.apex.execute("fromMSStatusAToB","changeStatus",{id: "{!Process_Cost__c.Id}" ,status:"Accepted"}); 
}

</script>

 And I call this function with a command link like this:

 

<apex:commandLink value="Change Status to Accepted" onclick="foundryFromCreatedToAccepted()" />  

 

The problem is that all code is saved, but it doesn't seem to work. Do you have any ideas why it doesn't work? Any workaround? How can I debug this kind of problems?

 

Many thanks,

 

MGA.

Hello,

 

I have a WS that changes the value of one field using Javascript. something like this:

 

WS:

 

global class fromMSStatusAToB{

WebService static void changeStatus(String id, String status) {

    // update a status field.             
}
}

 In the layout I lifted a button with this code that works normally:

 

{!REQUIRESCRIPT("/soap/ajax/15.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/15.0/apex.js")} 
sforce.apex.execute("fromMSStatusAToB","changeStatus",{id: "{!Process_Cost__c.Id}" ,status:"Accepted"}); 
alert('MS Status updated'); 
window.location.reload(true);

 This works normally. But now the requirements changed and I need to put this on a custom VF page. To meet that requirements I put in the VF the following code to call the Apex WS:

 

<script src="/soap/ajax/15.0/connection.js" type="text/javascript"</script>
<script src="/soap/ajax/15.0/apex.js" type="text/javascript"></script>

<script>
function foundryFromCreatedToAccepted(){
sforce.apex.execute("fromMSStatusAToB","changeStatus",{id: "{!Process_Cost__c.Id}" ,status:"Accepted"}); 
}

</script>

 And I call this function with a command link like this:

 

<apex:commandLink value="Change Status to Accepted" onclick="foundryFromCreatedToAccepted()" />  

 

The problem is that all code is saved, but it doesn't seem to work. Do you have any ideas why it doesn't work? Any workaround? How can I debug this kind of problems?

 

Many thanks,

 

MGA.

Hi,

 

I need to retrieve some data using a nested SOQL, but I can't get the needed data. The SOQL is the following:

 

SELECT (SELECT Name,
               Unit_Price__c, 
               Quantity__c, 
               Time__c 
        FROM Valitut_Tuotteet__r)
FROM Service_Reservation__c 
WHERE Room_Reservation__c =: roomRes

 I need to extract the Name, Unit_Price__c, Quantity__c and Time__c and show them on a table (apex:repeat). Do you have any idea of how can I access that data?

 

Using <apex:repeat> and retrieving the fields doesn't work, I guess is because the data structure that the query creates is not a simple List<Service_Reservation__c>. 

 

Any idea on this?

 

Greetings,

 

MGA.

Hi,

 

This is a very simple task. For some reason I cannot show on a VF page the value that I calculated in the controller side. Morever, it doesn't show anything on the debug, seems it doesn't get in the calculation. Here is the code:

 

Declaring the variables involved:

 

public List<Selected_Product__c> total{get;set;}
public decimal totalNet {get;set;}

 Getting all the rows related:

 

public generateServiceOrder(ApexPages.StandardController controller) {
 String servOrder= ApexPages.currentPage().getParameters().get('id');

 total = [SELECT Total_Gross__c
          FROM Selected_Product__c
          WHERE Service_Reservation__c =:servOrder];                                      
        
}

 Preparing the result to be retrieved by the VF:

 

public decimal getTotalNet(){
    
        totalNet = 0.0;
        for(Selected_Product__c allSelected:total){
        
            totalNet+=allSelected.Total_Gross__c;
        
        }
        return totalNet;
}

 

The VF:

 

<apex:outputText value="EUR {!totalNet}"/>

 

And this is the resulting debug. As you can see, it never gets into getTotalNet, and totalNet never gets populated.

 

24.0 APEX_CODE,FINEST;APEX_PROFILING,INFO;CALLOUT,INFO;DB,INFO;SYSTEM,DEBUG;VALIDATION,INFO;VISUALFORCE,INFO;WORKFLOW,INFO
14:10:02.115 (115261000)|EXECUTION_STARTED
14:10:02.115 (115297000)|CODE_UNIT_STARTED|[EXTERNAL]|066R00000009cJp|VF: /apex/getServiceOrder
14:10:02.121 (121397000)|CODE_UNIT_STARTED|[EXTERNAL]|01pR0000000ER63|generateServiceOrder 
14:10:02.121 (121429000)|SYSTEM_MODE_ENTER|true
14:10:02.122 (122456000)|METHOD_ENTRY|[1]|01pR0000000ER63|generateServiceOrder.generateServiceOrder()
14:10:02.122 (122465000)|STATEMENT_EXECUTE|[1]
14:10:02.122 (122556000)|SYSTEM_MODE_ENTER|false
14:10:02.122 (122575000)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:5
14:10:02.122 (122584000)|STATEMENT_EXECUTE|[1]
14:10:02.122 (122596000)|SYSTEM_MODE_EXIT|false
14:10:02.122 (122603000)|METHOD_EXIT|[1]|generateServiceOrder
14:10:02.122 (122746000)|VARIABLE_SCOPE_BEGIN|[8]|this|generateServiceOrder|true|false
14:10:02.122 (122777000)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:20
14:10:02.122 (122791000)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:20
14:10:02.122 (122797000)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:20
14:10:02.122 (122808000)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:20
14:10:02.122 (122827000)|VARIABLE_ASSIGNMENT|[8]|this|{}|0x30964412
14:10:02.122 (122841000)|VARIABLE_SCOPE_BEGIN|[8]|controller|ApexPages.StandardController|true|false
14:10:02.122 (122995000)|VARIABLE_ASSIGNMENT|[8]|controller|"StandardController [null]"|0x594f12a9
14:10:02.123 (123008000)|STATEMENT_EXECUTE|[1]
14:10:02.123 (123014000)|SYSTEM_MODE_ENTER|false
14:10:02.123 (123019000)|HEAP_ALLOCATE|[3]|Bytes:5
14:10:02.123 (123027000)|STATEMENT_EXECUTE|[3]
14:10:02.123 (123038000)|STATEMENT_EXECUTE|[4]
14:10:02.123 (123043000)|STATEMENT_EXECUTE|[5]
14:10:02.123 (123048000)|STATEMENT_EXECUTE|[6]
14:10:02.123 (123054000)|SYSTEM_MODE_EXIT|false
14:10:02.123 (123062000)|SYSTEM_MODE_ENTER|false
14:10:02.123 (123067000)|HEAP_ALLOCATE|[6]|Bytes:5
14:10:02.123 (123071000)|STATEMENT_EXECUTE|[8]
14:10:02.123 (123074000)|STATEMENT_EXECUTE|[9]
14:10:02.123 (123096000)|SYSTEM_METHOD_ENTRY|[9]|ApexPages.currentPage()
14:10:02.123 (123158000)|HEAP_ALLOCATE|[9]|Bytes:69
14:10:02.123 (123166000)|SYSTEM_METHOD_EXIT|[9]|ApexPages.currentPage()
14:10:02.123 (123186000)|SYSTEM_METHOD_ENTRY|[9]|System.PageReference.getParameters()
14:10:02.123 (123201000)|HEAP_ALLOCATE|[9]|Bytes:44
14:10:02.123 (123237000)|SYSTEM_METHOD_EXIT|[9]|System.PageReference.getParameters()
14:10:02.123 (123245000)|HEAP_ALLOCATE|[9]|Bytes:2
14:10:02.123 (123266000)|SYSTEM_METHOD_ENTRY|[9]|MAP.get(ANY)
14:10:02.123 (123283000)|HEAP_ALLOCATE|[9]|Bytes:15
14:10:02.123 (123289000)|SYSTEM_METHOD_EXIT|[9]|MAP.get(ANY)
14:10:02.123 (123298000)|VARIABLE_SCOPE_BEGIN|[9]|servOrder|String|false|false
14:10:02.123 (123309000)|VARIABLE_ASSIGNMENT|[9]|servOrder|"a0HR0000006AIgJ"
14:10:02.123 (123313000)|STATEMENT_EXECUTE|[11]
14:10:02.123 (123320000)|HEAP_ALLOCATE|[11]|Bytes:233
14:10:02.123 (123337000)|HEAP_ALLOCATE|[11]|Bytes:7
14:10:02.123 (123362000)|HEAP_ALLOCATE|[11]|Bytes:-4
14:10:02.123 (123369000)|HEAP_ALLOCATE|[11]|Bytes:7
14:10:02.123 (123374000)|HEAP_ALLOCATE|[11]|Bytes:15
14:10:02.123 (123388000)|HEAP_ALLOCATE|[11]|Bytes:-4
14:10:02.123 (123897000)|SOQL_EXECUTE_BEGIN|[11]|Aggregations:0|select Product__r.Name, Product_Content__c, Service_Time__c, Quantity__c, Unit_Price__c, Total_Net__c from Selected_Product__c where (Service_Reservation__c = :tmpVar1 and Billing_Category__c = :tmpVar2) order by Service_Time__c desc
14:10:02.144 (144334000)|SOQL_EXECUTE_END|[11]|Rows:2
14:10:02.144 (144365000)|HEAP_ALLOCATE|[11]|Bytes:12
14:10:02.144 (144390000)|HEAP_ALLOCATE|[11]|Bytes:776
14:10:02.144 (144435000)|HEAP_ALLOCATE|[11]|Bytes:784
14:10:02.144 (144471000)|METHOD_ENTRY|[11]|01pR0000000ER63|generateServiceOrder.__sfdc_servingorder(LIST)
14:10:02.144 (144511000)|HEAP_ALLOCATE|[3]|Bytes:20
14:10:02.144 (144533000)|HEAP_ALLOCATE|[3]|Bytes:20
14:10:02.144 (144546000)|HEAP_ALLOCATE|[3]|Bytes:20
14:10:02.144 (144561000)|HEAP_ALLOCATE|[3]|Bytes:20
14:10:02.144 (144577000)|VARIABLE_ASSIGNMENT|[-1]|this|{}|0x30964412
14:10:02.144 (144658000)|VARIABLE_ASSIGNMENT|[-1]|value|[{"Quantity__c":15,"Product__r":{"Name":"Pieneen nälkään 3","CurrencyIsoCode":"EUR","Id":"a0LR0000002CQ7IMAW"},"CurrencyIsoCode":"EUR","Service_Time__c":"9:45","Product_Content__c":"Janssoninkiusausta\nV (92 more) ...","Product__c":"a0LR0000002CQ7IMAW","Unit_Price__c":3.00,"Id":"a0MR0000002MxGZMA0","Total_Net__c":45.00},{"Quantity__c":12,"Product__r":{"Name":"½ Pv.Kokouspkt I","CurrencyIsoCode":"EUR","Id":"a0LR0000002CQ7YMAW"},"CurrencyIsoCode":"EUR","Service_Time__c":"9:15","Product__c":"a0LR0000002CQ7YMAW","Unit_Price__c":3.00,"Id":"a0MR0000002IdVsMAK","Total_Net__c":36.00}]|0x52bfeda2
14:10:02.144 (144734000)|VARIABLE_ASSIGNMENT|[3]|this.servingorder|[{"Quantity__c":15,"Product__r":{"Name":"Pieneen nälkään 3","CurrencyIsoCode":"EUR","Id":"a0LR0000002CQ7IMAW"},"CurrencyIsoCode":"EUR","Service_Time__c":"9:45","Product_Content__c":"Janssoninkiusausta\nV (92 more) ...","Product__c":"a0LR0000002CQ7IMAW","Unit_Price__c":3.00,"Id":"a0MR0000002MxGZMA0","Total_Net__c":45.00},{"Quantity__c":12,"Product__r":{"Name":"½ Pv.Kokouspkt I","CurrencyIsoCode":"EUR","Id":"a0LR0000002CQ7YMAW"},"CurrencyIsoCode":"EUR","Service_Time__c":"9:15","Product__c":"a0LR0000002CQ7YMAW","Unit_Price__c":3.00,"Id":"a0MR0000002IdVsMAK","Total_Net__c":36.00}]|0x30964412
14:10:02.144 (144764000)|METHOD_EXIT|[11]|01pR0000000ER63|generateServiceOrder.__sfdc_servingorder(LIST)
14:10:02.144 (144775000)|STATEMENT_EXECUTE|[22]
14:10:02.144 (144830000)|HEAP_ALLOCATE|[22]|Bytes:-4
14:10:02.144 (144841000)|HEAP_ALLOCATE|[22]|Bytes:14
14:10:02.144 (144860000)|HEAP_ALLOCATE|[22]|Bytes:-4
14:10:02.145 (145270000)|SOQL_EXECUTE_BEGIN|[22]|Aggregations:0|select Product__r.Name, Product_Content__c, Service_Time__c, Quantity__c, Unit_Price__c, Total_Net__c from Selected_Product__c where (Service_Reservation__c = :tmpVar1 and Billing_Category__c = :tmpVar2) order by Service_Time__c desc
14:10:02.151 (151663000)|SOQL_EXECUTE_END|[22]|Rows:1
14:10:02.151 (151683000)|HEAP_ALLOCATE|[22]|Bytes:8
14:10:02.151 (151701000)|HEAP_ALLOCATE|[22]|Bytes:327
14:10:02.151 (151724000)|HEAP_ALLOCATE|[22]|Bytes:331
14:10:02.151 (151751000)|METHOD_ENTRY|[22]|01pR0000000ER63|generateServiceOrder.__sfdc_addonservices(LIST)
14:10:02.151 (151782000)|HEAP_ALLOCATE|[4]|Bytes:20
14:10:02.151 (151800000)|HEAP_ALLOCATE|[4]|Bytes:20
14:10:02.151 (151825000)|HEAP_ALLOCATE|[4]|Bytes:20
14:10:02.151 (151840000)|HEAP_ALLOCATE|[4]|Bytes:20
14:10:02.151 (151859000)|VARIABLE_ASSIGNMENT|[-1]|this|{"servingorder":"0x6922acb"}|0x30964412
14:10:02.151 (151913000)|VARIABLE_ASSIGNMENT|[-1]|value|[{"Quantity__c":1,"Product__r":{"Name":"Astiat","CurrencyIsoCode":"EUR","Id":"a0LR0000002CQ8EMAW"},"CurrencyIsoCode":"EUR","Service_Time__c":"20:15","Product__c":"a0LR0000002CQ8EMAW","Unit_Price__c":60.00,"Id":"a0MR0000002MxGUMA0","Total_Net__c":60.00}]|0x18dde0dd
14:10:02.151 (151960000)|VARIABLE_ASSIGNMENT|[4]|this.addonservices|[{"Quantity__c":1,"Product__r":{"Name":"Astiat","CurrencyIsoCode":"EUR","Id":"a0LR0000002CQ8EMAW"},"CurrencyIsoCode":"EUR","Service_Time__c":"20:15","Product__c":"a0LR0000002CQ8EMAW","Unit_Price__c":60.00,"Id":"a0MR0000002MxGUMA0","Total_Net__c":60.00}]|0x30964412
14:10:02.151 (151980000)|METHOD_EXIT|[22]|01pR0000000ER63|generateServiceOrder.__sfdc_addonservices(LIST)
14:10:02.151 (151991000)|STATEMENT_EXECUTE|[33]
14:10:02.152 (152002000)|HEAP_ALLOCATE|[33]|Bytes:86
14:10:02.152 (152045000)|HEAP_ALLOCATE|[33]|Bytes:-4
14:10:02.152 (152296000)|SOQL_EXECUTE_BEGIN|[33]|Aggregations:0|select Total_Gross__c from Selected_Product__c where Service_Reservation__c = :tmpVar1
14:10:02.155 (155508000)|SOQL_EXECUTE_END|[33]|Rows:3
14:10:02.155 (155525000)|HEAP_ALLOCATE|[33]|Bytes:16
14:10:02.155 (155544000)|HEAP_ALLOCATE|[33]|Bytes:276
14:10:02.155 (155563000)|HEAP_ALLOCATE|[33]|Bytes:288
14:10:02.155 (155588000)|METHOD_ENTRY|[33]|01pR0000000ER63|generateServiceOrder.__sfdc_total(LIST)
14:10:02.155 (155615000)|HEAP_ALLOCATE|[5]|Bytes:20
14:10:02.155 (155639000)|HEAP_ALLOCATE|[5]|Bytes:20
14:10:02.155 (155663000)|HEAP_ALLOCATE|[5]|Bytes:20
14:10:02.155 (155678000)|HEAP_ALLOCATE|[5]|Bytes:20
14:10:02.155 (155697000)|VARIABLE_ASSIGNMENT|[-1]|this|{"addonservices":"0x956014b3","servingorder":"0x6922acb"}|0x30964412
14:10:02.155 (155742000)|VARIABLE_ASSIGNMENT|[-1]|value|[{"CurrencyIsoCode":"EUR","Id":"a0MR0000002IdVsMAK","Total_Gross__c":40.68},{"CurrencyIsoCode":"EUR","Id":"a0MR0000002MxGUMA0","Total_Gross__c":73.80},{"CurrencyIsoCode":"EUR","Id":"a0MR0000002MxGZMA0","Total_Gross__c":50.85}]|0x60880aa9
14:10:02.155 (155787000)|VARIABLE_ASSIGNMENT|[5]|this.total|[{"CurrencyIsoCode":"EUR","Id":"a0MR0000002IdVsMAK","Total_Gross__c":40.68},{"CurrencyIsoCode":"EUR","Id":"a0MR0000002MxGUMA0","Total_Gross__c":73.80},{"CurrencyIsoCode":"EUR","Id":"a0MR0000002MxGZMA0","Total_Gross__c":50.85}]|0x30964412
14:10:02.155 (155806000)|METHOD_EXIT|[33]|01pR0000000ER63|generateServiceOrder.__sfdc_total(LIST)
14:10:02.155 (155819000)|SYSTEM_MODE_EXIT|false
14:10:02.155 (155837000)|CODE_UNIT_FINISHED|generateServiceOrder 
14:10:02.177 (177507000)|CODE_UNIT_STARTED|[EXTERNAL]|01pR0000000ER63|generateServiceOrder get(servingorder)
14:10:02.177 (177525000)|SYSTEM_MODE_ENTER|true
14:10:02.177 (177542000)|CODE_UNIT_STARTED|[EXTERNAL]|01pR0000000ER63|servingorder
14:10:02.177 (177558000)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:20
14:10:02.177 (177571000)|CODE_UNIT_FINISHED|servingorder
14:10:02.177 (177576000)|CODE_UNIT_FINISHED|generateServiceOrder get(servingorder)
14:10:02.178 (178604000)|CODE_UNIT_STARTED|[EXTERNAL]|01pR0000000ER63|generateServiceOrder get(addonservices)
14:10:02.178 (178614000)|SYSTEM_MODE_ENTER|true
14:10:02.178 (178625000)|CODE_UNIT_STARTED|[EXTERNAL]|01pR0000000ER63|addonservices
14:10:02.178 (178635000)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:20
14:10:02.178 (178643000)|CODE_UNIT_FINISHED|addonservices
14:10:02.178 (178648000)|CODE_UNIT_FINISHED|generateServiceOrder get(addonservices)
14:10:02.196 (196521000)|CODE_UNIT_STARTED|[EXTERNAL]|01pR0000000ER63|generateServiceOrder get(totalNet)
14:10:02.196 (196536000)|SYSTEM_MODE_ENTER|true
14:10:02.196 (196550000)|CODE_UNIT_STARTED|[EXTERNAL]|01pR0000000ER63|totalNet
14:10:02.196 (196564000)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:20
14:10:02.196 (196576000)|CODE_UNIT_FINISHED|totalNet
14:10:02.196 (196581000)|CODE_UNIT_FINISHED|generateServiceOrder get(totalNet)
14:10:02.433 (216222000)|CUMULATIVE_LIMIT_USAGE
14:10:02.433|LIMIT_USAGE_FOR_NS|(default)|
  Number of SOQL queries: 3 out of 100
  Number of query rows: 6 out of 50000
  Number of SOSL queries: 0 out of 20
  Number of DML statements: 0 out of 150
  Number of DML rows: 0 out of 10000
  Number of script statements: 8 out of 200000
  Maximum heap size: 0 out of 6000000
  Number of callouts: 0 out of 10
  Number of Email Invocations: 0 out of 10
  Number of fields describes: 0 out of 100
  Number of record type describes: 0 out of 100
  Number of child relationships describes: 0 out of 100
  Number of picklist describes: 0 out of 100
  Number of future calls: 0 out of 10

14:10:02.433|CUMULATIVE_LIMIT_USAGE_END

14:10:02.216 (216245000)|CODE_UNIT_FINISHED|VF: /apex/getServiceOrder
14:10:02.216 (216251000)|EXECUTION_FINISHED

 

Does anyone know what is the problem in here?. Seems like a pretty straightforward and simple problem.

 

Greetings,

 

MGA

 

Hi all,

 

I have a problem getting the value from an AgreggateResult returned by an SOQL. Here is the code from the SOQL:

 

        total = [SELECT SUM(Total_Net__c)tmp
                 FROM Selected_Product__c
                 WHERE Service_Reservation__c =:servOrder
                 GROUP BY Service_Reservation__c];
              system.debug('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%'+total);    

 That system.debug gives me this: 

 

16:17:01:123 USER_DEBUG [24]|DEBUG|%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%(AggregateResult:{tmp=40.0})

 Which is the value I want to show. In a different method I try to return 'result' as integer this way:

 

    public integer result {get; set;}

...


 public integer getResult(){
    
       integer result;
       for(AggregateResult ar:total){
       
           result = (integer)ar.get('tmp');
       system.debug('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%'+result);
       }
                                     
       return result;
    }

NOTE: When I debug this it never gets to the system.debug, but salesforce allows me to save this code (hence, no syntax errors).

 

And in the VF page I call for result this way:

 

<apex:outputText value="{!result}"/>

 

And no result at all (empty).

 

Do you have any idea of why this is happening?. Any solution?

 

Many thanks,

 

MGA.

Hi all,

 

I have the following code that doesn't generate a proper SOQL sentence. I'm passing a date from a VF page standard date selector, I needed to create a query, but the query doesn't work properly. I think it is because of the Date/Datetime format, but after try all posibilities, it doesn't work as it should (the query doesn't work).

 

public generateRestSched(ApexPages.StandardController controller) {

 

String room = ApexPages.currentPage().getParameters().get('id');
bookingdate = date.parse(ApexPages.currentPage().getParameters().get('date'));
system.debug('###############################'+bookingdate);
 

entries = [SELECT Reservation_Time_Start__c,
   End_Time__c,
   Customer_and_Event_Info__c,
   Booking_Date__c,
   Additional_Information__c,
   Room_del__c
FROM Room_Reservations__c
WHERE Booking_Date__c =:bookingdate
AND Room_del__c=:room];

 

system.debug('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&'+entries);

}

 

 

Any ideas of what is going on?

 

Thanks!,

 

MGA.

Hi,

 

I have a requirement to build a text file (txt) in Salesforce and store it attached under a custom object. The file has a certain format (I will need to build it manually using Apex). As far as I know, it cannot be created using PDF creation technique.

 

Do you know of any technique to create custom files other than PDF creation and store them in Salesforce?

 

All ideas are welcome!.

 

Greetings, 

 

MGA.

Hi all,

 

I have a problem when trying to develop a solution that deals with 'large' amounts of data. The situation is the following. 

We have to develop for our customer a solution that handles records inserted in their Salesforce under a custom object (Unprocessed Agreements). Each record from this custom object hosts information that, once processed, will end in Accounts, Contacts and a custom object called 'Agreements'. Basically, each record of the custom object has all the information of an agreement with its account and its contact related. So processing each record of 'Unprocessed Agreements' means to create an Account (if not already in SF); a Contact (if not already in SF) and an Agreement (if is already in Salesforce, updates this agreement). All the logic built to meet this requirements has to rely on a scheduled class that will run and perform this every day.

The number of agreements, Accounts and Contacts might be around 3000 for each entity, in order to not hit the SOQL limits, we developed the functionality so that first 'dumps' all the accounts, contacts and agreements existing in Salesforce into Lists, and we do searches over that lists to check if the Accounts, Contacts or Agreements were created before, then we build the logic on top of this checks. 

Our problem seems that when we want to perform searches over those Lists of records, we hit a limit: ''Too many statements: 200001" when looping over those lists. We make sure to not hit the SOQL query limit, but we faced this limit mentioned above. The logic built works as desired when we keep low the amount of Accounts, Contacts and Agreements. 

Do you have any ideas on how to handle this?

Best regards, 

 

MGA.

Hi all,

 

I have a set of Customer IDs in dataSet variable, I want to build a SOQL with an 'IN' filter in the WHERE clause...but it's not compiling:

 

List<Account> AccIds = [SELECT Id FROM Account WHERE AccountNumber IN =: dataForUpdate];

 

Any idea of what is going on?

 

Greetings, 

 

MGA.

Hi all,

 

I have this SOQL with a child relationship (parent-to-child)

 

[SELECT Name, Birthdate, (SELECT Name_Em__c, Job_Title__c FROM Employment__r),
 (SELECT Degree__c, Name_Ed__c FROM Education__r)
FROM Contact WHERE Id IN (SELECT Candidate_Contact__c
      FROM Application__c

      WHERE Job__c =:JobOrderId)

];

 

And the following Visualforce on a pageblocktable:

 

<apex:column headerValue="Company" value="{!ed.Employment__r.Name_Em__c}"/>

 

But I cannot get the information from the two sub-select into the table. 

 

Do you have any idea on how to get it?

 

Many thanks,

 

MGA.

String assesment_query = 'SELECT a,b,c,d,e,f,g,h,i,j'+ 
+'FROM Assesment__c WHERE Candidate__c IN '													+'(SELECT Candidate_Contact__c '+																		+'FROM Application__c '+																		+'WHERE Job__c =:'+JobOrder+' '+																		+'AND Stage__c =:'+offer+')'+
		        +' AND RecordTypeId =:'+ProfileId+';';
List<Assesment__c> assesment = Database.query(assesment_query);

 Hi all,

 

I have the code above and gives me this error:

 

System.QueryException: unexpected token: WHERE 

 If I execute this directly (eg.: List<Assessment__c> assessment = [the query here]; Works perfectly.

 

In the string query:

JobOrder is an ID.

offer is a String.

ProfileId is an ID.

 

Does anyone knows why this happens?. Do you know of any solution?

 

Thank you!,

 

MGA

Hi,

 

I have a requirement to develop a table that contains a list of records; each record has columns with information from two different custom objects. I know how to make two different listings with the information from each object separated, but I can't come up with a custom controller (or extension) that retrieves the information from different objects and shows that in one single table.

 

The only (VERY VAGUE) idea I have is from here: http://stackoverflow.com/questions/8157240/combine-multiple-objects-within-a-list

 

Any idea, comment or help will be very welcome.

 

Many thanks,

 

MGA.

Hi all,

 

I'm trying to build a dataList with data from a query with a sub-query. This is the VF markup:

 

<apex:page standardController="Application__c" extensions="getDataFinalReport" tabStyle="Application__c" >

  <apex:pageBlock title="Candidates">
  <apex:form id="theForm">
    <apex:pageBlockSection showHeader="true" title="List of Candidates" >
      <apex:dataList var="a" value="{!can}" type="1">
      <apex:outputText value="{!can.Candidate_Full_Name__c}"/>
      </apex:dataList>
    </apex:pageBlockSection>
    
  </apex:form> 
  </apex:pageBlock>

</apex:page>

 

And this is the controller extension:

 

public with sharing class getDataFinalReport {

    public getDataFinalReport(ApexPages.StandardController controller) {

    }
    
    string JobOrderId = ApexPages.currentPage().getParameters().get('id');
    
    public ApexPages.StandardSetController can {
        get {
            if(can == null) {
                can = new ApexPages.StandardSetController(Database.getQueryLocator(
                
                [SELECT 
                        (SELECT Candidate_Full_Name__c 
                         FROM Application__c)
                 FROM Job_Order t 
                 WHERE Id=:JobOrderId]));
            }
            return can;
        }
        set;
    }

    // Initialize can and return a list of records  
    
    public List<ts2__Application__c > getCandidateLines() {
         return (List<ts2__Application__c >) can.getRecords();
    }
        
    
}

 

The problem now is that, when I try to save the VF gives me the following error:

 

Error: Unknown property 'ApexPages.StandardSetController.Candidate_Full_Name__c'

 

I tried creating the get/set for Candidate_Full_Name__c but it doesn't work either , can anyone help me with this?

 

Many thanks,

 

MGA

Hi there,

 

I'm trying to create test coverage for a trigger over User object, soI need to create a User to fire the trigger. I coded a test class following this: http://www.salesforce.com/us/developer/docs/apexcode/index_Left.htm#StartTopic=Content/apex_dml_non_mix_sobjects.htm?SearchType

 

This is how it looks like:

 

public class UserTriggerHandlerTest {
 
        @isTest (seeAllData=true)
        static void testUserCreate(){
               
                // Setup test data
                // This code runs as the system user
                Profile p = [SELECT Id
                             FROM Profile
                             WHERE Name='Portal User'];
 
                Profile p2 = [SELECT Id
                              FROM Profile
                              WHERE Name='System Administrator'];
                 
                User u = new User(Alias = 'custPort', Email='customer@portal.com',
                EmailEncodingKey='UTF-8', LastName='Portal', LanguageLocaleKey='en_US',
                LocaleSidKey='en_US', ProfileId = p.Id,
                TimeZoneSidKey='America/Los_Angeles', UserName='customer@portal.com');
               
                User u2 = new User(Alias = 'admn', Email='admin@test.com',
                EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
                LocaleSidKey='en_US', ProfileId = p2.Id,
                TimeZoneSidKey='America/Los_Angeles', UserName='customer@portal.com');
               
                System.runAs(u2) {
               
                        insert u;
               
                }
       
        }
}

 



The test fails with the following message:

FATAL_ERROR System.DmlException: Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: []
FATAL_ERROR Class.UserTriggerHandlerTest.testUserCreate: line 23, column 1

 

Any ideas? Does anyone know how to avoid this or any workaround to do test coverage for a trigger over User?

 

Thanks.

 

MGA.

Hi,

 

I'm developing a visualforce page where I need to support translations. My approach is to create Custom Labels and use the "language" attribute in apex page to provide the language string.

 

 

<apex:page controller="MyController"  language="{!language}">

...


<apex:pageBlock title="{!$Label.My_Label}" mode="detail"> 

...

 

The language string gets its value in the controller (actually is a value parsed from an XML).

 

My question is:

 

How can I generate the Visualforce page so that the header and sidebar will have the standard language value (the one selected by the user) but the rest of the labels in the VF will be translated according to the parameter passed from the controller?

 

I will appreciate any kind of aproach that is sustainable (not hardcoding the labels in the controller). Many thanks.

 

MGA

Hi all,

 

I need to trim an XML from unnecesary elements before parsing it (due to its size). In order to do that I had the idea of loop over a given list of elements I don't need and using replaceAll() for that.

 

Once I found what I thought is the right regular expression (testing it in regex engines online with a given XML) I use it in my code but Salesforce gives me the error 'Regex too complicated'

 

The regular expression I came up with is this:

 

<(TAG)\b[^>]*>(.*?)</\1>

 

 This regular expression matches an entire XML ELEMENT with its value (it includes ELEMENTS with attributes) and its closing tag. 

 

I tried this regex in this engine: regex online engine tool

 

This is the text I use for testing purposes:

 

<BLOCK_SUMMARY>
     <COUNT>1</COUNT>
     <TOTAL>
	<AMOUNT SIGN="+" VAT="INCLUDED">123</AMOUNT>
     </TOTAL>
     <TEST>Testing</TEST>
</BLOCK_SUMMARY>

 Using the engine above linked with the regex I came up with the engine gives as a result (underlined) the match. This result is what I use in a simple piece of Apex to trim the whole XML. Something like this:

 

...

String[] elementsToDelete = new String[]{'TEST'};
String result = null;
    	
for(String s:elementsToDelete){
    		
   result = xml.replaceAll('<('+s+')\b[^>]*>(.*?)<\\1>','');
} 

...

Notice I had to change the grouping /\1 for \\1 to be able to save this code in Salesforce and following java.util.regex Pattern Class (the one that SF is based in according to the documentation). (More info about groupings here)

 

I know this is a kind of very specific problem, but I tried to provide all information I have here. Can anyone spot what is the problem with the regex? Is it even possible to write a regex like that and Apex regex engine read it?

 

Any help is very welcome.

 

MGA

 

 

 

Hi all,

 

I developed a functionality that makes use of HttpRequest class. In order to test it I used HttpCalloutMock. This functionality is withing a @future (callout=true) method. I developed the test classes following the documentation for HttpCalloutMock. The tests (2) pass in sandbox, but when deploying to production they both give error System.NullPointerException (apparently the HttpResponse is null) in the assertion line. Here is the code for the tests and the implementations for HttpCalloutMock within the same Test class:

 

@isTest
global class TrustCalloutTest {
    
    global class TrustCalloutMockBasicCallout implements HttpCalloutMock {
        
        global HTTPResponse respond(HTTPRequest req) {
            
            HttpResponse res = new HttpResponse();
            res.setBody('TEST');
            res.setStatusCode(200);
            return res;
        }
    }
    
    global class TrustCalloutMockRequestKey implements HttpCalloutMock {
        
        global HTTPResponse respond(HTTPRequest req) {
            
            HttpResponse res = new HttpResponse();
            res.setBody('RECEIVED');
            res.setStatusCode(200);
            return res;
        }
    }
    
    static testmethod void testCalloutRequireKey() {
    	
        HttpResponse res; 
        Test.setMock(HttpCalloutMock.class, new TrustCalloutMockRequestKey());
        res = TrustCallout.requestTransferKey('BLAH','https://beta2.trustpoint.fi/API/requirekey.php');
        System.assertEquals(200, res.getStatusCode());
    }
    static testmethod void testCalloutBasicCallout(){
         
    	HttpResponse res;
        Test.setMock(HttpCalloutMock.class, new TrustCalloutMockBasicCallout()); 
        res = TrustCallout.basicCallout('BLAH','https://beta2.trustpoint.fi/API/committransfer.php');
        System.assertEquals(200, res.getStatusCode());    
    }
}

 

The actual callout works normally, and it also follows the documentation.

 

Endpoints were added at both sides (production and sandbox).

 

Any idea of what is going on?

 

Thanks.

 

MGA.

 

 

Hello,

 

I have a WS that changes the value of one field using Javascript. something like this:

 

WS:

 

global class fromMSStatusAToB{

WebService static void changeStatus(String id, String status) {

    // update a status field.             
}
}

 In the layout I lifted a button with this code that works normally:

 

{!REQUIRESCRIPT("/soap/ajax/15.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/15.0/apex.js")} 
sforce.apex.execute("fromMSStatusAToB","changeStatus",{id: "{!Process_Cost__c.Id}" ,status:"Accepted"}); 
alert('MS Status updated'); 
window.location.reload(true);

 This works normally. But now the requirements changed and I need to put this on a custom VF page. To meet that requirements I put in the VF the following code to call the Apex WS:

 

<script src="/soap/ajax/15.0/connection.js" type="text/javascript"</script>
<script src="/soap/ajax/15.0/apex.js" type="text/javascript"></script>

<script>
function foundryFromCreatedToAccepted(){
sforce.apex.execute("fromMSStatusAToB","changeStatus",{id: "{!Process_Cost__c.Id}" ,status:"Accepted"}); 
}

</script>

 And I call this function with a command link like this:

 

<apex:commandLink value="Change Status to Accepted" onclick="foundryFromCreatedToAccepted()" />  

 

The problem is that all code is saved, but it doesn't seem to work. Do you have any ideas why it doesn't work? Any workaround? How can I debug this kind of problems?

 

Many thanks,

 

MGA.

Hello,

 

I have a WS that changes the value of one field using Javascript. something like this:

 

WS:

 

global class fromMSStatusAToB{

WebService static void changeStatus(String id, String status) {

    // update a status field.             
}
}

 In the layout I lifted a button with this code that works normally:

 

{!REQUIRESCRIPT("/soap/ajax/15.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/15.0/apex.js")} 
sforce.apex.execute("fromMSStatusAToB","changeStatus",{id: "{!Process_Cost__c.Id}" ,status:"Accepted"}); 
alert('MS Status updated'); 
window.location.reload(true);

 This works normally. But now the requirements changed and I need to put this on a custom VF page. To meet that requirements I put in the VF the following code to call the Apex WS:

 

<script src="/soap/ajax/15.0/connection.js" type="text/javascript"</script>
<script src="/soap/ajax/15.0/apex.js" type="text/javascript"></script>

<script>
function foundryFromCreatedToAccepted(){
sforce.apex.execute("fromMSStatusAToB","changeStatus",{id: "{!Process_Cost__c.Id}" ,status:"Accepted"}); 
}

</script>

 And I call this function with a command link like this:

 

<apex:commandLink value="Change Status to Accepted" onclick="foundryFromCreatedToAccepted()" />  

 

The problem is that all code is saved, but it doesn't seem to work. Do you have any ideas why it doesn't work? Any workaround? How can I debug this kind of problems?

 

Many thanks,

 

MGA.

Hi,

 

I need to retrieve some data using a nested SOQL, but I can't get the needed data. The SOQL is the following:

 

SELECT (SELECT Name,
               Unit_Price__c, 
               Quantity__c, 
               Time__c 
        FROM Valitut_Tuotteet__r)
FROM Service_Reservation__c 
WHERE Room_Reservation__c =: roomRes

 I need to extract the Name, Unit_Price__c, Quantity__c and Time__c and show them on a table (apex:repeat). Do you have any idea of how can I access that data?

 

Using <apex:repeat> and retrieving the fields doesn't work, I guess is because the data structure that the query creates is not a simple List<Service_Reservation__c>. 

 

Any idea on this?

 

Greetings,

 

MGA.

Hi all,

 

I have a problem getting the value from an AgreggateResult returned by an SOQL. Here is the code from the SOQL:

 

        total = [SELECT SUM(Total_Net__c)tmp
                 FROM Selected_Product__c
                 WHERE Service_Reservation__c =:servOrder
                 GROUP BY Service_Reservation__c];
              system.debug('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%'+total);    

 That system.debug gives me this: 

 

16:17:01:123 USER_DEBUG [24]|DEBUG|%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%(AggregateResult:{tmp=40.0})

 Which is the value I want to show. In a different method I try to return 'result' as integer this way:

 

    public integer result {get; set;}

...


 public integer getResult(){
    
       integer result;
       for(AggregateResult ar:total){
       
           result = (integer)ar.get('tmp');
       system.debug('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%'+result);
       }
                                     
       return result;
    }

NOTE: When I debug this it never gets to the system.debug, but salesforce allows me to save this code (hence, no syntax errors).

 

And in the VF page I call for result this way:

 

<apex:outputText value="{!result}"/>

 

And no result at all (empty).

 

Do you have any idea of why this is happening?. Any solution?

 

Many thanks,

 

MGA.

Hi all,

 

I have the following code that doesn't generate a proper SOQL sentence. I'm passing a date from a VF page standard date selector, I needed to create a query, but the query doesn't work properly. I think it is because of the Date/Datetime format, but after try all posibilities, it doesn't work as it should (the query doesn't work).

 

public generateRestSched(ApexPages.StandardController controller) {

 

String room = ApexPages.currentPage().getParameters().get('id');
bookingdate = date.parse(ApexPages.currentPage().getParameters().get('date'));
system.debug('###############################'+bookingdate);
 

entries = [SELECT Reservation_Time_Start__c,
   End_Time__c,
   Customer_and_Event_Info__c,
   Booking_Date__c,
   Additional_Information__c,
   Room_del__c
FROM Room_Reservations__c
WHERE Booking_Date__c =:bookingdate
AND Room_del__c=:room];

 

system.debug('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&'+entries);

}

 

 

Any ideas of what is going on?

 

Thanks!,

 

MGA.

Hi all,

 

I have a problem when trying to develop a solution that deals with 'large' amounts of data. The situation is the following. 

We have to develop for our customer a solution that handles records inserted in their Salesforce under a custom object (Unprocessed Agreements). Each record from this custom object hosts information that, once processed, will end in Accounts, Contacts and a custom object called 'Agreements'. Basically, each record of the custom object has all the information of an agreement with its account and its contact related. So processing each record of 'Unprocessed Agreements' means to create an Account (if not already in SF); a Contact (if not already in SF) and an Agreement (if is already in Salesforce, updates this agreement). All the logic built to meet this requirements has to rely on a scheduled class that will run and perform this every day.

The number of agreements, Accounts and Contacts might be around 3000 for each entity, in order to not hit the SOQL limits, we developed the functionality so that first 'dumps' all the accounts, contacts and agreements existing in Salesforce into Lists, and we do searches over that lists to check if the Accounts, Contacts or Agreements were created before, then we build the logic on top of this checks. 

Our problem seems that when we want to perform searches over those Lists of records, we hit a limit: ''Too many statements: 200001" when looping over those lists. We make sure to not hit the SOQL query limit, but we faced this limit mentioned above. The logic built works as desired when we keep low the amount of Accounts, Contacts and Agreements. 

Do you have any ideas on how to handle this?

Best regards, 

 

MGA.

Hi all,

 

I have a set of Customer IDs in dataSet variable, I want to build a SOQL with an 'IN' filter in the WHERE clause...but it's not compiling:

 

List<Account> AccIds = [SELECT Id FROM Account WHERE AccountNumber IN =: dataForUpdate];

 

Any idea of what is going on?

 

Greetings, 

 

MGA.

Hi all,

 

I have this SOQL with a child relationship (parent-to-child)

 

[SELECT Name, Birthdate, (SELECT Name_Em__c, Job_Title__c FROM Employment__r),
 (SELECT Degree__c, Name_Ed__c FROM Education__r)
FROM Contact WHERE Id IN (SELECT Candidate_Contact__c
      FROM Application__c

      WHERE Job__c =:JobOrderId)

];

 

And the following Visualforce on a pageblocktable:

 

<apex:column headerValue="Company" value="{!ed.Employment__r.Name_Em__c}"/>

 

But I cannot get the information from the two sub-select into the table. 

 

Do you have any idea on how to get it?

 

Many thanks,

 

MGA.

String assesment_query = 'SELECT a,b,c,d,e,f,g,h,i,j'+ 
+'FROM Assesment__c WHERE Candidate__c IN '													+'(SELECT Candidate_Contact__c '+																		+'FROM Application__c '+																		+'WHERE Job__c =:'+JobOrder+' '+																		+'AND Stage__c =:'+offer+')'+
		        +' AND RecordTypeId =:'+ProfileId+';';
List<Assesment__c> assesment = Database.query(assesment_query);

 Hi all,

 

I have the code above and gives me this error:

 

System.QueryException: unexpected token: WHERE 

 If I execute this directly (eg.: List<Assessment__c> assessment = [the query here]; Works perfectly.

 

In the string query:

JobOrder is an ID.

offer is a String.

ProfileId is an ID.

 

Does anyone knows why this happens?. Do you know of any solution?

 

Thank you!,

 

MGA