• Greg H
  • SMARTIE
  • 1028 Points
  • Member since 2005
  • Interactive Ties


  • Chatter
    Feed
  • 30
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 23
    Questions
  • 421
    Replies
Good afternoon, folks.

I'm in the process of trying to consolidate the SOQL calls within a trigger of a particularly difficult sObject.  This sObject has enough code running on it that we're pretty regularly hitting the 101 error--so it's time to clean up and bulkify where possible.

I've run the following to fill a map with an sobject, and the children of that sobject.  Let's assume for the moment that Service_Order_Line is a child of Service_Order with a many-to-one relationship, and I've filtered this down so I'm only getting one Service_Order and maybe 5 or 10 Service_Order_Lines:

map<ID, Service_Order__c> testResults = new map<ID, Service_Order__c>([select ID, Name, (select ID, Name from Service_Order_Line__r) from Service_Order__c']);

Further down in the trigger, I'll need to reference the child objects, but I can't seem to find a syntax to make it work.  How would I write the following to loop through the children of testResults?

for(Service_Order_Line childrenOfTestResults : testResults.Service_Order_Line__r) {
    system.debug(childrenOfTestResults.Name);
}
Hello,

I exeucte a postman request to get the token.

I was writing a code for authenticating the API in slaesforce, but found that the headers are not correct.

I tried to get the headers by other way.

User-added image

How can i write the code for first part of the screen shot,  ?
  • September 23, 2019
  • Like
  • 0
I had a simple question. I want to check if an email entered in the form is the right format. How do you splice in apex? In other words I want to see that after the @ symbol, we only have gmail.com. I was going to write something like 
if(email__c.contains('@gmail.com'){} but then I realized that this may not be enough because someone could potentially enter an email of gmail.com@hotmail.com for example. So I want to see what I can write in apex to check if the email is in the format ###@gmail.com
Thank you

I'm new to developing and trying to determine if I will get errors thrown in my batch apex code. The purpose is to: upon deactivation of a user (trigger, which I understand isn't best practice but don't know another way the batch can be automatically started w/o checking for deactivated users every night), all of the leads of deactivated user are queried to change the OwnerId to a catchall user. The trick is that one user may have as many as 200,000 leads that need to be updated, hence why I am using batch apex. Two questions:

1. How many batch jobs will be activated with each deactivated user? (I think the answer is one?)

2. Will the batch job be sent to the Flex Queue as 'holding' and then to active, giving the org 105 possible batch jobs to be held/processed at once before throwing errors, or will it bypass Flex Queue, thereby limiting the org to only 5 batch jobs at a time?

I hope my questions make sense, and I appreciate any help. I have spent many hours researching this as a newbie. In case it's relevant, my code is below:

Trigger:

trigger BatchUpdateTrigger2 on User (after update)  {

//Map will keep deactivated users and their Id's, to be used later in batch Apex
	 Map<id, User> DeactivatedUsers = new Map<id, User>();
//Check all users in trigger, first if the IsActive button has been newly changed and if it now says that the user is not active    
for (Integer i=0;i<Trigger.new.size();i++) {
    
if (Trigger.new[i].IsActive!=Trigger.old[i].IsActive &&
   Trigger.new[i].IsActive == false) {
	DeactivatedUsers.put(Trigger.new[i].Id, Trigger.new[i]);
   }
}
// Make sure that there are users to be processed
if (DeactivatedUsers.size() > 0) {

            BatchUpdateLeads objBatchUpdateLeads=new BatchUpdateLeads(DeactivatedUsers);
            Database.executeBatch(objBatchUpdateLeads);
}
}


Batch Apex Class:

global class BatchUpdateLeads implements Database.Batchable<SObject> {
   
        //Save a public variable to hard-code the catchall user that will become lead owner
  	public Id GenericUserId = '0054P000009pLkrQAE';
    
    //map of userid - user that retrieves deactivated user(s) from previous trigger
    Map<Id, User> DeactivatedUsersMap = new Map<Id, User>();
    
    global BatchUpdateLeads(Map<Id, User> DeactivatedUsers) {
    DeactivatedUsersMap = DeactivatedUsers;
    }
    
//Search for the leads whose OwnerId is the deactivated user(s)
    global Database.QueryLocator start(Database.BatchableContext BC) {
    return DataBase.getQueryLocator([SELECT Id, OwnerId FROM Lead WHERE OwnerId IN : DeactivatedUsersMap.keySet()]);
    }
    
    //For leads whose owner was deactivated, change OwnerId to the catchall user
    global void execute(Database.BatchableContext BC, List<sObject> scope){
              List<Lead> leads = (List<lead>)scope;
                for (Lead l: leads){
                    l.OwnerId = GenericUserId;}
        
//Check that there are leads to be updated, then update
            if (leads.size() > 0){
              update leads;
            }
    	}
    global void finish(Database.BatchableContext BC) {
        
    //Send an email to system admin after the batch completes (fill in email)
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    String[] toAddresses = new String[] {'xxxxxxx@gmail.com'};
    mail.setToAddresses(toAddresses);
    mail.setSubject('Apex Batch Job is done');
    mail.setPlainTextBody('The Batch Apex Job Processed Successfully');
    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}
I have writen a Batchable class that works in Sandbox. Im trying to write a test class for this and am really struggling to make headway. 

This is my Class 
global class HealthUpdaterBatchable implements Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext BC) { 
        String query = 'SELECT Id FROM HealthScore__c';
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List<HealthScore__c> hsList) {
        for(HealthScore__c hs : hsList)
        {        
            hs.id = hs.id;
        }
        try {
        	
            update hsList;
        } catch(Exception e) {
            System.debug(e);
        }
    }   
    global void finish(Database.BatchableContext BC) {
    	
  }
}
This is my test class so far 
private class HealthUpdaterBatchableTest {

static testmethod void test() {

HealthScore__c[] hsList = new List();
for (Integer i=0;i<200;i++) {
HealthScore__c m = new Healthscore__c();
hsList.add(m);
}
insert hsList;

Test.startTest();
HealthUpdaterBatchable c = new HealthUpdaterBatchable();
Database.executeBatch(c);
Test.stopTest();
    
HealthScore__c[] hsUpdatedList = [SELECT Id FROM HealthScore__c];
System.assert(hsUpdatedList[0]);
}
}
Im getting a few errors
  • Expecting < but was ( -Line 6
  •  Invalid type: HealthScore - Line 18
  •  Method does not exist or incorrect signature: void assert(Healthscore) from the type System. - Line 19.
Any advice or assistance is very much appreciated 
 
I am trying to update a custom event field, sales_within_1_year__c, when a custom contact field, sales__c, changes. For example:

Event 1: tied to Contact A & Contact B; sales_within_1_year = $0
Event 2: tied to Contact A & Contact C; sales_within_1_year = $10

Contact A sales changes from $100 to $200.
Event 1: new sales_within_1_year = $100
Event 2: new sales_within_1_year = $110

If the sales for Contact B or C changed, it would only affect the event they are tied to.

I thought my trigger would work, and it does when I change a contact's sales number individually. But when I bulk update contacts, none of the sales_within_1_year numbers change. I was wondering if someone could help me through this. Thanks!

Here is my trigger:

trigger EventSales on Contact (before update) {
                //Create a list of contact IDs that have updating sales
                List<Id> contactIds = new List<Id>();
    for(Contact con : trigger.new) {
        if(Trigger.newMap.get(con.Id).Sales__c == NULL) return;
        else if(trigger.newMap.get(con.Id).Sales__c == 0) return;
        else if(trigger.oldMap.get(con.Id).Sales__c == NULL) {
            contactIds.add(con.Id);
        }
        else if(trigger.newMap.get(con.Id).Sales__c !=
                trigger.oldMap.get(con.Id).Sales__c) {
            contactIds.add(con.Id);
        }
    }
   
    //Create a list of event relations (contact-event pairs) for updating contacts
    List<EventRelation> evRel = [SELECT EventId, RelationId
                                FROM EventRelation
                                WHERE RelationId IN :contactIds];
   
    //Create a map of the updating contacts and their related events
    Map<Id, List<Id>> contactEvents          = new Map<Id, List<Id>>();
   
    //Create a list of event Ids that are going to be updated
    List<Id> eventIds = new List<Id>();
   
    //Put the contact Id and event Id in the map for events that have updating contacts
    for(EventRelation rel :evRel) {
        if(contactEvents.containsKey(rel.RelationId)) {//If the contact is already in the map
            List<Id> relatedEv = contactEvents.get(rel.RelationId);//Grab the list of events tied to the contact
            relatedEv.add(rel.EventId);//Add the new event to the list
            contactEvents.put(rel.RelationId, relatedEv);//Put the updated list into the map
        }
        else {//If the contact isn't in the map
            contactEvents.put(rel.RelationId, new List<Id>{rel.EventId});//Put the contact and event into the map
        }
        //Add the updating event to the eventIds list
        if(eventIds.contains(rel.EventId)) return;
        else eventIds.add(rel.EventId);
    }
   
    //Create a list of events that are going to be updated
    List<Event> listEventsMaker = [SELECT Id, Sales_within_1_year__c
                                   FROM Event
                                   WHERE Id IN :eventIds
                                   AND EndDateTime = LAST_N_DAYS:365];
   
    List<Event> listEvents = new List<Event>();
    for(Event ev :listEventsMaker) {
        if(listEvents.contains(ev)) return;
        else listEvents.add(ev);
    }
   
    //Keep a list of events to update
    List<Event> changedEvents = new List<Event>();
   
    //Update the sales amounts for the events
    for(Id con :contactEvents.keySet()) {//For each contact in the map
        List<Id> thisContact = new List<Id>();//Create a list of events tied to this specific contact
        Contact oldCon = trigger.oldMap.get(con); //create a record for the contact pre-update
        Contact newCon = trigger.newMap.get(con); //create a record for the contact post-update
        if(newCon.Sales__c == NULL) return;
        else if(newCon.Sales__c == 0) return;
        else if(oldCon.Sales__c == NULL) {
            for(Id event :contactEvents.get(con)) {
                thisContact.add(event);
            }
            for(Event ev :listEventsMaker) {
                if(thisContact.contains(ev.Id)) {
                    changedEvents.add(ev);
                    if(ev.Sales_within_1_Year__c == NULL) {
                        ev.Sales_within_1_Year__c = newCon.Sales__c;
                    }
                    else ev.Sales_within_1_Year__c += newCon.Sales__c;
                }
            }
        }
        else if(oldCon.Sales__c
                != newCon.Sales__c) {
            for(Id event :contactEvents.get(con)) {
                thisContact.add(event);
            }
            for(Event ev :listEventsMaker) {
                if(thisContact.contains(ev.Id)) {
                    changedEvents.add(ev);
                    if(ev.Sales_within_1_Year__c == NULL) {
                        ev.Sales_within_1_year__c = (newCon.Sales__c
                                                     - oldCon.Sales__c);
                    }
                    else ev.Sales_within_1_Year__c += (newCon.Sales__c
                                                       - oldCon.Sales__c);
                }
            }
        }
    }
    update changedEvents;
}
 
Hello everybody,
I needed to modify an apex class I deployed to production before.
The problem is that the code coverage is now 45% and I don't understand why it doesn't enter if neither if nor else. 

I'm doing a callout into a future method, using HttpCalloutMock.
Main class example :
User-added imageTest class :
Test.startTest();
        Test.setMock(HttpCalloutMock.class, new AppelAPIMock());
        ExpeditionSearchDPD.updateExpe(expeditions);
Test.stopTest();
AppelAPIMock :
@isTest
global with sharing class AppelAPIMock implements HTTPCalloutMock{
    global HTTPResponse respond(HTTPRequest req){
        HttpResponse res = new HTTPResponse();
        res.setHeader('Content-Type', 'text/xml');
        res.setBody('<?xml version="1.0" encoding="utf-8"?>' +
        	'<soap12:Envelope xmlns:soap12="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">' +
        		'<soap12:Body>' + 
            		'<getShipmentTraceResponse xmlns="http://www.cargonet.software/">' + 
            			'<getShipmentTraceResult>' + 
                            '<ShippingDate>02.08.2019</ShippingDate>' + 
                            '<DeliveryDate>05.08.2019</DeliveryDate>' + 
                            '<Weight>0</Weight>' + 
                    	'</getShipmentTraceResult>' + 
                 	'</getShipmentTraceResponse>' + 
               	'</soap12:Body>' + 
            '</soap12:Envelope>');
        res.setStatusCode(200);
        return res;
    }
}
Thank you for your answers

 
Hi All,
I Have an Visual force page with some Set of List and String.
I have given those List and string While calling the Batch apex
Extension_Batch  batch = new CloneNSTExtension_Batch(List name,String name);
         batch.executeBatch(batch);
My clarification is how to take the String name inside the excute method in batch apex.Because,those string(which have value from the  normal apex class) I have added as the Condition value in query.

Please advice.

Thanks in advance
Sumitha P
I have to Auto Number fields on the Opportunity and the Quote objects. They are both running using the same format which is confusing for users. I'd like to identify the records that have matching Auto Number field values. How can I achieve this through SOQL?
Hi Everyone,
I am new with salesforce and I am still my learning phase.
I just wanted to know whether could we use VF standard stylesheet and external stylesheet such as bootstrap simultaneously? If yes, please let me know how to use??

Thanx in advance.
I am pretty new to Salesforce development and I am having a hard time wiriting a test class for some code that I am writing for a Jira to Salesforce connector. Below is my class and trigger, but I am not sure how to write a test class for a web service callout. Any help would be appreciated.

Class: 
global class JIRAWebserviceCalloutSyncStatus {
    @future (callout=true)
    WebService static void syncstatus(String status, String jiraKey) {
        //Modify these variables:
        String username = 'salesforceconnector';
        String password = 'xxxxxx';
        String jiraURL = 'https://xxxxx.xxxxxx.com';
        String transitionId;
         
        //Map Salesforce Status to JIRA transition Id:
         if (status == 'Waiting on Risk') {                  // Salesforce.com Status
            transitionId = '181';                 // JIRA transition ID
        } else if (status == 'Waiting on Customer') {
            transitionId = '21';
        } else if (status == 'Active') {
            transitionId = '161'; 
        } 
        
         
        //Construct HTTP request and response
        HttpRequest req = new HttpRequest();
        HttpResponse res = new HttpResponse();
        Http http = new Http();
 
        //Construct Authorization and Content header
        Blob headerValue = Blob.valueOf(username+':'+password);
        String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(headerValue);
        req.setHeader('Authorization', authorizationHeader);
        req.setHeader('Content-Type','application/json');
 
        //Construct Endpoint
        String endpoint = jiraURL+'/rest/api/2/issue/'+jiraKey+'/transitions';
         
        //Set Method and Endpoint and Body
        req.setMethod('POST');
        req.setEndpoint(endpoint);
        req.setBody('{ \"transition\": {\"id\": \"'+transitionId+'\"}}');
 
        try {
            //Send endpoint to JIRA
            res = http.send(req);
        } catch(System.CalloutException e) {
            System.debug(res.toString());
        }
    }
}

Trigger:
trigger SyncStatus on Case (after update) {
    //Identify profile name to be blocked from executing this trigger
    String JIRAAgentProfileName = 'JIRA Agent';
    List<Profile> p = [SELECT Id FROM Profile WHERE Name=:JIRAAgentProfileName];
     
    //Check if specified Profile Name exist or not
    if(!p.isEmpty())
    {
        //Check if current user's profile is catergorized in the blocked profile
        if(UserInfo.getProfileId()!= String.valueOf(p[0].id))
        {
            for (Case c : Trigger.new) {
                //Define parameters to be used in calling Apex Class
                String status = c.Status;
                String jiraKey = c.JIRA_Key__c;
                 
                JIRAWebserviceCalloutSyncStatus.syncstatus(status, jiraKey);
            }
        }
    }
}

Test Class:
 
@isTest
public class TestJIRAWebserviceCalloutSyncStatus {

    static testMethod void TestJIRAWebserviceCalloutSyncStatus(){
        Test.startTest();
        JIRAWebserviceCalloutSyncStatus.SyncStatus();
        Test.stopTest();
         
        
        
    }
    
    
    
}

 
After a succesful SOAP request. I am now trying to extract the <SagittaCode> value from the response body below. I am trying to use the XmlStreamReader method getAttributeValue, but not haveing much luck. 

I am getting an error of " Illegal State: Current state is not among the states START_ELEMENT , ATTRIBUTEvalid for getAttributeValue()". 

Thanks for the help! 
HTTP/1.1 200 OK
Content-Type: application/soap+xml; charset=utf-8
Content-Length: length

<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body>
    <clientInsertResponse xmlns="http://amsservices.com/">
      <clientInsertResult>
        <Success>boolean</Success>
        <SagittaId>long</SagittaId>
        <SagittaCode>string</SagittaCode>
        <Errors>
          <Errors>
            <Code>int</Code>
            <Message>string</Message>
          </Errors>
          <Errors>
            <Code>int</Code>
            <Message>string</Message>
          </Errors>
        </Errors>
      </clientInsertResult>
    </clientInsertResponse>
  </soap12:Body>
</soap12:Envelope>

 

I want to add a new filter condition to a report when I visit it via a custom link.  I know how to get the field ID for a custom object's fields.  I know how to get the field IDs for standard objects.  How do I get the ID for a custom object's standard fields?  Specifically, I want to use the Name field of an object as the field to filter on.

 

So far, my added filter condition hasn't even appeared when I click the link.  I suspect this is because I've failed to find the proper ID thus far.  I am filling in parameter pc4 with the ID value, Of course, pn4, and pv4 are getting appropriate values too.

Hello,

 

I found a previous post referencing this but cannot seem to get it to work in my org.  I am already using an Extension on this page to reference users information from names in a picklist.  I have tried to put two extensions, such as extensions="ProjectConfirmationEXT,timeZone" but get the following error,  "Error: Unknown constructor 'timeZone.timeZone(ApexPages.StandardController controller)'"

 

Can someone help me figure out what I am doing wrong?

 

VisualForce page

 

<apex:page standardController="Job__c" extensions="ProjectConfirmationEXT" showHeader="false" renderAs="pdf">

<apex:dataTable style="font-family: Calibri, sans-serif;" id="EventTable" value="{!Job__c.Events}" var="e" width="100%" rowClasses="odd,even" styleClass="tableClass" cellpadding="4" border="1">     
        
        <apex:column headerValue="Date">
            <apex:outputField value="{0,date,MM/dd/yyyy}">
                <apex:param value="{!e.StartDateTime}" />
            </apex:outputField>
        </apex:column>
        <apex:column headerValue="Start Time">
            <apex:outputText value="{0,time,HH:MM}">
                <apex:param value="{!e.StartDateTime}" />
            </apex:outputText>
        </apex:column>
        <apex:column headerValue="End Time">
            <apex:outputText value="{0,time,HH:MM}">
                <apex:param value="{!e.EndDateTime}" />
            </apex:outputText>
        </apex:column>
        
    </apex:dataTable>

 

timeZone EXT

 

public class timeZone {
        public String dateTimeValue { get; set; }
        public timeZone() {
            dateTimeValue = System.Now().format('MM/dd/yy HH:mm a', 'PST');//GMT
        }
}

 

 

 

 

 

I'm attempting to add my company logo to a visual force page, which is then being rendered as a pdf, but have not been successful.  I've attempted to do so in three ways:

 

Image is on a website:

<apex:image url="http://www.tsysacquiring.com/graphics/logos/tsysacquiring_top_logo.gif" width="220" height="55"/>

 

Image has been loaded into Salesforce into documents, and is in the /alva/ folder:
<apex:image value="/alva/TSYS_logo_for_TSYS_Sales_App.jpg" width="220" height="55"/>

 

Image is on my C:\drive:

<apex:image value="C:\data\TSYS_Logo_for_TSYS_Sales_App.jpg" width="220" height="55"/>

 

All three attempts have resulted in a broken image icon being displayed.  This seems like a very straightforward thing I'm attempting, and I'd expect it to be rather simple.  Any one have a syntax example that they know works.

 

Thanks!

 

Hey Guys,

 

Looking for a way to restrict a trigger when a specific opportunity record type isn't selected.

 

My Code:

 

 

 

trigger Opportunity on Opportunity (after insert) {

List<OpportunityLineItem> blineItems = new List<OpportunityLineItem>();

 

for(Opportunity o : trigger.new){

string a;

string b = o.Product2__c;

String c = o.RecordTypeId;

 

if(c == '012T00000000LSb') {

if(b == 'VOIP') {a = '01uT0000000zxBPIAY';}

else if(b == 'Radio') {a = '01uT0000000zxC9IAI';}

else {a = '01uT0000000zxC2IAI';}

 

blineItems.add(new OpportunityLineItem(quantity = o.Product_Quantity__c,

UnitPrice = o.Product_Price__c,

OpportunityId = o.Id,

pricebookentryid = a

));

}

}

insert blineItems;}

 

  And maybe there's a more efficient way to use Case for PriceBookEntryId's: VOIP, Radio etc...

 

Thanks in advance! 

 

Hello,

 

I'm using the Apex Data Loader (17.0) to load the account table.  I have Sys Admin privilege.  I can't seem to update the OwnerID field though the data loader to an owner other than myself.  No matter what I do, Salesforce sets my ID as the ownerID.  I can change it just fine interactively through the wizard to whatever I want, but I can't seem to do it from inside of the Apex Data Loader.  The OwnerID value I am using in the Data Loader is the ID field that goes with the user I want.  Anyone have any suggestions?

 

Gloria Lee

  • January 23, 2010
  • Like
  • 0

Hi,

I'm trying to extend the filter criteria in this code to show only records whose date field (workshop_date__c) are either today or in the future.

Any ideas on how I edit this code to do that?

listClass = [Select Id, Name, Contact__c,Contact__r.Name, Product2__c,Product2__r.Name, Workshop_Date__c From SFDC_Class__c Where Product2__r.Name = 'Austin CEU Workshop' Limit 1000];

 


Just to be clear.. this is the code from a custom controller used for a visualforce page displayed publicly with sites.  

Thanks for helping out a newb.

Hi .. I'm getting Max SOQL queries errors (Too many SOQL queries: 21) from my triggers.

My trigger is this:

trigger trgAccountCalculations on Account (before delete) {
if (trigger.isBefore && trigger.isDelete) {
for (Account a : [Select Id, Name,
(Select Id From Billings__r LIMIT 1)
From Account Where ID IN: trigger.old])
{
if (a.Billings__r.size() > 0)
trigger.oldMap.get(a.Id).addError('ERROR : Cannot delete this Account.');
}
}
}

 

How do u guys see this trigger to be broken with Governor Limit? I don't think I can bulkify it more :-( ...

 

  • January 12, 2010
  • Like
  • 0

I am trying to integrate NetDocuments with Salesforce. Specifically, I am trying to pass a CSV formatted string to NetDocuments which will grant certain permissions on NetDocuments. The code with an issue is below:

public String createProjectAndSecurity(String sessionId) {
	String resultStatus;
	HttpRequest externalRequest = new HttpRequest();
	externalRequest.setMethod('POST');
	externalRequest.setEndpoint('https://vault.netvoyage.com/ndApi/storage.asmx');
	externalRequest.setHeader('Content-Type', 'text/xml; charset=utf-8');
	externalRequest.setHeader('SOAPAction', 'http://netdocuments.com/ndApi/UpdateLookupTable');//
	externalRequest.setHeader('Cookie', sessionId);
	String bodyString = '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">';
	bodyString += '<soap:Body>';
	bodyString += '<UpdateLookupTable xmlns="http://netdocuments.com/ndApi/">';
	bodyString += '<repository>XX-XXXXXXXX</repository>';
	bodyString += '<emailAddr>greg@interactiveties.com</emailAddr>';
	bodyString += '<completionEmail>True</completionEmail>';
	bodyString += '<updateMode>add</updateMode>';
	bodyString += '<tableData>Project, Project Type, Project Closed, Project Access, Project Hold\nTESTING - 001,,,XYZ Company|VES,</tableData>';
	bodyString += '</UpdateLookupTable>';
	bodyString += '</soap:Body>';
	bodyString += '</soap:Envelope>';
	externalRequest.setBody(bodyString);
	Http http = new Http();
	try {
		HTTPResponse externalResponse = http.send(externalRequest);
		resultStatus = externalResponse.getStatus();
	} catch(System.CalloutException e) {
		//Exception handling goes here....
	}
	return resultStatus;
}

 

I keep receiving an internal server error response from NetDocuments. I am able to login to NetDocuments and get a session variable, which is what gets passed to this class and used in the request. I think the problem is with the value being passed in the tableData portion of the request but I am not sure. This tableData value should be a CSV formatted string.

 

Does anyone have any ideas?

-greg

  • September 27, 2012
  • Like
  • 0

While trying to deploy code using Ant I receive the error "...not available for deploy for this organization." So I tried to deploy my code using Eclipse but the Classes I want to deploy are not showing up as being able to deploy. Does anyone know what is causing this problem or how to fix it?

-greg

  • October 04, 2010
  • Like
  • 0

We have a trigger on Task that has been working fine for over a year. Recently, an admin tried to add a number of recurring Tasks via the data loader and received the error message "UNSUPPORTED_APEX_TRIGGER_OPERATION:Apex Task trigger cannot handle batch operations on recurring tasks."

 

I thought I could update the trigger to check for recurring tasks but that still doesn't resolve the problem. Has anyone come across this error and, if so, how did you resolve it?

-greg

  • January 13, 2010
  • Like
  • 0

I wrote a trigger to fire on the Account object after the record is updated. At a high level I want the trigger to reassign Contacts and Opportunities to the new Account Owner but only when a specific User makes the update.

 

Upon testing in the user interface, I found that the trigger fires when a User reassigns an Account using the "[Change]" link on the Account detail page even when the User is not the one specified in the trigger.

 

Am I missing something about how an Account trigger works regarding OwnerId updates?

-greg

  • December 08, 2009
  • Like
  • 0

I am looking to move an old AppExchange product from its current technology (sControl/AJAX toolkit) to Visualforce.  The high level business requirement is to have the product function and look exactly as it does today.  Please use this link to access an org where the product is installed and functioning so that you can research my request and provide an adequate estimate.  Interested parties can contact me by phone (303) 317-2235 or email sales@interactiveties.com.
-greg

  • August 05, 2009
  • Like
  • 0

I have an existing Visualforce page with a custom controller. When the code was originally written all of the data for display on the VF page was available via relationships and it was simple to gather in a single query. Business requirements have now changed and I need to get data from another object based on results from the original query. How do I combine two different query results into a single List?

 

My over-simplified, original code is below:

--- Visualforce Page --- <apex:page controller="cController"> <apex:pageBlockTable value="{!Data}" var="d"> <apex:column>{!d.Field_1__c}</apex:column> <apex:column>{!d.Field_2__c}</apex:column> </apex:pageBlockTable> </apex:page> --- Custom Controller --- public class cController { public Custom__c[] co = new List<Custom__c>(); public cController() { try { co = [SELECT Account__c, Field_1__c, Field_2__c FROM Custom__c]; } catch (Exception e) { //System.Debug('Exception: '+e); } } public Custom__c[] getData() { return co; } }

For lack of a better way to explain what I would like to do - here is some incorrect code:

 

public class cController { public sObject[] co = new List<sObject>(); public cController() { try { for (Custom__c temp : [SELECT Account__c, Field_1__c, Field_2__c FROM Custom__c]) { Contact cont = [SELECT Name FROM Contact WHERE AccountId = :temp.Account__c LIMIT 1]; co.add(temp, cont); } } catch (Exception e) { //System.Debug('Exception: '+e); } } public sObject[] getData() { return co; } }

 

Basically, I simply want the controller to pass back data from more than one object so I can display it together on the page. I thought I could use the generic sObject but that is proving difficult and I am not familiar with nested Lists (if that is even an option).

 

Any assistance would be greatly appreciated,

-greg

  • March 20, 2009
  • Like
  • 0

I have been looking through documentation but haven't found an answer yet. If an org is maxed out on custom objects and they would like to install a package, which includes two objects, would the installation error out or would the installation be permitted?

-greg

  • February 20, 2009
  • Like
  • 0

I have a visualforce page that uses a custom component. I want the component's controller to be aware of a variable that should be used in the the WHERE clause of the controller's query. My code is below:

<!-- visualforce page -->
<apex:page controller="pageController" standardStylesheets="true" tabStyle="SObject__c">
<apex:repeat value="{!categories}" var="c">
<c:customComponent cName="{!c.Name}" cRef="{!c.Id}"></c:customComponent>
</apex:repeat>
</apex:page>

<!-- custom component -->
<apex:component controller="componentController">
<apex:attribute name="cName" description="desc..." type="String" required="true"></apex:attribute>
<apex:attribute name="cRef" description="String to use for controller class." type="String" required="true" assignTo="{!value}"></apex:attribute>

<div class="customStyle">
<apex:dataTable id="linkList" value="{!links}" var="link">
<apex:column>
<apex:facet name="header">Field 1</apex:facet>
<apex:outputText value="{!link.Field_1__c}"></apex:outputText>
</apex:column>
<apex:column>
<apex:facet name="header">Field 2</apex:facet>
<apex:outputText value="{!link.Field_2__c}"></apex:outputText>
</apex:column>
</apex:dataTable>
</div>
</apex:component>

<!-- component controller -->
public with sharing class componentController {
public SObject__c[] links = new List<SObject__c>();
String value;

public String getValue() {
return value;
}

public void setValue(String s) {
value = s;
}

public componentController() {
try {
links = Database.query('SELECT Field_1__c, Field_2__c FROM SObject__c WHERE Field_3__c=:value');
} catch (Exception e) {
System.Debug('Exception: '+e);
}
}

public SObject__c[] getLinks() {
return links;
}
}

Basically, the "cRef" attribute from the component does get assigned to the "value" variable in the componentController but "value" is actually NULL when the query inside the componentController is executed.

 

Can anyone point out what my code is missing in order to use the "value" from the component in the query?

 

Any help is greatly appreciated,
-greg

  • February 20, 2009
  • Like
  • 0
I currently use a Home Page Component to display an sControl inside the salesforce sidebar. In my sControl I use a function to resize the IFRAME, which houses the sControl, after the sControl is loaded. In an effort to move away from using sControls, I have built a Visualforce page to replace my sControl but I get an error when I try to run the JavaScript function to resize the IFRAME. The error is "Permission denied to get property Window.document."
 
Can anyone tell me how to resolve this error or another way to resize the IFRAME in the sidebar where the Visualforce page is located? Or if there is another way to include a Visualforce page into the sidebar where the sidebar will resize correctly based on the content inside the Visualforce page
-greg
  • February 06, 2009
  • Like
  • 0
We wrote a trigger on Account to update child records when the NoOfEmployees value is updated by a user.  The trigger is currently running and works as desired in our production org (na2 & still on winter release).  When our Sandbox was upgraded to Summer 08 we went in to look through the functionality, in general, and found that this same trigger is not working the same way.
 
In both orgs the trigger fires and updates the related records. In na2 any account record changes are saved but in tapp0 the account changes are not saved - the values return to the pre-update values.
Code:
trigger PushEmployees2AccountProductLine on Account (before update) {
 Map<Id, Account> acctsWithNewEmplCnt = new Map<Id, Account>();
 for (Integer i = 0; i < Trigger.new.size(); i++) {
  if(Trigger.old[i].NumberOfEmployees != Trigger.new[i].NumberOfEmployees){
   acctsWithNewEmplCnt.put(Trigger.old[i].id, Trigger.new[i]);
  }
 }
 List<Account_Product_Line__c> updatedAPL = new List<Account_Product_Line__c>();
 for (Account_Product_Line__c apl : [SELECT id, Account__c, Employees_Here__c FROM Account_Product_Line__c WHERE account__c in :acctsWithNewEmplCnt.keySet()]) {
  Account parentAccount = acctsWithNewEmplCnt.get(apl.account__c);
  apl.Employees_Here__c = parentAccount.NumberOfEmployees;
  updatedAPL.add(apl);
 }
 update updatedAPL;
}

I am not sure if the problem is in the trigger we wrote or if there is a possible bug in the summer release.  Does anyone have any ideas?
-greg
I wrote a trigger to check if certain fields contain credit card numbers when they are saved.  If I find a credit card I will eliminate the digits from the first portion of the string and replace with a sequence of star characters (************0000).  The code works fine in all test cases except when the credit card is entered with spaces between the digits (ie 0000 0000 0000 0000).  I'm thinking that the only way to address this test case is with the Pattern & Matcher methods.  However, I am not having any luck matching possible patterns within my code.
 
Does anyone have a pattern for checking credit card numbers that they would be willing to post here?  I would greatly appreciate the assistance.
-greg
I may be overlooking something here and am hoping someone can point me in the correct direction.  I am building a class which will eventually be called from an sControl.  I basically want to summarize opportunity data in the class and return that summarized data to my sControl where I can control the display/format of it.
 
I am just getting started with my class and am already encountering an exception with the number of query rows.  My Class is below (and I know that I do not have the summary organization done yet):
Code:
global class getOppSummary2 {
 webService static Opportunity[] getOpps(String regionVal, Date startDate, Date endDate, Date lastNinetyDays) {
  Map<Id, User> allUsers = new Map<Id, User>();
  for (User[] usrArray : [SELECT Id FROM User WHERE Reporting_Region__c = :regionVal AND IsActive = true]) {
   for (Integer a = 0; a < usrArray.size(); a++) {
    allUsers.put(usrArray[a].id,usrArray[a]);
   }
  }
  Opportunity[] allOpps = new Opportunity[]{};
  for (Opportunity oppArray : [SELECT AccountId,Account.Name,Amount,CloseDate,CreatedById,CreatedBy.Username,First_Appointment_Date__c,Id,MFTC_DUNS_Number__c,Name,OwnerId,Owner.FirstName,Owner.LastName,RecordTypeId,Revenue_Type__c,StageName FROM Opportunity WHERE OwnerId in :allUsers.keySet() AND ((IsClosed=false AND CloseDate < :startDate AND StageName<>'Targeted Account (No Forecasted Sale)') OR (IsClosed=true AND (CloseDate >= :lastNinetyDays AND CloseDate <= :startDate) AND (StageName='Closed Won' OR StageName='Closed Won/Contract')) OR (IsClosed<>true AND (StageName='Targeted Account (No Forecasted Sale)' OR StageName='Fallback Opportunity')) OR (IsClosed<>true AND (CloseDate >= :startDate AND CloseDate <= :endDate) AND (StageName='First Time Visit Completed' OR StageName='Proposal/Pricing Presented' OR StageName='Verbal Agreement' OR StageName='First Order')))]) {
   allOpps.add(oppArray);
  }
  return allOpps;
 }
 static testMethod void getOppSummaryTest() {
  getOpps('West',Date.newInstance(2008,03,12),Date.newInstance(2008,06,12),Date.newInstance(2007,12,31));
 }
}

My question is why am I encountering this exception?  Am I not looping through the map correctly?  I have over 4,000 users and way more opportunities to churn through which is why I want to do this in a class.
 
Thanks for any assistance,
-greg
  • March 12, 2008
  • Like
  • 0
I created an Apex trigger in Sandbox.  I am now trying to deploy the Trigger using the Force.com IDE for Eclipse.  When I get to the step where I "Validate Deployment" it results in a failure.
Deployment Log:
*** Deployment Log ***
Result: FAILED

...

# Deploy Results:
 Name: unpackaged/package.xml
 Action: NO ACTION
 Result: FAILED
 Problem: Invalid version specified:12.0

Does anyone know why this is happening?  Could it be because our Sandbox was already upgraded to the Spring 08 (API version 12.0) release and our production instance wasn't yet (still API version 11.1)?
-greg
  • January 30, 2008
  • Like
  • 0
I created a tab override which displays an sControl.  The sControl simply displays records for informational purposes.  However, the override gives an insufficient privileges error when a user with a read-only profile accesses the tab.  The user already has access to the records being displayed in the sControl so the issue is truly the tab override on the object.
 
According to the salesforce.com support team this is not a bug - I disagree.  Can anyone help me understand why this is not a bug?
-greg
  • December 13, 2007
  • Like
  • 0
I've read on posts in the discussion boards and in the force.com cookbook that Apex code should be created in a Developer Edition account and then it can be moved to a production account (Enterprise, etc).  I've created a simple sControl and Apex Class in a DE account and I am unable to move it to a production (EE) account.
 
I've tried to create a copy of the Class using Eclipse and although it looks like the class gets copied to EE it does not.  So I tried creating a package for the AppExchange to move my sControl and Apex Class but I cannot add the Class to the package and it doesn't get picked as a dependent when I add the sControl to the package.
 
Can anyone provide some clarity on what I can do to get this code from DE to EE?
-greg
  • October 03, 2007
  • Like
  • 0
I have defined a tab for a custom object and this tab uses an icon from a documents folder.  It is a png file.
 
When I set the tabStyle in my visualForce page, however, the icon is not displayed.  I have already verified that the image is set to externally available but is there something not properly setup in my page declaration?
 
Code:
<apex:page tabStyle="Custom__c">

When I use "Contact" or "Account" the icon for those objects gets displayed.
 
Any thoughts?
-greg
  • September 21, 2007
  • Like
  • 0
I need to check the status code of a remote URL prior to allowing a POST.  Since this POST would be to a domain other than salesforce, I believe I need to use the remoteFunction() call in the AJAX toolkit.  I've set this up using the proxy proxy settings but cannot seem to figure out how to get only the "status code" piece of the response.
 
Code:
function getResponse() {
 sforce.connection.remoteFunction({
  url : "http://remote.location.com/specific/page",
  method : "GET",
  mimeType : "text/xml",
  onSuccess : function(response) {
   document.getElementById("responseTXT").innerHTML = "<div style=\"font-weight: bold; color: #FF0000;\">SUCCESS!!!!</div><div>"+response+"</div>";
  },
  onFailure : function(response) {
   document.getElementById("responseTXT").innerHTML = "<div style=\"font-weight: bold; color: #FF0000;\">Failed:</div><div>"+response+"</div>";
  }
 });
}

If you look at my function from above, you can see that I can get back "response" and when it does return it literally displays the content of the remote URL in the sControl.  But I was hoping I'd be able to get back something like "response.status" or "response.statusCode" and simply use that code to determine if I should allow for the POST later in the sControl.
 
Any help is appreciated,
-greg
  • August 09, 2007
  • Like
  • 0
I have an sControl where I need to filter down all the roles rolling up to a person in the role hierarchy in a very large org.  After I filter down the valid roles of people rolling up to the user, I then want to look at the profiles of each of those people to exclude some specific profiles from the sControl details.
 
I am encountering a problem with the sControl when I query the profileid from the user object.  Since the query is running for the user and not me (as an admin), I am seeing errors.  The faultstring I am receiving is that the field profileid is not valid for user.
 
I think this is a bug because all users have access to user records.  Does anyone know of an easy work-around for me to get profileid for an array of users?
-greg
  • March 27, 2007
  • Like
  • 0
I am trying to create an scontrol to list all profiles that have a certain opportunity recordtype associated to them.  Does anyone know where I can look or what I can do to get this association?
-greg
  • February 20, 2007
  • Like
  • 0
I need to create an array of translated picklist values for the Opportunity StageName field.  The only documentation I can find related to translations is to use the toLabel() function when querying.  Isn't there a way to get the translations through the meta data?  Thanks in advance for any assistance.
-greg
  • February 15, 2007
  • Like
  • 0
Trigger UpdateParentAcct_OldOrg on Account ( after update) {
    
 // the line below fails;
Account a;

     
}
Hi,

I have a simple trigger and test class where I need some help to get from the 62% coverage and up to at least 90%.  The lines which are not covered are the ones after the 'IF' statement. 

Can someone please help me with the remaining test class code?

The trigger is as follows:

trigger contactCreateCommunityUser on Contact (before insert) {
    String currentuser = UserInfo.getUserId();
    String emailAddress = UserInfo.getUserEmail();
    
    ID contactId = [Select contactid from User where id =: Userinfo.getUserid()].contactId;
    List <User> systemAdm = [SELECT Id
                               FROM User
                              WHERE Name like '%Systemadministrator%'];
    system.debug('Systemadmin ID ' + systemAdm);
    If(contactId != null) {
        ID AccID = [Select AccountID from Contact where id =: contactid].AccountId;
        for(Contact con : trigger.new){
            con.OwnerId = systemAdm.get(0).Id;
        }
    }
}


Test class:
@isTest
private class contactCreateCommunityUserTest {       
    static testmethod void contactCreateCommunity() {
        Account acc = [SELECT Id
                        FROM  Account
                        Limit 1];
        
        Contact con = new contact();
        con.lastName = 'TestLastName';
        con.AccountId = acc.Id;
        Insert con;
    }
}
Good afternoon, folks.

I'm in the process of trying to consolidate the SOQL calls within a trigger of a particularly difficult sObject.  This sObject has enough code running on it that we're pretty regularly hitting the 101 error--so it's time to clean up and bulkify where possible.

I've run the following to fill a map with an sobject, and the children of that sobject.  Let's assume for the moment that Service_Order_Line is a child of Service_Order with a many-to-one relationship, and I've filtered this down so I'm only getting one Service_Order and maybe 5 or 10 Service_Order_Lines:

map<ID, Service_Order__c> testResults = new map<ID, Service_Order__c>([select ID, Name, (select ID, Name from Service_Order_Line__r) from Service_Order__c']);

Further down in the trigger, I'll need to reference the child objects, but I can't seem to find a syntax to make it work.  How would I write the following to loop through the children of testResults?

for(Service_Order_Line childrenOfTestResults : testResults.Service_Order_Line__r) {
    system.debug(childrenOfTestResults.Name);
}
Do Apex Callouts (Call from Apex to External Rest/SOAP services) count against Org API Limits. 
I know they are limited by Governor limits but do they count against the org API Limits.
The salesforce documentation is not very clear and not sure how to get official confirmation from Salesforce on this.


http://resources.docs.salesforce.com/200/9/en-us/sfdc/pdf/salesforce_app_limits_cheatsheet.pdf. Page 41 of the document (page 37 based on Numbering in the document) clearly says Apex callouts are excluded.

But the latest document link does not have such Note
https://resources.docs.salesforce.com/222/latest/en-us/sfdc/pdf/salesforce_app_limits_cheatsheet.pdf (No Note at Page 9)
I want to delete the Error_Log__c in production.  However, my "deactivated" trigger still has a handle as follows,

trigger UpdateErrorLog on Error_Log__c (before insert) {...}

Again the above trigger was deactivated thru change set but I cannot delete the Error_Log__C.  I submitted a case to Salesforce and directed me to here.   How can I dereference Error_Log__c from UpdateErrorLog trigger?
Hello,

I exeucte a postman request to get the token.

I was writing a code for authenticating the API in slaesforce, but found that the headers are not correct.

I tried to get the headers by other way.

User-added image

How can i write the code for first part of the screen shot,  ?
  • September 23, 2019
  • Like
  • 0
I had a simple question. I want to check if an email entered in the form is the right format. How do you splice in apex? In other words I want to see that after the @ symbol, we only have gmail.com. I was going to write something like 
if(email__c.contains('@gmail.com'){} but then I realized that this may not be enough because someone could potentially enter an email of gmail.com@hotmail.com for example. So I want to see what I can write in apex to check if the email is in the format ###@gmail.com
Thank you

Hello,

I am trying to create new authetication through my application and I am getting {"error":"invalid_grant","error_description":"authentication failure"} error when trying to call the Token Request: "https://eu5.salesforce.com/services/oauth2/token"

Can u help me out why I'm getting this error ?
Best Regards , 
Raneen Khoury

I'm trying to use two soql queries to grab the relevant information for an email class, but it is failing when it tries to run the second query when running the test class. I'm actively stumped as to why it's not finding the created product. I'm not super experienced and mostly cut/paste things for apex, so I'm sure there's something goofed along the way. Code below:
Class:

global class EmailPTRAttWearplates implements Messaging.InboundEmailHandler {
	  global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
		  Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
          
          Production_Tracking_Record__c ptr;
          Product2 prod;
          
           ptr = 
              [select id, Product__c from Production_Tracking_Record__c
              where Name = :email.subject];
          
           prod =
              [select Wearplate__c, Wearplate_Thickness__c, Pre_Order_Wearplates__c from Product2
              where Name = :ptr.Product__c];
          
          if(prod.Pre_Order_Wearplates__c=false)
          {
           PTR_Attachment__c Att = new PTR_Attachment__c(Name=email.subject,
                                                         PTR__c=ptr.Id,
                                                         Component__c='Wearplate',
                                                         Quantity__c=2,
                                                         Thickness__c=prod.Wearplate_Thickness__c,
                                                         Material__c=prod.Wearplate__c,
                                                         Directory_Link_Text__c='R:\\Parts Orders\\Internal Laser Parts');
          insert Att;
          }
       return result;
      }
}



Test Class:

@IsTest
public class EmailPTRAttWearplates_Test {
 public static list<Production_Tracking_Record__c> PTRlist;
    static testMethod void myTest() {
   		Messaging.InboundEmail email  = new Messaging.InboundEmail();
        Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
    
    		email.fromAddress = 'test@test.com';
    		email.subject = '12345';
   
    Test.startTest();
    
        
        Account acct = new Account(Name='Test Account',
                                   Type='Direct Customer',
                                   Shipping__c='Prepaid',
                                   Ship_Via__c='UTS',
                                   Sales_Discount__c=0);
        insert acct;
        
        Product2 prod = new Product2(Name='Test Product',
                                     Rotor_Configuration__c='Closed Adjustable',
                                     Inboard_or_Outboard__c='Outboard',
                                     Endcap_Face_Preparation__c='Wearplate',
                                     Wearplate__c='Mild Steel',
                                     Wearplate_Thickness__c='.375',
                                     Pre_Order_Wearplates__c=false,
                                     Vane_Thickness__c='.375',
                                     Vane_Material__c='AR500',
                                     Shroud_Mat__c='Mild Steel',
                                     Shroud_Thickness__c='.375',
                                     Adjustable_Blade_Thickness__c='0.3125',
                                     Blade_Mat__c='Mild Steel');
        insert prod;
        
        Opportunity opp = new Opportunity(Name='12345',
                                          RA__c='12345',
                                          StageName='Quote Sent',
                                          CloseDate=System.today(),
                                          AccountId=acct.Id,
                                          Make__c='Kice',
                                          Model__c='VJ 14x10x10',
                                          Product__c=prod.Id,
                                          Max_Temp__c='120',
                                          Serial__c='N/A',
                                          Cold_Clr_Radial__c='.004-.007',
                                          Cold_Clr_Side__c='.004-.007');
        
        insert opp;
    		
        Production_Tracking_Record__c ptr = new Production_Tracking_Record__c(Name = '12345',
        																	  RA__c = opp.Id,
            																  Product__c = prod.Id);
        insert ptr; 
        
        EmailPTRAttWearplates paw = new EmailPTRAttWearplates();
        
        Messaging.InboundEmailResult result = paw.handleInboundEmail(email, env);
        
    Test.stopTest();
    
        System.assert (result.success, 'InboundEmailResult returned a failure message');
    
    }
}

 
Having a problem getting a salesforce access token. Getting the access token works fine in postman, but what I'm trying to do it in C# i'm getting an error.
I've tried to doing the equivlent to what I was doing in postman but I'm not sure if getting this right.
 
var client = new HttpClient();
        string baseAddress = @"https://test.salesforce.com/services/oauth2/token";

        string grant_type = "authorization_code";
        string client_id = "client_id here";
        string client_secret = "client_secret here";
        string auth_url = "https://test.salesforce.com/services/oauth2/authorize";
        string callback_url = "https://app.getpostman.com/oauth2/callback";
        string redirect_uri = "https://app.getpostman.com/oauth2/callback";

        var form = new Dictionary<string, string>
            {
                {"grant_type", grant_type},
                {"client_id", client_id},
                {"client_secret", client_secret},
                {"auth_url", auth_url},
                {"callback_url", callback_url},
                {"redirect_uri", redirect_uri}
            };

        HttpResponseMessage tokenResponse =  client.PostAsync(baseAddress, new FormUrlEncodedContent(form)).GetAwaiter().GetResult();
        var jsonContent =  tokenResponse.Content.ReadAsStringAsync().GetAwaiter().GetResult();



This is the error I'm getting:
{ 
"error": "invalid_grant", 
"error_description":"invalid authorization code" 
}

 

I discovered geocodes could be added to Accounts without needing code but for the sake of learning, could someone provide a newbie with constructive feedback on this trigger? I'd really like to figure this out.

I have two sales reps splitting California for their sales territory. One owns anything above Santa Barbara and one owns everything else. I created a custom object labeled 'Cities' with fields for City__c and Latitude__c, and imported this data for all California cities.

Whenever an Account is created or updated, I want my trigger to query the custom object 'Cities', match the Account BillingCity to the City__c field on my custom object, and evaluate if the corresponding Latitude__c field on my custom object is greater than Santa Barbara's latitude.  

If the latitude is greater than Santa Barbara's, add the Account to a list which will be updated with the Northern Sales Rep as the Owner. If the latitude is not greater than Santa Barbara's, add the Account to a list which will be updated with the Southern Sales Rep as the Owner.

When I test the trigger, I get the dreaded "System.NullPointerException: Attempt to de-reference a null object ()" error which confuses me because I check to see if BillingCity is null and confirmed I have all California cities and latitudes imported into my custom object. I have a feeling the error is somewhere around line 13 where I query my custom object and try to find the corresponding latitude...

Thanks to anyone for taking the time to help me learn! 

Here is my trigger:

trigger CaliSalesTerritory on Account (before insert, before update) {

    List <Account> caliAccts; // A List to hold all California Accounts
    List <Account> norCalCities; // A List to hold all Northern California Accounts
    List <Account> soCalCities; // A List to hold all Southern California Accounts
    
    for (Account acct : Trigger.new) { 
        if (acct.BillingState == 'California' && acct.BillingCity != null) {
            caliAccts.add(acct); 
// For all Accounts being inserted or updated, if the BillingState is "California" and the BillingCity isn't null, add the Account to the caliAccts list    
        }
    } 
   
    for (Account acct2 : caliAccts) {
        Cities__c caliLatitude = [Select Latitude__c FROM Cities__c WHERE City__c = :acct2.BillingCity]; 
 // For all Accounts in the caliAccts list, query the Cities__c object and return the Latitude based on the Account's BillingCity
       
    if (caliLatitude.Latitude__c > 34.4285) {
           norCalCities.add(acct2);
// If the Latitude is greater than Santa Barbara's latitude, add the Account to the norCalCities list            
        }    
            else {
                soCalCities.add(acct2);
// If the Latitude is not greater than Santa Barbara's latitude, add the Account to the soCalCities list                            
            }
    }
           
    for (Account northRepAcct : norCalCities) {
        northRepAcct.OwnerId = '0050f0000097wqI'; //Northern Sales Rep UserId
// Assign all Accounts in the norCalCities list to the Northern Sales Rep
    }  
    update norCalCities;
    
    for (Account southRepAcct : soCalCities) {
        southRepAcct.OwnerId = '0050f000009K2kr'; //Souther Sales Rep UserId
// Assign all Accounts in the soCalCities list to Southern Sales Rep        
    } 
    update soCalCities;
}
Hi Guys,
can anyone pls suggest how to get a certain value from nested list<map's>
 List<Map<String,Object>> newl =  new List<Map<String,Object>>();
                         for(Object itrObj : l){
                             newl.add((Map<String, Object>)itrObj); // got all records here
//how to get certain values from the collection
                             
                             system.debug('id val==>'+ newl);
                         }
               
Hi all,

I would really need your help. :(

I need to generate for my organization a PDF document (Order Insertion for our advertising campaigns). I would need to add different fields that the SF users could fill in, like: Campaign Name: xxxx , Campaign Start Date: xx/xxx/xxxx, Price: xx/CPM, etc.

Also, I need to add a header (picture- logo of the company) and a footer (contact, signature, etc).

Basically, I have the Order Insertion in a .xlsx format and I would like to transfer all the info from the Excel in Salesforce. As I understood, it could work with VisualPage creation and customization but I think I need some programmatic help.

Thank you very much for your answer,
Otilia

I'm new to developing and trying to determine if I will get errors thrown in my batch apex code. The purpose is to: upon deactivation of a user (trigger, which I understand isn't best practice but don't know another way the batch can be automatically started w/o checking for deactivated users every night), all of the leads of deactivated user are queried to change the OwnerId to a catchall user. The trick is that one user may have as many as 200,000 leads that need to be updated, hence why I am using batch apex. Two questions:

1. How many batch jobs will be activated with each deactivated user? (I think the answer is one?)

2. Will the batch job be sent to the Flex Queue as 'holding' and then to active, giving the org 105 possible batch jobs to be held/processed at once before throwing errors, or will it bypass Flex Queue, thereby limiting the org to only 5 batch jobs at a time?

I hope my questions make sense, and I appreciate any help. I have spent many hours researching this as a newbie. In case it's relevant, my code is below:

Trigger:

trigger BatchUpdateTrigger2 on User (after update)  {

//Map will keep deactivated users and their Id's, to be used later in batch Apex
	 Map<id, User> DeactivatedUsers = new Map<id, User>();
//Check all users in trigger, first if the IsActive button has been newly changed and if it now says that the user is not active    
for (Integer i=0;i<Trigger.new.size();i++) {
    
if (Trigger.new[i].IsActive!=Trigger.old[i].IsActive &&
   Trigger.new[i].IsActive == false) {
	DeactivatedUsers.put(Trigger.new[i].Id, Trigger.new[i]);
   }
}
// Make sure that there are users to be processed
if (DeactivatedUsers.size() > 0) {

            BatchUpdateLeads objBatchUpdateLeads=new BatchUpdateLeads(DeactivatedUsers);
            Database.executeBatch(objBatchUpdateLeads);
}
}


Batch Apex Class:

global class BatchUpdateLeads implements Database.Batchable<SObject> {
   
        //Save a public variable to hard-code the catchall user that will become lead owner
  	public Id GenericUserId = '0054P000009pLkrQAE';
    
    //map of userid - user that retrieves deactivated user(s) from previous trigger
    Map<Id, User> DeactivatedUsersMap = new Map<Id, User>();
    
    global BatchUpdateLeads(Map<Id, User> DeactivatedUsers) {
    DeactivatedUsersMap = DeactivatedUsers;
    }
    
//Search for the leads whose OwnerId is the deactivated user(s)
    global Database.QueryLocator start(Database.BatchableContext BC) {
    return DataBase.getQueryLocator([SELECT Id, OwnerId FROM Lead WHERE OwnerId IN : DeactivatedUsersMap.keySet()]);
    }
    
    //For leads whose owner was deactivated, change OwnerId to the catchall user
    global void execute(Database.BatchableContext BC, List<sObject> scope){
              List<Lead> leads = (List<lead>)scope;
                for (Lead l: leads){
                    l.OwnerId = GenericUserId;}
        
//Check that there are leads to be updated, then update
            if (leads.size() > 0){
              update leads;
            }
    	}
    global void finish(Database.BatchableContext BC) {
        
    //Send an email to system admin after the batch completes (fill in email)
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    String[] toAddresses = new String[] {'xxxxxxx@gmail.com'};
    mail.setToAddresses(toAddresses);
    mail.setSubject('Apex Batch Job is done');
    mail.setPlainTextBody('The Batch Apex Job Processed Successfully');
    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}
I am trying to update a custom event field, sales_within_1_year__c, when a custom contact field, sales__c, changes. For example:

Event 1: tied to Contact A & Contact B; sales_within_1_year = $0
Event 2: tied to Contact A & Contact C; sales_within_1_year = $10

Contact A sales changes from $100 to $200.
Event 1: new sales_within_1_year = $100
Event 2: new sales_within_1_year = $110

If the sales for Contact B or C changed, it would only affect the event they are tied to.

I thought my trigger would work, and it does when I change a contact's sales number individually. But when I bulk update contacts, none of the sales_within_1_year numbers change. I was wondering if someone could help me through this. Thanks!

Here is my trigger:

trigger EventSales on Contact (before update) {
                //Create a list of contact IDs that have updating sales
                List<Id> contactIds = new List<Id>();
    for(Contact con : trigger.new) {
        if(Trigger.newMap.get(con.Id).Sales__c == NULL) return;
        else if(trigger.newMap.get(con.Id).Sales__c == 0) return;
        else if(trigger.oldMap.get(con.Id).Sales__c == NULL) {
            contactIds.add(con.Id);
        }
        else if(trigger.newMap.get(con.Id).Sales__c !=
                trigger.oldMap.get(con.Id).Sales__c) {
            contactIds.add(con.Id);
        }
    }
   
    //Create a list of event relations (contact-event pairs) for updating contacts
    List<EventRelation> evRel = [SELECT EventId, RelationId
                                FROM EventRelation
                                WHERE RelationId IN :contactIds];
   
    //Create a map of the updating contacts and their related events
    Map<Id, List<Id>> contactEvents          = new Map<Id, List<Id>>();
   
    //Create a list of event Ids that are going to be updated
    List<Id> eventIds = new List<Id>();
   
    //Put the contact Id and event Id in the map for events that have updating contacts
    for(EventRelation rel :evRel) {
        if(contactEvents.containsKey(rel.RelationId)) {//If the contact is already in the map
            List<Id> relatedEv = contactEvents.get(rel.RelationId);//Grab the list of events tied to the contact
            relatedEv.add(rel.EventId);//Add the new event to the list
            contactEvents.put(rel.RelationId, relatedEv);//Put the updated list into the map
        }
        else {//If the contact isn't in the map
            contactEvents.put(rel.RelationId, new List<Id>{rel.EventId});//Put the contact and event into the map
        }
        //Add the updating event to the eventIds list
        if(eventIds.contains(rel.EventId)) return;
        else eventIds.add(rel.EventId);
    }
   
    //Create a list of events that are going to be updated
    List<Event> listEventsMaker = [SELECT Id, Sales_within_1_year__c
                                   FROM Event
                                   WHERE Id IN :eventIds
                                   AND EndDateTime = LAST_N_DAYS:365];
   
    List<Event> listEvents = new List<Event>();
    for(Event ev :listEventsMaker) {
        if(listEvents.contains(ev)) return;
        else listEvents.add(ev);
    }
   
    //Keep a list of events to update
    List<Event> changedEvents = new List<Event>();
   
    //Update the sales amounts for the events
    for(Id con :contactEvents.keySet()) {//For each contact in the map
        List<Id> thisContact = new List<Id>();//Create a list of events tied to this specific contact
        Contact oldCon = trigger.oldMap.get(con); //create a record for the contact pre-update
        Contact newCon = trigger.newMap.get(con); //create a record for the contact post-update
        if(newCon.Sales__c == NULL) return;
        else if(newCon.Sales__c == 0) return;
        else if(oldCon.Sales__c == NULL) {
            for(Id event :contactEvents.get(con)) {
                thisContact.add(event);
            }
            for(Event ev :listEventsMaker) {
                if(thisContact.contains(ev.Id)) {
                    changedEvents.add(ev);
                    if(ev.Sales_within_1_Year__c == NULL) {
                        ev.Sales_within_1_Year__c = newCon.Sales__c;
                    }
                    else ev.Sales_within_1_Year__c += newCon.Sales__c;
                }
            }
        }
        else if(oldCon.Sales__c
                != newCon.Sales__c) {
            for(Id event :contactEvents.get(con)) {
                thisContact.add(event);
            }
            for(Event ev :listEventsMaker) {
                if(thisContact.contains(ev.Id)) {
                    changedEvents.add(ev);
                    if(ev.Sales_within_1_Year__c == NULL) {
                        ev.Sales_within_1_year__c = (newCon.Sales__c
                                                     - oldCon.Sales__c);
                    }
                    else ev.Sales_within_1_Year__c += (newCon.Sales__c
                                                       - oldCon.Sales__c);
                }
            }
        }
    }
    update changedEvents;
}
 
I get sent emails with data in both the bodies and as a csv attachment with contact information that I need to update.  Currently I use the dataloader or the data import wizard and manually upload the information into our Org.  From the research I have done on the forums it appears that I can write an Apex class to parse the information from both the body of the email or an attachment and update the contact records with the appropriate information.  Looking for some examples or resources to write this in Apex so that my external partners can email an address and have the data update in my organzation.  Hopefully this makes sense on this post like it does in my head.  Any information or references would be greatly appreciated.