• Maf_007
  • NEWBIE
  • 410 Points
  • Member since 2013

  • Chatter
    Feed
  • 14
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 27
    Questions
  • 78
    Replies

Hi ,

 

I have done one test method for my Trigger . Myunittest method is success with out returning errors I observed this under Tests tab in developer console. but it showing Failed symbol for my testclass .

 

Tests [tab] from developer console

 

Failed symbol : Here mytest Class Name  

but here if i open my test method it showing success symbol. 

 

 

 

Can any one help me on this.

 

  • November 14, 2013
  • Like
  • 0

Hello!  We are a real estate developer. We receive deposits from customers, and we track them with salesforce. I'd love an email alert to automatically fire a couple days before the deposit deadline to the corresponding contact.  I have no problems creating the time-based workflow rule, but i cant seem to be able to set the email update to be sent to the contact (there is only one in the account).  We manage deposits in a custom objects called ''deposits'' which is linked to assets.   Is it possible to do what i want to do?

 

thanks in advance,

Hi Everyone,

 

I am new to Salesforce platform and need some help on the following Issue. Any co-operation would be appreciated:

 

I want to have a trigger to prevent some users to post any question or reply to any question on chatter answer. I believe chatter and chatter answer are two separate objects ( correct me if I am wrong please). Now which object my trigger should be on as I can not see an object named chatter answer in salesforce?

 

Thanks for your help.

Hi All,

I am trying to do a really simple thing here but it's not working. I am trying to display a page message from action function method but it's not working. I have checked the debug log as well but it seems like it's not invoking the method at all. Could anyone see if I am doing anything wrong here:

<apex:page standardController="MyObject__c" extensions="MyControllerExt" >
    <apex:form id="MainForm">
    
        <apex:actionFunction name="InvokeActionFunction" action="{!InvokeActionFunction}" rendered="{!displayactionfunction}" reRender="MainForm,Msg"/>
        
        <apex:pageBlock>
            <apex:pageBlockSection>
                    <apex:messages id="Msg"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
        
    </apex:form>
</apex:page>

Controller Ext:

public class MyControllerExt{
    Public static Customer__c Cus {get; set;}
    public boolean displayactionfunction{get; set;}
    public MyControllerExt(ApexPages.StandardController CusController)
    {
		System.debug('Record to process is: ------------->'+CusController.getRecord());
        Cus = (Customer__c)CusController.getRecord();
        displayactionfunction = true;
    }
    
    Public void InvokeActionFunction()
    {
        ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL,System.Label.Problem_Saving_Record);
        ApexPages.addMessage(myMsg);
        System.debug('Page Message is-------------------------------->'+myMsg);
        displayactionfunction = false;
    }
}

Thanks in advance!
Hi All,

I have a visualforce page which overrides the new button for creating new record. It performs data validation and rerenders the page if something is wrong. I am trying to use same controller extension from a custom button as well. but when I add the visual force page in my button I get following error:

SObject row was retrieved via SOQL without querying the requested field:

A lot of people suggested to set rendered = false on the page but that does not meet my requirement as I need to get those fields in edit mode to perform similar action as I did when creating the record.

Any suggestions would be greatly appreciated.
Hi All I am trying to parse an XML string using DOM parser and got stuck. Is there anyone who can give me some insight on this:

Below is the XML string I am trying to Parse:

String XmlResponse = '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> '+
   						' <soap:Body>'+
      					'<GetInventoryDetailsResponse xmlns="http://services.XXXXXXX.com/schema/bs/inventory/v01/MaintainInventory" xmlns:ns2="http://services.XXXXXXX.com/schema/common/header/v01/Header" xmlns:ns3="http://services.XXXXXXX.com/schema/common/inventory/v01/inventory" xmlns:ns4="http://services.XXXXXXX.com/schema/common/acknowledgement/v01/Acknowledgement"> '+
      					'<Inventory>'+
   						'<ns3:TypeDesignator>test</ns3:TypeDesignator>'+
   						'<ns3:TypeDescription>test123</ns3:TypeDescription>'+
      					'</Inventory>'+
   						'</GetInventoryDetailsResponse>'+
						'</soap:Body>'+
        				'</soap:Envelope>';

And my Code is Below:

public static final String soapNS = 'http://schemas.xmlsoap.org/soap/envelope/';
public static final String Acknowledgement_ns = 'http://services.xxxx.com/schema/common/acknowledgement/v01/Acknowledgement';
public static final String MaintainInv_ns = 'http://services.xxxx.com/schema/bs/Inventory/v01/MaintainInventory';
public static final String Inv_ns = 'http://services.xxxx.com/schema/common/Inventory/v01/Inventory';
public static final String Head_ns = 'http://services.xxxx.com/schema/common/header/v01/Header';

Dom.Document doc = new Dom.Document();
doc.load(XmlResponse);

dom.XmlNode xroot = doc.getrootelement();
String body_prefix = xroot.getPrefixFor(soapNS);
			
System.debug('Body Prefix is: ----------------'+body_prefix);
			
dom.XmlNode body = xroot.getChildElement('Body', soapNS);
			
System.debug('Body is: ---------------->>>'+body);

dom.XmlNode Invres = body.getChildElement('GetInventoryDetailsResponse', null);

System.debug(Invres is: ---------------->>>'+Invres);

//Above Line I get null Value but it should have inventory node under it???

tried with following still same issue:

//dom.XmlNode Invres = body.getChildElement('GetInventoryDetailsResponse', MaintainInventory_ns+' '+Inventory_ns+' '+Head_ns+' '+Acknowledgement_ns);

Any Idea what is wrong there?


I am trying to make a SOAP call out but getting an error because of the request xml has been constructed. The server side wants every header elements (user name, password, security token) to have a namespace (header schema) but the Apex generated does have a name space for every element but embeded under header element. please see the below requests:

Required Request:

<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:head="http://services.xx.com/schema/common/header/v01/Header" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <env:Header>
      <Header xmlns="http://services.xx.com/schema/common/header/v01/Header">
         <head:UserName>xx</head:UserName>
         <head:Password>xxxxx</head:Password>
         <head:SecurityToken>xxxx</head:SecurityToken>
         <head:Timestamp>2014-07-01T12:14:20.413Z</head:Timestamp>
      </Header>
   </env:Header>
   <env:Body>
      <UpdateCustomerRequest xmlns="http://services.xx.com/schema/bs/customer/v01/MaintainCustomer">
         <Customer>
            <AccountGUID xmlns="http://services.xx.com/schema/common/customer/v01/Customer">xx</AccountGUID>
            <regID xmlns="http://services.xx.com/schema/common/customer/v01/Customer">123</regID>
            <FirstName xmlns="http://services.xx.com/schema/common/customer/v01/Customer">Test</FirstName>
            <LastName xmlns="http://services.xx.com/schema/common/customer/v01/Customer">Phone User</LastName>
            <Gender xmlns="http://services.xx.com/schema/common/customer/v01/Customer">Female</Gender>
         </Customer>
         <HandsetList/>
      </UpdateCustomerRequest>
   </env:Body>
</env:Envelope>

Salesforce generated Request:

<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <env:Header>
      <Header xmlns="http://services.xxx.com/schema/common/header/v01/Header">
         <UserName>xxxx</UserName>
         <Password>xxxx</Password>
         <SecurityToken>xxxx</SecurityToken>
         <Timestamp>2014-07-01T12:14:20.413Z</Timestamp>
      </Header>
   </env:Header>
   <env:Body>
      <UpdateCustomerRequest xmlns="http://services.xxx.com/schema/bs/customer/v01/MaintainCustomer">
         <Customer>
            <AccountGUID xmlns="http://services.xxx.com/schema/common/customer/v01/Customer">001M000000XhiniIAB</AccountGUID>
            <VregID xmlns="http://services.xxx.com/schema/common/customer/v01/Customer">123</VregID>
            <FirstName xmlns="http://services.xxx.com/schema/common/customer/v01/Customer">Test</FirstName>
            <LastName xmlns="http://services.xxx.com/schema/common/customer/v01/Customer">Phone User</LastName>
            <Gender xmlns="http://services.xxx.com/schema/common/customer/v01/Customer">Female</Gender>
         </Customer>
         <HandsetList/>
      </UpdateCustomerRequest>
   </env:Body>
</env:Envelope>

My WSDL generated Interface and header below:

//Generated by wsdl2apex

public class WS_SOA_MaintainCustomerInterface {
    public class MaintainCustomerServiceHTTPBinding {
        public String endpoint_x = 'http://services.xxx.com/wsdl/bs/customer/v01/MaintainCustomerService';
        public Map<String,String> inputHttpHeaders_x;
        public Map<String,String> outputHttpHeaders_x;
        public String clientCertName_x;
        public String clientCert_x;
        public String clientCertPasswd_x;
        public Integer timeout_x;
        public WS_SOA_HeaderInfo.Header Header;
        private String Header_hns = 'Header=http://services.xx.com/schema/common/header/v01/Header';
        private String[] ns_map_type_info = new String[]{'http://services.xx.com/schema/bs/customer/v01/MaintainCustomer', 'WS_SOA_MaintainCustomerType', 'http://services.xx.com/schema/common/customer/v01/Customer', 'WS_SOA_CustomerType', 'http://services.xx.com/wsdl/bs/customer/v01/MaintainCustomerService', 'WS_SOA_MaintainCustomerInterface', 'http://services.xx.com/schema/common/header/v01/Header', 'WS_SOA_HeaderInfo', 'http://services.xx.com/schema/common/handset/v01/Handset', 'WS_SOA_HandsetDetail', 'http://services.xx.com/schema/common/acknowledgement/v01/Acknowledgement', 'WS_SOA_MaintainCustomerAcknowledgement', 'http://services.xx.com/schema/common/service/v01/Service', 'WS_SOA_ServiceInfo'};
        
        public WS_SOA_MaintainCustomerType.UpdateCustomerResponseType updateCustomer(WS_SOA_CustomerType.CustomerType Customer,WS_SOA_HandsetDetail.Handset HandsetList) {
            WS_SOA_MaintainCustomerType.UpdateCustomerRequestType request_x = new WS_SOA_MaintainCustomerType.UpdateCustomerRequestType();
            request_x.Customer = Customer;
            request_x.HandsetList = HandsetList;
            WS_SOA_MaintainCustomerType.UpdateCustomerResponseType response_x;
            Map<String, WS_SOA_MaintainCustomerType.UpdateCustomerResponseType> response_map_x = new Map<String, WS_SOA_MaintainCustomerType.UpdateCustomerResponseType>();
            response_map_x.put('response_x', response_x);
            WebServiceCallout.invoke(
              this,
              request_x,
              response_map_x,
              new String[]{endpoint_x,
              'http://services.xx.com/wsdl/bs/customer/v01/MaintainCustomerService/updateCustomer',
              'http://services.xx.com/schema/bs/customer/v01/MaintainCustomer',
              'UpdateCustomerRequest',
              'http://services.xx.com/schema/bs/customer/v01/MaintainCustomer',
              'UpdateCustomerResponse',
              'WS_SOA_MaintainCustomerType.UpdateCustomerResponseType'}
            );
            response_x = response_map_x.get('response_x');
            return response_x;
        }
    }
}


Header Class:

//Generated by wsdl2apex

public class WS_SOA_HeaderInfo {
    public class Header {
        public String UserName;
        public String Password;
        public String SecurityToken;
        public String Domain;
        public String Role;
        public String MessageID;
        public String TransactionID;
        public DateTime Timestamp;
        
        private String[] UserName_type_info = new String[]{'UserName','http://services.xx.com/schema/common/header/v01/Header',null,'0','1','false'};
        private String[] Password_type_info = new String[]{'Password','http://services.xx.com/schema/common/header/v01/Header',null,'0','1','false'};
        private String[] SecurityToken_type_info = new String[]{'SecurityToken','http://services.xx.com/schema/common/header/v01/Header',null,'0','1','false'};
        private String[] Domain_type_info = new String[]{'Domain','http://services.xx.com/schema/common/header/v01/Header',null,'0','1','false'};
        private String[] Role_type_info = new String[]{'Role','http://services.xx.com/schema/common/header/v01/Header',null,'0','1','false'};
        private String[] MessageID_type_info = new String[]{'MessageID','http://services.xx.com/schema/common/header/v01/Header',null,'0','1','false'};
        private String[] TransactionID_type_info = new String[]{'TransactionID','http://services.xx.com/schema/common/header/v01/Header',null,'0','1','false'};
        private String[] Timestamp_type_info = new String[]{'Timestamp','http://services.xx.com/schema/common/header/v01/Header',null,'0','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://services.xx.com/schema/common/header/v01/Header','true','false'};
        private String[] field_order_type_info = new String[]{'UserName','Password','SecurityToken','Domain','Role','MessageID','TransactionID','Timestamp'};
    }
}

Has someone encountered this problem and possibly give a work around of this problem?

Hi All,

I have a batch call out class which has a nested SOQL query string in start method. My test class fails with following:

System.SObjectException: Invalid aggregate relationship Child Relationship Name for Account

my code is below:

global class batchclassname implements Database.Batchable<sObject>, Database.Stateful, Database.AllowsCallouts
{

     global database.querylocator start(Database.BatchableContext BC)
    {
	 String Query = 'SELECT id, Industry__c, (Select id, Account_Name__c from Children__r where active__c = true) FROM Account Limit 100';
        
     return Database.getQueryLocator(Query);
    }
    
    global void execute(Database.BatchableContext BC, List<SObject> scope)
    {   
        if(scope.size()>0)
        {
			for(sobject s: scope)
        	{
            	//Get the Account sobject
            	Account a = (Account)s;
            	
            	List<Child__c> RelatedChildren = a.getsobjects('Children__r'); // This line causing issue in test class I believe
               
                       for(Child__c Ch:RelatedChildren)
                      {
                           do some call out here....
                       }
                  }
            }
     }

    global void finish(Database.BatchableContext BC)
    {
        	
    }
    

}
Hi All,

I have a trigger on Lead
 which insert a record on a custom object (Lead looks up to custom object) which causes a trigger on custom object to fire to relate lead with the custom object. But surprisingly newly created lead does not come up on my soql query (every other matching record is available)? Is there any reason for that or Salesforce has a limitation doing so?

Any help will be appreciated? 

Hi All,

 

I am writing a trigger on Contact to update a date field on account depending on a date field on all related contacts. I am getting a List out of bound  exception: 4

 

Could I please have some guidance on how to rectify this issue? My code is below:

 

//Method to process Trigger.new context for after trigger
    public void LastActivityDateUpdate(List<Contact> updatedcontacts){
        Set<id> contactids = new Set<id>{};
        
        for(Contact con:updatedcontacts){
            if(con.Last_Activity_Date__c != null){
        		contactids.add(con.AccountId);
            }
        }
        
        List<Account> Accwithdateupdate = [Select id, Last_Modified_Date__c, (select id, Last_Activity_Date__c from Contacts) from Account where id in: contactids];
        DateTime lastactivitydateholder;
        
        for(Account a : Accwithdateupdate){
            
            for(Contact c: a.contacts){
                for(integer i = 0; i<a.contacts.size(); i++){
                    lastactivitydateholder = (a.contacts[i].Last_Activity_Date__c > a.contacts[i+1].Last_Activity_Date__c) ? a.contacts[i].Last_Activity_Date__c : a.contacts[i+1].Last_Activity_Date__c;
					//lastactivitydateholder = c.LastActivityDate;
                	//lastactivitydateholder1 = lastactivitydateholder;
                }
            }
            a.Last_Modified_Date__c = lastactivitydateholder;
        }
        update Accwithdateupdate;
    }

 

Thanks in Advance.

Hi,

 

I have a trigger on a custom object called service__c which is a child of account. Trigger prevents users to have more than one open service for an account at the same time (pick list status__c field). My problem here is It does not allow me to update picklist value for the open account eventhough this is the only open account. My code is below:

public with sharing class ServiceTriggerHandler {
	private boolean m_isExecuting = false;
	private integer BatchSize = 0;
	
	/*public ServiceTriggerHandler(boolean isExecuting, integer size){
		m_isExecuting = isExecuting;
		BatchSize = size;
	}*/
	
	public void servicestatusvalidationmethod(List<Service__c> services){
        Set<id>serviceids = new Set<id>{};
        
        for(Service__c service:services){
            //if(service.Status__c != 'Closed'){
				serviceids.add(service.Account__c);
           // }
        }
        List<Service__c> allactiveservices = [select id, Status__c,Account__c from Service__c where Account__c IN: serviceids and Status__c != 'Closed'];
        System.debug(allactiveservices);
        
        for(Service__c newservice:services){
            for(Service__c servicesvalidation:allactiveservices){
                if(newservice.status__c != 'Closed'){
                	newservice.addError('There is already one Active Service For this Account');
            	}
            }
        }
    }
}

 

 

Any help would be highly appreciated.

 

Thanks,

Hi All,

 

I am trying to update some fields with values in a map but it seems like my code always update the fields with first key value field eventhough there are two keys in the map. Please help, my code is below:

 private static Map<String,list<string>> parsexml(DOM.XMLNode node){
        list<String> mslist = new list<string>();
        Map<String,list<string>> msmap = new Map<String,list<String>>{};
        String MSId;
        String annsave;
        String costsave;
        String save2;
        String supersave;

        for(Dom.XMLNode child : node.getChildElements()) {
                    if(child.getName()=='Reference'){
                    	MSId = node.getText().trim();
                        system.debug(MSId);
                    }
                    else if(child.getName()=='Annual-Saving'){
                    	annsave = node.getText().trim();
                        system.debug(annsave);
                        mslist.add(annsave);
                    }
                    else if(child.getName()=='Cost-Saving'){
                    	costsave = node.getText().trim();
                        system.debug(costsave);
                        mslist.add(costsave);
                    }
                    else if(child.getName()=='Extra-Save'){
                    	save2 = node.getText().trim();
                        system.debug(save2);
                        mslist.add(save2);
                    }
                    else if(child.getName()=='Total-Save'){
                    	supersave = node.getText().trim();
                        system.debug(supersave);
                    }
                    msmap.put(MSId,mslist);
                    system.debug(msmap);
        }

        return msmap;//returns a map of list 
    }

 

And the following should match the record id with key and update record:

 

List<CostSaver__c> Ms = [select id, name, Annual_Cost_Saving__c, Save_amount__c from CostSaver__c where id in:msmap.keyset()];
        //system.debug(Cs);
        for(CostSaver__c m: Cs){
            for(String mapvalues:msmap.keyset()){
            	//System.debug('map values:'+mapvalues);
                if(mapvalues == m.id){
                	System.debug(Double.valueof(msmap.get(mapvalues)[0]));
                    System.debug(Double.valueof(msmap.get(mapvalues)[1]));
                    System.debug(Double.valueof(msmap.get(mapvalues)[2]));
            	}
            }
        }

 Now the problem is I am getting same value for 2nd record as well??

 

Could anyone please check this for me?

 

Thanks,

 

 

Hi All,

 

I am trying to write a test class for apex scheduler and batch class but I am not getting enough code coverage. I get enough coverage for batch class but not for the scheduler. My classes and text classes are following:

 

Scheduler Class:

 

global class WebserviceScheduler implements Schedulable {
   global WebserviceScheduler(){}

    public static void start(){
        //Seconds Minutes Hours Day_of_month Month Day_of_week optional_year
        System.schedule('Pending Cost Score Update', '0 5 1-23 * * ?', New WebserviceScheduler());

    }
    
    global void execute(SchedulableContext SC) {
      WebserviceBatchHandler bh = new WebserviceBatchHandler();
        database.executebatch(bh,10);
   }
}

 

Batch Class:

 

global class WebserviceBatchHandler implements Database.Batchable<Me__c>, Database.AllowsCallouts{
    
    Me__c[] msquery = [SELECT Id,Name,Annual_Saving__c,Cost__c FROM Me__c where Cost__c =: null];
    global Iterable<Me__c> start(Database.BatchableContext BC){
        system.debug(msquery);
    }
  
    global void execute(Database.BatchableContext BC, List<Me__c> scope){
        //
            for(Me__c MStoupdate : scope){
                String MSName = MStoupdate.Name;
                CallNesWS ws = new CallNesWS();
                ws.CallNesWS(MSName);
        	}
        	//Pass the opportunities to web service method
        	//CallNesWS.CallNesWSMethod(oppmap,oppid);
    }  
    global void finish(Database.BatchableContext BC)
    {
        //Send an email to the User after your batch completes
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
		String[] toAddresses = new String[] {'maf@xxx.com'};
		mail.setToAddresses(toAddresses);
		mail.setSubject('Apex Batch Synch Job is done');
		mail.setPlainTextBody('The batch Apex Synch job processed ');
		Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
}

 

And Test Class is below:

 

@isTest
global class TestBatchScheduler
{
    public static testMethod void testscheduleClass()
    {
        List<Opportunity>oplist = new List<Opportunity>{};
        SchedulableContext SC;
        Test.startTest();
        Account a = new Account(Name = 'Maf Test');
        insert a;

        Opportunity opp = new Opportunity (Name='testopp', Accountid = a.id,stageName = 'request result');
        oplist.add(opp);
        
        Me__c ms = new Me__c(Annual_Saving__c = 100);
        insert ms;
        
        WebserviceScheduler wsch = new WebserviceScheduler();
        wsch.execute(SC);
        string schedule = '0 5 1-23 * * ?';
        system.schedule('Process Trans 1', schedule, wsch);
        Test.stopTest();
    }

    public static testMethod void testBatchClass()
    {
        Database.BatchableContext BC;
        Test.startTest();
        WebserviceBatchHandler b = new WebserviceBatchHandler();
        ID myBatchJobID = database.executebatch(b);
        Test.stopTest();
    }
}

 

 

Any idea how I can increase code coverage for Scheduler???

 

 

Also How can I test the batch class from debug window as I get invalid batchablecontext error??

 

Hi,

 

I am parsing an xml file and putting the value in a Map. Now I would like to update an object with the values in the map But I am getting following error:

 

Initial term of field expression must be a concrete sobject: List <String>

 

My xml parser is below:

 

 private Map<String,list<string>> parsexml(DOM.XMLNode node){
        list<String> mslist = new list<string>();
        Map<String,list<string>> msmap = new Map<String,list<String>>{};
        //system.debug('Node:::'+node);
        String annualsave;
        String costsaving;
        String annualscore;
        String MSId;
        String result;
        
        for(Dom.XMLNode child : node.getChildElements()) {
            //system.debug('child:::'+child);
            for(DOM.XMLNode node1:child.getChildElements()){
                system.debug('child of child::'+node1);
                if(node1.getName()=='Id'){
                    	MSId = node1.getText().trim();
                        system.debug(MSId);
                    }
        		else if(node1.getName()=='Annual-Save'){
                    	annualcarbonsave = node1.getText().trim();
                    	result = annualsave;
                        system.debug(annualsave);
                    	mslist.add(annualsave);
                    }
                    else if(node1.getName()=='Cost-Save'){
                    	costsave = node1.getText().trim();
                        system.debug(costsave);
                        mslist.add(costsave);
                    }
                    else if(node1.getName()=='Annual-Score'){
                    	annualscore = node1.getText().trim();
                        system.debug(costscore);
                        mslist.add(annualscore);
                    }
                msmap.put(MSId,mslist);
            }
        }

        return msmap;
    }

 And Here I am relating this to the salesforce object:

 

Map<String,list<string>> msmap = new Map<String,list<String>>{};

msmap = parsexml(root);

List<Me__c> Ms = [select id, annual_save__c, cost_save__c from Me__c where id in: msmap.keySet()];
        for(Me__c m: Ms){
        	m.cost_save__c = msmap.get(m.id).costsave;
        }

 

Could you please guide me in right direction here.

 

Thanks,

 

 

Hi All, 

 

I am calling an webservice using wsdl class and getting a result successfully. The result is consists of seven strings and one of the strings contains the desired data in xml format. Now when I debug the string I can see the xml string but after parsing and fetching the required data, My debug shows null. 

 

Could anyone please help me on this??

 

Helper class to to Call WS via method in WSDL Class:

 

public class CallWS{
	List<XMLFile__c> xfiles = [select id, sendXML__c, sendXML2__c from XMLFile__c where name = :'XML FIles For WS'];    
    WS_Security_token__c stoken = [select Security_Token__c from WS_Security_token__c where Security_Token__c = :'xxxx'];
    
    String token = stoken.Security_Token__c;
    String xml1 = xfiles[0].sendXML__c;
    String xml2 = xfiles[0].sendXML2__c;
    String wsresult;
    
    //constructor method makes the web service call and gets the result back
    public void CallWS(){
    	NWebservice.NServiceSoap nws = new NWebservice.NServiceSoap();
        NWebservice.ProcessMultipleResponse_element result;
        
        result = nws.ProcessMultiple(token, xml1, xml2);//result consists of multiple xml strings
        String returnedxml = result.ProcessMultipleResult;// required string defined in wsdl
        wresult = returnedxml;
        String x = parsexml(wresult);
        
        system.debug(result);// shows all strings
        system.debug(returnedxml); // shows desired  string
        system.debug(x); // shows null....?? but there's value in this node 
    }
    
    private String parsexml(String toparse){
        String annsave;
        String costsave;
        String save2;
        String supersave;
        DOM.Document doc = new DOM.Document();
        
        try {
    		doc.load(toparse);
            	for(dom.XmlNode node : doc.getRootElement().getChildElements()){
                    if(node.getName()=='Annual-Saving'){
                    	annsave = node.getText().trim();
                        system.debug(annsave);
                    }
                    else if(node.getName()=='Cost-Saving'){
                    	costsave = node.getText().trim();
                        system.debug(costsave);
                    }
                    else if(node.getName()=='Extra-Save'){
                    	save2 = node.getText().trim();
                        system.debug(save2);
                    }
                    else if(node.getName()=='Total-Save'){
                    	supersave = node.getText().trim();
                        system.debug(supersave);
                    }
            	}
  			} catch (System.XMLException e) {  // invalid XML
    		e.getMessage();
  			}
        return annsave;
    }
}

  

Hi All,

 

I have a trigger on Opportunity which updates a field in Line Item when Parent is Updated. I get 83% code coverage. Just curious to know Why not getting with the test class?? Could anyone please have a look:

 

public class OppProductClass{
    public static void OppTermUpdate(List<Opportunity> Opps){
        List <Opportunity> ChangedOpps = New List <Opportunity> ();
        List <Opportunitylineitem> OLIupdate = New List <Opportunitylineitem> ();
        List <Opportunity> tickOppsupdate = New List <Opportunity> ();
    
        For (Opportunity Opps1: Opps){
            //If(opps1.Hours_Spent_is_changed__c == TRUE || opps1.Hours_Spent_is_changed__c == False){
            Changedopps.add(Opps1);
        //}
        }
        /*List<Opportunity> tickboxupdate = [select id, Hours_Spent_Is_Changed__c from Opportunity where Hours_Spent_Is_Changed__c = True];
    
        for(Opportunity op:tickboxupdate){
            op.Hours_Spent_Is_Changed__c = false;
            tickOppsupdate.add(op);
        }*/ 
        
        List <Opportunitylineitem> OLI = [Select ID, Contract_Term__c, opportunityid, Opportunity.Contract_Term__c from Opportunitylineitem where Opportunityid in: Changedopps];
    
        For (Opportunitylineitem newoli: Oli){
            Newoli.Contract_Term__c = Newoli.Opportunity.Contract_Term__c;
            OLIupdate.add(newoli);    
        }
                
        Update Oliupdate;
        //Update tickoppsupdate;
        recursionprevent.preventflag = true;
    }
}

 Test Class:

 

/*
Author: Mahfuz Choudhury
Date: 09.10.13
ClassName:OpportunityFetcher on Opportunity
*/

@isTest(seeAllData=true) 
public class TestOppProductUpdate2{
    private static testMethod void TestOppProduct(){
       OppProductClass objclassconfirm = new OppProductClass();
        
       list <Opportunity> bulkopp = new list<Opportunity>{};
       list <OpportunityLineItem> OLIList = new list<OpportunityLineItem>{};
            
       Opportunity opp = new Opportunity (Name='test', StageName='Needs Analysis', CloseDate=system.today());
       bulkopp.add(opp);   
        
       Pricebook2  standardPb = [select id, name, isActive from Pricebook2 where IsStandard = true limit 1];
       
       Pricebook2 pbk = new Pricebook2 (Name='Test Pricebook Entry 1',Description='Test Pricebook Entry 1', isActive=true);
       insert pbk;
       
       Product2 prd = new Product2 (Name='Premium Product',Description='Test Product Entry 1',productCode = 'ABC', isActive = true);
       insert prd;
       
       PricebookEntry pbe = new PricebookEntry (Product2ID=prd.id,Pricebook2ID=standardPb.id,UnitPrice=50, isActive=true,UseStandardPrice=false);
       insert pbe;
        
       OpportunityLineItem OLI = new OpportunityLineItem();
       OLI.Quantity = 2;
       OLI.OpportunityId = bulkopp[0].id;
       OLI.UnitPrice = 5.00;
       OLI.PricebookEntryId = pbe.id;

       // Insert opportunity
       Test.starttest();
        try{
            OppProductClass.OppTermUpdate(bulkopp);
            insert bulkopp;
            insert OLI;
            bulkopp[0].Contract_Term__c = 15;
            OppProductClass.OppTermUpdate(bulkopp);
            Update OLI;
            Update bulkopp;
            OLI = [SELECT Quantity, Contract_Term__c FROM OpportunityLineItem WHERE Id =:bulkopp[0].Id limit 1];
            }catch(DMLexception e){
            System.assertEquals('test',bulkopp[0].Name);
            System.assertEquals(bulkopp[0].Contract_Term__c, OLI.Contract_Term__c);
            }
       Test.stopTest();

        
    }
}

 Please note, I do not get coverage for the following:

For (Opportunitylineitem newoli: Oli){
            Newoli.Contract_Term__c = Newoli.Opportunity.Contract_Term__c;
            OLIupdate.add(newoli);    
        }

 

Hi All,

 

I am new in visual force. I have written my first visual force controller class and having issue with the test class. My controller class is below:

 

public class TestVFController{
    Private Account ACID;
    public List<Contact> Conts {get; set;}
    public Boolean refreshPage {get; set;}
    ApexPages.StandardController stdCtrl;

public TestVFController(ApexPages.StandardController myController) {
    	stdCtrl = myController;
    	refreshPage = false;
        This.ACID = (Account)stdCtrl.getRecord();
        Conts = new List<Contact>();
        Contact c = new Contact();
        c.accountid = ACID.id;
        Conts.add(c);
}
        
    public void addrow() {
        Conts.add(new Contact());}
            
    public void removerow(){
        Integer i = conts.size();
        Conts.remove(i-1);}
            
    public PageReference savereturn() {
        insert Conts;
        //PageReference result = stdctrl.view();
        PageReference result = new PageReference('/apex/test2');
        //PageReference result=ApexPages.currentpage();
        result.setRedirect(true);
        return result;
    }
        
    public PageReference OK(){
        refreshPage = true;
        PageReference pageRef = new PageReference('/apex/test1');
        //pageRef.setRedirect(true);
        return pageref;
    }
}

 

And my test class is below:

@isTest
public class TestForController{
    static testMethod void Testmycontroller() {
        List<Contact> c = new List<Contact>{};
        Account act = new Account(Name = 'Test acc');
        insert act;
        
        PageReference pageRef = Page.test1;
        Test.setCurrentPage(pageRef);
        
        // Instantiate the standard controller
        Apexpages.StandardController sc = new Apexpages.standardController(act);
        TestVFController mycon  = new TestVFController(sc);
        String nextPage = mycon.savereturn().getUrl();
        
        Contact con = new Contact();
        con.FirstName = 'Maf';
        con.LastName = 'Test';
        Con.Email = 'maf@test.com';
        Con.accountid = act.id;
        c.add(Con);
        insert c;
        
        mycon.Conts.add(con);
        
        mycon.savereturn();
        mycon.addrow();
        mycon.removerow();
    }
}

 

Note that, My Standard Controller is Account and My extension controller class is Adding multiple contacts related to that account

 

I get the following error and only 53% code coverage:

 

System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [LastName]: [LastName]


Class.TestVFController.savereturn: line 25, column 1
Class.TestForController.Testmycontroller: line 15, column 1

 

Could anyone please help me on that???

 

Hi All,

 

I have custom VF page block where there are two input fields take input and create a contact associated with this account. It also should redirect to another page where customer click to get back to the same page. Now how do I associate this new contact with the account? Also my redirection does not work?? Any help would be appreciated. My code is below:

 

Page Block:

<apex:page standardController="Account" extensions="ContactEntry"  sidebar="false" showHeader="false" >
    <apex:form >
    <apex:pageBlock title="Sales Contacts Quick Entry" >
            <apex:pageBlockButtons >
                <apex:commandButton value="Save" alt="save" action="{!save}" rerender="error" id="savebutton" />
            </apex:pageBlockButtons>
            <apex:pageBlockTable value="{!conts}" var="a" id="table">
                <apex:column headerValue="First Name">
                    <apex:inputField value="{!a.FirstName}"/>
                </apex:column>               
                <apex:column headerValue="Last Name">
                    <apex:inputField value="{!a.LastName}"/>
                </apex:column>                
                <apex:column headerValue="Phone">
                    <apex:inputField value="{!a.Phone}"/>
                </apex:column>
                <apex:column headerValue="Email">
                    <apex:inputField value="{!a.Email}"/>
                </apex:column>
            </apex:pageBlockTable>
    <apex:pageblockButtons location="bottom">
        <div style="text-align:right;margin-right:30px;font-weight:bold;">
            <apex:commandLink value="Add Row" action="{!addRow}" rerender="table,error" immediate="true" />
&nbsp;|&nbsp;&nbsp;
            <apex:commandLink value="Remove Row" action="{!removeRow}" rerender="table,error" immediate="true" />                
        </div>
    </apex:pageblockButtons>  
    </apex:pageBlock>
    </apex:form>
</apex:page>

 

 

And Apex Class:

 

public class ContactEntry{

    public List<Contact> Conts {get; set;}

    public ContactEntry(ApexPages.StandardController myController) {
        Conts = new List<Contact>();
        //Contact c = new Contact();
        Conts.add(New Contact());}
        
    public void addrow() {
        Conts.add(new Contact());}
            
    public void removerow(){
        Integer i = conts.size();
        Conts.remove(i-1);}
            
    public PageReference save() {
        insert Conts;
        PageReference secondPage = Page.test2;
        secondPage.setRedirect(true);
        return secondPage; }
        
    public PageReference OK(){
        PageReference pageRef = new PageReference('/apex/test1');
        return pageref;
    }
}

 

Test 2 is the confirmation page and is below:

 

<apex:page standardController="Account" extensions="ContactEntry"  sidebar="false" showHeader="false" >
    <apex:form >
    <apex:pageBlock title="Sales Contact Save Confirmation" >
            <apex:pageBlockButtons >
                <apex:commandButton value="OK" alt="OK" action="{!OK}" id="confirmbutton" />
            </apex:pageBlockButtons>
            <apex:pageBlock >
            "Your Contacts have been added"
            </apex:pageBlock>
    <apex:pageblockButtons location="bottom">
        <div style="text-align:right;margin-right:30px;font-weight:bold;">             
        </div>
    </apex:pageblockButtons>  
    </apex:pageBlock>
    </apex:form>
</apex:page>

 

 

I get an URL does not exist error???

 

 

Hi,

 

Could anyone please provide me an example of creating an XML from field values of an object. I need to create this xml and send as string to a web service. Any suggestion also be appreciated.

 

Thanks

Hi All,

 

I am trying to build an integration with an outside website to send some data and get result back using web service. I have been given their WSDL file along with a security token. Now, I have consumed the WSDL file in apex and created a class from that. Now my question is:

 

  1. How do I make the web service call (e.g. provide security token, provide xml file which needs to be passed over to other system. From same class or a different class)
  2. If it's from a different class which methods I call and where do I put the credentials i.e. security token

Could someone please provide a simple example as Salesforce docs didn't help me much to get the grasp of it

 

M

  • September 27, 2013
  • Like
  • 0

Hi,

 

I was wondering if anyone could help me on the following test class as I am getting an error message and getting only 52% code coverage:

 

My Email Service Class is:

global class EmailDemoReceive implements Messaging.InboundEmailHandler {
  global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, 
                                                         Messaging.Inboundenvelope envelope) {
  	
    Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
                                                             
    //retrieve all eco survey where it matches with the email subject.... 
    List<Opportunity> existingsurveys = [select id, Job_Reference__c from Opportunity where Job_Reference__c = :email.subject];
    Map<id,Opportunity> ES = new Map<id,Opportunity>{};
    ID ESid;
        
        for(Opportunity Opp: existingsurveys){
        	//ES.put(Opp.id, Opp);
            ESid = Opp.id;
        }
    try{
        //check Eco Survey for an existing record with same reference and there's an attachment
        if(existingsurveys.size() > 0){
            // Save attachments
            if(email.binaryAttachments!=null && email.binaryAttachments.size()>0){
            	for (Messaging.Inboundemail.BinaryAttachment bAttachment : email.binaryAttachments) {
  					Attachment attachment = new Attachment();
                    String checker = bAttachment.filename;
 
                    //only accept xml attachments..
                    if(checker.contains('.xml')||checker.contains('.pdf')){
                    	attachment.Name = bAttachment.fileName;
  						attachment.Body = bAttachment.body;
  						attachment.ParentId = ESid;
                		//attachment.ParentId = ES.get(EcoSurvey__c).id;
  						insert attachment;
                    }
                    else{
                    	continue;
                    }
				}
            }
        }
    
    }Catch(QueryException e){
    
    }
    return result;
    }
}

 

And Test Class Is:

 

@isTest(SeeAllData=true)
public class TestEmailAttachment{
	public static testMethod void EmailAttachmentTester(){
        
        // setup controller object
        EmailDemoReceive objconfirm = new EmailDemoReceive();
        System.debug('Im starting a method');
        
        //Create an Account for the opportunity to be created
        Account acc = new Account();
        acc.Name = 'M.Choudhury';
        insert acc;
        
        
        //create a new opportunity with email subject as job reference number
        Opportunity Opp = new Opportunity();
        Opp.Name = 'tasty test';
        Opp.Accountid = acc.id;
        Opp.StageName = 'Pre Qualification';
        Opp.closedate = Date.Today()+2;
        insert Opp;
        
        Opportunity testop1 = [select id, Job_Reference__c from Opportunity where id = :Opp.id];
        
        // Create a new email, envelope object and Attachment
        Messaging.InboundEmail email = new Messaging.InboundEmail();
        Messaging.InboundEnvelope envelope = new Messaging.InboundEnvelope();
        objconfirm.handleInboundEmail(email, envelope);
        
        email.subject = testop1.Job_Reference__c;
        email.plainTextBody = 'Hello, this a test email body. for testing purposes only. Bye';
        envelope.fromAddress = 'maf@cloudsocius.com';
        Messaging.InboundEmail.BinaryAttachment[] binaryAttachments = new Messaging.InboundEmail.BinaryAttachment[2];
        Messaging.InboundEmail.BinaryAttachment binaryAttachment = new Messaging.InboundEmail.BinaryAttachment();
		binaryAttachment.Filename = 'test.pdf';
        
        Messaging.InboundEmail.BinaryAttachment binaryAttachment1 = new Messaging.InboundEmail.BinaryAttachment();
        binaryAttachment1.Filename = 'test.xml';
        
        
        Messaging.InboundEmailResult result = objconfirm.handleInboundEmail(email, envelope);
        System.assertEquals( result.success  ,true);
        
        update testop1;
        
        //Opportunity testop = [select id, Job_Reference__c from Opportunity where id = :testop1.id];
        
        Attachment att = [Select id, name, parentid from Attachment where parentid = :testop1.id and name = 'test.pdf'];
        System.assertEquals(binaryAttachment.Filename,att.name);
    
    }
}

 I get the following error Message:

 

System.QueryException: List has no rows for assignment to SObject

Class.TestEmailAttachment.EmailAttachmentTester: line 48, column 1

 

  • September 26, 2013
  • Like
  • 0

Hi Guys, I have an email server which receives email and compare the email subject with an external id field and if they both match the attachment should be saved against that record I have written the following class but can't figure out how to match and save the attachment. Any help would be appreciated:

 

InboundMessage Class:

 

global class EmailDemoReceive implements Messaging.InboundEmailHandler {
  global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, 
                                                         Messaging.Inboundenvelope envelope) {
  	
    //retrieve all eco survey where it matches with the email subject.... 
    List<EcoSurvey__c> existingsurveys = [select id, Job_Reference__c from EcoSurvey__c where Job_Reference__c = :email.subject];
    Map<id,EcoSurvey__c> ES = new Map<id,EcoSurvey__c>{};
        
        for(EcoSurvey__c MES: existingsurveys){
        	ES.put(MES.id, MES);
        }
    try{
        //check Eco Survey for an existing record with same reference and there's an attachment
        if(existingsurveys.size() > 0 && 
           (email.binaryAttachments != null && email.binaryAttachments.size() > 0||
           email.TextAttachment != null && email.TextAttachment.size() > 0)){
            // Save attachments
			for (Messaging.Inboundemail.TextAttachment tAttachment : email.textAttachments) {
  				Attachment attachment = new Attachment();
 
  				attachment.Name = tAttachment.fileName;
  				attachment.Body = Blob.valueOf(tAttachment.body);
  				attachment.ParentId = ES.get(email.subject).id;;
  				insert attachment;
			}
			for (Messaging.Inboundemail.BinaryAttachment bAttachment : email.binaryAttachments) {
  				Attachment attachment = new Attachment();
 
  				attachment.Name = bAttachment.fileName;
  				attachment.Body = bAttachment.body;
  				attachment.ParentId = ES.get(email.subject).id;
  				insert attachment;
			}
        }
    
    }Catch(QueryException e){
    
    }
    Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
    return result;
    }
}

 

  • September 23, 2013
  • Like
  • 0

Hi,

I have a trigger on Opportunity which fires once opportunity stage = closed won. My Test method passes but shows error on class?

 

/*
Author: Mahfuz Choudhury
Date: 13.09.13
TestClassName:TestCloneOppLineItem on Opportunity
*/
@isTest(seeAllData=true) 
private class TestCloneOppLineItem{
    static testMethod void TestOppMethod() {
        List<Contact> contlist = new List<Contact>{};
        
        //Start of the test execution
        Test.starttest();
        //create a new account to associate with the opportunity
        Account a = new Account(Name = 'Test Account');
        insert a;
        
        //Create a contact to assign as primary contact role
        Contact con = new Contact(FirstName = 'Maf', LastName = 'Sample', AccountId = a.Id);
        Contact con1 = new Contact(FirstName = 'Lewis', LastName = 'Test', AccountId = a.Id);
        contlist.add(con);
        contlist.add(con1);
        insert contlist;
        
        //Select A Standard pricebook for the product
        Pricebook2  standardPb = [select id, name, isActive from Pricebook2 where IsStandard = true limit 1];
        
        //Create a Test PriceBook for OpportunityLineItem
        Pricebook2 pbk = new Pricebook2 (Name='Test Pricebook Entry 1',Description='Test Pricebook Entry 1', isActive=true);
        insert pbk;
        
        //Insert a new Product for test class
        Product2 prd = new Product2 (Name='Premium Product',Description='Test Product Entry 1',productCode = 'ABC', isActive = true);
        insert prd;
        
        //Insert a new Pricebook entry
        PricebookEntry pbe = new PricebookEntry (Product2ID=prd.id,Pricebook2ID=standardPb.id,UnitPrice=50, isActive=true,UseStandardPrice=false);
        insert pbe;
        
        //create a new opportunity to test
        Opportunity opp = new Opportunity();
        opp.Name = 'Test Opportunity';
        Opp.AccountId = a.id;
        Opp.StageName = 'Closed Won';
        Opp.Type = 'Existing Business';
        Opp.CloseDate =  Date.today()+2;
        insert opp;
        
        OpportunityLineItem OLI = new OpportunityLineItem();
        OLI.Quantity = 2;
        OLI.UnitPrice = 5.00;
        OLI.OpportunityId = Opp.id;
        //OLI.ProductId = pbe.Id;
        OLI.PricebookEntryId = pbe.id;
        insert OLI;
        
        //creating opportunity contact role and make it primary
        OpportunityContactRole ocr = new OpportunityContactRole(OpportunityId = Opp.Id, ContactId = Con.Id, IsPrimary = true);
        insert ocr;
        
        System.assertEquals('Closed Won',Opp.StageName);
        System.assertEquals(Opp.IsOnlineOrder__c, false);
        
        Opp.IsOnlineOrder__c = true;
        Update Opp;
        System.assertEquals(Opp.IsOnlineOrder__c, true);
        Test.stopTest();
    }
}

 Can I get some help on this plz...

  • September 13, 2013
  • Like
  • 0
Hi Friends,
I have a requirement to create batch apex code to import csv file without use of visualforce page i.e. directly from system through file path. And schedule this batch class to import csv file automatically after 2 days.
Guys please help me for this problem statement as early as possible.
Thank you much in advance for your valuable help.

Regards,
Nitesh 
I am trying to use, google captcha and google translate in lightning component. Though from spring'17 release we can not use third party javascripts in lightning even if we have added them to csp. We will have to add that script in static resource and call it in lightning component. As per google, script for these pages are dynamically generated and not suggested to be stored and used. Any workaround for making this work in lightning?
Hi All,

I am trying to do a really simple thing here but it's not working. I am trying to display a page message from action function method but it's not working. I have checked the debug log as well but it seems like it's not invoking the method at all. Could anyone see if I am doing anything wrong here:

<apex:page standardController="MyObject__c" extensions="MyControllerExt" >
    <apex:form id="MainForm">
    
        <apex:actionFunction name="InvokeActionFunction" action="{!InvokeActionFunction}" rendered="{!displayactionfunction}" reRender="MainForm,Msg"/>
        
        <apex:pageBlock>
            <apex:pageBlockSection>
                    <apex:messages id="Msg"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
        
    </apex:form>
</apex:page>

Controller Ext:

public class MyControllerExt{
    Public static Customer__c Cus {get; set;}
    public boolean displayactionfunction{get; set;}
    public MyControllerExt(ApexPages.StandardController CusController)
    {
		System.debug('Record to process is: ------------->'+CusController.getRecord());
        Cus = (Customer__c)CusController.getRecord();
        displayactionfunction = true;
    }
    
    Public void InvokeActionFunction()
    {
        ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL,System.Label.Problem_Saving_Record);
        ApexPages.addMessage(myMsg);
        System.debug('Page Message is-------------------------------->'+myMsg);
        displayactionfunction = false;
    }
}

Thanks in advance!
Hi All,

I have a visualforce page which overrides the new button for creating new record. It performs data validation and rerenders the page if something is wrong. I am trying to use same controller extension from a custom button as well. but when I add the visual force page in my button I get following error:

SObject row was retrieved via SOQL without querying the requested field:

A lot of people suggested to set rendered = false on the page but that does not meet my requirement as I need to get those fields in edit mode to perform similar action as I did when creating the record.

Any suggestions would be greatly appreciated.
Hi All I am trying to parse an XML string using DOM parser and got stuck. Is there anyone who can give me some insight on this:

Below is the XML string I am trying to Parse:

String XmlResponse = '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> '+
   						' <soap:Body>'+
      					'<GetInventoryDetailsResponse xmlns="http://services.XXXXXXX.com/schema/bs/inventory/v01/MaintainInventory" xmlns:ns2="http://services.XXXXXXX.com/schema/common/header/v01/Header" xmlns:ns3="http://services.XXXXXXX.com/schema/common/inventory/v01/inventory" xmlns:ns4="http://services.XXXXXXX.com/schema/common/acknowledgement/v01/Acknowledgement"> '+
      					'<Inventory>'+
   						'<ns3:TypeDesignator>test</ns3:TypeDesignator>'+
   						'<ns3:TypeDescription>test123</ns3:TypeDescription>'+
      					'</Inventory>'+
   						'</GetInventoryDetailsResponse>'+
						'</soap:Body>'+
        				'</soap:Envelope>';

And my Code is Below:

public static final String soapNS = 'http://schemas.xmlsoap.org/soap/envelope/';
public static final String Acknowledgement_ns = 'http://services.xxxx.com/schema/common/acknowledgement/v01/Acknowledgement';
public static final String MaintainInv_ns = 'http://services.xxxx.com/schema/bs/Inventory/v01/MaintainInventory';
public static final String Inv_ns = 'http://services.xxxx.com/schema/common/Inventory/v01/Inventory';
public static final String Head_ns = 'http://services.xxxx.com/schema/common/header/v01/Header';

Dom.Document doc = new Dom.Document();
doc.load(XmlResponse);

dom.XmlNode xroot = doc.getrootelement();
String body_prefix = xroot.getPrefixFor(soapNS);
			
System.debug('Body Prefix is: ----------------'+body_prefix);
			
dom.XmlNode body = xroot.getChildElement('Body', soapNS);
			
System.debug('Body is: ---------------->>>'+body);

dom.XmlNode Invres = body.getChildElement('GetInventoryDetailsResponse', null);

System.debug(Invres is: ---------------->>>'+Invres);

//Above Line I get null Value but it should have inventory node under it???

tried with following still same issue:

//dom.XmlNode Invres = body.getChildElement('GetInventoryDetailsResponse', MaintainInventory_ns+' '+Inventory_ns+' '+Head_ns+' '+Acknowledgement_ns);

Any Idea what is wrong there?


Hi All,

I have a batch call out class which has a nested SOQL query string in start method. My test class fails with following:

System.SObjectException: Invalid aggregate relationship Child Relationship Name for Account

my code is below:

global class batchclassname implements Database.Batchable<sObject>, Database.Stateful, Database.AllowsCallouts
{

     global database.querylocator start(Database.BatchableContext BC)
    {
	 String Query = 'SELECT id, Industry__c, (Select id, Account_Name__c from Children__r where active__c = true) FROM Account Limit 100';
        
     return Database.getQueryLocator(Query);
    }
    
    global void execute(Database.BatchableContext BC, List<SObject> scope)
    {   
        if(scope.size()>0)
        {
			for(sobject s: scope)
        	{
            	//Get the Account sobject
            	Account a = (Account)s;
            	
            	List<Child__c> RelatedChildren = a.getsobjects('Children__r'); // This line causing issue in test class I believe
               
                       for(Child__c Ch:RelatedChildren)
                      {
                           do some call out here....
                       }
                  }
            }
     }

    global void finish(Database.BatchableContext BC)
    {
        	
    }
    

}
Hello guys,

This error is driving me crasy
arithmetic expression must use numeric argument

obj.Without_credit_time_off_amount__c =( (User.Salary__c)/30)*obj.Days__c;

Without_credit_time_off_amount__c currency type
Days__c formula field, number type
Salary__c is a currency type

I've tried to cast the salary__c value but in vain

Hi All,

 

I am writing a trigger on Contact to update a date field on account depending on a date field on all related contacts. I am getting a List out of bound  exception: 4

 

Could I please have some guidance on how to rectify this issue? My code is below:

 

//Method to process Trigger.new context for after trigger
    public void LastActivityDateUpdate(List<Contact> updatedcontacts){
        Set<id> contactids = new Set<id>{};
        
        for(Contact con:updatedcontacts){
            if(con.Last_Activity_Date__c != null){
        		contactids.add(con.AccountId);
            }
        }
        
        List<Account> Accwithdateupdate = [Select id, Last_Modified_Date__c, (select id, Last_Activity_Date__c from Contacts) from Account where id in: contactids];
        DateTime lastactivitydateholder;
        
        for(Account a : Accwithdateupdate){
            
            for(Contact c: a.contacts){
                for(integer i = 0; i<a.contacts.size(); i++){
                    lastactivitydateholder = (a.contacts[i].Last_Activity_Date__c > a.contacts[i+1].Last_Activity_Date__c) ? a.contacts[i].Last_Activity_Date__c : a.contacts[i+1].Last_Activity_Date__c;
					//lastactivitydateholder = c.LastActivityDate;
                	//lastactivitydateholder1 = lastactivitydateholder;
                }
            }
            a.Last_Modified_Date__c = lastactivitydateholder;
        }
        update Accwithdateupdate;
    }

 

Thanks in Advance.

Hi ,

 

I have done one test method for my Trigger . Myunittest method is success with out returning errors I observed this under Tests tab in developer console. but it showing Failed symbol for my testclass .

 

Tests [tab] from developer console

 

Failed symbol : Here mytest Class Name  

but here if i open my test method it showing success symbol. 

 

 

 

Can any one help me on this.

 

  • November 14, 2013
  • Like
  • 0

Hi,

 

I'm getting 'You have uncommitted work pending. Please commit or rollback before calling out' msg when I run my test class.  Can somebody help me to fix this please?

 

global class LeadCallOutBatchable implements Database.Batchable<sObject>, Database.AllowsCallouts{

global final String Query;

   global final String Entity;

 

   global LeadCallOutBatchable() {

      Query='SELECT Id, FirstName, LastName, UserName__c, Email, Title, fs_skills__c, fs_overview__c, fs_facebook__c, fs_twitter__c, fs_linkedin__c ' +   'FROM Lead WHERE UserName__c != null';  

        Entity= 'Lead';

   }

 

   global Database.QueryLocator start(Database.BatchableContext BC) {

      return Database.getQueryLocator(query);

   }

    

   global void execute(Database.BatchableContext BC, List<Lead> scope) {

        

        List<Lead> leadsToUpdate = new List<Lead>();

        String PersonURL ;

        Integer count = 0;

        System.debug('scope: ' + scope);

        

        for(Lead leadRec : scope ) {   

            String jResponse = '';

            JPersonList deserialPersonList = new JPersonList();

            count++;

            System.debug('Count: ' + count);           

            PersonURL =  URL

            

            try {

                HttpRequest req = new HttpRequest();

                req.setMethod('GET');

                String username = JUSERNAME;

                String password = JPW;

                Blob headerValue = Blob.valueOf(username + ':' + password);

                String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(headerValue);

                req.setHeader('Authorization', authorizationHeader);

                req.setHeader('Accept', 'application/json');

                req.setEndPoint(PersonURL);

                

                Http http = new Http();

                system.debug('req: ' + req);

                HTTPResponse res = http.send(req);

         

               jResponse = res.getBody();

                

 

                jResponse = jResponse.Replace('throw \'allowIllegalResourceCall is false.\';', '');    

                //System.debug('Request Body: ' + jResponse);

                

                JSONParser parser = JSON.createParser(jResponse);

 

  // deserialize

                JObject personRecord = (JObject) System.JSON.deserialize(jResponse, JObject.class);

 

//some codes to compare

                

                       leadsToUpdate.add(leadRec);

                       System.debug('leadsToUpdate: ' + leadsToUpdate);

            }

            }

            catch(Exception ex) {

                System.debug('Exception: ' + ex);   

            }

        }

        System.debug('leadsToUpdate: ' + leadsToUpdate);

        update leadsToUpdate;

    }

        

   global void finish(Database.BatchableContext BC){ 

   }

}

 

 

test classes:

 

@isTest

public class LeadCalloutBatchableTest{

    public static testmethod void TestLeadCalloutBatchable() {

        

        List<ID> acRecs=new List<ID>();

        Lead testLead = new Lead( IncludeInSFToSync__c = true, FirstName = 'STEVE' , LastName = 'JOHN', UserName__c = 'stevej', Email = 'r@gmail.com', Title = 'testtest', fs_skills__c = 'developement' , fs_overview__c='good', fs_facebook__c='facebook', fs_twitter__c='twitter', fs_linkedin__c = 'linkedin');

        insert testLead;

        acRecs.add(testLead.id);

       

        string JSONstr = 

        SingleRequestMock fakeResponse = new SingleRequestMock(200,'Complete', JSONstr ,null);

 

        Test.startTest();

        Test.setMock(HttpCalloutMock.class, fakeResponse);

        Database.executeBatch(new LeadCallOutBatchable(), 200);

       

        Test.stopTest();

   

    }

}

 

 

@isTest

global class SingleRequestMock implements HttpCalloutMock {

    protected Integer code;

    protected String status;

    protected String bodyAsString;

    protected Blob bodyAsBlob;

    protected Map<String, String> responseHeaders;

  

   

    public SingleRequestMock(Integer code, String status, String body, Map<String, String> responseHeaders) {

        this.code = code;

        this.status = status;

        this.bodyAsString = body;

        this.bodyAsBlob = null;

        this.responseHeaders = responseHeaders;

 

    }

         

   public SingleRequestMock(Integer code, String status, Blob body, Map<String, String> responseHeaders) {

        this.code = code;

        this.status = status;

        this.bodyAsBlob = body;

        this.bodyAsString = null;

        this.responseHeaders = responseHeaders;

    }

    

    public HTTPResponse respond(HTTPRequest req) {

        HttpResponse resp = new HttpResponse();

        resp.setStatusCode(code);

        resp.setStatus(status);

        if (bodyAsBlob != null) {

            resp.setBodyAsBlob(bodyAsBlob);

        } else {

            resp.setBody(bodyAsString);

        }

        

        if (responseHeaders != null) {

            for (String key : responseHeaders.keySet()) {

                resp.setHeader(key, responseHeaders.get(key));

            }

        }

        return resp;

    }  

}

 

 

 

  • November 13, 2013
  • Like
  • 0

Does anyone know why an Activity is not showing up when I edit my BeazerLot__c object although I have made the following trigger code:

 

trigger CreateTaskonCloseofDateEscrow45DayCall on BeazerLot__c (after update) {


BeazerLot__c b = new BeazerLot__c ();


Task t = new Task();
t.OwnerID = trigger.new[0].Ownerid; //trigger.new[0].DefaultCaseOwner__c;
t.Subject = '45 Day Call';

insert t;

}