• JA-Dev
  • NEWBIE
  • 50 Points
  • Member since 2010

  • Chatter
    Feed
  • 2
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 2
    Questions
  • 19
    Replies

I have a managed package that runs batch apex every night for those that install it.  I pushed a fix to those orgs the other evening via push upgrades.  Now 2 customers who didn't have any problems before threw exceptions.

 

It sounds like the Apex Scheduler might be having issues - is that the likely issue or is it possible there's something funky with my code?

 

Upon further review, there was another error just prior to this one:

 

Developer script exception from Oceaneering International, Inc. : 'chttrunfollow.UnfollowQueueDelayRecordsBatch' : Unable to write to any of the cursor stores in the alloted time

 

Error message:

Developer script exception from Oceaneering International, Inc. : 'chttrunfollow.UnfollowQueueDelayRecordsBatch' : Unable to write to any of the ACS stores in the alloted time.

 

I'm working on a trigger that simply populates a date/time value into a field on the account when a record of a specific record type gets created on a related custom object. The trigger is fine but the test class fails due to the line where I try to specify the record type in the test. The error I get is below.

 


System.StringException: Invalid id: DO NominationClass.AccUpdateTest.SponsorshipInsert: line 11, column 20 External entry point

 

My trigger code:

trigger AccUpdate on AE_Sponsorship__c (after insert, after update) {
//Query for the Account record types
     List<RecordType> rtypes = [Select Name, Id From RecordType 
                  where sObjectType='AE_Sponsorship__c' limit 1];
     
     //Create a map between the Record Type Name and Id for easy retrieval
     Map<String,String> accountRecordTypes = new Map<String,String>{};
     for(RecordType rt: rtypes)
        accountRecordTypes.put(rt.Name,rt.Id);

    for (AE_Sponsorship__c a: trigger.new){
            if(a.RecordTypeId==accountRecordTypes.get('DO Nomination'))
            {
            Account myAcc = [select Id from Account where ID = : a.Account__c];
        myAcc.Test_Update_from_AE_sponsorship__c = a.lastmodifiedDate;
        update myAcc;
        }
    }
}

My test class:

@isTest
private class AccUpdateTest {
    private static testmethod void SponsorshipInsert(){
    AE_Sponsorship__c sponsor1 = new AE_Sponsorship__c(
    Overall_Monthly_Volume__c=100, 
    Met_with__c='jim', 
    Expected_Flagstar_Volume__c=100, 
    Approved_for_CFL__c=TRUE, 
    Account__c = '0015000000Jo7v5',
    Date_of_Visit__c=Date.newInstance(2010, 07, 15),
    RecordTypeID = 'DO Nomination'
);
insert sponsor1;
}
}

 Can anyone help me get this final piece working please? I need to specify the record type without hard coding the record type ID, which is why the trigger has a map for record type.

 

Thank you,

Larry

 

Hi,

 

We have a batch job that updates a number of records and it could potentially throw a DML exception. I was trying to capture the ids of the records that caused an exception, but it seems that it won't return the ids. Here is a snippet of what it looks like:

 

 

Database.SaveResult[] lsr = Database.update(recordsToUpdate, false);
for (Database.SaveResult sr : lsr) {
    if (sr.isSuccess()) {
        // This gets me the ids as expected
        successRecords = successRecords + sr.getId() + ',';
    else if (!sr.isSuccess()) {
        // This does not capture the ids of the failed records
        errorRecords = errorRecords + sr.getId() + ',';
    }
}

 

Also, I saw that there is an Database.SaveResult.getErrors() function that I have not tried using yet. Would that give me the id of the failed record? I'm simply trying to capture any records that did not update, so that we can later reprocess.

 

Thanks in advance!

 

 

  • February 03, 2011
  • Like
  • 0

Hi,

 

I've seen this example that shows how to leverage the Scheduling API to set jobs to run on an hourly basis. But can I set up a Batch Apex job to run hourly as well? If so, can someone guide me through the process? I already know how to write and set up Batch Apex jobs that run daily, but need help getting them to run hourly.

 

Thanks in advance.

  • August 13, 2010
  • Like
  • 0

I have a managed package that runs batch apex every night for those that install it.  I pushed a fix to those orgs the other evening via push upgrades.  Now 2 customers who didn't have any problems before threw exceptions.

 

It sounds like the Apex Scheduler might be having issues - is that the likely issue or is it possible there's something funky with my code?

 

Upon further review, there was another error just prior to this one:

 

Developer script exception from Oceaneering International, Inc. : 'chttrunfollow.UnfollowQueueDelayRecordsBatch' : Unable to write to any of the cursor stores in the alloted time

 

Error message:

Developer script exception from Oceaneering International, Inc. : 'chttrunfollow.UnfollowQueueDelayRecordsBatch' : Unable to write to any of the ACS stores in the alloted time.

 

I'm trying to use ConnectorConfig to make Java based API calles, but the ConnectorConfig class is missing.

I have the wsc-20.jar in my path, but still no good.

 

The following imports cause errors in eclipse:

 

import com.sforce.ws.ConnectorConfig;
import com.sforce.ws.ConnectionException;

 

Any ideas?

Came across an interesting problem today where one of our bulk triggers failed due to a Too Many DML Rows limit exception.

 

We have a custom object (Order__c) with a child object (Order_Line__c).

We have a trigger on the Order to automatically create Order_Line__c records whenever a new Order is created. However, when the number of line items exceeds 100 our trigger fails BUT ONLY WHEN INVOKED VIA A STANDARD page, our unit tests work fine and if we VF the New Order page it works fine:

 

e.g.

 

 

trigger trg_ai_Order on eclone__Order__c (after insert) {
	
	List<Order_Line__c> items = new List<Order_Line__c>();
	
	for (Order__c o : trigger.new) {
		// This is just an example to demonstrate the issue
		for (Integer i=0; i<101; i++) {
			Order_Line__c oi = new Order_Line__c();
			oi.Order_No__c = o.Id;
			items.add(oi);
		}
				
	}
	
	// Insert the items
	insert items;

}

Add a new Order using the standard tab for Order gives:

 

Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger eclone.trg_ai_Order caused an unexpected exception, contact your administrator: eclone.trg_ai_Order: System.LimitException: eclone:Too many DML rows: 101

 Whereas the following anonymous apex works fine (as the limit is 10,000):

 

Order__c o = new Order__c();
insert o;

 

 

 

And creating a Visualforce page with just the standardcontroller works fine too (an easy workaround).

 

Now I can see from the Apex Developers guide there's different limits for the Trigger and Apex and thinking about it I see that the Unit Test etc have a different entry point, hence why the different limit applies, but this seems to invalidate all our bulk trigger unit tests!

 

What's everyone else's experience of this, do you revert to Asynchrous apex instead, or Visualforce your pages ?

  • January 06, 2011
  • Like
  • 0

Hey all.

I've tried to write and deploy my first batch apex trigger, btu it's causing some issues. It worked in sandbox, but of course when deployed to production everything went to crap.

 

This is the error I'm getting

 

Apex script unhandled exception by user/organization: 005400000012Tpc/00D400000009zFE

 

Failed to process batch for class 'deleteCampaignMembers' for job id '70740000003FdnJ'

 

caused by: System.DmlException: Delete failed. First exception on row 0 with id 00v4000000MqwniAAB; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, deleteCampaignMembers: execution of AfterUpdate

 

caused by: System.AsyncException: Database.executeBatch cannot be called from a batch or future method.

 

Trigger.deleteCampaignMembers: line 17, column 31: []

 

Class.deleteCampaignMembers.execute: line 22, column 3 External entry point

 

Here is my trigger

 

trigger deleteCampaignMembers on Campaign (after update)
{
    Campaign[] campaigns = Trigger.new;
    List<Id> completedCampaigns = new List<Id>();
               
    for (Campaign currentCampaign : campaigns)
    {
        if(currentCampaign.isActive == false && (currentCampaign.status == 'Project Complete' || currentCampaign.status == 'Canceled' ))
        {                   
             completedCampaigns.add(currentCampaign.id);    
        }
    }
    if(completedCampaigns.size() > 0)
    {
         for (Id cid : completedCampaigns)
         {    
            id batchinstanceid = database.executeBatch(new deleteCampaignMembers('select Id from CampaignMember where campaignId = \''+cid+'\''));
        }
    }  
}

 

 

And here is the associated class.

 

global class deleteCampaignMembers implements Database.Batchable<sObject>
{
    global final String Query;
    global deleteCampaignMembers(String q)
    {
        Query=q;
    }

    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC,List<CampaignMember> scope)
    {
        List <CampaignMember> lstAccount = new list<CampaignMember>();
        for(Sobject s : scope)
        {
            CampaignMember a = (CampaignMember)s;
            lstAccount.add(a);
        }
        Delete lstAccount;
    }

    global void finish(Database.BatchableContext BC)
    {
        //Send an email to the User after your batch completes
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {'xxxxxxxxxxx@xxxxxxxxxxx.com'};
        mail.setToAddresses(toAddresses);
        mail.setSubject('Apex Batch Job is done');
        mail.setPlainTextBody('The batch Apex job processed ');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
}

 

 

I'm really not sure what's its talking about. It's really a fairly simple trigger. If a campaign has been deactivated and the status is project complete, delete all the campaign members, then send me an email. That's it. I'm not sure what I'm doing wrong. Any tips would be much appreciated. Thank you.

 

Hi.

i had made a class test in sandbox, gives me 81%..then i deploy the class to production to run , gives me an error : Failure Message: "System.QueryException: List has no rows for assignment to SObject", Failure Stack Trace: "Class.myClass.myTest: line 6, column 21 External entry point"

 

this is my class:

line 6 is this: 

Product2 produto3 = [select id from Product2 where name = 'DSL 10ppm CIF NWE AAWZC00'];

Can help me?

 

 

@isTest 
private class myClass {
    static testMethod void myTest() {
//--------------------------------------------------
 
Product2 produto3 = [select id from Product2 where name = 'DSL 10ppm CIF NWE AAWZC00'];
RecordType rtp = [select id from RecordType where name = 'Platts'];
Pricing__c p = new Pricing__c (RecordTypeId = rtp.id, produto__c =produto3.id, valor_inicial__c =1, cambio_usd_ton__c = 1,
valido_de__c =date.today(), valido_ate__c= date.today());
insert p;



Product2 produto4 = [select id from Product2 where name = 'Diesel - PVP'];
RecordType rtpp4 = [select id from RecordType where name = 'Preço de Venda'];
Pricing__c p4 = new Pricing__c (RecordTypeId = rtpp4.id, produto__c = produto4.id, 
valido_de__c =date.today(), valido_ate__c= date.today());
insert p4;


Product2 produto_composto2 = [select id from Product2 where name = 'COMBUSTÍVEL BIODIESEL 10%'];
RecordType rtpp = [select id from RecordType where name = 'Produtos Compostos'];
Pricing__c p3 = new Pricing__c (RecordTypeId = rtpp.id, produto__c = produto_composto2.id, 
valido_de__c =date.today(), valido_ate__c= date.today());
insert p3;
Account acc = new Account(name='testing account');
        insert acc;
Account acc_filho = new Account(name='testing account filho');
        insert acc_filho;
        
Account a = [select Parentid from Account where //id ='001Q000000AdLXY'
id= :acc_filho.id];

a.parentid = acc.id;
//'001Q000000AdLXO';
update a;

Account aa = [select Parentid from Account where id= :acc_filho.id];

aa.parentid = null;
update aa;
 
Partidas_Financeiras__c pf_criar = new Partidas_Financeiras__c(conta__c = acc.id,valor_liquido__c =1 );
insert pf_criar;
    list<Partidas_Financeiras__c> pf = [select Recebido_aguarda_registo_em_SAP__c from
    Partidas_Financeiras__c where conta__c = :acc.id];
    for(Partidas_financeiras__c pfff : pf){
pfff.Recebido_aguarda_registo_em_SAP__c =true;
}
update pf;   
        
 //create a test opportunity

        Opportunity op = new Opportunity(name='testopp1', StageName='Prospecting', CloseDate = date.today(), 
        AccountId = acc.Id);
        insert op;
        Product2 produto = [select id from Product2 where name = 'COMBUSTÍVEL GASÓLEO'];
        PriceBookEntry pbookEntry = [select id from PriceBookEntry where Product2Id = :produto.id];
        Centro_de_carga__c cdc = [select id from Centro_de_carga__c where name = '01 - PrioAF: Matosinhos'];
        //create opportunity line item
        OpportunityLineItem olitem = 
        new OpportunityLineItem(OpportunityId = op.Id, PriceBookEntryId = pbookEntry.Id, 
        Quantity = 1,centro_de_carga2__c = cdc.id, tipo_de_preco_de_referencia__c = 'Preço de Compra',
        incoterms__c = 'EXW');
        insert olitem;

        Product2 produto_composto = [select id from Product2 where name = 'COMBUSTÍVEL BIODIESEL 10%'];
        PriceBookEntry pbookEntry2 = [select id from PriceBookEntry where Product2Id = :produto_composto.id];
        Centro_de_carga__c cdc2 = [select id from Centro_de_carga__c where name = '01 - PrioAF: Matosinhos'];
        OpportunityLineItem olitem2 = 
        new OpportunityLineItem(OpportunityId = op.Id, PriceBookEntryId = pbookEntry2.Id, 
        Quantity = 1,centro_de_carga2__c = cdc2.id, tipo_de_preco_de_referencia__c = 'Preço de Compra',
        incoterms__c = 'EXW');
        insert olitem2;
       
Product2 produto_composto3 = [select id from Product2 where name = 'COMBUSTÍVEL BIODIESEL 20%'];
PriceBookEntry pbookEntry3 = [select id from PriceBookEntry where Product2Id = :produto_composto3.id];
            OpportunityLineItem olitem3 = 
        new OpportunityLineItem(OpportunityId = op.Id, PriceBookEntryId = pbookEntry3.Id, 
        Quantity = 1,tipo_de_preco_de_referencia__c = 'Preço de Venda',
        incoterms__c = 'EXW');
        insert olitem3;
    
        Product2 produto7 = [select id from Product2 where name = 'COMBUSTÍVEL GASÓLEO'];
        PriceBookEntry pbookEntry4 = [select id from PriceBookEntry where Product2Id = :produto7.id];
        //create opportunity line item
        OpportunityLineItem olitem4 = 
        new OpportunityLineItem(OpportunityId = op.Id, PriceBookEntryId = pbookEntry4.Id, 
        Quantity = 1, tipo_de_preco_de_referencia__c = 'Platts',
        incoterms__c = 'EXW');
        insert olitem4;

 
//---------------------------------------------------------------------

Proposta__c pro =new Proposta__c (Oportunidade__c =op.Id, name ='teste',valido_de__c =Date.today(),
    Validade_em_dias__c =3, count_proposta__c =1 );
insert pro;

Proposta__c pro2= [select substituida__c  from Proposta__c where id = :pro.id];
pro2.substituida__c = true;
update pro2;

Proposta__c pro3 =new Proposta__c (Oportunidade__c =op.Id, name ='teste2',valido_de__c =Date.today(),
    Validade_em_dias__c =3 );
insert pro3;



//-----------------------------------------------------------
RecordType rt = [select id from RecordType where name = 'Combustíveis Compostos'];
Input_Resumo_pricing__c  irp= new Input_Resumo_pricing__c(RecordTypeId = rt.id, valido_de__c = Date.today(),
valido_ate__c = Date.today());
insert irp;

RecordType rt2 = [select id from RecordType where name = 'Combustíveis não Compostos'];
Input_Resumo_pricing__c  irp2= new Input_Resumo_pricing__c(RecordTypeId = rt2.id, valido_de__c = Date.today(),
valido_ate__c = Date.today());
insert irp2;

RecordType rt3 = [select id from RecordType where name = 'Pricing Manual'];
Input_Resumo_pricing__c  irp3= new Input_Resumo_pricing__c(RecordTypeId = rt3.id, valido_de__c = Date.today(),
valido_ate__c = Date.today());
insert irp3;

//--------------------------------------------------------------


//-----------------------------------------------


    }
}
 

 

I have a custom object. And i want to deploy only selected fields and validation of that custom object. I selected those using by selected the meta data component. But my deployment fails with an error saying  "Must specify a non-empty label for the CustomObject".

 

Although i am using the Eclispe 3.5 with all the latest updated from Force.com IDE (using check for updates)

 

But nothing seems working??

 

Please help ....

  • September 08, 2010
  • Like
  • 0

Fellow developers,

 

I am experiencing a strange error - perhaps someone has come across this before and knows a solution?

 

I have a VF page that takes a number of parameters from the url and creates various custom objects. One of the last tasks it has to do is insert a Lead. If an Id parameter (containing a string not related to a SFDC id) is present in the querystring I get the error:-

 

EXCEPTION_THROWN|[199,17]|System.DmlException: Insert failed. First exception on row 0; first error: UNKNOWN_EXCEPTION, invalid parameter value: []

Line 199 inserts the Lead.

 

so /mypage?firstname=bob&lastname=smith&id=abc123    = BROKEN

but /mypage?firstname=bob&lastname=smith                         = OK

 

I don't use the id. I don't have a standard controller. Its just a standard constructor (public myPage(){...} ) and action dosomething() in the VF page tag.

 

The reason is that it is there in an external flash application and the client swears it used to work with the id parameter and it will continue to be being passed in.

 

(I did try doing the following in the constructor "apexpages.CurrentPage.getParameters().remove('id');" with no success.)

 

Any ideas??

 

Thanks,

Rich.

 

 

 

 

Hey guys...

 

I've recently started digging into email services... I like them, but I'm running into problems with the addresses being added to a string with names and all that...

 

I'm rebuilding email-to-case as a custom solution because I have no way to "reply to all" instead of just "reply to" when a new case is entered...

 

Here's where I am at so far:

This class works relatively well...

 

global class email01 implements Messaging.InboundEmailHandler {

public List<string> allAddresses {get;set;}

global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {

Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();

Contact fromCtc;
Task emTask;
allAddresses = new List<string>();

//Here I am adding all the addresses into one list to make them easier to deal with later
allAddresses.addAll(email.toAddresses);
if (email.ccAddresses != null) {
allAddresses.addAll(email.ccAddresses);
}

try {
//If this contact is not already in the system...
if ([select count() from contact where email = :email.fromAddress] == 0) {

//specify the new contact
fromCtc = new contact();

//Retrieve the sender's first and last names
String fName = email.fromname.substring(0,email.fromname.indexOf(' '));
String lName = email.fromname.substring(email.fromname.indexOf(' '));

//create the contact
fromCtc.firstName = fName;
fromCtc.LastName = lName;
fromCtc.Email = email.fromAddress;
insert fromCtc;

//otherwise - select the one in the system
} else {
fromCtc = [select id from contact where email = :email.fromAddress];
}

//specify the ref tags we use
string startRef = '[ tioref:';
string endRef = ':tioref ]';

//Now we need to figure out what this is in regards to:
// Note that business rules determine this by the toAddress
// of the message, or the refId
//Now if the subject contains both of those ref numbers, then we should act on it
if(email.subject.contains(startRef) && email.subject.contains(endRef)) {

//Lets pull the id out of the subject string
string refId = email.subject.substring(email.subject.indexOf(startRef) + 9, email.subject.indexOf(endRef));

//Now that we've gotten that... Let's query the db for it and find out what it is:

Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
Map<String,String> keyPrefixMap = new Map<String,String>{};
Set<String> keyPrefixSet = gd.keySet();
for(String sObj : keyPrefixSet){
Schema.DescribeSObjectResult r = gd.get(sObj).getDescribe();
String tempName = r.getName();
String tempPrefix = r.getKeyPrefix();
keyPrefixMap.put(tempPrefix,tempName);
}

string tPrefix = refId.subString(0,3);
string objectName = keyPrefixMap.get(tPrefix);
System.debug('objectName:::::' + objectName);

//If this is a case
if (objectName == 'Case') {
//go do this...
caseEmailHelper.caseEmail(refId, email.fromAddress, email.fromName, email.toAddresses, email.ccAddresses, email.subject, email.plainTextBody);
}
            }
//Otherwise I wanna determine what address it was sent to - right now I just have one test address... I don't think this is a right way to do it, but I'm not sure.
else {
                for (string address : allAddresses) {
                    if (address == 'mytestaddress@mydomain.com') {
                        caseEmailHelper.caseEmail(null, email.fromAddress, email.fromName, email.toAddresses, email.ccAddresses, email.subject, email.plainTextBody);
                    }
                }
            }
            result.success = true;
        }
        //Otherwise - debug it, and blame it on someone else...
        catch (exception e) {
            system.debug(e);
            result.success = false;
        }
        return result;

    }
}

 

 

 

This class is having some problems...

 

public with sharing class caseEmailHelper {

public Case c {get;set;}
public EmailMessage e {get;set;}

public static void caseEmail(String id, String fromAddress, String fromName, List<string> toAddresses, List<string> ccAddresses, String subject, String body) {

Case c = new Case();
Contact ctc = [select id from contact where email = :fromAddress];

//If this is a new case - meaning we do not have an ID
if ([select count() from Case where id = :id] == 0) {
//Then create the case and set the mandatory fields...
c = new Case();
c.Subject = subject;
c.Description = body;
c.Origin = 'Email';
c.ContactId = ctc.Id;
insert c;
//... and send a reply
caseReply(c.id, fromAddress, fromName, toAddresses, ccAddresses, subject, body);

} else {
c = [select id from Case where id = :id];
}

EmailMessage e = new EmailMessage();
//Iterate through the toAddresses and add them to the email toAddress
for ( integer i = 0 ; i < toAddresses.size(); i++) {
if (e.ToAddress == null) {
e.ToAddress = toAddresses[i];
} else {
e.toAddress = e.toAddress + '; ' + toAddresses[i];
}
}
e.FromAddress = fromAddress;
e.fromName = fromName;
//iterate through the ccAddresses and add them to the ccAddress
//NOTE this could be null... so lets make sure to check that...
if (ccAddresses != null ) {
for ( integer i = 0 ; i < ccAddresses.size(); i++) {
if (e.CcAddress == null) {
e.CcAddress = ccAddresses[i];
} else {
e.CcAddress = e.CcAddress + '; ' + ccAddresses[i];
}
}
}
e.subject = subject;
e.ParentId = c.id;
e.Incoming = true;
e.TextBody = body;
e.MessageDate = system.Datetime.now();
//Status 0 = New, 1 = Read, 2 = Replied, 3 = Sent, 4 = Forwarded
e.status = '0';
insert e;
}

//Sending a reply
// Note that I have passed an ID even though I may already have one
// this means i might just be able to call this from other places later...
public static void caseReply(String id, String fromAddress, String fromName, List<string> toAddresses, List<string> ccAddresses, String subject, String body) {

Case c = [select id, contactId from Case where id = :id];

if (toAddresses != null) {
for (integer i = 0 ; i < toAddresses.size(); i++) {
string toAddy = toAddresses.get(i);
if (toAddy == 'mytestaddress@mydomain.com') {
toAddresses.remove(i);
}
}
}
if (ccAddresses != null) {
for (integer i = 0 ; i < ccAddresses.size(); i++) {
string ccAddy = ccAddresses.get(i);
if (ccAddy == 'mytestaddress@mydomain.com') {
ccAddresses.remove(i);
}
}
}
//Do something else for now...

// Create a new single email message object
// that will send out a single email to the addresses in the To, CC & BCC list.
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

//send this to the id we have specified
mail.setTargetObjectId(c.contactId);

//Send it back to everyone!
mail.setCcAddresses(ccAddresses);
mail.setToAddresses(toAddresses);

mail.setWhatId(c.id);

//Use the template we got
mail.setTemplateId('00X800000016PCm');

// Specify the address used when the recipients reply to the email.
// NOTE this does not seem to work when using templates... even if I removed the setReplyTo in the template...
// you MUST use a set replyToIn this template to keep working...
mail.setReplyTo('mytestaddress@mydomain.com');

// Specify the name used as the display name.
mail.setSenderDisplayName('TIO Networks Support');

// Set to True if you want to BCC yourself on the email.
mail.setBccSender(false);

// Optionally append the salesforce.com email signature to the email.
// The email address of the user executing the Apex Code will be used.
mail.setUseSignature(false);

// Send the email you have created.
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

//Save this as an activity in the case record
mail.setSaveAsActivity(true);
}
}

 

my problem seems to be on the blue line... it doesn't like my addresses....

Debug log:

System.EmailException: SendEmail failed. First exception on row 0; first error: INVALID_EMAIL_ADDRESS, Invalid to address : John Doe <john.doe@gmail.com>: []

 

I guess it has something to do with just passing those address strings with all the other characters in them... how I can get rid of those in email01 class and just pass something nice and clean?

 

Thanks!!

  • August 20, 2010
  • Like
  • 0

Hello,

 

I have a trigger that creates is supposed to create a new record based on a status field of a different custom object. When i run the trigger, it creates 2 new records in the second custom object. Help solving why it is creating two instead of one is appreciated.

 

My code below:

 

Trigger:

 

 

trigger CreateTicket on Maintenance_Request__c(after update)

{

    if(Trigger.isUpdate){
        for(Maintenance_Request__c m: Trigger.new)

       {

          if(m.Status__c == 'Pending Support')

          {

               Support_Team_Request__c st = new Support_Team_Request__c();

              

                  st.Your_name__c = m.Your_Name__c;
                  st.Client_reported_issue__c = 'No';
                   st.Short_description__c = m.Short_Description__c;
                   st.Client_Name__c = m.Client_Name__c;
                   st.Description_of_Issue__c = m.Detailed_Description__c;
                    st.Mailbox__c = m.Mailbox__c;
                    st.Priority__c = 'medium';
                    st.Created_From_MTR__c = 'Yes';
                    st.Request_Type__c = 'production' ;  
                    st.Participant_Name__c = m.Participant_Name__c;
                    st.Participant_ID__c = m.Participant_ID__c;
                    st.CC_Contact__c = m.CC_Contact__c;

                insert st;

          }
         
        }
    }  

}

 

 

 

Test Class:

 

 

@isTest
private class CreateTicketTriggerTest {

    static testMethod void myUnitTest() {
      
        Maintenance_Request__c mr = new Maintenance_Request__c();
    
        mr.Your_Name__c = 'Test User';
    mr.Short_Description__c = 'Test request';
    mr.Client_Name__c = '0015000000GibFx';
    mr.Detailed_Description__c = 'Test maintenance request';
    mr.Mailbox__c = 'test@example.org';
    mr.Participant_Name__c = 'Test Participant';
    mr.Participant_ID__c = '123';
      mr.Request_Type__c = 'Account Merge';
        mr.Request_Type__c = 'Account Merge';

        
    insert mr;
        
        mr.Status__C = 'Pending Support';
    update mr;
    }
}

 

 

  • August 17, 2010
  • Like
  • 0

I'm working on a trigger that simply populates a date/time value into a field on the account when a record of a specific record type gets created on a related custom object. The trigger is fine but the test class fails due to the line where I try to specify the record type in the test. The error I get is below.

 


System.StringException: Invalid id: DO NominationClass.AccUpdateTest.SponsorshipInsert: line 11, column 20 External entry point

 

My trigger code:

trigger AccUpdate on AE_Sponsorship__c (after insert, after update) {
//Query for the Account record types
     List<RecordType> rtypes = [Select Name, Id From RecordType 
                  where sObjectType='AE_Sponsorship__c' limit 1];
     
     //Create a map between the Record Type Name and Id for easy retrieval
     Map<String,String> accountRecordTypes = new Map<String,String>{};
     for(RecordType rt: rtypes)
        accountRecordTypes.put(rt.Name,rt.Id);

    for (AE_Sponsorship__c a: trigger.new){
            if(a.RecordTypeId==accountRecordTypes.get('DO Nomination'))
            {
            Account myAcc = [select Id from Account where ID = : a.Account__c];
        myAcc.Test_Update_from_AE_sponsorship__c = a.lastmodifiedDate;
        update myAcc;
        }
    }
}

My test class:

@isTest
private class AccUpdateTest {
    private static testmethod void SponsorshipInsert(){
    AE_Sponsorship__c sponsor1 = new AE_Sponsorship__c(
    Overall_Monthly_Volume__c=100, 
    Met_with__c='jim', 
    Expected_Flagstar_Volume__c=100, 
    Approved_for_CFL__c=TRUE, 
    Account__c = '0015000000Jo7v5',
    Date_of_Visit__c=Date.newInstance(2010, 07, 15),
    RecordTypeID = 'DO Nomination'
);
insert sponsor1;
}
}

 Can anyone help me get this final piece working please? I need to specify the record type without hard coding the record type ID, which is why the trigger has a map for record type.

 

Thank you,

Larry

 

 

string productquery = 'select id, viewhref__c, subject__c, posteddate__c from lithiummessage__c where lithiumboard__r.productcode__c = ' + '\'%' + :getproduct() + '%\'' + ' ORDER BY posteddate__c DESC LIMIT 10';
		
		List<LithiumMessage__c> lm = new List<LithiumMessage__c>();
		lm = database.query(productquery);
system.debug(logginglevel.info,'items: ' + lm);

 

So, if productcode is equal to to what I'm passing in, the query works.  if it's no equal, say 'lmiignition,lmiignitionandroid', it will not return any results.  isn't '%' supposed to wildcard any number of chars?  This usually works for me, but I haven't had the need to try it in relationship queries until now.

 

I wrote the query:

 

Select count() from Account

 

I have around 20,000 accounts in the system.

So how am I suppouse to get their number in the system?

Thanks!

  • August 15, 2010
  • Like
  • 0

 

i need helping finding why i am getting that error. and also is there a way i can identify the actual record causing it instead of the output just saying that error ?

 

 

public void doPhoneComparison(){
		
		try{
		
		// sf contact phone numbers
		map<string,string> map1 = new map<string,string>();
		
		// phone numbers obj phone numbers
		map<string,string> map2 = new map<string,string>();
		
		// get all contact phone numbers, there is going to be over 7000
		integer i=0;
		
			ApexPages.addMessage( new ApexPages.Message(
    		ApexPages.Severity.INFO  , datetime.now() +' checking phone number field...'));

        	ApexPages.addMessage( new ApexPages.Message(
    		ApexPages.Severity.INFO  , datetime.now() +' checking external phone numbers...'));

  		// get all 'phone number' obj phone numbers
  		for(Phone_Numbers__c p : [select phone_number__c from Phone_Numbers__c]){
  			
  			p.phone_number__c = p.phone_number__c.replaceAll('-','');
			p.phone_number__c = p.phone_number__c.replaceAll('\\(','');
			p.phone_number__c = p.phone_number__c.replaceAll('\\)','');
			p.phone_number__c = p.phone_number__c.replaceAll(' ','');

              map2.put(p.phone_number__c,p.phone_number__c);
        }
        
        	ApexPages.addMessage( new ApexPages.Message(
    		ApexPages.Severity.INFO  , datetime.now() +' comparing phone numbers...'));
  
       // compare the two numbers
         for(Contact c : [select id,phone from Contact where id != null AND phone != null]){
 
         	if(c!=null && c.phone!=null && c.phone.length()>0){
	         	if(c.phone.contains('-')==true){
	         		c.phone = c.phone.replaceAll('-','');
	         	}
	         	
	         	if(c.phone.contains('(')==true){
					c.phone = c.phone.replaceAll('\\(','');
	         	}
				
				if(c.phone.contains(')')==true){
					c.phone = c.phone.replaceAll('\\)','');
				}
				
				if(c.phone.contains(' ')==true){
					c.phone = c.phone.replaceAll(' ','');
				}
         	}

		 //   if (map1.get(map2.get(c.phone)) == c.phone ) 
		  if (map2!=null && map2.get(c.phone) == c.phone ) 
		    { 
		    	// output matches
		        ApexPages.addMessage( new ApexPages.Message(
    			ApexPages.Severity.INFO  ,'found match:  contact phone ' +c.phone +' , external phone ' +map2.get(c.phone) +' '));
		   		i++;
		    } 
	
		} 
       
		// output count of records processed
		ApexPages.addMessage( new ApexPages.Message(
    	ApexPages.Severity.INFO  ,'matches ' +i ));
    	
		} catch(NullPointerException e){
			ApexPages.addMessages(e);
		}
	}

 

Hi,

 

I've seen this example that shows how to leverage the Scheduling API to set jobs to run on an hourly basis. But can I set up a Batch Apex job to run hourly as well? If so, can someone guide me through the process? I already know how to write and set up Batch Apex jobs that run daily, but need help getting them to run hourly.

 

Thanks in advance.

  • August 13, 2010
  • Like
  • 0

Can anyone help with this?

 

I thought this would be the simplest part of my day but it isn't. I have just created a class that pulls down nodes from an XML file from an external server and inserted that into SFDC.

 

That all works fine when I use a hardcoded end point.

 

But my issue is I need a dynamic endpoint because the URL I pass through the external server will always have different content based on latitude and longitude fields that I have stored in a custom object called Incident__C.

 

The idea is that the my xml parser class is called from a trigger that runs AFTER an insert so I should be able to pick up fields froma newly created Incident__c record to create and end point. Only I can't get it to work.

 

Any ideas - heres my endpoint from the class....

 

req.setEndpoint('http://www.uk-postcodes.com/latlng/latitude__c,longitude__c.xml');

 

It never pulls through the fields from the record that has just been triggered.

 

Thoughts? Do I need to reference the newly created Incident__c somehow for these fields to be picked up?

 

Do you have to treat merged fields differently in a class?