In-Line Validation in Visualforce Pages

In-line validation

The following Visualforce code demonstrates how to call an Apex ActionMethod after a user exits the field.  Here customer is an instance of the Account SObject which has the custom field Date_Of_Birth__c.  I want to check the age of the customer to see if he is at least 18.  This code uses the actionSupport tag to listen for the onblur event (when the user leaves the field), then calls checkDateOfBirth() method in the controller (or extension).

Visualforce InputField with ActionSupport

This Apex code from the controller inspects the date of birth field and adds an error if the date entered is not from 18 years prior to the current date.

In-line validation

Apex ActionMethod

When the user enters an age less than 18 they are shown the error message on the field widget.

Field Error

In-line error on the field

Posted in Force.com, Uncategorized | Leave a comment

Salesforce.com Application Cohabitation

Introduction / Problem Statement

Cutting right to the chase-How do you decided if a new application should co-exist with your current applications implemented in Salesforce.com?  I’m writing this in response to my own inquiry and hoping that as I annotate these thoughts/arguments I can illicit enough feedback from “the community” to either validate it or point me in the right direction.

Background-I was a key contributor of a start-up some years back where we decided to home-grow most of our enterprise applications on a Solaris-Oracle-J2EE stack.  The benefit of this was that we didn’t require multiple technical teams with varying skills to support the “best of bread” sales, service, employee management, ERP, CRM, XYZ applications.  We could hire(or teach) the skills we needed on the stack and the developers could support all of the applications we put on this bohemoth.

As I “moved on” from this Utopian software environment I realized that big enterprises don’t work that way.  The PeopleSoft HR application needs to feed Microsoft Active Directory and Siebel CRM and tie to the home-grown Sales Compensation System which ties to the blah, blah, blah system.  Meanwhile you’ve got n number of systems that all need to be aware of your users, groups, customers, products, permissions, and so on.  That’s a lot of redudancy.

Enter Salesforce.com and the Force.com platform.  Now you can have your CRM app co-exist with your time management app and your sales compensation app and your whatever app all in one “org”.  But with great power (I won’t say it)…   With each new app it’s really important to ask if it (the new app) should cohabitate with your existing org.  Here’s my criteria.

My Criteria (and maybe yours)

Here’s an ever-popular bullet point list that will help guide you through the decisions on whether to put that new app in your existing Salesforce.com org or to ‘spin of a new org’.

  • Are the users of the new app existing licensed users?
  • Is there overlap in the new app’s data with the existing orgs data?
  • Does the new app “naturally fit” with the existing app?
  • Will you and your team be successful with this application?
  • Are the general features of the new app consistent with your existing app?

The Breakdown

OK, so I’ve thrown down my list of criteria in a simplified single line statement, now it’s time to back each one up.

The Users

This is the big one.  If your new app’s users are going to be “net new” licensed users of Salesforce.com then you’ve got yourself a case for a brand new org.  Whether you’re paying X dollars per month for 50 users in one org and 25 users in another org it still comes out to X dollars times 75 per month (see Editions and Pricing).  But there has to be some middle-ground here.  If out of your 75 total users, more than 33% (you need to decide the threshold) will need to use both apps, then you’re probably better off having both apps in one org.  Users bouncing out of one org and into another is a pain, and they’ll share that pain with you.  So consider this “high” as a factor in deciding.

Data Overlap

Data overlap is always going to happen, whether it’s in your picklist values or your default contact information, or whatever.  I’ll bet that my DE org has some data in common with your production org right now.  But I’m talking about serious data overlap.  Like the entire(or most of) your Account records or all (or most) of your Campaigns.  Second only to user overlap this needs to be high on your list when considering multiple orgs.

Brief “me/us” story.  When my development team decided to create our change management app on the Force.com platform we considered whether our sprint, backlog item, and requirements custom objects would ever be shared with our sales and service agents data needs.  The obvious “no” led us to create this app in a separate Force.com org.  Since then we have realized that release notes would have been a hell-of-a-lot easier had we co-habitated, but that doesn’t out-weigh the fact that we can do whatever we want, whenever we want to our own org without an CR and 3 weeks of “it won’t break any of your stuff, I promise” meetings.

Application Natural Fit

This is one you’re going to have to spend some time thinking about.  Say your call center is using the “Service Cloud 2.0″ application and you’re considering a Customer Feedback application.  Natural Fit = true.  A customer feedback button or tab fits because your users are dealing with your customer and to send them out to another application would be absurd.  On the contrary if you’re sales agents are using the “Sales Cloud 2.0″ (or 3.0 or ? by now)  and your I.T. department wants to implement an ITIL based service application (like RemedyForce no I don’t work for BMC), then I’d say that’s a rather un-natural fit and the I.T. guys should get their own damn org.

New App needs versus Existing App Policies (reworded from bullet points)

Enterprises and companies are made up of groups of people, and sometimes (as I tell my kids) these people don’t see eye to eye.  So this section of the blog is dedicated to the politics of the decision.  [Switching to really frank mode] Listen closely.  If you’ve got a group inside your organization that is difficult to work with, then implementing their application on the Force.com platform will be just as disastrous as the last effort was when they launched their application on Java & Struts.  So let the .Net guys take on this one.  After all you’re competing with those guys for the CIO’s attention and when the thing go awry you can stand proudly and lie “This would have been successful if we had done it in Salesforce!”

General Feature Comparrison

If you’re still reading I’ll make this one fairly simple.  Think like a consultant who’s getting on the plane at 5pm and needs to leave at 3 even though he only got into the office at 10am and had an hour and a half lunch.  Consider whether the new application will required cool new post-2008 Salesforce features like Visualforce, Sites, Batch Apex, and JavaScript Remoting.  Can this new app be done using standard layouts and standard reports?  Is this an assignment for Asok when he returns from ADM-201?  If so then maybe you don’t need to order 16 new Salesforce Unlimited licenses at $250 per user per month.  Perhaps this can be done in a new org with 16 Professional Edition licenses at $65 per user per month.

Conclusion

As anticipated, I’ve educated myself during this blogging exercise and I think that each of my bullet point items which list the pros and cons of application cohabitation become progressively less pertinent.  Meaning?  I should score each of them to make it useful, so I will.

  • User Overlap – 50%
  • Data Overlap – 30%
  • Natural Fit – 10%
  • Politics – 6%
  • General Features Required – 4%

Hopefully this helps others in the community.  I know it will help me tomorrow during my technical recommendation when I quote this blog in the 3rd person to prove my point.

Cheers!


Posted in Uncategorized | 2 Comments

Improving Force.com Deployments

Introduction / Problem Statement

Salesforce.com customers with Large Data Volumes (LDV’s as they are called) can experience prolonged deployments as their Apex test classes run over millions of records. Since my organization has recently reduced our deployments time from over sixty minutes to less than ten I thought I’d share some of the tricks we used.  To give some background on this I’ll share some stats about our org (without actually naming it).  We have 2,142 active users, 920,334 characters of Apex code, 11 Batch Apex classes, and currently use 460.1 GB of our 488.3 GB total storage(we pay extra for storage), and our Account object has 10,682,959 records and growing.

Analysis

The first thing you’ll need to do is figure out which classes are taking so much time to run.  To do this you’ll need to [Run All Tests] in your production (or in a full copy sandbox if possible) and look at the output to determine which test classes need improvement.

In the output each test class will have next to it the number of milliseconds it took to complete so you’re looking for the ones with the execution time in the hundreds of thousands (123,456 milliseconds is roughly 123 seconds, or 2 minutes).  Search in the execution log for those long running classes and start to look through SOQL statements for long execution times.  Search for SOQL_EXECUTE_BEGIN and compare the time to the next statement of SOQL_EXECUTE_END.  When you see a SOQL query that takes a long time to run you can find out which class is calling it and make adjustments based on one of the options below.

How Apex Test Classes Work

When you run a test class (or all tests) the platform considers the entire transaction to be a single unit of work and (in database terms) rolls back the entire transaction once the test run completes whether it’s successful or not.  This means that all DML statements(insert, update, delete, undelete) are reversed after tests are run.

What causes tests to fail?  If there is (a) an uncaught exception during execution, or (b)a System.assert() fails, or (c)you are deploying to a production org and you don’t have 75% test coverage.  That’s all that come to mind right now.  If you have others please tell me and I’ll amend this.

Options

Data Housekeeping.  If your test classes have to search through Lead records from  three years ago, you might consider archiving that data.  Tell guys in reporting that you want to store this “valuable” information in their data warehouse.  It’ll help them feel important.  Then you can purge those old records out of Salesforce and gain from the reduction of rows your test classes evaluate.  You may want to consider this housekeeping to be a part of your regular maintenance.

Know when you’re testing.  In one of the recent Salesforce releases a new feature was added that makes your classes aware that they are running in test context.  This magic method is Test.isRunningTest() and it allows you to add clauses to your dynamically built SOQL like “order by createdDate desc limit 5″.  My orgs deployment engineer is the one who suggested this and it’s one of the key contributors to speeding up our deploys.

Add indexes on crucial fields.  Another key to our success in reducing deployment time was to add an index on a field we used in one of our Batch Apex classes that was part in the “where” clause.  The index we added was on our Account object which has over 10M rows.  “How do I add an index to a field in Salesforce?” you ask.  Edit the field and mark it as an External Id.  This effectively puts an index on the field in the background.  Use this sparingly, though, because there’s a limit on the number of fields per object you can mark as an External Id.

What not to do

I’ve heard of developers deleting all the records in an object, then inserting specific test records during testing.  Since we know all of the DML operations will be rolled back after the test completes this would seem to be a harmless operations, but if you have 200k Lead records it takes a long time to delete them and to undelete them when you’re done.  So don’t do this!  Be smarter about your test records.  Create them all with a LeadSource of TEST, and in your Apex class check the “Test.isRunningTest()” method and add a ” and LeadSource = ‘TEST'”.

Summary

Hopefully this post has give you some ideas on how to speed up your deployments.  The people responsible for running the smoke tests and deployment validations really appreciate getting to bed before midnight and you have better things to do with your time than wait for test classes to finish.

What’s Next

I’ve been considering writing a blog on something we use called TestDataFactory.  A class whose sole responsibility is creating random sets of data for our test classes.  Interested?

Posted in Force.com | 2 Comments

Overriding the Overridden View Pages

Salesforce.com has a clever way of overriding the default view page with a Visualforce page.  As a developer/administrator there are times when you want to un-override the page and see the standard page layout.  You can tell when the pages are overridden because the URL looks something like this:

Notice the “/apex/OpportunityDetail?id=…”.  The 15 characters following the id is the Salesforce Record Id.  It’s starts with 006 so you know it’s an Opportunity.  This is called the ID Prefix.  001’s are Accounts, 00Q’s are Leads, and so on.  Once you’ve been working in Salesforce for a while you start to recognize some of the prefixes.

To view the standard page layout without the Visualforce override you can update the URL changing the “/apex/…” to the Salesforce record ID and add “?nooveride=1”.  See below:

This is how we can look at records that won’t load under normal conditions (say, when the developer doesn’t check for nulls in controller extensions).

There are other tricks, like adding “/e” after the id to put the record into edit mode so you can quickly update the record (say, to put in values instead of nulls that the controller extensions aren’t expecting).

I’ve showed this trick to my power users and support staff, but only with the warning: “PLEASE don’t show this to users.  We need to control how they’re accessing the data.

Posted in Uncategorized | Leave a comment

Force.com Contest App for Home Brew Festival

Introduction / Problem Statement

My friends and I decided we would hold an annual contest to see who’s home brewed beer was best.  The first problem we ran into was voting, mostly because we didn’t plan ahead and coming up with a way to accurately count 100 hand-written ballots after “sampling” the contest entries was troublesome.  Being techies the solution seemed obvious: Develop an application that allows people to enter their own votes into a central place and tally the results when the contest ends.

I set out to create such an app using LAMP hosted on a ISP who charged $7 per month.  That worked fine for the first few years, but when Salesforce.com announced Force.com Free Edition I quickly converted and dropped the account with the ISP(which was best because I only need the contest app once a year but kept the account at $84 annual).  There is no charge (duh, it’s Free) and I can keep the app all year without activity and use it again each following brewfest.

What does it do?

Ninety percent of what the contest app does is allow the contest administrator to create contests, add contestants and entries, and generate ballots.  The other ten percent of the app has to with the actual voting.  I’m using the one Site that comes with Free Edition to host a set of Visualforce pages that let users enter their ballot id then the score for each of the contest entries.  The app forces voters to enter a valid ballot id so they don’t vote more than once.

When the contest is over I update the contest record to indicate voting is closed then print out the related list of entries sorted by score, and viola, we have a winning home brewed ale.  All without the hassle of five slightly inebriated guys arguing about how to count votes then having to make up spreadsheets then having one guy read them and another guy enter them.

How does it work?

As with all good apps let’s start with the data model.  Please excuse my lack of a good ERD here.  I’m looking for something free that will do ERDs and I’m not going to draw all this out in mspaint.  My main objects are Contest, Contestant, and Entry.  The Contest defines the event, the Contestant is the brewer, and the Entry names the brewed beer being judged.  The relationships are pretty much the way you’d expect them to be.

Outside the main obects I’ve got one for Ballots, Votes, and a cheater for Ballot Generation.  Ballots looks up to Contest.  Votes is slightly more complicated because it has a Master-Detail relationship to Entry(so I can do a roll-up summary), a lookup to Ballot, and a numeric field for the score.

I’m using standard page layouts to maintain all of this data, except for the cheater object.  I didn’t want to write any Visualforce for the app administrator’s sake, so to generate ballots in bulk I insert a new record in the Ballot Generation object (which looks up to Contest), enter the number of ballots to generate, say “50”, into a numeric field, then the trigger fires and creates 50 Ballot records that look up to the Contest then inserts them.  Honestly I don’t know what made me do that because it seems like a crappy solution, but it works and I’m the only one that knows I did it that way(until now).

The Site hosts a three page wizard that gets the ballot code(page 1), displays the contestants and entries next to an <apex:SelectRadio> with 1 through 5 as options(page 2), and finally a “thank you” page that tells the voter they’re done(page 3).  The site isn’t fancy which has everything to do with the fact that “sexy web sites” aren’t my forte’, but people are hitting this site with mobile devices as well as desktops so the simpler the better.

How is it used?

When people show up to brewfest and are ready to start making the rounds they pick up a contest sheet, a golf pencil, and a ballot code (this year the ballot codes are going to be stickers on the contest sheet), then walk around and sample the home brews.  Discreetly or indiscreetly they fill in the circles on the contest sheet like the old scantron test from high school.  When they’re done they find a computer provided at the party or use their smart devices to go to the voting web site, enter their ballot code, and vote.  This year I added a QR image on the ballot so that people with smart devices that have bar code readers on them can scan the QR code and be taken right to the voting site and have their ballot code automatically entered.

What’s next?

I had planned on using Twilio to let people vote by touch tone phone call, but I had a problem maintaining the state after the caller entered their ballot code, so I dropped it.  I would pick it up again, just to say I did it, but it’s not a high value item for me.  If anyone reading this has suggestions on how to maintain state in a Twilio call(session) please send me your comments.  I’m probably missing something simple.

I toyed with the idea of creating an Android app, but then I started to get too busy with “work” work, and this spare time, impress my friends at brewfest fun work started getting to be too much.  There’s always next year for that.  Or maybe I’ll publish the app on the AppExchange and pay the $300 review cost just to say I’ve got an app out there.  I could create a repository for it on github.com and go all open source with it.  That way maybe other people could benefit from it and add to it with apps for mobile devices or maybe even a sexier user interface.

Conclusion

Overall this is a really fun experience.  I’ve expanded my knowledge of the Force.com platform by playing with Force.com Free Edition and created a great app that handles the voting at brewfest.  Creating something useful is always rewarding.  I’m also using Free Edition in the office in a change management application that helps us manage our product backlog, development sprints, resources, and deployments, but that’s a topic for another blog.

Posted in Uncategorized | 1 Comment

The Force.com Database versus the traditional DBMS

Part 1 – Intro and Storage

After having the argument over and over with other guys in IT I decided to write down some notes on how the Force.com DB is “different”.  This is not an Introduction to the Force.com Database.  That article is already written.  And it’s not a deep dive into how the data is defined and stored.  Check out that section (starting on page 5) of the whitepaper on the Force.com Multitentant Architecture.  I’m talking about the points I find difficult to explain to the people familiar with traditional databases like Oracle, MySQL, and even DB2.

Disclaimer: I’m going to make some statements here about the Force.com database as I understand it, so bear with me.  Let’s get the heavy one out of the way first.

“Salesforce.com doesn’t store data the way traditional databases do.”  Or at least they don’t count the space used like everyone else does.  We all learned that to figure out how much space you need you multiply the number of bytes in a row times the number of rows.  Then you add some factor, say 20%, for indexes.  You repeat this for each table in your database and when you’re done you know how much storage to ask the DBAs for.  I’m purposely leaving out things like future growth and archiving to keep it simple.

So how does Salesforce do it?  They’ve create a layer on top of their actual DB ,which I dub “the magic DB layer”, which stores each row as 2k.  That by itself has a huge impact when you’re trying to normalize your data model.  Check out Database.com’s pricing and you’ll see they’re charging by number of records and transactions.

Let’s take an example.  If you’re keeping track of customer information and you know every customer will have two phone numbers, one home and one mobile, then you would likely create two tables (sObjects in Force.com): Customer and Phone.  On the Phone object you would add a reference to the Customer.  This is the traditional parent-child relationship and is future ready when the requirement comes along for additional phone numbers.  Now if you insert a single customer (1 record) and their home and mobile numbers (2 records), you now have 3 records and have taken up 6k.  That may not seem like a lot, but when you have 4.2 million customers (as a certain company I’m familiar with does), that’s now  25.2 GB of data.  But we can flatten that out by adding the home and mobile phone to the Customer object which eliminates the separate object and brings our usage back down to 8.4 GB.

Wow, that’s some savings, but what happens when the requirement comes along to add another phone per customer for fax number?  You would just add the fax number as another field on the Customer object and that doesn’t require any additional storage usage.  How?  The answer to that is, “I don’t care.  Salesforce.com takes care of that.”  Had I used the normalized model with a separate object for Phone I would have added (assuming every customer has a fax number) another 8.4 GB of usage.

What else have you impacted by de-normalizing?  What about the UI?  There has to be an impact there because now you need to make that field value available to the users.  That’s ok, though, because in my example I’m using the object’s standard page layouts (I kept that a secret), and I can just update the page layout and add the fax number to the customer page.

My point with this is not to avoid normalization, just to consider the impact.  Your storage capacity on Salesforce.com is based on your Salesforce.com Edition and number of licensed users.  For most editions each user gets 20MB (approximately 10,000 records), and if you need to store more than your capacity you may find yourself calling up your account rep trying to negotiate additional users or storage.

Finally, the example I used was just to get the point across.  There are standard objects like Account and Contact that already have those phone fields flattened on them.

Posted in Uncategorized | 2 Comments