• JeremyKraybill
  • NEWBIE
  • 305 Points
  • Member since 2008

  • Chatter
    Feed
  • 11
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 5
    Questions
  • 161
    Replies

Hi.

 

Several triggers I've written call class functions that wrap database operations with the goal that calling functions can perform a database rollback if a wrapped operation fails.

 

Since this is my first real attempt at APEX coding and after some head scratching, I've gotten everything covered except two lines I'm not sure how or even if I can test.

 

For example, given a simple wrapper class:

 

 

public class PackageHelper { public class PackageHelperException extends Exception {} public static Boolean addAccountNote(Account a, String title, String body) { if( null == a) throw new PackageHelperException('####addAccountNote: a == null'); System.debug('#################### >> addAccountNote'); title = (null == title || title.length() < 1) ? 'No title provided' : title; body = (null == body || body.length() < 1) ? 'No body provided' : body; try { insert new Note( ParentId = a.Id, Title = title, Body = body); } catch ( System.DmlException e) { System.debug('#################### addAccountNote ' +'could not insert note:'+e.getMessage()); return false; } return true; } // test for addAccountNote private static testMethod void test_addAccountNote() { String title = 'Note Title'; String body = 'Note Body';

Account a;

Note t;

Boolean result;

try { result = addAccountNote((Account)null, title, body); } catch (Exception e) { System.assert(e.getMessage().contains('a == null')); }

System.assertEquals(null, result);

a = new Account(Name='Test Account'); insert a;

 

// add a note

System.assertEquals(true, addAccountNote(a, (String)null, ''));

// was note added?

t = [ select Id, Title, Body from Note where ParentId = :a.Id limit 1 ]; System.assertEquals('No title provided', t.title); System.assertEquals('No body provided', t.body);

 

// ok, delete it delete t;

 

// add another System.assertEquals(true, addAccountNote(a, '', (String)null)); t = [ select Id, Title, Body from Note where ParentId = :a.Id limit 1 ]; System.assertEquals('No title provided', t.title); System.assertEquals('No body provided', t.body); delete t;

 

// and another System.assertEquals(true, addAccountNote(a, title, body)); t = [ select Id, Title, Body from Note where ParentId = :a.Id limit 1 ]; System.assertEquals(title, t.title); System.assertEquals(body, t.body); delete a; } }

 

 

Running the tests on this class reports full coverage except for these two highlighted lines:

 

 

try {
insert new Note( ParentId = a.Id, Title = title, Body = body);
}
catch ( System.DmlException e) {
System.debug('#################### addAccountNote '
+'could not insert note:'+e.getMessage());
return false;
}

 

Perhaps I'm missing something fundamental, but how can I test for an exception which, in the best of all worlds, never occurs and over which I have no control?

 

Thanks.

 

 

Hi,

 

I have a Visualforce page which is embedded on a Custom object detail page.

The height of the Visualforce page gets changed dynamically.

If only one record is displayed, the remaining section is shown in white colour.

If there are more records, then most of the content is not shown because of the section height.

 

So how can i adjust the height dynamically.

 

Is there any other solution, through which i can achieve this.

 

Thanks in advance,

OnDem 

 

I have a requirement to send out an email to a selectable list of Contacts based on a specific contact role  from an opportunity using Professional Edition. The email is a Bid For Service that is sent out from an Opportunity to Contacts on Accounts (with an Account type of "Service Provider") whose roll is "Candidate Bidder."  Not all "Candidate Bidders" will be included, so the list must be selectable.  Using the API and creating a wrapper class makes this easy, but, that is not available.

 

 

 I have tried a variety of options: Account Contact Roles are not avail able in a List View; I've created a report that creates the list of records, but don't seem able to access report records in a VF page; Account Contact Roles are not available as a standard List Controller (would have also made this easier).

 

I created a page using a component that set the filterId to a specific listview and retrieved all the Accounts.  However, I am unsure of how to proceed and get all the correct contacts using the Account contact roles, selecting the contacts, and pass their email address to a VF template.

 

Thanks

Had a VF page and controller that was working fine until Spring '09 was installed.  It appears that any values in any public variables are maintained fine when rendered as HTML output and we get a single debug log.  However, if we renderAs="pdf", we end up with multiple log entries and the controller values are lost between the two separate logs resulting in a bunch of null value errors.  What's changed in Spring '09 and how do we accomodate for this?  An simple pseudo-code example would be:

 

public Account myAcct; public Account getAccount() { myAcct = ([SELECT name FROM Account where somecriteria]) System.debug('myAcct Name='+myAcct.name); } public getAcctName() { System.debug('myAcct Name='+myAcct.name); return myAcct.name;}

 


 

This is a simple example but the first debug statement works fine.  The second one returns a null error/value when rendering as PDF.  However, rendering as HTML doesn't have a problem.

 

Hey guys,

 

I'm trying to have Visualforce render a pagesection dependent on whether or not a checkbox has been selected. I'm getting nowhere fast and was wondering if somebody could help?

<apex:pageblock title="Additional Required Information"> <apex:outputtext value="Is the status for a set period of time, set amount of units, or other?" /> <apex:pageblocksection columns="5"> <apex:pageblocksectionitem > <apex:outputlabel value="Time" for="TimeScope" /> <apex:inputcheckbox value="{!Opportunity.Period_of_Months__c}" id="TimeScope" />

</apex:pageblocksectionitem> <apex:pageblocksectionitem > <apex:outputlabel value="Amount of units" for="UnitScope" /> <apex:outputpanel > <apex:inputcheckbox value="{!Opportunity.Status_Number_of_Units__c}" id="UnitScope"> <apex:actionsupport event="onchange" rerender="ProductUnitsInformation" status="AjaxStatus" /> THIS SECTION SHOULD CAUSE THE SECTION AT THE BOTTOM TO RENDER (OR NOT) </apex:inputcheckbox> </apex:outputpanel> </apex:pageblocksectionitem> <apex:pageblockSectionItem > <apex:outputlabel value="Other" for="OtherScope" /> <apex:inputcheckbox value="{!Opportunity.Status_Other__c}" id="CarbonScope" /> </apex:pageblockSectionItem> <apex:pageblocksectionitem > </apex:pageblocksection>

<apex:pageblocksection> <apex:outputpanel id="ProductUnitsInformation"> THIS IS THE SECTION TO BE RE-RENDERED <apex:actionStatus id="AjaxStatus" startText="Requesting..."> <apex:facet name="stop"> <apex:pageblocksection rendered="{!Opportunity.Status_Number_of_Units__c}"> <apex:pageblocksectionitem > <apex:inputfield value="{!Opportunity.Number_of_Units__c}" /> <apex:inputfield value="{!Opportunity.Unit_Identifier__c}" /> </apex:pageblocksectionitem> </apex:pageblocksection> </apex:facet> </apex:actionStatus> </apex:outputpanel> </apex:pageblock>

 

What I'm trying to make happen is, upon selection of the checkbox (id = UnitScope, with the child apex:actionsupport tag), the apex:outputpanel (id=ProductunitsInformation) should render.

 

Currently, upon selection of the checkbox, the action status does not render, and the screen does not change. I'm sure I'm just being naive, but I've not had a great deal of success with the event handlers and AJAX updates.

 

If anybody could point me in the right direction, I'd be very thankful.

 

Andy

I've spent some time trying to get some dynamic elements onto a page that is rendered as a pdf.  I've isolate what I believe to be a bug and would like for someone to verify.  In order to combat the various problems around losing state of member variables in page flows that contain the same controller, I've packed the url that I redirect to with query string parameters that will then be used by the target page to fill content.  Like so:

 

String url = '/apex/PrintMultipleSOs?id=' +
        ApexPages.currentPage().getParameters().get('id');
        Integer counter = 0;
        signaturePageItems = myServiceMap.values();
        for (Service_Order__c eachSO: signaturePageItems){
            if (counter == 0){
                //i'm hacking this because having trouble with the map and the signature page items array
                url = '/apex/PrintMultipleSOs?id=' + eachSO.id;   
            }
            else {
                url += '&so'+counter+'='+eachSO.Id;
            }
            counter++;
        }
        PageReference sigPage = new PageReference(url);
        sigPage.setRedirect(true);
        return sigPage;

 

So if I have 3 SOs, I'll end up with a query string that is {url}?id={firstRowID}&so1={secondRowID}&so2={thirdRowID}.

 

So now in my target page, I'll need to query for these so I want to just iterate over the map of values from 

ApexPages.currentPage().getParameters().  (side note that when working in dev mode there is a query string parameter that was causing my iteration to fail until I removed it from my user profile)

 

//this will never work for a user that is in dev mode b/c there is an additional qs parameter for the dev mode
              Map<String, String> soList = ApexPages.currentPage().getParameters();
              //todo: pull the query into a list return, rather than adding to temp array and potentially hitting soql limit
              for (String eachSOID:soList.values()){
                  tempService = [select Id,Name,Order_Stage__c, Product__c, Term__c, Product_Category__c,
                Hub_Circuit_ID__c, Flex_Facility_ID__c, Ring_Name__c, Bandwidth__c,Customer_Circuit_Id__c,
                Customer_PO__c, Auto_Switching__c,Card_Protection_Required__c,Core_Network_Protection_Required__c,
                Colocation_Type__c, Cabinet_Rack_Provided_By__c, Primary_Power__c, Redundant_Power__c,
                Address_A__c, Suite_Room_A__c, City_A__c, State_A2__c, Zip_A__c, Address_Z__c, Suite_Room_Z__c, City_Z__c, State_Z__c, Zip_Z__c,
                Account__c from Service_Order__c where id = :eachSOID];
                myServiceMap.put(tempService.id, tempService);
               
              }

 

So this works fine when the target page is not a pdf.  I'm guessing there's another hidden querystring param (like the dev mode stuff)  However, brute force does appear to work on the target page.  Like so:

 

String so1 = ApexPages.currentPage().getParameters().get('so1');
              tempService = [select Id,Name,Order_Stage__c, Product__c, Term__c, Product_Category__c,
                Hub_Circuit_ID__c, Flex_Facility_ID__c, Ring_Name__c, Bandwidth__c,Customer_Circuit_Id__c,
                Customer_PO__c, Auto_Switching__c,Card_Protection_Required__c,Core_Network_Protection_Required__c,
                Colocation_Type__c, Cabinet_Rack_Provided_By__c, Primary_Power__c, Redundant_Power__c,
                Address_A__c, Suite_Room_A__c, City_A__c, State_A2__c, Zip_A__c, Address_Z__c, Suite_Room_Z__c, City_Z__c, State_Z__c, Zip_Z__c,
                Account__c from Service_Order__c where id = :so1];
                myServiceMap.put(tempService.id, tempService);
               
                String so2 = ApexPages.currentPage().getParameters().get('so2');
                tempService = [select Id,Name,Order_Stage__c, Product__c, Term__c, Product_Category__c,
                Hub_Circuit_ID__c, Flex_Facility_ID__c, Ring_Name__c, Bandwidth__c,Customer_Circuit_Id__c,
                Customer_PO__c, Auto_Switching__c,Card_Protection_Required__c,Core_Network_Protection_Required__c,
                Colocation_Type__c, Cabinet_Rack_Provided_By__c, Primary_Power__c, Redundant_Power__c,
                Address_A__c, Suite_Room_A__c, City_A__c, State_A2__c, Zip_A__c, Address_Z__c, Suite_Room_Z__c, City_Z__c, State_Z__c, Zip_Z__c,
                Account__c from Service_Order__c where id = :so2];
                myServiceMap.put(tempService.id, tempService);

 

Why is this misbehaving?

I need a trigger to create a Dummy Account record every time a Contact is saved with its AccountID field empty (so that Contact is not marked Private and thereby inaccesssible to all beside Owner and Admin). Would the following work? Do I need to add something so that it ONLY creates a dummy record when the AccountID field is empty?

 

trigger create_dummy_accnt on Contact (before insert) {

 

  // create a container to bulk insert accounts
  List<Account> accountsToInsert = new List<Account>(); 

 

  // loop through trigger records
  for (int i=0; i<Trigger.new.size(); i++)
  {
    {
      Account CreateAccnt = new Account();
      CreateAccnt.Name = 'Dummy Account';
      accountsToInsert.add( CreateAccnt );
    }
  }

  // bulk insert accounts
  if (!accountsToInsert.isEmpty()) {
    insert accountsToInsert;
  }
}

 

Also, can anyone think of a way to keep the resulting dummy accounts off the recently viewed items list?

 

Ideally I'd like to drop this workaround and somehow prevent the system from marking Contacts with blank Account ID private - there's no way to do that programatically I don't suppose?

 

The only other workaround I know is to make everyone a system admin. Yikes!

Is there an easy way to only display the Time of a DateTime object in VisualForce?

 

Also is there an easy way to display the Day-of-the-week like 'Friday' in VisualForce?

 

Currently, I'm using a switch statement taken from the pdf on Formulas, but am wondering if there is a better method:

{!CASE(MOD( TODAY() - DATE(1900, 1, 7), 7),0, "Sunday",1, "Monday",2, "Tuesday",3, "Wednesday",4, "Thursday",5, "Friday",6, "Saturday", "Error")}

 

Thanks

Parker

 

I am writing a trigger that checks to see when a Case is Closed, that there are no Open Child Cases associated with that Case.

I can get it working fine with plain trigger code:

 

trigger CloseCase_whenNoOpenChildCase on Case (after insert, after update) {

Case[] cc = Trigger.new;

for (Case c:cc)
{
if (c.IsClosed)
{

Integer OpenChildCase = 0;
for (Case ChildCase : [select id from case where ParentId = :c.id and (isClosed != true)])
OpenChildCase++;
if (OpenChildCase > 0)
c.addError('You are trying to Close a Parent Case that still has open child case! Parent Case number is '+c.casenumber+' or Parent Case id = '+c.id);
}
}
}
 
But now I want to use apex classes and so I created a CloseParentCase_NoOpenChildCase class with the CloseoutParentCase method and so replaced the trigger code to this:
trigger CloseCase_whenNoOpenChildCase on Case (after insert, after update) {

Case[] cc = Trigger.new;

for (Case c:cc)
{
if (c.IsClosed)
{
CloseParentCase_NoOpenChildCase.CloseoutParentCase(c);
}
}
}
And the class I created is as followed: 
public class CloseParentCase_NoOpenChildCase
{

public static void CloseoutParentCase (Case c)
{
if (c.isClosed)
{


Integer OpenChildCase = 0;
for (Case ChildCase : [select id from case where ParentId = :c.id and (isClosed != true)])
OpenChildCase++;
if (OpenChildCase > 0)
c.addError('You are trying to Close a Parent Case that still has open child case! Parent Case number is '+c.casenumber+' or Parent Case id = '+c.id);
}
}
 
 
 
And I wanted to create testmethods that will show when I try to close out a case that has child case, it will fail.  But the problem is it looks like when I run the test, it will fail because of the addError call within the class, so the running of the test will fail.
 For example, in my testmethod, I would do something like the code below, but the problem is it would fail at the statement:     update parent_case;
and this is because it would hit the logic in the the CloseoutParentCase method which issues the addError call.
 
So what is the proper way to write a test method when the logic of the trigger/class itself is to result in a failure when certain situation occurs? 
 
  static testmethod void testCloseoutParentCase ()
{


Case parent_case = new Case(RecordTypeId = '0120000000002Ld',Status ='New');
insert parent_case; // hit the trigger

// make sure Case is created
System.assert(parent_case.id != null);
System.assertEquals(parent_case.Status,'New');


Case SRchild_case0 = new Case(RecordTypeId = '0120000000002Ld',Status ='New',parentid=parent_case.id);
insert SRchild_case0; // hit the trigger

// make sure Case is created
System.assert(SRchild_case0.id != null);

// double check

Case SRchild_case = [ select Status from case where parentid = :parent_case.id];

// make sure Case is created
System.assert(SRchild_case.id != null);


// Now try to update the parent case to Closed, it should fail since we have an open child case
// and therefore parent case status should still be New

parent_case.Status='Closed';
update parent_case;

System.assertEquals(parent_case.Status,'New');
 

delete SRchild_case0;
delete SRchild_case;
delete parent_case;
}
}
 
 
 
 

 

Hello all,

I'm working on a project to give users the ability to create secure notes on any object.  The design is going fine except for the last piece: how to encrypt or obfuscate the note so that even administrators browsing cannot read them.

 

Apex does not do encryption (only hashing), so I have to come up with a method for obfuscating the note.  

 

I can do this with JavaScript, but how do I:

1. Obfuscate some text in JavaScript and then save it back to a salesforce field?

 

A secondary question, is there any other way anyone can think of to do this other than javascript?

 

Thanks,

C.

We're having a problem with handling a fault coming back from a Callout.  We are getting an exception stating we received a SOAP fault (we want the fault for the purposes of testing error handling), and I'm unclear on the real problem-- is the problem with our ability to get to the fault data, or did we create a problem with the content of our fault, hence triggering the exception.

 

I have a couple of questions:

 

1) Normally, does any fault throw an exception, or would a fault appear in the response?  I haven't found anything in the documentation that explicitly explains how faults are handled.

 

2) What other methods and members are available for me to examine in the CalloutException other than the common methods (getCause()/getMessage())?  Again, the documentation is vague, and I can't find anything absolute that says CalloutException exactly what CalloutException provides (e.g. like JavaDocs for the APIs).

 

3) The exception we recieve manages to display the standard faultcode and faultstring, and the faultstring appears as what is provided by the exceptions's getMessage() method.  This gives me the sense that the fault is completely successfully parsed, or I'm getting a really poor error message from the API.  Below is the full SOAP Fault we receive.  I read another forum message indicating namespace prefixing was required for items in the detail of the message.  As far as I can tell, this is legal syntax, and other tools importing this WSDL handle faults properly: 

 

 

<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
  <S:Body>
    <ns2:Fault xmlns:ns2="
http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns3="http://www.w3.org/2003/05/soap-envelope">
      <faultcode>ns2:Client</faultcode>
      <faultstring>"IGI0120:CBM5644:The Telephone Number Area Code is incorrect."</faultstring>
      <detail>
        <AAAError:AAAError xmlns="AAA" xmlns:AAAError="AAA">
          <AAAError>
            <RC>1495</RC>
            <MQQ>1</MQQ>
            <MSGNO>1495</MSGNO>
            <MSGTEXT>"IGI0120:CBM5644:The Telephone Number Area Code is incorrect."</MSGTEXT>
          </ICOMSError>
        </AAAError:ICOMSError>
      </detail>
    </ns2:Fault>
  </S:Body>
</S:Envelope>

Does anybody know of a way to perform field level validation in VisualForce.   I would like to enter a field value and if there is an invalid entry, I would like to display an error before the page proceeds to the next field. 

Hi,


Does anyone have an idea of how to work around the string limits in this case.

 

I have an apex code that reads a document object. I can get that fine, and it's a CSV fine. I then want to run through the document and parse it line by line. I can get the body into a blob with document.body, then get the body as a string with the body.toString() method.

 

But the problem here is the limits on a string are 100,000 characters. If my blob is larger than 100,00 characters, then what can I do? I don't have to have it all at once. A loop is find but I don't see a way to do blob.tostring(start byte, end byte).

 

Any ideas?

 

Thanks!

Hey,

I have an apex class that is called when i send an email in my application,
sometimes the class throw this error message:

Attempt to execute a class that never successfully parsed: Static initialization: Myclass.cls

It doesn't happen every time i call the class.
I have done some research at this forum and the apex docs but this message are not listed.

anyone knows what means ? and how to fix it?

thanks,
Hi fellow developers,

I'm trying to emulate the sample in the vf dev guide (Adding Custom List Buttons using Standard List Controllers), but with a twist: using a detail from a master-detail (Account = Master, detail = Flavor_Request__c).

I have both the Apex Class and controller similar to the example in the dev guide:

Code:
public class OpptyFlavorListButton
{
    public OpptyFlavorListButton(ApexPages.StandardSetController controller) {
            controller.setPageSize(10);
    }
}

<apex:page standardController="Flavor_Request__c" recordSetVar="flavors"
    tabStyle="Flavor_Request__c" extensions="OpptyFlavorListButton">
<apex:form >
    <apex:pageBlock title="Edit Status" mode="edit">
        <apex:pageMessages />
        <apex:pageBlockButtons location="top">
            <apex:commandButton value="Save" action="{!save}"/>
            <apex:commandButton value="Cancel" action="{!cancel}"/>
        </apex:pageBlockButtons>

        <apex:pageBlockTable value="{!selected}" var="f">
            <apex:column value="{!f.name}"/>
            <apex:column value="{!f.Request_Type__c}"/>
            <apex:column value="{!f.Sample_Size__c}"/>
            <apex:column headerValue="Status">
                <apex:inputField value="{!f.Status__c}"/>
            </apex:column>
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:form>
</apex:page>

 



The buttons are added to the appropriate layouts, however, I keep getting the following errors:
1. Invalid variant 'parent': value 'Account'
2. Invalid variant 'parent': value 'Opportunity'

I get error #1 when trying this from the Account page (related list of flavors)
I get error #2 when trying this from the Opportunity page (related list of flavors)

I'm hitting these errors as the System Administrator who wrote the code...

Any feedback/suggestions would greatly be appreciated.

Thanks,
Larry


Message Edited by Legerdemain on 12-04-2008 08:38 PM

Message Edited by Legerdemain on 12-04-2008 08:39 PM