Skip to main content

Posts

Showing posts from 2013

GROUP BY ROLLUP()

Use Case In one of my recent project, to achieve business objective I had to write a query to find total on the basis of certain criteria, say: GROUP BY Status, LeadSource . Further, I had to find subtotal on the basis of only Status. The solution which came on top of my mind was that get all records using a query something like: SELECT Status, LeadSource, COUNT(Name) cnt FROM Lead GROUP BY Status, LeadSource . And then loop through records and with the help of APEX , get the subtotals. As a developer, I can use collections to get my business objective. But I was curious to know if there is anything we can add in SOQL to get subtotals too.  Solution My curiosity took me to " GROUP BY ROLLUP() " option. With API version 18.0 and later, you can use GROUP BY ROLLUP to add subtotals for aggregated data in query results. This allows the query to calculate subtotals so you don't have to maintain that logic in your code. Use GROUP BY ROLLUP with aggregate functio

User Sharing - OWD for User Object Winter'14

Problem I am a manufacturer and I need to include all dealers in my organization while still keeping them from seeing each other. Solution   Before Winter'14 release, it was not possible. But with Winter'14 release, salesforce has introduced "User Sharing".  User Sharing enables you to show or hide an internal or external user from another user in your organization. Previously, User Sharing for external users was enabled by default with Communities, while User Sharing for internal users was available through  a pilot program. With Winter ’14, User Sharing is automatically enabled in new organizations. You can: Set the organization-wide defaults for user records to Private or Public Read Only. Create user sharing rules based on group membership or other criteria. Create manual shares for user records to open access to individual users or groups. Control the visibility of external users in customer or partner portals and communities. htt

Partial Data Sandbox

With Winter'14, salesforce has introduced a new sandbox type ' Partial Data Sandbox '. It will be fourth type of sandbox besides Developer Sandbox, Developer Pro Sandbox and Full Sandbox . Partial Data sandboxes include all of your organization’s metadata and add a selected amount of your production organization's data that you define using a sandbox template. A Partial Data sandbox is a Developer sandbox plus the data you define in a sandbox template. It includes the reports, dashboards, price books, products, apps, and customizations under Setup (including all of your metadata). Additionally, as defined by your sandbox template, Partial Data sandboxes can include your organization's standard and custom object records, documents, and attachments up to 5 GB of data and a maximum of 10,000 records per selected object. A Partial Data sandbox is smaller than a Full sandbox and has a shorter refresh interval. You can refresh a Partial Data sandbox every 5 days.

Grant Access Using Hierarchies

Problem There is a custom object say 'XYZ' and OWD for this is set to ' Private ', which means record of this can be seen by only owner and users above in role-hierarchy and territory. However, to share this with other user, we can manually share it. The problem is that I don't want other users, who are above in role-hierarchy and territory of the user with whom record has shared, can see it. Solution We can un-check ' Grant Access Using Hierarchies ' check box for object 'XYZ' on 'Sharing Settings' page. We can go to Setup >> Security Controls >> Sharing Settings and click on ' Edit ' button. On the edit page, we can un-check ' Grant Access Using Hierarchies ' for required object.  Major uses of 'Grant Access Using Hierarchies' are:- If you disable the Grant Access Using Hierarchies option, sharing with a role or territory and subordinates only shares with the users directly asso

Import GitHub Project in Eclipse

Use Case   There is a project going on and you join the team in between. Team is using Git for central repository. For you the starting point is to add git project in your Eclipse IDE and start development/enhancement/maintenance. Solution Pre-requisite - Eclipse having Force.com & egit plug-in installed. EGit plugin can be downloaded from http://www.eclipse.org/egit/download/ Steps to import your project from Github:- Go to Github.com and take URL of the project-   Open Eclipse IDE and go to New >> Import  Select 'Projects from Git' from pop-up window  Select URI and click 'Next'  Enter repo details as shown below. You only need to enter URL copied from GitHub for your project, 'Host' and 'Repository path' will be populated automatically. You will need to enter your github user name & password. Click on 'Next'.  From next screen, select all branches you want to have. To be safe, add all branches. Click

Hierarchical Relationship

Recently, I came across one of requirement where client wanted to have a custom lookup field on User object. This lookup will be on User. Based upon certain criteria, value of this field will go to Manager field. They didn't want update of Manager, but on the basis of some business use case. First impression to me was it will be straight forward to create a lookup on user and then in trigger will check for business use case and update Manager field accordingly. However, when I proceed with creating a look on User object, I couldn't find an option ' Lookup Relationship ' on first screen of 'New Custom Field'.  In fact, I saw only available option ' Hierarchical Relationship ' for creating any sort of relationship. I know most of us know about it. But you can't defer on my opinion that we tend to forget these small stuff. Since, on user you can't have any direct relationship, but only user. Salesforce gives you special relationship data t

ReadOnly Annotation

Use Case:- You want to show up to 10000 record on single VF page. Count of records based upon some business requirement where number of records could go up to 1 million. So far, it was not possible to achieve above in VF page because of following limitations:- The maximum number of items in a collection that can be iterated over using components such as <apex:dataTable> , <apex:dataList> , and <apex:repeat> is 1000. Normally, queries for a single Visualforce page request may not retrieve more than 50,000 rows. Solution:- But with API version 23.0 , salesforce has introduced ' ReadOnly ' annotation which has following functionality/restriction:- The @ReadOnly annotation allows you to perform unrestricted queries against the Force.comdatabase. All other limits still apply. It's important to note that this annotation, while removing the limit of the number of returned rows for a request, blocks you from performing the following operations

Error: Function ISNEW may not be used in this type of formula

Today while creating a workflow rule, I wanted to use ISNEW() function to check whether a record has been created or updated. The evaluation criteria I had selected was " created, and any time it’s edited to subsequently meet criteria ". When I clicked on 'Check Syntax' button, it threw error " Error: Function ISNEW may not be used in this type of formula ". I was under impression that it should be available to all criteria, but ' created '. After checking docs, I found that we can use ' ISNEW() ' function only with evaluation criteria " created, and every time it’s edited " and it can't be used with evaluation criteria " created " & " created, and any time it’s edited to subsequently meet criteria ".  Be careful before deciding upon selection of " Evaluation Criteria " and use of function within!

New Objects in API Version 29.0

Today, while working on Event object, I recognized that we can add more than one Lead/Contact to an event using 'Add to Invitees' link. My curiosity to understand how it is being stored in DB took me to ' EventRelation ' & ' UndecidedEventRelation ' objects. I suspected there are many more and it leads me to Winter'14 release doc and I found whole set of new objects in API Version 29.0 These objects are new in API version 29.0. The AcceptedEventRelation object represents invitees with the status Accepted for a given event. The AccountCleanInfo object stores the metadata Data.com Clean uses to determine an account record’s clean status. The AllowedEmailDomain object represents an allowed email domain for users in your organization. The AppMenuItem object represents an item in the app picker, exposing metadata for tab sets, service providers, and Connected Apps. The AttachedContentDocument object contains all ContentDocument objects associat

Bulkify Apex Methods - Using Collections in methods

I am working on an app which we plan to publish on app exchange. As per pre-requisite requirement by salesforce, any app before getting listed on app exchange should go through code review from checkmarx. To comply with this, we submitted our code base to checkmarx. We were surprised to see one of problem reported by checkmarx. The error says " Bulkify Apex Methods - Using Collections in methods ". Code snippet in question is (I have to hide my business logic :) ):- List<Account> lstAccount = new List<Account>(); Integer i = 0; for(Account acct : [Select Id, Name from Account]){ lstAccount.add(acct.Name = 'Test Account' + i); i++; } if(lstAccount.size() > 0) update lstAccount; I was wondering what is wrong with this, as it seems perfect. I went to http://www.salesforce.com/us/developer/docs/apexcode/Content/langCon_apex_loops_for_SOQL.htm to understand 'SOQL for Loop Formats'. As per this url, the summary says:- SOQ

Could not run tests on class - Solution

Today while writing a test class, there was some code related bug. After debugging I spotted and fixed it. However, when I tried to run test it gave me strange error saying something like:- Error: Could not run tests on class 01pK00000007EWE As per my blog http://sfdc-know-how.blogspot.in/2013/11/could-not-run-tests-solution.html, I cross checked if 'Disable Parallel Apex Testing' is checked and found that its already unchecked. Next step was to 'Clear Test Results'. After clearing the test results, I did 'Run Test' on my test class and guess what, it executed like charm. Another weird behavior because of Winter'14 release.

Limit Info Header - Possible bug with Chatter REST API

With Winter'14 release, Salesforce has introduced 'Limit Info Header'. The Limit Info header is a response header that’s returned from each call to the REST API. This header returns limit information for the organization. Use this header to monitor your API limits as you make calls against the organization. Same is also available with SOAP API. I was very excited to see this. The very common use case I can think of is to access this header value and decide if we want to show end user some graceful message in case they have exhausted all available number of API calls. I tested it straight away with a simple call get detail of account object as shown in below figure. I was happy to see desired value of 'api-usage' in header. However, when I tried the same on chatter REST API, I couldn't find 'sforce-Limit-Info' field in response header as shown in below figure. Possible salesforce bug!

User Sharing - Winter14 Release

Today, while working on one of our client's organization there was a requirement to get the detail of Owner of a collaboration group. We couldn't use Salesforce UI to get and look into CollaborationGroup because of some reason. I used ID of CollaborationGroup to make a query and get OwnerId field's value. OwnerId was that of a user, since it was starting with '005'. When I run a query on User to get detail of this user, I was surprised that query returned 0 records. I was puzzled, since CollaborationGroup has a user as owner, but query is not returning me detail of this user. After much of exploration, I realised that it is because of one of feature released in Winter14 ' User Sharing '. Following is detail of what it is:- Control who sees who in the organization with standard sharing functionality. User Sharing enables you to show or hide an internal or external user from another user in your organization. Previously, User Sharing for exte
' Push Upgrades ' is a nice feature for Creating & Uploading Patches to customers organization easily. However, there is best practices around this suggested by salesforce which is listed on https://help.salesforce.com/HTViewHelpDoc?id=push_patch_best_practices.htm&language=en_US. However, apart from above best practices, there could be scenario, where you might have created a new component say trigger or class. Now, when you create a new version of package and push it to customers organization there are highly likely chances that your customer forget to add access of these new component(s) to desired profiles (except system administrator, since they will get access automatically).  In case of manually updating package on customer's organization, they get an option where they are asked to who all you want to give access and then admin can make decision. Tip - In case you are using 'Push Upgrade' and if new release is going to have new component, pleas

Batch Job - First error: Future method cannot be called from a future or batch method

Today while working on one of requirement, where we need to schedule a job after every fixed interval of time. During unit testing we found our job stuck. Initially we thought, it may be because of non-availability of resources, since scheduled jobs get queued if resources are not available and runs as soon as resource is free. After waiting for 30 mins, we went to Setup >> Jobs >> Apex Jobs to see what is status of Batch Apex. We found that 'Scheduled Apex' i.e. scheduler was in ' Queued ', while the ' Batch Apex ' i.e. batch was in ' Failed ' status. It was causing job to stay stuck. First error: Future method cannot be called from a future or batch method We need to be careful against such scenario. We may think that our job is running properly, whereas it may be in stuck status because of exception. We need to do follow to avoid such issue:- 1. Properly unit test job, with all possible use case and mass data. Don't test only f

Issue with All Topic Records SystemModStamp field update

We have number of Topic records in one of org created in span of last 2 months. However, we have noticed that if we assign a topic to some FeedItem, it causes SystemModStamp field of all Topic records of org get updated with current datetime value. Our assumption is that, SystemModStamp of only assigned Topic's record should be updated. Looks like potential BUG ! Following with SFDC, will keep you all updated.

Error: Compile Error: Schedulable class has jobs pending or in progress

Today, while working on one of class, when I tried to save my changes I got following error:- Error: Compile Error: Schedulable class has jobs pending or in progress at line 5 column 21 I thought, its coming because there may be some job is running or scheduled. However, when I checked Setup >> Build >> Jobs >> Scheduled Jobs , I couldn't find any scheduled job. Just to be sure that there is not any apex job in running status I checked Setup >> Build >> Jobs >> Apex Jobs . And there were not any job in running status.  Just to be clear, Apex Jobs were listed in descending order of Submitted Date . I just checked first few of Apex Jobs. They were either in Aborted or Completed status. I was wondering what's wrong. After further analysis, I decided to check Setup >> Build >> Jobs >> Apex Jobs in more detail. After scanning status of all Apex Jobs, I found one job which was still in ' Queued ' status. And i

Could not run tests - Solution

Today I have written a test class, having only one test method into it. When I ran the test class to check for code coverage, I got a very strange error saying "could not run tests on <Id of test class>". Whereas it was showing that the test method run successfully with desired result in terms of code coverage. I further tried to update the test class and it again gave very strange error "java.lang.reflect.InvocationTargetException".  Initially I thought there is something wrong with my class and cross checked for syntax, identifier etc. After making sure that there is nothing wrong with class, I went to see if anyone faced same issue before. I found actually quite a few and below is solution to get rid of this:- Go to App Setup >> Develop >> Apex Test Execution and click on "Options". Uncheck 'Disable Parallel Apex Testing' and click on Ok. Go to App Setup >> Develop >> Apex Test Execution and click on "

IP Ranges on Profiles

Use Case - An organization with some 50+ profiles is running a mission critical sfdc solution since last 5-6 years and after analysis of security implications decided to have IP based restriction on access. The organization in question is trying to make sure that mission critical application can be accessed only through office network or via VPN if outside office. The organization is global in nature and has 500+ possible IPs. Also, the deployment process involves migration of components through 4 boxes. Possible Solution:- 1. Manually add IPs to all profiles - 50+ profiles X 500+ IPs = 25000 IPs entry. Quite cumbersome indeed, may be hours and hours. Also, very much possible that Networking team wants to do testing with only few IPs first and then add more and more. 2. Use Eclipse to add IP ranges to profiles - It will need just addition of 500 IPs on one profile and latter just copy & paste the same in other profiles. I am going to describe below how we can mak

Memory Reference in Apex

Recently during one of project, I was creating a map of integer and list of integer. My code snippet something like:- I was expecting something like {1=(1), 2=(1,2 ), 3=(1,2,3), 4=(1,2,3,4), 5=(1,2,3,4,5), 6=(1,2,3,4,5,6), ...} as output. However, I was surprise to see the output as {1=(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 2=(already output), 3=(already output), 4=(already output), 5=(already output), ...}. I was wondering what's wrong with my code and started exploring how I can fix it. After going through blogs & docs, I get to know that if I call some method like clear() on a list and put it in a map and use the same variable with modified values for next element of map, ultimately SFDC stores address of same variable in each element of map, because of which I finally get same value in each element of map as per above code. If I make a small change in my code,as shown below, my code will start yielding expected result:- If you closely look into change, instea