Posts in "SalesForce" category

Asynchronous Apex and Transaction Boundaries

When asked the question: “Just when does asynchronous apex actually run?” Most people will answer by saying something along the lines of “when the system has available resources”. And they’re correct, or at least partially correct as there is one other important thing to remember; it won’t run until the successful completion of the current transaction. But is this always the case?

Why is this important?

Let’s take a simple and common example; we need to call an external webservice to keep some data in sync as it changes within Salesforce. Since we can’t make a callout from within a trigger the accepted pattern is to call a future method (considered to be asynchronous apex) with the callout=true flag set. This creates a new transaction for us that isn’t part of the trigger and we’re free to call our external system.

This is all good so far. Now let’s imagine that for some reason our trigger, after calling this future method throws some kind of unhandled exception. This means that the whole transaction is going to be rolled back with no changes being committed to Salesforce. If our future method executed as soon as we called it we would now be in a situation where the external system is out of sync with Salesforce. Hence why the platform waits for the current transaction to finish successfully before letting it be run.

So why are you bringing this up?

Let’s be honest I’m not going to be bringing this up purely for the educational purposes of the masses. I’m bringing it up because I believe that I have found an annomoly with this expected behaviour. Let’s look at the following code, a trigger and a helper class;

Pretty straight forward stuff. So what am I expecting to see if I run the following execute annoymous code;

Well, we’re inserting 300 records and we know that the platform batches calls to triggers up into 200s so we should come through our trigger twice and as such call two future methods. We should be able to see that in our debug logs. Also we remember that both executions of the trigger are in the same transaction (the debug of the count shows us that too) therefore both of our future methods should run after the trigger transaction has completed. And if we look at the timings for the trigger and the future methods we can see that this is indeed the case.

1-GoodSummary 1-GoodTrigger 1-GoodFutureA 1-GoodFutureBGet to the point!

So far all I have done is to describe what should happen and then demonstrate that it does happen; not the most interesting of post. Let’s alter this example slightly and see what happens. Instead of inserting the data using an execute anonymous block let’s use the data loader. I have loaded a simple CSV file with 300 accounts in it via the Data Import Wizard. We’re loading the same data so we’d expect to see the same results in the debug log.

If we check the execution of the trigger itself we can see that we have, as expected, passed through it twice and within the same transaction. So that’s good.

2-BadTrigger

However a closer look at the times of execution highlight a problem. We can see that one of the future methods is being executed before the trigger transaction has completed. This is not how we expect the platform to behave.

2-BadFutureA 2-BadFutureB

Is this really such a problem?

Yes! Yes it is. Let’s change our code to throw an exception in the second pass of the trigger. And then rerun our two tests.

3-GoodSummary

In the first test, the execute anonymous one, we see that the future methods never run. This is good, remember our sync example before? If there’s an unhandled exception and the transaction gets rolled back then we don’t want to communicate with the outside world.

The second test, loading via the data import wizard, doesn’t look so good.

3-BadSummary

We can see that one of the future methods has been executed despite the fact that in reality the whole transaction should have been rolled back. So, whilst no records will have been inserted our future method is still called. It’s interesting to note that the second future method isn’t called, the one that is in the same trigger execution as the exception.

What can we do about it?

To be honest I don’t think there’s a great deal we can do about it other than be aware right now. I have seen this behaviour with queueable jobs too, so I am presuming it affects all asynchronous apex. My personal next step is to raise the issue with Salesforce and get some clarity around it and whether it’s a bug.

Streaming Lightning: Sometimes Electricity and Water Do Mix

It’s all about Lightning right now and rightly so it’s the future; a good looking, exciting future. So what have I been doing with all of this then? I always find new technology is best learnt when you have a real use case and I have been lucky enough to have one to work on over the past few weeks. Not only that but it’s one that has lead me to have to do something that I couldn’t find documented anywhere!

Continue Reading…

An Erratum From The Salesforce1 World Tour In Paris

Last week at the Paris World Tour I was asked a question about the getContent() and getContentAsPDF() methods on the PageReference class. I was rushed and gave the best answer that I could at the time. However, as the two gentlemen left me I had a nagging feeling that I was missing a piece of information. This morning I have finally found the time to come back to the question and get the complete answer. But first the question;

Why do getContent() and getContentAsPDF() throw an exception when called from a future method, despite the documentation saying that you can do this?

Continue Reading…

Deprecated classes visible in Process Builder

Lightning Process Builder has been around a while now and I think that we’re all starting to get use to it and see it’s potential; it’s massive.

There are of course a few teething problems, as you would expect, and they have mostly been documented but I just wanted to add to the list. Not as a complaint, more as a warning.

Continue Reading…

Is this thing on?

One of the biggest challenges that I face when writing my code is making sure certain things are enabled in an Org. For example some people still don’t have Chatter enabled so trying to post to a feed is going to cause my code to blow up. Each time I come across something like this I always have to go hunting to find the best way to figure out if something is on or not. This trawling of the internet finally got the better of me the other day and I have started a Feature class.

Continue Reading…

When Two Become One: Data in VF Controllers

We all love Visualforce, right? It gives us the chance to have that finer grained control over how things look for users and users love us making things look good for them – often much more than any functionality we provide. And when dealing with Visualforce, it’s often not long until we need to write a Custom Controller or a Controller Extension in Apex to allow us to fulfil some requirement or other. Controllers provide us with three main functions; to provide access to data, to provide us access to business logic through actions and to provide navigation. Actions and navigation are pretty straight forward as there is only one way to implement them in your controllers. Data however can be implemented in two ways and what’s worse… at the same time!

Continue Reading…

All decimals are equal, but some decimals are more equal than others

I learnt something rather intriguing today on the old Force.com platform: decimals just don’t behave how I expected them to when converting them to strings. I have obviously set myself up with that line but nevertheless let me go through the motions.

Before today I would have expected the following code to display the same three strings on each of the lines.

That is, despite how I declared the decimal in code, they would all be stored the same and hence all output the same way – truncated to zero decimal places in this case, given they are all exactly one. However when I run the page I get the following result:

Output 1

This struck me as a bit odd as it’s actually remembering how I declared the number and then using that when it converts it back to a string.

This got me thinking a little bit: is there some weird bug where by the numbers are considered to be different? I didn’t think this was the case but you can never be too sure so I added the following two methods to my test class and got the following output on the page:

Output 2

As expected comparing the numbers they are the same; they are both exactly 1. However comparing the strings we see that they are different (I know we could see that from the previous output but it’s always good to see what the compiler thinks).

My next thought was what does it do when we add decimals together that have been declared with a different precision? This leads to the following tests:

Output 3

We can see from this that order of inputs doesn’t matter and that the result will always have the precision of the most precise input.

So now that we know how it all works, even if it wasn’t what I originally thought, but where does that get us? Well strangely enough I had an application for this pretty much straight after I discovered it. I had to send a JSON object to a ReST service and needed to make sure that all the numbers I sent were formatted to show two decimal places. This little oddity means that I can simply multiple my input by 1.00 and I know that when I take the string value of the result I will have everything formatted just the way I want it. Perfect.

Output 4

Update

It has been rightly pointed out to me that this phenomenon is expected and well documented behaviour (SF Docs) Thanks gain @jamesmelv before I write my next post I will promise to read the documentation.

Generating Hashcodes

I was quite excited by the introduction of the hashCode and equals methods to custom classes in Winter ’13, as I was finally going to be able to get a map to behave the way that I wanted it to. I started to write such a map and a post to go with it when I started to discover a few, shall we say, nuances about what was necessary to implement these methods – in particular the hashCode one. I will follow up with my magic map post but for the meantime I want to discuss the implementation of hashCode method.

I never studied computer science, or indeed maths in enough depth to know the intricacies of hash codes but I know enough to know that good hashing methods are hard to come by and potentially are computationally expensive. Given both of these facts I came up with a cunning plan when I was designing my hashCode method, in fact it was more cunning than a… never mind. My plan was thus:

First of all I would create a string representation of my object by making use of the JSON serializer and once I had this string I would simply call it’s hashCode() method.

The beauty of this plan is that I would be leveraging the internal hashing algorithm on the platform, which should be great, well optimized, well dispersed etc and I would only be using two statements to get said hash code. (I could have made it one I know but for clarity I kept it at two) Basically I would get a great, generic, hash generator without using a million lines of Apex and hence continuing to play nicely with the governor limits.

Now the thing about plans as cunning as this is that they normally don’t work and whilst this is a gross generalisation in this case it was the unfortunate truth. It didn’t work. The problem is that the hashCode method isn’t exposed on the string object. I must admit I found this a little odd: in order to use a custom class in a set then we have to implement this public method. Given that a string can be used in a set I would have expected the same pubic method to exist. I’m sure that it does exist the problem is that it hasn’t been exposed to use mere mortals. Whilst I’m on this subject I will mention my general confusion at the implementation of this feature in general. I would have expected an interface to implement or indeed a virtual class to override. However instead we’re asked to add two methods randomly to each class. I’m not a great fan of this – there is obviously some jiggery going on as the code is compiled and I think that rather than hiding this it would have been better to expose it to us. Heading down this route flies in the face of some OO principles and as such, in my eyes, makes the code much more confusing and potentially unclear than it needs to be; but what do I know?

Anyway, putting this to one side and returning to my hunt for a good hashing method. My next thought was to have a look around the web for hashing algorithms and investigate implementing one in Apex. After a bit of hunting I came across the FNV algorithm – it is spoken well of and seems easy enough to implement. Easy enough that is in most other languages but Apex as ever presents it’s challenges. The problem comes in the fact that you need to operate on an octet of data – just one byte. Now using a string as our starting point it’s quite difficult to extract just one byte of data from it. You can split the string into individual characters but you have no way of getting back to the integer that represents that character. A shame really given that you can do this process the other way around: you can use string.fromCharArray() to convert a list of integers into a string. Oh well, this is part of the fun of this platform – find the your way around the obstacles.

So, how to navigate around this small issue then? Well we could build a static map that lists all possible characters and maps them to an integer. This could work, although with some of the extended character sets this could become rather painful to build, not to mention the fact that we need to keep our value less that 256 to stay with our 8 bits of data. We need to represent our string of data some other way – some way that has a limited character set. Base64 was designed exactly for this purpose so we could base64 encode our string – the size of the map is limited and the platform offers us a way to do this. You could also convert your string to a hex representation – the map is even smaller in this case, although the resulting string would be longer. To be honest I think this is a personal preference thing, I have no string thoughts about going with either solution. With this adaptation we can now nicely execute the FNV algorithm in Apex and it ends up looking something like this:

It’s beautiful and it works. However it has a small flaw that is very much specific to the platform. It is computationally expensive in fact, in terms of script statements it’s almost unbounded. Only really limited by the size of the string put into it, which in turn is only limited by the size of the heap! So whilst we have a way of generating a good hash code we need to do something about controlling it’s size. Ironically the hing about a hash code is that it is always the same length, no matter what input you give it and it’s this realisation that leads me to the solution to this problem. The somewhat odd solution is in fact to hash the string before putting through our FNV hashing code. The best part of this is that we can make use of standard platform functions to do this for us. The crypto class allows us to generate a HMAC from any input – ta da! This is fantastic we can now in one script statement compress any string into a reasonably unique (very very low chance of collision) string and best of all it will always be the same length, so we can now predict the effort needed by of hash code method to compute our object’s hash.

At this point I can imagine what you’re thinking – why on earth didn’t you just make use of the built in hash function right at the start. Well I thought about it but it returns a string and our hash code method needs to return an integer. So I would still need a way to convert a string to an integer – which is what the FNV piece of code will do for us.

Putting all of the pieces together we get something that looks like this:

I have kept the conversion to JSON in there as it allows me to provide a generic function for finding an objects hash code, although if you need to make use of internal state to uniquely identify your objects you would need to modify this piece. I then create a HMAC of the JSON and convert it to a hex value. This hex string is then broken down and character by character mapped to an integer which acts as our octet of data in the FNV code. Then, after all of that, we’re left with an integer which we can use as our hash code.

I have to admit this does seem like an awfully large amount of work to simply generate an integer although as I mentioned before finding a good hashing algorithms isn’t trivial stuff. And it is further complicated by needing to stick within governor limits. I feel as though what I have come up with here is a good compromise that makes use of standard platform functionality where possible and hopefully provides a decent dispersion. However, as I mentioned before I don’t really know much about the maths behind hashing and am very happy to have any flaws pointed out to me. (I’m sure I’ve made a rookie mistake somewhere in there)

As I said before it would be great if the platform exposed some way for us to do this – be it exposing their own native hash methods on a string or indeed providing an object.hash method that all objects have access to. But in the meantime I will be using this method to help me create custom sets and maps.

As a small side note: you may have noticed a couple of odd lines in the code, where I convert a string into a long. Trust me, I believe this has to be in here… I don’t want it to be but there’s what looks like a small platform bug, after I have done some more testing on this I shall report back.

Handling Optional Platform Features From APEX

Over the past few weeks I have been getting a few requests from some of our customers to add a feature to one of our products; some minor integration with Chatter. Being a company that prides ourselves on being responsive to our customers wants (once a little common sense has been applied of course) we decided to add said feature.

The feature itself was trivial to implement but what struck me as I was thinking about it was: “what about our customers without Chatter enabled?” I know it’s becoming less and less common these days but back when we were consulting full time we heard numerous clients ask us to make sure Chatter was turned off – and no amount marketing material was going to convince them to turn it on. With this in mind I was suddenly a lot less bullish about this new feature – I didn’t want to alienate a whole section of our potential market just for this feature.

I had a dig around the Salesforce documentation to see what, if anything could be done about this – I couldn’t believe that I was the first person to have this worry. Things were a little sparse I found reference to a new status for a DML exception and also to a new Exception type. It appeared that it had been thought about but how exactly it was handled still seemed unclear.

When faced with a lack of documentation, indeed when faced with almost any uncertainty, I do what any developer would do: I write some code! In this case code to prove once and for all what really happens. I whipped up a very simple managed package that had a VF page which inserted a FeedItem and then captured any exceptions and outputed them to the user. Simple. When I created the package I left the Chatter “Required Feature” unchecked. This seems a bit backwards, I have Chatter features but you don’t need to have Chatter turned on, anyhow this is what makes it an optional platform feature. Once I’d uploaded the package I span up another org and disabled Chatter in it. And then installed the package and navigated to my test page.

Boom! It broke. Well actually it worked but it threw an exception so it did in fact break. Given the mention of exception in the documentation this was pretty much what I expected to happen. Although to be honest it’s a little disappointing.

Why do I find it disappointing? After all I have a mechanism with which I can have Chatter features in my product but not need the user to have Chatter turned on in their Org. Well, if we were measuring happiness purely in terms of whether I have met my requirements then you’re right I should be estatic. However I find it disappointing that I am forced by the platform to use exception handling techniques to control the logic of my application.

Look at this code to see what I mean:

First off I just want to say that it’s not all bad – the exception that gets thrown is very specific to this problem so we can be sure that the only reason we’re in that catch is that Chatter isn’t enabled. If we want to deal with other excpetions from that code then we can use other catch statements. All good. Now for the not so good side of things, first of a bit of a bug bear the name of the exception is very generic, yet according to the documentation it can only be thrown if Chatter isn’t enabled. Either change the name of the exception or update the documentation to reflect the fact that in the future this may cover features other than just Chatter.

OK with that out of the way let’s get back to the question of logic. The idea behind exceptions is to provide a method to change the normal execution flow of a piece of code when an error occurs. It provides an opportunity for the developer to handle this error, this thing that wasn’t expected to happen. In this case we are expecting that some of our customers will not have Chatter enabled. This isn’t an errornous state of affairs it’s just the way life is. What we’re really wanting to do here is say: “Is chatter enabled? Yes? OK then insert a record because we can”. Instead we’re forced to to say: “Insert a record. Oh balls it didn’t work, must be because it’s not enabled, oh well”. We’re using exception methods to handle the consequences of not being able to make a logical decision upfront.

All of this is just bad practice and something that we shouldn’t be doing. Another reason often cited in other languages is that throwing an exception is a computationally expensive task. I can’t imagine that this is any different in Apex, especially given that it not compiles down to Java byte code anyway however I haven’t tried to eek out any benchmarks to prove it.

Interestingly it feels like the designers of the platform have a penchant for this anti-pattern. Seems like a strong thing to say, what do I mean? Well a couple of things make me feel this way. The first is the fact that we see this pattern in Apex already – we’re all guilty of assigning a LIMIT 1 query directly to an instance of an object and catching the exception if there are no matching records. What should happen in this case? Well how about just assigning null to the variable? The second thing that piques my worry is the name of the exception and the fact that it’s very generic it feels like we’re going to see the exception being thrown for other features as well, which will force us to replicate said horidness over and over.

So what can be done about all of this? After all there’s no point complaining unless you have a suggestion for improvement. First things first – I am not against this exception! I know it sounds like I want to see it burnt at the stake but that’s really not the case. I can completely understand why it is needed. In fact I wouldn’t change the exception at all, it’s completely appropriate for the action taken in the given circumstances. However, what is needed is something to compliment it, something that is the equivilient of the Limits class that already exists. How about a class called Features? It would have a series of static methods that give us the ability to test for the existence of optional features before we try and make use of them. That way we could use some conditional code structures to control the logical flow of the application, allowing us to change our try/catch example into something a bit better structured:

This feels like much better code, not only does it remove the nasty exception code but it also becomes much clearer as to what the code is trying to achieve.

Anyway enough of my disappointment, the crux of the matter is: there is a way to handle “optional” features on the platform such as Chatter from within your code. And this is great because it means I can add my trivial Chatter based feature to my application and not worry about alienating a whole section of my market or indeed having to try and manage two code bases.

Just be careful when you do make use of this exception though and please remember that you’re using an anti-pattern because you have to not becuase you should.

CoffeeScript in VisualForce

CoffeeScript has been around for a few years but has been gaining a lot more traction recently. For those unfamiliar with this language it allows you to write Javascript using a more Ruby-esque syntax. It’s brevity and clarity have made it increasingly popular and I thought that it might be good to find a way to make use of it from within VisualForce pages.

CoffeScript is “compiled” to JavaScript which is then sent to the users browser, this means that browsers don’t need to know anything about this new language but developers can write more robust JavaScript quicker. And whilst this is great news for browsers it’s not so great for the prospects of using CoffeeScript on the Force.com platform. Why? Well, the way that things are expected to happen in the CoffeeScript world means that we need a compiler that can run server side. Which in turn means we need a CoffeeScript compiler written in Apex.

Obviously writing a compiler in Apex isn’t beyond the realms of possibility but it is beyond the realms of what I’m willing to do to get this to work at the minute. It is also probably the best solution to the problem but I decided to look for an alternative.

My first thought was inspired by the fact that CoffeeScript is written in CoffeeScript. Given this and the fact that CoffeeScript is just JavaScript I realised that it must be possible to run the CoffeeScript compiler in the user’s browser. Unsurprisingly this is true and has been done. In fact if you include the coffee-script.js script and then tag your CoffeeScript in <script type="text/coffeescript"> tags the CoffeeScript compiler will process your scripts in the browser. Nice. Well kind of. It seems a bit wrong in my mind to be foisting this effort onto your users and the approach is frown on by the CoffeeScript community in general.

So, whilst this approach would have made it possible to use CoffeeScript in VisualForce I set out to look for another way of achieving this that was cleaner to the developer and the end user. In this vain I turned my attention to thinking of other places that I could run JavaScript. The immediate, and somewhat obvious, answer was node.js running on Heroku. This was a simple solution: node.js is great at executing JavaScript and the CoffeeScript compiler is even available as a npm package. The idea was a simple service which accepted a request body containing CoffeeScript, compile it up and return the JavaScript… nice!

The JavaScript above runs on node.js on Heroku and does exactly what I described in the previous paragraph. It’s really that simple. I was using uglify-js to minify the output but left it out of the examples to keep them to the point. Free free to have a play with this, just post some CoffeeScript to http://high-window-9445.herokuapp.com/ and you should get a JavaScript response.

So now that we have a server based approach to compiling CoffeeScript how do we make use of it easily from within VisualForce? My aim here was to keep it simple; it should be as easy as add a script tag. To achieve this simplicity I put together a basic Apex component which takes the name of a static resource (your CoffeeScript file) and in turn outputs JavaScript.

Then in the controller all we need to do is find the CoffeeScript resource, pass it out to our Heroku instance and send the response to the browser – simple.

There we have it, a fully functioning CoffeeScript VisualForce component; we too now have access to the benefits that CoffeeScript brings!

Using it is very simple: upload your CoffeeScript as a static resource and then include a line like this in the VisualForce page that you want to use the uploaded script in. Hey Presto! Job done.

Obviously there are short comings of this component as it stands one massive improvement for example would be to cache the returned JavaScript as another static resource so you only need to call out to Heroku once. There probably needs to be some better error handling; at the minute I just return a blank string if things went wrong, whereas it might be nice to know why.

Having said that I have achieved what I set out to do and hopefully have provided enough of a platform for those that want to include CoffeeScript in their VisualForce to get started with. In the meantime if I have another evening where I’m feeling a little bored I might round this component out and add it to GitHub for the easy consumption by the masses.

Older Posts »