More Info about the Apex Realtime Debugger

If you happened to catch my post last year about the release of the new Apex Realtime Debugger, then you might also be interested in checking out this demo recording which was made at the recent TrailheaDX conference last month.

The short talk was given by Greg Wester and if you are really just interested in seeing a good demo of the Realtime Debugger, then I suggest you skip the first 5 minutes of the 16 minute recording.

Greg also reveals at the end certain FAQ’s that you might be interested in which include:

  • The Debugger only works in the Sandbox and there are no plans to ever have it work in production.
  • Licenses are assigned via permission sets and you can only have one instance running per org.
  • It does not support asynchronous code. Only synchronous operations.
  • You can get a trial of the debugger if you contact your Account Exec.
  • This fall they will be doing a pilot with vendors that allows them to step through managed code. This should be of big interest to ISV’s out there.

ApexDebugger

Apply .NET Skills to Salesforce

NETTrailReleased yesterday is a new trail titled, “Apply .NET Skills to Salesforce” and it is all about wooing more .NET developers to the Salesforce platform, which I am of course, all for.

This FREE and most excellent resource is written by a .NET developer for .NET developers. It does not sugar coat anything about the platform, but instead tells .NET developers honestly and directly what the platform offers and how their existing .NET skills can allow them to transition easily to Force.com. It also points out a lot of the common pitfalls they will want to avoid to be successful on the platform.

It consists of two modules. The first is all about SOQL and database basics and it has the following 4 units:

  • Moving from SQL to SOQL
  • Writing SOSL queries
  • Writing Efficient Queries
  • Manipulating Records with DML

The second module (which is my absolute favorite), it all about Apex and the Force.com platform and it has the following units:

  • Mapping .NET concepts to Force.com
  • Understanding Execution Context
  • Using Asynchronous Apex
  • Debugging and Running Diagnostics

I hope you check them out, as well as the Salesforce platform, which is growing more impressive by the day. And please let me know what you think.

New Way to Avoid the Dreaded Mixed DMLError in Test Method

As of the Spring 16 release, there is now another way to avoid an error that would often occur when running Apex unit tests. The MIXED_DML_OPERATION error would occur because you can’t perform DML on a setup sObject (such as User, for example) and a non-setup object (such as Contact) in the same transaction.

So, if you had some code such as the following:


@isTest
public class UserAndContactTest {
    public testmethod static void testUserAndContact() {
        Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
        UserRole r = [SELECT Id FROM UserRole WHERE Name='COO'];
        u = new User(alias = 'jsmith', email='jsmith@acme.com',
                emailencodingkey='UTF-8', lastname='Smith',
                languagelocalekey='en_US',
                localesidkey='en_US', profileid = p.Id, userroleid = r.Id,
                timezonesidkey='America/Los_Angeles',
                username='jsmith@acme.com');
            insert u;

        Contact currentContact = new Contact(
            firstName = String.valueOf(System.currentTimeMillis()),
            lastName = 'Contact');
        insert(currentContact);
    }
}

The unit test code above would fail with the MIXED_DML_OPERATION error.

Previously, the only way to get around it was to enclose all the operations within a System.runAs block, but now you have another alternative in which you can use @future to bypass the error. For example, the following class could contain the code used to insert the user:


public class InsertFutureUser {
    @future
    public static void insertUser() {
        Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
        UserRole r = [SELECT Id FROM UserRole WHERE Name='COO'];
        User futureUser = new User(firstname = 'Future', lastname = 'User',
            alias = 'future', defaultgroupnotificationfrequency = 'N',
            digestfrequency = 'N', email = 'test@test.org',
            emailencodingkey = 'UTF-8', languagelocalekey='en_US', 
            localesidkey='en_US', profileid = p.Id, 
            timezonesidkey = 'America/Los_Angeles',
            username = 'futureuser@test.org',
            userpermissionsmarketinguser = false,
            userpermissionsofflineuser = false, userroleid = r.Id);
        insert(futureUser);
    }
}

And then, you could just change the original code to be the following:


@isTest
public class UserAndContactTest {
    public testmethod static void testUserAndContact() {
        InsertFutureUser.insertUser();

        Contact currentContact = new Contact(
            firstName = String.valueOf(System.currentTimeMillis()),
            lastName = 'Contact');
        insert(currentContact);
    }
}


And then there will be no more error. I think it is a better way of handling the issue than using runAs and should be considered when there is a need to run DML operations for setup and non-setup objects in the same unit test transaction.

Who-hoo – The new Apex Interactive Debugger is finally here!!!

UPDATE on 3/1/2017: If you are interested in learning more about the Debugger, check out this Developers Relations Post. I would also suggest you check out this very interesting StackExchange Post, in which someone who has actually used the Debugger chimed in. FYI: It costs about $18,000/year.

Any Salesforce developer that has migrated from another language (especially .NET) knows that the debugging capabilities in Force.com are…ummm, how shall I put it?

They suck! Yeah, that’s it.

Well, guess what? As of Winter 16, Salesforce is offering a new Apex Interactive Debugger that will finally make developers of other platforms feel right at home.

I am talking about an interactive debugger that allows you to set, remove and suspend breakpoints. It also allows you to step in, step out, step over and through your code, as well as view variables at any point in the stack and also output System.debug statements to the console window.

This new interactive debugger is being offered as an eclipse plug-in (see image below).

ApexDebugger

Now, I must offer full disclosure right up front and tell you that there is one really big gotcha with this announcement and that is this:

It’s going to cost you. As in money. I would imagine a good amount of it too (although you will have to contact your Account Executive to find out exactly how much). Supposedly you can purchase debugger sessions that can be shared by your whole development team.

But why? Salesforce has always offered development tools for free.

The big reason for this cost is not because Salesforce is trying to make a lot of money off customers. It is to effectively limit the use of the tool. Because Salesforce is a multi-tenanted environment and resources are shared, if every customer all of a sudden was granted access to the new Apex Interactive Debugger, guess what would happen?

Crash!!!! as in all the servers lock up and no one is happy.

The Interactive debugger uses a debugger session manager and every debugging session is a transaction that can last up to 30 minutes. Each transaction needs a thread and a database connection. These are very expensive resources and in a shared environment, if every customer was able to do this, performance problems would quickly result.

Another thing to note is that the debugger uses the debugging API and at this time, that API is not publically available. This means that you will not find this kind of functionality offered in any third-party tools, such as MavensMate. Once Salesforce works out the kinks, they will likely release it publically, but in the meantime, the eclipse plug-in is the only way to go.

Also, for obvious reasons, this will only work on Sandbox orgs.

If you are a partner or a big development shop (now I am starting to wish I was one of those), then these limitations and the cost will likely not offset the benefit to having this super new tool. If you are interested in learning more, check out this Dreamforce video in which Josh Kaplan walks you through using the new debugger.

Happy debugging!!!!

UPDATE on 3/1/2017: If you are interested in learning more about the Debugger, check out this Developers Relations Post. I would also suggest you check out this very interesting StackExchange Post, in which someone who has actually used the Debugger chimed in. FYI: It costs about $18,000/year.

Why Every Salesforce Developer should be using Trailhead

I have recently been using Trailhead to help me study for an upcoming exam and I have been incredibly impressed with how good it is. I have already posted about the Trailhead modules that cover new material, such as Lightning, but what I was surprised about was how useful it was for reviewing material that I thought I already knew pretty well.

Trailhead is definitely not exhaustive in it’s coverage, but what I like most about the modules is that they go over just the stuff you really need to know. And most importantly, they go over best practices. There are so many examples of inefficient and just plain bad code out there (even on some of the Salesforce sites I hate to say). The text and challenges in the Trailhead modules were well thought out and it is obvious they put a lot of time into developing them. It still Trailheadsurprises me that something this good is free, but fortunately for us, it is.

If you are preparing for one of the Certified Developer tracks, you really need to check out the Developer Trail. It covers a lot of what goes into the exams and the progressively harder challenges really solidify what you just learned. Unlike tutorials that you can just follow in your sleep, the challenges tell you to do something, but not how to do it. And, if you do not do it exactly right, you do not get the points. You actually have to THINK about what you are doing and this is absolutely the best way to learn.

And if you are a certified developer who has been doing this for several years, there is still stuff for you to learn, even when it comes to best practices. As we all know, this platform is changing constantly and that means that so are best practices.

And honestly, it is just fun seeing yourself rack up the points. I really like the WooHoo I get at the end of the challenge. I am proud to say I have 5 badges and over 12,000 points so far (with more to come). How many will you get?

Best Way to Generate Lots of Fake Test Data for Force.com Orgs

I am currently designing a course for lynda.com about improving Visualforce performance. I decided that it was necessary to load my Developer org with a bunch of fake Account data in order to demonstrate some of the performance improvement techniques I was suggesting. I am NOT talking about unit test data, but actual data (just randomly generated). I have tried to generate things like this in the past and it always turned into a big pain. So I went ahead and did some general queries to see if anyone had already slayed this dragon.

At first I was excited about an article I found on DeveloperForce about Generating and Loading Representative test Data for Salesforce and Force.com Orgs. Perfect, I thought. That is just what I need. Unfortunately, I needed it fast and this article details a painfully long way of generating a Ruby on Rails app and installing all sorts of things that I really did not have the time for. I have worked with RoR a bit and knew this method would take way too long.Fake

I did not want to create my own custom Apex factory or install some expensive app off the AppExchange. So back to searching and then I came upon the website GenerateData.com. I was a bit skeptical about it working, but in less than 15 minutes, I had generated my first data set for 100 Accounts and loaded it into my Dev org. I had hit the fake data jackpot!!!!

Now in all fairness, it did take me a few more tries before I got the data exactly the way I wanted, but this method was definitely fast and effective. I will also tell you that you are limited to only generating datasets of 100 records at a time using the Free version, but if you are willing to pay a very small fee (which I was, since I think it is a GREAT deal for all the time it saved me), then you can save data sets and generate as many records as you need.

And to save you a little time, I am including a screenshot of what my final Account Data Set looked like.

GenerateData

With my paid account, I generated 1000 Account records and imported them using the Data Import Wizard in Setup | Data Management. It took me less than 2 hours to get all the data loaded exactly as I needed it. I consider that HUGE!!!

I hope you find this tool as useful as I did. I sure do appreciate the developer, Ben Keen who wrote it! GREAT job!!!!

Considerations when Sending Outbound Emails Through Apex

email-outbound-imageIn a recent post, I went over things to consider when receiving emails using Apex code. In this post, I will go over some tips and considerations you should make when working with outbound emails in the real-world.

  • First off, in order to work with outbound messaging in your Sandbox (note that I said Sandbox and NOT Developer edition), you will first need to enable it since it is disabled by default in Sandboxes. You can do this by going to Setup | Email Administration | Deliverability  and changing the Access Level to All Email.
  • Even though you can create email templates using text or HTML, as long as you are NOT sending mass emails, consider using Visualforce instead to design a more robust and dynamic email template. I said the part about mass emails because Visualforce cannot be used in these particular situations. But assuming you are just dealing with single emails, then Visualforce can be a great alternative. Refer to this doc for more info on how to use them.
  • If you are a Sys Admin or you have permission to “Manage Public Templates”, then you can access the email templates by going to Setup | Communication Templates | Email Templates. Otherwise you can access the ones you have access to by going to Setup |My Setttings | Email | Email Templates.
  • Outbound email message limits are based on Greenwich Mean time (GMT) and not necessarily your time zone (unless of course, you live in England). Also, the limits on mass emails vary by your Salesforce Edition. Checkout page 16 of this Limits Cheatsheet for more specific info.
  • Even though the limits clearly state that you can send up to 1000 emails per org per day, this only applies to non-Development or non-Trial orgs. Development and Trial orgs are restricted to a far lower number of 10-15 messages per day (depending on when your org was created).
  • Most code examples I have seen out there do not show how to use the reserveMassEmailCapacity and reserveSingleEmailCapacity methods from the Messaging class. They can be used to check whether you will exceed the org limit or if the org does not have the right permissions when trying to send either Mass or Single emails. Prior to Winter 14, these methods existed, but for some reason using them still resulted in an unhandled limit exception. Using them should result in a handled exception and this is a much better way of avoiding unexpected outcomes. For example, the following code should now work ok:
try {
    Messaging.reserveSingleEmailCapacity(numOfEmailsToSend);
} catch (Exception e) {
    //handle your exception gracefully
}

Training Review: Force.com Training on Pluralsight.com

Anyone that reads my blog knows that I am big fan (and regular subscriber) of the Pluralsight training videos. I cannot imagine staying up to date as a programmer without them. At this time, there are only a limited number of courses that cover the Force.com platform (8 to be exact), but I expect new titles will be added very soon. logo-v4

I really think that viewing these courses can be beneficial to anyone studying for the basic or advanced developer certification, or just people working with the Salesforce.com platform in general. These courses can also be valuable to developers (of any platform) that want to determine whether learning more about the Force.com platform is beneficial to them.

Pluralsight offers a free trial that allows you to view 10 days and up to 200 minutes of training. That would allow you to view for free at least one, but maybe two of the courses I describe in this post. Below, I will summarize which courses you should view, depending on where you are coming from and what you are trying to achieve.

First of all, if you only have time to watch one of these courses, I would watch this one:

Force.com Platform: The Big Picture by Don Robins – This is a high-level course that would be very useful for someone brand new to the platform. It is short (1 hours and 24 minutes) and would also be of great interest to experienced developers that have not worked with the platform for long. Robins includes a lot of history about Salesforce and does an excellent job of describing the “Perspective Shift” that is necessary for developers that want to be successful on the platform.

If you are studying for the First-Level Salesforce Developer Exam, I recommend viewing the following course:

Force.com For Developers by Richard Seroter – This is the longest course in the series (5 hours and 47 minutes), but it is also the most thorough. It provides a good overview of the entire platform in a very clear and easy to understand way. Seroter covers many topics that are covered on the 401 Dev exams, such as Reports, Workflows and Approval Processes. He also covers topics on the 501 Advanced Developer Exams, so this course would be good for people studying for that exam as well.

If you are studying for the Second-Level Salesforce Advanced Developer Exam, I recommend viewing the following courses:

Force.com Design Patterns – Part 1 by Adam Purkiss – This course is definitely not for beginners or anyone new to the platform. Purkiss talks about advanced topics such as the use of wrapper classes to get around some of the inherent limitations of SOQL. Some of the code walk-throughs were unpolished and appeared to have not been practiced in advance, but the beginning of each section was very good. My favorite section was the one on Trigger Design Patterns.

Force.com Design Patterns – Part 2 by Adam Purkiss – This course has three distinct segments and I can see the first two (Test Design Patterns and VisualForce Architecture) being especially valuable to anyone pursuing the Advanced Developer Certification. I actually enjoyed this course more than the preceding Part 1, because the examples were more general and the author did not have to waste a lot of time describing how the sample application worked. Purkiss includes many best practices that if you follow will ensure that your code stands the test of time. I really enjoyed the section on how to use Knockout.js to do JavaScript Remoting to create an HTML page that saved custom settings directly to Apex.

Introduction to Visualforce by Matt Lacey – This was my least favorite course, mostly because the speaker had a heavy accent that was hard to understand. He also rushed through the content and the general audio quality of the video was bad. However, the course did provide useful content that would be relevant to anyone studying for the Advanced Developer exam.

If you are an Experienced Software Developer that wants to understand more about the Force.com platform, I recommend viewing the following courses:

Force.com for .NET Developers by Dan Appleman – This course does a very good job of describing the Force.com fundamentals in way that makes sense to .NET developers specifically. Appleman is an experienced author who spent many years creating content for the .NET community, but a few years ago he switched (almost primarily) to working with the Force.com platform. Like myself, Appleman does not dismiss the .NET platform and certainly sees it as still viable, but he also can see the alluring reasons to understand the Force.com platform as well.

Force.com and Apex Fundamentals for Developers by Dan Appleman – Unlike the last course that was specifically designed for .NET developers, this course was designed for developers coming from any platform. It is not a course for people new to programming, but attempts to give experienced software developers a head start to writing “GOOD” code on the Force.com platform. Appleman will tell you about best practices and describe real-world scenarios that only come from hard-earned experience. Most importantly, he covers why design patterns used in other languages do not always apply in Force.com. He focuses on the 4 most important concepts (Execution Context, Use of Static Variables, Limits and Bulk Patterns) that you need to know to start working safely and efficiently in Force.com.

Patterns of Cloud Integration by Richard Seroter – This is NOT a course specifically about Force.com and instead focuses on many technologies that can be used to accomplish integration with cloud applications (on any platform, Force.com included). This course would be of great interest to any technical architects that need to understand to complexities involved with integrating cloud-based applications. Seroter is no doubt an expert in this field and he covers a variety of tools and platforms (such as Biz Talk Server, Windows Azure Service Bus, Mule Cloud Hub and custom code using .NET, node.js, Java, etc) used to integrate Ground to Cloud, Cloud to Cloud, or Cloud to Ground scenarios.

Lessons Learned While Writing Apex Code

I have been writing object-oriented code for several years and specifically writing Apex code for over a year now, yet every time I go to create a new class or a trigger, I feel like I learn something brand new. This post is a summary of some of the most important lessons I have learned. I hope it helps you to avoid some of the same speed bumps that I have encountered.

Tip #1 – Make sure you “Bulkify” every Trigger

This is “THE BIGGEST TIP”. It is probably the one you will see the most written about, but it is so critical to writing good code, that I think it is ok to re-stress the point. In case you do not know, bulkifying a trigger means that the trigger can effectively handle being executed numerous times (200 times typically). trigger

Why 200?

Well that is usually the maximum number of times it can be executed (depending on the context). You see, your trigger can be executed multiple ways. It can be executed by users performing actions in Salesforce, or it can be executed by someone bulk loading data through the Apex Data Loader or the API. If your code is not written efficiently, it could very well throw the dreaded “Too Many SOQL Queries”. Trust me, you do not want to see this message.

So how do you avoid it?

Glad you asked. I am not going to bore you with a long detailed explanation of what you can do to bulkify your triggers, because honestly that has been done to death. I will however, tell you the golden rule to remember when writing triggers:

“If any of the following statements (SELECT,UPDATE, INSERT,DELETE) appear within a for loop, your code needs work.”

Basically, if any of those statements (which represent either a SOQL Query or a DML statement) appears in a for loop, this means you are executing a very expensive operation numerous times (or at least as many times as the loop iterates, perhaps even more). Avoiding expensive database calls is a common thing to avoid in any programming language, but is especially important for Apex development because of Salesforce’s Governor Limits (which imho are GREAT for ensuring that we all create the best code possible).

If you want to learn more about all the things you can do to bulkify your triggers, check out this very informative post by Salesforce Guru, Jeff Douglas. Everyone should also checkout the post on the DeveloperForce Wiki titled, “Apex Code Best Practices“.

Tip #2 – Create at least two testMethods in your Unit Test Code

Most posts or instructions I read did not really stress the importance of creating both a single instance and bulk instance testMethod in your test class.

Why two methods and not just one?

The first method should be for testing what happens when a single record is handled. It is here that you should include System.AssertEquals to test whether a condition is true. This will tell you whether the trigger actually did what it was supposed to do.

It is possible to write Unit Test code that does not do this kind of check and still get 100% coverage. However, I would not consider the test to be a good one and neither should you.

The second test method should cover what happens when the trigger must handle multiple records. The following code is an example of using two such methods to test the validity of a trigger.

TestBulkCode

Tip #3 – Bulkifying your code is not just important for triggers

So what else is it important for?

How about Unit test code contained in class files – especially the ones that were built while keeping tip #2 in mind. That’s right, even your unit test code needs to be written efficiently – especially when it is set to execute a bulk testMethod.

If your Unit Test code uses a For loop to create a set of records and performs a SOQL query or a DML statement within that loop, guess what? Not only might you get an error, but your code is going to take way longer than it should to run tests and ultimately deploy.

This tip also applies to methods contained within a Helper class. The more efficient your code, the better, so always assume the worst and expect all of your code to be called multiple times.

Tip #4 – Use Both the Developer Console AND the Force.com IDE

I have been very impressed with the newly available Developers Console. For a long time, the Force.com IDE was hands down the best tool for developing Apex code, but I feel like that is starting to shift – a bit, at least.

For some tasks, I prefer using the Force.com IDE – like for just browsing and editing code. I also love the schema editor for examining metadata. However, I am discovering that there are certain tasks that I prefer the Developer Console for.

The biggest thing is for running Unit Tests. In my experience, the Developer Console is many times faster at executing unit tests – especially the ones that test bulk methods.

I also like the way the execute anonymous code area is right at the top of the Console. It just makes more sense to me in this spot. I also like the layout of the Query Editor tab and especially that it returns the value of an AggregateResult (see image below). This is something you cannot do with a query in the Schema Editor of the Force.com IDE

DeveloperConsole

If you have not checked out the Developer Console or only glanced at it, I encourage you to give it a look. Try doing some tasks in one tool and then switch to doing the same task in the other tool. You may be surprised by which you prefer.

Tip #5 – Periodically go back and evaluate old code

Just like no two people will likely write the same identical answer to an essay test, no two developers will write the same development code (unless of course, you copy someone else’s code). There are dozens, maybe hundreds of ways to code some things and most ways involve inefficient code. Chances are high that you have written at least one piece of code that can be improved.

Learning how to be an efficient developer is a process. You do not learn it by reading one article, one book, or one post. It takes time to develop the skills to write efficient code in every situation – especially when you are new to a platform or language. Set aside time (say once a year) to periodically go back and evaluate old code you have written. You will probably be surprised at how much you can learn in a year.