Tuesday, January 27, 2015

Salesforce Apex Performance Best Practices | Triggers

Standard

Triggers are key for a powerful performance, if you handle them carefully, you can scale performance without hitting exception. In here, I am sharing few pattern, that I find most interesting. The first pattern below is based of the articles written by +Kevin O'Hara.  The key practices is to write logic out of the trigger into a custom apex class using Polymorphic design. Check out previous post about Apex Best Practices

Polymorphic Trigger : 

Write all logic in one apex class to easily manage triggers for an objects and contextual methods. Like


Then write object specific class to override each method an apply business logic.


Call the AccountTriggerHandler class in the Trigger



Contextual Trigger : 

You can write context trigger for before and after context for an transaction. Either you can write multiple triggers or one trigger to nail all context like shown here



Recursive trigger : 

Recursive trigger situation occurs when a trigger and workflow stuck in unlimited looping situation, a simple scenario would be, workflow updates a field, which  in-turn invokes Trigger and henceforth, workflow turns on back again and so forth recursion comes in scene.

Key solution is using static variable, I wrote blog post here and here and recommend reading solution by Andrew Fawcett . Basically you can use static variable to solve your problem.


Create a class with static variable


Now use this variable to check, if trigger ran before


Using Enums for Contextual Trigger :

This is another solution proposed by Mat Kuffman and well explained by Steve Anderson
In this approach, the idea is to create a class with enum variable handling events and the context class call helper class to process all records. On trigger, for each type of event we can invoke the Context class, I wrote an example using Account sObject in mind, but ideally it can be applied to generic sObject.

ActionHandler Class


Context Class


Enum Trigger




Read More :



Sunday, January 25, 2015

Salesforce Apex Performance Best Practices | Apex

Standard


There are bunch of articles out there talking about best practices in Salesforce. I see some of the common practices that every salesforce developer should be aware of, I developed notes over period of time with some examples to follow.  I added references to bunch of key sources and articles down at the bottom covering some official articles and as well as good StackExchange articles where people have done amazing job responding to questions.

Querying Salesforce in Trigger : 

Make sure you have no SOQL in for loop

Wrong Approach



Recommended Approach


Bulkify Trigger with Set and Map: 

Salesforce provides standard data-structures like Maps and Set to per-filter and pre-populate data to avoid repeated SOQL calls, this allows user to handle bulk data, often called bulkification of code. Triggers in salesforce are intentionally designed to handle bulk data, so here we simple pull Ids into a set which is used to iterate and populate a Map holding all values. The map is our data storage and used for querying Salesforce

Recommended Approach


SOQL In for loop for large datasets : 

SOQL-IN for loops, allow you to set the range of for loops through a SOQL query, example below shows two ways of writing for-loops. First approach may throw error of 'heap size' governor limit.


Avoiding SOQL Injection :

SOQL injection, allows user to pass set of keywords input, which becomes wildcard to access all data in Salesforce, if query is pro-actively designed to handle those wild card. A simple example below demonstrates SOQL injection in action.

Vulnerable to SOQL Injection


Dynamic SOQL



Querying Child Items :

Inefficient way of querying child item would iterating through each parent object and querying child item, which is ugly. Smartly this can be done as show below.

Wrong Approach

Recommended Approach


@future method in Salesforce : Making integration/service communication future proof.

Annotate a method with future, when you want to perform a job asynchronously, like making an outbound call to Facebook, Twitter on a field update.Ideally if it is not 'asynchronous', then salesforce hang up and wait for response and this delay or hang up process. But key is, writing logic of @future method in separate class.

Recommended Approach : Write your @future method and logic in separate class


Call Asynchronous class through Apex Trigger

Things to remember

  • Future cannot call another future method neither a batch job can call @future method
  • Use callout=true for making callouts
  • You cannot guarantee order of execution
  • Future call have limits and can run concurrently
  • Check video, below if you want to get-around these limits in some ways 
  • Video covers, future calling future and chaining asynchronous calls

Better {get; set;} method using pattern called 'Lazy Loadin

Try to  add filter if possible in your get property to only query salesforce conditionally, when some criteria is met, and avoiding querying salesforce every time the class constructor called.

Recommended Approach : Adding conditional logic in getter


Transient Keyword and Properties to reduce view state

Transient keyword is used for properties or variable, which don't want to store on the view part of the application, this can be used primarily to reduce down the view state of visualforce page,  you should remember that static method are by default transient and simple example to understand usage of transient is shown here and then another awesome discussion in here on stackexchange, which talk about another side of visualforce, when your UI has many components and result in heavy view state

I strongly recommend reading this article mentioning some read best practices for improving visualforce performances

How to make Salesforce Properties Transient : Check out similar blog post here for explanation in detail



Best Practices for View State 


Best Practices for Asynchronous Apex 


Read More :

Design Patterns by +Andrew Fawcett :

 Other Resource for Best Practices

Wednesday, January 14, 2015

How to add Google Map in Salesforce (featuring Google Map V3) Revised Post

Standard

Watching data on map with Geo-location is always fascinating, I had written a blog post here  couple of year back, about adding Google Maps in Visualforce and adding them accounts layout, many of you might have already implemented or might have seen implementation on account layout, this article is written for people who are requesting me to update old code matching new API standard and features, at the same time a  revision to old blog post.

Lately in one of the project, I recently was working with Geo-location API intensively and  I learned that there are cool changes on Google Map API V3. I have updated the code to meet new standard for V3 static map api and sharing code snippets on varied instances and features of Google Maps

How to get coordinates from address using Google Geo-code Services  ?
Google Map API needs geolocation coordinates,  using Geocode service from google, you can get coordinates for a location address.



How will your account address look like ? 
Your address would be combination of couple of standard fields shown below, which can generate complete address

 var accountLocation = "{!Account.BillingStreet}, {!Account.BillingPostalCode} {!Account.BillingCity}, {!Account.BillingState}, {!Account.BillingCountry}";
  
Binding Address to convert to Geo-location ?       
In the JavaScript call back method, simply pass on the address of Account to get back latitude and longitude
       

Once you know the latitude, you can pass on values to initiate the Map. To check full code, scroll down in bottom for complete source code hosted on Github repository.

You can do couple of cool effects on top of map as well using simple tweaks.

Adding Marker Drop Effect
 

 
Adding Bounce Effect to Toggle Bounce 

 
Adding Circle Effect : 
Get the List of accounts which are in Texas, California and New York and then create a method in Javascript to draw circle based on count


Controller behind simply bring count of accounts state wise


Plugging properties to inject value to draw radius of circles

Adding RoadMap and 45 degree Tilt : 


Source Code

The Source Code is available in this Git-hub repository

Read more :

Show Salesforce Data on Google Maps using Salesforce Reports by my colleague Arun
Avinava Maiti BlogForce9 Google Map Component
Youtube for Amazing Implementation and Ideas

Tuesday, December 23, 2014

Beautify Visualforce Pages with Google Material Design and Paper Elements

Standard



Twitter Boostrap is fairly popular design framework and I have written bunch of blog post on them, then learned about Flat UI, which were slick and beautiful, but not good enough to leverage real touch feel to application. 

Not too long ago, Google introduced Material Design, a brand new set of guidelines for designers and developers alike. Material Design introduces a fresh perspective on user interfaces, motion, and interaction states, and are a great foundation for you to build a product upon.

Material design offer more power to to users, as it is quicker to get back to and find a certain state withing an application and clearly adds more intuitiveness, feel and productivity to application


In recent android version called Lollipop, you might have seen massive changes in the designs, transition and feel of applications, Inbox by Gmail is another email application that have caught lot of attention by offering a  brand new experience, so I thought of giving kick start on material design, I simply started by importing Paper-elements on the page. Paper-element are set of elements design to produce paper type touch feel to the application, I used the CDN resource to the HTML

To get started, I created a codepen, embedded below that you can navigate here switching tabs below

See the Pen Google Material Design Paper Elements by Harshit Pandey (@oyecode) on CodePen.

Implementation
Create a visualforce page and import cdn resource for paper element and polymer core-elements as shown in the code below and start implementing check out Live Page here


Source Code
Check out the code to new Visualforce page available at this Github Gist

Summary
After importing, you can add custom style to arrange elements properly on page and them implementing paper-elements as shown in the snippet below and that's it,  the visualforce page is ready to serve. Moving further, there are more interesting resources out there, check out polymer apps using material design and this page will give the most fun you can imagine for the next five minutes using Material Design. Stay tuned for next post on more of my experiments using Material Design with Visualforce applications

Other important resources are

Friday, December 19, 2014

Make realtime mobile and web application in minutes using Firebase

Standard


Real-time application are fascinating and comes with lot productivity, like if you see Google Drive real time integration or Socket.io node base application, they are productive and offer wide range of implementations. I recently meat, Firebase team in Google Cloud Platform Live in San Francisco. I was surprise to see, how quickly you can make real-time application using Firebase, and recently learned that they are acquired by Google.


How easy is to make real-time application ? 
Making a real-time application is still tricky and require lot of coding, and powerful architecture to sync data back and forth, Firebase resolve this problem for us and offer three-way data binding to us.

What is Firebase ? 
Firebase is an API oriented service that store and sync data in database real time. With that it mean, you don't have to worry about your server, database, or real-time components. Firebase manage that all for you. With the API provided, you simple retrieve or push data to Firebase and it will take care of saving and syncing data to all connected devices and applications.


Future Prospects of Firebase ? 
Google recently acquired Firebase and more likely be offering Firebase features pretty soon . Google has a history of integrating the services it acquires for Cloud Platform rather quickly. I am expecting a tight integration with Google Cloud Platform which is will power instant real-time data integration and synchronization, it would be interesting to see, how this will take shape and Google Cloud Platform offer number of services already, so clearly this will be powerful and promising integration of technologies

Let us get started, create an account on Firebase and click to create a new application, like I created application name Oyecode, shown in the picture above. Once you create an application you can see that its fairly easily to define your data structure as the data stored as key values pair, pretty similar to Couchdb and Mongo.

Firebase store data as key-value pair, so once you populate the data, you can see your data in the wizard, as shown below


Building Real-time, Responsive Application only with HTML and JavaScript

In the video below, I am explaining how quickly you can build an application using simply HTML and deploy on Firebase platform, I have explained the code in the embedded video here. As we know that talk is cheap, and developers want to see code. Below is the code and live application, feel free to edit code live here on Codepen

To play with live hosted version : Go to Firebase Hosted Application
See the Pen raLpKb by Harshit Pandey (@oyecode) on CodePen.









Check the video below, explaining how to built this application 
Once you built an application, simple you can install Firebase Command Line Tool to deploy your application on Firebase cloud hosting services. Type in this command on your command line

 

Check out the application in action

 Check the video below,  where I demonstrated the real time behavior of the application


Further References :
Firebase Docs 
Firebase Samples 

Tuesday, November 25, 2014

How to make Google Polymer powered Salesforce1 Mobile Apps in Minutes

Standard

In this mobile first era of software development, making an mobile app powered by enterprise data is still not a smooth process. Salesforce offered variety of tools to make power packed enterprise applications, last year Salesforce released mobile packs, dedicated for most of the popular libraries, offering jump start to developers coming from varied platforms.

Web components on the other hands offer promising future, and have fundamentally changed the way developers think of application building. Google Polymer have done wonderful job of offering framework to built components. At salesforce, mobile sdk team took early lead and developed Mobile Pack for Polymer.

Who are working on web-components ?

Major of known companies, are working on building components driven frameworks,  Salesforce released Lightening Framework, which is based on Aura project offer components driven development pattern.  In Dreamforce' 15 +Samantha Ready at Salesforce had showcased, leading frameworks

Mobile Pack for Polymer is offered with Polymer Designer tool, this tool host all components that mobile team have built, and can be easily assembled to make mobile apps in minutes, you can toggle from designer to see the code behind. In other words, you can easily build mobile application by dragging dropping components,  in a mobile designer fueled by Salesforce data, this experience was never so easy.

Recently, I spoke at Google workshop for Polymer called ItsHackademic in Mountain View, CA.  I presented our work at Salesforce. To our surprise, it turn out, that we at Salesforce, have done one of the best implementation of Web-components. As Google quoted us in talks,

"Salesforce have radically changed application building experience of mobile apps just by web components, like no other"  - Google 

I have written about this library previous post here, but today ,I recorded a video demonstrating, how easily you can built an application by components re-use them to add more values.

The video below takes you to the journey of building a Salesforce powered mobile application and I'll explain here how to make Salesforce 1 mobile Apps in minutes. You can re-use this component to pull data and create more components on top of it, not just mobile but can be web.



Make web applications by reusing components 

I took data-component, shown in video, at added Javascript library called Amcharts, to populate charts with data. Check out my another library here demonstrating, how to built visually appealing and responsive (mobile ready charts) in minutes here on official Salesforce blog.

Google Polymer with Salesforce

Check out presentation slides below, for lightning talks covering only highlights not full presentation coverage



Sunday, November 9, 2014

Learn how to use Salesforce Communities Designer for Self Service Portal

Standard

Salesforce community portal have been in use for long time, but was limited in offering pleasant features and specially custom configuration. To introduce as new feature, lot of additional works needs to be done, both from development and design perspective, which include using HTML, CSS and Javascript on top of Visualforce. 


Clearly powerful user-experience and clean user interface adds high user engagement. In person, we have spend weeks to leverage an impactful customer experience with Salesforce Communities 

Salesforce introduced community designer and have fascinated me in person, I have been working on this platform for about three year, and I find this tool be very productive. I teamed up with +Harshit, and decided to write this blog post here explaining how to create google looking customized community portal with 'No-Code' by using Salesforce Community Designer Tool released in Winter'15.

To explain a functionality, I am choosing a business scenario, covering business activity in an financial institution, and covering mundane activities like resolving credit-card/loans issues. My objective is to explain this all with no-code, and just deal everything with 'Point and Click'. 

Prerequisites

1) Let us set up a new developer org . spin up for an org from salesforce developers home

2) If you are not familiar with communities, we recommend reading this setup guide here .

3) Knowledge articles is the soul for this whole set up. Get some coffee and go to this setup video here

Having installed Prerequisites (Note : three of mentioned resources, are mandatory) , we will look up Salesforce Community Builder and Templates, to set up Self-Service Portal

Navigate to Set up>Communities>All Communities


Note : As shown in picture above, two new additional setting are introduced as  ‘Administration Settings’ and ‘Community Management’

Salesforce Community Templates 

Primarily, three important templates available to jump start, but I would like to share the amenities, each templates offer, and make choice easier for you.

1) Kokua - Uses data categories, case and Salesforce Knowledge.
2) Koa- Designed for Mobile, features include, articles search and case management.
3) Napili- Offer most features, with Q&A, Knowledge Articles and Case Support. Clearly, I’ll use this template moving forward

Pickup template of your choice, In here, I have created a community named ‘FunCommunity’ as you can see in drop-down,




Setup Navigational Topics 

Got to Community Setup shown as above and you will see salesforce settings screen similar to
one shown below



Bind Topics 

Go to (Setup -> Topics -> Topics for Objects) to bind topics to every knowledge article. Clearly, this make it easier to locate or navigate in the community

Screen shot below explains, how to add banner images for each topic. I have created three topics for here to demonstrate, Credit Card, Debit Card and Loan Processing




Assign Data Category


Locate arrow on top-right, to assign data-category for each topic, in the picture below



Featured Topics

Every featured topics, pop as thumbnail on homepage, add feature topics here


Video Summary 

With that said, community is configured and in shape, this has all done with  'no-code' involved. I have compiled these steps in a video below and discussed some more feature(s). Feel free to provide us feedback and share your knowledge with us.



 

About the Author 

I have worked with +Mohit Srivastav  while writing our last post on Angular Js with Salesforce, after Winter'15 Salesforce release, he decided write another blog post here and connected with me to coordinate resources and I would like to thank him for taking time out of his schedule and like to congratulate for winning 'Summer of Hacks in India', follow him on his blog 'CloudyWorlds'

Multiple ways to use REST API with Salesforce

Standard

REST API is much more popular architecture for connecting/integrating systems and communicating with the help of exposed methods . Salesforce had launched tons of API in last couple of years, so as opened opportunities for people to connect data in multiple ways.

I am trying to sum up some guidelines and tutorial (not everything) but many things, this is the collection of methods/process that you developers can use to play with REST API's specially focusing Salesforce.com development. The idea behind this post, to collect rest resources together at one place for developers to chose from. 

For the most of the method I am discussing here, I am using OAuth2 protocol to connecting systems. Let's jump start by logging in to your Salesforce org, create a connected application, you can keep the callback url as provided (default by salesforce) it varies based on implementation, explained here and summarized in my previous post(s)


How to Access Salesforce REST Api using Curl

Curl is client URL request library, the allows you make REST calls through developer console in Window/Mac. Now to understand how to access any salesforce API with curl, check out this post here


Salesforce REST API using Chrome Developer Console

Once you login to Salesforce, here is the another post sharing, how to access Salesforce REST API using Jquery through Developer Console 

Salesforce REST API with Google Chrome

Salesforce REST API using Node.Js

+Christophe Coenraets  has written 30 lines of code post using Node.js to make REST Console Editor for self, check it out and then I added my bit on top it to make SOQL query basic editor using REST API, don't forget to check +Jitendra Zaa post on building Node.js SOQL query builder here

Salesforce REST API using Node.js

Using the Toolkit in an HTML page outside the Force.com platform via Forcetk Library

+Pat Patterson wrote simple implementation using RemoteTK on a visualforce page, check out his git repository here 

Salesforce REST API using JSForce Library :

JSForce is one of the most organized library I came across written by my friend +Shinichi Tomita and former salesforce employee who founded MashMatrix, here how to integrate here 

Using JSForce with Salesforce | Oyecode

NGForce : Library on Javascript

Powerful javascript library written by +Kevin O'Hara , check out this amazing video here

Built your own API using nothing but Apex

There are few use-cases and scenarios, when you need to expose you salesforce method to post and return back data, which can be exposed out to world as REST Endpoints, can using Salesforce standard REST architecture and OAuth (1&2) patterns, you can communicate with enterprise data. 
Learn how to built your own REST api using Apex here

RESTForce Gem for Ruby on Rails 

Simply neat and powerful that I have used and very lightweight alternative to databasedotcom gem for Ruby Guy and use Rails. Easy to access data, here are few snippets, to get started read amazing tutorial written by Bruno Fagundez  on RestForce here 

How to built ForceServer?

Well, don't forget the checkout my favorite evangelist amazing post here at Salesforce +Christophe Coenraets on building local server to streamline oAuth and REST Services with Salesforce

Using REST API to connect Google Docs with Salesforce

Learn to built Google Script, and connect Salesforce Platform, pull and push data by writing Salesforce from Google Script Connecter I wrote,  learn to built script that connects with Salesforce using REST API and push/pull data on a Google Drive Spreadsheet here


Saturday, November 1, 2014

Using Yeoman Generator for Google Polymer

Standard


Building polymer components is quick and easy,  but managing components still require standardization and alignment. To provide a scaffold to application/component, team at Google built scaffold tool called 'Yeoman' and dedicated CLI tool for multiple technologies including Polymer. Yeoman is powerful scaffolding tool that not only streamline components development process,  but also provide a structure to development process, which enforces best practices.



What does it do ?
With a set of commands, Yeoman compile required resources for you and you can skip lots of manual setup . Yeoman is designed to handle configuration and accumulate components for development and  clearly minifies the pain of maintaining minor configurations and making it easy for developer to focus more on application logic

What does it have ? 
Primarily its a combination of 'Yo' which is scaffolding tool,  'Grunt' task manager and 'Bower' a powerful package manager. So clearly with few set of commands, you can built scaffold, download files and test/build/serve it easily


Getting Started with Yeomen 

To get started with Yeoman Generator for Polymer, I would like to share the video shared by +Rob Dodson where he have explained the steps to configure Yeoman and create your polymer components.


Read more about Yeoman here and go here for instructions to install on your machine and here for finding list of Yeoman generator for other technologies that may interest you

Tuesday, October 21, 2014

Trailhead | A learning path for Force.com Platform

Standard
Trailhead : A new learning path for force.com platform

In Dreamforce'14, our team of (developer relations) launched Trailhead. Trailhead is designed to align the salesforce resources, which will streamline the learning process and at the same time provide a defined learning path for developers start learning force.com platform.

Salesforce have offered resources through youtube, blogs, workshops, elevate conferences, meetup and many more ways. But alignment of resources was still needed to be done. In the project Trailhead, Salesforce have developed the power packed content that comes with challenges and these challenges can be taken in your personal 'development org' or dev edition. Trailhead check the work done by you, by querying against your organization and clearly offer a brand new experience of learning and doing work at the same time.


Trailhead also offer a  profile page, which is your Trailhead profile, that beautifully presents the work done by you and showcase your the badges you earned or awarded to you. Your Trailhead profile could be public or private depending on the choices of your preferences. Trailhead profile showcase the medals/badges earned and certainly add lot of authenticity your 'Salesforce profile' besides your Salesforce Forum Profile


Trailhead offers  multiple Trails where each Trails is defined learning guided path, each Trail further goes deep down in the Modules and then to Units. A units may or may not have a challenge, some units require reading the text, while most of them have a challenge to take.



Primarily, Trails have two broad categories, Salesforce Administration and Developer with Force.com platform, later likely more Trails would offered as it grows. My team have done amazing job of offering guided path for all developers around the globe who are excited about the technologies and wrote a brand way of learning through a gaming experience and the profile building at the same time, without hopping for distributed resources. 

I strongly recommend existing users, new comers and MVP's to try out Trailhead and spread the the words to help people all over the globe. Don't forget to share your work with your Trailhead Profile

PS : Image Credit @Salesforce.com Inc