The Silver Lining

Lessons & Learnings from a salesforce certified technical architect.

Archive for the ‘Apex’ Category

A Beginner’s Guide to Object-Oriented Programming with Apex: 1. Encapsulation

with 4 comments

This is part 2 in the series “A Beginner’s Guide to Object-Oriented Programming with Apex” and will cover the aspect of Encapsulation.

A Beginner’s Guide to Object-Oriented Programming with Apex

  1. Introduction
  2. Encapsulation (this post)
  3. Abstraction
  4. Polymorphism

What the hell is Encapsulation?

Encapsulation isn’t a tricky concept in itself but some confusion does arise from it’s close relationship with Abstraction (to be covered in my next post). Broadly it is defined as one of, or both of the following:

  1. An information hiding mechanism.
  2. A bundling of data and methods that operate on that data.

These are pretty abstract statements but in reality are very simple. I will demystify them with examples below but for now let’s use an analogy:

Imagine you have a watch (or if you have one just consider it, don’t worry about the imagining part) that tells you the date and time. You can adjust the date and time using buttons/knobs/switches but you have no idea what happens inside the watch, just that it results in the date and time changing. You have some data (the date and time), you have some methods to operate on that data (buttons/knobs/switches) and there is a whole lot of stuff going on in the background that you don’t know about (and it’s better that way, imagine you had to adjust all those bits and pieces yourself).

That’s encapsulation baby! Read the rest of this entry »

Written by Wes

June 17, 2014 at 6:09 pm

Posted in Apex, SalesForce

Tagged with , ,

A Beginner’s Guide to Object-Oriented Programming with Apex: 0. An Introduction

with 5 comments

Apex has come a long way in the past few years, and as Salesforce has grown so has the number of super smart people working on the platform. There are lots of guides on how to do fancy things using JavaScript, Apex and Visualforce as well as many more whitepapers on the topics of governances and standards. However I think there is a gap, and I’d like to plug it.

Over the next few weeks and months I will be releasing articles that describe and show the basics of object-oriented programming (OOP) with Apex. My approach will be to make these articles as modular and simple as possible. The target audience? Developers with a-teeny-bit-of-experience through to those who have tons of experience but never had any formal training in OOP.

A Beginner’s Guide to Object-Oriented Programming with Apex

  1. Introduction (this post)
  2. Encapsulation
  3. Abstraction
  4. Polymorphism

What the hell is OOP?

Good question, and although many agree on some elements of OOP there is still a divergent view in the details. Contrasting it to what came before helps though.

The programming paradigm prior to OOP essentially had everyone writing code as your would an essay i.e. a single long text with one line written (and executed) after the other. There were no classes, no methods, no GOTO statements even (if you go far back enough that is). If you needed the same complex calculation in 5 parts of your application you had to write it 5 times. This is obviously a bad idea and over time the geniuses that created computer programming started inventing bits and pieces of engineering to make it easier to create, maintain and extend their code. Collectively, these features together with their experience were the beginnings of OOP.

The most commonly cited features of OOP are described below.

Encapsulation

A way to hide state (or private data), but also – confusingly – a way to bundle data and capabilities to operate on that data.

As an example consider a sausage making machine, you pour some stuff into one end and get sausages out of the other without needing to know the internal workings. The inner workings are encapsulated within the machine.

Abstraction

This is one of the trickiest concepts because it is relative, you can have levels of abstraction and it essentially means providing the appropriate level of information and data at the requested level.

With my previous example, if you are the sausage maker then you just need to know what stuff to insert into which part of the machine. But, if you were the sausage machine repair man you would need to have the tools, knowledge and access to all the bits and bobs inside of the machine. These are different levels of abstraction.

Inheritance

A controversial aspect since some languages think that inheritance is bad. In short it is the capability of a class or object to have certain methods and attributes passed down to them through a hierarchy.

Now that I’ve started the sausage story I can’t stop! All sausages share certain qualities e.g. they’re all encased in something, have some type of contents and (usually) need to be cooked before being eaten. You could represent these common attributes in a parent class and have specific types of sausages (pork, chicken, blood pudding) “subclass this superclass” i.e. inherit from it.

Polymorphism

Polymorphism is extremely rewarding when you get it right because it just feels smart. In short it allows you to define ways of dealing with data without knowing exactly how that data will be defined in the future.

To finish off the sausage story (anyone else hungry?) you could put any type of meat into the machine but in the end you will still always get a sausage i.e. provided that a certain type of input (any type of meat and spice) is provided to the machine it “knows” what to do with it (make delicious sausages) even though the types of sausages may have differences.


Don’t worry if these concepts haven’t clicked just yet, each will be covered in detail in future posts.

These concepts are obviously academic and language agnostic but Apex makes them available to you through the constructs of classes, methods and attributes of those classes, instances of those classes.

A note on terminology. In the Salesforce world an Object is most commonly used to refer to a data entity e.g. Account or CustomObject__c. In the OOP paradigm an Object is an instance of a Class i.e. MyClass.cls is an Apex class which provides the blueprint for instances of itself. This becomes clearer with an example:


MyClass myObject = new MyClass();

myObject.divideByZero();

MyClass is the class, and myObject is an instance of that class AKA an object. Got it? Great.

Why Should I Use OOP?

Because it will make you a better programmer and it doesn’t hurt with the ladies/men (delete as appropriate). Your code will be better, you will end up doing less boring work and it will be easier (and quicker) to fix bugs. I guarantee it.

Next Time on Th3Silverlining

My next post will delve into the feature called Encapsulation so hit the subscribe button to find out when it’s published. See y’all then.

Written by Wes

June 6, 2014 at 5:10 pm

Salesforce: Universal Batch Scheduling Class

with 2 comments

Mark David Josue. All Rights Reserved.I’d like to propose a new way of working with scheduled batch classes. I’ve worked on several hundred Salesforce projects in the past few years and often see batch scheduling classes being created per scheduling requirement and it grinds my OCD – not in a good way. In most cases you should only need one “Batch Scheduler” per Org, let me demonstrate how and why.

The Universal Batch Scheduler™

Requirements

Let’s assuming you have a batch class that you need to run on a repeated schedule*, such a class signature is given below. That class will have to obey some conventions such as implementing the Batchable interface as shown in the standard documentation.

global class MyBatch implements Database.Batchable<SObject> {

// …

}

* For one off, schedule execution of batch classes you can use the System.ScheduleBatch() method.

The Scheduler

Now you might be tempted to created a scheduled Apex class specifically for this batch class, but by using the principle of polymorphism you could create a universal scheduler instead.

First of all you’ll need to implement the required interface for scheduled Apex classes as shown below.

global class BatchScheduler implements Schedulable {

// …

}

Next assign global, class-level variables which will be used to access the parameter values required when executing a batch class. Note that we’re creating a variable called “batchClass” whose type is the interface Database.Batchable. This means that any class that implements this interface can be assigned to this variable, this behaviour is called polymorphism.

  global Database.Batchable<SObject> batchClass{get;set;}
  global Integer batchSize{get;set;} {batchSize = 200;}

And finally implement the method required by the Scheduleable interface and use the variables to kick off the execution of a batch class.

  global void execute(SchedulableContext sc) {
   database.executebatch(batchClass, batchSize);
  }

Et voila! You now have a class that can be used to schedule any batch class in your Org. The final code being:

global class BatchScheduler implements Schedulable {
  global Database.Batchable<SObject> batchClass{get;set;}
  global Integer batchSize{get;set;} {batchSize = 200;}

  global void execute(SchedulableContext sc) {
   database.executebatch(batchClass, batchSize);
  }
}

In order to use it you would have to initiate the schedule from an anonymous block (Developer Console, Eclipse, Mavensmate etc.). For example I would schedule my batch class using something like this:

// Instantiate the batch class
MyBatch myBatch = new MyBatch();

// Instantiate the scheduler
BatchScheduler scheduler = new BatchScheduler();

// Assign the batch class to the variable within the scheduler
scheduler.batchClass = myBatch;

// Run every day at 1pm
String sch = '0 0 13 * * ?';

System.schedule('MyBatch - Everyday at 1pm', sch, scheduler);

There may be cases where the universal batch scheduler is not appropriate i.e. special pre-work has to be done in the scheduling class, but in most cases I’ve seen it’ll do the job. Hopefully this’ll help you make your Orgs a little neater too.

Written by Wes

February 2, 2014 at 12:34 pm

Salesforce JavaScript Remoting: Using Apex and JavaScript objects to pass data from client- to server-side and vice versa

with 13 comments

I’ve spoken about how to do this at a high-level during Cloudstock London and there are hints at how it can be done but no formal documentation that I’ve found, so here we are 🙂

Quite simply JavaScript Remoting will transform Apex objects and classes (or collections of these types) into JavaScript objects for you. The opposite is true too but there are some rules you need to observe.

Apex Types to JavaScript Equivalents

This is the easier of the type conversions in that you don’t have to really do anything to make it happen. The code below uses a custom class that I’ve defined but you can do the same with any sObject too. Let’s have a look at the code.

The Controller

public with sharing class RemotingObjectsController {

    /* The remoting method simply instantiates a two custom types, puts
       them into a list and then returns them. */
    @RemoteAction
    public static List<CustomClass> getClassInstances(){
        List<CustomClass> classes = new List<CustomClass>();

        CustomClass me = new CustomClass('Wes');
        CustomClass you = new CustomClass('Champ');

        classes.add(me);
        classes.add(you);

        return classes;
    }

    /* My custom type */
    public class CustomClass{
        public String firstName{get;set;}

        CustomClass(String firstName){
            this.firstName = firstName;
        }
    }
}

The Visualforce

<apex:page controller="RemotingObjectsController">
  <script>
      // Will hold our converted Apex data structures
      var classInstances;

      Visualforce.remoting.Manager.invokeAction(
        '{!$RemoteAction.RemotingObjectsController.getClassInstances}',
        function(result, event) {
          // Put the results into a var for pedantries sake
          classInstances = result;

          console.log(classInstances);

          // Assign the first element of the array to a local var
          var me = classInstances[0];

          // And now we can use the var in the "normal" JS way
          var myName = me.firstName;
          console.log(myName);
        });
  </script>
</apex:page>

The Output

Console output from the JS code.

JavaScript Types to Apex Equivalents

This is a little tricker, especially when it comes to sObjects. Note that the approach below works for classes and sObjects too.

The Visualforce Page

<apex:page controller="RemotingObjectsController">
  <script>
      /* Define a JavaScript Object that looks like an Account */
      /* If you were using custom objects the name must include the "__c" */
      function Account(){
          /* Note the field names are case-sensitive! */
          this.Id = null; /* set a value here if you need to update or delete */
          this.Name = null;
          this.Active__c = null; /* the field names must match the API names */
      }

      var acc1 = new Account();
      acc1.Name = 'Tquila';
      acc1.Active__c = 'Yes';

      var acc2 = new Account();
      acc2.Name = 'Apple';
      acc2.Active__c = 'Yes';

      var accounts = new Array(acc1, acc2);

      Visualforce.remoting.Manager.invokeAction(
        '{!$RemoteAction.RemotingObjectsController.insertAccounts}',
        accounts,
        function(result, event) {
          console.log(result);
        });
  </script>
</apex:page>

The Controller

There not much to the controller in this case.

public with sharing class RemotingObjectsController {

    @RemoteAction
    public static void insertAccounts(List<Account> accounts){
        insert accounts;
    }

}

Why is this cool?

Good question. If the Force.com Platform didn’t do this for you then we – the developer – would need to convert ours types explicitly on both the server-side and the client-side, and man-oh-man is that boring, error-prone work. Yet again the guys at salesforce.com have built in a convenience that saves us time and let’s us get on with the work of building cool apps.

Written by Wes

June 22, 2012 at 11:06 am

Salesforce: JavaScript Remoting – a different way of thinking

with 6 comments

 

Remoting is awesome.

JavaScript Remoting for Apex operates in a very different paradigm from what you might be used to i.e. Visualforce pages have controllers and the two interact through action methods – where this might be a full form submission or some neat AJAX functionality. Remoting also calls controller methods but there is a gaping maw in terms of how the two work under the hood.

I’ve seen a few great articles on the syntax and example usage of JavaScript Remoting for Apex but when I started using it I came across a number domain differences that weren’t documented anywhere. Hopefully my list here will help you in the learning process. The best way to describe the new way of thinking is to examine the features set in contrast to “normal” Apex and Visualforce.

How JavaScript Remoting Differs

  • Pass parameters naturally i.e. the call matches the method signature syntactically instead of requiring <apex:param/>.
  • Action methods when called in “normal” Visualforce can only return NULL or a PageReference. Remoting allows you to return a wider range of data types, even objects and collections.
  • Remoting methods have no access to the view state e.g. if a static variable is initialised to some value (outside the remoting method) a remoting method will see this as NULL unless it is re-initialised in that method! Conversely if a remoting method sets a state variable value the scope of that value is only within that method.
  • It’s much faster. I’m building an application at the moment that is 95% backed by JS Remoting and when I show it to other developers they are struck dumb for at least 3 hours because of the speed.
  • Neater debugging info in the browser console. Salesforce has done a great job of providing feedback directly to the browser’s console log.
  • Each method call gets its own executional/transactional context i.e. fresh governor limits per call!

If I’ve missed anything please let me know and I’ll add it. Viva la knowledge crowdsourcing!

Written by Wes

February 5, 2012 at 4:05 pm

Salesforce: Dynamically determining the field type of a dynamically determined sObject

with 2 comments

This solution is quite difficult to find.

Call me crazy but I need to do this from time to time, and every time I do I can’t remember how I did it before! So I then trudge through the API and the Apex docs until I find the answer and that’s no mean feat in this specific case. Well, no more my friends because I’m putting it right here on this very blog!

In short the code below will return (as a String) the type of field that we’re working with. Neither the name of the object or the name of the field need to be known in advance.

    public static String getFieldType(String fieldName){
    	// Assume that "sObjectName" is populated elsewhere
	Schema.SObjectType t = Schema.getGlobalDescribe().get(sObjectName);

	Schema.DescribeSObjectResult r = t.getDescribe();
	Schema.DescribeFieldResult f = r.fields.getMap().get(fieldName).getDescribe();

	if (f.getType() == Schema.DisplayType.String){
		return 'String';
	} // .... else if

	return null;
    }

Written by Wes

February 1, 2012 at 9:33 pm

Salesforce: Different percentage unit test code coverage in different environments

with 3 comments

Spot the difference.

Many people are finding that their tests are reporting different degrees of test-coverage in different environments. There are a few things to check if you are getting inconsistent results but there’s a new bug in the wild. Before you assume you have the bug make sure that you’ve:

  1. ‘Run All Tests’ in each environment. This will tell you a few things viz.
    • Perhaps there are tests failing that are bringing coverage in that environment down.
    • There are some tests that only fail when run in the browser e.g. MIXED_DML_EXCEPTION will not rear it’s head through the IDE.
  2. Click the ‘Compile all classes’ link above the Setup > Develop > Apex Classes view. I’m not sure when this lil’ bugger first appeared but it’s darn useful. Essentially it makes sure that all the dependencies in your code are fulfilled e.g. if page A uses controller B that in turn refers to utility class C it’ll make sure each of those pieces exist and work (as far as compilation goes at least).
  3. Double-check your test classes to make sure they’re not data dependent. If they are and you have different types/amounts of data in your respective environments it’s 100% feasible that the test coverage will be different.

Now if you’ve checked all of the above you might have been afflicted by a new bug which, for some reason, counts braces, whitespace (and more!) as being uncovered by your tests. This is preposterous of course and to fix it simply remove all test history from the deranged environment. Re-running the test and/or deploying them should now be back to normal!

Written by Wes

November 30, 2011 at 11:01 pm

Salesforce: Stop email being sent on user creation or password reset or …

leave a comment »

I’ve had to do this a few times but infrequently enough for me to forget how to do it each time. Forgetting things isn’t usually an issue because of our Google Overlords and their mighty The Google but it’s quite a journey down the rabbit hole to find this specific information.

The reasons it’s tricky to find is because the setting that controls whether an email is sent to the user on creation is not directly associated with users but with DML. Long story short you need to set a particular Database.DMLOption e.g.


User u = new User();
// Add some details here ...

// Set the DML options
Database.DMLOptions dlo = new Database.DMLOptions();
dlo.EmailHeader.triggerUserEmail = false;

Database.insert(u,dlo);

Hopefully this information will now be easier to find next time I forget 🙂

Written by Wes

October 30, 2011 at 1:12 pm

Posted in Apex, SalesForce

Tagged with , , , , ,

Salesforce & LinkedIn Developer API: 401 – Unauthorized

with 3 comments

Image representing LinkedIn as depicted in Cru...

Image via CrunchBase

I’m not going to get into the boilerplate code you’ll need in order to get OAuth up and running as it’s pretty straight forward, but I did run into a peculiar issue which took me some time to narrow down. To reproduce these steps you’ll need to:

  1. Correctly setup OAuth between the Force.com Platform and LinkedIn
  2. Authorise access to your LinkedIn account
  3. Attempt to fetch a resource using an API endpoint such as: http://api.linkedin.com/v1/people/~/network/updates?scope=self

When attempting to make the call out in step 3 you’ll get a “401 – Unauthorized” error. So to be clear OAuth is working perfectly but a call like this one will still result in the error.

After some troubleshooting I noticed that some API endpoints didn’t result in the error e.g. http://api.linkedin.com/v1/people/id=abcdefg/network/updates?scope=self. At this point I realised the issue was probably the tilde (‘~’) character in the URI.

Grasping at straws I manually replaced the tilde with it’s URL friendly equivalent ‘%7E’ and the callout worked perfectly. Now this is strange because I am, in the course of making the callout, URL encoding all parts of the endpoint URL. It seems that for some reason the LinkedIn OAuth services needs to have the tilde encoded twice when signing the request :/

Salesforce: Programmatically Populating Sample Data Post-Deployment

with 12 comments

I’m not sure if this concept is obvious when reading my previous post, so I thought I’d run through it with a specific example.

Rule one of packaging - Finish your bolognese first!

Let’s say that you’ve created what can only be described as an exemplary application in the form of a Managed Package. Although your user interface is beyond compare, you’d also like to populate some of your core objects with example data. Some options that immediately spring to mind are:

  1. Get the person that installs the package to call you, and you can do it post-installation.
  2. Get the person that installs the package to create sample data manually post-installation.
  3. Give the user a “Start Here” page with a call-to-action – such as a commandButton – that fetches the data from some API and parses into object data.

Option 3 is pretty excellent, especially now that you can package Remote Site Settings but I think we can do one better. And when I say better I mean simpler and with fewer potential points of failure. Read the rest of this entry »

Written by Wes

January 28, 2011 at 6:45 pm