Thursday, 24 October 2013

Battling CPU time out limit in apex sfdc



As per winter 14 release a new Limit was introduced for apex transactions which was brought in instead of number of script statements (2,00,000 script statement was maximum script statements allowed ).If you are guessing its CPU time out limit i am blogging on ..you are right .Its this new feature which asks for developer to be more smart and more thoughtful in designing and approaching any apex design going forward 


One question that quickly came to my mind when this was announced is what will happen to previous code which took more than 10s (Please note for synchronous transactions 10 seconds is the CPU limit ) ?


I found answer to this in my favorite community that i spent lot of my time in(Yes its the salesforce.stackexchange.com) 


http://salesforce.stackexchange.com/questions/18244/how-do-sf-calculate-the-cpu-limit


Read the technical  discussion that went deep to exploring OS concepts in computer science .So the answer why the previous code wont break is because salesforce analyzed all their previous code and for each org they took the maximum CPU time that a code took to execute and have set the time out equal to that .Example assume before winter 14 i have an org A and that had a code which did not hit script execution limit but took 15 seconds of CPU time in that case for org A the CPU time limit is 15 seconds .



It wont be fair if i dont explain whats this CPU time of apex transaction here.


CPU Time :Read the below blog link from apex product manager himself to dig deeper .


http://blogs.developerforce.com/engineering/2013/09/script-limits-begone.html


The time taken by the apex transaction in a context including validations,workflows apex code and  excluding time taken in DML,queries,callouts is called CPU time .

Lets be once more clear on whats counted in CPU time and whats not


What's counted:

- All Apex code
- Library functions exposed in Apex
- Workflow execution
What's not counted:

- Database operations, e.g. DML, SOQL
- SOSL
- HTTP callouts


Now lets discuss some of the best practices  in code which will help to reduce the CPU time out 


1)Using Map Based Query 

Very clear this was taught to us when we had to reduce script statements ,well same best practice is also useful when you want to reduce the CPU time

2)Explore option to see if your business scenario allows you to do the operation asynchronously 

In some cases business process may not be real time and hence if there is a chance to make code execute in @future ,this will break the context and also the CPU time out limit for asynchronous process is 60seconds(6X of synchronous process).So do consider a thought on this if you are in trouble of hitting this limit


3)Aggregate SOQL usage 


Since the database time is not calculated in CPU time its always better to explore the usage of aggregate SOQL for your business use case .


Say you want summation of field value  of some records ,if you use normal for loop to get these obvious you have spent CPU time there .Instead try to push your calculation using SUM,AVG aggregate functions at the database layer itself so that you have reduced CPU time and have pushed the process on database layer itself.Explore options to group by or create some sort of filtering at database layer and push your calculations at database layer to reduce chances of hitting CPU time out issue .


4)Make sure you take only necessary data and run a loop .


This is essential now to filter only specific data while doing a for on a list of records as too much looping will increase CPU time .Same held good when we had no of script statements limit .


So conclusion is clear some of best practices we used to reduce script statements still hold good and its essential to follow these .


If you have come across any other techniques in apex to reduce the CPU time consumed please post below and i am happy to learn and share .


Happy coding !





Sunday, 20 October 2013

Oauth Google With Salesforce.com using apex

In this short blogpost lets explore oauth along with a classic example of connecting salesforce and google and fetching auth token from the google using on demand salesforce emerging platform language apex 

There are already excellent client libraries to help you started with oauth 2.0 

The above link is really nice one to explore more code in your faviourate language .Now coming to salesforce we have excellent blog post that teaches oauth in depth and i call it as sfdc oauth bible 


The above URL teaches lot of stuff in a very lucid and very unique style .Thanks to the author .

In this blog post we will connect sfdc and Google and obtain oauth token from the google .This oauth token can be used to fetch personalized  data from Google using the Google API's(I will love to do one more blog post where an example of data fetched from Google will be shown)


Using OAuth 2.0 to Access Google APIs


The API's provided by the Google can be accessed easily once we authorize the app created in google with sfdc.

There are various different types of apps that we can create which includes web server,client app,native,installed apps .


Reading the above document is really helpful as very steps are highlighted that we will do before moving into sfdc end 

1)Register your application

To register an application google provides a console name cloud console 


Here in the above URL we will need to do very important steps .One is to create a project and then register a web app .
Creation of project is just a button click on new project and providing a name and saving it.

To register an app go to Project>API's>Register APPs

Here create a new web app .You can register any of the type of app and note the mechanism for each is different and discussed in the Guide
For this demo we will create a web server application.

2)Authenticating the User

User authentication is our next step.Once we register our web app of sfdc in google we obtain the clientid and client secret which are used to fetch the oauth token from google .

Please note a very important parameter is necessary that's redirect url for the web app .In force.com we will create a small visualforce page and the url this visualforce page has ,to be provided as the redirect url.Also its important to fill the web orgin in cloud console  so as per your salesforce request url please provide as appropriate(example in my case its developer org and hence its https://ap1.salesforce.com).

If my visualforce page is named as GoogleAuth then my redirect url would be https://ap1.salesforce.com/apex/GoogleAuth

We are ready to see some code that is written in visualforce and apex language to fetch the oauth token from the google completing the oauth dance



Let me explain the code above to my best of ability of explaining

1)The controller consists of two major methods

Connect method()
Showtoken()

Connect method redirects to url to authorize the app .First step is to get "code " url parameter from the google .This will be got only once we authorize the app .Typically web server oauth flow you will see in video

Show token method is called once we have the "code" parameter.

string codeparam=apexpages.currentpage().getparameters().get('code');

Using the code parameter we will make a request body and make a http request from sfdc.



The body formation is the key and all parameters are clearly explained in the google documet https://developers.google.com/accounts/docs/OAuth2

We are printing the oauth token obtained and using this oauth token we can fetch the personalised user data like contacts,calendar events ,access Map API's,etc




Here is the video link

http://screencast-o-matic.com/watch/cI6Y2hV7dS

There is force.com toolkit for the google found in the link below which is very easy to install and use

http://wiki.developerforce.com/page/Google_Data_API_Toolkit

But this blogpost my intention was to demonstrate oauth and its concepts for force.com lovers .Hope you enjoyed this blog!Happy coding !

There is lot of to do's after fetching oauth token but this is the starting point to get going .Infact an  oauth token is short lived and hence a refresh a token is necessary to fetch and left as an exercise to reader.





Wednesday, 2 October 2013

Using MavensMate and SublimeText For Apex and Visualforce Development



Recently i tried the mavensmate open source IDE for the force.com mentioned in the site and was quite impressed on windows .It hardly took time for me to understand and start using it .Thanks to excellent UI and its support with sublime text editor .

Let me document few initial settings i did to get this up and running and there is lot to speak on how to use this .I will highlight major points in this blog and that should be good enough to start using this .

Lets begin with how to set this up

For IOS and Linux i have no experience configuring this but looks like documentation for the same is very clear in User Guide

For windows i did configure it and was stuck at a place and i will elaborate at this step so that some one dont pull out hair searching and googling lot 

Following things needed to be downloaded

1)Git Download
2)Sublime Text 3
3)MavensMate.exe file

One by one we need to download the above and keep installing on windows machine .Please note i have provided the link .And hence clicking on above hyperlinks should help you to find location from where to get installed 

I was stuck on how to provide path form my local machine

The screenshot of the error i received when i first tried creating project





















So the error is [ mm property] is not set so lets resolve this .



The error can be resolved by setting your local path on the default settings file .

mm_workspace was empty and i have given my file patch here as "mm_workspace" : ":\\Users\\mshrivasta002\\Mavensmate" and now we are ready to create projects

     {
	//set to absolute location where you wish your MavensMate project to reside
	//if the location does not exist, MavensMate will attempt to create it
	//for example: "/Users/username/Documents/workspaces/mavensmate" (notice the absolute path)
	//WINDOWS USERS: it's probably best to set this like so: C:\\path\\to\\your\\workspace
	"mm_workspace" : "C:\\Users\\mshrivasta002\\Mavensmate",

	//set to desired Salesforce.com API version (tooling api functionality requires 27.0+)
	"mm_api_version" : "28.0",

	//if true, MavensMate will automatically hide the debug panel upon a successful operation
	"mm_hide_panel_on_success" : true,
         --------
         ----------
         -----------------
     }


To create projects just navigate  to Mavensmate>NewProject and a screen comes up to enter credentials and create the project

A sample screen shot on how this comes up is below


The deployment interface is really good as well and works good for chrome browser(Not yet tried with other browsers)

A small screen shot on how this looks is below


The major features that are really significant and give an edge over eclipse are as below

1)Auto complete for the visualforce is supported (In eclipse we may need separate plugins )
2)Debug logs obtained from the server are pretty 
3)Performance and speed of data fetch from server  is not so bad (OK but i feel needs improvement)
4)There are already templates available for most of common scenarios like batch apex,visual force controlers,email services ,etc
5)The tooling API is used and hence everything is JSON based and there are also commands for compiling and creating and editing files  everything can be done from command line .The API documentation is really good

http://mavensmate.com/API/Overview

6)Syntax highlighting is bonus and sublime text editor is really good one .

Frankly speaking a single blog-post is not sufficient but this will just motivate to try this IDE for a change.Happy coding !!!


Introducing Lightning Base Components

Lightning Base Components are great addition to the platform and in fact revolutionary .One of the concerns around lightning component ...