Testing Tidbits

Today I’m going to talk about two of my go-to “tools” (for lack of a better term) when it comes to testing functionality in any Salesforce org that I do work in. I don’t always do these things…(but when I do….*never mind*) though I’m starting to do them more often and its been working for me.

The first of these items also comes up often in the #salesforce IRC channel as well and its been talked about in many places but I see this brought up so often that its probably a good idea to mention it yet again.

Use Hierarchy Custom Settings to “short circuit Validation Rules, Workflow Rules and even Triggers. (If you aren’t sure what Custom Settings are or what they do, then watch this video[1]). These are very valuable not only for day to day operations, but also in my unit tests. The idea for unit testing is to test small chunks of functionality. Sometimes things like Validation Rules can get in the way of that. If you’re testing a bit of code that operates on an opportunity, but that functionality doesn’t care whether or not certain fields are required, use the Custom Setting to turn off the Validation Rules that would fire so you don’t have to populate a bunch of fields that you aren’t testing/don’t care about.

For example lets say we have some validation rules in place that ensure a specific group of fields are filled out on an opportunity. Further more, lets say that we are testing a trigger that will create some child object(s) when that opportunity is created/updated, etc. If all we really want to test is whether or not that trigger works when an opportunity is inserted, why run validation on that opportunity? (Unless of course those child objects depend on these fields, lets assume they don’t for now). If our Validation Rules have the short circuit in place, our test code can turn them off in our test to ensure we don’t get errors. This is also valuable because IF we are breaking our tests down into small bite-sized chunks, when someone comes along later and adds a Validation Rule it won’t break our test. (Again, this will assume those creating the Validation Rule are inspecting our Custom Setting first, so it will take some cooperation). So lets say we have a Custom Setting called Admin Settings and a checkbox on that custom setting called Run Validation Rules. In our test setup, or in the test itself we can simply do this:

Admin_Settings__c settings = Admin_Settings__c.getInstance();
settings.Run_Validation_Rules__c = false;
insert settings;

Now when our test code runs the Validation Rule will be skipped. If we get in the habit of doing this for all of our Validation Rules, Workflow Rules, etc. then we can keep things pretty clean and not so brittle. Its never a nice surprise when you go to deploy a changeset and tests start failing because someone added a Validation Rule in production! Of course there are times when you are testing larger chunks of code or functionality and you’ll want to ensure that these rules run. In that case, instead of setting Run Validation Rules to false, just set it to true and you should be good to go.

You can also use this short circuit in triggers by creating another checkbox field on Admin  Settings called Run Triggers and in your trigger inspect that field to see if its true or false:

Admin_Settings__c settings = Admin_Settings__c.getInstance();
if(settings.Run_Triggers__c == true) {
    doIt();
}

You could even get really specific and create custom settings for different objects. Maybe don’t want to short circuit all VRs or WFRs. You could get more specific with fields like: “Run Opportunity Validation Rules” etc…

The second tidbit isn’t necessarily Salesforce specific as you can use this all over the place. I was actually surprised by the number of people that didn’t know you could do this so that’s why its here.

Take advantage of Gmails flexible email addresses.  For instance, if my email is thedude@ihatetheeagles.com, I have several ways that emails can be addressed to me:

  • thedude@ihatetheeagles.com
  • the.dude@ihatetheeagles.com
  • the.d.ud.e@ihatetheeagles.com (etc)
  • thedude+test1@ihatetheeagles.com
  • thedude+myappname@ihatetheeagles.com (etc)

You get the idea. I’m not sure if other email services allow this and if so great, use them. I use them to have unique email addresses on my test users/contacts etc but still have all messages come to my email address when testing. You could potentially use this as a form of getting a stream of messages on a per-app basis and applying a filter in gmail to automatically archive/apply label to messages coming in to thedude+myapp1@ihatetheeagles.com to have groups of messages filtered out by app. If I’m doing a ton of testing and messages that are coming to me are coming from different areas of the app, I can use these addresses even to figure out what app, what part of an app, etc the messages are coming from.

What are some of your favorite goto nuggets for testing, or anything for that matter? As always if there is something you perhaps want me to deep dive on, let me know in the comments.

P.S. I actually love the Eagles…

 

[1] video found on youtube, author: Shannon Hale (@shannonsans)

:wq!

 

Developer with Admin Tendencies

Since the release of Spring ’15, I’ve had the opportunity to use the Process Builder on a couple of projects. When you’re a developer, you tend to see solutions “in code” more often than not. We think in code, we love to write code, its just what we do. With this latest release however I took the opportunity to write a few processes where in the past I would have written triggers and I must say, its pretty slick thus far.

In order to get a personal comparison, I wrote a trigger and supporting utility class first which took me a little under 30 minutes or so, including unit testing.  (Sadly I neglected to write down the lines of code, but it wasn’t much really as this was a simple record creation process with some basic criteria).

Then I decided to replace that trigger with the Process Builder (or as some people are suggesting, PB & J, Sandwich, etc but I digress). Upon firing it up for the first time I was impressed. The UI was clean and it was pretty self explanatory. Perhaps it was the fact that I’d already worked through the logic once when writing the trigger version, but I had the Process Builder version saved and activated in under 10 minutes and it was doing everything my trigger was doing. Color me impressed. (There were/are still a few minor bugs — like a drop down list that was rendering too low on my screen to be seen, I had to shrink my browser view to fit more on it, but that wasn’t too bad).

Admittedly, I should have been checking this out in a dev org long ago but as stated, I’m a developer, I think in code. I was largely focused on learning what I could about lightning components (and I’m still way behind) in my minimal free time, so Process Builder just kinda fell to the side for me.

I was listening to the @Code_Coverage podcast yesterday over lunch (episode 18) and hear a brief mention of a team of Java devs that basically rewrote the entire authentication process in code (or something to that effect — I was coding at the time). Sadly, I think this is something that developers are apt to do more often than not, we tend to ignore the pieces of functionality that could be done with clicks. However, Salesforce has given us some pretty sweet tools and I’d like to think I’m becoming more of a developer with admin tendencies. After all, Apex Commandment #3 is “Thou shalt have a happy balance between clicks & code.” This is something that the platform makes easy for us and we should embrace these tools more often. When I first started — everything was code. After two years or so under my belt I’ve seen a transformation. I still have the internal fight with myself “I can just knock this out in code, I’m in here already” and that voice used to win often — its winning less and less and I’d like to think I’m finding that happy balance.

So use the tools, find that happy balance and become a developer with admin tendencies :)

 

:wq!

Getting Back to Basics

Sometimes we get so good at what we do or we do what we do so often, we wind up flying on auto-pilot. Whether this is evident in your personal life, or work life — its pretty much unavoidable. Given the nature of this blog however, I’m focusing on work life. Being a consultant, I get to poke around at numerous orgs. Most of these orgs have been around for longer than I have and may have perhaps lost their admin, never had an admin, or have just been “brought along for the ride” and when I show up there are many basic things I see that could possibly help the organization in question maintain a better environment for their data, especially when inviting “outsiders” into their org for support.

Here are some items for those entities that don’t have a dedicated salesforce admin to keep in mind when working in their org that go a very long way to producing an environment that is easily support or passed on from one admin to the next, etc.

  1. Fill out description fields, for everything. When adding a new field to a standard or custom object (or even just adding a new object, etc), you are given the option to fill out a description field. Use this. As far as what to say — think about what you would want to know about this field if you had no prior knowledge of your org.  Be explicit, and avoid company specific abbreviations etc. (As an outsider looking in for the first time, you’re likely not going to know all the internal vernacular used within a company, e.g TPS Reports). This has the added advantage of reminding yourself what a certain field is there and what it does should you not need to work with part of your org for sometime. If you’re at all like me, if its been off your plate for more than a week or so — you’ve forgotten it. The description field is a great reminder.
  2. Naming standards for fields: If you can, be explicit in your naming of fields.  A field name ip_Total__c might not be as clear as Internal_Product_Total__c. For a little more typing, you’re building documentation directly into your objects. Yes you can be more explicit in your labels, but speaking purely from a developer point of view, if I’m using Internal_Product_Total__c in my code instead of ip_Total__c, my code just got easier to read as well. (So thanks in advance for that!)
  3. Naming standards for everything: Okay so this may be a cheat just to add another number to this list, but lets forget that for a moment. Why not be as explicit as you can with the naming of things like workflow rules, workflow actions, email templates, email alerts. If it can be read/referenced why not make it clean and obvious what its doing or what its being used for? “Send Email” is nowhere near as clear as “Send Internal Products Total Goal Reached”, etc
  4. Eliminate cruft: This one is a bit tricky as I’m never a fan of deleting…anything, but I’ve poked around enough orgs that I’ve seen many an attempt at writing a validation or workflow rule only to abandon it later for one reason or another. If its in your org and never been used, or something you were just experimenting with — get rid of it. That’s what sandboxes and dev orgs are for. Which is a great segue…
  5. Don’t make changes in production: this is dangerous. Even if it seems harmless you can do bad things. Bad things, in case you were confused, are not good things (unless you learn from them, but again…you can learn from a sandbox or dev org as well). Playing the “what if” game in production is scary for your data…your data doesn’t like “what if” — it likes routine…and tidiness, and maybe long walks on the beach…data is king, honor your king…its good to be king.

To most of you reading this this is hopefully review, however since I only make the effort half the time myself, this is as much for me as it is the newbie who might be wandering out in the big world of Salesforce for the first time. (Do as I say, not as I do right?).

P.S. I promise I am working on some more technical “stuff” but I’m still fighting my way through some of what it is I want to show, but its coming…I swear…I have here somewhere…kinda.

 

:wq!

Wednesday Wrap Up — October 2014 Edition

Being fairly new to this “regular blogging” habit that I’m trying to form, I’ve decided that the first Wednesday of every month will be known as “Wrap Up Wednesday” here on sudovi.com.  What I plan to do is simply summarize everything that either influenced me, entertained me, or general buzz that interested me from the previous month. Some of it may be related directly to Salesforce but buyer beware — I’m a man of many interests so there may be some other things that sneak in from time to time. So without further delay, welcome to the first of hopefully many “Wednesday Wrap Ups!”

Personal Happenings:

  • Highlight of my year: I got to sing at Dreamforce! (Okay, i really will shut up about this…someday.)
  • I had a lightbulb moment
  • I reflected (perhaps out of place) on what I think makes a Salesforce MVP
  • Sarah Deutsch asked me to rewrite the lyrics to “All About That Bass” and she totally rocked it!
  • I smoked my first cigar and had my first Armagnac thanks to my new buddy Adam Daw. Armagnac — hell yes. Cigar — I’ve got much to learn…maybe @MichaelForce can help.

Dreamforce 2014:

  • The developer group over at Salesforce launched “Trailhead” and I’ve been enjoying watching the tweets come through as people complete the modules/challenges. I’ve not gotten very far myself, but intend to go front to back through all of the content. Some will be review but we can always use review. I’ve already referred a personal friend to it to get him up and going with Salesforce. I can’t wait to watch his progress & its a great way to started on the force.com platform.
  • Lightning Components were opened up to developers and it promises to be slick as hell. I’ve only been able to spend a few hours with it so far, but I believe it will change much of what a developer on the platform does in the future. Our jobs won’t change immediately, there will always be enough apex work to go around, but things will indeed change. Jeff Douglas has a great intro to lightning so check it out.
  • Process Builder seems to be getting quite a bit of attention as well and really will shake things up in admin land. Brian Kwong (aka SalesforceWizard) has several good entries regarding process builder. I’ve not had the chance to do much besides give it a glance at this point but I believe its open beta so it would behoove you to get on this now.
  • Salesforce released Wave and next generation analytics platform. To be honest, I was wowed by the demo at the keynote — but that’s as far as I took it. I can’t focus on everything and I’m scattered as it is :)
  • POODLE just doodled all over SSL. On October 14th google engineers released information regarding a flaw in the SSL 3.0 protocol. Salesforce announced they’ll be shutting down that protocol and mass hysteria ensued. Its all very confusing and hard to even tell if one will be affected by it. There is a link on stackexchange that goes into excruciating detail of what the problem is and further down there is a link that will help you figure out which services may have a problem with this, but for the impatient…I think the magic you are looking for upon test completion is in the configuration section of the results. You’re looking for support of TLS 1.0 at least.

Other tech related stuff:

  • Apple CEO Tim Cook comes out as gay. This shouldn’t matter, but sadly we still live in a world where people think this an issue of some sort.
  • Apple Yosemite was released — and I like it :)
  • The Django project added four new core team members. Congrats folks!
  • An Indiegogo project was launched to help Django provide first class support for third party templating engines. I personally prefer the tempting framework that Django provides out of the box, but this can only help…

There are many more items of tech interest that I am sure I am leaving out but these are the ones I am remembering. This month, perhaps I’ll start bookmarking these things…I just hope I can keep this habit up! For now…

 

:wq!

What Makes a Salesforce MVP?

DISCLAIMER: I am perhaps unqualified to speak about such a topic seeing as how I am not an MVP. Therefore, please do not take my words as any sort of official statement as to what “qualities” (for a lack of better term at the moment) one must possess in order to obtain said title.

With that out of the way: Last night I was “twitter lurking” (twurking?!? nah) and ran across a conversation regarding a company that was publicizing the number of Salesforce MVPs on staff for a given RFP. Some lively debate ensued (to which I remained a silent spectator) but it got me thinking, “What traits do I expect to see in an MVP?” I don’t think there is any one group of answers to such a question, but perhaps there are some commonalities. I’m going to try and stick to the items specifically called out in this particular discussion from last night.

  1. Knowledge of the platform: This is a given, but “how much knowledge?” Should this person be an expert in all aspects of the platform? Should they be “consultants?” Given the size of the platform and all one can do with it, I think this is a very, very tall ask. Are there some that can do/know it all? Possibly, but probably not. I mean its a HUGE platform and new stuff is coming out all the time. So in this case — knowledge of the platform sure, but in the absence of some of that knowledge of the details, knowledge of where to go to find the answers, and how to apply them to the task at hand can be more important. It helps to be as well rounded as possible but I don’t expect someone to have all the answers simply because they’re an MVP.
  2. Similar to the afore mentioned “knowledge” lets talk Certification: Should an MVP be certified? I think it certainly can’t hurt at all, and I think most people would expect an MVP to be certified. That being said — I can see situations where they may not be. Maybe they were at one time but their life got busy with children, family, hobbies and didn’t keep up their certification. That being said, the Salesforce community — and perhaps the Microsoft world, (maybe Novell — I’m aging myself here) are the only arena’s in which I’ve ever seen such emphasis on being certified. It absolutely helps your career to be able to say I am a certified X. However, I taught myself how to program in Java in the year 2000. I didn’t understand a damn thing at the time but was able to study for and pass the Sun Certified Java Programmer certification. Had any seasoned Java developer actually gazed upon my code at that time however — they’d have been in shock. I think it was at least a year afterward before I finally fully understood what a constructor was for, or what “this” meant, or what “static” really was. So certification helps no doubt, but how much weight does it actually hold? It at least shows initiative and dedication and I suppose that is something. However, I don’t see that as a requirement when the next three items are considered.
  3. Presence: An MVP should be present. Maybe not necessarily answering all the questions on Stack Exchange or in the Success communities, (I mean who can keep up with @SteveMoForce anyway?) but an active part of the community. Encouraging others, advocating for the platform, and sharing their experiences. The program’s own requirements point out that this can be a Twitter presence,  or Success Communities, blogging, etc. I assume its best to have a mix of all of those environments. First and foremost though — an MVP is present, friendly and approachable. (Queue the segue music…)
  4. Personality: This feels kind of strange for me to mention but I believe personality is probably much more important than many people think. Someone can be the best developer in the world, or the best admin — but if they aren’t friendly and approachable then I think it’d be very hard to fulfill that MVP role. Speaking as an outsider to the MVP world, I feel like those MVPs that I’ve met personally are absolutely friendly and approachable. I think we in the community get somewhat “star struck” if you will and may find it hard to introduce ourselves at first, but when you do you will find that they are very approachable people that are easy to interact with, and are relatable. That’s not to say they’re all extroverted and have all the time in the world to chat with everyone, and maybe some are just quiet, but they’re indeed friendly.
  5. Passion: Above all lies passion. An MVP has a passion for the platform, or the company itself, or a passion for the community. A passion to be knowledgable, to be present and approachable, and to help the others in this amazing community. When you interact with someone it should be pretty obvious from the start whether or not they have a passion for what they are talking about. They exude excitement for whatever it is they are doing. In some cases, they may not be the most knowledgable but they drive forward with energy to learn more and to bring others along with them on the journey. Their energy gets others around them excited too, passion rubs off on  people, its catchy. When people in the community start motivating each other, just look what happens (looking at you @Bill_Greenhaw!)

Is being an MVP more important than being certified? That’s a personal, perhaps company culture issue. Does being an MVP automatically make you a great consultant/employee? I don’t think so, no more than being a great consultant/employee will make you an MVP. I do however think that those traits all work together in harmony. So if there’s anyone in the community that has inspired, encouraged, or assisted you in some way, please take the time to nominate them.

So what do think? What makes an MVP an MVP?

 

:wq!

It’s the Community, Stupid!

Last year, I didn’t get it. I attended my very first Dreamforce in San Francisco, CA. I had just recently started a new job working with a former coworker of mine and was thrust into this world of fanatics. I sat there and listened to a very moving keynote, and watched the launch of a new mobile platform for interacting with Salesforce. I attended hands-on training sessions, attended numerous technical talks, and drank free beer. I still didn’t get it. All of this tech was all well and good, but it wasn’t doing anything that “only they could do” so to speak. I didn’t seem to understand the energy that everyone else around me was feeling. I’d been to many a tech conference in the past, and didn’t see people as ecstatic to be there as the 100+ thousand folks that were in attendance last year.

Dreamforce 2014 however is another story. This year I found myself thrust into this new world of people. I had the privilege of hanging out with another developer that for all intents and purposes is identical to me. We have the same insecurities when it comes to our capabilities on the platform and in our professional careers. We both have the same social anxieties, quirks, etc. This person is/was just like me. It seemed that this year we both vowed to come out of our shells and boy did we ever. We talked with strangers, actively sought out conversation (though I believe she was much better at it than I was), we helped each other become part of the community.

During a rather long walk back from the Gala we were discussing past experiences and at one point she just said “I LOVE SALESFORCE” — she practically danced when she said it, and was carrying the biggest smile I’d ever seen on her face. (She’s normally very quiet and reserved). At that point, it hit me: “It’s the community, stupid!”

It’s not the platform, the points, the clicks, the tech — those are all awesome, but its the people. Hearing stories of how this platform, this environment led them to jobs and experiences that have changed their lives is what makes this a great community to be proud of. Watching this normally shy and quiet person practically dance down the street was a much needed blast of fresh air for me, and the timing was perfect.

I’ve been slinging code since the late 90’s. I had passion for it back then. I had passion through most of the last decade but began to burn out in fear of becoming the 65 year-old cranky programmer that the new kids lock in the closet when customers come around. I burned out. Working 10 years mainly answering to marketing firms with very unrealistic expectations of real world I.T. hurdles nearly killed me…I mean that. My career at that time was putting me into very dark places at work but even more so in my personal life and I needed a change. (I know that sounds dramatic but its so very true).

Salesforce was a way for me to sort of change things up and “slow my roll” and its been a great experience. More often than not, I’m working with departments that understand business process, and how development actually works, that things don’t always go according to plan, that what seems like “magic” actually takes time and effort. I can’t say that I’ve found “new passion” for code — I’m always going to be a coder, but I feel my passion is shifting towards helping people. If that help is in the form of creating Apex, Visualforce, Lightning Components, answering questions, replacing a dryer vent, or re-assuring them that they friggin’ ROCK, it doesn’t matter. THEY matter…the people. This awesome place that is the Salesforce community.

I owe a very large part of my Dreamforce experience this year to that community and to people like: Erica Kuhl (@ericakuhl) for putting me out on her stage at the Communities keynote to sing my song, Bill Greenhaw (@Bill_Greenhaw) a Salesforce MVP that thinks that I’m “the stuff” (he didn’t use that word but that could have been the beer…ssshhh), Sarah Deutsch (@sarahforce) who gives the worlds greatest hugs, Michael Farrington (@michaelforce) for asking me “What’s next” and forcing me to think about the future. Brian Kwong (@kwongerrific), Mark Ross (@markross__c), Chris Duarte (@TheChrisDuarte) for pulling me into their circle, it was truly awesome. There are numerous others I could mention (@ericdresh, @andyboettcher) but this is beginning to sound like some weird Oscars speech, so allow me to lump in the other MVPs that I met, you all know who you are.

There are a few more people I’d like to shout out to but I don’t know their names. These were your everyday, non-MVP salesforce users/admins/dev like myself. I was standing in line to grab some books in the devzone when I struck up a conversation with fellow attendees. Before I knew it, they were asking ME questions about the platform and I was more than excited to help with what I knew and point to places for more information for what I didn’t. I was even thanked — maybe it was politeness, but maybe I indeed helped and it felt pretty damned cool. At other conferences, I always felt like I was the one playing catchup and therefore never spoke — to anyone — ever.

Lastly…I owe the overwhelming majority of this “lightbulb experience” to my good friend and developer twin: Jenny Bennett (@jennyjbennett). Without her stepping up her social game, I’d have likely spent another year as a under-confident wallflower. Watching her hit cloud 9 after passing part one of her Advanced Developer exam and seeing her have to fight to hide her overwhelming joy was an incredible and enlightening experience. Hearing her declare her love for the platform in the middle of downtown San Francisco put me over the edge. Even after she left on Thursday — (ditched me more like it) — it was because of her — and nudging from my colleague Kelly Leslie (@kellyleslie44) — that I was inspired and felt bold enough to attend the Cigar Bar party on my own. That is something I’d have never done last year, or any year before that, or at any other conference. I’m pretty sure I won’t have any problems next year getting out there and that’s all because of this year’s Dreamforce experience & the incredible community of people surrounding it. What you all — we all — have going on here is the most astoundingly supportive and friendly community in the industry. It’s not the platform, its the people…I get that now.

:wq!

Why Go to Dreamforce 2014

Since “I said so”  or “Because you get to see my ugly mug in person” won’t suffice, here are some valid reasons you should strongly consider heading to Dreamforce 2014 this year, particularly if you are a developer.

#1) The DevZone — last year was my first Dreamforce experience and sadly I missed much of what was going on in the DevZone. However I did find myself skipping out on a couple of sessions (sssshhhh) to go see what all the buzz was about. From arduino & Raspberry PI to 3D printers, this place had it all and was the ideal place to get your geek groove on. Oh yeah, and Bean Bags…lots of Bean Bags…

#2) H.O.T.s — Hands On Training. Last year I was only able to get into one of these things but it was great (Canvas Apps in case you were wondering).  They fill up early so be sure to reserve your place as soon as possible. How better to learn something new than by doing? Its how we do what we do right? Remember H.O.T.s == Good++ :)

#3) Mini Hacks — last year they had a huge hackathon, but the real action if you ask me, was in the mini hacks. I didn’t officially participate in them, but I did snag some of the challenges and spec things out in my hotel room later. This year, they’re definitely on my radar. I’m purposely going to leave a few holes in my sessions to see whats up for grabs.

#4) The Music –Not to be stereotypical but if you’re a geek, you are likely into music as well. I don’t know a single developer that doesn’t sling code without a pair of noise-canceling headphones and their favorite jam blaring full-bore into their cerebral cortex. Dreamforce has music everywhere you go. Last’s year’s Gala was Green Day (one of my favorites), this year is Bruno Mars — not exactly my thing, but he could be yours right? Its a big, big world. There were also a number of indies on the smaller stages throughout the week. Its everywhere, and its good…so good.

#5) Knowledge — last year there were 130,000 people at Dreamforce. The amount of concentrated knowledge in that one single spot in San Francisco is unfathomable and some of that knowledge is bound to rub off on you. If you’re a newbie like I was, you’ll come back invigorated, ready to put  your new found knowledge to practice. If you’re an expert already, you’ll no doubt pass on your knowledge to others. It can’t be helped, its what developers do, we talk about code. We eat, live, breathe code. Maybe you’ll even make a couple friends, get popular and find yourself on the next MVP list? Hey! It could happen.

#6) The people — they’re everywhere. You WILL meet someone new, even if you’re an introvert (I’m an introvert — it took me 20 minutes to get up the courage to go talk to a guy about his Google Glass — Glasses?? Glass? I digress). And let’s face it, we’re not there just to learn about the platform, we are there to hang out and let loose with “our kind”. I fully plan on earning a new nickname as the one I earned at Midwest Dreamin’, while rather entertaining just isn’t gonna cut it for me long term (sorry Bubba, EasyT and Blondie) — ask me in person sometime, its not for public consumption — and where better to ask me than Dreamforce 2014?.

Lastly — because I said so, and my ugly mug will be there — we can selfie :)

Go check it out.

:wq!

Thats Why Admin’s Drink

EDIT: My kickstart to get this professionally going. Please consider helping out.

Reverb Nation (link to audio)

As a hobbyist musician — lets face no Grammy’s are heading my way anytime soon — I couldn’t resist writing a song about Salesforce. I’ve been particularly infatuated with the hash tag: #ThatsWhyAdminsDrink. So today, I bring to the incredible admin’s all throughout the Salesforce community their very own song based on the afore mentioned hashtag.

This comes with a caveat however, not only am I NOT a professional musician — I’m even MUCH LESS a professional sound engineer. I can do some very basic “stuff” with Garage Band, but I feel in order to do this right, I’d like to have this professionally recorded in a studio but someone who actually knows what they are doing. To that point, I’d also like to add some studio musicians to the mix because I need drums, bass, and a guitar player that can solo. I have a few connections that I can line this up with no doubt but it all takes time and money. Time I can deal with, but money, not so much. So this is me, writing a song for a community I’ve enjoyed being part of for over a year now, asking for a little help in making this something we can all point to and tell our friends: “That song is about me — and what I do everyday” :)  Please consider donating to my Kickstarter project in order to help me make this a real thing :)

For now, the very rough recording can be found on my Reverb Nation page (Dammit Andy).

I know its rough, but please let me know what you think in the comments.

 

:wq!

Adventures in Apex Batch

Earlier today I was working with some web services and needed to be able to update a number of accounts in batch. Well I didn’t so much NEED to, but I had to allow for that possibility.  Due to the number of callouts being made to this external web service, any more than two accounts getting updated and I’d hit a callout limit.  Part of me wants to scream #YourDoingItWrong, but that’s another story.

So I found myself pouring over the documentation, various blog entries, and forum postings to figure out how exactly to tackle the issue.  I had already written the batch class to handle this, but it was once I tried putting that code into practice when things went awry.  I had a sneaky suspicion — that turned out to be correct, but more on that shortly — that the finish method in an apex batch class would be something that just “happens” — it would just get called.  However, in my testing it was appearing to me that I was wrong.  To add to the frustration, I was unable to find evidence that the finish method happens automatically. (I was assuming it was akin to a try/catch/finally block with the finish method being analogous to the “finally” clause). However, it *had* to be that way and indeed it is, but I was still in the weeds.  How about a little code? You can probably find where I went wrong. (Leaving out the juicy bits and replacing with pseudo code):

   global class BatchPushAccount implements Database.Batchable, Database.AllowsCallouts {

	String query;
	List accountsPushed = new List();
	List failures = new List();

	global BatchPushAccount() {
		query = ' start(Database.BatchableContext BC) {
		return Database.getQueryLocator(query);
	}

   	/* PERFORMED IN BATCHES OF ONE SINCE EXTERNAL SYSTEM HAS NUMEROUS
         * CALLS TO GET THINGS "DONE"
         */
        global void execute(Database.BatchableContext BC, List scope) {	
		for(Account a : scope) {
		 ...call out to web service here
                 ...if successful, set some values on account and then
                 accountsPushed.add(a);
                 ...else handle the failures behind the scenes
                 failures.add(customresponse);
		}	
	}

	global void finish(Database.BatchableContext BC) {
	    if(accountsPushed.size() > 0) {
		System.debug('Running update on pushed accounts');
		update accountsPushed;
	    }

	    if(failures.size() > 0) {
		System.debug('There were: ' + failures.size() + ' failures');
		ServiceUtility.handleFailedResponses(failures);
	    }	
	}
   }

Upon running the above code I *NEVER* saw my debug statements from the finish method and sure enough, the records were not updated on the Salesforce side. This started making me wonder “maybe finish doesn’t just happen.” I did some more reading and realized that I was doing this dry run through anonymous apex and began to wonder if I actually had to invoke the finish method myself. I ran across another blog entry that didn’t come right out and say this, but it DID make me realize I had yet to write a Schedule class to do this and call the batch from apex code (hmmm). Which I promptly did, thusly assuming I’d call finish from there, (which is WRONG), but for the purposes of other newbies like me trying to see what that looks like, its pretty simple:

        global class PushAccountSchedule implements Schedulable {
	    global void execute(SchedulableContext sc) {
	        BatchPushAccount b = new BatchPushAccount();
	        Database.executeBatch(b);
	    }
        }

I couldn’t even begin to figure out *HOW* I’d call the finish method since it takes an instance of a BatchableContext…”batch.finish(batch)” sure as heck didn’t make any sense…but after reviewing my code once more — it was obvious. The finish method was INDEED running, but my debug statements were depending on one of two lists being populated (see the code near the top of the batch class). This is where the light-bulb went on. The finish method appears to happen in an entirely different request and therefore the lists that I thought I was populating during my “execute” phase were now in fact *empty*. This was easily proven by placing a debug statement just inside the finish method and trying again and upon so doing, my new debug statement appeared whilst neither of the other two showed up. The finish method was doing what it was supposed to, there was just nothing there for it to do anything with. In the end I moved my update code from the finish method into the execute method of my batch (outside of my for loop by the way — that being said, it wouldn’t have mattered really since these were running in batches of 1) which worked flawlessly. So now my code as an empty finish method since there’s nothing I need to do once the job completes.

Lesson Learned: the execute and finish methods in a batch class do not operate within the same context. File this under #GoodToKnow and #IMustHaveMissedThatSomewhere

:wq!

EDIT: I’ve found this now too…just don’t know if its worth it or if it matters at this point. #BetterPracticeSomewhere?