• Ankit Sehgal
  • SMARTIE
  • 778 Points
  • Member since 2015


  • Chatter
    Feed
  • 21
    Best Answers
  • 1
    Likes Received
  • 1
    Likes Given
  • 4
    Questions
  • 89
    Replies
I have a triiger that, upon update or insert makes a number of callouts to an external API.  

So the trigger calls a method from a helper class that is defined as @future (callout=true) .

That all works great until I try to send an email as part of this sequence.  Then any callouts that occur after the email is generated give the error "System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out".

I first tried sending this email through another method marked as @future, but was told that future methods can't call future methods.

So I changed it to a queable:
 
public class TribeSendEmail implements Queueable {
    
    String HTMLBody = '';  
    String recipientEmail = '';
    
    public TribeSendEmail(String HTMLBody, String recipientEmail) {  
  
        this.HTMLBody = HTMLBody;  
        this.recipientEmail = recipientEmail;  
    }  
  
    public void execute(QueueableContext qc) {  
        Messaging.reserveSingleEmailCapacity(1);
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        
        String[] toAddresses = new String[] {recipientEmail}; 
        String[] ccAddresses = new String[] {foo@bar.org'};
        
        mail.setToAddresses(toAddresses);
        mail.setCcAddresses(ccAddresses);
        mail.setSubject('This is the subject');
        mail.setBccSender(false);        
        mail.setHtmlBody(HTMLBody);        
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });    
    } 
}
Which I call as follows from the @future method:
System.enqueueJob( new TribeSendEmail( emailBody, recipient ) );
but it still gives me the errors on any subsequent callouts.

Note that there are no DML actions in any of these classes aside from the sending of the email, and if I comment out the "enqueJob" statement, it all works fine.

Can anyone suggest a way to send an email from within this context or advise if I am doing something wrong?

Thanks!



 
Hi Folks,
What is Problem on Code coverage on the Batch APEX class
User-added image

Your help is highly appreciated
Fiona
I need to set inbound REST integration in one of my requirement. Whenever we hit Salesforce URL, it should update some info in Salesforce. I am using GET method and passing parameters in URL.

Here is URL I am hitting from POSTMAN - https://peeke-dev-ed.my.salesforce.com/services/apexrest/SFRen/BreakDownCounter?cust=KonarkRegency&build=A&wTank=T1&wLevel=50

But this gives me error - "errorCode": "INVALID_SESSION_ID"  

When I hit URL(/services/apexrest/SFRen/BreakDownCounter?cust=Greenland County Narhe Gaon&build=A&wTank=T1&wLevel=50) from workbench, it updates records successfully. 

My Apex Class is-
@RestResource(urlMapping='/BreakDownCounter/*')
global with sharing class RESTBreakDownController {
    @HttpGet
    global static void updateWaterLevels(){        
        String accntName=RestContext.request.params.get('cust');
        String buildName=RestContext.request.params.get('build');
        String tankName=RestContext.request.params.get('wTank');
        String waterLevel=RestContext.request.params.get('wLevel');
        
        SFRen__Water_Tank__c wTank=[select Id, SFRen__No_of_Times_Emptied_in_a_Day__c , SFRen__Building__c, SFRen__Max_Capacity__c, SFRen__Today_Water_Use__c, SFRen__Current_Water_Level__c, SFRen__Building__r.SFRen__Account__r.Name, SFRen__Building__r.Name from SFRen__Water_Tank__c where SFRen__Building__r.SFRen__Account__r.Name=:accntName and SFRen__Building__r.Name=:buildName and Name=:tankName limit 1];       
        
        if(wTank!=null){
            SFRen__Tank_Level__c level=new SFRen__Tank_Level__c(SFRen__Reading_Time__c=System.now(),SFRen__Water_Level__c=Decimal.valueOf(    waterLevel),SFRen__Water_Tank__c=wTank.Id);       
            insert level;            
        }       
    }   
}

I am not using any authentication. Am I missing anything in the process? Any help would be much appreciated. Thank you in advance.
Hello All,

I have added a couple of custom fields to Account and Case objects and I will migrate my changes from sandbox environment to production environment. But the production environment already has other custom fields that do not exist in the sandbox environment.

What is the change set behavior? It will override all fields in production or it will append my new fields to the existing configuration?

Thanks,
Ahmed Kishk
Hello ,
      I am working on salesforce integration with external system.  I  have a scenerio where nightly batch-class has to run to update inventory in both salesfroce and external- system. I do have some  experience with integration but not with integration using batch class. I am wondering if it is possible to write a batch class to make a HTTP request  and run in nightly basis ?
Hi,
according to the documentation: "Network Access allows you to whitelist a set of IP address ranges that you trust."
If we use this, what is to stop an attacker who has learnt one of our user's passwords, spoofing our IP address to gain access to our system without a verification code?
Hi,

What is maximum size of file downloaded using renderas in VF page.
Assumptions: 
1). Account object has a custom string field named acFieldOne
2). Contact object has a custom string field named coFieldOne
 
How to write a trigger, such that any time a Contact is created, the  coFieldOne field on the Contact, is stamped with the value in the acFieldOne field on the Account ?
Thanks in Advance.
I was running into this error in some code of mine and so I began to do some troubleshooting.  Hoping someone can explain what is going on.

So while troubleshooting, I opened an execute anonymous window to test a theory; this error only appears when referencing CampaignMember and not other objects.  Test Code 1 below results in the error "Illegal assignment from List<CampaignMember> to List<CampaignMember>"  while test code 2 executes with no errors. 

What is the difference and how can get around this issues?

------------Test Code 1:-----------------
string ID='xyz';
list<CampaignMember> lst = new List<CampaignMember>();
lst = [Select id from CampaignMember where id =:ID];


--------------Test Code 2:-----------------
string ID='xyz';
list<Campaign> lst = new List<Campaign>();
lst = [Select id from Campaign where id =:ID];
I have a custom data type formula field that contains a currency. See below... 

Name + "  $" +  TEXT(Quote_Per_Adult__c) + " rate per person based on " +  TEXT(Occupancy__c) + " Occupancy  "

It will populate in the email template like this...

Golden Nugget:Carson Tower $502.3 rate per person based on Double Occupancy

How can I make the price populate with the decimals at the end? instead of $502.3, I need it to populate as $502.30

I've tried just typing in Currency(Quote_Per_Adult__c), that didn't work.....I also tried TEXT(Quote_Per_Adult__c |# Currency) and it also did not like that.

Any help please!
Hi,

We've started using quick actions to create Cases and we want an option, like you do in the Case edit screen, to choose whether to assign via assignment rules or not.

The below trigger pushes everything through the assignment rules even if created by the quick action, and due to the fact that I cannot include the assign via assignment rules checkbox on the quick action I have created a field called use_assignment_rules__c. I would therefore like to nest an IF statement into this trigger to only run the trigger when the checkbox is equal to true. Struggling to make this work could anyone advise on how to get the trigger to work, any help would be greatly appreciated.

Thank you,

Snita
 
trigger AssignmentRulesonCaseTrigger on Case (after insert) {
    List<Id> caseIds = new List<Id>{};
        if(trigger.IsAfter && trigger.isInsert){
            for (Case theCase:trigger.new) 
                caseIds.add(theCase.Id);
            
            List<Case> cases = new List<Case>{}; 
            for(Case c : [Select Id from Case where Id in :caseIds])
            {
                Database.DMLOptions dmo = new Database.DMLOptions();
     
                dmo.assignmentRuleHeader.useDefaultRule = true;
                c.setOptions(dmo);
                
                cases.add(c);
            
    }
            Database.upsert(cases);
        }
}

 
Hi,

I am fairly new to developing classes and pages, and need assistance in getting a test class to work for this controller extension.  Your help is appreciated!

Controller:

public with sharing class OpportunityControllerExtension {

    private final Opportunity opp;
    
        public OpportunityControllerExtension(ApexPages.StandardController stdController)  {
            this.opp = (Opportunity) stdController.getRecord();
            
       }
       
    public PageReference Dismiss()  {
    
        opp.Display_Alert__c = false;
        update opp;
        
            PageReference pageRef = ApexPages.currentPage();
            pageRef.setRedirect(true);
            return pageRef;
            
            
       }
   }

I've tried a simple insert new opportunity test class, but I keep getting the error "Error: Compile Error: Constructor not defined".

Thank you!
Hi,
I'm creating a VF Page with a two columns table.
In the two columns I have to insert for each row a .txt file loaded from static resource.
That's my problem:
When I loaded the txt file in Visulaforce page with this line of code:
​<tr><b>{!$Resource.Cond1}</b></tr>

where Cond1  is the name of the txt file I loaded in static resources

My output in the page is
/resource/1469117262000/Cond1
instead of the actual content of txt Cond1 file.
Where am I wrong?
There's a special visualforce tag to use?
Please help me to solve this issue.


 

I need a salesforce developer to help me integrate Salesforce with Boberdoo. I need to be able to send lead information in one of my Salesforce Campaigns to my Boberdoo campaign. I understand this can be accomplished via API, though I do not have the exprerience to do so myself. Successful work will lead to future projects, if interested. 

Thank you

I’m trying to write a before delete trigger on a custom object called  “Dental_Assessment” so that if the ID of the record being deleted is the same as a field on the account it will set that field on the account to null. "Dental_Assessment" is a child object of custom object "Treatment" which is a child object of Account. I thought I had it, but I can’t figure out how to get it to update the account record. can anyone help me with the syntax for doing this?
 
This is my trigger, except line 5 doesn’t work:
 
trigger DeleteID on Dental_Assessment__c (before delete) {
 if(System.Trigger.IsDelete) {
  for (Dental_Assessment__c Assmt: trigger.old) {
    if(Assmt.ID = Assmt.treatment__c.individual__c.Last_Exam_Assmt_Form_ID__c) {
    Assmt.treatment__c.individual__c.Last_Exam_Assmt_Form_ID__c = null; 
   }
   }
   }
}
 
Hi, I'm spitballing here, but if I had a couple of PICKLIST's that contained the terms

Excellent
Average
Poor

and these where assigned a value is true in an IF statement (3,2,1) would it be possible to get a total to give a final score?

Example:
IF(ISPICKVAL( picklist__c, "Excellent"), 3,0,
IF(ISPICKVAL( picklist__c, "Average"), 2,0,
IF(ISPICKVAL( picklist__c, "Poor"), 1,0,
0
)))

Can I add another picklist__c in the same formula and add up the results?
Hi ,
regarding js in vf i have doubts in below code.pls help me.

1.function js(value)
   <apex:inputText value="{!search}"  id="search" onkeyup="js(value)"   />
   I used parameterized method but the above code is working even i remove parameter value,Is the declaration is correct and when to use parameterized method,because i used as the method returns a value in inputtext through this parameter.Is it correct,if not correct me


2.I am checking database value  in java script [controller:  pos=Database.query(holdString);] when pos contains letter which dont have records ,it should display no records found ,i am trying as i mentioned above in script but i think its not the write way,this i achived through controller, but i want this validation  through javascript 

as i am new to javascript,pls help me to understand.


<apex:page controller="searchwithactionstatuscontroller" id="one">
<script>
function js(value){
var inputValue = document.getElementById(search).value;
alert(inputValue );
if(inputValue==null||inputValue==''){
alert('no records found');
}
else{
actionFunName();
}
}
</script>


<apex:form id="two">
       <apex:actionFunction name="actionFunName" action="{!searchpositions}"  reRender="two" />
<apex:outputLabel for="search" value="SEARCH :" style="font-weight:bold"   />
<apex:inputText value="{!search}"  id="search" onkeyup="js(value)"   />
<!--<apex:actionSupport event="onkeyup" action="{!searchpositions}" reRender="one:two:block1"/>-->
<apex:outputText id="error" value="{!error}" />
<apex:pageBlock rendered="{!blockOnLoad}" id="block1">
<apex:pageBlockSection >
<apex:pageBlockTable value="{!poslis}" var="pl"   >
<apex:column value="{!pl.name}"/>
</apex:pageBlockTable> 
</apex:pageBlockSection>
</apex:pageBlock>
<apex:pageBlock rendered="{!blockOnEnter}" > 
<apex:pageBlockSection id="d">
<apex:pageBlockTable value="{!pos}" var="p"  >
<apex:column value="{!p.name}"/>
<apex:column >
<apex:inputCheckbox value="{!p.name}"/>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlockSection>
 </apex:pageBlock> 
</apex:form>
</apex:page>


controller
---------------

public with sharing class searchwithactionstatuscontroller {

    public String error { get; set; }
public boolean blockOnLoad{set;get;}
public boolean blockOnEnter{set;get;}


    public PageReference searchpositions() {
        string holdString ='SELECT name from Position__c  where name like  \'%'+search+'%\' ORDER BY name asc';
        pos=Database.query(holdString);
       blockOnLoad=false;
        blockOnEnter=true; 
        return null;
    }
public String search { get; set; }
public List<position__c> poslis{set;get;}
public List<position__c> pos{set;get;}

public searchwithactionstatuscontroller() {
poslis=[select Name from position__c];
blockOnLoad=true;
blockOnEnter=false;
}
}



 
  • May 09, 2016
  • Like
  • 0
Hello, 

Using this article (http://blog.jeffdouglas.com/2011/03/02/dynamically-group-display-query-results/) I have created a VF page and controller that dynamically groups custom object records by their associated campaign. 

It works great, except the campaigns in the array seem to display in random order on the VF page - and my users don't like that!

Is there a way that I can tweak my controller (shown below) to make the array of campaigns appear in alphabetical order? 

Here is my controller: 
 
public with sharing class AllSpotController{

public List <Job_Number__c> SPOT {get;set;}
public String[] campaigns {get;set;}

public void load() {

  SPOT = [Select id, name, Thumbnail_URL__c, ISCI__c, Title__c, Project__c, Campaign__r.Name, Nets_Running__c, View_Link__c, Internal_Title__c, Legal__c from Job_Number__c where ISCI__c <> null];
  
  Set<String> campaignSet = new Set<String>();
  for (Job_Number__c j : SPOT)
      campaignSet.add(j.Campaign__r.Name);
      
      campaigns = new String[campaignSet.size()];
      Integer i = 0;
      for (String campaign : campaignSet) {
      campaigns[i] = campaign;
      i++;
        }
    }
}

Thanks in advance!

John
Hi Every one,
I'm unable to send email to all my users. This below code is allowing me to send email around 20 users only, if the limit exceeds 20 its throwing an error message . I want to send atleast 100 users, Please help me.

I'm having student object, in that 4 categories are there . Based on selection of category email must be sent. Each category having arond 100 users.

SendEmail failed. First exception on row 0; first error: LIMIT_EXCEEDED, Too many bccAddresses addresses.: [bccAddresses, 66]
Error is in expression '{!send}' in component <apex:commandButton> in page sendemailtocategory: Class.CategoryEmail.send: line 77, column 1
VF page:

<apex:page standardController="Student__c" extensions="CategoryEmail" id="pg">
<apex:sectionHeader title="Send an E-mail"/>

    <script>
function read(){
var sel=document.getElementById("{!$Component.pg.fm.pb.pbs.pbsi.selectcat}").value;
//alert(sel);
var subj=document.getElementById("{!$Component.pg.fm.pb.pbs1.pbsi1.sub}").value;

var body=document.getElementById("{!$Component.pg.fm.pb.pbs2.pbsi2.bdy}").value;

if(sel!='' && subj !='' && body!='')
   readsel(sel,subj,body);
  else
  {
  alert('Please fill all values.');
  return false;
  }
}
</script>

<apex:form id="fm">
<apex:pagemessages />
<apex:actionFunction action="{!readsel}" name="readsel">
<apex:param value="sel" assignTo="{!selectcat}"/>
<apex:param value="subj" assignTo="{!subject}"/>
<apex:param value="body" assignTo="{!body}"/>
</apex:actionFunction>
<apex:pageBlock title="Sending E-mail" id="pb">
<apex:pageBlockSection id="pbs" columns="1">
<apex:pageblockSectionItem id="pbsi">
<apex:outputLabel id="ol" value="Category" for="Cat"/>
<apex:actionRegion >
<apex:SelectList value="{!selectcat}" size="1" id="selectcat"  >
    <apex:selectOption itemValue=""  itemLabel="-- Please select a category--"></apex:selectOption> 
      <apex:selectOptions value="{!Name}">
      </apex:selectOptions>
      <apex:actionSupport event="onchange" />
    </apex:SelectList>
     </apex:actionRegion>
</apex:pageblockSectionItem>
</apex:pageBlockSection>
<apex:pageBlockSection id="pbs1" columns="1">
<apex:pageblockSectionItem id="pbsi1">
<apex:outputLabel value="Subject" for="sub"/>
<apex:inputText maxlength="100" value="{!subject}" id="sub"  size="75" />
</apex:pageblockSectionItem>
</apex:pageBlockSection>
<apex:pageBlockSection id="pbs2" columns="1">
<apex:pageblockSectionItem id="pbsi2">
<apex:outputLabel value="Body" for="bdy"/>
<apex:inputTextarea value="{!body}" id="bdy" rows="20"  cols="89" richText="true"/>
</apex:pageblockSectionItem>
</apex:pageBlockSection>
<apex:pageBlockButtons >
<apex:commandButton action="{!send}" value="Send"  onclick="return read();" id="cmdbutton"/>
<apex:commandButton action="{!cancel}" value="Cancel"/>
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
</apex:page>


Controller: 

public with sharing class CategoryEmail {
    public String subject{get; set;} 
    public String body{get; set;} 
    public String selectcat {get; set;} 
    public List < Student__c > stud {get; set;} 
    public String selectedLocation {get;set;}
   
    public PageReference readsel() {
        system.debug('selectcategory111' + selectcat);
        return null;
    }
    public CategoryEmail(ApexPages.StandardController controller) {

    }
  public List < SelectOption > getName() {
        List < SelectOption > options = new List < SelectOption > ();
        options.add(new SelectOption('Enrichment', 'Enrichment'));
        options.add(new SelectOption('After School', 'After School'));
        options.add(new SelectOption('Pre – K', 'Pre – K'));
        options.add(new SelectOption('Summer Camp', 'Summer Camp'));
        return options;
    }

 public List<SelectOption>  getLocations() 
    {
        List<SelectOption> options = new List<SelectOption>();
        options.add(new SelectOption('--Select a Location--','--Select a Location--'));
        Id lmId = UserInfo.getProfileId();
        if(lmId == [SELECT Id FROM Profile Where Name = 'Location Manager'].Id)
        {
        for (Location__c l: [SELECT Name, isLocationManager__c FROM Location__c WHERE isLocationManager__c = 'yes'])
        options.add(new SelectOption(l.Name,l.Name));
        }
        else
        {
        for (Location__c l: [SELECT Name, isLocationManager__c FROM Location__c])
        options.add(new SelectOption(l.Name,l.Name));
        }
        return options ;
        
    }
    public PageReference send() {
         List < String > emailTo = new List < String >();
         List < String > emailCc = new List < String >();
         List< document > documentList=[select name from document where Name='logo'];
   
         emailTo.clear();
         emailCc.clear();
       
        stud = [select id, Name, Parent_Alternative_Email_ID__c, Parent_Email__c, Category__c from Student__c where Category__c = : selectcat];
 
        for (student__c std: stud) {
            if(std.Parent_Email__c !=null)
                 emailTo.add(std.Parent_Email__c);
            if(std.Parent_Alternative_Email_ID__c !=null)
                emailCc.add(std.Parent_Alternative_Email_ID__c);
        } 
        
        
       List<Messaging.SingleEmailMessage> mails= new List<Messaging.SingleEmailMessage>();
       Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage();
        semail.setBccAddresses(emailTo);    
        semail.setCcAddresses(emailCc);
        semail.setSubject(subject);
     
        semail.setHtmlBody(body);
        mails.add(semail);
        if(!mails.isEmpty()){
        if(!semail.BccAddresses.isEmpty()){
         Messaging.sendEmail(mails);
         ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.INFO, 'Email has been sent');
                    ApexPages.addMessage(myMsg);
                    
        }
        else{
        ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.WARNING, 'No Students are availble for selecting Category');
                    ApexPages.addMessage(myMsg);
        
           }
        }
        mails.clear();
        subject='';
        body='';
        selectcat='';
        return null;
        
    }
    
}

 
Hi, I'm trying to use an apex class to query the database and display the results on a visualforce page. The class (and page) saves without error, but nothing displays on the page when I navigate there. I'm new to this and know what's missing is likely very simple, but any help would be appreciated.

Here's the class:
public class SSReportTest {
    public String casenumber = 'JAMF-0160404';
    public List<sObject> numberList {get; set;}
    
    public List<sObject> getList() {
        numberList = Database.query('SELECT Case.Owner from Case where Case.CaseNumber = "J-0160404"');
        return numberList;

    }
}
And here is the visualforce page:
<apex:page controller="SSReportTest">
    
    <apex:pageBlock >
        {!numberList}
    </apex:pageBlock>
    
</apex:page>

Thanks everyone!
 
I need to implement a lead approval process through email for a user having Force.com app subscription licence. Is it a good idea to write a trigger for an email alert and using inbound email handler for the response which will accept or reject the lead?
I need to calculate the sum of tax field of all the quote line items which have taxable check box true and display it on the Quote field.The tax field on the line item is a formula field so i am unable to create a roll up summary.I wrote a trigger but it is failing in delete case.Can somebody guide me where i am goinge wrong with it 
trigger CalculateTotalTax on QuoteLineItem (after insert,after update,after delete) 
{
    list<QuoteLineItem> l;
    if(Trigger.isInsert || Trigger.isUpdate)
    {
    	l =[SELECT Id,QuoteId,Tax__c,Taxable__c FROM QuoteLineItem WHERE ID IN: Trigger.new];
    }
    if(Trigger.isDelete)
    {
        l =[SELECT Id,QuoteId,Tax__c,Taxable__c FROM QuoteLineItem WHERE ID IN: Trigger.old];
    }
    Decimal ttx=0.00;
    String qid;
    for(QuoteLineItem q : l)
    {
        qid=q.QuoteId;
    }
    for(QuoteLineItem f : l)
    {
        if(f.Taxable__c == true)
        {
                ttx+=f.Tax__c;
        }
    }
    Quote q=[SELECT Id,TotalTax__c FROM Quote WHERE Id =: qid];
    q.TotalTax__c=ttx;
    System.debug(ttx);
    update q;
}
i need to synchroze metadata from Org A to Org B. How can i syncronize my org metadata to another org using ant and github ? is it possible to clone a repository from github containing migration data form Org A and deploy it direectly to Org B ?
I want to record all my call logs on my android smartphone in my salesforce org. on a daily basis. Do i need to create a native android app for that ? What are the requrements to implement such functionality ? 
I want to record all my call logs on my android smartphone in my salesforce org. on a daily basis. Do i need to create a native android app for that ? What are the requrements to implement such functionality ? 
We have cases getting created through an external email through email to case assignment how can we handle this
I have a triiger that, upon update or insert makes a number of callouts to an external API.  

So the trigger calls a method from a helper class that is defined as @future (callout=true) .

That all works great until I try to send an email as part of this sequence.  Then any callouts that occur after the email is generated give the error "System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out".

I first tried sending this email through another method marked as @future, but was told that future methods can't call future methods.

So I changed it to a queable:
 
public class TribeSendEmail implements Queueable {
    
    String HTMLBody = '';  
    String recipientEmail = '';
    
    public TribeSendEmail(String HTMLBody, String recipientEmail) {  
  
        this.HTMLBody = HTMLBody;  
        this.recipientEmail = recipientEmail;  
    }  
  
    public void execute(QueueableContext qc) {  
        Messaging.reserveSingleEmailCapacity(1);
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        
        String[] toAddresses = new String[] {recipientEmail}; 
        String[] ccAddresses = new String[] {foo@bar.org'};
        
        mail.setToAddresses(toAddresses);
        mail.setCcAddresses(ccAddresses);
        mail.setSubject('This is the subject');
        mail.setBccSender(false);        
        mail.setHtmlBody(HTMLBody);        
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });    
    } 
}
Which I call as follows from the @future method:
System.enqueueJob( new TribeSendEmail( emailBody, recipient ) );
but it still gives me the errors on any subsequent callouts.

Note that there are no DML actions in any of these classes aside from the sending of the email, and if I comment out the "enqueJob" statement, it all works fine.

Can anyone suggest a way to send an email from within this context or advise if I am doing something wrong?

Thanks!



 
We are trying to expose a service in Salesforce using Apex that external systems can call. This service is pretty simple. We will run a query against an object and create a response that returns an array of "coupon codes" stored on each account of a certain record type that has a coupon code.
basically it's just [SELECT Id, Coupon__c FROM Account WHERE Coupon__c != null]
We then will loop through the list and formulate a JSON array and return the coupon codes.
The issue here is we have more than 50,000 rows needing to be returned. So SOQL 101 is an issue. Also heap size could be an issue. We are expecting possibly up to 500,000+ accounts with coupons to be returned.
What are our options here? Should we tell our consumers to call a standard Salesforce API, similar to how you can execute queries in workbench? This would require subsequent calls to retrieve all 500,000 accounts/coupons though, right? Like a query more type of thing?
Also now that we are exposing APIs from Salesforce, I know we have a 24 hour API call limit. Is there a concurrent limit? If we are allowed say, 5,000,000 calls over a 24 hour period, what happens in 4,000,000 all come at the same time? How will the system respond?
Any help would be appreciated. Thanks!
Hi Folks,
What is Problem on Code coverage on the Batch APEX class
User-added image

Your help is highly appreciated
Fiona
Hey all!
I'm getting this error and not quite sure what I'm doing wrong.  My brain is a bit tired from trying to figure this out so any help here would be greatly appreciated.  I'm tempted to build the report from scratch, but I don't have time to do that right now. 
User-added image

Hello,

I have a custom Time field called Scheduled_ET__c. The drop-down displays time in 15 minute increments, however we do not want the user to select 15 or 45 minute increments. Since there is no way I can find to eliminate 15 or 45 from the drop-down I need to find another soultion.

My thoughts are...use a validation rule or Apex to change the minutes to a 30 min increment.

Is it possble to extract the minutes part of a custom time field in Apex and how would one do that?

My rounding logic would be if user enters <16 round down to 00, >16 and <45 round to 30, >45 up to 00 and increment hour.

Any thoughts or suggestions would greatly be appreciated.

Kind regards,

Robert

Hi!
I'm new to apex coding.  I'm looking for an example of code for a trigger that will add the text 'new' to a name field once a contact object has been created.  Any suggestions are greatly appreciated.
this header is different

the original template of salesforce is :User-added image

may i know why iam not getting the standard header in salesforce
Hi All,
i have a helper class which is working fine on contact to track history now i want to change it into generic class
which should work for every object not only contact 
my class is given below:-
public class GenericClass {
    public static List<Contact> newContact = new List<Contact>();
    public static List<Contact> oldContact = new List<Contact>();
    public static Map<Id, Contact> newMapContact = new Map<Id, Contact>();
    public static Map<Id, Contact> oldMapContact = new Map<Id, Contact>();
    
    public static void GenericClassMethod(Map<Id, Contact> oldMapContact, Map<Id, Contact> newMapContact){
        List<History_Tracking__c> historiesToInsert = new List<History_Tracking__c>();
        for(Contact con : newMapContact.values()){
            Contact OldCon = oldMapContact.get(con.Id);
            System.debug('con'+con);
            System.debug('oldCon'+OldCon);
            for (String conField : ContactHistory()) {
                
                History_Tracking__c conHistory = createUpdateHistory(conField, oldCon, con);
                historiesToInsert.add(conHistory);
                System.debug('ConHistory'+conHistory);
                 System.debug('histories'+historiesToInsert);
            }
            
        }
        
        
        if(!historiesToInsert.isEmpty()) {
            List<History_Tracking__c> historiesToInsertWithoutDuplicates = new List<History_Tracking__c>();
            Set<History_Tracking__c> historiesSet = new Set<History_Tracking__c>();
            historiesSet.addAll(historiesToInsert);
            historiesToInsertWithoutDuplicates.addAll(historiesSet);
            
            insert historiesToInsertWithoutDuplicates;
            System.debug('ConRecord'+historiesToInsertWithoutDuplicates);
        }
    }
     private static History_Tracking__c createUpdateHistory(String field, Contact oldCon, Contact newCon) {
        History_Tracking__c      conHistory = new History_Tracking__c();
        conHistory.FieldName__c = field;
        conHistory.ObjectName__c = 'Contact';
        conHistory.ObjectId__c = oldCon.Id;
        String oldValue = String.ValueOf(oldCon.get(field));
        String newValue = String.ValueOf(newCon.get(field));
        
        conHistory.OldValue__c = oldValue;
        conHistory.NewValue__c = newValue;
        if (conHistory.OldValue__c != null) conHistory.OldValue__c = conHistory.OldValue__c.abbreviate(255);
        if (conHistory.NewValue__c != null) conHistory.NewValue__c = conHistory.NewValue__c.abbreviate(255);
        return conHistory;
    }

    public static  List<String> ContactHistory(){
        Map<String,FieldTracking__c> MapToFieldHistory = new Map<String,FieldTracking__c>();
        for(FieldTracking__c ft: [Select  Id, selectedField__c,Selectedobject__c from FieldTracking__c]){
            MapToFieldHistory.put(ft.Selectedobject__c, ft);
        }
        List<String> ListFieldTracking = new List<String>();
        String fieldValues =  String.valueOf(MapToFieldHistory.get('Contact').selectedField__c);
        ListFieldTracking.addAll(fieldValues.split(','));
        return ListFieldTracking;
    }
}
how to do it?
Any suggestions?
  • September 04, 2018
  • Like
  • 0
Hi Everyone,
I am new to salesforce, can you please provide test class for this class

public without sharing class UtilityClassWithoutSharing {
  static final String ERROR_MSG = 'The Opportunity you have chosen does not meet all Opportunity Validation rules.  Please update the opportunity and then re-assocaite it with the Deal.';
  
  //Method used in Deal Trigger.
  public static void updateOpp(map<id,id> oppIdDealIdMap, List<Deal__c> newDeals){
    
    list<Opportunity> opps = [select id,Deal__c from Opportunity where id in:oppIdDealIdMap.keySet()];
    list<Opportunity> oppsToUpdate = new list<Opportunity>();
    
    if(opps!=null && opps.size()>0){
      for(Opportunity opp:opps){
        if(opp.Deal__c != oppIdDealIdMap.get(opp.id)){
          opp.Deal__c = oppIdDealIdMap.get(opp.id);
          oppsToUpdate.add(opp);
        }
      }
    }
    
    // for handeling proper error messages
    //modified by Manmeet on 19th Dec 2012 for T-104876
    if(oppsToUpdate!=null && oppsToUpdate.size()>0){
      Database.SaveResult[] results = Database.update(oppsToUpdate,false);
      System.debug('MPK: '+results);
      Map<Id,String> mapErrors = new Map<Id,String>();
      for(Integer index = 0 ; index < results.size(); index++){
          Database.SaveResult result = results.get(index);
          Opportunity oppty = oppsToUpdate.get(index);
          if(!result.isSuccess() && String.valueOf(result.getErrors()[0].getStatusCode()).contains('FIELD_CUSTOM_VALIDATION_EXCEPTION')){
              mapErrors.put(oppty.Deal__c,ERROR_MSG);
          }
      }
      for(Deal__c deal  : newDeals){
          if(mapErrors.containsKey(deal.id)){
              deal.addError(mapErrors.get(deal.id));
          }
      }
    }
  }
  
  //Method used in Deal Trigger.
  public static void updateOppToRemoveDealId(list<id> oppIdDealIdMap){
    
    list<Opportunity> opps = [select id,Deal__c from Opportunity where Deal__c in:oppIdDealIdMap];
    list<Opportunity> oppsToUpdate = new list<Opportunity>();
    
    if(opps!=null && opps.size()>0){
      for(Opportunity opp:opps){
          opp.Deal__c = null;
          oppsToUpdate.add(opp);
        
      }
    }
    
    if(oppsToUpdate!=null && oppsToUpdate.size()>0){
      update oppsToUpdate;
    }
  }
}


Thanks
I need to set inbound REST integration in one of my requirement. Whenever we hit Salesforce URL, it should update some info in Salesforce. I am using GET method and passing parameters in URL.

Here is URL I am hitting from POSTMAN - https://peeke-dev-ed.my.salesforce.com/services/apexrest/SFRen/BreakDownCounter?cust=KonarkRegency&build=A&wTank=T1&wLevel=50

But this gives me error - "errorCode": "INVALID_SESSION_ID"  

When I hit URL(/services/apexrest/SFRen/BreakDownCounter?cust=Greenland County Narhe Gaon&build=A&wTank=T1&wLevel=50) from workbench, it updates records successfully. 

My Apex Class is-
@RestResource(urlMapping='/BreakDownCounter/*')
global with sharing class RESTBreakDownController {
    @HttpGet
    global static void updateWaterLevels(){        
        String accntName=RestContext.request.params.get('cust');
        String buildName=RestContext.request.params.get('build');
        String tankName=RestContext.request.params.get('wTank');
        String waterLevel=RestContext.request.params.get('wLevel');
        
        SFRen__Water_Tank__c wTank=[select Id, SFRen__No_of_Times_Emptied_in_a_Day__c , SFRen__Building__c, SFRen__Max_Capacity__c, SFRen__Today_Water_Use__c, SFRen__Current_Water_Level__c, SFRen__Building__r.SFRen__Account__r.Name, SFRen__Building__r.Name from SFRen__Water_Tank__c where SFRen__Building__r.SFRen__Account__r.Name=:accntName and SFRen__Building__r.Name=:buildName and Name=:tankName limit 1];       
        
        if(wTank!=null){
            SFRen__Tank_Level__c level=new SFRen__Tank_Level__c(SFRen__Reading_Time__c=System.now(),SFRen__Water_Level__c=Decimal.valueOf(    waterLevel),SFRen__Water_Tank__c=wTank.Id);       
            insert level;            
        }       
    }   
}

I am not using any authentication. Am I missing anything in the process? Any help would be much appreciated. Thank you in advance.
Hello All,

I have added a couple of custom fields to Account and Case objects and I will migrate my changes from sandbox environment to production environment. But the production environment already has other custom fields that do not exist in the sandbox environment.

What is the change set behavior? It will override all fields in production or it will append my new fields to the existing configuration?

Thanks,
Ahmed Kishk
Hello ,
      I am working on salesforce integration with external system.  I  have a scenerio where nightly batch-class has to run to update inventory in both salesfroce and external- system. I do have some  experience with integration but not with integration using batch class. I am wondering if it is possible to write a batch class to make a HTTP request  and run in nightly basis ?
Hi,
according to the documentation: "Network Access allows you to whitelist a set of IP address ranges that you trust."
If we use this, what is to stop an attacker who has learnt one of our user's passwords, spoofing our IP address to gain access to our system without a verification code?

Hi,

I'm not sure what I'm doing wrong here but even if I set the timeout to 120secs or 60secs it still throws a time out exception after 10secs.

Here's the code that makes the call out. This code is used as a OnClick Javascript on my custom button.
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    req.setMethod('GET');
    req.setTimeout(120000);
    
    try
    {
      HTTPResponse response = m_http.send(req);
      
     if(response.getBody() != null)
        return 'Success';
     else
        return 'Failed'; 
            
    } catch(System.CalloutException e) {
      return 'Error ' + e;
    }
------------------------------------------------------------------------------------------------------------------------------------------------------------

Is there somewhere else I need to set to make sure it uses the timeout set on the code?

Thanks for the help.

What would happen if I perform a DML update operation on the before update trigger of the same sObject record ?