Search
Twitter

Entries in apex code (6)

Wednesday
May012013

Explore the Different Messaging Options in VisualForce (Part 2)

This post begins where Part 1 left off; continuing to explore the different messaging options in VisualForce.

  • apex:message allows for field-specific errors. Let's look the code below and see how it renders:
<apex:page controller="TestMessageController">
    <apex:form >
        <apex:outputLabel value="Test String" /><apex:inputField value="{!test.Name}" id="test"/>
        <br/><apex:message for="test"/>
    </apex:page>
 
public class TestMessageController{
    public Account test {get;set;}
    public TestMessageController(){
        test = new Account();
        test.Id.addError('Correct');
        test.Name.addError('Wrong');
 
    }
}
  • The last option we have is apex:messages, which is similar to apex:message, except that it displays all errors in a list. Let's incorporate the apex:messages in the previous code and see how it renders:
<apex:page controller="TestMessageController">
    <apex:messages />
    <apex:form >
      <apex:outputLabel value="Test String" /><apex:inputField value="{!test.Name}" id="test"/>
      <br/><apex:message for="test"/>
    </apex:form>
</apex:page>
 
public class TestMessageController{
    public Account test{get;set;}
    public TestMessageController(){
        test = new Account();
        test.Id.addError('Correct');
        test.Name.addError('Wrong');
    }
}
Friday
Apr262013

Explore Different Messaging Options in VisualForce (Part 1)

VisualForce offers several options when it comes messages such as a warning of an error. Today, I'm going to explain the key differences between the messaging options in VisualForce:

  • apex: pageMessage is used to display a single custom message using the Salesforce formatting. With this one, you have the option to control and specify the "Severity" (the displaying of the message box) and the "Strength" (size of the box). Check out the below code for an example:

 <apex:page>
    <apex:pageMessage summary="This is a pageMessage" severity="error" strength="1"/>
</apex:page>
  • Another option is to use apex: pageMessages; which is used to concurrently display the custom messages entered by the developer and those generated by Salesforce. See the example in the code below and how it renders:
 <apex:page controller= "TestMessageController">
  <apex:pageMessages />
</apex:page>
 
public class TestMessageController{
    public TestMessageController(){
         ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'This is apex:pageMessages'));
         ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'This is apex:pageMessages still'));
         ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'This is apex:pageMessages info'));
         ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'This is apex:pageMessages warning'));
    }
}
Friday
Dec072012

Apex Unit Test

 

SALESFORCE APEX CODE LIMITS

I’ve been developing code on various platforms for years, but lately I’ve been working on Saleforce’s proprietary language apex.  If you know java then apex should not be that strange to you at all.  That is pretty much where the similarities end.  Being a cloud based company, Salesforce enforces all sorts of rules and limits on your code. You’ll quickly learn how to be a smarter developer when you have to think about these limits. 

 Salesforce requires that you have 75% coverage on all code you write.  If you fall below this number then you cannot deploy any of the code you have written.  Coverage just means that if you have piece of code that says “hello” you must test it and verify that it says hello.  If not, every line is counted against your overall number.  You cover your code by writing the infamous unit tests.

Rewind to last month and it is really easy to forget or ignore writing test cases.  You can only get away with this for so long before your coverage starts gradually depleting.  After much effort I did a good job addressing a lot of missing coverage.  One thing that became really evident is that I was failing to do a negative test.  A negative test is just what it sounds like.  You pass in junk data and expect a failure.  This proves that your code not only works, but it handles exceptions correctly.  Below I have some sample code that illustrates both a positive and a negative test case.

 

           static testMethod void testremoveFormulaFieldsSchema()

           {

             

              //Negative Test of formula field schema

              Map<String, Schema.SObjectField> targetSchemaFieldMap = null;

              targetSchemaFieldMap = removeFormulaFieldsSchema(targetSchemaFieldMap);

              system.assert(targetSchemaFieldMap == null, 'We did not get a null schema ');

             

              //Positive Test of formula field schema

              targetSchemaFieldMap = Schema.SObjectType.Account.fields.getMap();

              targetSchemaFieldMap = removeFormulaFieldsSchema(targetSchemaFieldMap);

              system.assert(targetSchemaFieldMap != null, 'We failed to get the account schema ');

             

     }

As you can see above I call the same method “removeFormulaFieldsSchema” in both scenarios but in the first test I am passing null as a parameter.  This will test our code on how I handle exceptions and I expect nothing back after the code is executed.  In the second example I would expect data to be returned to me.  I also included the actual method I was testing for clarity below.  These two tests gave me 100% coverage in my new method and I was a happy person.

 

       public static Map<String, Schema.SObjectField> removeFormulaFieldsSchema(Map<String, Schema.SObjectField> schemaMap)

       {

         Map<String, Schema.SObjectField>  resultschema = new Map<String, Schema.SObjectField>();

 

              try

              {   

                for(String field : schemaMap.keyset())

                {

      

                  Schema.DescribeFieldResult desribeResult = schemaMap.get(field).getDescribe();

      

                  if (!desribeResult.isCalculated())

                  {

                    //Field is not a formula field so it is added to the schema.

                    Schema.SObjectField fieldS = schemaMap.get(field); 

                    resultschema.put(field,fieldS);

                  }

               }

                 return resultschema;

              }catch(exception e)

                {

                     return schemaMap;

                }

}

I hope this helps some apex coders out there to understand the importance of getting your unit test written with your new code.  It was a lot of effort to go back and fix all the omissions but it paid off.  I even found some bugs in the code that I didn’t expect.  Who would have thought that unit testing actually works and isn’t just some evil chore Salesforce imposes on us.

 

photo credit: <a href="http://www.flickr.com/photos/epospisil/5596869376/">epospisil</a> via <a href="http://photopin.com">photopin</a> <a href="http://creativecommons.org/licenses/by-nc-nd/2.0/">cc</a>

Tuesday
Oct092012

Fix System Query Exception Error

 

What the Heck is This? "System.QueryException: List Has No Rows for Assignment to SObject"

So I was quering Account a = [Select name from account where id=: strld];

and an exception was thrown: System.QueryExceptoin: List has no rows for assignment to SObject.

 

Here is the mistake I made and how to fix it:

List<Account>lst = [Select name from account where id=: strld];

Sunday
Mar062011

Intro to Force.com Programming

I love how Salesforce.com thinks! In celebration of reaching 1,000,000,000 lines of Apex code, they celebrate by teaching more programmers about how to join up and get started. Blink and you might miss it though--the webinar is THIS week, Wednesday, March 9. You can choose between 7am PST or 10am PST if they are both still available when you register.

If you or someone in your office would benefit from the basics of Apex-the programming language for the Force.com platform, then act fast and register. The list of instructional goals during the webinar are introductions to the following topics:

  • Apex syntax, and the contexts in which you can use the language
  • Apex's database integration and use in programming UI controllers
  • The testing and code coverage facilities
  • Other uses, such as web services and asynchronous execution

We have a new developer registered as well as a couple of people who are not developers but need to understand a little more about the capabilities of Apex. Oh, and maybe one of us will win the new iPod Touch that is being given away!

Monday
Sep202010

Regular Expressions in Apex Code

Every once in a while it's very helpful to use regular expressions in your code. The problem is that resources and examples are often scattered. I wanted to give two simple examples of how you can write and test regular expressions in your Apex code inside Salesforce.com.

Return all the numeric characters in a string via regular expression

For the sake of quickly writing and testing this, I've just created a new Lead trigger that runs before insert. I've then set a test input string "input" and I'm using a Pattern object to return the matches in a new string "test". I then print a system debug statement so that I can look in the debug logs to see my results.

trigger myLeadTrigger on Lead (before insert) {

    string input = 'a3f45qq456';

    for (Lead l : Trigger.new)
    {
        //instantiate new Pattern object        
        Pattern p = Pattern.compile('[^0-9]');
        

        //return a string that contains only numeric values from 0-9 from my original input
        String test = p.matcher(input).replaceAll('');
        

        //print a debug statement with my test results
        System.debug(test);

    }

}

Ouput from the debug log shows us that this is working:

16:5:8.981|USER_DEBUG|[12,9]|DEBUG|345456

As you can see, "345456" are the alpha chars from the original string "a3f45qq456".

 

Return all the alphabetical characters in a string via regular expression

For the sake of quickly writing and testing this, I've just created a new Lead trigger that runs before insert. I've then set a test input string "input" and I'm using a Pattern object to return the matches in a new string "test". I then print a system debug statement so that I can look in the debug logs to see my results.

 

trigger myLeadTrigger on Lead (before insert) {

    string input = 'a3f45qq456';

    for (Lead l : Trigger.new)
    {
        //instantiate new Pattern object        
        Pattern p = Pattern.compile('[^a-zA-Z]');
        

        //return a string that contains only numeric values from 0-9 from my original input
        String test = p.matcher(input).replaceAll('');
        

        //print a debug statement with my test results
        System.debug(test);

    }

}

 

Ouput from the debug log shows us that this is working:

6:46:21.762|USER_DEBUG|[14,9]|DEBUG|afqq

As you can see, "afqq" are the alpha chars from the original string "a3f45qq456".