Archive

Archive for the ‘Visualforce’ Category

Getter Method Order and Visualforce Pages

August 24th, 2010 11 comments

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.

Categories: Apex, Visualforce

Choose My Next Blog Posts

July 13th, 2010 2 comments

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 ...
Categories: Apex, Visualforce, salesforce

IP Address Geolocation with Force.com

July 9th, 2010 No comments

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 8 comments

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);
    }
}

Seattle Force.com Developer Meeting – June 2010

May 28th, 2010 No comments

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!

Seattle Force.com Developer Meeting – May 2010

May 5th, 2010 No comments

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.

Categories: Apex, Visualforce

Dreamforce 2010 and jQuery

April 22nd, 2010 8 comments

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

Categories: Visualforce, jQuery, salesforce

Override Visualforce Help Link with jQuery

April 12th, 2010 9 comments

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…

Categories: Visualforce, jQuery, salesforce

Salesforce Seizure

April 6th, 2010 2 comments

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.

Categories: Visualforce, salesforce

Seattle Force.com Developer Meeting

March 31st, 2010 No comments

There is a another force.com developer meeting for Seattle coming up this Thursday. If you are in the Seattle area and want to meetup or learn more about developing on the force.com platform please stop by.

Just a friendly reminder that this Thursday, April 1st at 4:00pm will be the our monthly meeting.

The meetings as always will be held in the West Monroe Partners office located at:

1215 4th Ave, Suite 1010
Seattle, WA 98161

This session will be an open forum so bring any questions, problems, and/or issues you have so we can discuss with the group.

If you have something cool you’d like to show off or present let me know and we can arrange for you to speak at one of the upcoming sessions.

Serious Performance Issues with New Salesforce UI CSS

March 24th, 2010 5 comments

To be honest I sort of feel bad about writing this post. I have already reviewed, ranted about, and tweaked the new salesforce.com UI, but here comes my third consecutive post related to this. I promise my next post will be about something super cool and radtaculous you can do with salesforce!

We hoped to enable the new UI in the next few weeks and like any good admin or developer I checked all of our custom Visualforce pages to make sure everything still looked and worked correctly. Everything started out so smooth. Everything was looking good. My basic, and for the most part, static Visualforce pages seem to work fine.

Read more…

Improve the New Salesforce UI with Greasemonkey

March 17th, 2010 8 comments

In my last post (you can read it here) I was ranting like an angry hippopotamus about the new salesforce.com UI released with Spring 10 and what I think it should look like. This follow up post will show you how to make the changes I proposed in that post a reality.

Before we work the magic and make the new UI even better I want to expand on some of my thoughts regarding the new UI. Some may say it is “change” and change is hard, you just need to get used to it. Not true. Change should never be hard. Change should be something better. It should be a measurable improvement over the previous version. A perfect example of this was the recent redesign of cnn.com. This was a massive improvement and nearly everyone everyone applauded the changes. Change was easy because it made our user experience better. I don’t hate the new salesforce UI. I don’t even not like it. There is just something about it that doesn’t feel right. I can’t place my finger on it but I think the changes I’ve made below will make a huge improvement. Blah blah blah, enough pointless blabbering, let’s get to the good stuff.

Since the original post I have had some time to get comfortable with the new UI and several of the changes I initially proposed probably aren’t needed.  My first stab at changing the UI was also a bit bold, too bold. I took my changes of the UI to the extreme to really emphasize the direction I think the new UI needs to move. In reality the changes needed are much softer. What it came down to in the end was eliminating the massive amount of white space in the record detail section and bringing back the old style page block section separators. So how do we do this? Greasemonkey to the rescue!!!!

The first ingredient of awesomesauce is to install the Greasemonkey plugin for the Firefox browser. You can download that here. Greasemonkey allows you customize websites with fancy pants JavaScript.


Read more…

Categories: Technology, Visualforce

The New Salesforce UI Should Look Like This

March 11th, 2010 19 comments

UPDATE: See the follow up post here: Improve the New Salesforce UI with Greasemonkey

The new salesforce.com UI has been rolled out to all instances as of March 6th and the feedback is starting to roll in. Based on the feedback I have heard, direct and indirect, is that there appears to be four groups of people. A few people that love it, a few people that like it, a lot of people that are undecided, and a lot of people that don’t like it. This is probably not the distribution of feedback salesforce was hoping for.

Read more…

Categories: Technology, Visualforce

Seattle Force.com Developer Group

March 3rd, 2010 No comments

Heads up that if you are a Force.com/Salesforce developer or want to learn more about force.com development in the Seattle area there is a meeting this Thursday, the 4th.

The meetings as always will be held in the West Monroe Partners office located at:

1215 4th Ave, Suite 1010

Seattle, WA 98161

When:  Thursday, March 4th, 2010

Start Time: 4:00 PM

This session will be an open forum so bring any questions, problems, and/or issues you have so we can discuss with the group. If we finish early, we can maybe grab a beer at one of the local bars downtown.

If you are interested even a little please stop by.

Categories: Apex, Technology, Visualforce

Add Slider to a Visualforce Page with jQuery

February 16th, 2010 17 comments

A while back Jeff Douglas posted on his blog how to embed a Flex slider into a visualforce page. This is pretty slick and can be really useful, but I’m not a really a fan of Flex (I’ll post about that later) so today let’s look at doing the same thing a little different.

Instead of using Flex to build the slider I will show you how to do this with javascript. This requires less code and I feel it is easier to implement.

We are going to add a super nifty ultra slick slider with only 16 lines of javascript code.

Read more…

Categories: Visualforce, jQuery