• sfdcfox
  • ALL STAR
  • 24859 Points
  • Member since 2007

  • Chatter
    Feed
  • 897
    Best Answers
  • 7
    Likes Received
  • 2
    Likes Given
  • 32
    Questions
  • 4551
    Replies
Hi, we have a requirement to integrate Salesforce with a ThirdParty Vendor using webservices.

We need to send around 300,000 Records from Salesforce to the ThirdParty vendor using their webservice.
We have a custom apex program using which we are able to call the third party web service successfully within a future method in a schedulable program. However, for a volume as high as 300k records, I am not sure how to avoid hitting the governer limits. My understanding is that, I can make 10 calls in an apex class and can call the future method 10 times, making 100 web service calls in total. This is not sufficient for 300k records. Supposing we can include multiple records in one call, we will still hit another problem. Since each call's size is restricted to 3 MB and our one SOAP call's xml size is around 20k, the maximum we can do is 150 records per call giving us the ability to send 150 X 100 = 15k records. Is there any method to avoid hitting governer limits in this scenario.

Please help me as I am new to Sales force development.
Hi

I am trying to display image in visualforce page based on condition. The condition applied is on {$CurrentPage.parameters.startpage} value.

If {$CurrentPage.parameters.startpage} = "xyz" then display image <apex:image  url="xxxxxxx"> else display image <apex:image  url="yyyy">

I click a link and try to get the parameters of that url. Based on those parameter, I have to render different images on VF Page.

www.testurl.com/?value=xyz

www.testurl.com/?value=abc

Please find below the code I am using and let me know whats wrong there

<apex:image value="{If({!$CurrentPage.parameters.startpage}='xyz','/servlet/servlet.ImageServer?id=015D0000002Dkr2&oid=00DD0000000CWRY&lastMod=1388753305000' , '/servlet/servlet.ImageServer?id=015D0000002Dkr2&oid=00DD0000000CWRY&lastMod=1388753305000')}" />

Hi all,
      This is my first attempt at using JSON in APEX, seems pretty straight forward.  I have what I think is a very simple question...making a call out to a webservice that is returning a JSON string for new order information.   In my apex class, I have a simple order class:
public class OrderInfo{
     public String CustomerName {get; set;}
     public String CustomerNo {get; set;}
     public String OrderStatus {get; set;}
     public String CustomerPONo{get; set;}
     public String Name {get; set;}
     public String GrossAmount {get; set;}
     public String WantedDeliveryDate {get; set;}

}

I make a call out to my webservice and get back my JSON string...all is well.  Now I need to deserialize it which I'm doing like this:
HTTPResponse res = h.send(req);  //response comes back correctly, data is all formatted as I would expect..
       //deserialize the JSON data returned by the web service into the OrderInfo class defined above
        OrderInfo newOrder = new OrderInfo();
        newOrder = (OrderInfo)JSON.deserialize(res.getBody(), OrderInfo.class);
So here is my problem, when I look at the values of my newOrder object they are all null.  Based on examples I viewed, It looked like the deserialize method with a specified object type would update the values in the object.  Do I need to do something else to save the values into the newOrder object?  
    I really appreciate any assistance, I'm sure it's something very simple!  Thanks in advance!!

Hi and thanks for your help.

I have 2 custom objects:
• Registrations
•  Registration Requests
The Problem: When the Registration Request Before Insert Trigger catches a duplicate it doesn’t stop the After Insert Trigger from running.  What is the best way to stop the processing of the After Insert Trigger if the error message is thrown in the Before Insert Trigger?
Registrations Object has this trigger to stop duplicates from being entered and a way to bypass it if decided:


trigger stopDupsonRegistrations on Registration__c (before insert) {
    Map<String, Registration__c> regMap = new Map<String, Registration__c>();
    Map<String, Registration__c> regMap1 = new Map<String, Registration__c>();
    Map<Boolean, Registration__c> regMap2 = new Map<Boolean, Registration__c>();
    Map<Boolean, Registration__c> regMap3 = new Map<Boolean, Registration__c>();       
    for (Registration__c regReq : System.Trigger.new) {
                // store registration pertinent values
                regmap.put(regReq.Account__c, regReq);
                regmap1.put(regReq.Product__c,regReq);
                regmap2.put(regReq.Duplicate_Registration__c,regReq);
                //regmap3.put(regReg.Manufacturer_Name__c,regReq      
    //Loop through and make sure no duplicates exist    //fields are Account, Product         
    for (Registration__c reg : [SELECT Account__c,Product__c,Manufacturer__c, Registration_Status__c FROM Registration__c]) {
   If (regReq.Duplicate_Registration__c == False && regReq.Account__c == regReq.Account__c && reg.Product__c == regReq.Product__c )      {
       regReq.addError('Registration for this Product already exists. If you want to enter it anyway, check the "Account has multiple locations" checkbox'  + ' and fill out the Location field');      
      }// end regReq.Duplicate_Registration__c   
}  //end for (Registration__c reg :
} // for (Registration__c regReq
}// end trigger

Registration Request object has 2 triggers Before insert and After insert
The before insert is:  This checks to see if a duplicate record exists and if so throw a message.
trigger stopDuplicateRegRequest on Registration_Requests__c (before insert, before update) {
    Map<String, Registration_Requests__c> regMap = new Map<String, Registration_Requests__c>();
    Map<String, Registration_Requests__c> regMap1 = new Map<String, Registration_Requests__c>();   
    Map<Boolean, Registration_Requests__c> regMap2 = new Map<Boolean, Registration_Requests__c>();
       
    for (Registration_Requests__c regReq : System.Trigger.new) {
                // store registration Request pertinent values
                regmap.put(regReq.Account__c, regReq);
                regmap1.put(regReq.Product__c,regReq);          
                regmap2.put(regReq.Duplicate_Registration__c,regReq); 
      
    //Loop through and make sure no duplicates exist
    //fields are Account, Product 
   
    for (Registration__c reg : [SELECT Account__c,Product__c, Registration_Status__c, Duplicate_Registration__c FROM Registration__c])
{
   If (regReq.Duplicate_Registration__c == False && reg.Account__c == regReq.Account__c && reg.Product__c == regReq.Product__c )
      {
      regReq.addError('Registration for this Product already exists. If you want to enter it anyway, check the "Account has multiple locations" checkbox'
                       + ' and fill out the Location field');
      regReq.StopInsert__c = True;                
       }// end if
      
} //end for (Registration__c reg
}//for (Registration_Requests__c

       }//end trigger

The after trigger is:  It is just a simple record creation.

trigger Reg_Request_to_Reg on Registration_Requests__c (after insert) {
    List<Registration__c> newRegistration = new List <Registration__c>();
   
           for (Registration_Requests__c reg : trigger.new) {
           
            Registration__c newReg = new Registration__c();
            newReg.Account__c = reg.Account__c;
            newReg.Opportunity__c = reg.Opportunity_Name__c;
            newReg.Product__c = reg.Product__c;
            newReg.Manufacturer_Name__c = reg.Manufacturer_Name__c;
            newReg.Inside_Sales_Rep__c = reg.Inside_Sales_Rep__c;
            newReg.Location__c = reg.Location__c;
            newReg.Duplicate_Registration__c = reg.Duplicate_Registration__c;
            newReg.Registration_Request_URL__c = 'https://na12.salesforce.com/' + reg.ID;
            newRegistration.add(newReg);
           
        }//end for
       
        insert newRegistration;
       
        }//end trigger
I have code that returns a fieldset based on a field's value (e.g. if Field is X, returns fieldset X but if Field is Y, returns fieldset Y. It then cycles through and adds up the number of fields in the fieldset. Next, I'd like to be able to cycle through each field and if its value is "Yes", then add a count. Below is a code snippet. Obviously, the if(lead[f.getFieldPath()] == 'Yes') line does not work. How can I find the value of the fieldsetmember? I also tried constructing a database.query (string query = 'Select ' + f.getFieldPath() + ' from lead where id =: lead.id'), but then I can't figure out how to query the result just for the field value.

if (fsMap.get(strProgram) != null){
                for(Schema.FieldSetMember f : fsMap.get(strProgram).getFields()) {
                    TotalPreReqs += 1;
               
                if(lead[f.getFieldPath()]== 'Yes'){              
                    PreReqCount += 1;          
             
                }
            }//end cycle through fieldset
            }
  • December 30, 2014
  • Like
  • 0
As part of an approval process I'm creating I'd like to be able to attach a license key to an email that is then sent to a contact email of an opportunity when the opportunity is approved.

We have a separate system that generates & stores our license keys & I'd like to avoid having to upload the key to SFDC to avoid duplication & confusion over which is the valid key as the attached one will have a short expirey time on it.
Hi All ,
Help for a new salesforce enthusiastic..Cance of improving this trigger for bulk loads? How can i use try catch?
Many Thanks!!

trigger updateGTAHotelCount on Account (after delete, after insert, after update) {

//The Triger will update the GTA Hotels Statistics for this year in Strategy Master City for the Accounts with Property Status = LIVE and RecordType= Property.
//The Account Object has lookup to City__c and city__c has a lookup to Pseudo_city__c object.
//This trigger will aggregate the total number of Accounts for a Master City, total number of Five star Account etc

    public Set<id> cityIds = new Set<id>();  
    public Set<Id> mCityIds = new Set<Id>();   
    public Map<Id, Pseudo_City__c> MCitiesToUpdate = new Map<Id, Pseudo_City__c>();
    public Map<Id,City__c> citiesToUpdate = new Map<Id,City__c>();
      //Create a set of city Ids for the Accounts and Map of Cities to update 
  List<Pseudo_city__c> updateMasterCity = new List<Pseudo_city__c>();
      if(trigger.isInsert || Trigger.isUpdate){
        for(Account item : Trigger.new){
            if (Item.recordTypeId=='012200000004rPU' && Item.Property_Status__c=='LIVE' )
              cityIds.add(item.city_new__c);
             }
          system.debug('The list of cities for insert/Update-- ' + cityIds);
         
         }         
      if(Trigger.isDelete){
         for(Account item : Trigger.old){
             if (Item.recordTypeId=='012200000004rPU' && Item.Property_Status__c=='LIVE' )        
                 cityIds.add(item.city_new__c);
                }
                system.debug('The list of cities Delete -- ' + cityIds);
           }
          
      
      
       for(City__c Tempcity : [Select Master_City_Cluster__c from city__c where ID IN :cityIds ]){
              mcityIds.add(Tempcity.Master_City_Cluster__c ); 
              }        
          system.debug('The Master cities to be updated   ' + mCityIds );
      
       for(Pseudo_city__c mcity :[Select Id,GTA_3_Hotels__c,GTA_4_Hotels__c,GTA_5_Hotels__c,GTA_2_or_less_Hotels__c,GTA_Hotels_2012__c from Pseudo_City__c where Id in :mcityIds]){
               MCitiesToUpdate.put(mcity.Id, mcity);             
           }
           
            system.debug('The master City Details  '+ MCitiesToUpdate );                     
      
       for(City__c city :[Select Id, Name,Master_City_Cluster__c,City_Location__c,(Select Id,Name,Property_Status__c,Location__c,recordTypeId,Star_Rating__c,GTA_Connect_Chain__c,DI_Master_Chain__c,ThresholdC__c,Grand_Total_RNs_2013__c from city__c.Accounts1__r) FROM city__c where Master_City_Cluster__c IN :mcityIds]){
              
                If(city.Master_City_Cluster__c != null )
                  citiesToUpdate.put(city.Id,city);
                }
             system.debug('The cities to be updated ' + citiesToUpdate);
         
      
     //Loop through every mastercity, then cities for each master cities and then accounts  for each city and count them total and then based on matching criteria
     
      for(Pseudo_city__c MCToUpdate :MCitiesToUpdate.values()){
          //Initialize the variable to 0
          integer mtotalLiveAccount = 0;
          integer mtotalfivestarHotels=0;
          integer mtotalfourstarHotels =0;
          integer mtotalthreestarHotels =0;         
          integer mTotalGTAconnectRegional = 0;
          integer mTotalGTAconnectGlobal = 0;
          integer mTotalGTAconnectIndependent = 0;          
          integer mtotalCityCenterAccount = 0;
          integer mtotalAirportAccount=0; 
          integer mtotalRegionAccount =0;
          integer mtotalPOIAccount=0;
          integer mtotalTwoStarorLess=0;
          double GrandTotalRNs2013=0;    
            //looping thru the Master cities         
       
         for(city__c citi : citiesToUpdate.values()){
          
           //looping through the cities in this Master city
             if(citi.City_Location__c == 'City Center' && citi.City_Location__c != null ) {
                for(Account acc : citi.Accounts1__r){
                   If(acc.Property_Status__c=='LIVE' && acc.recordTypeId=='012200000004rPU')
                   mtotalCityCenterAccount+= 1;
             }
              system.debug('In city loop City Center Hotels : ' + mtotalCityCenterAccount);            
             }
             if(citi.City_Location__c == 'Suburb & Airport' && citi.City_Location__c != null) {
                for(Account acc : citi.Accounts1__r){
                  If(acc.Property_Status__c=='LIVE' && acc.recordTypeId=='012200000004rPU')
                   mtotalAirportAccount+= 1;
             }
                 system.debug('In city loop Airport Hotels : ' + mtotalAirportAccount);            
             }         
            
             if(citi.City_Location__c == 'Point of interest' && citi.City_Location__c != null) {
                 for(Account acc : citi.Accounts1__r){
                    If(acc.Property_Status__c=='LIVE' && acc.recordTypeId=='012200000004rPU')
                    mtotalPOIAccount+= 1;
             }
                 system.debug('In city loop POI Hotels : ' + mtotalPOIAccount);                  
             }
                         
            
             for(Account acc : citi.Accounts1__r){
                   If(acc.Property_Status__c=='LIVE' && acc.recordTypeId=='012200000004rPU')
                   mtotalLiveAccount+= 1;
                if (acc.Star_Rating__c=='5 Star' && acc.Star_Rating__c != null)
                   If(acc.Property_Status__c=='LIVE' && acc.recordTypeId=='012200000004rPU')
                     mtotalfivestarHotels += 1;            
              
                if (acc.Star_Rating__c=='4 Star' && acc.Star_Rating__c != null)
                    If(acc.Property_Status__c=='LIVE' && acc.recordTypeId=='012200000004rPU')
                    mtotalfourstarHotels += 1;            
              
                if (acc.Star_Rating__c=='3 Star' && acc.Star_Rating__c != null )
                    If(acc.Property_Status__c=='LIVE' && acc.recordTypeId=='012200000004rPU')
                    mtotalthreestarHotels += 1;            
                if(acc.Star_Rating__c =='1 Star' || acc.Star_Rating__c=='2 Star' || acc.Star_Rating__c== 'NA')
                              If(acc.Property_Status__c=='LIVE' && acc.recordTypeId=='012200000004rPU')
                              mtotalTwoStarorLess+=1; 
               
               // if (((acc.DI_Master_Chain__c != 'ACCOR') || (acc.DI_Master_Chain__c != 'BW') || (acc.DI_Master_Chain__c != 'DESIGN') || (acc.DI_Master_Chain__c != 'EC') || (acc.DI_Master_Chain__c != 'FAIRMONT') || (acc.DI_Master_Chain__c != 'HILTON') || (acc.DI_Master_Chain__c != 'HYATT') || (acc.DI_Master_Chain__c != 'IHG') || (acc.DI_Master_Chain__c != 'JUMEIRAH') || (acc.DI_Master_Chain__c != 'KI') || (acc.DI_Master_Chain__c != 'LUXE') || (acc.DI_Master_Chain__c != 'MC') || (acc.DI_Master_Chain__c != 'MK') || (acc.DI_Master_Chain__c != 'MOHG') || (acc.DI_Master_Chain__c != 'SG') || (acc.DI_Master_Chain__c != 'WY') ) && (acc.GTA_Connect_Chain__c != null) && ((acc.GTA_Connect_Chain__c != 'Intercontinental Hotels Group') || (acc.GTA_Connect_Chain__c != 'Accor Hotels') || (acc.GTA_Connect_Chain__c != 'Best Western International') || (acc.GTA_Connect_Chain__c != 'Carlson Hospitality') || (acc.GTA_Connect_Chain__c != 'Choice Hotels International') || (acc.GTA_Connect_Chain__c != 'Design Hotels') || (acc.GTA_Connect_Chain__c != 'Fairmont Raffles Swissotel Hotels & Resorts') || (acc.GTA_Connect_Chain__c != 'Four Seasons Hotels & Resorts') || (acc.GTA_Connect_Chain__c != 'Hilton Worldwide') || (acc.GTA_Connect_Chain__c != 'Hyatt Hotels and Resorts') || (acc.GTA_Connect_Chain__c != 'Jumeirah International LLC') || (acc.GTA_Connect_Chain__c != 'Kempinski') || (acc.GTA_Connect_Chain__c != 'KEMPINSKI HOTELS & RESORTS') || (acc.GTA_Connect_Chain__c != 'Langham Hotels') || (acc.GTA_Connect_Chain__c != 'Luxe Worldwide Hotels') || (acc.GTA_Connect_Chain__c != 'Mandarin Oriental Hotel Group') || (acc.GTA_Connect_Chain__c != 'Marriott International Inc.') || (acc.GTA_Connect_Chain__c != 'Millennium & Copthorne Hotels plc') || (acc.GTA_Connect_Chain__c != 'Moevenpick Hotels & Resorts') || (acc.GTA_Connect_Chain__c != 'Shangri-La Hotels and Resorts') || (acc.GTA_Connect_Chain__c != 'Starwood Hotels and Resorts') || (acc.GTA_Connect_Chain__c != 'The Ascott Group') || (acc.GTA_Connect_Chain__c != 'Wyndham Hotel Group' ) || (acc.GTA_Connect_Chain__c != 'independent' )))
               //     If(acc.Property_Status__c=='LIVE' && acc.recordTypeId=='012200000004rPU')
               //     mTotalGTAconnectRegional+= 1;
               
                if (!((acc.DI_Master_Chain__c == 'ACCOR') || (acc.DI_Master_Chain__c == 'BW') || (acc.DI_Master_Chain__c == 'DESIGN') || (acc.DI_Master_Chain__c == 'EC') || (acc.DI_Master_Chain__c == 'FAIRMONT') || (acc.DI_Master_Chain__c == 'HILTON') || (acc.DI_Master_Chain__c == 'HYATT') || (acc.DI_Master_Chain__c == 'IHG') || (acc.DI_Master_Chain__c == 'JUMEIRAH') || (acc.DI_Master_Chain__c == 'KI') || (acc.DI_Master_Chain__c == 'LUXE') || (acc.DI_Master_Chain__c == 'MC') || (acc.DI_Master_Chain__c == 'MK') || (acc.DI_Master_Chain__c == 'MOHG') || (acc.DI_Master_Chain__c == 'SG') || (acc.DI_Master_Chain__c == 'WY') ) && (acc.GTA_Connect_Chain__c != null) && !((acc.GTA_Connect_Chain__c == 'Intercontinental Hotels Group') || (acc.GTA_Connect_Chain__c == 'Accor Hotels') || (acc.GTA_Connect_Chain__c == 'Best Western International') || (acc.GTA_Connect_Chain__c == 'Carlson Hospitality') || (acc.GTA_Connect_Chain__c == 'Choice Hotels International') || (acc.GTA_Connect_Chain__c == 'Design Hotels') || (acc.GTA_Connect_Chain__c == 'Fairmont Raffles Swissotel Hotels & Resorts') || (acc.GTA_Connect_Chain__c == 'Four Seasons Hotels & Resorts') || (acc.GTA_Connect_Chain__c == 'Hilton Worldwide') || (acc.GTA_Connect_Chain__c == 'Hyatt Hotels and Resorts') || (acc.GTA_Connect_Chain__c == 'Jumeirah International LLC') || (acc.GTA_Connect_Chain__c == 'Kempinski') || (acc.GTA_Connect_Chain__c == 'KEMPINSKI HOTELS & RESORTS') || (acc.GTA_Connect_Chain__c == 'Langham Hotels') || (acc.GTA_Connect_Chain__c == 'Luxe Worldwide Hotels') || (acc.GTA_Connect_Chain__c == 'Mandarin Oriental Hotel Group') || (acc.GTA_Connect_Chain__c == 'Marriott International Inc.') || (acc.GTA_Connect_Chain__c == 'Millennium & Copthorne Hotels plc') || (acc.GTA_Connect_Chain__c == 'Moevenpick Hotels & Resorts') || (acc.GTA_Connect_Chain__c == 'Shangri-La Hotels and Resorts') || (acc.GTA_Connect_Chain__c == 'Starwood Hotels and Resorts') || (acc.GTA_Connect_Chain__c == 'The Ascott Group') || (acc.GTA_Connect_Chain__c == 'Wyndham Hotel Group' ) || (acc.GTA_Connect_Chain__c == 'independent' )))
                    If(acc.Property_Status__c=='LIVE' && acc.recordTypeId=='012200000004rPU')
                   mTotalGTAconnectRegional+= 1;           
             
                if (((acc.GTA_Connect_Chain__c == 'Intercontinental Hotels Group') || (acc.GTA_Connect_Chain__c == 'Accor Hotels') || (acc.GTA_Connect_Chain__c == 'Best Western International') || (acc.GTA_Connect_Chain__c == 'Carlson Hospitality') || (acc.GTA_Connect_Chain__c == 'Choice Hotels International') || (acc.GTA_Connect_Chain__c == 'Fairmont Raffles Swissotel Hotels & Resorts') || (acc.GTA_Connect_Chain__c == 'Four Seasons Hotels & Resorts') || (acc.GTA_Connect_Chain__c == 'Hilton Worldwide') || (acc.GTA_Connect_Chain__c == 'Hyatt Hotels and Resorts') || (acc.GTA_Connect_Chain__c == 'Jumeirah International LLC') || (acc.GTA_Connect_Chain__c == 'Kempinski') || (acc.GTA_Connect_Chain__c == 'KEMPINSKI HOTELS & RESORTS') || (acc.GTA_Connect_Chain__c == 'Langham Hotels') || (acc.GTA_Connect_Chain__c == 'Luxe Worldwide Hotels') || (acc.GTA_Connect_Chain__c == 'Mandarin Oriental Hotel Group') || (acc.GTA_Connect_Chain__c == 'Marriott International Inc.') || (acc.GTA_Connect_Chain__c == 'Millennium & Copthorne Hotels plc') || (acc.GTA_Connect_Chain__c == 'Moevenpick Hotels & Resorts') || (acc.GTA_Connect_Chain__c == 'Shangri-La Hotels and Resorts') || (acc.GTA_Connect_Chain__c == 'Starwood Hotels and Resorts') || (acc.GTA_Connect_Chain__c == 'The Ascott Group') || (acc.GTA_Connect_Chain__c == 'Wyndham Hotel Group')) && !(acc.GTA_Connect_Chain__c == null))
                                   If(acc.Property_Status__c=='LIVE' && acc.recordTypeId=='012200000004rPU')
                                   mTotalGTAconnectGlobal+= 1;    
                              
                if(((acc.GTA_Connect_Chain__c == 'independent') && !((acc.DI_Master_Chain__c == 'ACCOR') || (acc.DI_Master_Chain__c == 'BW') || (acc.DI_Master_Chain__c == 'EC') || (acc.DI_Master_Chain__c == 'FAIRMONT') || (acc.DI_Master_Chain__c == 'HILTON') || (acc.DI_Master_Chain__c == 'HYATT') || (acc.DI_Master_Chain__c == 'IHG') || (acc.DI_Master_Chain__c == 'JUMEIRAH') || (acc.DI_Master_Chain__c == 'KI') || (acc.DI_Master_Chain__c == 'MC') || (acc.DI_Master_Chain__c == 'MK') || (acc.DI_Master_Chain__c == 'MOHG') || (acc.DI_Master_Chain__c == 'SG') || (acc.DI_Master_Chain__c == 'WY'))))
                   If(acc.Property_Status__c=='LIVE' && acc.recordTypeId=='012200000004rPU')
                   mTotalGTAconnectIndependent +=1;
                  
                if(acc.ThresholdC__c=='Top Focus' && acc.ThresholdC__c!= null && acc.Grand_Total_RNs_2013__c != null){
                 GrandTotalRNs2013 = GrandTotalRNs2013 + acc.Grand_Total_RNs_2013__c;
                 }
                 }
            }
                            
          system.debug('The Total number of accounts for this Master City is  '+ mtotalLiveAccount); 
          system.debug('The no hotels in CityCenter : ' + mtotalCityCenterAccount);
          system.debug('The no hotels in Airport : ' + mtotalAirportAccount); 
          system.debug('The no of hotels in POI  is : ' + mtotalPOIAccount);       
         
          system.debug('The no of 3 star hotel here is : ' + mtotalthreestarHotels);
          system.debug('The no of 4 star hotel here is : ' + mtotalfourstarHotels );
          system.debug('The no of 5 star hotel here is : ' + mtotalfivestarHotels );
          system.debug('The no of 2 star and less hotel  is : ' + mtotalTwoStarorLess);
         
          system.debug('The no of GTAconnectGlobal hotel  is : ' + mTotalGTAconnectGlobal);
          system.debug('The no of GTAconnectRegional hotel  is : ' + mTotalGTAconnectRegional);
          system.debug('The no of GTAconnectIndependent hotel  is : ' + mTotalGTAconnectIndependent);
         
         
               MCToUpdate.GTA_Hotels_2012__c = mtotalLiveAccount;
               MCToUpdate.GTA_5_Hotels__c= mtotalfivestarHotels;            
               MCToUpdate.GTA_4_Hotels__c= mtotalfourstarHotels;             
               MCToUpdate.GTA_3_Hotels__c = mtotalthreestarHotels;
               MCToUpdate.GTA_2_or_less_Hotels__c=mtotalTwoStarorLess;
               MCToUpdate.GTA_City_Centre_Penetration__c=mtotalCityCenterAccount;
               MCToUpdate.Suburbs_Airport__c= mtotalAirportAccount;
               MCToUpdate.GTA_POI_Hotels__c= mtotalPOIAccount;
               MCToUpdate.GTA_Global_Chain_Hotels__c=mTotalGTAconnectGlobal;
               MCToUpdate.GTA_Regional_Chain_Hotels__c=  mTotalGTAconnectRegional;
               MCToUpdate.GTA_Independant__c =    mTotalGTAconnectIndependent;                     
               MCToUpdate.RN_Projection_2014_Top_Focus__c = GrandTotalRNs2013;
               updateMasterCity.add(MCToUpdate);
}
        //Finally update all affected cities:
        update updateMasterCity;
}

Hi,

I am trying to create a visual force page that will have two fields Source and Destination but they both reference the same back end master/detail field.  This page uses Opportunity as the standard controller and the child table/object as the extension.  I want the user to be able to select Opp A in the source field and Opp B in the dest field for example.  This seems to work fine.  I cannot seem to get any controller action to occur using the onchange event so I am thinking I could get around this with an additional button named MOVE.

How can I reference both of the different values in these two fields from my controller when they have a VALUE setting that is the same?  Below is some of the main code snippet around the VF page.

<apex:page StandardController="Opportunity" Extensions="Enrollment_MoveLatestEnrollContr2" id="Page" tabstyle="Opportunity"
           sidebar="false" showHeader="false" title="Move Latest Enrollment" >
        
    <apex:sectionHeader title="Move Latest Enrollment" subtitle="Move Latest Enrollment" />     
    <apex:form id="myForm">
        <apex:pageMessages escape="false" />  
        <apex:PageBlock id="pbSrceDest" rendered="{!isAdmin}">                 
            <apex:pageBlockSection columns="1" title="Select a Destination Opportunity"  collapsible="false" >
                <apex:inputField id="SourceOpp" label="Source Opportunity" value="{!Enrollment.Opportunity__c}" />            
                <apex:inputField id="DestOpp" label="Destination Opportunity" value="{!Enrollment.Opportunity__c}" />               
            </apex:pageBlockSection>
...
...

Thanks in advance for your assistance:)

 

Business requested to hide “Cancelled” records  from standard record search. When users search for records in Salesforce, system shows all records  which meet search criteria. (like process, requested, in effect, records ..... all showes me but...... i want all records  except cancelled records......)
 except “Cancelled....how can i acheave dis can any one help me plz


Can you please explain a team development scenario if everyone is using single developer sandbox for the development and not individual dev orgs. I mean this is what is practical where we have support team supporting a particular force.com app and each developer is assigned to a bug/fix or more than one developer is assigned to particular bug. In that case how source control (my case is SVN) works.
Will this work practically? What do you recommend?
Hi folks
Still new but getting there bit by bit. I have this trigger, It is supposed to update certain specific fields based on different picklist values. I'm thinking it's not bulkified like it should be. I'm thinking (but could be wrong) I need to make a set/list and update the values of the set before letting it go ahead and do it's stuff, so I can do everything with one update.  Here's the trigger.

trigger updateAppNum on CustomObject__c (before insert, before update) {

   //Get set of Incomplete ids
    List<Integer> appUps = new List<Integer>();
   
    for(CustomObject__c ap :trigger.new) {
        if (ap.Status__c == 'Incomplete') {
          ap.AppInc__c = 1;
        }
        if (ap.Status__c == 'Complete - Pending Review') {
          ap.AppCompP__c = 1;
        }
        if (ap.Status__c == 'Complete - Decision Made') {
          ap.AppCompD__c = 1;
        }
        if (ap.Status__c == 'Deferred') {
          ap.AppDef__c = 1;
        }
        if (ap.Status__c == 'Withdrawn') {
          ap.AppW__c = 1;
        }
    }

}

If I am in salesforce I can go to a record, click on its sharing button and from there I can click on Expand List.  Next, I can find a username and click on the Why? link beside their name.  This will take me to the entitywhylist.jsp page which seems to simply be able to accept 2 arguments (record Id and user Id) and return a full explanation of what relationships and reasons permit the user to access that record.

 

My question then: Is there an Apex method that can do this.  If I have the record Id and the user Id is there an inexpensive way of returning the information provided by the entitywhylist page?  All the other similar solutions to questions like this seem to involve iterating over a potentially large number of groups and roles.

  • December 09, 2013
  • Like
  • 0

Apologies, but this is probably a really simple javascript / VF issue, but I have been going around in circles

 

I want to conditionally render a column in a pageBlockTable based on the value of another column in the table. I have written a javascipt function which should return true / false according to the value of the field. 

 

My Javascript function is:

 

<script type="text/javascript">
   function renderStatus(attendeeRole) {

       	if (attendeeRole == "Minutes Only")	{
            return false;
	}
	else {
	    return true;
	} 
   }
</script>

 

The excerpt from the table is:

 

<apex:column headerValue="Invite Status" styleClass="{!att.Status__c}" >
   <apex:inputField value="{!att.Invite_Status__c}" 
       rendered="return(renderStatus('{!att.Role__c}'))" />  
</apex:column>

 

I have tried many different variations of trying to fire the js function but just cannot seem to make it work.

 

The result is always a column that does not render regardless of the value of the field att.Roler__c

 

Thanks in advance

 

PS: I always struggle with javascript in VF. Is there a decent reference document / book out there that can help? 

 

 

 

I have put a button on an object, this object has some configuration settings. On clicking the button configuration needs to put in a xml format and the text file needs to be downloaded on to desktop or anyother location outside of salesforce.

 

On clicking the button, I am able to build the xml but I am having trouble putting the file on desktop. I know there is render as but I dont want any manual intervention for saving.

 

Can someone advice me on this....

I have written a test case which is attempting to get maximum coverage on a complex page. I now keep hitting the "Too many DML statements" problem. I get that what this is for, but I need to find a way of working around this for testing purposes.

 

Any ideas?

 

NB: I could resort to breaking my test into multiple classes, but that seems messy!

Hi every one,

 

       Can i Call a Future Method in another Future Method?????

hi friends

can anyone tell me...

what is the error we get when we use soql quiry in any for loop?

thnks

Hi all,

I'm currently working on a trigger for preventing duplicate Leads from being inserted during the mass data upload. The trigger should treat two leads equal if their Company and Email fields are equal. Since the trigger would fire during the mass data upload (custom), I had to minimize the number of executed SOQL queries in order to cope with SF limits.

Here's how the code looks like atm:

trigger MyTrigger on Lead (before insert) {

Map<String, Lead> leadMap = new Map<String, Lead>();

List<String> fieldNames = new List {'Email', 'Company'}; // it will actually be obtained from somewhere else, but I'm hardcoding it atm

String leadQueryString = '';
String leadDupeError = 'A Lead with the same {0} already exists: {1}';
String fieldSet = '';
Integer i = 0;

List<Set<String>> leadValues = new List<Set<String>>(); // referencing a set by its index in the list doesn't work in dynamic query

for (String fieldName : fieldNames)
{
	Set<String> thisFieldValues = new Set<String>();
	
	for (Lead lead : System.Trigger.new)
	{
		if(String.isNotBlank((String)lead.get(fieldName))) thisFieldValues.add((String)lead.get(fieldName));
	}
	// keeping a corresponding set of values for this field
	leadValues.add(thisFieldValues);
	
	// constructing my query filters
	leadQueryString += (leadQueryString == '' ? '' : ' AND ') + fieldName + ' IN :leadValues[' + i + ']'; // this index doesn't work	
	fieldSet += (fieldSet == '' ? '' : ', ') + fieldName;
	
	i++;
}

List<Lead> possibleDupes = Database.query('SELECT Id, ' + fieldSet + ' FROM Lead WHERE ' + leadQueryString);

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

for (Lead lead : System.Trigger.new)
{
	for (Lead pd : possibleDupes)
	{
		boolean match = true;
		
		for(String fieldName : fieldNames)
		{
			if (((String)lead.get(fieldName)) != (String)pd.get(fieldName)) {
				match = false;
				break;
			}
		}
		if (match) {
			lead.addError(String.format (leadDupeError, new List<String> { fieldSet, pd.Id})); // this will prevent the insert
			dupes.add(lead);
			break;
		}
	}
}

}

 Actually, referencing leadValues[i] in query doesn't work :( It gives me the following error:  System.QueryException: unexpected token: '['
To get it work, I had to remove the [] clauses from the query and add two additional lists: 

leadValues0 = leadValues[0]
leadValues1 = leadValues[1]

This way it does work, but it's not dynamic (I want the number of filter fields be more flexible).

So, the question is: is there a way to bypass this error without having to keep the exact number of field values sets?

I would also appreciate any other suggestions on improving my trigger :)

Hi ,

 

I am curious to know which method for "type: object" are supported in salesforce.

What its use and how it can be leaveraged in salesforce.

 

Thanks

_RSN

 

 

Hi,

I'm Getting below error :-

 

Error Message System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: OpportunityLineItem.CurrencyIsoCode

Class.SearchOpptyPageController.cOpportunity.<init>: line 530, column 1 Class.SearchOpptyPageController.getOpportunities: line 509, column 1 Class.SearchOpptyPageTest.opptyTest1: line 182, column 1

<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Controller Method due to which i'm getting error is :-

 <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>.

public List<cOpportunity> getOpportunities(){                  

opportunityList = new List<cOpportunity>();          

for(Opportunity o : (List<Opportunity>)con.getRecords()) {

            if(ModalityString != null || PortfolioString != null){       

          if(o.OpportunityLineItems.size() > 0){  

                       opportunityList.add(new cOpportunity(o));                  

    }               

}                

else{                                           

opportunityList.add(new cOpportunity(o));  <<<<<<<<<<ERROR-1 Line 509>>>>>>>>>>>>>>>>>                  

  }            

}               

   return opportunityList;      

}       

public Class cOpportunity{        

public Product2 opppr1 {get;set;}        

public Opportunity opp {get;set;}        

public Account acc1 {get;set;}         public Boolean selected{get;set;}        

public String convertPrice {get;set;}     

    //public Decimal convertPrice {get;set;}         

List<OpportunityLineItem> oppLineLst;       

  cOpportunity(Opportunity o){           

  convertPrice = '';        

     opp=o;           

  selected=false;         

   oppLineLst = [Select convertCurrency(TotalPrice),id,CurrencyIsoCode From OpportunityLineItem where OpportunityId =: o.Id];         

     oppLineLst = new   List<OpportunityLineItem>();         

    For(OpportunityLineItem ol :o.OpportunityLineItems){            

  Double conversionRate = [SELECT conversionrate,isocode FROM currencytype WHERE isocode =:ol.CurrencyIsoCode LIMIT 1].conversionRate;   <<<<<<<<<<<<<<ERROR -2 Line 530>>>>>>>>>>>>>    >>>>>>>>>>>>       

            

  //  if(!convertPrice.contains(String.ValueOf(ol.TotalPrice * conversionRate)))         

      if(ol.CurrencyIsoCode != 'USD')             

     convertPrice +=   '\n\r'+ (ol.TotalPrice * (1/conversionRate)).setscale(2)+'\n\r';      

          else                 convertPrice +=   '\n\r'+ (ol.TotalPrice).setscale(2) +'\n\r';       

      }             

        }

    }

  • November 20, 2013
  • Like
  • 0
The old developer forum had private messages, but the new forum doesn't appear to. Ironically, I got a message on the 23rd of December saying that I had a new private message. Clicking on the link results in an error page. Are there private messages, and if so, how do we get to them? Furthermore, if not, when will they be available?

Background


I am creating a Google Chrome Packaged App that allows users to access various features from a plurality of salesforce.com organizations. This app will allow users to perform various tasks depending on their permissions in each organization, such as querying data and logging in with a single click. To avoid storing passwords, I'm trying to use OAuth2 to generate refresh tokens that can be used to access those organizations, with a mechanism to revoke those tokens if needed across all organizations in the event of a compromise.

 

Problem


Generating a refresh token only happens in certain flows that follow a certain pattern, and those patterns seem to be incompatible with Google's "chrome.identity.launchWebAuthFlow" mechanism.

 

Attempted Solutions


So far, I have tried the following end-points to try and get Google Chrome to recognize that we've successfully completed the flow and obtain a refresh token. Here are my attempts so far:

 

/services/oauth2/authorize?

grant_type=code&

client_id=XYZ&

prompt=login&

scope=full+refresh_token&

redirect_uri=https://<appid>.chromiumapp.org/callback

 

This link follows the web server flow. We get a code back that we can use to call /services/oauth2/tokens, but ths requires the client_secret, which we are not supposed to embed in the code for security reasons-- the source code is open.

 

/services/oauth2/authorize?

grant_type=token&

client_id=XYZ&

prompt=login&

scope=full+refresh_token&

redirect_uri=https://<appid>.chromiumapp.org/callback

 

This link won't give us a refresh_token, because it does not have a custom protocol and does not match login.salesforce.com/services/oauth2/success.

 

/services/oauth2/authorize?

grant_type=token&

client_id=XYZ&

prompt=login&

scope=full+refresh_token&

redirect_uri=chrome-extension://<appid>/callback

 

This link results in an error in Google Chrome about not being able to load the authorization page, but would give us a refresh token if it worked.

 

/services/oauth2/authorize?

grant_type=token&

client_id=XYZ&

prompt=login&

scope=full+refresh_token&

redirect_uri=https://login.salesforce.com/services/oauth2/success

 

This page doesn't actually show an access token or error, so Google Chrome never detects that the flow is complete. We do not get an access token or refresh token. I have a feeling this is is the proper flow to use, but without a way to detect the token, it simply doesn't work. The authorization page simply sits open forever once we reach this step.

 

Question


How am I supposed to code this app such that it securely accesses salesforce.com without compromising the client_secret while preventing excessive login attempts and/or API calls from a periodic timer that would be required?

 

I realize that this question may be outside the scope of this forum, but this seems to be fairly salesforce.com specific, as other OAuth2 sites work just fine with chrome.identity.launchWebAuthFlow, so I thought I'd ask here and see if anyone knows enough about Chrome and OAuth2 as it pertains to accessing salesforce.com.

Summary

A class implementing an override for public String toString() will not have this function honored by String.join(). Instead, it returns the name of the class. Using the normal concatenation operator on the list yields output that is expected.

 

Repro



<apex:page controller="repro">
    <table>
        <tbody>
            <tr>
                <td>new sub1().tostring()</td>
                <td>{!Sub1ToString}</td>
            </tr>
            <tr>
                <td>''+(new sub1[] { new sub1() })</td>
                <td>{!Sub1AsList}</td>
            </tr>
            <tr>
                <td>string.join(new sub1[] { new sub1() }, '')</td>
                <td>{!Sub1AsJoin}</td>
            </tr>
            <tr>
                <td>new sub2().tostring()</td>
                <td>{!Sub2ToString}</td>
            </tr>
            <tr>
                <td>''+(new sub2[] { new sub2() })</td>
                <td>{!Sub2AsList}</td>
            </tr>
            <tr>
                <td>string.join(new sub2[] { new sub2() }, '')</td>
                <td>{!Sub2AsJoin}</td>
            </tr>
        </tbody>
    </table>
</apex:page>

 

public with sharing class repro {
    class sub1 {
    
    }
    
    class sub2 {
        public override string tostring() {
            return 'Hello. I am sub2.';
        }
    }
    
    public string getSub1ToString() {
        return new sub1().tostring();
    }
    
    public string getSub1AsJoin() {
        return string.join(new sub1[] { new sub1() }, '');
    }

    public string getSub1AsList() {
        return ''+(new sub1[] { new sub1() });
    }
    
    public string getSub2ToString() {
        return new sub2().tostring();
    }
    
    public string getSub2AsJoin() {
        return string.join(new sub2[] { new sub2() }, '');
    }
    
    public string getSub2AsList() {
         return ''+(new sub2[] { new sub2() });
   }
}

 Output from above:

 

new sub1().tostring()sub1:[]
''+(new sub1[] { new sub1() })(sub1:[])
string.join(new sub1[] { new sub1() }, '')repro$sub1
new sub2().tostring()Hello. I am sub2.
''+(new sub2[] { new sub2() })(Hello. I am sub2.)
string.join(new sub2[] { new sub2() }, '')

repro$sub2

 

As one can see, It's not even trying to join them together, it's just calling some sort of odd "List<Object>.getType()" function that we can't even access.

 

I've logged a case with support, but since I'm half-expecting them to just close it without even trying to log a bug, I'm also posting this here hoping that some PM or internal salesforce.com developer will see this and have it fixed at some point.

If I "use strict" in my code, will Visualforce Remoting blow up? Has anyone tried testing this to see what will happen? Are there any gotchas I should be made aware of?

 

I tried something like this:

 

"use strict";
(function(window,undefined) {
  var addEvent = function(...) { ... };
  var callbackHandler = function(...) { ... };

  var onWindowLoad = function(...) {
     Visualforce.remoting.Manager.invokeAction(
       "{!$RemoteAction.myClass.myMethod}",
       callbackHandler);
  };
  addEvent(window,"load",onWindowLoad,true);
})(window);

Where ... is not relevant. It runs, and the data comes back just fine, but I wanted some feedback on if there were any known issues where it might be possible that remoting fails entirely because of strict mode, perhaps even outside the realm of being able to use exception handling. Or, should I just forego strict mode and leave that for another day?

I am working on a class that will be incorporated into our project that helps build dynamic queries specific to our managed package's process. Everything was going fine until I saved my code and the Developer Console froze up. The mouse cursor wouldn't change, the menu stopped responding, everything. The only thing I could do was to close the Developer Console through the system's close button (but it didn't ask me to "End Process"). At this point, the tab where I was logged into my Developer Edition was also frozen; I had to close this tab as well using the tab's close button. I logged back in and went back to the console, and it immediately froze again. I managed to get the class closed in the Developer Console by hitting File > Close All as soon as the Developer Console popped up (and I still had to close the Console and Developer Edition a second time). This is the new Developer Console. Is there some known glitch?

Given the following code:

 

public class subscriptfailure {

    public Integer rows { get; set; }
    public Id[] items { get {
        if(items==null)
            items = new Id[0];
        if(rows!=null) {
            while(rows<items.size())
                items.remove(items.size()-1);
            while(rows>items.size())
                items.add('001000000000000');    // Replace with null to see error
        }
        return items;
        } set;
    }
    
    public Integer[] indices {
        get {
            Integer[] v = new Integer[0];
            while(v.size()<items.size())
                v.add(v.size());
            System.debug(items);
            System.debug(v);
            System.assertEquals(v.size(),items.size());
            System.assertEquals(rows==null?0:rows,v.size());
            return v;
        }
    }
    
    public SelectOption[] getAccounts() {
        SelectOption[] options = new SelectOption[0];
        for(Account record:[SELECT Id,Name FROM Account LIMIT 10])
            options.add(new SelectOption(record.id,record.Name));
        return options;
    }
}

 

<apex:page controller="subscriptfailure">
    <apex:form id="form" >
        <apex:pageBlock >
        <apex:inputText value="{!rows}">
            <apex:actionSupport event="onchange" reRender="form"/>
        </apex:inputText>
        <apex:pageBlockTable value="{!indices}" var="index">
            <apex:column >
                <apex:selectList size="1" value="{!items[index]}">
                    <apex:selectOptions value="{!accounts}"/>
                </apex:selectList>
            </apex:column>
        </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Changing an empty ID to null (e.g. items.add(null)) will result in the error, despite the list containing a number of items equal to the size of rows, which the user can type in.

 

While it appears I have a viable workaround, I thought I'd post this here and see if this is something that can be fixed. Posting a random ID just to prevent an error is surely a poor practice.

See last paragraph for summary...

 

I was trying to create an adaptive loader routine in Apex Code, and I came across an interesting bug. First, let's take a look at what I was attempting to do:

 

sobject record = cache.load( recordId );
set< id > relatedIds = new set< Id >( );

for( SObjectField field: Cache.getFieldTokens( record.getSObjectType( ) ) ) {
   if( record.get( field ) != null && record.get( field ) instanceOf id ) {
       relatedIds.add( Id.valueOf( record.get( field ) );
   }
}
map< id, sobject > related = new map< id, sobject >( Cache.load( relatedIds ) );

Where:

* Cache.load( Id ) returns a single record from a static map, querying the record, if necessary.

* Cache.getFieldTokens( SObjectType ) returns all tokens from a SObjectType.getDescribe().fields.getMap().values(), again loading from a static map if previously defined.

* Cache.load( Set< Id > ) is a batch version of above, returning a list of SObject records in arbitrary order, querying records that are missing from the cache, and capable of returning multiple types of SObjects.

 

When I tried this initially, I got an odd exception: "Invalid ID."; the exception was thrown from my Cache class, so I wondered how it could have gotten there.

 

I fiddled around with the straightforward means of assigning an ID via a string:

 

Id a = '0013000000f3adA'; // OKAY
Id b = 'john doe';        // EXCEPTION

So, it would appear the setter function works fine.

 

Next, I tried casting:

 

String a = '0013000000f3Adf', b = 'john doe';
Id c = ( Id )a; // OKAY
Id d = ( Id )b; // EXCEPTION

So far, so good; it's also using the setter function of ID.

 

Next, I tried using Id.valueOf:

 

Id a = Id.valueOf( '0013000000d3afA' ); // OKAY
Id b = Id.valueOf( 'john doe' );        // OKAY ?!?!

This means that Id.valueOf doesn't use the setter method, but instead internally constructs an ID.

 

The next tidbit came when I tested the Set<T> class against an ID.

 

First, a straight assignment:

 

Set< Id > a = new set< Id >( );
a.add( '00130000003faZs' ); // OKAY
a.add( 'john doe' ); // EXCEPTION

So, it seems that Id's setter is in play here.

 

Next, I tried using the defunct valueOf:

 

Set< Id > a = new Set< Id >( );
a.add( Id.valueOf( 'john doe' ) ); // OKAY ?!?!

So, it seems that a "corrupted" ID value will be accepted into a set of IDs.

 

This led to the next problem:

 

for( Id b: a) {
  // Do something
}

If a is a set of IDs, and a corrupted ID value (via valueOf) is in the set, you will receive an "invalid ID" error here.

 

Finally, this led me back to my source code:

 

if( Id.valueOf( 'john doe' ) instanceOf Id ) {
  System.debug('** Invalid ID was accepted by instanceOf **');
}

So, Set<T>.add(Object) apparently checks the class of the incoming object against the class of its template, and automatically accepts them without question, otherwise attempts a cast (calling the correctly-working setter function).

 

I submitted a case to support, and they told me to go away because I don't have premier support, and all I wanted to do was log a bug with the dev team.

 

Hopefully an admin will see this and it will get logged as a bug. In the interim, the community should note that Id.valueOf is broken, and instanceOf is also broken as a side-effect. Instead, you should always use casting, and try-catch the cast so you can detect incorrect ID values.

 

Sometime a week or two ago, files being saved in a project were no longer committed to the server directly. Instead, they would have the "Save locally only" marker, and I would have to use Force.com | Save to Server... to resolve this issue. A Google search produced a way to open the log file, and this is the entry that I see:

 

WARN [2012-11-26 16:06:59,426] (DefaultBuilder.java:applyDirtyMarkers:85) - TODO: apply 'Save locally only...' markers on each resource

I've tried deleting the project and re-building it, importing it back from our svn, refreshing the metadata, deleting the src folder, and so on. Nothing seems to fix the problem.

 

I'm using Force.com IDE version 25.0.0.

 

Any suggestions or pointers would be appreciated.

We have a class that's listed like this in our org:

 

Version: 24.0

Status: Active

Size without Comments: 2076

Coverage: 14% (32/216)

 

This class is, in total, 38 lines, covered like this:

 

5 "white" lines, not counted.

10 "red" lines, not covered.

23 "blue" lines, covered.

 

How is it that the coverage could be this screwed up?

I have a case open with Technical Support, but I thought I'd post something here, too. They're already working on the issue, but I would like to let the community know about this bug.

 

If you have a managed package developer org, and you open the Force.com Console, click on Repository, select the element type you'd like to create, and click New, your new element (page, component, etc) will not be part of the managed package namespace. This will cause the package upload to fail, and the elements won't work correctly (e.g. a visualforce page will show as "does not exist" despite being present in the system's repository). This bug will also allow you to create duplicate elements, one which is namespaced, and one not.

 

The current solution to the problem is to clone the element, update all references to the element you're about to delete, then delete the non-namespaced element.

  • September 12, 2012
  • Like
  • 0

While creating a custom PDF Visualforce page, I noticed an odd glitch regarding headers and footers.

 

Let's say that you have an image that is on the header of one page, and on the footer of each subsequent page, but smaller (using the same URL):

 

<apex:page renderAs="PDF">
 <head>
  <style rel="stylesheet">
   @page:first {
    @top-left {
     content: element(logo1);
    }
    @bottom-left {
     content: none;
    }
   }
   @page {
    @bottom-left {
     content: element(logo2);
    }
   }
   #logo1 {
    position: running(logo1);
   }
   #logo2 {
    position: running(logo2);
   }
   #logo1 img {
    height: 0.75in;
   }
   #logo2 img {
    height: 0.25in;
   }
  </style>
 </head>
 <div id="logo1">
  <img src="/servlet/servlet.FileDownload?file=015Z0000000ABCD"/>
 </div>
 <div id="logo2">
  <img src="/servlet/servlet.FileDownload?file=015Z0000000ABCD"/>
 </div>
<div style="page-break-after: always">
Page 1 sample content
</div>
<div>
Page 2 sample content
</div> </apex:page>

When you try to render this, you'll find that both images are the same size! The solution to this problem is to make the URLs unique. In the example above, I changed the URLs as follows:

 

/servlet/servlet.FileDownload?file=015Z0000000ABCD&ver=1

...

/servlet/servlet.FileDownload?file=015Z0000000ABCD&ver=2

The Visualforce rendering engine then correctly assigns a different size to each element, and they will appear as they should.

 

I'm not sure if this is supposed to work this way, or if there's some other CSS that needs to be used to render the images properly without using a URL parameter, but I thought I'd throw this out there and see if I'm just doing it wrong, or if it really is a glitch.

We have some code in a managed package that allows a user to preview a Visualforce PDF, and once they are satisfied, they can save the file back to the parent record. This code works fine when the Visualforce page called is in our managed package. However, if the managed package instead tries to call a Visualforce page outside of our managed package, then the page crashes with a WSOD (White Screen of Death).

 

The error is as follows:

 

An internal server error has occurred
An error has occurred while processing your request. The salesforce.com support team has been notified of the problem. If you believe you have additional information that may be of help in reproducing or correcting the error, please contact Salesforce Support. Please indicate the URL of the page you were requesting, any error id shown on this page as well as any other related information. We apologize for the inconvenience.

Thank you again for your patience and assistance. And thanks for using salesforce.com!

Error ID: 1710413537-5764 (587506552)

 

Of course, I've submitted a case to Support, but I wanted to see if anyone has encountered a problem with getContent() crashing a Visualforce page like this, and what the resolution to this was.

I thought this would be obvious, but I can't seem to get this to work, so looking for a bit of help here.

 

Basically, I have a custom setting with a text field; the intent is to redirect to a page if this setting is set, so users can hook into some of our functionality by providing custom pages.

 

In my controller, I check to see if this text field has a value, and if so, I redirect to it.

 

public ApexPages.PageReference redirect() {
    ApexPages.PageReference ref = null;
    if(settings.general.override_page__c != null) {
        ref = new apexpages.pagereference(url.getsalesforcebaseurl().toexternalform()+'/apex/'+settings.general.override_page__c);
        ref.setRedirect(true);
        ref.getParameters().putAll(new map<string,string> { 'id' => String.valueOf(record.id), 'entity' => Entity.getName(record) } );
    }
    return ref;
}

However, this is apparently still redirecting to our package's namespace, instead of back to the standard namespace. 

 

Any suggestions?

 

 

I believe I just found two bugs (?) in the platform that I can't seem to find documentation on. The first is a compilation issue. You can't apparently assign to a private static variable if it has a setter but no getter.

 

public class X {
    private static boolean Y {
        set {
            y = value;
        }
    }

    static {
        x.y = true;  // This line fails to compile: 'Variable is not visible'
    }
}

 The second problem is with code coverage. If a getter/setter is on the same line as the variable declaration, you get code coverage, otherwise, you don't. Example follows.

 

// EXPECTED RESULT: 100% CODE COVERAGE
// ACTUAL RESULT: 66% CODE COVERAGE
public class X { public static boolean Y { get { return true; } } public static boolean Z { // THIS LINE DOES NOT GET CODE COVERAGE get { return false; } }
public static testMethod void test() {
System.assertEquals(true,x.y);
System.assertEquals(false,x.z);
} }

Has this been a problem for anyone else?

 

I remember this working previously (or some incarnation thereof), but it's not working now when I'd actually like to use it. Does anyone know what the new method for displaying a dynamic sobject's label is without resorting to a describe call in a controller or extension?

We have two pages, aptly named QuotePDF and QuotePDF1. The former is designed to allow the user to preview the quote and save it to the quote and optionally send an email with it attached. Yes, we know this is standard functionality, but we're doing "extra" stuff with our code that we wanted to retain.

 

At any rate, with no changes to our code, we suddenly had a break in our code. Previously, it was working great without a problem. Now, the Preview works as expected, but Page.QuotePDF1.getContent() is failing with the error "SObject row was retrieved via SOQL without querying the requested field: Quote.ShippingName", regardless of what we try to do to fix the problem. Here's what we've got in place so far:

 

public with sharing class quotePDFExtension {
    public quotePDFExtension(Apexpages.standardcontroller con) {
        controller = con;
        if(!test.isrunningtest()) {
            con.reset();
// Cached field describe as a String[] con.addfields(data_util.getobjectfields('Quote')); } } // Other non-interesting stuff here, including controller variable public apexpages.pagereference saveToQuote() { quotedocument qd = new quotedocument(); apexpages.pagereference ref = page.quotepdf1; ref.getparameters().put('id',quote.id); qd.document = ref.getcontent(); // also tried getcontentaspdf
// ref.setredirect(true/false); -- neither had any effect qd.quoteid = quote.id; insert qd; return controller.view(); } }

The controller explicitly has all fields added to it, we've tried to force a redirect.

 

Yes, both pages use the same standardController(Quote) and extensions(quotePDFExtension). I'd rather not split them apart if I can help it.

 

Up until this previous weekend, everything was running just fine. However, whatever happened this weekend broke several pieces of code that was previously working. I can't seem to debug this either, as the error causes the entire page to crash rather ungracefully.

 

I've tried several fixes that mentioned this problem from 2009, but to no avail, including static variables, etc. The only thing I don't want to do is hardcode a query in place, as this is rather limiting. I'd like to have the system determine what fields should be queried dynamically, the way it should be.

In a Developer Edition with a managed package that the org manages, we know that salesforce.com is smart enough to know that all code without a namespace is running in the org's default namespace, which is the namespace of the managed package. This means that we can write the following code in Visualforce with impunity:

 

<apex:inputField value="{!CustomObject__c.SomeField__c}"/>

Salesforce.com knows there's no ambiguity and is able to successfully resolve the reference without any help or hint on the developer's part. Looking at the same code in an organization where this code is installed yields the following insight:

 

<apex:inputField value="{!namespace__CustomObject__c.namespace__SomeField__c}"/>

The uploader knows that it has to prepend the namespace into these value attributes so that the fields can be resolved at compile time in the target organization, and everything works as expected. However, when you're not using an attribute value, such as a "normal" formula-style merge field, we run into a problem:

 

{!CustomObject__c.CustomField__c}

When you try to load this page into the target organization, everything installs fine, but when you try to run the page, you get the following exception:

 

SObject row was retrieved without requesting the following field: CustomField__c

When you look at the source code, you'll see that the merge field was unaffected by the uploader, and consequently, the code won't run at all. Worse, since the package is managed, the only solution is to modify your code to make sure the generated SOQL contains namespaces, which means you have to write these fields thusly:

 

{!namespace__CustomObject__c.namespace__CustomField__c}

This is problematic from several standpoints, but perhaps the most trying question here is: why are attribute values correctly fixed, while merge fields are not? Is this documented somewhere as to why this happens? Is it a bug, or a feature?

 

From my perspective, this could be a bug, since it means you have to hardcode in namespace values, so you can't use the code in a portable fashion: You can neither upload it as a non-managed package to another org without fixing the code, nor can you sync this code across developer orgs without some additional work.

 

However, if it is indeed a feature, I'd like to know where this is documented, and why merge formulas don't work while attribute values do work. I'm making this public so that this can be documented for future developers that may also have this question. I couldn't seem to find a post that specifically mentioned this bug or feature (however it might be labelled).

 

This question was posed to Dev Support, and they came back with "you need to use the namespaces", which doesn't tell anyone about the "why" it works this way, if it was designed this way, will it happen this way in the future, or anything else even remotely useful. I had already worked out that we would need namespaces in these merge fields, or we would have to wrap them in apex:outputPanel tags, or even use wrapper classes, but I wanted to know if this is on anyone's roadmap, or if there's a legitimate, albeit undocumented, purpose behind this limitation.

I couldn't seem to find a solid answer, so I hope someone here knows... How many pricebooks can you have, and how many pricebook entries can you have per pricebook? Is there an actual limit?

I was checking my code in an org of mine, and I noticed that many of my classes (written by myself) had an unusual code coverage (000000000000000%). Some also have no percentage at all, despite being test classes. I ran a "calculate your organization's coverage" and it fixed the display issue, but I thought I'd post something here to see if someone can look into why that may have happened to begin with.

Using Payment Connect, our Sites URL appears as follows:

 

 

https://<org-name>.secure.force.com/pmtx/<page-name>

 

 

In our developer organization, the page we've created works perfectly. In production, however, since there is a namespace, it appears to create some confusion. If I use the following code:

 

 

sforce.apex.execute('MyClass','MyFunction',{})

The AJAX toolkit forms the following SOAP URL:

 

 

 

https://<org-name>.secure.force.com/services/Soap/package/<class-name>

This causes the following error to be thrown:

 

 

 

UNKNOWN_EXCEPTION: site under construction

 

I did some searching on the Forums, and found several posts related to this error, but they did not really answer the question I had. Digging deeper, I found that the correct SOAP URL should have been:

 

 

https://<org-name>.secure.force.com/pmtx/services/Soap/package/<class-name>

With a little bit more of a dig, I uncovered a variable called UserContext.siteUrlPrefix. I added a single line in order to attempt fixing the toolkit as follows:

 

 

 

UserContext.siteUrlPrefix='pmtx'

This resulting in the following SOAP URL being generated:

 

 

https://<org-name>.secure.force.com/pmtx/pmtx/services/Soap/package/<class-name>

So, this all leads up to the following question:

 

How do I use sforce.apex.execute in a manner that will generate the correct URL without doing some "hacks" on my part? Is this a bug of some sort with the Sites detection algorithm, or is there something more innocent that I am missing? The obvious solution is to create a new Sites page that is in the default namespace, which would resolve the issue, but how would I go about getting the correct SOAP URL generated?

 

 

The old developer forum had private messages, but the new forum doesn't appear to. Ironically, I got a message on the 23rd of December saying that I had a new private message. Clicking on the link results in an error page. Are there private messages, and if so, how do we get to them? Furthermore, if not, when will they be available?

Summary

A class implementing an override for public String toString() will not have this function honored by String.join(). Instead, it returns the name of the class. Using the normal concatenation operator on the list yields output that is expected.

 

Repro



<apex:page controller="repro">
    <table>
        <tbody>
            <tr>
                <td>new sub1().tostring()</td>
                <td>{!Sub1ToString}</td>
            </tr>
            <tr>
                <td>''+(new sub1[] { new sub1() })</td>
                <td>{!Sub1AsList}</td>
            </tr>
            <tr>
                <td>string.join(new sub1[] { new sub1() }, '')</td>
                <td>{!Sub1AsJoin}</td>
            </tr>
            <tr>
                <td>new sub2().tostring()</td>
                <td>{!Sub2ToString}</td>
            </tr>
            <tr>
                <td>''+(new sub2[] { new sub2() })</td>
                <td>{!Sub2AsList}</td>
            </tr>
            <tr>
                <td>string.join(new sub2[] { new sub2() }, '')</td>
                <td>{!Sub2AsJoin}</td>
            </tr>
        </tbody>
    </table>
</apex:page>

 

public with sharing class repro {
    class sub1 {
    
    }
    
    class sub2 {
        public override string tostring() {
            return 'Hello. I am sub2.';
        }
    }
    
    public string getSub1ToString() {
        return new sub1().tostring();
    }
    
    public string getSub1AsJoin() {
        return string.join(new sub1[] { new sub1() }, '');
    }

    public string getSub1AsList() {
        return ''+(new sub1[] { new sub1() });
    }
    
    public string getSub2ToString() {
        return new sub2().tostring();
    }
    
    public string getSub2AsJoin() {
        return string.join(new sub2[] { new sub2() }, '');
    }
    
    public string getSub2AsList() {
         return ''+(new sub2[] { new sub2() });
   }
}

 Output from above:

 

new sub1().tostring()sub1:[]
''+(new sub1[] { new sub1() })(sub1:[])
string.join(new sub1[] { new sub1() }, '')repro$sub1
new sub2().tostring()Hello. I am sub2.
''+(new sub2[] { new sub2() })(Hello. I am sub2.)
string.join(new sub2[] { new sub2() }, '')

repro$sub2

 

As one can see, It's not even trying to join them together, it's just calling some sort of odd "List<Object>.getType()" function that we can't even access.

 

I've logged a case with support, but since I'm half-expecting them to just close it without even trying to log a bug, I'm also posting this here hoping that some PM or internal salesforce.com developer will see this and have it fixed at some point.

If I "use strict" in my code, will Visualforce Remoting blow up? Has anyone tried testing this to see what will happen? Are there any gotchas I should be made aware of?

 

I tried something like this:

 

"use strict";
(function(window,undefined) {
  var addEvent = function(...) { ... };
  var callbackHandler = function(...) { ... };

  var onWindowLoad = function(...) {
     Visualforce.remoting.Manager.invokeAction(
       "{!$RemoteAction.myClass.myMethod}",
       callbackHandler);
  };
  addEvent(window,"load",onWindowLoad,true);
})(window);

Where ... is not relevant. It runs, and the data comes back just fine, but I wanted some feedback on if there were any known issues where it might be possible that remoting fails entirely because of strict mode, perhaps even outside the realm of being able to use exception handling. Or, should I just forego strict mode and leave that for another day?

See last paragraph for summary...

 

I was trying to create an adaptive loader routine in Apex Code, and I came across an interesting bug. First, let's take a look at what I was attempting to do:

 

sobject record = cache.load( recordId );
set< id > relatedIds = new set< Id >( );

for( SObjectField field: Cache.getFieldTokens( record.getSObjectType( ) ) ) {
   if( record.get( field ) != null && record.get( field ) instanceOf id ) {
       relatedIds.add( Id.valueOf( record.get( field ) );
   }
}
map< id, sobject > related = new map< id, sobject >( Cache.load( relatedIds ) );

Where:

* Cache.load( Id ) returns a single record from a static map, querying the record, if necessary.

* Cache.getFieldTokens( SObjectType ) returns all tokens from a SObjectType.getDescribe().fields.getMap().values(), again loading from a static map if previously defined.

* Cache.load( Set< Id > ) is a batch version of above, returning a list of SObject records in arbitrary order, querying records that are missing from the cache, and capable of returning multiple types of SObjects.

 

When I tried this initially, I got an odd exception: "Invalid ID."; the exception was thrown from my Cache class, so I wondered how it could have gotten there.

 

I fiddled around with the straightforward means of assigning an ID via a string:

 

Id a = '0013000000f3adA'; // OKAY
Id b = 'john doe';        // EXCEPTION

So, it would appear the setter function works fine.

 

Next, I tried casting:

 

String a = '0013000000f3Adf', b = 'john doe';
Id c = ( Id )a; // OKAY
Id d = ( Id )b; // EXCEPTION

So far, so good; it's also using the setter function of ID.

 

Next, I tried using Id.valueOf:

 

Id a = Id.valueOf( '0013000000d3afA' ); // OKAY
Id b = Id.valueOf( 'john doe' );        // OKAY ?!?!

This means that Id.valueOf doesn't use the setter method, but instead internally constructs an ID.

 

The next tidbit came when I tested the Set<T> class against an ID.

 

First, a straight assignment:

 

Set< Id > a = new set< Id >( );
a.add( '00130000003faZs' ); // OKAY
a.add( 'john doe' ); // EXCEPTION

So, it seems that Id's setter is in play here.

 

Next, I tried using the defunct valueOf:

 

Set< Id > a = new Set< Id >( );
a.add( Id.valueOf( 'john doe' ) ); // OKAY ?!?!

So, it seems that a "corrupted" ID value will be accepted into a set of IDs.

 

This led to the next problem:

 

for( Id b: a) {
  // Do something
}

If a is a set of IDs, and a corrupted ID value (via valueOf) is in the set, you will receive an "invalid ID" error here.

 

Finally, this led me back to my source code:

 

if( Id.valueOf( 'john doe' ) instanceOf Id ) {
  System.debug('** Invalid ID was accepted by instanceOf **');
}

So, Set<T>.add(Object) apparently checks the class of the incoming object against the class of its template, and automatically accepts them without question, otherwise attempts a cast (calling the correctly-working setter function).

 

I submitted a case to support, and they told me to go away because I don't have premier support, and all I wanted to do was log a bug with the dev team.

 

Hopefully an admin will see this and it will get logged as a bug. In the interim, the community should note that Id.valueOf is broken, and instanceOf is also broken as a side-effect. Instead, you should always use casting, and try-catch the cast so you can detect incorrect ID values.

 

Sometime a week or two ago, files being saved in a project were no longer committed to the server directly. Instead, they would have the "Save locally only" marker, and I would have to use Force.com | Save to Server... to resolve this issue. A Google search produced a way to open the log file, and this is the entry that I see:

 

WARN [2012-11-26 16:06:59,426] (DefaultBuilder.java:applyDirtyMarkers:85) - TODO: apply 'Save locally only...' markers on each resource

I've tried deleting the project and re-building it, importing it back from our svn, refreshing the metadata, deleting the src folder, and so on. Nothing seems to fix the problem.

 

I'm using Force.com IDE version 25.0.0.

 

Any suggestions or pointers would be appreciated.

I was looking at field level help on the IdeaExchange and I thought to myself, "Self, wouldn't it be nifty to build a feature like that for fun?" So I did.

However, I don't have time to write some fancy documentation, so here's the quick version:

1) Test drive the app, and make sure to get the XML file from the Documents tab.
1) Install the app into your organization.
2) Find the ID of the S-Control in Setup | Build | Custom S-Controls (eg. 01N30000000XXXX).
3) Elect to show custom sidebar components (Setup | Customize | User Interface).
4) Create a new home page component (Setup | Customize | Home | Home Page Components). Make sure the component is on the "narrow" side.
 Use the following code (check "Show HTML" first), updating the ID of the S-Control:
<IFRAME style="DISPLAY: none"
src="/servlet/servlet.Integration?lid=01N30000000XXXX">
</IFRAME>
5) Create a home page layout (Setup | Customize | Home | Home Page Layouts), and add the component to the layout. Assign the layout to the correct profiles.
6) Update the XML file from step 1 to include your terminology. You may embed HTML tags by escaping them-- see the example XML file for examples of this.
7) Edit the S-Control (Setup | App Setup | Build | Custom S-Controls), and use the "Attach File" feature below the code to upload the file. Save to have the XML file uploaded.

That's it. You now have field level help on all standard and custom objects. Testing suggests that the XML file is cached by the browser, so only the home page should take longer to load. The XML parser in modern browsers seems to be quite fast at what they do; I can't even tell the script runs (although I'm only using a 3kb example, it seems to scale well).

I'd feel safe in saying the XML file could be at least 100kb without a penalty, if not more.

The code isn't that elegant, as I wrote it in about 20-30 minutes or so, so use at your own risk. (Honestly, it took me longer to create the appExchange entry for it than it did to write the app itself). Feel free to modify it, tweak it, whatever you would like to do to it.

How it works:

1) By embedding it on each page, it loads when the browser loads any detail page.
2) When it loads, it calls the XML file into memory and searches for an object with the same name as the page.
3) If it finds one, it proceeds to load the field entries and tries to locate each field. If it finds the field, it adds the custom message to the field.

If you have questions, post them to this thread, and if I have time, I'll answer them. I don't have time to support this as a full-time application though, so be forewarned. That's why I'm posting this as a free publication with the intent that someone will find it useful for future integrations using this methodology.

One final note: I apologize for the source code. I tend to be rather cryptic at times when writing code privately. If you can't figure something out, just ask. And please keep it in this thread, so all the answers can be found later.

~ sfdcfox ~
I'm trying to do a query to return a field with the type reference.  I am assuming that it means the field resides in another object table?

How do you return the value of a reference field in a simple SQL statement?
How to write Test class for std controller and custom controller,wrapper class?
I'm writing a trigger on OpportunityLineItem, but I need to access the Close Date of the OpportunityLineItem's associated Opportunity. Is there a way to do this?
Hi,

  I need to make a callout to a webservice to update the content before it is saved using a trigger. Currently I am using "After insert" to get the id of the object and call an async class which would then update the object based on the response from web service. However I would like to change this behavior to before insert in which case the id of the object is returned as null since the object is not saved yet Is there any way I could do this ?

Thanks,
Anil
Hi there, 
I'm trying to use Analytics API to fetch the results of a report (syncronous) and this report contains a field that might have a JSON inside.

The problem is that the API is returning 

<pre>{
          "value" : "{\n20:{Net:0.0,VAT:0.0,Total:0.0,VAT(%):...",
          "label" : "{\n20:{Net:0.0,VAT:0.0,Total:0.0,VAT(%):..."
        }</pre>

(is cutting out part of the information).

Is there any parameter that I can use or some way to prevent the API from cutting out this information?

Thanks and regards.
  • January 20, 2014
  • Like
  • 0
I have been struggling to understand why code coverage for a trigger is 100% in sandbox and 0% when attempting to deploy to production.
Hi, we have a requirement to integrate Salesforce with a ThirdParty Vendor using webservices.

We need to send around 300,000 Records from Salesforce to the ThirdParty vendor using their webservice.
We have a custom apex program using which we are able to call the third party web service successfully within a future method in a schedulable program. However, for a volume as high as 300k records, I am not sure how to avoid hitting the governer limits. My understanding is that, I can make 10 calls in an apex class and can call the future method 10 times, making 100 web service calls in total. This is not sufficient for 300k records. Supposing we can include multiple records in one call, we will still hit another problem. Since each call's size is restricted to 3 MB and our one SOAP call's xml size is around 20k, the maximum we can do is 150 records per call giving us the ability to send 150 X 100 = 15k records. Is there any method to avoid hitting governer limits in this scenario.

Please help me as I am new to Sales force development.
Hi

I am trying to display image in visualforce page based on condition. The condition applied is on {$CurrentPage.parameters.startpage} value.

If {$CurrentPage.parameters.startpage} = "xyz" then display image <apex:image  url="xxxxxxx"> else display image <apex:image  url="yyyy">

I click a link and try to get the parameters of that url. Based on those parameter, I have to render different images on VF Page.

www.testurl.com/?value=xyz

www.testurl.com/?value=abc

Please find below the code I am using and let me know whats wrong there

<apex:image value="{If({!$CurrentPage.parameters.startpage}='xyz','/servlet/servlet.ImageServer?id=015D0000002Dkr2&oid=00DD0000000CWRY&lastMod=1388753305000' , '/servlet/servlet.ImageServer?id=015D0000002Dkr2&oid=00DD0000000CWRY&lastMod=1388753305000')}" />
Hi , 

I have created force.com site to login for customer portal users. we are applying session timie out value is 8 hours . is this settings apply for portal users also? 

is there any way to apply session settings different portal users? 

Thanks & Regards
Siva.

Hi all,
      This is my first attempt at using JSON in APEX, seems pretty straight forward.  I have what I think is a very simple question...making a call out to a webservice that is returning a JSON string for new order information.   In my apex class, I have a simple order class:
public class OrderInfo{
     public String CustomerName {get; set;}
     public String CustomerNo {get; set;}
     public String OrderStatus {get; set;}
     public String CustomerPONo{get; set;}
     public String Name {get; set;}
     public String GrossAmount {get; set;}
     public String WantedDeliveryDate {get; set;}

}

I make a call out to my webservice and get back my JSON string...all is well.  Now I need to deserialize it which I'm doing like this:
HTTPResponse res = h.send(req);  //response comes back correctly, data is all formatted as I would expect..
       //deserialize the JSON data returned by the web service into the OrderInfo class defined above
        OrderInfo newOrder = new OrderInfo();
        newOrder = (OrderInfo)JSON.deserialize(res.getBody(), OrderInfo.class);
So here is my problem, when I look at the values of my newOrder object they are all null.  Based on examples I viewed, It looked like the deserialize method with a specified object type would update the values in the object.  Do I need to do something else to save the values into the newOrder object?  
    I really appreciate any assistance, I'm sure it's something very simple!  Thanks in advance!!

Hi, 

I have made my cases object private and have a custom visualforce page and controller to retrieve a list of cases.

On the standard page, a user can only see those cases they have read permissions on.

On the visualforce page, the query also retrieves cases where the case contact is also from the same account. However, the user does not actually have permission to these cases, and gets a permission error when they try to access it. 

Just for my own sanity, when you run a query it should only retrieve those objects which you have at least permission to, correct? It has been working like this for everything else I can remember. 

Is there something weird with case sharing and customer portal licenses?

I am using overage customer portal licenses in a community.  
I have a function that uses a sosl query:

private List<Product2> runSoslToExecute() {
    List<List<Product2>> searchResults = [FIND :query IN ALL FIELDS RETURNING Product2 (Id, Name)];
    List<Product2> results = new List<Product2>();
    for(Product2 p : searchResults[0]) {
        results.add(p);
    }
    return results;
}

If I search for "AB*" then I also get results that include "1AB...". I thought the "*" wildcard only searches in the middle and end of the search and not at the beginning? Is there a way to run the sosl search so it only searches "AB" at the beginning?

Thanks for any help.
Hi,

I have urgent client requirement. Please help me in doing this.
Actually client has send me a php WSDL file which is containing "rpc" style. When I am including this WSDl file in salesforce. I am getting error that "rpc" style doesn't support.

So, How to call wsdl( php SOAP webservice) from salesforce, and in that i have to pass some field values to PHP server.
Please help me in doing this Integration... I tried to do by googling it. But I didn't find out correct solution.

I tried using http callouts as like....

HttpRequest req = new HttpRequest();
req.setEndpoint('http://tfserver.forexwebsolutions.com/tfserver.php?wsdl');
req.setMethod('GET');
Http http = new Http();
HttpResponse response = http.send(req);
System.Debug('STATUS:'+response.getStatusCode());
System.Debug('Body:'+response.getBody());

Here I am getting the XML in respose....
Please help me in passing values to php fields... So that it will be very helpful.
Whether it is possible to add standard account logo image of salesforce in visualforce page and also customizing the text in that logo ?
Hi everybody!

First at all: Happy New Year to you and your family. I wish you all the best in new 2014 year.

And about my case:

I use 'MyPdfRenderingPage.getContent();' method to get Blob PDF-body, create PDF attachment and sent it by mail.

And a code (please see below) works great in  Console's Execute Anonimous Window. It creates a mail with PDF file attached which I can open later.

But if I insert the same piece of code in my Email service (it receives a mail, creates a record and returns new mail with PDF attachment), it doesn't work correctly. I receive the mail, but can't open PDF attachment.

So I checked what does that Blob return content? If to execute 'MyPdfRenderingPage.getContent();' method in Email service, it returns HTML file with JS script inside leads to MyPdfRenderingPage.

In both cases the code runs by the same user, i did check it as well.

I have no idea what is wrong here...

Thanks a lot for your help.

----------
And that code below
______

Messaging.reserveSingleEmailCapacity(5);

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

String[] toAddresses = new String[] {'my@mail.com'};

mail.setToAddresses(toAddresses);

mail.setReplyTo('my@mail.com');

mail.setSenderDisplayName('Support');

mail.setSubject('New Record Created : ' + newRecords[0].id);

mail.setBccSender(true);

mail.setUseSignature(false);

mail.setPlainTextBody('Your new record has been created.');

mail.setHtmlBody('Your new record has been created.');


    PageReference pdf = Page.MyPDFpage;
    pdf.getParameters().put('id', (String)newRecords[0].id);
    pdf.getParameters().put('position', '1');
    pdf.setRedirect(true);

    Blob pageContent = pdf.getContent();

    Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
    efa.setFileName('PrintThisPDF.pdf');
    efa.setBody(pageContent);                                                          

mail.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});                                                         
                                                          
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
Hi and thanks for your help.

I have 2 custom objects:
• Registrations
•  Registration Requests
The Problem: When the Registration Request Before Insert Trigger catches a duplicate it doesn’t stop the After Insert Trigger from running.  What is the best way to stop the processing of the After Insert Trigger if the error message is thrown in the Before Insert Trigger?
Registrations Object has this trigger to stop duplicates from being entered and a way to bypass it if decided:


trigger stopDupsonRegistrations on Registration__c (before insert) {
    Map<String, Registration__c> regMap = new Map<String, Registration__c>();
    Map<String, Registration__c> regMap1 = new Map<String, Registration__c>();
    Map<Boolean, Registration__c> regMap2 = new Map<Boolean, Registration__c>();
    Map<Boolean, Registration__c> regMap3 = new Map<Boolean, Registration__c>();       
    for (Registration__c regReq : System.Trigger.new) {
                // store registration pertinent values
                regmap.put(regReq.Account__c, regReq);
                regmap1.put(regReq.Product__c,regReq);
                regmap2.put(regReq.Duplicate_Registration__c,regReq);
                //regmap3.put(regReg.Manufacturer_Name__c,regReq      
    //Loop through and make sure no duplicates exist    //fields are Account, Product         
    for (Registration__c reg : [SELECT Account__c,Product__c,Manufacturer__c, Registration_Status__c FROM Registration__c]) {
   If (regReq.Duplicate_Registration__c == False && regReq.Account__c == regReq.Account__c && reg.Product__c == regReq.Product__c )      {
       regReq.addError('Registration for this Product already exists. If you want to enter it anyway, check the "Account has multiple locations" checkbox'  + ' and fill out the Location field');      
      }// end regReq.Duplicate_Registration__c   
}  //end for (Registration__c reg :
} // for (Registration__c regReq
}// end trigger

Registration Request object has 2 triggers Before insert and After insert
The before insert is:  This checks to see if a duplicate record exists and if so throw a message.
trigger stopDuplicateRegRequest on Registration_Requests__c (before insert, before update) {
    Map<String, Registration_Requests__c> regMap = new Map<String, Registration_Requests__c>();
    Map<String, Registration_Requests__c> regMap1 = new Map<String, Registration_Requests__c>();   
    Map<Boolean, Registration_Requests__c> regMap2 = new Map<Boolean, Registration_Requests__c>();
       
    for (Registration_Requests__c regReq : System.Trigger.new) {
                // store registration Request pertinent values
                regmap.put(regReq.Account__c, regReq);
                regmap1.put(regReq.Product__c,regReq);          
                regmap2.put(regReq.Duplicate_Registration__c,regReq); 
      
    //Loop through and make sure no duplicates exist
    //fields are Account, Product 
   
    for (Registration__c reg : [SELECT Account__c,Product__c, Registration_Status__c, Duplicate_Registration__c FROM Registration__c])
{
   If (regReq.Duplicate_Registration__c == False && reg.Account__c == regReq.Account__c && reg.Product__c == regReq.Product__c )
      {
      regReq.addError('Registration for this Product already exists. If you want to enter it anyway, check the "Account has multiple locations" checkbox'
                       + ' and fill out the Location field');
      regReq.StopInsert__c = True;                
       }// end if
      
} //end for (Registration__c reg
}//for (Registration_Requests__c

       }//end trigger

The after trigger is:  It is just a simple record creation.

trigger Reg_Request_to_Reg on Registration_Requests__c (after insert) {
    List<Registration__c> newRegistration = new List <Registration__c>();
   
           for (Registration_Requests__c reg : trigger.new) {
           
            Registration__c newReg = new Registration__c();
            newReg.Account__c = reg.Account__c;
            newReg.Opportunity__c = reg.Opportunity_Name__c;
            newReg.Product__c = reg.Product__c;
            newReg.Manufacturer_Name__c = reg.Manufacturer_Name__c;
            newReg.Inside_Sales_Rep__c = reg.Inside_Sales_Rep__c;
            newReg.Location__c = reg.Location__c;
            newReg.Duplicate_Registration__c = reg.Duplicate_Registration__c;
            newReg.Registration_Request_URL__c = 'https://na12.salesforce.com/' + reg.ID;
            newRegistration.add(newReg);
           
        }//end for
       
        insert newRegistration;
       
        }//end trigger
I am trying to get aouth token from using the username and password authentication for Salesforce rest api.

I am using this url: https://login.salesforce.com/services/oauth2/token

I am using this Header:

grant_type: password
content-type: application/x-www-form-urlencoded
client_id: 3MVG9Y6d_Btp4xp7vvFtoM5KvlxGGeHkTNHMBRocXHDKgrY.**********************
client_secret: 77228**********
username: ******@****.com
password: ********ESbfkvMHuULtcEROf6CNiMRZ
I am also giving the accesstoken in the password. but I am always getting this:

error_description: "grant type not supported"
error: "unsupported_grant_type"
  • December 31, 2014
  • Like
  • 0

Hi

i have requirement where i have implemeted custom change owner rathen than standard owner change.here i need to restrict some of the users to assign a case to queue.i mean those users who are having role "executive" and "specialist" not eligible to transfer a case to queue.

 

here is the snippet.

 

i have highlited a line where i am facing the problem.

 

what i am trying to write a condition is if the user role is executive he should  not assign a case to queue.but he can assign to user.

 

public with sharing class CaseExtension
{
    private final Case c;
    public User userProfile {get;set;}
    public Case caserec{get;set;}
    public Id getId {get;set;}
    integer counter=0;
   
  
   
    public CaseExtension(ApexPages.StandardController sc)
    {
        this.c = (Case)sc.getRecord();
             
        userProfile = [SELECT Id,Name,UserRole.Name,Profile.Name  FROM user where Id =: userInfo.getUserId()];
          }
   
    public PageReference updateCaseOwner()
    {    
       
       if(userProfile.UserRole.Name=='GBS IPAS Executive'&& c.OwnerId != 'User'){
         ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'You should not transfer to Queue'));   
         return null;
        } 
              c.Owner_Update__c = True;
               try{
        update c;
        }catch(Exception ex){
               
                String err = ex.getMessage();
                if(err.contains('INSUFFICIENT_ACCESS_OR_READONLY'))
                    err = 'You do not have sufficient access to perform the necessary action. Please contact the record owner';

                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, err));
                return null;
            }
           

        pageReference p3 = new PageReference('/' + c.Id);
             p3.setRedirect(true);

        system.debug('value of p3: ' + p3);

        return p3;
    }
    }

 

Thanks in Advance.

 

Regards,

 

Praveen Reddy

  • December 13, 2013
  • Like
  • 0

See last paragraph for summary...

 

I was trying to create an adaptive loader routine in Apex Code, and I came across an interesting bug. First, let's take a look at what I was attempting to do:

 

sobject record = cache.load( recordId );
set< id > relatedIds = new set< Id >( );

for( SObjectField field: Cache.getFieldTokens( record.getSObjectType( ) ) ) {
   if( record.get( field ) != null && record.get( field ) instanceOf id ) {
       relatedIds.add( Id.valueOf( record.get( field ) );
   }
}
map< id, sobject > related = new map< id, sobject >( Cache.load( relatedIds ) );

Where:

* Cache.load( Id ) returns a single record from a static map, querying the record, if necessary.

* Cache.getFieldTokens( SObjectType ) returns all tokens from a SObjectType.getDescribe().fields.getMap().values(), again loading from a static map if previously defined.

* Cache.load( Set< Id > ) is a batch version of above, returning a list of SObject records in arbitrary order, querying records that are missing from the cache, and capable of returning multiple types of SObjects.

 

When I tried this initially, I got an odd exception: "Invalid ID."; the exception was thrown from my Cache class, so I wondered how it could have gotten there.

 

I fiddled around with the straightforward means of assigning an ID via a string:

 

Id a = '0013000000f3adA'; // OKAY
Id b = 'john doe';        // EXCEPTION

So, it would appear the setter function works fine.

 

Next, I tried casting:

 

String a = '0013000000f3Adf', b = 'john doe';
Id c = ( Id )a; // OKAY
Id d = ( Id )b; // EXCEPTION

So far, so good; it's also using the setter function of ID.

 

Next, I tried using Id.valueOf:

 

Id a = Id.valueOf( '0013000000d3afA' ); // OKAY
Id b = Id.valueOf( 'john doe' );        // OKAY ?!?!

This means that Id.valueOf doesn't use the setter method, but instead internally constructs an ID.

 

The next tidbit came when I tested the Set<T> class against an ID.

 

First, a straight assignment:

 

Set< Id > a = new set< Id >( );
a.add( '00130000003faZs' ); // OKAY
a.add( 'john doe' ); // EXCEPTION

So, it seems that Id's setter is in play here.

 

Next, I tried using the defunct valueOf:

 

Set< Id > a = new Set< Id >( );
a.add( Id.valueOf( 'john doe' ) ); // OKAY ?!?!

So, it seems that a "corrupted" ID value will be accepted into a set of IDs.

 

This led to the next problem:

 

for( Id b: a) {
  // Do something
}

If a is a set of IDs, and a corrupted ID value (via valueOf) is in the set, you will receive an "invalid ID" error here.

 

Finally, this led me back to my source code:

 

if( Id.valueOf( 'john doe' ) instanceOf Id ) {
  System.debug('** Invalid ID was accepted by instanceOf **');
}

So, Set<T>.add(Object) apparently checks the class of the incoming object against the class of its template, and automatically accepts them without question, otherwise attempts a cast (calling the correctly-working setter function).

 

I submitted a case to support, and they told me to go away because I don't have premier support, and all I wanted to do was log a bug with the dev team.

 

Hopefully an admin will see this and it will get logged as a bug. In the interim, the community should note that Id.valueOf is broken, and instanceOf is also broken as a side-effect. Instead, you should always use casting, and try-catch the cast so you can detect incorrect ID values.

 

Hi,

Ant deployment. I am a System administrator. Package.xml contains:

<types>
        <members>*</members>
        <name>CustomApplication</name>
</types>

When I try to ant retrieve from my sandbox I get:

[sf:retrieve] package.xml - You do not have the proper permissions to access CustomApplication.

Why?

Paul

As many of you have discovered, our developer community is awesome. The wealth of knowledge here is phenomenal. This is an all volunteer community and people who take the time to help and post answers do so totally on their own initiative. With that said when someone provides the right answer to your question please take the time to mark their answer as the accepted solution. Also give them a kudos if they've really gone the extra mile to help out. Show some love ;)