Salesforce interview questions
20 questions with answers. 1,775 open jobs in India ask for Salesforce.
What are Salesforce ID's composed of?
The Id Field Type is a base-62 encoded string.
Each character can be one of 62 possible values:
- a lowercase letter (a-z) - 26 values
- an uppercase letter (A-Z) - 26 values
- a numeric digit (0-9) - 10 values
As there is a combination of lower and upper case letters the casing of the 15 character Id has significance. E.g. 50130000000014c is a different ID from 50130000000014C.
Within a 15 character Id the breakdown is:
- First 3 characters - Key Prefix As per Jon's answer, the first 3 characters are the key prefix that identify the object type. There are a few exceptions to this where multiple objects all share the same key prefix! There are a number of fixed key prefixes that are common across all of Salesforce. Custom objects get a unique key prefix per Org. I'd need to confirm this, but I'm fairly certain that Custom objects in managed packages can have a different keyprefix in each installed org.
- The 4th and 5th characters - Reserved. Currently used for the instance id (a.k.a. pod identifier) (As per comment from @ca_peterson). Starting with the 4th character and overflowing to the 5th if required. Indicates which pod/instance the record was created on. Note that data may be migrated to other pods over time. Updated based on a separate question that indicated the pod identifier is actually two characters rather than one as initially thought.
- 6th and 7th characters - Reserved. Will be
0until such time that Salesforce has a need for it. Source - Steven Tamm - Remaining 8 characters - basically a really big number. Like 62^8 big.
To this you can add an optional 3 character suffix that will make the Id unique case-insensitive. This is useful when working with programs that can't maintain the case of the ID (E.g. Excel VLookup).
Notes about the suffix:
- this is not intended as a check sum to verify the other 15 characters haven't been corrupted.
- you can't just lower/upper case the entire ID. While it helps other case insensitive applications handle the IDs Salesforce is still case sensitive and won't auto correct the casing based on the suffix. E.g. the casing on a KeyPrefix is important with
00tbeing OpportunityShare and00Tbeing Task.
The algorithm to convert from a 15 character Id to an 18 character Id is: (Source - I'm sure there used to be official documentation on how do this.)
Divide the 15 char into 3 chunks of 5 chars each.
For each character give that position a value of 1 if uppercase, 0 otherwise (lowercase or number).
Combine the bits from each chunk into a 5 bit integer where the rightmost bit is the most significant bit. This will yield a number between 0 and 31 for each chunk.
Construct an array that contains the sequence of capital letters A-Z and 0-5 (26 + 6 = 32 possible values).
Use the integer from each chunk to choose a character from the array.
Append the resulting 3 characters, in chunk order, to the end of the 15 char id.
Read the rest at the sourceFrom Salesforce Stack Exchange: asked by Ryan Elkins, answered by Daniel Ballinger (CC BY-SA 4.0)
Unit testing code which has logic around the CreatedDate
Spring '16 Release Notes document a new system method supporting this:
Test.setCreatedDate(recordId, createdDatetime)Sets CreatedDate for a test-context sObject.
This will definitely complement the
loadData()anddeserialize()techniques.Account account = new Account(Name = 'Test'); insert account; Datetime yesterday = Datetime.now().addDays(-1); Test.setCreatedDate(account.Id, yesterday);Test Class: Contains methods related to Apex tests.
setCreatedDate(recordId, createdDatetime)
Sets CreatedDate for a test-context sObject.
All database changes are rolled back at the end of a test. You can’t use this method on records that existed before your test was executed. You also can’t use setCreatedDate in methods annotated with
@isTest(SeeAllData=true), because those methods have access to all data in your org. If you set CreatedDate to a future value, it can cause unexpected results. This method takes two parameters—an sObject ID and a Datetime value—neither of which can be null.Insert your test record before you set its CreatedDate, as shown in this example.
@isTest private class SetCreatedDateTest { static testMethod void testSetCreatedDate() { Account a = new Account(name='myAccount'); insert a; Test.setCreatedDate(a.Id, DateTime.newInstance(2012,12,12)); Test.startTest(); Account myAccount = [SELECT Id, Name, CreatedDate FROM Account WHERE Name ='myAccount' limit 1]; System.assertEquals(myAccount.CreatedDate, DateTime.newInstance(2012,12,12)); Test.stopTest(); } }From Salesforce Stack Exchange: asked by David Gillen, answered by Matt and Neil (CC BY-SA 4.0)
End of javascript sidebar workarounds? (Salesforce Classic / Aloha)
ALERT UPDATE (Spring'16)
These workarounds were never supported by Salesforce officially. They have worked for many years but now the are no longer possible with the Spring'16 Update. It was announced by Salesforce in 2015 that even the workarounds described in the section below for Winter'16 are shut down with the Spring'16 Release, in February 2016. I verified it on different pods and can confirm it's over. Here are the details:
What is changing?
The Salesforce Technology team is updating code within the standard Messages & Alerts and Custom Links home page components, including JavaScript and custom HTML markup to comply with our evolving security architecture best practices. These changes will enhance the security of your organization.
End of Sidebar workarounds via Messages & Alerts and Custom Links finally in Winter or Spring '16? It's pretty clear and it looks like we have an end-date now.
The new Lightning Experience UI is still evolving. The Lightning Experience UI will probably make a lot of use cases for these workaround obsolete. At this time (2015-10) the new UI is not really feature complete. With the Spring '16 Release it's likely that many features required by typical customers might be there. However in my opinion it won't be possible to migrate all Orgs in 2016-02 on the Lightning Experience UI.
Unfortunately most (or all) of the limitations of the Aloha UI we found reasonable for considering those workarounds are still present.
So the decision to shut down the workarounds at this time can create some extra effort only for an intermediate time until most Orgs can migrate completely to Lightning Experience. It would have been nice, if Salesforce could allow us a little bit more "grace time" for those Orgs, e.g. in form of an critical update or in form of switching that "security improvement" off for one or two releases...
MODIFICATION UPDATE (Winter'16)
Here you can find a way which worked until Spring'16: Requirescript change in Winter '16 release
ORIGINAL POST (Summer'14 to Summer'15 )
At least up to Summer'15 there is a solution without HTML-Areas.
What does NOT work anymore:
New HTML-Areas are useless in Summer'14! Careful with existing HTML-Areas: you save it, you loose it in Summer'14. They get crippled!
It does not work in Winter'16 anymore! It had worked in Summer'14, Winter'15, Spring'15 and Summer'15. For Winter'16 you need this instead and with Spring'16 it looks like an end...
- create a StaticResouce "YourStaticResourceName" upload a JS file containing whatever you need (e.g. jquery) and add a command in the end, like console.log('bingo!');
- go to Setup > Home > Custom Links
- create a new link call it "injection"
- Behaviour = "Execute JavaScript"
- Content Source = "Onclick JavaScript" (don't get irritated, you won't have to click!)
- at the body enter {!REQUIRESCRIPT("/resource/1402932484000/YourStaticResourceName")}
- go to Setup > Home > Home Page Components
- create a new one
- call it "injection-box"
- pick type "Links" (instead of HTML-Area we used before)
- click next
- pick "injection" we created above
- save it
- got to Setup > Home > Home Page Layouts
- add "injection-box" to your layout
- go to anywhere it worked before and check for 'bingo!' in your console. See that 'YourStaticResourceName' is successfully injected to the standard pages :-)
Read the rest at the sourceFrom Salesforce Stack Exchange: asked by Rao, answered by Uwe Heim (CC BY-SA 3.0)
Any reason to skip DML on empty lists?
Good question, I've never considered it before...
i've just assumed the platform will play fair and I'm pleased to find it does!
System.debug('Before DmlStatements : ' + Limits.getLimitDmlStatements()); System.debug('Before DmlRows : ' + Limits.getDmlRows()); insert new List<Account>(); System.debug('After DmlStatements : ' + Limits.getLimitDmlStatements()); System.debug('After DmlRows : ' + Limits.getDmlRows());Results in a successful completion and confirmation of no governor usage.
09:00:14.185 (5185191000)|USER_DEBUG|[1]|DEBUG|Before DmlStatements : 150
09:00:14.185 (5185303000)|USER_DEBUG|[2]|DEBUG|Before DmlRows : 0
09:00:14.185 (5185553000)|SYSTEM_CONSTRUCTOR_ENTRY|[3]|()
09:00:14.185 (5185606000)|SYSTEM_CONSTRUCTOR_EXIT|[3]|()
09:00:14.185 (5185933000)|USER_DEBUG|[4]|DEBUG|After DmlStatements : 150
09:00:14.186 (5186055000)|USER_DEBUG|[5]|DEBUG|After DmlRows : 0
From Salesforce Stack Exchange: asked by Robert Sösemann, answered by Andrew Fawcett (CC BY-SA 4.0)
Force.com IDE - Still Officially Supported?
As the original author of the IDE, I can understand why you would be unclear on the future of the IDE. Rather than say it has been deprecated I would say that it has been put in maintenance only mode, but IS supported. That is to say, that with each release of the platform, the next being Winter '14, the IDE will be updated so that the API endpoint of the SOAP API used by the IDE is current.
The IDE uses a combination of SOAP and Metadata APIs and to gain access to the most recently exposed metadata, this endpoint update, and re-compiling needs to occur. But, that is the extent of support that we are committing to with the current IDE code base.
The long term strategy is as described above. We have moved resource from adding new features to the IDE to developing an API who sole purpose is to support tooling. You can see the progress of the tooling API in the Developer Console, which is the first place that this API is being put to work. Once the tooling API has reached a level of functionality, we will revisit an Eclipse plugin.
tl;dr The IDE was built by salesforce Developer Evangelism for the reasons that you excellently point out above. It was built before we released a Metadata API even, mostly to gain the usefulness of an IDE, but the main reason was so that the developer had access to the built in source code control, something that is terribly important for real development and governance.
Due to the popularity and adoption by the developer community, the project was "forced" upon the R&D side of the house so that it could be properly supported and maintained. The code behind the IDE has evolved organically and over a lengthy enough period of time that the entire underlying implementation has rightly been called into question. Newer APIs exist that can/will be used in conjunction with the tooling API to deliver a better performing, less chatty IDE. Included in this is something akin to a grammer for proper code assist and refactoring, replacing the current polling mechanism with a streaming API mechanism and a better Visualforce editor.
The Force.com service is unique, so while we can borrow a lot of techniques and approaches, some aspects of this just have needed to be invented. Hopefully this demonstrates our commitment to the IDE and other tools like Mavens Mate and BrainEngine
EDIT: On September 17, 2013 the DeveloperForce blogs came out with the following article. Cliff notes:
- We will be updating the plugin to work with the latest versions of Eclipse and Java shortly after the Winter ’14 release.
- We have been finishing up the Tooling API to prepare for the more complete refactoring which is now in flight.
After the refactor:
- Dynamic Metadata API: No more need to upgrade the plugin every release to get the latest metadata API. Latest and greatest available at all times.
- oAuth: No more need to reset a security token and update projects with new credentials. oAuth authentication will keep your plugin authenticated to an instance until you tell it you don’t want to be authenticated anymore. Especially useful for those of you with admins requiring monthly password resets.
- Code Completion: The Tooling API provides symbol tables for an org, which will be used to offer code completion. Developer Console offers this today; rebuilding with the Tooling API will allow the plugin to offer it too.
- Better Save Process: The Tooling API provides a mechanism for saving code artifacts more directly than the metadata API, providing a much less unwieldy experience.
- Plugin-only: The current approach of offering a bundled exe to install both Eclipse and the Force.com IDE plugin. We’ll be all plugin, all the time.
Read the rest at the sourceFrom Salesforce Stack Exchange: asked by Jesse Altman, answered by Dave Carroll (CC BY-SA 3.0)
How to reduce a large internal view state / what is in the internal view state?
I needed to reproduce this in a smaller more focused example to prove my hunch. Then further down you'll see how I've approached a solution that hopefully doesnt impact your desire to structure the data as you currently have it. Yet does more work in the viewstate in order to simplify the VF markup.
Research. It looks like it is the use of nested apex:repeat and apex:outputPanel's, they internally appear to use quite a lot of state. In the reproduction below, I found around half of my view state allocated to internal. And I didn't even take my example further by using apex:outputField (which I also suspect to be quite heavy). So with this in mind first, my reproduction controller and page are shown below. Followed by one possible way I considered to reduce the VF components on the page a little more but get the same output.
public with sharing class ViewStateTestController { public List<Row> rows {get;set;} private static final Integer scaler = 5; public class Row { public Boolean isGrouping {get;set;} public Boolean selected {get;set;} public String name {get;set;} public String data1 {get;set;} public String data2 {get;set;} public String data3 {get;set;} public List<Row> children {get;set;} } public ViewStateTestController() { rows = new List<Row>(); for(Integer group1Idx=0; group1Idx<scaler; group1Idx++) { // Add group for level 2 data Row group1Row = new Row(); group1Row.isGrouping = true; group1Row.Name = 'Level 1 Group'; group1Row.children = new List<Row>(); rows.add(group1Row); for(Integer group2Idx=0; group2Idx<scaler; group2Idx++) { // Add some level 2 data for(Integer group2DataIdx=0; group2DataIdx<group2Idx+1; group2DataIdx++) { Row group2DataRow = new Row(); group2DataRow.isGrouping = false; group2DataRow.Name = 'Level 2 Data'; group2DataRow.data1 = 'Some Level 2 Data 1'; group2DataRow.data2 = 'Some Level 2 Data 2'; group2DataRow.data3 = 'Some Level 2 Data 3'; group1Row.children.add(group2DataRow); } // Add group for level 3 data Row group2Row = new Row(); group2Row.isGrouping = true; group2Row.Name = 'Level 2 Group'; group2Row.children = new List<Row>(); group1Row.children.add(group2Row); for(Integer group3Idx=0; group3Idx<scaler; group3Idx++) { // Add some level 3 data for(Integer group3DataIdx=0; group3DataIdx<group3Idx+1; group3DataIdx++) { Row group3DataRow = new Row(); group3DataRow.isGrouping = false; group3DataRow.Name = 'Level 3 Data'; group3DataRow.data1 = 'Some Level 3 Data 1'; group3DataRow.data2 = 'Some Level 3 Data 2'; group3DataRow.data3 = 'Some Level 3 Data 3'; group2Row.children.add(group3DataRow); } } } } } }And the VF page...
Read the rest at the sourceFrom Salesforce Stack Exchange: asked by Ralph Callaway, answered by Andrew Fawcett (CC BY-SA 3.0)
Is it possible to run a SOQL Query and get a Map returned?
I know only one:
Map<ID, Contact> m = new Map<ID, Contact>([SELECT Id, LastName FROM Contact]);Here is the doc: Maps of sObjects
From Salesforce Stack Exchange: asked by dublintech, answered by Sergej Utko (CC BY-SA 3.0)
How can I efficiently generate a Set<Id> from a List<SObject> structure?
This trick only works on the Id field, but you can use the Map constructor that accepts an SObject list to do this without consuming a script statement for each element in the List.
For example:
List<SObject> results = Database.query(someSOQL); Set<Id> resultIds = (new Map<Id,SObject>(results)).keySet();What this second line does is create a new
Map<Id,SObject>from the results list using a special constructor, and then take the map's set of keys via the keySet() method. Then the map falls out of scope and it's heap space is released, leaving you with a very governor-efficient set.From Salesforce Stack Exchange: asked by ca_peterson, answered by ca_peterson (CC BY-SA 4.0)
Can we determine if the Salesforce instance is production org or a Sandbox org?
Update: There is a new method that doesn't use a query. Check out this answer
In Summer '14, (version 31.0), there is a new field available on the Organization object.
SELECT IsSandbox FROM Organization LIMIT 1From the release notes under New and Change Objects:
The Organization object has the following new read-only fields.
- InstanceName
- IsSandbox
You can, for example, create a lazy loader that other classes can use like this:
public Boolean runningInASandbox { get { if (runningInASandbox == null) { runningInASandbox = [SELECT IsSandbox FROM Organization LIMIT 1].IsSandbox; } return runningInASandbox; } set; }You can then call that as a Boolean value:
if (!runningInASandbox()) { Messaging.SingleEmailMessage msg = new Messaging.SingleEmailMessage(); msg.setSubject('An email'); msg.setToAddresses(new List<String>{siteAdmin.Email}); msg.setPlainTextBody('A message'); Messaging.sendEmail(new List<Messaging.SingleEmailMessage>{msg}); }From Salesforce Stack Exchange: asked by Anup, answered by Daniel Hoechst (CC BY-SA 4.0)
Difference between the multiple messaging options in Visualforce?
Let me start off by explaining each of these in more detail.
apex:pageMessage is used to display a single custom message using the Salesforce formatting. You can specify the severity (which will control the display of the message box) and the strength (which will control the size of the box). Take the following code for example:
<apex:page > <apex:pageMessage summary="This is a pageMessage" severity="info" strength="3"/> </apex:page>Renders as:
Now let's tweak that code slightly:
<apex:page > <apex:pageMessage summary="This is a pageMessage" severity="error" strength="1"/> </apex:page>Notice how I changed the severity and the strength. This controls the size and the display of the message. This renders as:
This can be used to display any custom message that you always want to appear on the screen. There may be a case that whenever a user is on a form you may want a warning to appear to display important information to them.
apex:pageMessages is used to display all of the messages on a page. It will display Salesforce generated messages as well as custom messages added to the ApexPages class. Let's take a look at it in use:<apex:page controller="TestMessageController"> <apex:pageMessages /> </apex:page> public class TestMessageController{ public TestMessageController(){ ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'This is apex:pageMessages')); } }This renders as:
Let's add some more messages and see how it reacts:
<apex:page controller="TestMessageController"> <apex:pageMessages /> </apex:page> public class TestMessageController{ public TestMessageController(){ ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'This is apex:pageMessages')); ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'This is apex:pageMessages still')); ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'This is apex:pageMessages info')); ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'This is apex:pageMessages warning')); } }This renders as:
Notice how that single instance of the apex:pageMessages handles all of the errors on the page. The use case for this object is to capture all errors on the page. It should be used on most custom Visualforce page as a catch all to let users know what errors occur (if no other messaging is used).
apex:message is used to display an error on only a very specific field. It is used to allow the developer to place field specific errors in a specific location. Take the following code for example:<apex:page controller="TestMessageController"> <apex:form > <apex:outputLabel value="Test String" /><apex:inputText value="{!test.Name}" id="test"/> <br/><apex:message for="test"/> </apex:form></apex:page>
public class TestMessageController{ public Account test{get;set;} public TestMessageController(){ } }renders as:
Notice how this currently doesn't have a message displayed. Also notice how this particular element is specified specifically for one field. The error will only occur on that one field. Let's change the code a bit and take a look at this with an error on the Name field:
<apex:page controller="TestMessageController"> <apex:form > <apex:outputLabel value="Test String" /><apex:inputField value="{!test.Name}" id="test"/> <br/><apex:message for="test"/> </apex:form> </apex:page> public class TestMessageController{ public Account test{get;set;} public TestMessageController(){ test = new Account(); test.Id.addError('Correct'); test.Name.addError('Wrong'); } }This renders as:
Notice how only the Name error is shown because that is the only field that has an apex:message associated to it. Also notice that although this does have some styling, the styling is minimalistic and Salesforce expects the developer to handle the styling as necessary in this situation.
Read the rest at the sourceFrom Salesforce Stack Exchange: asked by Jesse Altman, answered by Jesse Altman (CC BY-SA 4.0)
How do I start to debug my own Apex code?
Here is how I debug my issues. In most cases I would only make it to step 2 before I solve my problem.
Step 1: Explain it to your Rubber Duck
I try explain what my code is doing to my rubber duck. A lot of the time I figure out the problem when I'm explaining the code to someone else. (If exceptions are involved, take a look at your code at the line numbers reported and consider what could have generated the exception.)
Step 2: System Debugs
Debug log recording in Setup is turned on for your User via:
Setup > Monitoring > Debug logs. See here for more information.I would place temporary debug statements such as
System.Debug('>>>> the value of x is ' + x);within my code to make sure that the code is executing the way I think its working. Individual SObjects, Maps of SObjects and Lists of SObjects can all be appended and that shows you all populated SObject fields.The
>>>>is a unique string that usually doesn't appear anywhere else in the log files. This allows me to quickly find my debug output. (Logs are truncated after 2M bytes of output - there are work-arounds for this.)Step 3: Use the Developer Console
The Developer Console is a great tool for debugging. You do the following things (and more) with the developer console
- View Logs. This is another way of viewing debug output.
- Execute SOQL. This can be used to verify that the SOQL in your code is returning the correct information
- Execute Anonymous. Apex code can be run directly from the dev console
- Checkpoints can be added in the code (maximum of 5 per class), which will allow you to stop the code executing and to see variable information.
See Josh Kaplans YouTube video for more info on the dev console
Step 4: Create a Unit Test
A unit test is a great way to figure out what is going on with a piece of code. It allows you to:
- Execute your code in an environment with no other data
- Create test data that you can use over and over again.
- Use asserts to check your code e.g.
System.assert(contacts.size() > 0);orSystem.assertEquals(expectedX, actualX);
Step 5: Take a break
I find myself getting frustrated when I have been looking at the same problem for a long period of time. This does not help solve the problem, it can actually make it harder to clearly see what is going on in the code. Take a break for a while and you may find that when you look at the problem again it makes more sense.
Step 6: Ask for help
If you have done all the steps above and reached this point then you most likely need help. This is where a colleague or stack exchange come in. Make sure when asking a question that you clearly state your problem, provide enough information to make it understandable to others and if you are providing a code sample make sure that it is formatted and easy to read.
From Salesforce Stack Exchange: asked by Keith C, answered by BarCotter (CC BY-SA 3.0)
Apex static code analysis
UPDATE: On Pluralsight Robert from PMD and Lorenzo from Clayton.io just released a FREE (no-signup) in-depth course on Automated Code Analysis in Salesforce.
I recently ported the famous Java Static code analyzer PMD to Apex. We also ported many of the original Java rules and created a few Apex specific to showcase how to write language-specific rules (e.g. AvoidSoqlInLoops, AvoidLogicInTriggers,...).
Other than CodeScan, our effort is open source and was merged back into the original PMD repository on Github (https://github.com/pmd/pmd). Every Salesforce developer or expert out there can fork the repo and create new and better rules and integrations.
As the Apex language module is now part of the regular PMD distribution all PMD-based tools also speak Apex now, e.g. the Eclipse / Force.com IDE.
We have also built an open-source engine for CodeClimate so you cannot only analyze files on your local machine but also have code checked into your Github repos verified.
Just recently another Github-integrated services called Codacy.com added full support for PMD and Apex.
From Salesforce Stack Exchange: asked by Bob Roberts, answered by Robert Sösemann (CC BY-SA 4.0)
SFDC: Understanding With Sharing, Without Sharing & Unspecified Sharing Classes
Part 1
Correct. You cannot "automatically" enforce field level security or profile permissions with "with sharing," as this would make code much more difficult to debug because of failures. This is noted in Using the with sharing or without sharing Keywords, under the second note.
Correct. This means that if do not specify "with sharing" or "without sharing" for the inner class, it behaves according to the calling class mode, or "without sharing" if called directly, except as noted in the first section of the link provided above.
Partially correct. If you run a class that has no sharing in Execute Anonymous, or in Chatter, it is treated as "with sharing." In all other cases, it is treated as "without sharing." For most cases, this is not significant, but you should be aware of this feature.
Correct. Extensions are basically a rewrite of the original class plus additional code, so they behave like the original class, including its sharing mode.
Correct. Calling a function in a class will use the sharing mode of that class, unless it is undefined, in which case the mode stays the same.
Part 2
Correct, as per 4 above.
Correct, as per 5 above.
Correct, as per 5 above.
Correct, as per 4 above.
Incorrect, as per 3 above. Because A has "with sharing", C will have "with sharing" when called from A.
Partially correct, or incorrect, depending on the exact definition of A. If A is "public with sharing class A extends C", then it is "with sharing," or if it is "public class A extends C", then it falls under item 3 from part 1 (that is, "without sharing unless executed from executeAnonymous").
With Sharing
This is when you're trying to perform an update as the user. If user X cannot edit record Y, then an error will occur. If user X cannot see record Y, they cannot query that record. Use this mode when for pages that should respect sharing settings, or any other time you might want to enforce the rules.
For example, a page that edits opportunities should probably enforce sharing to make sure that users can't modify other users' sales data without the appropriate sharing in place. For Visualforce pages, this is true approximately 99% of the time. Some Visualforce pages might be able to circumvent sharing, for example, to show data that the user wouldn't normally. A page that can tell users that a possible duplicate lead exists (without exposing who works the lead, or specific details) would not want to use "with sharing" in a private data model.
Without Sharing
This is when you're trying to perform an update that should not fail ordinarily. For example, a logging system is designed to write certain non-fatal messages to a logging object. The user doesn't have any right to edit the logging files normally (OWD is private, and the logging records are owned by a system administrator), but the logging files need to be queried and updated accordingly (to save space, etc). Using "with sharing" would make this code impossible, but by placing that code in a "without sharing" class, the code can make logs on behalf of the user even though that user has no access to the object normally. As another example, users can't see others leads, but the system needs to flag potential duplicates and notify someone that there is a duplicate. "Without sharing" makes this code possible.
From Salesforce Stack Exchange: asked by Swati, answered by sfdcfox (CC BY-SA 4.0)
How to study/prepare for the Salesforce ADVANCED Developer Certification?
I decided to take this exam (Multiple Choice) after i completed one year of development on force.com platform.
Majority of the questions test your apex and Visualforce skills and make sure you are familiar and have some practical hands on before you decide to go for this exam.
I found multiple blogs helping me to clear this exam with lot of ease .I just blogged in my blog too on some tips that i found helpful
http://cloudyworlds.blogspot.in/2012/09/advanced-developer-first-round.html http://cloudyworlds.blogspot.in/2013/07/tips-on-passing-advanced-developer.html
Pay attention to
1)Email services(Inbound Email Handler Class and Test Class)
2)Webservices(SOAP and REST)
3)Deployment strategies
4)Various org editions provided by salesforce and there data limtations
5)Some Visualforce tags like apex:component,apex:include,apex:composition,tags related to Visualforce email template,ajax related tags (Action function,action support,action Region,etc)
6)Test classes and best practices while writing test code
7)Visualforce controllers (standard ,custom and extensions and how they differ)
8)Static Resources and there usage
9)PDF generation in force.com
Hope this helps you.As others have pointed go through the materials on Partner portal they are really helpful.All the best!
From Salesforce Stack Exchange: asked by Shumon Saha, answered by Mohith Shrivastava (CC BY-SA 3.0)
Salesforce, Oracle and the Seven Dwarfs
This seems timely as Grumpy just popped out of the developer console at me.
As per @sfdcfox's comment and answer to the linked question.
The Seven Dwarfs live in the platform code. You should never see DOPEY, SLEEPY, DOC, GRUMPY, SNEEZY, BASHFUL, or HAPPY, but occasionally they break out and appear to a user. If you spot one of them, you need to contact support so they can be put back in their dwarfy walled garden.
There are references to them back in 2009. See Salesforce, Snow White and the Seven Dwarfs and The Silver Lining - Meaningful Error Messages #94.
I suspect anyone who can tell you exactly where they are in relation to the database has probably signed a non-disclosure agreement. That doesn't mean we can't make some wild conjectures.
The presence of Oracle error codes like ORA-00001 and ORA-20191 plus the java.sql.SQLException would indicate they are some sort of layer immediately above the database running Java.
Its also interesting that they tend to bypass the GACK. Either they aren't being caught by the GACK mechanism or they are being rethrown. The latter seems unlikely. Why surface these errors rather than the generic GACK message. So the dwarfs live outside the standard application GACK error handling.
Why are there only 7? I'd assume it has something to do with the way Salesforce scales. Each instance/pod, e.g. na7, may have exactly 7 dwarfs. There are never any more or less and they would stand up a new pod rather than scale out the dwarfs. If you've got seven fixed servers I guess you are either naming them after dwarfs or deadly sins. Getting errors from Happy are probably better than errors from Lust or Gluttony.
Here's slide 8 from a Salesforce.com -architecture talk that I've defaced with where I think the dwarfs roughly reside in relation to the servers that makeup a pod and it's database cluster.
Here's another diagram from The Force.com Multitenant Architecture pdf.
The Query Servers might be in about the right place and performing the expected dwarf functions.
In Performance Monitoring and Testing in the Salesforce Cloud the Pod is shown as "30 plus servers" being used for Application,API, and Search servers over a "8 Node RAC cluster". I've never done infrastructure at that scale, but I suspect there is something working between all those servers and the database cluster.
See also: * Quora: What does Salesforce's infrastructure look like?
From Salesforce Stack Exchange: asked by Mark Pond, answered by Daniel Ballinger (CC BY-SA 3.0)
Pokemon Catch - Generic Exception Handling In Apex
Pros
One of the primary advantages of the Pokemon Catch is that you reduce the complexity of code in many cases. For example, if you're concerned about a NullPointerException, a CalloutException, a QueryException, and a DmlException, you have two choices:
try { ... } catch(NullPointerException npe) { ... } catch(CalloutException ce) { ... } catch(QueryException qe) { ... } catch(DmlException de) { ... }... or ...
try { ... } catch(Exception e) { ... }Which is easier to write? Which is easier to get 100% code coverage on? Code coverage alone may be one benefit of catching Exception directly, if you have many scenarios where you have to handle a bunch of Exception types.
However, both of those patterns are actually types of code smell. The former suggests that the developer couldn't perform many of the usual checks (e.g. a NullPointerException should never occur, because you should be able to simply say
if(something != null) ...), while the latter suggests that they have no idea what the API is doing, and so are going to just catch everything and hope for the best.Cons
The Pokemon Catch usually results in bugs, particularly regression bugs, from going unnoticed until some time after they're in production, usually right around the time users start asking "wait, why is the system behaving this way?" The more times you use Exception this way, the more risk you're inherently taking. It's preferable to have a hard crash with a stack trace than a silently debugged error that may go unnoticed for months.
The Exception
Of course, there are times when you do explicitly want to catch Exception directly. For example, a well-designed Exception-handling framework might wrap each of your methods in a consistent manner that allows solid error reporting, roll-back of partial operations, and so on. For code that advanced, I'd say it's perfectly acceptable. For the other 99.999% of code out there, it should not be used.
The Unfortunate
Unfortunately, every single line of code in the documentation either uses no error handling, or shows only the use of Exception. This is just plain wrong. While it does make it easy for novice programmers to understand what's going on, it'd be far more preferable if they used the correct data types and not abstract so much.
The Documentation
One thing that's notably absent from Apex that was a feature of early Java is the
throwskeyword. This keyword would force developers calling this method to catch the exception. While I'm glad we don't have that in Apex Code, because some odd 90% of the API probably throws NullPointerException, it was a nicety in terms of self-documenting code.The documentation itself doesn't tell you which methods can throw exceptions, or which types, which means that we end up with most developers going through NPE paranoia phases; we start using try-catch around every method, because we never know what's going to happen, or (like me), we experiment with null parameters to figure out which methods will break when called with null values.
One thing I'd love to do is to introduce a list of all known methods that throw exceptions, but it would take a lot of work and a lot of maintenance, which I don't have time for. I think it'd be a pretty cool thing to have on hand, though. Even better, I'd love it if salesforce.com would do this for us. Just put a little icon in the manual next to each method that throws NPE (or some other type).
The Takeaway
Avoid catching Exception at all. Ever. It's "never" the correct solution. However, sometimes we just don't have the time to write up all the proper code coverage, or sometimes the code coverage is "impossible" to achieve if we follow best practices. In general, if you can avoid using it, do so, and if it's unavoidable, I'd recommend documenting why it's unavoidable so you have something to reference later.
From Salesforce Stack Exchange: asked by Adrian Larson, answered by sfdcfox (CC BY-SA 3.0)
Has anyone, ever, successfully invoked the Metadata API from within Apex?
it's definitely possible to use CRUD based Metadata API calls in APEX. salesforce to salesforce and even loopback inside the same instance, we tried both. Adam already mentioned that a major part of the functionality is based on zipped metadata packages which cannot be created or unzipped using apex. however you can still create custom fields or objects using the create call which can be pretty useful. The ugly part of this is WSDL2APEX as it does not support schema type extensions but the Metadata WSDL has a super type Metadata that all components inherit from. We tried to modifiy the metadata WSDL and code WSDL2APEX produced but we ended up sending our own SOAP messages. Here's some simple code I just tested that illustrates how APEX can be leveraged to create a new custom object, just paste it into the developer console to test it:
HTTP h = new HTTP(); HTTPRequest req = new HTTPRequest(); req.setMethod('POST'); req.setHeader('Content-Type', 'text/xml'); req.setHeader('SOAPAction', 'create'); String b = '<?xml version="1.0" encoding="UTF-8"?>'; b += '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'; b += '<soapenv:Header>'; b += '<ns1:SessionHeader soapenv:mustUnderstand="0" xmlns:ns1="http://soap.sforce.com/2006/04/metadata">'; b += '<ns1:sessionId>' + UserInfo.getSessionId() + '</ns1:sessionId>'; b += '</ns1:SessionHeader>'; b += '</soapenv:Header>'; b += '<soapenv:Body>'; b += '<create xmlns="http://soap.sforce.com/2006/04/metadata">'; b += '<metadata xsi:type="ns2:CustomObject" xmlns:ns2="http://soap.sforce.com/2006/04/metadata">'; b += '<fullName>sample__c</fullName>'; b += '<deploymentStatus>Deployed</deploymentStatus>'; b += '<description>created by the Metadata API</description>'; b += '<enableActivities>true</enableActivities>'; b += '<label>sample Object</label>'; b += '<nameField>'; b += '<displayFormat>AN-{0000}</displayFormat>'; b += '<label>sample__c Name</label>'; b += '<type>AutoNumber</type>'; b += '</nameField>'; b += '<pluralLabel>sample Objects</pluralLabel>'; b += '<sharingModel>ReadWrite</sharingModel>'; b += '</metadata>'; b += '</create>'; b += '</soapenv:Body>'; b += '</soapenv:Envelope>'; req.setBody(b); req.setCompressed(false); req.setEndpoint('https://na12-api.salesforce.com/services/Soap/m/25.0'); HTTPResponse resp = h.send(req); System.debug(resp.getBody());you probably have to adjust the endpoint to point to your server. Using some Visualforce and a actionPoller component you can develop a nice object builder and even check if the asynchronous object creation was succussful.
From Salesforce Stack Exchange: asked by Adam, answered by h9nry (CC BY-SA 3.0)
How does SF calculate the CPU time?
Josh Kaplan the Apex Product Manager gave quite a detailed blog post on this new governor entitled Script Limits, Begone!. In it he states this...
What does this CPU timeout include? We are only counting things that require application server CPU use. For example, the time spent in the database retrieving records will not count, nor will time spent waiting for a callout to return. There are some things that use the app server CPU that we do not count, which are things beyond your control as a programmer. For example, you don’t control when your code needs compilation, so we don’t count that. We will be counting almost everything else that happens on the app server, including declarative actions. If DML in your code encounters a validation rule with a formula, we will count the time spent evaluating that formula.
The limit is non-deterministic which is why your seeing the variance. This could be considered a concern, given the limit it replaced, while troublesome to us, was at least predictable and scoped by namespace. However as you will see from Josh's excellent post (see section 'But I Have Fear And Doubt!') that Salesforce are all over this, monitoring orgs and reviewing any code both past and present that gets close I'm told. Josh has been present on SE a few times, let see if we can grab his attention to see if he would like to comment further beyond the blog statements.
There is also this statement in the documentation under Understanding Execution Governors and Limits. As well as the usual methods on the Limits class.
CPU time is calculated for all executions on the Salesforce application servers occurring in one Apex transaction—for the executing Apex code, and any processes that are called from this code, such as package code and workflows. CPU time is private for a transaction and is isolated from other transactions. Operations that don’t consume application server CPU time aren’t counted toward CPU time. For example, the portion of execution time spent in the database for DML, SOQL, and SOSL isn’t counted, nor is waiting time for Apex callouts.
From Salesforce Stack Exchange: asked by BarCotter, answered by Andrew Fawcett (CC BY-SA 3.0)
How to study/prepare for the Salesforce Developer Certification?
While the study guide is minimal, it is intended to be. And the topic list is essentially your list of what to learn in order to pass. Don't worry about the big topics, but look at the small ones, rate yourself on a scale of 1-3.
- I know it
- I kind of know it/I need a little bit of review
- I have no clue/I want to build it to see if I understand it
Forget the 1's
Start learning the 2's
Work your way into the 3's
I would say that this advice could be followed for any of the certification exams.
As for the developer certification specifically, the Force.com Fundamentals is good. The Force.com workbook. And don't overlook the online help and training. When the exams are reviewed, the first point of reference for any question that needs to be modified/clarified is the help and training.
A few weeks before your exam, go through the current release training. Every question for every exam is reviewed every single release. If you began your prep in Winter 13, but your exam will be on Spring 13, you might be relying on old information.
Finally, I always caution people about practice exams. Because of the always changing nature of the platform (and by extension the certification exams), that person who wrote those practice questions a year ago, may have been spot-on correct then, but a year later they may be out of date. Unless the questions you are using list the release they were written for, don't rely on a successful practice exam to tell you you will pass our certification.
I teach our Developer curriculum (including DEV401). That's my job at SFDC right now. Those people who go on and get their Developer Certification after DEV401 invariably tell me that it was a huge benefit to take the course. Everyone who teaches it themselves has to be Developer certified, as well as go through our rigorous instructor certification process. So if that is an option for you. Yes. Take DEV401. You will not regret it.
From Salesforce Stack Exchange: asked by Richard N, answered by pchittum (CC BY-SA 3.0)
What is the difference between Custom Settings and Custom Metadata Types?
I’m the original inventor of and lead developer for custom metadata types.
Although we have a variety of use cases in mind, custom metadata types are primarily intended to let you develop peers of Salesforce standard metadata types, such as custom fields, tabs, or workflow rules (obviously in this first release we don’t have the power required to duplicate all the functionality in these types).
Just as you can’t perform CUD on such types in Apex today (you can’t create a new tab, modify a custom field, or delete a workflow rule in Apex), you can’t yet perform CUD on custom metadata types in Apex, short of a metadata API callout. You can help us get that feature prioritized by voting for the idea here. To see how to create tooling using Apex for a custom metadata type, you can look at Jean-Baptiste Pringuey’s sample “configurator.”
Testing is a tricky question, which I address in a blog post I just posted. The use case you describe is definitely a legitimate one. There's been a fair bit of demand for configuration visibility to ftests. See the idea Custom Settings should be treated as a Setup Object for APEX Tests
There’s a lot more planned for custom metadata types than custom settings on steroids. App configurations that don’t have to be re-created in every environment and that can respect managed state (so you can have some that are not deletable or mutable by subscribers) was just a starting place that filled a known need. Aaron’s second blog post gives you a taste of things to come in the near term (safe harbor applies, of course).
Winter `16 features
Layoutable UI for entering and updating records is one of the big features that came out in Winter -- take a look at Custom metadata types: they’re money; actually, even better!
Record-level protection of configuration (as opposed to hiding the entire type, which is both a custom settings and a Summer CMT feature) is another.
The third big feature is field-level control over who can edit values. By setting a field to subscriber editable, you'll be able to default the value in a package and let customers change that value if they need to.
More recent features
It's been a while!
Custom Metadata types now support (as of Summer 17):
- Picklist fields
- Relationships to records of other custom metadata types, to SObject types (EntityDefinition), and to SObject fields (FieldDefinition)
- Text Area (Long) fields
- Asynchronous (but not requiring remote site settings) upsert in Apex via Metadata.MetadataOperations.enqueueDeployment()
- Validation formulas (including traversal of relationships)
From Salesforce Stack Exchange: asked by Daniel Ballinger, answered by Avrom Roy-Faderman (CC BY-SA 3.0)
Related topics
Where these questions come from
Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.
- Salesforce Stack Exchangeby its contributors, named on each answerCC BY-SA20 questions