Sunday, 10 November 2013

Simulating SSO concept using axiom as IDP (An app on heruko) and Salesforce











SSO(Single SIGN ON) is a very vital concept and as a fresher to IT industry many of us struggle to understand the definition and importance. The aim of the blog post is to help you to  understand what SSO is and how easy it is to configure in salesforce.

SSO (Single Sign On) allows the end users to provide their credentials once and obtain access to multiple resources. The key point of the concept is that the users are not prompted for their credentials anew on access to participating resources until the
    active  session is terminated. 

     The participating resources are typically related, but still remain independent. 

    Specifically, each system may have own authorization system, providing system-specific      roles to the end users.

 We will be using an IDP simulator axiom on heruko to simulate federated SSO concept  with salesforce as the service provider .

There are four  ways we can have single sign on with salesforce and get authenticated .

  1. Delegated SSO
  2. Federated SSO
  3. OAUTH
  4. JIT SSO (Just in Time SSO)
I am not going to explain each one of these as this is not the aim of this blog ,having said that i have few good reference link which you can refer to understand the difference between each of them 


The above link is an awesome webinar which explains all the four ways and there advantages and disadvantages 

2)There are some  blog posts on developer.force.com and these blog posts are very interesting read





One of them,(first link a) uses salesforce as IDP and also as a service provider ,so two orgs are connected and explains the concept of SSO.These are valuable resources to spend time reading and configuring .


Now let me take some time to describe Federated SSO at high level .The above diagram will help me explaining the concept of Federated SSO.

In federated SSO uses SAML and we have an IDP(Identity Provider) and a Service Provider(SP).


The user makes a request to Force.com for a specific resource: This request may happen in a variety of ways for a variety of reasons. For example, the user may be following a bookmark, clicking on a link from an email, of allowing their browser to auto-complete.
  • Force.com detects the user needs to authenticate and redirects the user to their SAML Identity Provider: Since the user doesn't present a session cookie, they need to authenticate. An organization-specific hostname allows the user's Org to be discovered, and they are sent over the SAML protocol. Along with a SAML Request, a form parameter called RelayState is passed along to the IDP. This captures the location of the resource the user originally requested
  • The user accesses their IDP and authenticates. This authentication is performed by the IdP giving the customer complete control over the authentication process. A variety of popular techniques may be used, such as LDAP, a web access management system, Integrated Windows Authentication, or a 2-factor system such as SecurID.
  • Once authenticated, the IDP sends a SAML Response back to Force.com. This response happens via the user's browser, and includes the RelayState originally sent by the Service Provider. The echoing of RelayState is critical to the success of the protocol, as this is what allows the user to be returned to the originally requested resource.
  • Force.com processes the SAML assertion and logs the user in. The digital signature applied to the SAML Response allows verification that the message is from the Identity Provider, at which point the user is authenticated. They are granted a session and redirected to their original request.
Now come the actual part of practically simulating 

Here i will be using axiom a heruko app built just  for learning, testing, and troubleshooting single sign-on solutions for Salesforce.com

1)Configuration in Salesforce Environment 

This is very simple and let me go through this step by step with screenshots

a)So first step is to register a domain in my domain and set the redirection policy (Navigate to Domain management>my Domain in your salesforce instance 















b)Next step is to enable SAML 2.0 and configure the parameters for SAML SINGLE SIGN ON Settings

Once you enable SAML 2.0 as in below screenshot,the next step will be to download the certificate from axiom tool and upload in the SAML single sign on settings .Here are the screen shots to help you 











































So i hope screen shots are clear to understand .So its basicallyits feeding the entity Id and SSO start page got from the axiom screen back to the salesforce and then in the below video i am going to demonstrate how easy it is now to simulate the whole behavior.Its no point more speaking in words i felt instead decided to put a video






Monday, 4 November 2013

Using Change sets Effectively For Enterprise Application Deployment For Force.com Projects

Deployments in force.com can be a headache specially if you are new to platform ,in fact you may mess up if you use changesets and have no experience before doing this or if you have come up from java/.NET background where you have used ANT for deployments and now asked to use change sets of salesforce

The aim of this blog-post is share some of the tips and tricks for using the changeset effectively for deployment.

So i assume here that we generally go through salesforce document and we are ready after going through salesforce document to explore some tips and tricks that i generally use for deployments when using change set

http://help.salesforce.com/HTViewHelpDoc?id=changesets.htm&language=en_US
https://help.salesforce.com/apex/HTViewHelpDoc?id=changesets_best_practices.htm&language=en

The above links is must read before you start reading the tips i have for using changesets effectively

Problem 1:The field level security and permissions of objects and fields are not obeyed once i deploy fields and objects using changesets 

http://salesforce.stackexchange.com/questions/15238/change-sets-including-custom-objects-and-custom-fields

So the solution is quite simple we forget that profiles and permission sets should be migrated along with migration of fields,objects,apex classes,visualforce,record types etc to apply the permissions 

Problem 2:Reports and Dashboards don't migrate properly

Reports and Dashboards do get migrated well with changesets .All that we need to ensure is to include the folders also that are necessary along with these dashboards .

There are two specific problems that i encountered 

i)In deploying folders or dashboard we get error saying the user with given mail ID don't exist in destination org 

Solution is simple, either we will have to remove the running user from the dashboard of  current org from which we are deploying or other way around to temporarily form  the user mail id in the destination org or may be create folders not deploying manually

ii)I received internal sever error when migrating reports and dashboards .

Internal server errors are meant for salesforce support but here is something that comes by luck sometimes




 If the destination organisation does not have folder sharing enabled then we cant deploy reports we receive internal salesforce errors.Manually enable in destination org to resolve this issue 

Problem 3:Deployed email templates in one go and in next go i deployed letter head and there was no association between email template and letter head 

This particular thing i noticed and looks like a bug but nevertheless,we must be careful in deploying email templates and letterheads .Its better to include both together to avoid such complains .

Problem 4:Its difficult adding fields to changesets when i have large number of fields or components 

For this lets hack a salesforce a bit .

































So from the above pictures we will need to follow these to make our life simpler .First we will sort the fields by Type and then click on the "more" link found at the bottom.

Now the fields looks little better organised for the selection.Lets make it more easier .


si=-2&lsr=0&entityType=CustomFieldDefinition&rowsperpage=260


So observing the url once we click more, at the end of the URL we find a parameter called rowsperpage.This parameter holds no of rows that is displayed when forming the changesets .Now if we increase the rows per page from 260 to some large number 50000 we find we avoided pagination and now sorting on type again ,we find the interface is really selective and we need not paginate lot to add components into changeset.


si=-2&lsr=0&entityType=CustomFieldDefinition&rowsperpage=50000


Increasing rowsperpage avoids pagination and we can scroll at bottom to greater extent and avoids us to one more iteration to add components into changesets 



Disadvantages of Changesets 

Some of the disadvantages of changesets are as follows which needs some attention in future from salesforce

1)For standard fields and objects we will need to manually check permissions and field level security(manual activity or use force.com IDE)

2)Removing components from changeset is painful..yes its painful due to bad user interface and with no sorter available and pagination rendering is ajax one making more slower

Few Interesting tips 

1)The components in changesets are the very latest version components at that particular instance in the organisation.What i meant by this is say you formed a changeset at an hour before and one of the trigger got deactivated later ,say 10 minutes before you deployed into next instance .The trigger will appear deactivated in destination org as the current instance and code or build is taken during deployment .So make sure to form these only at time of deployment 

2)Approval process are available ,groups and queues can be deployed .If any issue its better to form queues and groups manually as this is simpler than debugging issue 

3)Be extra careful in adding metadata to changeset that have recently modified by salesforce during salesforce API release .An example to quote ,in winter 14 release only my sandbox was updated to 29 and my production was still on 28.0 and salesforce made some changes to Topics object and some unknown error was received during deployment .In order to avoid this i preferred removing that permission sets .

4)If some components is not getting deployed and if its config build and small effort prefer manually creating and removing same from changesets .Good thing about changesets is changesets can be cloned .

Hope this was interesting post!!Happy deployments and coding !




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 !!!


Saturday, 28 September 2013

OutputPanel Usage In Visualforce Page

Salesforce has a provided with a very important tag ,apex:outputPanel. Recently I answered a question on stackoverflow that motivated me to write this small post.


The above link opens the documentation about this tag .This blogpost i have explored its exact use cases to use this tag

  1. Conditionally render a section of block of html element in a visualforce can be achieved with this tag as this tag has render attributes .


     2. A very interesting case is if the element is not rendered initially then on Re-rendering the panel nothing rerenders .The following blog below from Bob demonstrates on how to resolve this .Again the outpanel is the rescue

http://bobbuzzard.blogspot.in/2011/02/visualforce-re-rendering-woes.html

   3.A common requirement that comes sometimes is to align the command button to the center of the screen.The apex:pageblockButton can be used but in some cases we have buttons without pageblock and we get errors saying PageblockButtons can be direct parent

 
    
    

There are some interesting points to note in the above code .There is a layout attribute and i have made it block.Making it block we have a div element while making inline has a span element .You can clearly observe if i make layout as inline the above code wont make the button centered as the style will be inline for the span element.



Sunday, 8 September 2013

Fun With New HTML5 Tag Support in Visualforce

Winter 14 release notes are up and i am sure many of you would have glanced it .The most exciting feature is support for some html 5 components in the visualforce ,which open lot of opportunities for developers working on the platform to provide robust UI to the end customer using the platform.

Many times customers have been asking for features like auto suggest(auto complete),calendar widgets,Phone field validation or email validation on the form element.I don't say we   never gave this functionality to the customers ,we still were able to give these cool features but with help of jquery UI plugins ,some work arounds (like creating fields of input field to bring calendar on vf),or using any other open source UI or javascript library to achieve these functionality.

Now with this new winter 14 release some of our pains to use these libraries for small functionality like auto complete is easily achievable through native tag support provided in the visualforce page.

The release notes has a sample visualforce  program on all the newly introduced attributes and tags and there appropriate usage .

Lets explore some of the new tags and see how we can do some cool UI stuff,

Autocomplete:

This is commonly needed functionality and we had to use jquery UI to achieve this .This is very simple now using datalist tag .


<apex:inputText label="Account" value="{!AccountName}" list="{!Accounts}"
      html-inputText="Enter your preferred browser" html-autocomplete="on" />
  </apex:pageBlockSection>

Date Pickers:

Date pickers are very essential componet and widely used widget .Usually all mobile applications need this and most of times we used workaround to create a input field on object and use that for visualforce page for desktop application.For mobile we had to use jquery mobile and use the javascript remoting to bind with data .Now with apex:input tag this can be easily achieved


<apex:pageBlockSection >
     <apex:outputLabel ></apex:outputLabel>
     <apex:input label="datePicker" value="{! fDate }" type="auto"/>
     </apex:pageBlockSection>

Phone Validator and Email Validator :
This are widely supported now in 29.0 version and html placeholder specifes the format 


<apex:pageBlockSection >
     <apex:outputLabel ></apex:outputLabel>
     <apex:input label="Email" value="{!email }" type="email"
      html-placeholder="you@example.com"
      html-pattern="^[a-zA-Z0-9._-]+@example.com$"/>
      </apex:pageBlockSection>

 <apex:pageBlockSection >
     <apex:outputLabel ></apex:outputLabel>
     <apex:input label="Phone" value="{!phone }" type="tel"
      html-placeholder="999-999-9999"
      html-autofocus="true"/>
      </apex:pageBlockSection>

Incrementor or stepper:Usually number stepper component is generally needed and helpful in mobile apps .Visualforce now natively supports this .

<apex:pageBlockSection >
    <apex:outputLabel ></apex:outputLabel>
    <apex:input label="Increment Me!!" value="{! hello }" type="auto"
     html-min="0" html-max="100" html-step="5"/>
    </apex:pageBlockSection>


A small example to demonstrate the usage of these tags is below

A small code class to support the above page




You can take a look at the sample site url and try doing the autocomplete or inspecting picker.

http://demoprerelease-developer-edition.prerelna1.pre.force.com/

Note:Also one thing thats very important to note is these tags are not supported in all browsers .Its supported on most of modern browsers but one has to test this tags thoroughly before deciding to solution around this .Internet Explorer its not advisable to use .In mozilla also as i observed few tags dont work.Chrome these tags are best.

Saturday, 24 August 2013

Aggregate SOQL Functions in SFDC Pros and Cons

"Aggregate query does not support queryMore(), use LIMIT to restrict the results to a single batch"

I was lately working on some reporting requirement on salesforce which was possible only through visualforce and as soon as i heard the business scenario i was confident enough that my solution will be simplified if i stick to the Aggregate Function in SOQL SFDC.

I knew i had huge data in my org and never thought using Aggregate function will lead me to below error

"Aggregate query does not support queryMore(), use LIMIT to restrict the results to a single batch"

This error motivated me to blog this article and share some experience on when to make use of these aggregate query and when not in apex .

If you are confident that the data in a object  can exceed 20000(approximate figure) rows i would prefer avoid these and instead prefer using loops and making page read only at-least and writing my own logic to sum and count .

The read only attribute gives the power to exceed the no of rows limit from 50000 to 1000000 and this is huge number and what internally salesforce does is ,it  uses queryMore() call to chunk the data that's rendered on to the visualforce page and hence if we use best practices to manage heap and with winter 14.0 removing the limitations on script statements one can still manage to show data even if the object consists of huge data .

Happy coding !



Saturday, 3 August 2013

From Administrator To Advanced administrator of Salesforce CRM and Force.com Applications



Recently salesforce came with BETA exams for the advanced administrator and this provided me an opportunity to clear this exam free of cost.To know more about what BETA exams are and how they can be useful in getting yourself certified please read the below article 

BETA EXAMS KNOWLEDGE ARTICLE

The aim of this blogpost is  to give an idea of what are the areas candidates must go through to gain this valuable certification.Please dont ask for exam dumps or any other material as these are not ethical and also whats the use of attending an exam just by going through dumps .

Please make a habit of going through study guide and make sure you go through all the videos mentioned in the study guide(All videos are  not free and you may need partner portal access to watch .Ask your organisation if they have one ) .Also search for topics mentioned in  study guide in salesforce help and training portal .

Let me ease some task by providing links to the study guide and help and training portal

LATEST STUDY GUIDE (AS OF SUMMER 13)

HELP AND TRAINING PORTAL

Please make sure to download latest study guide from below link

http://certification.salesforce.com/administrators

The following areas a candidate must concentrate to gain this certification

1)Delegated administration -This topic is very important and huge number of questions come in exams 

2)Security concepts -The sharing model as well as Territory concepts are very vital for this examination.
Go through the guide mentioned below

http://login.salesforce.com/help/doc/en/salesforce_security_impl_guide.pdf

Territories_Implementation_Guide

3)Use of audit logs and debug logs

4)Deployments tools (Change sets ,Force.com IDE and ANT)-The advantages and concentrate mainly on pros and cons of changesets 

5) Forecasting-collaborative forecasting and Customizable and concentrate on reports that can be possible on forecasting

https://na1.salesforce.com/help/doc/en/forecasts.pdf

6)How to customize and maintain products, price books, schedules, and quotes

7)Entitlements and Knowledge service cloud features in service cloud 

8)Reports,Dashboards ,workflows ,Approval process ,formula fields ,need for external Ids,data mangement tools like data loader ,validation rules 

9)Pay special attention to whats PARENTGROUPVAL and PREGROUPVAL Summary formula fields in reporting

10)Content management and data modelling

These are 10 priority items to really dig into while preparing for this exam.

The actual hands on on these topics are really helpful than just trying to go through reading material or videos .You can sign up for free developer org and practice these through workbook and tip sheets available on below link

http://help.salesforce.com/HTViewHelpDoc?id=quicktour_tips.htm&language=en_US

All the best for your preparation and keep following salesforce certification group  in LINKEDIN to recieve more updates ,when these BETA exams are available . 


Saturday, 20 July 2013

Fun With Maps In Apex

Maps are my favorite collection types .The Reason why its very essential to use Maps in apex  classes or triggers is it makes life simple for writing bulkified apex class or trigger .

Read more on Maps in below article from salesforce

http://www.salesforce.com/us/developer/docs/apexcode/Content/langCon_apex_collections_maps.htm
http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_map.htm

Apex we all know runs on an multitenant  architecture .The resources are shared and hence we have governor limits in apex .The advantages of proper usage of maps will help  to  reduce script statements,No of queries for a single context of class or trigger execution,avoiding query on a single object twice .

As a fresher to salesforce  we are unaware of various techniques that we can employ to reduce the script statements and reduce heap size of collection like Lists,Maps and Sets.

You can read some nice articles in developerforce and get familiar with some of common techniques which developers have discovered to deal with no of script statements and heap size issues

My favorite  recipes are as follows

http://developer.force.com/cookbook/recipe/using-sobject-constructors-to-save-script-statements
http://developer.force.com/cookbook/recipe/initialising-maps-from-queries

If you have been coding in apex from long time you might  have come across common use case that you need to aggregate collection of child records grouped by ParentId.

Something like say i will query on Contact Object and i am retrieving all contacts and I need a collection Map of Parent Id (AccountId) as Key and the collection of contacts related to AccountId .In short in apex language terms Map<AccountId,List<Contacts>>

Here is the code that i have included as an example on how to form the collection of Map<Id,List<Contact>>



Hope you enjoyed the technique .Happy coding !Let me know the feedback on the Post.

Thursday, 4 July 2013

Tips On Passing Advanced Developer Salesforce Certification Programming Assignment

As promised as per my previous blog i am sharing my experience on how to clear the advanced developer programming assignment and essay exams to obtain the Advanced Developer Certification.

One of the basic things i would like to mention is ,this you will not have it  overnight as the demand for the course is very high and there are limited slots available in each quarter .One has to be very sharp to quickly register for the exam on the dates mentioned in the certification.salesforce.com. Small negligence  will cause you to wait for another 2 to 3 months .

The assignments are distributed nearly after a month once you have registered .So this gives ample amount of time to revise your apex and visualforce skills.

Once the assignments are distributed you will have nearly a month time to complete your assignment and i would suggest reading the whole pdf that comes with assignment more than thrice atleast to make sure you understand the logical requirements and the hidden aspects of the assignments .

Usually a month time is enough for this but one has to make sure they spend atleast one weekend (Assuming your office timings are hectic and you have lot of work to cover on weekdays)

While doing assignment remember few key points 

1)Follow best practices while designing your trigger and visualforce controllers .Some of the reference links for the wiki articles that helped me  are below 

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

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

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

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

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


2)Testing is the most important aspect that is looked when your assignments are evaluated .Make sure you have adequate test methods with proper asserts 

3)Your application will also be evaluated as per security guideline's so make sure you understand the best practices for writing a secure code 


What does an Essay Examination consists of ?

Essay exams are just to evaluate that you have yourself designed the application and written the code .A Simple descriptive questions will be thrown that you should be good if you yourself have written the code .

To understand more on this i would suggest you to read the below article which is one of the best articles written so far on this subject


Hope you enjoyed this short read and its informational.Let me know your feedback on this article .

Saturday, 22 June 2013

Fun with Angular Js and Visualforce Page

Recently i authored a visualforce page just to demonstrate the use of angular JS (Javascript framework from google ).It was very good experience working with Harshit Pandey.

The idea was just to demonstrate how easily even with getters concept of visualforce one can bind data to the angular JS script

The page gives functionality of sorting ,pagination and searching all in a single UI.The UI is done through twitter bootstrap plugin.

The page code can be found below


The controller code is very simple and its just returning JSON object

The same post is posted by Harshit in a friendly format .You can find at following link http://www.oyecode.com/2013/06/getting-started-with-angularjs-on.html

Thanks and Happy Coding !

Monday, 3 June 2013

Using CSS in pdf for page numbering with API 28.0 (@page CSS properties)

Generating PDF in salesforce is very easy with renderAs="pdf" attribute of apex page tag.For those of you needing sample on how to achieve this ,the below link points in right direction to get started and create some professional documents using some CSS power and Visualforce tags

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

With API 28.0 my designed visualforce pages stopped showing the pagenumbers and other CSS attributes using style with @page annotations .

Here is the code that i tried in sample page to figure the issue with less code



  
  


This code yielded a pdf with no page number and hence conclusion that the @page CSS style properties are not working in API 28.0
Now the question arises like why it works in API 27.0 and not in API 28.0 .To understand this i read enhancements that came in API 28.0 on visualforce .I inserted html tag at start in API 27.0 and found again that @page attribute was not working.Hence injection of html above the head tag creates the issue .

To remove the issue i used the API 28.0 feature to stop the injection of html tag. Here is the working code



  
  

Setting applyHtmlTag as false stops the injection of the html tag and hence the page again started working as expected in API 28.0

Saturday, 11 May 2013

Mobile Application Development On Force.com Touch Platform-Part 3

This is in continuation with my previous posts .This post basically covers the difference between local and server side implementation approach for developing cross platform hybrid  mobile application on touch platform.

An hybrid mobile application is cross platform and generally use phonegap that comes bundled with mobile SDK to develop the application. Web developers familiar with the javascript will find it very friendly to learn and develop hybrid mobile application.

The following table below summarizes the difference and comparison between local(javascript on local device and using ForceTK/RemoteTk  library) and server side(Visualforce with Javascript Remoting) approach:



Local/ServerSide Hybrid mobile application development on touch platform
Feature local Approach using mobile packs(Backbone js/angulur js/jquerymobile) Server side Approach using Visualforce page
Databinding ForceTK or RemoteTK,Javascript modal functions for angular js or backbone js library functions Javascript Remoting can be used
Offline Support Smartstore.js can be used to achieve .Its relatively easier to provide this functionality in local side approach Html5 app cache concept can be used to provide offline(Not secure ,Smartstore Recommended),Browser capacity to store data is limited and hence if offline is major part of requirement its essential to develop with local side approach
Packaging Repeated Packaging for any changes to the application Less Frequent packaging due to One Time SFDC Package Deployment
SFDC API Remote TK consumes no API calls and hence can be used to save API calls,ForceTK consumes API call Visualforce Remoting feature and hence API calls are only consumed for DML operations
Code Storage The javascript library,CSS and whole code resides on the device The main javscript is written inside the visualforce pages
User Interface Jquery mobile can be used to provide good user interface.With angular and backbone libraries such as bootstrap can be used Jquery mobile is preferred .Although no hard rule ,any UI CSS library can be kept in static resource and used to develop mobile friendly UI
Development Effort The developer must be good in CSS,HTML5 and must be familiar with javscript libraries like angular or backbone.js The knowledge of visualforce ,jquerymobile and apex remoting is enough to develop server side hybrid application


The conclusion is at this point it really depends on the requirement to adopt which development model to prefer depending on the requirements .

Reference

http://www2.developerforce.com/mobile/

Introducing Lightning Base Components

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