Getter Method Order and Visualforce Pages

August 24th, 2010

I recently had a Visualforce page that was working perfectly for over two years. This thing was solid, a workhorse, one of the most used pages I have ever created. Then one day it stopped working as expected. It wasn’t a big deal really, simply an warning message wasn’t being displayed to the users. All unit tests still passed and I had made no major changes to the code. What the crazy I thought?!? The only thing I may have done at some point in the past was make minor changes to the the layout or updated the page API version.

The way I architected the page from the very first day created a ticking time bomb that would show up two years after the page was created. Enter the world of Visualforce page generation and getter method order. Before I get to the juicy good stuff I’ll briefly explain how Visualforce pages are created…at a very high level.

1) Apex constructor code is run
2) Page generation begins
3) As the page starts to convert Visualforce markup to html it will see certain markup ( {!showWarning} ) on the Visualforce page related to variables in the controlling class
4) The page generation engine will be like, “Yo, controller, what up? Send me the variable showWarning” or “Hey, controla-homie, send me the list of accounts”. This is the GET of a specific variable.
5) The page generation engine can then embed the variable on the page as html output or perhaps use it to determine if pieces of the page should be rendered at all, such as a warning message
6) HTML is then fully created and sent to the browser making the request

Next lets take a little quiz. If you think quizzes are lame (I do) pretend this is a challenge of intellect that if solved will save the world from invading aliens. Ya, that’s a little weird and makes my sound crazier than I thought it would but let’s run with it. Take a look at the the code below. First the page:

<apex:page Controller="GetOrder">
 
	<apex:pageMessage title="Large Account Alert" severity="warning" strength="1" rendered="{!showLargeAcctWarning}"/>
 
	<apex:pageBlock >
		<apex:pageBlockTable value="{!accounts}" var="a">
			<apex:column value="{!a.Name}"/>
			<apex:column value="{!a.Name}"/>
			<apex:column value="{!a.NumberOfEmployees}"/>
		</apex:pageBlockTable>
	</apex:pageBlock>
</apex:page>

And then the class:

public class GetOrder{
 
    public Boolean showLargeAcctWarning {get; set;}
    List<Account> accts;
 
    public List<Account> getAccounts(){
        if(accts == null){
            accts = new List<Account>();
 
            for(Account a : [Select Id, Name, NumberOfEmployees from Account limit 5]){
                accts.add(a);
                if(a.NumberOfEmployees > 5){
                    showLargeAcctWarning = true;
                }
            }
        }
        system.debug(showLargeAcctWarning);
        return accts;
    }
}

Do you see anything wrong? If not, then you are a n00b and I laugh at your n00biness while I sit upon my white stallion. Just kidding, I’ve been working with Visualforce since the beginning and I only recently realized what is wrong with the code above. Not kidding about sitting upon a white stallion though. If you do see a problem you are officially a l337 \/I5U4lf0(3 haxor.

So what is the problem? The page should display a warning message if the Number of Employees is greater than 5, right? Wrong! Well… maybe. You can view the actual page above be clicking here. You will see the warning message is not displayed but the list definitely has accounts with more that 5 employees? What is going on here…..queue the Twilight Zone music (just to be clear, the Twilight ZONE, not the dumb sparkly vampire Twilight), you have just crossed over into the Visualforce Getter Zone, dun dun dunnnn.

Let’s take a look at the debug log to see what is happening. First let’s check the debug statement above to see if the show warning variable is being set to true.

screenhunter_07-aug-24-10-40

Hmm, the variable is definitely being set to true so why isn’t my warning being displayed. Let look a little deeper in to the log. Using the new Apex CSI log lets filter down to our get methods.

screenhunter_08-aug-24-10-42

If we look at this closely we will see the get method for the showLargeAcctWarning is called before the getAccounts methods. So when the page rendering and asks for the show warning variable it is false as it has not yet been set to true because the getAccounts method has not even executed yet.

So how to resolve this issue. Enter our knight in shining armor, the constructor. Rather than letting the page determine the order of get methods lets run them ourselves in the class constructor. When you execute code in the constructor it is guaranteed to run before the page generation process begins. Below is the updated code.

public class GetOrderFix {
 
    public Boolean showLargeAcctWarning{get; set;}
    List<Account> accts;
 
    public GetOrderFix(){ //This is the contructor, same name as class, will run before page generation begins
        getAccounts();
    }
 
    public List<Account> getAccounts(){
        if(accts == null){
            accts = new List<Account>();
 
            for(Account a : [Select Id, Name, NumberOfEmployees from Account limit 5]){
                accts.add(a);
                if(a.NumberOfEmployees > 5){
                    showLargeAcctWarning = true;
                }
            }
        }
        system.debug(showLargeAcctWarning);
        return accts;
    }
}

Now the getAccounts method is will run before page generation begins and when the generation engine asks for the show warning variable it will have a value of true. You can see the fixed paged here.

What can make these types of issues so hard to track down is that the order in which get methods are called have no official or documented process. What seems like minor change to your Visualforce markup could change the order in which get methods are called and this could cause your page to stop working properly. What I have started to do, and is probably a best practice I should have always been doing, is setup all initial variables, lists, etc in the constructor. Do this and it should minify your problems… at least with getter method order.

Seattle Force.com User Group – August 2010

August 5th, 2010

Major late notice here but today is a Seattle Force.com user group. If you are are Force.com pro or a n00b looking for more information about this platform swing by.

WHO: Me, you, and some other cool peeps.

WHAT: Discuss force.com related topics, questions, and technologies

WHEN: Today, August 5, 2010 4:00PM

WHERE:
West Monroe Partners
1215 4th Ave, Suite 1010
Seattle, WA 98161

WHY: See WHO & WHAT

This month’s meeting will be an open forum for any questions and discussion topics you may have.

Why I Can’t Buy the iPhone 4 (but really want to)

July 16th, 2010

This phone is cool, very cool. I really want it and when the first reviews started to come out I knew this would be my next phone. Enter the antenna issue.

Shortly after launch reports started to surface that touching the little back band in the lower left corner would significantly reduce cellular reception. Worst case the iPhone would go from five bars to no service. This was concerning. When the 3G came out there were reports of yellow tinted screens but this turned out to be a non issues so I thought I would wait it out to see what happens. Yet the reports continued to roll in.

We all know what happens next and if you are reading this I don’t need to go in to detail so here is the short version.

1) Steve jobs says “don’t hold it that way”
2) Antenna issue continues to explode across web
3) Consumer reports can’t recommend phone
4) Antenna issue hits mainstream news
5) Apple hold press conference regarding antenna issue

Today Apple had their press conference. Going into the conference I was hoping for a miraculous hardware fix but I figured they would offer a free bumper. I thought I would be happy with this and probably get the phone. They did offer free cases to customers but I still can’t bring my self to buy this phone. Here is why.

Apple Doesn’t Get It
People keep referring to this issue as the ‘Death Grip’. This makes it sound like you have to squeeze the life out of this phone to see the problem. In reality it should be called the ‘Pinky Touch of Death’ as it literally takes one finger to cause this problem. See video here. Apple then went on to show the death grip effect the reception on other smart phones. Cool, I don’t disagree with their findings but I’m pretty sure not one of those phones will loose that much signal with the touch of a single finger. I know my iPhone 3G doesn’t.

Ryan Block from gdgt.com specifically asked about this issue and Apple completely beat around the bush not even coming close to answering the question.

Q: How does touching the corner with a single finger seem to cause this issue? It’s not just a grip, it can just happen by touching a single finger.

A: Your body is a pretty effective signal absorber. When you make contact with that phone, its performance in contact with you is less than it’s freespace performance. It’s a way to attenuate the signal by some amount.

Huh? This question is what the entire press conference should have revolved around.

Stats are Wack
Apple says only .55 percent of users called support complaining of reception issues. Most users probably don’t even know about the antenna issue and probably wouldn’t call support if they dropped one or two more calls then normal. They would probably blame AT&T and then go on their merry way.

Apple also says the return rate of the iPhone 4 is much less then that of the 3GS but the 30 day return period is still open. It would be interesting to see how many iPhone 3GS were returned within three weeks. If I was going to return a phone I’m pretty sure I would wait until the last week so that I gave myself enough time to try out all features of the phone. I would guess return rates increase closer to the end of the 30 day return window.

Amount of additional dropped calls of iPhone 4 over 3GS is less than 1 per 100. Ok, I am going to guess this is .999 because if was anything less they would have said less than 0.5 per one hundred. This is a totally useless stat because we don’t know how many calls are being dropped. If the 3GS drops 1 per 100 then the iPhone 4 drops 2 per 100. Uh… this could potentially be a 100% or more increase. As you can see this stat was pure marketing.

September 30th
This date is key. When asked if the free case offer will extend beyond this date Jobs said they “Will evaluate” and “I have no idea what solutions may come up”. He is the CEO of multi-billion dollar company, I’m pretty sure he has some ideas. This response indicates one thing for me. They are working on a hardware fix that may or may not make it out by September 30th. They need to flush out current inventory and that seems about the right amount of time for this to happen.

There is simply to much shady behavior by Apple regarding iPhone 4. They provided a ‘solution’ but didn’t really address the main issue (see Q&A above). It is pretty clear to most people this is a design flaw that was missed in testing due to the 3G-esque cases that were used. The testers never actually touched the phone. This problem was eventually discovered before launch but it was too late for a hardware fix and hence the bumper at launch. Is this a major design flaw, no. Does this design flaw affect everyone, no. Would it affect me, probably not.

In the end I still want this phone, bad, but I just can’t spend thousands of dollars on a phone and a service contract if it doesn’t work as well as a cheap Nokia. Apple’s attitude and response regarding this issue has also sort of rubbed me the wrong way. At the same time I understand they can’t admit a design flaw as this would destroy sales and share price.

This phone will continue to fly of the shelves but I will be eagerly awaiting the 30th of September.

Categories: Technology 4 comments

Choose My Next Blog Posts

July 13th, 2010

I’ve got a pretty decent back log of super awesome and overwhelmingly exciting blog posts. Some related to force.com and some not. I’ve got so many that I can’t decide what is next so I need your help. Below are a few of the top choices. The only teaser is the title of the post.

On this poll you can select two options so make your votes count!

What should be my next blog post?

View Results

Loading ... Loading ...

IP Address Geolocation with Force.com

July 9th, 2010

If you have a website knowing where your visitors are located is a powerful feature. For starters it makes your website appear to have super powers if it automatically knows where the user is from. You can do all sorts of cool stalker stuff, and by cool stalker stuff, I mean customizing site content based on the visitors location.

iplocation

There are several different ways to figure out where a visitor is located, each with their pros and cons. The two main ways are IP address tracing and HTML5 geolocation. There is a great guide on developer.force.com about HTML5 geolocation that you should check out. HTML5 is all the rage these days but both methods have their advantages. In my testing HTML 5 was more accurate but it requires input from the user. The user must explicitly grant permission for the browser to find their location. Depending on the use case this may or may not work. IP address tracing on the other hand requires no input from the user and can be done completely behind the scenes unobtrusive to the user. The down side is that it is not as accurate. Another issue to consider is that some users (think your parents) will not want to click a button that gives away the location because they may think the internet is full of scams and the website will use this information to track them down and steal their identity….just sayin. So these are the two primary methods and choosing one really depends on the type of application you are building.

Read more…

Serious Force.com Cookie Security Issue

June 25th, 2010

UPDATE:
Before you read the update I would encourage you to read the original article below first.

This is not a bug but an expected issue with the way force.com sites pages are cached. For some reason in my crazy head I thought the only items cached on pages where the html structure, images, css, etc. I thought that even on cached pages the controller would execute on every load of the page. This is not true. The controller will only execute once when a page is not cached. Any subsequent visits while the page is cached will not cause the controller to execute. So if you are populating dynamic data on the page with Apex it will stay there for the next 10 minutes.

This becomes a major issue with pages that depend on cookies and customizing the site content per visit.

I’ve recommended that salesforce.com update their documentation with two big red bold updates:
1) Cached pages will not execute the controller on load
2) Pages that use cookies to display dynamic data should never be cached

I hope this is helpful to someone out there as I definitely learned something today.

Additional info can be found here: dev board post.

-Jason


Original Post:

I have discovered a major bug with the new cookie feature released in the Summer 10 edition of salesforce.com. Let’s get straight to the point. Cookie data is being passed across different browsers, different computers, and different users. Yes, you heard this right. Sounds unbelievable so I created a video that shows this happening. Clearly this is a major issue if you are storing session or personal information in cookies.

Before anyone rips into me for blogging about what could be a very significant security issue I have already notified salesforce.com and it is a high priority issue. I also believe it is best to get this information out to other force.com developers before they build something that depends on this functionality and this issue causes major problems for them.

At this point I highly recommend not using the new cooking feature until more information about this issue or a fix is released.

Page:

<apex:page controller="CookieBug" expires="60">
    <apex:form >
        <apex:inputText value="{!input}"/>
        <apex:commandButton value="Update Cookie" action="{!updateCookie}"/>
    </apex:form>
</apex:page>

Controller:

public class CookieBug{
 
    public String input {get; set;}
 
    public CookieBug(){
        //Autofill input based on cookie value
        Map<String,Cookie> cookies = ApexPages.currentPage().getCookies();
        if(cookies.size() > 0){
            if(cookies.get('myCookie') != null){
                input = cookies.get('myCookie').getValue();
            }
        }
    }
 
    public void updateCookie(){
        List<Cookie> cookies = new List<Cookie>();
        Cookies.add(new Cookie('myCookie',input,null,15552000,false));
        ApexPages.currentPage().setCookies(cookies);
    }
}

Dear Apple: Please Add Image Stabilization to iPhone Video

June 21st, 2010

There was a time long ago when home made videos where smooth and stable. The main reason for this was the size of the camera. Look at this bad boy…

vhs

While the quality of the video was horrible it was usually pretty stable and not bouncing all over the place. For starters it would literally rest on your shoulder which is a pretty solid platform. It is also physically large and therefore requires a lot more movement to cause a shaky recording. Over the years this has become more and more of a problem as cameras have become smaller and smaller.

Read more…

Categories: Technology 4 comments

Seattle Force.com Developer Meeting – June 2010

May 28th, 2010

UPDATE: I’ll be demoing how to authenticate with OAuth using Force.com and how this can be used with the Twitter API.

It’s that time again for the Seattle Force.com Developer Meetup. Details below…

When: 6/3/2010 4:00 PM – 6:00 PM Pacific Daylight Time
Where: 7 Simple Machines Office
Subject: Seattle Force.com User Group Meeting – June 3
Comments: This month, our meeting will be held in a new venue. 7 Simple Machines has offered up a change in venue for us in June.

Location:
Their office is located at:
800 Maynard Ave S, Suite 208
Seattle, WA 98134

http://www.7simplemachines.com/views/ContactUs.aspx

As always, bring your any ideas and questions to the meeting to discuss with everyone!

Dear Microsoft, Please sue me.

May 20th, 2010

As you’ve probably heard Microsoft is suing salesforce.com over nine patents Microsoft holds. One would probably assume these patents are for some ultra complicated algorithm or computer process hidden within the depths of top secret Microsoft source code. Well you’d be wrong, really wrong.

Let’s take a look at just a few of the patents they are suing over.

1) System and method for providing and displaying a web page having an embedded menu
2) Method and system for stacking toolbars in a computer display

Wait, what?!?! They own a patent on a flipping web menu!?! Yes, it would appear so. So if you have ever created or implemented a menu on a web page you are infringing on a Microsoft patent. See the menu across the top of this page? Yup, I’m a rebel.

3) Aggregation of system settings into objects

I’m not patent lawyer but I’m pretty sure this one means you can’t store some type of system setting (aka text/boolean/etc) value in an object. I didn’t read through the entire patent filing but I’m guessing ‘object’ refers to a class object or database object. So if I can’t store system settings in any of these two places where on earth can I store them! Maybe Microsoft thinks there is some pixie dust magic land where settings can be stored.

4) Timing and velocity control for displaying graphical information

This is lawyer speak for a time delayed tool tip. If you put your mouse over an icon, stop, wait 300ms, and show a tool tip you are busted! So the thousands of websites that have implemented this type of functionality are infringing on a Microsoft patent.

These are just a few of the patents Microsoft is suing over and the others I didn’t list are just as ridiculous.

What is all this madness? Well, there is a lot of crack smoking going on here. First we have the US Patent office smoking crack and approving ridiculous patents like these. Secondly, we have Microsoft smoking a little something suing over these absurd patents. If they were really concerned about protecting their intellectual property they would be suing a lot more people that have implemented these types of features, but they aren’t. They are suing a company that is a direct competitor that is innovating faster and more successfully than Microsoft in the given space. It’s is clear Microsoft is using it’s size and money ($250B) to take on a smaller company like salesforce ($10B) in the courtroom rather than on the keyboard which is just sad.

Some will say, “But Jason, you are biased supporter of salesforce.com”. Yup, that is probably true, but Microsoft isn’t really suing salesforce.com. They are suing all of us. Where “us” is any web developer or smaller company that has created the functionality mentioned above.

Seattle Force.com Developer Meeting – May 2010

May 5th, 2010

I really need to get better about posting these earlier but if you are able to make it to the Seattle Force.com Developer Meeting we would love to have you stop by. All are welcome, pros and noobs. Below is the info regarding the upcoming meeting.

Our next Force.com user group meeting will be held on Thursday, May 6th.

Time: 4:00pm – 5:00pm PDT
Location: WMP Seattle
1215 4th Ave, Suite 1010
Seattle, WA 98161

Richard Saunders and Evan Callahan will be presenting their Client Management System.

As always, we are looking for people to present at our future meetings, so please let me know if you would like to share something with the group.

The Best Way To Eat An Orange

May 3rd, 2010

There are many ways to eat an orange. This is the best way.

1) Find a delicious looking orange.
img_0288 Read more…

Categories: Life 7 comments

Dreamforce 2010 and jQuery

April 22nd, 2010

I finally got around to submitting a paper for Dreamforce 2010. The title…..wait for it……wait…..”Take Your Visualforce Pages to the Next Level with jQuery & jQuery UI”.

Visualforce is great for building solid and scalable web apps. Where it falls short is enhanced web 2.0 (I actually cringe at this term) usability. It lays a solid foundation but lacks slick UI features that users of today’s web expect and will soon demand. jQuery and jQuery UI make it incredibly easy to add enhanced functionality. In this presentation I will show best practices, pitfalls to watch out for, and of course show off some slick apps that use jQuery. What this won’t be is an advanced deep dive on jQuery. This presentation will show anyone who has a little web and Visualforce experience how to apply jQuery to projects they are working on as soon as they get back to work.

Salesforce has seriously pushed Flex the last few years but I guarantee you that 90% of the time I can build the exact same functionality in less lines of code with jQuery. It’s time to show some diversity at Dreamforce. Simply look at this trend for google searches.

jQuery is the most popular javascript library out there today and it even beats Adobe Flex in terms of people looking for more information. If Flex gets a dedicated session at Dreamforce so should jQuery!

If you are a regular reader of this blog you know I’ve got a quirky style with a touch of humor thrown in there. I’ll be sure to carry this over to my presentation unless salesforce makes me be all serious and professional, BORING.

If you like this idea please hit the link below and cast your vote.

Take Your Visualforce Pages to the Next Level with jQuery & jQuery UI

Auto Scrolling Salesforce Dashboard

April 20th, 2010

It is the slickness. I hope to have more info on what this is all about in an upcoming post but couldn’t resist posting this little teaser.

Override Visualforce Help Link with jQuery

April 12th, 2010

Popups suck. Everyone hates them, but it wasn’t always like this. There once once a time long long ago when popup actually displayed relevant information related to the site you were browsing. This was in a time before tabbed browsing and advertising behemoths. Then came advertising on the web and popups galore. Here begins the downfall of the popup. It wasn’t long before popups became incredibly annoying and web users closed them without a glance. Popups were used, abused, and are now the scum of the internet user experience.

helplink

So why this brief, and quite frankly masterfully written story on the history of popups? The help link you can add to Visualforce pages is a popup. There are a few reasons I don’t like this. One, it is a popup, and people hate popups. Two, you also have to manage an entirely separate page for what could be a very simple help dialog. And 3, it just doesn’t provide a good user experience. It feels so 1999. Read more…

Salesforce Seizure

April 6th, 2010

Here is a little jig i like to call the “Salesforce Seizure”.

Seriously, if you have photosensitive epilepsy I wouldn’t watch this.

Looks like it only happens in Firefox, possibly related to this and this.