Category: Salesforce

Salesforce Spring15 Test Class Additions

Salesforce has finally introduced a way to create test data for an entire test class; this will be a huge time savings for developers.

The rollback of records created during execution happens at the end of the test class’ execution. By only inserting records once, we should see tests run faster and require less system resources.

Lately, I have been updating all of my test classes to use this new @testSetup annotation. One thing to keep in mind, is that it will not set static variables and has a bug for package developers.

Here’s some sample code:

@isTest
private class join_Controller_Test {

	@TestSetup static void CreateTestData() {
		Util_TestSetup.createSettings();
		Account acc = Util_TestSetup.createAccount();
		Util_TestSetup.createContact(acc.Id);
		Util_TestSetup.createOpportunity(acc);
	}

	static testMethod void Test_Load() {

		Account acc = [select Id from Account];

                PageReference p = new PageReference('apex/internal_join');
                p.getParameters().put('acc', acc.Id);

                Test.setCurrentPage(p);
         
                test.startTest();

                internalJoin_Controller controller = new internalJoin_Controller();
		system.assertEquals(null, controller.OnLoad() );
		system.assertNotEquals(null, controller.acc );

                test.stopTest();
	}
}

I hope that the addition of @testSetup will finally result in better tests on Salesforce. As most programmers with test experience know, testing in Salesforce isn’t usually true unit testing.

Most are usually coded to be integration tests instead. Unit tests are tests that written to verify small sections (“units”) of code; integration testing is testing how the different units work together.

Another common, and disturbing trend, is that most programmers are simply coding unit tests to just get the 75% coverage and not using asserts. By using asserts, the tests can help significantly reduce bugs before code leaves development.

Introduction to Salesforce Trailhead

When Salesforce introduced Trailhead in the Dreamforce 2014 Developer Keynote I wasn’t overly excited. Trailhead is Salesforce’s Learning Platform; it’s designed to teach you how to administer and program in force.com

Over the last few months, it’s really started to come together and offer lots of interesting content, and challenges.

Overview

Trailhead consists of three different trails (or streams) that cover different parts of the force.com platform. The trails are then split into modules which take anywhere from a few minutes to about an hour to read and complete the challenge.

Trailhead Streams

Each module has examples, videos, and follow up exercises. The follow up exercise is often a multiple answer quiz or doing some sort of task through the platform.

To work on the system you need to have a salesforce developer community account, and then login. For each challenge you will be asked to link a Developer Edition account. This process is relatively seamless and simple.

I strongly recommend using a new developer edition account as it will break some challenges if you have different permission sets and validation rules. Error messages provided are incredibly generic and don’t usually seem to exist with a new developer edition account.

Trails

As you can see from the above photo of the trails, they are split into basically three distinct sections of force.com. The first trail or “Getting Started with the Force.com Platform” covers the basics of security, creating a custom app, and creating a custom object. The section about security is incredible well written and I believe we all have the potential to learn something there.

Challenges

Salesforce has cleverly built gamification into Trailed by giving out points for completing challenges. Once you have completed a trail you receive a badge. which is visible on your public Developer Community Profile for all of the world to see. 🙂

What’s really great about the challenges is that they aren’t just about coding or “declarative programming”, but there’s also some different tasks with configuration.

The data security trail covers a lot of different configuration options with profiles and permission sets.

Making the Most of Salesforce Trailhead

  • Read the text on the page, and Watch the videos. Some of the videos include information that isn’t really included in the text on the page.
  • Do the practice exercises. Most of these exercises only take a few minutes.
  • Look at the related resources.These resources mentioned at the end of many units are useful.
  • Celebrate your successes and failures; this is part of the learning process. We only can get better by doing. Post on twitter or Facebook when you’ve succeeded.

Conclusion

I believe Salesforce Trailhead is worth trying, and I’m sure even the seasoned expert can learn something as SFDC sure is a huge system. Salesforce seems to be adding new modules to the trails as newer features are being added; for example, there’s now a module regarding lightning/aura.

Hopefully they continue to keep adding to Trailhead, so we can learn about new features right around the time they are available in the new releases.

Happy hiking!

How to Make the apex:pageblocksection header collapsible

Since I’ve started developing for Salesforce one thing that has always frustrated me is that the apex:pageBlockSection’s header wasn’t collapsing the section when it was clicked. In this post, I’ve provided example code that will allow you to make headers collapsible when clicked by the user.

By adding the below JavaScript, we can easily add the collapsing to the headers. Make sure to include jQuery, and to add this code to your onload function. If you aren’t sure how to include jQuery please read my article on how to include jQuery in visualforce.

//Makes apex:pageBlockSection whole header clickable instead of that little ridiculous arrow.
jQuery('.tertiaryPalette').click(function() {
var eId = jQuery(this).parent().attr('id');

if (eId != null && eId != '')
twistSection(document.getElementById(eId).childNodes[0].childNodes[0]);
}
});

//we need to readd the click event to the little arrow image; or some users may be confused.
jQuery('.tertiaryPalette img').click(function() {
var eId = jQuery(this).parent().parent().attr('id');

if (eId != null && eId != '') {
twistSection(document.getElementById(eId).childNodes[0].childNodes[0]);
}
});

Salesforce Spring15 Including Mapping Features

Salesforce’s Spring 15 release is going to include mapping and geolocation for address fields. I believe, location based features started appearing before I started using Salesforce.

Even more exciting, is that visualforce will include a map component. The mapping component appears to be using Google Maps, but this could probably change.

The new mapping component uses JavaScript to zoom, and move around.

If you get an error when including the maps that reads something like this: “visualforce maps are not enabled for your organization. please contact your administrator” you will need to enable them by following the below directions.

How to Enable in Pre-Release
Setup -> Build -> Customize -> Maps & Location -> Settings. Read the disclaimer and click Okay or Agree.

Including the Map in Visualforce is incredibly easy; it can be done in basically one line of code. The component is simply apex:map.



If you get an error when trying to save the page, make sure your page version is at least 32.

Dreamforce 2014 Notes: Write Apex Tests Using Best Practices

One of the hands on training sessions I attended was “Write Apex Tests Using Best Practices” which really proved to me that a lot of what I believed and was doing were right.

Without further ado, here’s my notes:


Goals for tests

  • Auomated methods that verify application integrity
  • Future Proof
  • Proactively Identify Problems before they enter production
  • Salesforce Runs all customer tests before updates
  • Postive tests & Negative tests
  • Classes that are demarcated by the @isTest annontation won’t count against Apex code limit
  • contain member methods that can only be contained & used in a test
  • tests always have a void return type & no params
  • tests are always static
  • single autonomous transaction
  • only heap space, governor, etc
  • tests should insert their own test data
  • tests should be able to handle uncaught exceptions, etc
  • tests should have assertions to determine validity

Tests Leave No Footprint

  • Apex tests will not commit changes. SOQL still finds records
  • will not performs callouts to external web services
  • will not send outbound email

 

Tests Expect to Work with Mock Data

  • static resources can be used to stage test data in a cache
  • SOSL searches will not find pre-existing records
  • SOQL queries will only find pre-existing records for the following objects:
    • User
    • Profile
    • Organization
    • RecordType
    • For all other objects, SOQL visibility may be overridden with @isTest(seeAllData=true)

Governors

  • verify code is bulk ready
  • pass up to 200 records

Verify End State

  • using assertions

Best Practices

Don’t Depend on Pre-Existing Data

  • Avoid SOQL to initalize SOQL using SeeAllData=true
    • less portable
    • inconsistent results
  • Utilize mock data
  • Call Test.loadData() in a test method to populate
  • Create reusable mock data factories
  • Triggers should never contain business logic, they should only contain calls to classes
  • Use a Naming Convention like NameOfClass_Test
  • Exclude mock data initialization and result verification actions from governor calculations
  • Create separate tests with narrow goals

Challenges

  • blue boxes: test logic
  • grey boxes: business logic

Testing Visualforce Controllers

  • Mimic VisualForce page interactions by explicity calling methods
    • Form fields, eg form.Name use getter/setters
  • Test controller extensions by mocking the controller that was extended

 

Test.startTest synchronously runs asynchronous Apex

Testing Callouts

  • developers need to implement mock calls and responses that do not access the web services
  • setMock() needs to be run to do the fake response and call out

Testing Record Access

  • use System.runAs() methods to verify test users can find records that were shared with apex
  • using System.runAs() is a best practice.

Dreamforce 2014 Notes: Writing Apex and Visualforce Using Re-usable Patterns

Why use patterns:

  • patterns help us be more efficient
  • patterns describe reusable solutions to common problems

Bulk Processing

  • Caching
  • create triggers w/ ability to process hundreds of lookups
  • challenge: queries, DML, memory
  • collect all keys from trigger object in Set Object
  • Query once using SOQL in clause with key set
  • cache results in map object
  • look up related values using map key

Apex Summary Rollup

  • Need to roll up from a child to a parent in a lookup relationship
  • No declarative option for rolling up in a lookup relationship
  • Identify parent IDs affected by change in child.
  • perform an aggregate query on child records
  • update parents using IDs

Configuration Abstraction

  • Manage values that change from environment to environment
  • Maintainability
  • Ease of use

Pagination

  • display records one page at a time
  • performance and maintainability
  • StandardSetController

Search And Sort

  • Allows users to apply search criteria and column sort
  • challenges: Performance and maintainability
  • reusuable Apex and component framework for Search and Sort
  • Dynamic SOQL to modify Where and Order by query clauses

http://developer.force.com/cookbook/recipe/trigger-pattern-for-tidy-streamlined-bulkified-triggers

Looking Back at Dreamforce 2014

Welcome to DreamforceI was really blessed to be able to attend Dreamforce and learn even more about Salesforce.

While attending there, I attended a lot of the different keynotes and saw a lot of the new exciting features in action.

Dreamforce Sessions

At Dreamforce there was dozens of interesting sounding sessions. There were a few different ones that really stood out to me and offered interesting and new material to me. I believe that a lot of the sessions were recorded and able to viewed at a later date which is really exciting and available on youtube here.

One of my favourite sessions was Advanced Development using Apex Design Patterns by Robert Nunemaker. The vide is one if the hundreds uploaded by Salesforce to youtube here.

New Product Announcements

Before attending Dreamforce, I didn’t realize that Salesforce made a lot of its new product announcements there. Some of the new products they announced were: Lightning Components, Process Builder, Salesforce Wave,

Wave / Analytic Cloud

By Far, Wave was the most interesting announcement at Dreamforce 2014. It is a fairly dynamic business intelligence product that is optimized for use on mobile devices. What’s most awesome about Wave is that it will allow for on the spot and completely interactive exploration by business users rather than the static generated reports that have been prewritten.

Duplication Prevention

Through the use of fuzzy logic and other logic it will now be possible to stop duplication from occurring within Salesforce.

Sale Reach

Sales Reach units the power of Pardot, Communities and Sales Cloud into one system. Apparently, it will be able to do popup notifications on the Salesforce1 Application and assist with Leads/Prospect Tracking.

Lightning

Lightning is all about reducing development time and code. Lightning is basically a component framework and new set of tools that make building apps and making automation much faster.

Lightning Components allow developers to create reusable components for use in building apps. Lightning seems to be an event-driven architecture that makes use primarily of JavaScript and model-view controller architecture.

Process Builder allows business processes to be automated more easily and in a visual way.

Lightning Connect is the ability to connect to external data sources and with point and click be able to incorporate the data into Salesforce. The basic idea is that gone are the days of legacy systems and data silos, it would now be possible to use this data in Salesforce and with Wave.

Service Cloud

Smart Agent Console is designed to make it easier to provide good customer service to customers by making searching more intelligent, and where applicable making it possible to show sales data and billing data. It’s no secret that more competent agents allows companies to offer better service with less agents, reducing their service costs.

Community Cloud

Community Designer offers a few different themes that out of the box allow businesses to better connect to customers and reduce support costs. Community Designer allows new communities to be deployed by writing no-code and using point and click.

Topics allow users to access all of the relevant information in one place and even follow it to always stay up to date.

I’m so excited for Dreamforce 2015 and can’t wait to go.

Standard Salesforce Object Id Prefixes

The first three digits of an Id is an identifier to the type of entity that the object is. It doesn’t matter if the Id is a 15 digit or 18 digit id.

SObject ID Prefix
Account 001
Case 500
Contact 003
Lead 00Q
Opportunity 006
Task 00T