Scala, Salesforce and Scalable Applications

Posted on Updated on

Hi All,

Scala is emerging as a very popular programming language today although it’s been introduced in 2004. It has helped the programmers find the perfect balance between object-oriented programming and functional programming. Scala allows efficient code reuse and extensibility, and its ability to handle data in real-time has made it a popular choice for Big Data projects.

Scala offers the advantage of building on the Java programming language and platform. Not only you can use all the familiar Java libraries directly in your Scala code, you can also intermingle Scala with existing or new Java code. When combined with the open source Spark, Akka toolkit it also allows you to easily spread your application across multiple systems.The Scala programming language is designed around scalability. It gives you the tools you need to spread work across multiple cores with minimal impact on your application design.

If you are optimizing for easy product iterations, while building scalable infrastructure. Scala’s powerful type system, functional idioms, and concise patterns allow your team to quickly model the business solution. The first class immutable data structures and safe asynchronous/parallelized constructs allow you to easily build distributed systems.Over the past several years, Scala has been used by multiple organizations(like LinkedIn, Twitter, Sony, Siemens, Xerox) in the construction of large scale data stores and analytics platforms.

Companies and individuals using Scala to build their own new ideas, they also utilizing other excellent tools like Play Framework, Akka, Apache Spark and Kafka etc which are not only some of the hottest tools and projects on the market right now, but also intentionally built in Scala.

Apache Spark

Spark is a fast and general-purpose engine for large-scale data processing. Developed in the AMPLab at UC Berkeley.

Akka

Akka is an extremely concurrent framework for building distributed applications.

Apache Kafka

Apache Kafka is a publish-subscribe messaging system written in Scala and Java.

Salesforce Thunder

Salesforce introduced Thunder at Dreamforce 2015. Thunder is Salesforce’s big data processing engine. It is designed to capture, filter and respond to events in real time. It is built on open source technologies like Apache Spark, Apache Kafka, Apache Storm, Apache Cassandra, Heroku.

Thunder is optimized for Machine-to-Machine(M2M) and Internet of Things(IoT) environments.

Advertisements

Multiple Actions Batching in Lightning Framework

Posted on Updated on

Hi All,

Today I am going to tell you about multiple actions batching when you are working with multiple Lightning Components in an Application.

Most component based technologies allow independent components to maintain a communication channel with their back-end services unfortunately this can result in redundant messaging specially when it constrain by narrow band width on mobile devices.

Lightning Component Framework is design to optimize calls to Salesforce back-end. There could be many separate actions fired from multiple components in any application but all the actions are processed in a single batch this allow us for very efficient processing.

batchingevents

As actions are instantiated and configured they are enqued in a batch.The framework execute each action in the queue after batching up related request.

Now rather then sending separate request for each individual action a single call is made to the server with batch of asynchronous actions each containing the information they need and fire multiple apex processes.

As it is possible for certain actions to be fired more than once the framework also can ensure that only the most recent instance of any action will be batched for processing.

The related action methods are invoked and the framework than gathers and sends back a batch of results again in a single call invoking all related callback functions.

Hope this will be helpful πŸ™‚

How do Lightning Components interact with Salesforce?

Posted on

Hi All,

Today one of my blog visitor asked me, how do Lightning Components interact with Salesforce? How does Lightning component get data from server? I thought to write an article on this, it might help you also to understand the architecture of Lightning Component Framework.

Below image will help you in understanding this.

salesforce

 

  1. Whenever a Lightning Component or an App runs on browser of Mobile device, it first download all component resources(i.e. Styles, Scripts, Markup) on mobile device. They are contained in browser’s memory to support display and processing that is why we call it client-side.
  2. Now if you want to call a apex method from client side, you will fire an event on client side. This event will call a JavaScript method on client-side. This client-side method will make an HTTP requests to Salesforce to call apex method on server-side. Like you do in VisualForce using action function or other JavaScript.
  3. This HTTP request to call apex method will be asynchronous. Asynchronous means you will make the request and forget about it and the controller returns to the client. The processing will be done on server-side.
  4. In the meantime Salesforce processes the logic by executing some apex.
  5. Finally when it is done with processing and gets some resulted data or not, it makes a callback to the browser/client-side. The client response by invoking an associated JavaScript callback function which extract data passed back by apex methods. This data can be assigned to component attributes. Now display will be automatically refreshed.

Hope this will be helpful πŸ™‚

VanillaJs For Better Performance of Lightning Components

Posted on Updated on

Hi All,

Lightning is all about components. You can build applications by assembling components created by you and other developers. A component can contain other components, as well as HTML, CSS, JavaScript, or any other Web-enabled code.

If you have multiple Lightning Components on a Lightning Page/App with 3rd party libraries like jQuery,Bootstrap etc, you may face performance issues like slow loading, code conflicts, many others you don’t know.

Problems you may face while working with 3rd party libraries :

If you have 2 Lightning Components with different version of Libraries, they may conflict with each other.
If you are using same version, they may put unnecessary weight on Components which in turn load your component slowly.

So what could be the solution? The solution is to ensure that you really need to load 3rd party libraries or not.

Basically you should always avoid use of jQuery for very small things like getting element Id, Class, DOM manipulation and many others. To do these small things you have to import jQuery file in you component. Which will put unnecessary weight on your component.

Instead of this you can use getter setter methods provided by Framework or you can use VanillaJs.

You might be thinking what is “VanillaJs”?
Vanilla JavaScript is a fancy name developers have given to the core JavaScript and DOM API combined, and it is used to distinguish it from libraries such as jQuery.

VanillaJs is very easy to use, it is a fast, lightweight, cross-platform framework for building incredible, powerful JavaScript applications. You can read more about here.

VanillaJs is faster than jQuery see below comparison.

vanilla

I know you may have to write few more lines of code in comparison to jQuery, but it is better than putting unnecessary weight on components by importing library.

Comparison of jQuery and Vanilla JS for basic DOM manipulation.

Class selectors

// jQuery
$('.myClass');

// VanillaJs 
document.getElementsByClassName('myClass');

ID selectors

// jQuery
$('#myID');

// VanillaJs
document.getElementById('myID');

Tags

// jQuery
$('div');

// VanillaJs
document.getElementsByTagName('div');

Add and Remove Class

// jQuery
$('div').addClass('myClass');

// VanillaJs
var div = document.querySelector('div');
div.classList.add('myClass');

// jQuery
$('div').removeClass('myClass');

// VanillaJs
var div = document.querySelector('div');
div.classList.remove('myClass');

Add and Remove Attribute

// jQuery
$('.myClass').attr('disabled', true);

// VanillaJs
document.querySelector('.myClass').setAttribute('disabled', true);

// jQuery
$('.myClass').removeAttr('disabled');

// VanillaJs
document.querySelector('.myClass').removeAttribute('disabled');

Hope you will find VanillaJs better than jQuery with Lightning Components.

Thanks πŸ™‚

DropBox Lightning Component

Posted on Updated on

Hi All,

Today i will be showing you DropBox Lightning Component created by me and my colleague Sushil Kumar.

Dropbox is a file hosting service operated by Dropbox, Inc., headquartered in San Francisco, California,
that offers cloud storage, file synchronization, personal cloud, and client software. There are limits in storage of files in Salesforce. If you need a secure and free storage space for your files, you can use DropBox Lightning Component to store files directly in your DropBox app from Salesforce.

Features of this Lightning Component are :

  1. You can use this component on any sObject.
  2. You can store files for a specific record.
  3. You can upload multiple files.
  4. You can delete files directly in DropBox.
  5. You can view you files.

Click here to install Manage Package in your org.

After installing package register for My Domain.

Make sure you have DropBox Account. If you don’t have you can sign up and create DropBox App as below.

Sign up Dropbox account from DropBox website.

After the Sign up login into your dropbox account and then create a Dropbox App using following steps:

  1. Go to on dropbox developer edition i.e. https://www.dropbox.com/developer
  2. Click on My Apps > Create App.
  3. Then fill all information about app and then click on create. See below screen shot.

dropbox

Manage Dropbox Key from Custom setting

Insert a record in custom setting using following steps:

  1. Navigate to Setup > Develop > Custom Settings, click on Manage of β€œDropbox Key”.
  2. Click on New, than insert following value:

App Key : from DropBox App

App Secret : from DropBox App

Redirect URI : from salesforce <your domain>/apex/DropBoxOAuth or copy url from preview of DropBoxOAuth page.

isAuthentication : false

Click on Save.

Add Redirect URI in Dropbox App

To add Redirect URI, Open your Dropbox App and you must set auth2 Redirect URIs same as above Redirect URL.

That’s It.

Your final result will look like this.

Thanks. πŸ™‚

Understanding Server Side Errors In Lightning

Posted on Updated on

Hi All,

Every Salesforce developer might have faced server-side/apex errors or exceptions while running VF pages or Lightning Components. I have also faced errors while running VF pages and Lightning Components. It is easy to understand and handle errors on VF page but there is difference when you are working with Lightning Components.

If there is any error on VF page, it will show you user friendly or appropriate error message with line number, when you are not handling it. And if you are handling this exception, you can easily show them using or .

When you are running Lightning Components and if there is any server side error occur it will not show you error on browser. I don’t know why, maybe Lightning is still improving that’s why.

Run below code in your org.

//Apex Controller
public class DemoExceptionController{

    @AuraEnabled
    public static String getServerErrorMessage(){
		//DML Exception
        contact con = new contact();
        insert con;
		
		return 'anything';
	}
}
//ExceptionDemo.cmp
<aura:component controller="DemoExceptionController">
    
    <aura:attribute name="message" type="String"/>
	
    <ui:button label="Show Error" press="{!c.showError}"/>
    <br/>
	Error Message :<ui:outputText value="{!v.message}"/>
	
</aura:component>
//ExceptionDemoController.js
({
	showError : function(component, event, helper) {
		var action = component.get("c.getServerErrorMessage");
		
        action.setCallback(this, function(a) {
            component.set("v.message", a.getReturnValue());
		});
		$A.enqueueAction(action);
	}
})

When you click on “Show Error” button a DML exception will occur on server. This error should be shown on browser by system but it is not shown. I modified ExceptionDemoController.js to manually show server side errors.

({
	showError : function(component, event, helper) {
		var action = component.get("c.getServerErrorMessage");
		
        action.setCallback(this, function(a) {
            component.set("v.message", a.getReturnValue());
            
			if (a.getState() === "SUCCESS") {
				component.set("v.message", a.getReturnValue());
			} else if (a.getState() === "ERROR"){
                console.log(a.getError());
                var errors = a.getError();
				if(errors[0] && errors[0].pageErrors)
					component.set("v.message", errors[0].pageErrors[0].message);    
			}
			
        });
		$A.enqueueAction(action);
	}
})

Now when you click on “Show Error” button it will show you user friendly error message.

Now modify Apex Controller and ExceptionDemoController.js to show different type of error.

//Apex Controller
public class DemoExceptionController{

    @AuraEnabled
    public static String getServerErrorMessage(){
		//List Exception        
        List<Integer> li = new List<Integer>();
        li.add(15);
        Integer i2 = li[1]; // Causes a ListException
	}
}

//ExceptionDemoController.js
({
	showError : function(component, event, helper) {
		var action = component.get("c.getServerErrorMessage");
		
        action.setCallback(this, function(a) {
            component.set("v.message", a.getReturnValue());
            
			if (a.getState() === "SUCCESS") {
				component.set("v.message", a.getReturnValue());
			} else if (a.getState() === "ERROR"){
                console.log(a.getError());
                var errors = a.getError();
                if(errors[0] && errors[0].message)// To show other type of exceptions
                    component.set("v.message", errors[0].message);
                if(errors[0] && errors[0].pageErrors) // To show DML exceptions
            		component.set("v.message", errors[0].pageErrors[0].message);    
			}
        });
		$A.enqueueAction(action);
	}
})

Now when you click on “Show Error” button, this time it will not show you correct user friendly message instead of this “An internal server error has occurred” message will be shown. I tried with other type of exceptions to see the cases in which “An internal server error has occurred” message will be shown and in which correct user friendly message will be shown. In every case “An internal server error has occurred” message is shown except DML exception.

If you want to show appropriate error message you can handle exception to return appropriate error message.

//Apex Controller
public class DemoExceptionController{

    @AuraEnabled
    public static String getServerErrorMessage(){
		try{
            List<Integer> li = new List<Integer>();
            li.add(15);
            Integer i2 = li[1]; // Causes a ListException
        }catch(Exception e){
            return e.getMessage();
            
        }
	}
}

I know this is not a right way to show error message but I am just giving you an idea to show appropriate error message. You can write your own logic according to your requirement.

Thanks πŸ™‚

Understanding Expressions in Lightning

Posted on Updated on

Hi All,

Yesterday I stuck with Expressions in Lightning. While solving this I came to know about different ways of using Expressions and different types of these.

An expression is any set of literal values, variables, sub-expressions, or operators that can be resolved to a single value. You can use expressions for dynamic output or passing values into components by assigning them to attributes. Expressions are also used to provide action methods for user interface events(i.e. OnClick,OnHover).

Bound Expressions

Bound expression syntax is: {!expression}. Curly braces with “!” bang operator is used for Bound expressions.

If you are making any change using Bound expression it will immediately reflected on your component. Bound expressions are used to reflect changes on your Lightning Component. Below are examples of Bound expressions in component.

<aura:component>
	
	<!-- Accessing Fields and Related Objects -->
	<p>{!v.accounts.Name}</p>
	
	<!-- Concatinate value with String -->
	<p>{!'Hello ' + v.msg}</p>
	
	<!-- Ternary Operator -->
	<ui:button aura:id="likeBtn" label="{!(v.likeId == null) ? 'Like It' : 'Unlike It'}" />
	
	<!-- Conditional Markup -->
	<aura:attribute name="edit" type="Boolean" default="true"/>
	<aura:if isTrue="{!v.edit}">
		<ui:button label="Edit"/>
	<aura:set attribute="else">
		You canÒ€ℒt edit this.
	</aura:set>
	</aura:if>
	
	<!-- Adding two items -->
	{!(v.item1) + (v.item2)}
	
	<!-- Using Global Variables -->
	{!$Browser.isPhone}
	{!$Locale.timezone}
	
	<!-- Action Method -->
	<ui:button aura:id="likeBtn" label="Press Me" press="{!c.update}"/>
	
	<!-- Array Length -->
	{!v.myArray && v.myArray.length > 0}
	
</component>

Unbound Expressions

Unbound expression syntax is: {#expression}. Curly braces with “#” hash operator is used for Unbound expressions.

If you are making any change using unbound expression, it will not immediately reflect on your component. If you don’t want to reflect changes, you can use unbound expressions.

Note : Unbound expression changes are not reflected on component but they can be seen by javascript.

Below example show use of unbound expression in component.

//Component1.cmp
<aura:component>
    <aura:attribute name="truthy" type="Boolean"></aura:attribute>
     
    <aura:if isTrue="{#v.truthy}">
        True
    <aura:set attribute="else">
        False
    </aura:set>
    </aura:if>
    <ui:button aura:id="button" label="Check" press="{!c.update}"/>
</aura:component>
 
//Component1Controller.js
({
    update : function(component, event, helper) {
        component.set("v.truthy","false");
		console.log('----> '+component.get("v.truthy"));
    }
})
 
//Component1Renderer.js
({
    rerender: function(cmp, helper) {
        console.log('rerender'); 
        return this.superRerender()
    },
})

In above code when you click on “Check” button it will udpate unbound expression {!#v.truthy} in javascript controller. You will be able to see changes in console but they are not reflected on component.

Hope this will be helpful. Happy coding πŸ™‚