Category: Development

These posts all deal with code and topics of interest to developers

Finding What’s Hot and What’s Not with geolocation

Let’s see, clear some cobwebs, dust off some settings, check that it was indeed over a year since my last post. Yep, every thing seems in order. To kick off this post-a-versary, how about a quick exploration of Salesforce’s built in geolocation features, now that this data has been automatically added to the standard address fields!

A quick primer for the uninitiated, geolocation information is the location of something on the globe. Instead of using streets or landmarks, it uses latitude and longitude to find a location’s exact position. With this information at our disposal we can start to look at data on a geographic level. To illustrate this, we will look at a fictional company and how they can use geolocation to better outfit their sales people.

Path Skull

Introducing Path Skull, a fictional manufacturer of outdoor goods. They sell to retailers instead of directly to consumers so their sales people need to work to get their product into stores. To help them out when courting leads, they are going to use geolocation to figure out what sort of products sell well in a particular area. There is no need to show off your rugged sneakers when there is only demand for boots or your triple insulated sleeping bag when the market just wants to keep cool at night.

A clean sweep

All of this will depend on having the latitude and longitude of your accounts and leads. You do have that populated, right? No? That is fine because with Salesforce and Data.com it is all automatic, all you need to do first is to enable it. Go into the setting for your org and locate the ‘Clean Rules.’ For our examples, we will be activating ‘Geocodes for Account Shipping Address’ and ‘Geocodes for Lead Address’ but please activate whatever works for your use case. For more information, check out the official Salesforce release notes for the geocode clean rules.

Button Up

A new button on the lead will be the point of entry to this new functionality. Leads have a built in address field that will become the center of our area to report on. First off we will create a new visualforce page with the lead object as our standard controller and a new apex class to use as our controller extension. In the constructor of our extension we will use a distance query to find all the accounts within a 100 mile radius.

For this example I am just hard coding 100 miles, but for greater flexibility, consider a custom setting with the ability to change it on the results screen. Next we will grab the top five assets and products as well as the bottom five for the previously found accounts. The top five is the obvious one but the bottom five could just as well help you with what products not to even waste your breath on.

Once you have your data, it is up to you to display it in the most relevant way on your page. To wrap it all up, add a new button to the lead which opens the visualforce page and place the button on the lead’s page layout. With just a few lines of code your sales people now know what a lead may be interested in from the outset. How easy was it? With comments, the source for the controller turned out to be only 18 lines long.

The visualforce page to display the data as a pair of lists was only 15 lines long.

This was a simple example but with location-based SOQL queries and the location class, making use of location doesn’t have to be hard.

Using Gulp to Manage All Your Static Assets

The web development community continues its march towards more advanced methods and processes. CSS preprocessing, JavaScript testing and linting, image compression, and much more make up the web development landscape. Where does that leave you, humble Salesforce developer? Your JavaScript, css and images all get loaded into static resources and that’s it. Surely there is no way to integrate the Salesforce way with all these cool, new tools, right? Prepare to be mildly interested.

Now, before we get started, I am going to make a number of assumptions:

  • You are semi-comfortable with the command line
  • You have your own development environment. For reference, check Jesse Altman’s ideal explanation and for more depth, read the other articles he has in the series
  • You have your Salesforce code and metadata pulled down to your local machine for development
  • You have some way to deploy code (MavensMate, Force.com IDE, Ant migration tools, etc.)

Initial Gulp setup

The first part will be getting Gulp set up. To begin, you will have to download and install Node.js for whatever system you are using. After that is all set up, you are going to want to go into your Salesforce project and make a sibling folder to src. This is where we are going to load all of our assets, so name it appropriately. After that, make a folder for each asset type you are going to work with (i.e. js, css, img) and if you are going to use something like Sass or Less, then add a folder for that.

Next we are going to open the asset folder in a command line and enter the following commands:

The first command will bring up a series of prompts where you can enter some information on your project. The next two actually install Gulp.

Next we need to create gulpfile.js in the same folder and add these few lines

That file will set up the server (for now) so that typing the command gulp and navigating to localhost:8080 in a browser will show your asset directory.

Managing your dependencies

If you depend on a number of third party libraries, you may want to consider a package manager. If you don’t want this, it is not necessary for the article but it can be a huge help. I will be using a tool called Bower. Bower lets you search and download dependencies, much like npm, but with a focus on the front end. To get started with Bower, first we must run

What you actually install at this point is up to you, but for example I will install jQuery and Normalize.css. Like with npm, Bower has an init command that will prompt you for various values.

Local files, now with more cloud

Now that we have our files served up, we can use a bit of trickery to load from our little web server when developing locally, but then use the static resources in all the other environments. The basic premise of this is using a flag in a custom setting, something like Use Local, and either rendering a component with all the local assets, or the static resources. There are a lot of ways to actually lay this out, but for me, I will be using two sets of components so my CSS loads in the head and my JavaScript loads in the footer.

Before we even get to writing the components, we need a few things in place. First is the custom setting so you can turn the feature on and off. Next is some dummy static resources. Now this depends heavily on what you are going to do with your assets but for me, I plan on concatenating and minifying my JavaScript and CSS. I plan on zipping third party assets into their own file. For my purposes I will create a blank js file, css file, and zip file and upload it to the static resources. Once I get that done it is on to the components.

This design was originally from this GitHub repository for a Visualforce AngularJs Seed. The design was later refined by Peter Knole.

The story so far

If you have been following along you have all the bits and pieces set up. Now you need to put it together in a page and write up your CSS and JavaScript. The page can be anything, so long as it has the components for the CSS and JavaScript at the top and bottom respectively. Don’t forget to set the custom setting to true so you use your local files. If everything went well, then viewing your page should work. If it doesn’t, check that your browser isn’t blocking mixed content . If you really want to test, make a change to your CSS, save, then reload and see that your page changed without any long save times.

Example local page
I am not a designer

Building for now

You now can view your work in your own sandbox just fine, but what about everyone else? So this tutorial doesn’t become a colossal pain, we will be setting the custom setting to false to simulate the remote environment. Now, viewing the page shouldn’t look so good. That is because we haven’t done anything about the static resources. We are going to fix that, but we need a bit of help. First grab a few more dependencies:

Now for the script

To break that down, lets look at the tasks that were just added. The zip-vendor task  gets every file and directory in the bower_components folder, zips it up and puts it in the static resources. The process-css, and process-js task gets all our CSS and JavaScript files, concatenates them into their own files, minifies them, and then places them in the static resources. Once that is all set, run gulp build to rebuild the static resources. After that, you just need to get the files to the server however you are comfortable. For example, if you are using MavensMate, just run the compile.

Building for the future

There is so much more you can do than what I laid out. The tools and techniques of web development are constantly changing and shifting. This article was done so you can see a possibility. Nothing I have done is set in stone or even scratches the surface. The makers of jsForce, for instance, have a post I took inspiration from for deploying assets right from Gulp. There are also a wealth of tutorials on these tools as well as many others that can be added to your workflow.

I say to you now, welcome to the present age of web development, we’ve been expecting you.

mock_head

Mock Mocks in Apex

I love mocking frameworks. I love the ability to isolate a unit of code so I can make smaller, more coherent tests. I have grown accustom to them during my time with java and I would love to use them with apex. The problem is that mocking frameworks rely heavily on robust reflection, a feature apex sorrily lacks.

Sorry. Lost the happy, but the happy's back!
Sorry. Lost the happy, but the happy’s back!

While we cannot yet simply tell a method to generate a mock class, maybe we can make an approximation. A lightweight class that can be substituted for the real thing when testing a class that relies on it could work in many cases. How to get the mock class in there though, that is the question. While Apex is missing most of the necessary reflection, it is not missing all of it. Enter a little known blog, by a man called Jesse Altman, that goes into dependency injection with Apex. That, my friends, is the foundation of what I will go into here. If you didn’t click the link above, and I don’t know why you wouldn’t have, read the article on dependency injection right now. Seriously, if you go on without reading it I will be disappointed in you.

Are you done? And no lying, I will know. So, I have my classes and custom settings pretty much the same as the one from Jesse’s blog post and will be building from there. The best place to start with a blog post on mocks and unit tests is probably a unit test. The unit test will initially test the the classes as they are.

My service just just calls processPayment on a PaymentInterface, nothing special there. The test inserts a custom setting first, grabs the return value from processOrderPayment and verifies the result. Not too much going on here, certainly not deserving a post. Yet. Lets spice this test up.

Look at that, injecting an inner class from within the test worked just fine too. The problem is that this is a trivial example. Why bother mocking? Let’s make this a bit more complex.

I have changed the interface to have the method getAuthCode and added a string parameter to processPayment. The service now checks for a non null authCode and throws an exception if it is. Our mock has had its methods changed accordingly and now, process payment verifies the parameter passed to it. This is closer to our mocks, but now we have a branch we can only test by adding another mock. Inconvenient indeed. One last change, one last push over the finish line. A new class will get us where we need to go.

This hefty class will let us reuse the same mocks multiple times. I wont break this down line for line but I will summarize it. The command object holds parameters to verify against and return values to… return. The method add call adds the call to a map containing a list of command objects, keyed to the method name being mocked. The calls to a particular method must be mocked in the order they will be run. The method getCall gets the command for a method, verifies the parameters are the same and returns the stored return value. What does this look like in practice? Ask, and ye shall receive.

The mock now extends MockMaker and does nothing more than wrap different calls to getCall. The test methods (yes, now there are two) mock out the calls to the payment service with MockMaker.addCall. We can now use the single mock, injected into the OrderService via the factory, to run multiple tests. This isn’t perfect but for services with call-outs or just very heavy methods, this can be a real help.

Looping Slideshow Display With Visualforce and Apex Charting

Anyone ever seen pictures of west-cost start-ups with those TV screens front and center showing some sort of stat or metric? If it is a dev house maybe it is the builds, bugs, & deadlines. A sales firm may have revenue, opportunities and a highlight of recently closed deals. Either way, they are meant to highlight data and allow it to be consumed in a very passive manner, reading it as you pass by. Salesforce makes reports a breeze and dashboards are a snap too. However, what if you wanted to recreate that seamless look, without the tabs, browser UI, or any indication of what is driving the display at all? Sure, there are tons of articles that show you how to get PowerPoint to do that, but using stale data is for suckers. Let’s take a look at what some Apex, Visualforce and JavaScript could do for you.

We should start with the controller.

A good start but missing any real meat. Let’s look at what is there, shall we? Pretty much the only thing in this class so far is a nested wrapper class. This is just a convenient way to get data to the charts. Feel free to do your own thing if this isn’t your style. We better add a way to get some data.

This looks promising! This method grabs all the cases, groups them by priority, then counts the number of cases in those groups. We iterate over that data and toss it into that wrapper object from the prior code block. Add as many of these chunks of code as you want, one for each chart you feel like creating. We are almost done the controller, just one more piece.

This to-the-point bit of code is there to erase the current set of data so it can be refreshed. Remember what I said about stale data being for suckers? This prevents you from being a sucker. Put all of those together and you get a completed controller (mine has a second list of chart data because a one slide slideshow is boring).

On to the Visualforce. We will start off small again and build from there.

This is the base, telling the page to use the ChartController and to not show the header or sidebar. Remember, we don’t want this looking like a webpage or a browser, just a slideshow. Now we need a chart.

This is an apex chart. The width and the height shown here are based on my screen size and layout. If you have extra styling or branding on your slideshow (Trust me, you will want it. The end result of this is bare bones.) you will need to change these values to fit. The apex:chart tag also tells the page what data to use and the id will be used to keep the data fresh. The apex:pieSeries tag tells the page that the data comes from the data field on the wrapper and that the label comes from the name field. There is also the apex:legend tag which provides a legend in the position specified. Finally all of that is wrapped in a div that will provide us the means to allow for movement. Like with the controller, you need one of these for each list of ChartData that you created, just leave the ‘activeSlide’ style off the rest. We still need to code to bring this to life. Let’s begin with the styling first.

Simple stuff here. The ‘side’ class has an absolute position, a white background and is glued to the top left. Every slide has that and therefore, every slide is stacked on top of each other. The slide that also has the ‘activeSlide’ class rises to the top, thanks to its high z-index. To make these slides shuffle, we also need some JavaScript.

First off, I am lazy at times. Seriously, no joke. That is why I included JQuery, because it makes things so darn easy. The next bit sets up a JavaScript method named ‘refreshCharts’ that calls the controller method ‘refreshCharts’ and re-renders my two charts with that data. This is done with the apex:actionFunction tag and will automatically generate the appropriate code. After that, I set up another JavaScript method that will determine the next slide, remove the ‘activeSlide’ class from the currently visible slide, and add it to the next one. To set things in motion, I call that method every 5 seconds and the ‘refreshCharts’ method every 10 minutes. Mix it all together and cook at 350 degrees and your Visualforce should look like this:

What does this look like in action? A chart, then another chart. This is not worth a picture because a still image won’t show it in action and an animated gif can be staged. The best way to see this is to follow along and get this code into any developer account. After you do that, just type in the URL, ‘<YOUR_SALESFORCE_URL>/apex/<YOUR_VISUALFORCE_PAGE_LABEL>’. Tapping F11 should remove all of the browser UI and dragging the mouse to the right side will hide it from view. There you go, a live slideshow. This is the perfect project to dedicate some old hardware to.

CLI showing the output of the program

Static Code Analysis of Apex

Would you wander down memory lane with me? It was on one of my first projects at Trifecta that I was introduced to Sonar (now SonarQube), a dashboard that aggregated results from a pile of code analysis tools and presented them in a visually appealing way. I loved the kind of insight it provided.When it listed a bunch of unused methods I went to work pruning them. When it found string concatenation in a big, heavily used loop, I replaced it with StringBuilder. When I moved over to Salesforce, I found a number of solutions but most were either costly or incomplete.

SonarQube dashboard
Different name, same usefulness.

I did manage to find a wonderful blog post, written by Andrew Fawcett, which covered using the tooling API to call out methods that are not referenced anywhere and display it on a Salesforce canvas. This was exactly what I was looking for, or at least it had the potential to be. You see, finding unused methods is a great help once a code-base becomes large and complex enough. Removing these relics could reduce your code-base and may reduce your unit test and deploy time. That is what makes unused method finding, my top feature to have. Even so, I wanted more, and given the choice to extend his project or make my own, I of course made my own.

GitHub new repository button
As if this was even a choice.

I started off with Node.js (bffs 4 lyfe) for no other reason than “I wanted to experiment with it.” Then I reimplemented Andrew’s solution using the node-salesforce module to handle authentication and CRUD operations. Finally, I added a basic plugin system to allow for new checks to be added. How did that all turn out? Let’s find out.

CLI showing the output of the program
Well, it’s a start

I hate to say it, but Node may have been a mistake here. Don’t get me wrong, I had a lot of fun doing this, but there is a fundamental difference between Java and JavaScript that cranked the complexity right up. His logic was very sequential, going through steps one at a time with the next step depending on the completion of the last. Java did this very well, executing each call out to Salesforce and waiting for a response. Anybody familiar with AJAX should start to squirm right about now. I ended up with a tremendous chain of call backs, which fulfilled its purpose but got real messy in a hurry.

Reimplementing this solution went well enough minus the previously mentioned call back avalanche (call-backalanche?), but it was not without its drawbacks. These are no fault of Andrew and merely reflect the incomplete state of the Tooling API. For one thing, the method reference count does not count references in Visualforce. This was inconvenient, but to anyone coming from a java background where missing references in the view is par for course. I also ran into an issue trying this on an org with a scheduled job. You see, to build up the symbol table, it is compiled by basically performing a “check only” deploy. Salesforce did not like that one of the classes the scheduled job relies on was one of the classes we were checking. This resulted in total failure.

The plugins were perhaps the smoothest part of this project. Node’s ability to require a directory and a bit of trickery resulted in a plugin system as simple as dropping a properly constructed JavaScript file in the directory. These are not as efficient as if they were all part of the main file, as they end up looping over the same data a few times, but it is dead simple to add new checks, change thresholds, and disable old checks.

“So, is this project done?” I can hear you asking. The answer is an unequivocal no. On the roadmap is a web based interface, greater structure for plugins, ability to configure for multiple orgs, and heavy work trying out different flows and Node modules before I set in stone how everything will work. Until then, everything is in tremendous flux. Check it out at my GitHub repo.

Zero to Heroku

From Zero to Heroku in Three Posts, Part 3

Well, we have come a long way, from learning what Heroku was, to hosting a site on it. Now all that is left, are a few minor details. Let’s start by changing that wacky URL to something a bit more appealing.

Domain Name

For this section, unless you are hording domain names like some sort of virtual pack-rat, you will likely have to spend some money. If you have a great aversion to this, fear not, skip to the next section for more freebies. Now that that is out of the way, go buy a domain name. Go on, I can wait, no need to rush this. Once that is done log into the Heroku website, click the name of your app, then click settings. Scroll down to the section that says domains.

Heroku settings
You should be seeing this

On that line, enter the domain you own and click add. Now here is where my tutorial ends and Heroku’s documentation begins. Due to the sheer number of domain registrars, I must refer everyone to Heroku’s custom domain documentation and whatever documentation is published by your domain registrar.

Add-ons

Remember all of those add-ons from the first part? The post you surely read? Well now it is time to add one. This is not a necessity by any means, but it will be good to look through the add-ons and get a feel for how they work. We will start off easy with a simple log viewer. Log into the Heroku website, if you are not still there from the domain setup, click the name of your app, and this time click resources. On that page click Get Add-ons to be taken to the list of Heroku add-ons. You will likely have to click the login button in the top right if this is your first time here. Once that is taken care of, scroll down to the logging sections (section names are along the left hand side) and click Papertrail. I am going with Papertrail out of familiarity, not an endorsement. When I have tried out some of the others, maybe I will do a head-to-head comparison of them. As I was saying, click Papertrail and familiarize yourself with this layout. The add-on pages are set up with a general rundown of what the add-on does at the top and a breakdown of what level of service is offered at each pricing tier. Once you are ready, select the free tier and then select your app from the dropdown at the bottom, finally clicking the add button. Navigate back to your app and click the new Papertrail add-on at the bottom. Hurray, you now have a log viewer at your disposal. Not much use right now, but great if you start to see errors or start doing custom development.

Papertrail logs
All quiet on the website front.

Conclusion

We have come to the end of the opening week, three post blitz. I hope you will stop by every week (I am thinking a Wednesday update schedule would work) to see what I write for all of you.

Zero to Heroku

From Zero to Heroku in Three Posts, Part 2

So you have made it through From Zero to Heroku in Three Posts, Part 1 and you are still here! If you haven’t, it was a 1000ft view of Heroku, the platform we will be working on in this post series. If you already know Heroku, you should be good anyway. Let’s get started with making a personal page. Please note, this tutorial assumes you know how to make a website with HTML, CSS, and Javascript; otherwise this series of posts would become way too broad.

So first thing is first:

  1. Sign up for Heroku! No cost and only a minimum amount of forms to wade through makes this is one low barrier of entry.

    Heroku Sign Up Page
    Single field forms? Yes please!
  2. Grab the Heroku Toolbelt for your operating system. This little command line tool provides a powerful utility for managing your instances.
  3. Download Git if you don’t already have it. This is used to push your changes to Heroku. Due to wide range of options and preferences, I can’t give a one-size-fits-all recommendation. I am going to assume that you can access your Git tool for the command line for the rest of the post.
  4. Download my server app from github. Simply open your command line and navigate to where ever you want to put the folder, then run git clone git@github.com:Bobnix/static-nodeku.git
  5. Navigate to the static-nodeku directory you just created.
  6. Run heroku login and login with your account credentials.
  7. Run heroku create. This will create an instance in heroku and set up the related Git information for you. It will spit out a phrase in the form of WORD-WORD-NUMBER. Take note of this phrase.
  8. Run git push heroku master. This pushes the code from your computer to heroku.

Thats it! You now have a live site, let’s take a look at it by going to https://THE-PHRASE-FROM-STEP-7.herokuapp.com/….

Hello world
Humble beginnings

Well, that is a bit bare. Lets fix that. Because there are so many ways to go about doing this, actually making the site will depend heavily on how you are comfortable working. I personally use Notepad++ or Sublime on windows. Some of the more seasoned may breakout VIM or Emacs. Others may turn to WISIWYG editors. The only rule (for now) is that your site stays contained within the site folder in the server app.

Once you are done with your edits:

  1. Commit your changes by running git add . then git commit -a -m "YOUR MESSAGE HERE"
  2. Run git push heroku master again.
  3. After a few seconds, verify your changes.
Personal page
Now that is more like it

If all goes well, your site should reflect your changes. Keep revising untill you are satisfied, there is no penalty for the indecisive. The third and final post will go into some more optional pieces. If you don’t feel like registering a domain name (that will cost money), feel free to spread the link to where ever you want it to appear.

Zero to Heroku

From Zero to Heroku in Three Posts, Part 1

With Twitter, Facebook, Tumbler, LinkedIn, Instagram, GitHub, StackExchange, MySpace (is MySpace still a thing?) there is a lot of places to put your personal brand. You, dear reader, probably have a few of these yourself. Have you ever wanted a central location you could direct people to, one that linked to all your various identities? Luckily there are solutions, free ones in fact. The one I will be talking about in this series is Heroku, a web host with a unique way to do things.

First off, let’s figure out what Heroku does before we try to harness its awesome power. Something Heroku has no shortage of is the languages it supports. Most hosts support PHP, Python, and Ruby with a few supporting Java. Heroku on the other hand officially supports eight different languages (as of writing) and unofficially supports many more using its buildpack system.

Third Party Buildpacks
If you want to run a server in LISP, who am I to stop you?

Then there are the computational resources, the driving force for your site or app. Instead of having one monolithic app, Heroku encourages you to break your app into compartmentalized processes that it calls dynos. These dynos are split into two categories: web and worker dynos. The web dynos handle incoming requests and are generally what you think of with a webserver. The worker dynos are for performing asynchronous or long running tasks. You see, web dynos are supposed to respond swiftly, taking no longer than 30 seconds to respond to a request. To work around this, heavy lifting should be offloaded to the worker dynos, which have no qualm chewing away at a task for as long as it takes. If you are feeling the strain of a lot of traffic, simply move a slider to gain additional dynos. This is great for a surge after a targeted marketing effort.

Heroku dashboard
This thing goes up past 11

Finally are all the rest of the services that make a server tick. There are a simply dizzying number of add-ons to choose from. Would you like your app to access static documents, cached in memory? Covered! How about send emails and push notifications? Clear to go! Send messages between closely monitored processes for a wildly scalable app? Sure thing! All of these add-ons mean that you and your team can work in the technology that is more comfortable and better suited for the task at hand.

Add ons
Just because you can have MySQL and PostgreSQL doesn’t mean you should.

Phew! So after that advertisement, how in the world does that help you? Well, Heroku sells its services based on the amount of time that you leave your dynos running. You are given 750 free hours a month. Hmm, 31 days in a month max, times 24 hours in a day comes out to 744 hours. What luck, that is just enough to leave one dyno running full time for a month. With that dyno at your disposal, the prospect of a no cost personal site is starting to become clear.

Part II of this series requires git to be installed on your computer and a working knowledge of HTML & CSS.