How to assign Leads in a Round Robin fashion?

May 16, 2013 § Leave a comment

Round Robin Lead Assignment Process summary
This process mainly revolves around a set of users for a particular role (if the round robin needs to be assigned within the users of that role) or can also be completely different set of users from different role hierarchies. The users are set in the Lead Assignment rule using each criterion. Following are some high level requirements before making the round robin functional:
– Create a number field; let’s say “Lead Auto Increment ” and this field is being incremented using a trigger.

– Another formula field is created after this, let’s say “Small Market Assignment” (assuming users are from a role named “Small Market”) which will be as follows:
IF( NumberOfEmployees < 5001, MOD(Lead_Auto_Increment__c, 4), 99999)

– The Small Market Assignment will be populated based on the value of Lead Auto Increment. The MOD function is going to take our Lead Auto Increment value, do a bit of math and return a number in a range we specify. The “4” in the formula above means that it will return a number of 0, 1, 2, or 3. For the sake of our example here, we’re going to assume that we need to implement round robin assignment between 4 users and so the 4 in the formula. Depending on the number of users for our round robin, this value can be changed anytime. The formula is taking our Lead Auto Increment field and creating a Small Market Assignment value.

– Here in the formula, we are taking into consideration a business need for the round robin assignment. Any lead which has “No. Of Employees” less than 5001 will be considered as a criterion to be under the round robin assignment.

– Now, we have the two fields and the trigger in place. But there is a catch here. As we have decided to keep incrementing the Lead Auto Increment value and it is a field under the Lead object, we cannot keep track of the last value of this field in the last lead record created.

– For this, we will need some way to store the latest value of Lead Auto Increment field. Here, custom setting feature of Salesforce comes for our rescue. We will need to create a custom setting and create a field there; let’s say “AutoIncrement” which will store the latest value of the field “Lead Auto Increment”.
For example, we created a new Lead and the trigger updated the value of Lead Auto Increment to 0 since it has number of employees less than 5001 (we can add more conditions in the trigger based on the business requirement). Now, the custom setting field AutoIncrement will store the value 1. Next time, another lead is created/inserted, the Lead Auto Increment value will be 1 and AutoIncrement will be set to 2. This is accomplished using the same trigger.

Assignment Rules

– Further, if we think proactively, we will also realize that if an existing lead which is already assigned to one of those users (taken into consideration of our round robin assignment rule) is edited and meets our criteria again, then the trigger will update the Lead Auto Increment value and hence the Small Market Assignment value will be updated and finally, the lead will be re-assigned to another user. We don’t want this to happen.

– So, here we can create another field in the same custom setting; let’s say “Users” and store the Salesforce usernames of those users considered to be within our round robin rule. So, the trigger will check the criteria and before it updates the Lead Auto Increment value it will check if the current lead record owner is among these usernames stored in this field “Users”. If it is then the Lead Auto Increment value will not be updated and consequently, the Small Market Assignment value will not populate as well as the Lead Assignment rule will not trigger.

Custom Settings

– Also, please make a note that we need to start the value of the custom setting field “AutoIncrement” to 0(zero) in the very beginning. Also, sometimes Admins can forget to set this initial value, it is always a good practice to set this value from the trigger itself initially and keep on updating with the latest value going forward with each lead creation.

Advertisements Administration Winter ’12 Release Exam

March 5, 2012 § Leave a comment

Summary of Winter’12 Release Exam Notes

Collaboration Cloud
• New feature includes Approvals into chatter, customers into private groups and private messages and a powerful tab.
• Approver can receive a chatter feed with the defined template of feeds on chatter and the approver can approve or reject record right from the chatter post.
• Feed tracking should be enabled for the object on which the user wants to create an approval process.
• Define a post template and select fields which you want to see in your chatter feed of approval process.
• Enable Approval Processes for chatter.
• Enabling Approval Process within the chatter will help busy executives and sales rep to see the status of the approvals.
• All chatter groups and their respective users must be aware that guests are there in groups and Salesforce shows that on-group picture and member list and also mentions in clearly that members are in the group.
• A chatter group with allowed customers is designed to show the users that customers are in group and once the access is defined to customers it cannot be revoked.
• Any file within the chatter now can be shared with external user with “Share via Link” option and for that both content delivery and chatter file sharing must be enabled with appropriate permission from profile is also required.
• Starting winter’12 files tab is replacing the documents tab but using the default tabs option documents tab can be added back.
• User with “Manage Chatter Message Permission” can see all users’ messages.
• New chatter API object, some new fields are available and chatter REST API is now GA, which means that chatter can now be within the organization intranet.
• Hovers also got new pop up for almost every link, E.g. Files, Users and groups.

Sales Cloud
Social Contacts
• With winter’12 LinkedIn, twitter and Facebook are integrated with Salesforce now and sales reps can see the details of a user on these social networks.
• Social contacts need to be enabled for your organization.
• User need edit permission in order to attach social contact to a user and need read permission in order to see the contact’s social network.
• All the details are current in social contact as you cannot import social network information for a contact.
• Social Contacts settings are also available on user level.
• Your credentials are not exposed to salesforce because salesforce uses OAuth for Authentication.

Outlook Enhancements
• Outlook enhancements allow you to edit records in batch edit mood which help users solving unresolved items.
• Add up to 10 emails to outlook at a time.
• Combination of batch edit and recommendations help a lot in solving the unresolved Items.

• New version of forecast is only available to new customers old customers will continue to use the previous version.
• New version supports multiple currencies.
• Opportunities will be pulled dynamically on forecast selection.
• With new Forecast adjustments to the subordinates forecast are east to make.
• Forecast dates can be defined by administrator and forecast category can be changed to align with Organization’s business processes.
• Instead of the jigsaw tab there will now be a tab.
• will be enhanced and will add more contacts from another data company.
• includes some new features like you can save your search criteria, you can export contact and company data right from, you can exclude, include or opt for an exact match in search now, New list user is available for
• Saved searches are limited to 25 companies and contact searches at a time.
• Exporting company and contacts are limited to 50K.
• You cannot add more than your monthly limit and assigned credit from you admin.
• New icons for added contact and inactive contacts.
• When you export and add the same record it only counts once.
• If you want to exclude something from title fields you have to use title; prefix.
• In future, release titles field will be separated for search.
• Every field of search can contain 128 characters.
• You can now assign a “list user” to your users and they can use the monthly pool of the organization rather than personal user limit to make sure that any of the limits doesn’t go to waste.

• With winter’12 dashboard can have filters and can be applied to a single field and each user can choose from up to 10 filters, without dashboard filter we would have to create multiple dashboards.
• Using filters having a single dashboard can serve multiple purposes.
• Dashboard can only have a single filter and filter can only be based on pick list, lookup, and a text value.
• Dashboard with visualforce cannot use filters.
• Scheduled or emailed dashboard and chatter snapshot are unfiltered.
• Filter cannot be used on dynamic dashboard and filtered component cannot be followed in chatter.
• In the following releases filter will be available in dynamic dashboards as well.
• Enhanced reports tab helps you to locate your most recently viewed reports.
• User objects can now be the primary object in a custom report type and user can have child object based on the relationship he wants.
Cloud Based Flow Designer
• Cloud based flow designer to design business processes faster and efficient.
• Apex plugins can also be used within the cloud based flow designer.
• Currently it only supports English language.
• Ability to convert leads and send emails.
• API calls made by the desktop version of flow designer count against your API limit.

• With winter’12 Site force is generally available and with site force you can create pixel free highly scalable site.
• Siteforce is created by keeping a website publisher in mind it could be a new job for an organization, Publisher creates website and maintain the overall look and content of the website.Create template and pages, Modify layout and design and publish to a live site
• Web contributor import assets, edit content and images, preview pages
• With siteforce publisher and contributor can work together to produce agile websites.
• Siteforce in coming release will be integrated with

Productivity Enhancements with
• With winter’12 new home page layout, quick application create and a floating setup.
• We can now make setup page our landing page from user information.
• is a multitenant database as service and can serve with multiple applications including Java, Heroku, mobile and social apps.
• included with Developer, Enterprise and unlimited editions and can also be purchased as a standalone service with secure data storage, tuning scaling, backups and recovery is also available with
• is a subset of what we have used on platform.
• We can create our database using custom objects, formula and validation rules.
• Standard objects are not available in
• We can also write triggers and apex classes which fires on all seven events.
• We can also create workflow rules which have all four same actions as
• Wizard and data loader is also available or we can write our own data loader application.
• Sandbox and IDE can also be used for development on
• Your program can interact with using any of the API you are familiar with, SOAP based API , REST API and Bulk API.
• The Java SDK is a set of pre complied classes which make sure that you quickly developed and have a secure connection and you can also use OAUTH.
• The Java SDK can also be used with any with API Enabled.

Permission Set
• Permission sets allow you to grant more access on top of your profile settings and without modifying your existing profiles.
• If you want to give permission to a user of a profile but not to other who have the same profile you can use permission sets.
• Traditionally in order to do that you create more profiles and it increases the number of profiles drastically.
• With permission sets you can add more permission to whatever their profiles already provide.
• Profile+ permission set 1+ permission set 2=user access.
• We can assign 1000 permission set per user.
• Permission set can only be used to give access to user not to deny access.
• With permission sets users can be given responsibilities, deploy new phases and give specific application access.
• Permission sets needs to be created through user records.
• Permission set cannot be defined for a group of users.
• Reporting is not available on permissions set.
• Each permission set can be reused to other users

Schema Builder
• Schema Builder provides a visual representation of Objects and relationships.
• Required field color code, Color code for lookup and master detail relationship and schema view organizer.
• In future schema builder will be enhanced with adding SObjects and Fields directly from schema builder.

Chatter REST API
• The chatter REST API is a tool to integrate chatter with non-Salesforce Application.
• It returns feed items structured for rendering in on websites and mobile devices.
• Data automatically localize for users time zone and language.
• Chatter REST API will be used to build social applications.
• Integrate chatter with twitter and facebook.

Apex Enhancements
• Apex has received a number of enhancements this release
• On major enhancements is Native JSON (JavaScript Object Notation) support, JSON has become the standard of data transfer via is very concise and with winter’12 we can use built-in JSON classes to parse data within APEX.
• We can serialize SObject into JSON to send a data to an external system.
• Other Enhancements to Apex includes new system methods IsBatch, IsScheduled and IsFuture, Allow the determination of in which code it was invoked
• You can branch you code on the context of the code.
• Governor limits are raised for batch and future methods.
• SOQL Queries raised from 100 to 200
• Code statements raised from 200000 to 10,00000
• Heap size rises from 3MB to 6MB.
• @Readonly notation for web services and Schedulable interface allows unrestricted database queries and prevents any DML operations
• API for asynchronous test runs, allows developer to asynchronous test runs
• Test classes can now be public no longer needs to be private; this allows creation of reusable test classes for common test data creation.
• Developer console is now renamed as System log console, continued improvement and addition of new tools.

Questions with Answers:

1) In Siteforce, what can be done by a site publisher but not a site contributor? [Choose 2 answers]
A. Preview site pages
B. Import assets
C. Modify a layout (Your Answer)
D. Create a website (Your Answer)

2) What is a capability of the cloud-based Flow Designer? [Choose 2 answers]
A. Run and test a flow from the Audit tab.
B. Create a flow using a consolidated set of elements. (Your Answer)
C. Create a Flow and then upload it into Salesforce.
D. Add elements to the Flow from the Palette tab. (Your Answer)

3) When using Social Contacts, what determines the amount of information a Salesforce user sees when viewing a social network profile for a contact? [Choose 2 answers]
A. The user’s profile settings in Salesforce
B. The user’s social network connection to the contact (Your Answer)
C. The user’s access determined by account sharing rules
D. The contact’s social network privacy settings (Your Answer)

4) What is a capability of permission sets? [Choose 3 answers]
A. Grant permissions to specific users in addition to their existing profile permissions.(Your Answer)
B. Remove permissions that are currently granted in specific users’ profiles.
C. Modify existing permissions for a given role or public group.
D. Modify the tab settings and page layout assignments for specific users.

5) What is a capability of Chatter approvals? [Choose 2 answers]
A. Users can approve edits to Chatter files directly from the Chatter feed. (Your Answer)
B. Users can view and respond to approvals as Chatter posts through email notifications.
C. Group owners and managers can approve new members to Chatter groups from the group feed.
D. Users can view and respond to approvals as Chatter posts within their Chatter feed. (Your Answer)

6) What can be done with the schema builder? [Choose 2 answers]
A. View the relationships between a set of Salesforce objects. (Your Answer)
B. Create fields on a Salesforce object.
C. View the required fields of a Salesforce object. (Your Answer)
D. View the permissions for a Salesforce object.

7) What is a capability of within Salesforce? [Choose 2 answers]
A. Export contact and company records. (Your Answer)
B. Earn credits by contributing data.
C. Import specific companies to search.
D. Save search criteria for later use. (Your Answer)

8) In Salesforce for Outlook, which related records are recommended when assigning unresolved events, emails, and tasks? [Choose 3 answers]
A. Accounts (Your Answer)
B. Cases (Your Answer)
C. Contacts
D. Leads
E. Opportunities (Your Answer)

9) What can customers do in private Chatter groups?
A. Chatter customers can run reports on Chatter group membership.
B. Chatter customers can post to the groups to which they were invited. (Your Answer)
C. Chatter customers can view accounts, contacts, and opportunities.
D. Chatter customers can post to Chatter profiles and follow people.

10) If the User object is the primary object in a custom report type, which set of related Activities can be included in the report? [Choose 3 answers]
A. Activities last modified by a user (Your Answer)
B. Activities owned by a user (Your Answer)
C. Activities followed by a user
D. Activities created by a user (Your Answer)
E. Activities shared with a user

11) How can permission sets be used? [Choose 2 answers]
A. To assign read access to a custom object for specific users (Your Answer)
B. To assign access to a custom app for specific users (Your Answer)
C. To assign system permissions to specific users
D. To assign a record type to specific users

12) What is a recommended type of website to create using Siteforce? [Choose 2 answers]
A. eCommerce websites
B. Authenticated site
C. Targeted micro site (Your Answer)
D. Upcoming Event Site (Your Answer)

13) What functionality is available with [Choose 3 answers]
A. Automated tuning, scaling, backups and recovery. (Your Answer)
B. Standard and custom Salesforce objects
C. Analytics tool including reports and dashboards
D. Profiles, roles and sharing rules (Your Answer)

14) What can be created using Quick Start? [Choose 3 answers]
A. Custom apps (Your Answer)
B. Object relationships
C. Custom report types
D. Custom tabs (Your Answer)
E. Custom objects (Your Answer)

15) When viewing a dashboard, what can a user do with a dashboard filter?
A. Filter the data that appears in an emailed dashboard.
B. Filter by a specific field that is common to all dashboard components. (Your Answer)
C. Filter the Visualforce components on a dashboard.
D. Filter the dashboard by the running user.

NOTE : The questions and answers might not be in the same order as I have given above.

Running a Batch Job in Apex with mass records

March 5, 2012 § Leave a comment

A scenario comes when you need to process mass records either updating or inserting or deleting. We can make use of Batch Apex to process all the records at once.

Excerpts from the Winter ’10 Release :
Batch Apex gives you the ability to operate over large amounts of data by chunking the job into smaller parts, thereby keeping within the governor limits. Using batch Apex, you can build complex, long-running processes on the platform. For example, you could build an archiving solution that runs on a nightly basis, looking for records past a certain date and adding them to an archive. Or you could build a data cleansing operation that goes through all Accounts and Opportunities on a nightly basis and reassigns them if necessary, based on custom criteria.

In order to develop our Batch Apex, we need to create a new Apex class which extends “Database.Batchable” interface.

This interface will have three methods to be implemented:

  • start
  • execute
  • finish

“start” method is called at the beginning of a batch Apex job. Use this method to collect the records (of objects) to be passed to the “execute” method for processing. The Apex engine, automatically breaks the massive numbers of records you selected into smaller batches and repeatedly calls the “execute” method until all records are processed.

The “finish” method is called once all the batches are processed. You can use this method to carry out any post-processing operation such as sending out an email confirmation on the status of the batch operation.

Let’s take a closer look at each of these methods:
1. Start Method

global Database.QueryLocator start(Database.BatchableContext BC) {
      //passing the query string to the Database object.      
      return Database.getQueryLocator(query);

2. Execute method

 global void execute(Database.BatchableContext BC, List<sObject> scope){
    List<Account> accns = new List<Account>();

   for(sObject s : scope){Account a = (Account)s;
update accns;

3. Finish Method

global void finish(Database.BatchableContext BC){
  // Get the ID of the AsyncApexJob representing this batch job  
  // from Database.BatchableContext.    
  // Query the AsyncApexJob object to retrieve the current job's information.  

 AsyncApexJob a = [Select Id, Status, NumberOfErrors, JobItemsProcessed,
   TotalJobItems, CreatedBy.Email
   from AsyncApexJob where Id =:BC.getJobId()];

  // Send an email to the Apex job's submitter notifying of job completion.  
  Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
  String[] toAddresses = new String[] {a.CreatedBy.Email};
  mail.setSubject('Apex Sharing Recalculation ' + a.Status);
  mail.setPlainTextBody('The batch Apex job processed ' + a.TotalJobItems +
    ' batches with '+ a.NumberOfErrors + ' failures.');

  Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

Passing the certified Developer Exam (401)

December 7, 2011 § Leave a comment

This is just a small post I thought would be relevant to let you guys know that I have passed the certified Developer exam i.e the 401 exam and how to go about it with some insights from my own experience. The exam I would say won’t be that tough for someone who have worked for sometime and have got some hands on experience on the platform. Most of the questions are from the Administrative perspective i.e the 201 exam I should say. The rest are some advanced things one should know about the other features of the platform.

There are a lot of questions on sharing and security settings and some of them are scenario-based. For Example:

Q. A record was created and the option to share the record through Hierarchies has been unchecked. Who all can make changes to the record?
a. only the Owner
b. the owner, the members above the owner in the hierarchy and the administrator
c. the owner and the system administrator
d. only the system administrator.

Another Example:

Q. Features of platform that are enabled by default when we create a custom tab for an object.
a. Create new on the sidebar.
b. Search on the sidebar
c. Quick create on the sidebar
d. Recent Items on the sidebar

Then expect some direct questions like :

Q. What is the size of a visualforce page? 15 MB

Last but not the least, there will be some questions on which tool you will use with a given business requirement.

These are pretty much one should know before heading for the 401 exam. Many of the things will be what you would have come across in the platform itself and if you need any further help or have some queries, feel free to ask me or just mail me. I would be glad to help you out.

Using the Data Loader for Migration of Objects (Master-Detail relationship)

November 3, 2011 § Leave a comment

Using a Data Loader to migrate data from one Org to another is not that quite simple when there is a Master-detail relationship to be taken care of and maintaining the same relationship in the destination Org. I could not for the life of me remember the steps to follow whenever I am required to use Data Loader is such scenarios. And so I happen to write it down somewhere in a scrap paper and now as I have a running blog to share, I can post this and get a look every time I am going to use it in future and hopefully many will find it useful coming across this post.

Pre-requirement before following the below steps:

  1. You should have one csv file exported from the source Org which has all field values of the Master Object to be migrated to the destination Org.
  2. You should have a second csv file exported from the source Org which has all field values of the Detail Object along with the lookup ID field to the Master Object.

So here are the steps:

  • Create an External ID field in the Master Object of destination Org
  • Import the Master Object into destination Org with the ID field values(Source Org) inserted into the External ID field of destination org.
  • Export the Master Object from the destination Org along with the new ID field and the External ID field values as a CSV file.
  • Convert the ID values of both the master Object (in the csv file exported from Destination Org) and the detail Object (already exported from the source org) into a string of length 15 and then convert them with Tim’s formula to get the last 6 values of the each string in digits.
    • converting into string of 15 : =LEFT(A2,15)
    • Tim’s Formula : A3&CODE(MID(A3,13,1))&CODE(MID(A3,14,1))&CODE(MID(A3,15,1))
  • Convert any DATE fields with this formula before inserting into the destination Org
    • TEXT(A2,”yyyy-mm-ddThh:mm:ss”)&”.000Z” or select the date column and select ‘format’->’custom’ and type = yyyy-mm-ddThh:MM:ss:sssZ and press OK
  • Use VLOOKUP on the detail Object CSV file to match with the values in the Master Object CSV file
    • vlookup formula : VLOOKUP(value, table_array, match_value, case_sensitive or not(Boolean))
    • where value is the column in detail Object csv file to be searched or matched in Master Object csv file
    • and table_array is the fields(e.g. A1 to D1 till the last row) to be selected for matching in the Master Object csv file
    • and match_value is the no of the column next(usually 2) to the matched column(usually 1) in the Master Object csv file.
    • case_sensitive is the value to be given in VLOOKUP as a Boolean value either TRUE or FALSE to match for case-sensitivity.

In order to give these steps a graphical view, I have also created a diagram that can well explain what I am trying to convey in a simple way.


A simple graphical view of steps to use Data Loader

In the diagram above, I have taken a simple example of an Account (Master Object) and Contact Object (Detail Object).

Feel free to comment and make this post more useful. I might not be clear in some of the steps above and it can be simplified more for beginners to understand.

Using the Inbound Email Service of

November 2, 2011 § Leave a comment

If anybody has not come across this feature of Salesforce, then feel free to grok here as it is an out of the box functionality. This can help someone who needs to receive an email from outside of Salesforce and do something within Salesforce using an Apex class.

Just go to: Setup -> Develop -> Email Services.

Rest of the things are pretty straight forward. Click on “New Email Service” to create one. And then you can look up on Defining Email Services to fill in the details without much of an issue.

You would require an Apex Class to select for the field labeled as “Apex Class”. So, lets look at what you can do here:

global class ProcessEmail implements Messaging.InboundEmailHandler {
  global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) 
    Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
    String str = email.plainTextbody;
    List parts = str.split('\n');
    String obj_name = parts[0];
    Id obj_Id = null;
        obj_Id = [Select id from Object__c where Name =: obj_name].Id;
        Attachment attachment = new Attachment();
        attachment.ParentId = obj_Id;
        attachment.Name = email.subject;
        attachment.Body = Blob.valueOf(email.htmlbody);
        attachment.ContentType = 'html';
        insert attachment;
    }catch(Exception qe){
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

        String[] toAddresses = new String[1];
        toAddresses[0] = email.fromAddress;
        System.debug('====&gt; to addresse '+toAddresses[0]); 

        mail.setSenderDisplayName('App Support Administrator');
        mail.setSubject('App Support');
        mail.setPlainTextBody('The Object: ' + obj_name  +' did not match with our app.');
        mail.setHtmlBody('Your Request to add your email as an attachment to the Object_Name:<b> ' + obj_name +' </b>has not been created.'+
             'A matching record could not be found in the app');

        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    // Return the result for the Email Service
    return result;

Here in the above class what we are doing is that we are reading the email sent from an anonymous address and trying to match the first line of the email with one of our Object record Name in and based on that we attach the email body as an attachment to the respective Object record.

We also used a try and catch block to see if the Object record name matches with our record in and if it doesn’t then we shoot back an email to the anonymous user based on the email address used to send the email to

Next, what we need to do is just add an Email address to publicize to those potential users who are going to send email to i.e. to our app here.

If you have closed the Email Service window, better to open it and when you scroll down you will see a button to add “New Email Address”. Click on it and fill in the form using the help from this link Defining Email Service Addresses.

You just need to fill in the local part of the email address. Salesforce generates a unique domain-part for each email service address to ensure that no two email service addresses are identical. The generated domain-part appears to the right of the Email Address field.

One last thing that I would like to add here is that there might be a scenario when you might want to use the Email templates in to use while reverting back to the anonymous user. In that case, take a look into this post Salesforce: Using basic email templates from Apex code.

One drawback of using Email Template is that the user sending the email cannot be anonymous anymore as he/she will have to be from either the Account, Contact or User because Email templates uses merge fields and there has be some access rights linked to the user who can view these fields if there are restricted sharing settings.

A few other links that might be helpful in using these service: