When Salesforce is life!

Tag: Lightning

[Salesforce] My favorite Spring ’15 features

a{color:red !important;}
h3{color:red !important;}

This is my top 10 list of the Spring ’15 Force.com platform update’s features.

Make Long-Running Callouts from a Visualforce Page

This is a really important feature. Imagine you have big VisualForce pages in which Apex methods, triggered by buttons / links / rerenders, do one or more callouts to external services.

Imagine hundreds of users use that page and the external services go down, thus causing timeouts on the callouts.

This could lead to heavy problems, because there can be no more than 10 long running Apex processes at the same time: this leads to unexpected and horrible output errors.

Using this new feature we can now “asynchronize” synchronous Apex callouts, using the new Connection Apex class, that is used like a callback when the callout has ended.
Basically you create a method split in 2 parts: the first (invoked by a button / link) has the starting callout code and the last receives the results from the callout.
Even if the callout/callouts (you can trigger up to 3 callout a time) fails / go timed out this call won’t count towards the logn running processes.

I’m gonna write down a post to show how this works using HttpRequests and also SOAP requests.

Set Up Test Data for an Entire Test Class

This is an extremely useful feature for large ORGs with hundreds of test classes.

This allow us to write “test setup” methods (new annotation @testSetup) that are called once per test class: when a test method is executed the context has all the objects created in those setup methods (you can have more than one method of this kind, but the execution order is not guaranteed). Each test method execution rollbacks its data at the end, so that the following class’s test method will see the values as if they were just been created.

Deploy Your Components in Less Time

Imagine you have the GO for a deploy in your production ORG but you have to do it at saturday midnight (and test methods requires more than an hour to run!!!!)…this is absolutely not cool!

This feature allow you to send a deploy to production before your deadline, test classes are run during this “freezed” deploy and it stays freezed for 4 days: when you are ready you simply click the “Quick Deploy” button and the components are deployed instantly! Whoooaa this is magic!

Create Named Credentials to Define Callout Endpoints and Their Authentication Settings

You can finally leave all the authentication mess to the Force.com platform and just sit on your screen and simply code you business requirement, magically storing sessions, tokens and whatever it is needed on Salesforce.

You can also use a named credential in a simplyfied way to store callout endpoints.

Business Continuity – Promote Business Continuity with Organization Sync

With Organization Sync you can setup a secondary ORG that you can use when your primary ORG needs some maintenance (e.g. a big release of your developments), giving a 24/7 service availability.

Orgs are synched automatically through a data replication mapping.

I haven’t already tested this feature, but being available on developer Orgs I’ll certainly try it soon.

Visually Automate Your Business Processes

This is the Lightning Process Builder, a cool visual tool that help you automates your business processes, from simple actions to complex combinations.

It seems really awesome but unfortunately it is not available on the pre-release program.
You better see in the next days tens of posts about this new feature!

Lightning Components (BETA)

Lightning components are still in beta and the builder in pilot.
But we have new additions:

  • New Components: brand new base components (such as select input, textarea, …)
  • Namespace Requirement Removed: finally no need to setup a namespace, easing the creation of packages and the deploy across orgs
  • Support Added for Default Namespace: follows the previous point
  • Extend Lightning Components and Apps: like classes, you can extend components and apps
  • Referential Integrity Validation Added: integrity validation has been boosted

New increased limits

There are some new increased limits:

  • Deploy and Retrieve More Components: limit increased from 5000 to 10000 components
  • Chain More Jobs with Queueable Apex: from 2 chained jobs to infinity (except for Developer and Trial orgs where the limit is 5)
  • Make Apex Callouts with More Data: size per callout (HTTP or SOAP) increased from 3 MB to 6 MB for synchronous APEX and 12 MB for asynchronous

Create or Edit Records Owned by Inactive Users

All users can now edit objects owned by inactive Users, before Spring ’15 only administrator could do it!
Believe me, this is really usefull.

Legitimize User Activity using Login Forensics (PILOT)

These are forensics metrics to identify suspicious behavior of users (such as logins from unusual IPs or excessive number of login among the average number).
This is a PILOT program, so you have to explicitly ask Salesforce to be enabled.

As usual, may the FOrce.com be with you guys!

[Salesforce / Lightning] Loading scripts with RequireJS

a{color:red !important;}

UPDATE

Due to the introduction of the ltng:require, this post is no more a valid solution. Refer to the official Lightning documentation.

The following is a post that summarizes this blog post‘s solution (if you are not a TLDR; reader you will find there all my trials and errors).

Dreamforce 2014 came out with new awesome features on the Salesfoce platform: one of the most interesting has been the introduction of the new Lightning framework for fast development of reusable components.
In addition to the (still in pilot) Lightning App Builder (an amazing drag & drop tool for easy creation of apps), it’s not hard to figure out how far this new technology will lead the Force.com platform.

The main reason you want to develop a new Lightning component is the fact that you can compose components like a puzzle making them communicating using events: read the official development guide for more details on how to build your first lightning component.

One of the things you’ll be doing while developing new components, is using external libraries to give more and more features to your applications.
You’ll face the following constraints:

  • You can only get external libraries loaded from a static resource
  • You cannot use the {!$Resource.resourceName} expression because we are not inside a VisualForce page, so you have to simply refer to “/resource/[resourceName]” in your <script> tags

When loading more than one external scripts, sometimes happens that the order of loading is not the expected one (even if you have inserted the script tags in the right order).

You could use RequireJS library to overcome this problem (being sure that he’ll be responsible for loading libraries in the correct order).

But the question is: who is responsible to load RequireJS script?

Who will be executing the RequireJS loading code ONLY AFTER the library has been loaded?

Trying to get the right answer (see more details on the “fail” steps here and the community thread that brought me to the solution), I came to the following solution.

The solution is simple (to ease its understanding): you can improve it to add more features (e.g. style sheets loading) and to make a component out of it.

This is the main code (all the code has been packaged into this GitHub repository):

BlogRequireJSDinamic.app

<aura:application>
        <aura:handler event="forcelogic2:BlogRequireJSEvent" action="{!c.initJS}"/>
        <aura:registerEvent type="forcelogic2:BlogRequireJSEvent" name="requireJSEvent"/>
        <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
        <div id="afterLoad">Old value</div>
    </aura:application>

BlogRequireJSDinamicController.app

({
    /*
        Sets up the RequireJS library (async load)
    */
    doInit : function(component, event, helper){
        
        if (typeof require !== "undefined") {
            var evt = $A.get("e.forcelogic2:BlogRequireJSEvent");
            evt.fire();
        } else {
            var head = document.getElementsByTagName('head')[0];
            var script = document.createElement('script');
            
            script.src = "/resource/RequireJS"; 
            script.type = 'text/javascript';
            script.key = "/resource/RequireJS"; 
            script.helper = this;
            script.id = "script_" + component.getGlobalId();
            var hlp = helper;
            script.onload = function scriptLoaded(){
                var evt = $A.get("e.forcelogic2:BlogRequireJSEvent");
                evt.fire();
            };
            head.appendChild(script);
        }
    },
    
    initJS : function(component, event, helper){
        require.config({
            paths: {
                "jquery": "/resource/BlogScripts/jquery.min.js?",
                "bootstrap": "/resource/BlogScripts/boostrap.min.js?"
            }
        });
        console.log("RequiresJS has been loaded? "+(require !== "undefined"));
        //loading libraries sequentially
        require(["jquery"], function($) {
            console.log("jQuery has been loaded? "+($ !== "undefined"));
            require(["bootstrap"], function(bootstrap) {
                console.log("bootstrap has been loaded? "+(bootstrap !== "undefined"));

                $A.run(function(){
                    //do whatever GUI initialization you want
                    //in the aura context
                    $("#afterLoad").html("VALUE CHANGED!!!");
                });
                
            });//require end
        });//require end
    }
})

This is what you’ll get in the developer console of your browser:

RequiresJS has been loaded? true
    jQuery has been loaded? true
    bootstrap has been loaded? true 

And you will see “Old value” string replace with “VALUE CHANGED!!!” in the page body.

What has happened?

When the app loads (init event) the doInit function tries to understand if the RequireJS library has been loaded.
If so fires a BlogRequireJSEvent event.
If not yet loaded, dynamically creates a <script> tag with the path to RequireJS, binding an onload handler, which in fact will inform that the library has been loaded, using the same event.

The same app is also an handler for the BlogRequireJSEvent event trhough the initJS function: it will load sequentially jQuery and Bootstrap libraries: this way you are pretty sure libraries will be loaded in the correct order.

The next step is to make a component out of this app so you can use a RequireJS loader component in all your apps and make all your components handling the BlogRequireJSEvent event.

[Salesforce / Lightning] Loading scripts

a{ color: red !important;}

UPDATE

Due to the introduction of the ltng:require, this post is no more a valid solution. Refer to the official Lightning documentation.

This post has been more like a request for help, rather than a technical blog post, but it came to be an awesome way to see Salesforce community in action and ready to help!In the last Dreamforce 14 big Mark presented the Lightning framework for fast development of reusable components (see details here and the awesome Topcoder’s track).Click here for the “Lightning Components Developer’s Guide”, well written and clear.I’ve noticed a strange behavior regarding external javascript libraries loading.These are the requirements regarding external script loading:

  • You can only load external libraries got from a static resource
  • You cannot use the {!$Resource.resourceName} expression because we are not inside a VisualForce page, so you have to simply refer to “/resource/[resourceName]” in your <script> tags
  • From page 100: “If you want to use a library, such as jQuery, to access the DOM, use it in afterRender().

Apparently the last sentence is not true.The problem arose because I loaded jQuery + Bootstrap and sometimes (and randomly) the Bootstrap plugin did not load because of jQuery was not yet loaded: the cause was certanly the fact that libraries were not loaded sequentially!TLDR; click here for the solution!This is what I’m trying to do:

BlogScriptApp.app

<aura:application>
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <aura:handler event="aura:doneRendering" action="{!c.doneRendering}"/>
    <script src="/resource/BlogScripts/jquery.min.js" ></script>    
    <div id="afterLoad">Old value</div>
</aura:application>

BlogScriptAppController.js

({
 doInit : function(component, event, helper) {
        try{
   $("#afterLoad").html("VALUE CHANGED!!!");
            console.log('doInit: Success');
        }catch(Ex){
            console.log('doInit: '+Ex);
        }
 },
    doneRendering : function(component, event, helper) {
        try{
   $("#afterLoad").html("VALUE CHANGED!!!");
            console.log('doneRendering: Success');
        }catch(Ex){
            console.log('doneRendering: '+Ex);
            
            setTimeout(function(){
                try{
                    $("#afterLoad").html("VALUE CHANGED!!!");
                    console.log('doneRendering-Timeout: Success');
                }catch(Ex){
                    console.log('doneRendering-Timeout: '+Ex);
                }
            }, 100);
        }
 }
})

BlogScriptAppRenderer.js

({
 afterRender : function(){
        this.superAfterRender();
  try{
   $("#afterLoad").html("VALUE CHANGED!!!");
            console.log('afterRender: Success');
        }catch(Ex){
            console.log('afterRender: '+Ex);
        }
  
    }
})

This is what I get in the console

doInit: ReferenceError: $ is not defined
afterRender: ReferenceError: $ is not defined
doneRendering: ReferenceError: $ is not defined
doneRendering-Timeout: Success 

This means that in the last app event (aura:doneRendering) we don’t have the libraries loaded, and that the only way to do it is to detach from the current execution and use the “setTimeout” method to call asynchronously the needed code.No surprise that this could not work if the jQuery library took too long to loadOne of the suggestions was to use RequireJS on the app, but the problem is the same: if the external scripts are not loaded, the “require” method does not exists and you cannot load its configuration.In this case RequireJS would allow to load in the correct order all the libraries (for instance jQuery, than bootstrap, then another lib …), like in this example:

BlogRequireJSApp.app

<aura:application>
    <aura:handler event="aura:doneRendering" action="{!c.doneRendering}"/>
    <script src="/resource/RequireJS" ></script>    
    <div id="afterLoad">Old value</div>
</aura:application>

BlogRequireJSAppController.js

({
 doneRendering : function(component, event, helper) {
        try{
            helper.loadRequire(component);
            console.log('doneRendering: Success');
        }catch(ex){
            console.log('doneRendering: '+ex);
            setTimeout(function(){
                try{
                    helper.loadRequire(component);
                    console.log('doneRendering-Timeout: Success');
                }catch(ex){
                 console.log('doneRendering-Timeout: '+ex);
                }
            }, 100);
        }
 }
})

BlogRequireJSAppHelper.js

({
    loadRequire : function(component) {
        require.config({
            paths: {
                "jquery": "/resource/BlogScripts/jquery.min.js?",
                "bootstrap": "/resource/BlogScripts/boostrap.min.js?"
            }
        });
        
        require(["jquery"], function($) {
            require(["bootstrap"], function(bootstrap, chartJS) {
                $("#afterLoad").html("VALUE CHANGED!!!");
            });
        });
    }
})

This is what I get in the console

doneRendering: ReferenceError: require is not defined
doneRendering-Timeout: Success 

This way you’ll have the scripts loaded in the correct order usign the RequireJS library: anyway if the RequireJS library is not yet loaded (it depends by your data connection) you’ll see another exception at the end of the log

Here comes the Salesforce community!

I posted a question on the SF developer forums and got a super cool response.From that response I came up with a simple solution that uses dynamic script loading and one event fired: this solution is a simpler reinterpretation of the forum’s one to make it easier to understand.

BlogRequireJSDinamic.app

<aura:application>
        <aura:handler event="forcelogic2:BlogRequireJSEvent" action="{!c.initJS}"/>
        <aura:registerEvent type="forcelogic2:BlogRequireJSEvent" name="requireJSEvent"/>
        <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
        <div id="afterLoad">Old value</div>
    </aura:application>

BlogRequireJSDinamicController.app

({
    /*
        Sets up the RequireJS library (async load)
    */
    doInit : function(component, event, helper){
        
        if (typeof require !== "undefined") {
            var evt = $A.get("e.forcelogic2:BlogRequireJSEvent");
            evt.fire();
        } else {
            var head = document.getElementsByTagName('head')[0];
            var script = document.createElement('script');
            
            script.src = "/resource/RequireJS"; 
            script.type = 'text/javascript';
            script.key = "/resource/RequireJS"; 
            script.helper = this;
            script.id = "script_" + component.getGlobalId();
            var hlp = helper;
            script.onload = function scriptLoaded(){
                var evt = $A.get("e.forcelogic2:BlogRequireJSEvent");
                evt.fire();
            };
            head.appendChild(script);
        }
    },
    
    initJS : function(component, event, helper){
        require.config({
            paths: {
                "jquery": "/resource/BlogScripts/jquery.min.js?",
                "bootstrap": "/resource/BlogScripts/boostrap.min.js?"
            }
        });
        console.log("RequiresJS has been loaded? "+(require !== "undefined"));
        //loading libraries sequentially
        require(["jquery"], function($) {
            console.log("jQuery has been loaded? "+($ !== "undefined"));
            require(["bootstrap"], function(bootstrap) {
                console.log("bootstrap has been loaded? "+(bootstrap !== "undefined"));
                $("#afterLoad").html("VALUE CHANGED!!!");
            });//require end
        });//require end
    }
})

This is what I get in the console

RequiresJS has been loaded? true
jQuery has been loaded? true
bootstrap has been loaded? true 

What has happened?When the app loads (init event) the doInit function tries to understand if the RequireJS library has been loaded. If so fires a BlogRequireJSEvent event. If not yet loaded, dynamically creates a <script> tag with the path to RequireJS, attaching an onload handler, which in fact will inform that the library has been loaded with the same event.The same app is also an handler for the BlogRequireJSEvent event trhough the initJS function: it will load sequentially jQuery and Bootstrap libraries: this way you are pretty sure libraries will be loaded in the correct order.The next step in the solution given in the forums is to make a component that does all the work and fires an event that can be handled from anywhere in your app / components set.All the code above has been packaged into a GitHub repository.Enjoy!

Page 2 of 2

Powered by WordPress & Theme by Anders Norén