301. What is the use of static variable?
When you declare a method or variable as
static, it’s initialized only once when a class is loaded. Static variables
aren’t trmitted as part of the view state for a Visualforce page.
Static variables are only static within the scope of the request. They are not static across the server, or across the entire organization.
Static variables are only static within the scope of the request. They are not static across the server, or across the entire organization.
302. Explain Final variables?
• The final keyword can only used with
variables.
• Classes and methods are final by default.
• Final variables can only be assigned a value once.
• When defining constants, both static and final keywords should be used.
• Classes and methods are final by default.
• Final variables can only be assigned a value once.
• When defining constants, both static and final keywords should be used.
Example: public static final Integer =47;
303. Difference between with sharing and without
sharing in salesforce
By default, all Apex executes under the System
user, ignoring all CRUD, field-level, and row-level security (that is always
executes using the full permissions of the current user).
without sharing:
Enforcing the User’s Permissions, Sharing rules and field-level security should apply to the current user.
For example:
public with sharing class sharingClass {
// Code here
}
Enforcing the User’s Permissions, Sharing rules and field-level security should apply to the current user.
For example:
public with sharing class sharingClass {
// Code here
}
without sharing:
Not enforced the User’s Permissions, Sharing rules and field-level security.
For example:
public without sharing class noSharing {
// Code here
}
Not enforced the User’s Permissions, Sharing rules and field-level security.
For example:
public without sharing class noSharing {
// Code here
}
Enforcing the current user’s sharing rules can
impact: (with sharing)
SOQL and SOSL queries – A query may return fewer rows than it would operating in system context.
DML operations – An operation may fail because the current user doesn’t have the correct permissions. For example, if the user specifies a foreign key value that exists in the organization, but which the current user does not have access to.
SOQL and SOSL queries – A query may return fewer rows than it would operating in system context.
DML operations – An operation may fail because the current user doesn’t have the correct permissions. For example, if the user specifies a foreign key value that exists in the organization, but which the current user does not have access to.
304. Explain Class Constructors with example?
• A constructor is a special method used to create (or
instantiate) an object out of a class definition.
• Constructors never have explicit return types.
• Constructors have the same name as the class.
• Classes have default, no-argument, public constructor if no explicit constructors is defined.
• If you create a constructor that takes arguments and still want a no-argument constructor, you must explicitly define one.
• Constructors can be overloaded, meaning you can have multiple constructors with different parameters, unique argument lists, or signatures.
• Constructors are called before all other methods in the class.
• Constructors never have explicit return types.
• Constructors have the same name as the class.
• Classes have default, no-argument, public constructor if no explicit constructors is defined.
• If you create a constructor that takes arguments and still want a no-argument constructor, you must explicitly define one.
• Constructors can be overloaded, meaning you can have multiple constructors with different parameters, unique argument lists, or signatures.
• Constructors are called before all other methods in the class.
For Example:
public class TestObject2 {
private static final Integer DEFAULT_SIZE = 10;
Integer size;
//Constructor with no arguments
public TestObject2() {
this(DEFAULT_SIZE); // Using this(…) calls the one argument constructor
}
// Constructor with one argument
public TestObject2(Integer ObjectSize) {
size = ObjectSize;
}
}
New objects of this type can be instantiated with the following code:
TestObject2 myObject1 = new TestObject2(42);
TestObject2 myObject2 = new TestObject2();
public class TestObject2 {
private static final Integer DEFAULT_SIZE = 10;
Integer size;
//Constructor with no arguments
public TestObject2() {
this(DEFAULT_SIZE); // Using this(…) calls the one argument constructor
}
// Constructor with one argument
public TestObject2(Integer ObjectSize) {
size = ObjectSize;
}
}
New objects of this type can be instantiated with the following code:
TestObject2 myObject1 = new TestObject2(42);
TestObject2 myObject2 = new TestObject2();
305. Class Access Modifiers
• Classes have different access levels
depending on the keywords used in the class definition.
global: this class is accessible by all Apex
everywhere.
• All methods/variables with the webService keyword must be global.
• All methods/variables dealing with email services must be global.
• All methods/variables/inner classes that are global must be within a global class to be accessible.
• All methods/variables with the webService keyword must be global.
• All methods/variables dealing with email services must be global.
• All methods/variables/inner classes that are global must be within a global class to be accessible.
public: this class is visible across you
application or name space.
private: this class is an inner class and is
only accessible to the outer class, or is a test class.
protected: this me that the method or variable
is visible to any inner classes in the defining Apex class. You can only use
this access modifier for instance methods and member variables.
To use the private, protected, public, or
global access modifiers, use the following syntax:
[(none)|private|protected|public|global] declaration
[(none)|private|protected|public|global] declaration
306. Explain Variable and Method Access Modifiers
in Apex?
• Methods and variables have different levels
depending on the keywords used in the declaration.
– private: This method/variable is accessible within the class it is defined.
– protected: This method/variable is also available to any inner classes or subclasses. It can only be used by instance methods and member variables.
– public: This method/variable can be used by any Apex in this application namespace.
– global: this method/variable is accessible by all Apex everywhere.
• All methods/variable with the webService keyword must be global.
– The default access modifier for methods and variables is private.
– private: This method/variable is accessible within the class it is defined.
– protected: This method/variable is also available to any inner classes or subclasses. It can only be used by instance methods and member variables.
– public: This method/variable can be used by any Apex in this application namespace.
– global: this method/variable is accessible by all Apex everywhere.
• All methods/variable with the webService keyword must be global.
– The default access modifier for methods and variables is private.
307. Explain Casting in Apex?
Apex
enables casting: A data type of one class can be assigned to a data type of
another class, but only if one class is a child of other class.
• Casting converts an object from one data type to another.
• Casting between the generic sObject type and the specific
sObject type is also allowed.
For Example:
sObject s = new Account();
Account a = (Account)s;
Contact c = (Contact)s //this generates a run time error.
• Casting converts an object from one data type to another.
• Casting between the generic sObject type and the specific
sObject type is also allowed.
For Example:
sObject s = new Account();
Account a = (Account)s;
Contact c = (Contact)s //this generates a run time error.
308. Explain Exceptions Statements in Apex?
Similar to Java, Apex uses exception to note
errors and other events that disrupt script execution with the following
Exception statement keywords:
• Throw: signals that an error has occurred and provides an exception object.
• Try: identifies the block of code where the exception can occur.
• Catch: identifies the block of code that can handle a particular exception. There may be multiple catch blocks for each try block.
• Finally: optionally identifies a block of code that is guaranteed to execute after a try block.
• Throw: signals that an error has occurred and provides an exception object.
• Try: identifies the block of code where the exception can occur.
• Catch: identifies the block of code that can handle a particular exception. There may be multiple catch blocks for each try block.
• Finally: optionally identifies a block of code that is guaranteed to execute after a try block.
Exception Example:
public class OtherException extends BaseException {}
Try{
//Add code here
throw new OtherException(‘Something went wrong here…’);
} Catch (OtherException oex) {
//Caught a custom exception type here
} Catch (Exception ex){
//Caught all other exceptions here
}
public class OtherException extends BaseException {}
Try{
//Add code here
throw new OtherException(‘Something went wrong here…’);
} Catch (OtherException oex) {
//Caught a custom exception type here
} Catch (Exception ex){
//Caught all other exceptions here
}
309. Name different Exceptions?
All exceptions support built-in methods for
returning the error message and exception type, below is the some of the
Exception Methods,
AsyncException
CalloutException
DmlException
EmailException
JSONException
ListException
MathException
NoAccessException
NoDataFoundException
NullPointerException
QueryException
AsyncException
CalloutException
DmlException
EmailException
JSONException
ListException
MathException
NoAccessException
NoDataFoundException
NullPointerException
QueryException
310. Explain about Salesforce annotations
Apex annotations modify the way a method or
class is used.
Below is the list of annotations supported by
salesforce
@Deprecated
Use
the deprecated annotation to identify methods, classes, exceptions,
enums, interfaces, or variables that can no longer be referenced in subsequent
releases of the managed package in which they
reside. This is useful when you are re-factoring code in managed packages as
the requirements evolve. New subscribers cannot see the deprecated elements,
while the elements continue to function for existing subscribers
and API integrations.
@Future
Use
the future annotation to identify methods that are executed asynchronously.
When you specify future, the method executes when Salesforce has
available resources.
To
test methods defined with the future annotation, call the class
containing the method in a startTest, stopTest code
block. All asynchronous calls made after the startTest method
are collected by the system. When stopTest is executed, all
asynchronous processes are run synchronously.
@IsTest
Use
the isTest annotation to define classes or individual methods that
only contain code used for testing your application.
The isTest annotation is similar to creating methods declared
as testMethod.
@ReadOnly
The @ReadOnly annotation
allows you to perform unrestricted queries against the Force.com database.
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 within the request: DML
operations, calls to System.schedule, calls to methods annotated
with @future, and sending emails.
@RemoteAction
The RemoteAction annotation
provides support for Apex methods used in Visualforce to be
called via JavaScript. This process is often referred to as JavaScript
remoting.
@TestVisible
Use the TestVisible annotation to allow test methods
to access private or protected members of another class outside the test class.
These members include methods, member variables, and inner classes. This
annotation enables a more permissive access level for running tests only.
Apex REST annotations:
@RestResource(urlMapping='/yourUrl')
The @RestResource annotation
is used at the class level and enables you to expose an Apex class as
a REST resource.
@HttpDelete
The @HttpDelete annotation
is used at the method level and enables you to expose an Apex method
as a REST resource. This method is called when an HTTP DELETE request
is sent, and deletes the specified resource.
@HttpGet
The @HttpGet annotation
is used at the method level and enables you to expose an Apex method
as a REST resource. This method is called when an HTTP GET request is
sent, and returns the specified resource.
@HttpPatch
The @HttpPatch annotation
is used at the method level and enables you to expose an Apex method
as a REST resource. This method is called when an HTTP PATCH request
is sent, and updates the specified resource.
@HttpPost
The @HttpPost annotation
is used at the method level and enables you to expose an Apex method
as a REST resource. This method is called when an HTTP POST request
is sent, and creates a new resource.
@HttpPut
The
@HttpPut annotation is used at the method level and enables you to expose an
Apex method as a REST resource. This method is called when an HTTP PUT request
is sent, and creates or updates the specified resource.
311. Difference between trigger.newMap and
trigger.oldMap?
Trigger.newMap - A map of IDs to the new versions of the sObject
records. Note that this map is only available in before update, after insert,
and after update triggers.
Trigger.oldMap - A map of IDs to the old
versions of the sObject records. Note that this map is only available in update
and delete triggers.
312. What are the available Trigger Events?
There are 6 trigger events available.
1. Insert
2. Update
3. Delete
4. Merge
5. Upsert
6. Undelete
313. What are the available Trigger contest
variables?
Below are the list of Trigger context variables
1. isBefore
2. IsAfter
3. isInsert
4. IsUpdate
5. isDelete
6. isUndelete
7. isExecuting
8. new
9. old
10. newMap
11. oldMap
12. size
314. What is Force.com IDE?
The Force.com IDE is a powerful client
application for creating, modifying, testing and deploying Force.com
applications. Based on the Eclipse platform, it provides a comfortable
environment for programmers familiar with integrated development environments,
allowing you to code, compile, test, and deploy all from within the IDE itself.
315. Explain the Sequence of Salesforce Triggers
and Order of Execution?
The following is the
order of salesforce execution when the you create or update a record,
1) Loads the original record from the database or initializes the record for an upsert statement.
2) Loads the new record field values from the request and overwrites the old values.
If the request came from a standard UI edit page, Salesforce runs system validation to check the record for:
Required values at the layout level and field-definition level
Valid field formats (ex: zip code, country code format)
Maximum field length (ex: mobile number must 10 digits)
Salesforce doesn’t perform system validation in this step when the request comes from other sources, such as an Apex application or a SOAP API call.
3) Run all before triggers.
4) Runs most system validation steps again, such as verifying that all required fields have a non-null value, and runs any user-defined validation rules. The only system validation that Salesforce doesn’t run a second time (when the request comes from a standard UI edit page) is the enforcement of layout-specific rules.
5) Saves the record to the database, but doesn’t commit yet.
6) Run all after triggers.
7) Run assignment rules.
8) Run auto-response rules.
9) Run workflow rules.
10) If there are workflow field updates, updates the record again.
11) If the record was updated with workflow field updates, fires before and after triggers one more time (and only one more time), in addition to standard validations. Custom validation rules are not run again.
12) Run escalation rules.
13) If the record contains a roll-up summary field or is part of a cross-object workflow, performs calculations and updates the roll-up summary field in the parent record. Parent record goes through save procedure.
14) If the parent record is updated, and a grand-parent record contains a roll-up summary field or is part of a cross-object workflow, performs calculations and updates the roll-up summary field in the parent record. Grand-parent record goes through save procedure.
15) Run Criteria Based Sharing evaluation.
16) Commits all DML operations to the database.
17) Run post-commit logic, such as sending email.
1) Loads the original record from the database or initializes the record for an upsert statement.
2) Loads the new record field values from the request and overwrites the old values.
If the request came from a standard UI edit page, Salesforce runs system validation to check the record for:
Required values at the layout level and field-definition level
Valid field formats (ex: zip code, country code format)
Maximum field length (ex: mobile number must 10 digits)
Salesforce doesn’t perform system validation in this step when the request comes from other sources, such as an Apex application or a SOAP API call.
3) Run all before triggers.
4) Runs most system validation steps again, such as verifying that all required fields have a non-null value, and runs any user-defined validation rules. The only system validation that Salesforce doesn’t run a second time (when the request comes from a standard UI edit page) is the enforcement of layout-specific rules.
5) Saves the record to the database, but doesn’t commit yet.
6) Run all after triggers.
7) Run assignment rules.
8) Run auto-response rules.
9) Run workflow rules.
10) If there are workflow field updates, updates the record again.
11) If the record was updated with workflow field updates, fires before and after triggers one more time (and only one more time), in addition to standard validations. Custom validation rules are not run again.
12) Run escalation rules.
13) If the record contains a roll-up summary field or is part of a cross-object workflow, performs calculations and updates the roll-up summary field in the parent record. Parent record goes through save procedure.
14) If the parent record is updated, and a grand-parent record contains a roll-up summary field or is part of a cross-object workflow, performs calculations and updates the roll-up summary field in the parent record. Grand-parent record goes through save procedure.
15) Run Criteria Based Sharing evaluation.
16) Commits all DML operations to the database.
17) Run post-commit logic, such as sending email.
316. What is Visualforce in Salesforce?
Visualforce is the component-based user
interface framework for the Force.com platform. The framework includes a
tag-based markup language, similar to HTML. Each Visualforce tag corresponds to
a coarse or fine-grained user interface component, such as a section of a page,
or a field. Visualforce boasts about 100 built-in components, and a mechanism
whereby developers can create their own components.
• Visualforce pages can react differently to different client browsers such as those on a mobile or touch screen device.
• Everything runs on the server, so no additional client-side callbacks are needed to render a complete view.
• Optional server-side call outs can be made to any Web service.
• Visualforce pages can react differently to different client browsers such as those on a mobile or touch screen device.
• Everything runs on the server, so no additional client-side callbacks are needed to render a complete view.
• Optional server-side call outs can be made to any Web service.
Visualforce is a Web-based framework that
lets you quickly develop sophisticated, custom UIs for Force.com desktop and
mobile apps. Using native Visualforce markup and standard Web development
technologies such as HTML5, CSS, JavaScript, and jQuery, you can rapidly build
rich UIs for any app.
317. Let’s say we have to update the same record
in After Trigger context. Is there any way or workaround?
If we create a new instance of a sObject in
the Apex Trigger in memory using the Id of the newly created record as provided
in the After Trigger context, we can perform an Update DML statement and not
get a read only error. This is because in Apex, the SObject is seen as a new
reference (even though the records have the same SFDC ID) and therefore is
eligible for DML operations. The below snippet of code illustrated this working
and not working.
List<Contact> originals
= new List<Contact>();
if(mirrorResultMap.values().size() > 0)
{
for(Contact origContact :
contactRecs.values())
{
Contact
mirrorContact = mirrorResultMap.get(origContact.Id);
//origContact.Linked_Contact__c
= mirrorContact.Id; //Link the Original Record tot he Mirror Record WILL FAIL
Contact
origContactUpdate = new Contact(Id=origContact.Id, Linked_Contact__c
= mirrorContact.Id); //This will WORK
originals.add(origContactUpdate);
}
//update
contactRecs.values(); //Update the Records -> THIS WILL FAIL AS ITS ORIGINAL
RECORDS IN MEMORY
update originals;
}
318. System.debug() statements are included
against script count?
Any statement ending with semi-colon will be
included against script count.
319. While trying to access javascript code from some CDN like Google, we get error something like “attempt to run uG request”. How to resolve it?
While providing URL, do not specify the
protocol.
Use like this:
<script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js'></script>
320. Explain ActionFunction, ActionSupport and
ActionPoller in Visualforce.
apex:ActionFunction : This component
helps to invoke AJAX request (Call Controllers method) directly from Javascript
method. It must be child of apex:form.
apex:ActionSupport : This component adds
Ajax request to any other Visualforce component.
Example: Commandlink button has inbuilt AJAX
functionality however few components like OutputPanel does not have inbuilt
AJAX capabilities. So with the help of this component, we can enable AJAX.
apex:ActionPoller : This is timer
component which can send AJAX request on pre-defined interval. Minimum interval
is 5 sec and default is 60 sec.
321. In how many ways you can invoke Controllers /
Controller Extensions method from VF?
We can invoke Aprex Controllers or Controller
Extensions using below methods.
·
Javascript Remoting
·
ActionFunction
·
ActionSupport
·
ActionPoller
322. What is the use of apex:detail component ?
With the help of this Visualforce component,
we can directly get complete behavior of page layout defined for logged in
user’s profile. There is no need to add fields, related lists explicitly.
323. What is the difference between
“apex:dataTable” and “apex:pageBlockTable” components in Visualforce?
Both components are used to render data in tabular format.
DataTable
|
PageBlockTable
|
Not required
|
Should be defined inside pageBlock or
pageBlockSection
|
No styles are used
|
Uses standard style sheets
|
Not Required
|
It has the required attribute “value”
|
We need to specify
column headers explicitly
|
Column headers will be displayed
automatically
|
dataTable will render records in simple HTML
table format whereas the
pageBlockTable possess default look and feel
of salesforce standard CSS and must be written inside “apex:pageBlock”
component and a required argument value need to be passed for pageBlockTable.
324. User have all the permissions to see the
Dashboard and Source Folder still when he wants to see dashboard, it’s not
visible. What might be the cause?
It is possible that Salesforce User license
for Dashboard running user is different than User wants to access Dashboard.
Example – Running User license is “Salesforce”
and user trying to access Dashboard is “Salesforce Platform”.
325. How to implement the pagination in SOQL?
In spring 12, Salesforce has come up with
ability of SOQL to get records from position “X” instead of position “1” every
time to help creating pagination feature.
Pagination in SOQL using keyword Offset
Select Id, Name from Lead
LIMIT 5 OFFSET 2
Above query will return 5 Lead records
starting from record number 10 (5×2).
326. How to generate the random string or random
password using Apex?
Integer len = 10;
Blob blobKey = crypto.generateAesKey(128);
String key = EncodingUtil.convertToHex(blobKey);
String pwd = key.substring(0,len);
327. What is dynamic binding in salesforce?
Dynamic Visualforce bindings are a way of
writing generic Visualforce pages that display information about records
without necessarily knowing which fields to show. In other words, fields on the
page are determined at run time, rather than compile time. This allows a
developer to design a single page that renders differently for various
audiences, based on their permissions or preferences. Dynamic bindings are
useful for Visualforce pages included in managed packages since they allow for
the presentation of data specific to each subscriber with very little coding.
Example 1:
Access the Account name from Contact.
Access the Account name from Contact.
{!myContact['Account'][fieldname]}
Consider Data type in Apex
public Map<String,
List<Account>> accountsMap {get; set;}
Visualforce page:
<apex:variable value="A" var="selectedKey" />
<apex:pageBlockTable value="{!accountsMap[selectedKey]}" var="acc">
<apex:column value="{!acc.name}"/>
<apex:column value="{!acc.BillingStreet}"/>
<apex:column value="{!acc.BillingCity}"/>
<apex:column value="{!acc.BillingPostalCode}"/>
</apex:pageBlockTable>
328. How to convert lead using Apex?
Lead myLead = new Lead(LastName
= 'Foo', Company='Foo Bar');
insert myLead;
Database.LeadConvert lc
= new database.LeadConvert();
lc.setLeadId(myLead.id);
LeadStatus convertStatus = [SELECT Id,
MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
lc.setConvertedStatus(convertStatus.MasterLabel);
Database.LeadConvertResult lcr =
Database.convertLead(lc);
System.assert(lcr.isSuccess());
329. Consider total 90k records present in
Salesforce and you have used the count() method of soql. What will be output of
it? (we need to verify this feature in recent versions of the salesforce api’s)
It will throw an error something like “Too
many query rows: 50001”, as the record limit in SOQL is 50,000.
Although the count() returns only one row however it processes each record and thus hit the allowed governor limit.
Although the count() returns only one row however it processes each record and thus hit the allowed governor limit.
330. How to get the Recordtype Id using Dynamic
Apex?
Normally to get the RecordtypeId for any
sObject we use SOQL and it will count against your limit. So below method will
bypass the need of SOQL Query.
Map<String, Schema.SObjectType> m =
Schema.getGlobalDescribe() ;
Schema.SObjectType s =
m.get('API_Name_Of_SObject') ;
Schema.DescribeSObjectResult cfrSchema =
s.getDescribe() ;
Map<String,Schema.RecordTypeInfo>
RecordTypeInfo = cfrSchema.getRecordTypeInfosByName();
Id rtId = RecordTypeInfo.get('Record Type
Name').getRecordTypeId();
331. Write Apex code which will take the RecordID
as input and on the basis of that it will print the Object name and field names
of sObject.
List<Schema.SObjectType> gd =
Schema.getGlobalDescribe().Values();
Map<String,String> objectMap
= new Map<String,String>();
for(Schema.SObjectType f : gd)
{
objectMap.put(f.getDescribe().getKeyPrefix(),
f.getDescribe().getName());
}
String sampleId ='00390000003LIVw';
String prefix = sampleId.substring(0,3);
String objectName = objectMap.get(prefix);
System.debug('** SObject Name ** '+objectName);
System.debug('** SObject Name ** '+objectName);
Map<String, Schema.SObjectField> desResult
= Schema.getGlobalDescribe().get(objectName).getDescribe().Fields.getMap();
List<String> fieldList
= new List<String>();
fieldList.addAll(desResult.keySet());
for(integer i =0;i<fieldList.size();i++)
{
System.debug('** Field
Name ** '+fieldList[i]);
}
332. How to
get “https” link instead of “http” for Visualforce page using URLFOR() in Email
Template
When you create the Link using URLFOR() in
Email Template, it creates link in “http” format instead of “https” and thus
causes end user to logged into salesforce again.
So instead of
<a href='{!URLFOR('/apex/SomePage', null,
[id=Some_Object__c.Id,retURL="/apex/SomeOtherPage"])}'>Go to
SomePage here!</a>
We can use something like :
<a href='{!SUBSTITUTE(URLFOR('/apex/SomePage',
null,
[id=Some_Object__c.Id,retURL="/apex/SomeOtherPage"]),'http:','https:')}'>Go
to SomePage here!</a>
333. When you get the error “Non-selective query
against large object type”? How to resolve it?
Whenever an object has greater than 100K
records any query on that object must be “selective”. For a query to be
selective it must have enough indexed filters (where clauses) so that less than
10% of the records (in our example 10K) are returned before applying the limit
statement.
334. In Controller extension, you are getting the
error “SObject row was retrieved via SOQL without querying the requested field”
while accessing the field of parent Custom Object or standard Object for which
the Controller extension was written. How to resolve that?
In Constructor of the Controller extension,
only Id of Custom Object is supplied. We need to query the required field
explicitly in order to use in remaining part of the code.
335. Using Apex how you can determine that user is
in Sandbox or production?
By using below code, we can identify the given
organization is a sandbox or production.
If the code returns true then it is a sandbox
else it is a production.
public Static Boolean isSandbox(){
String host = URL.getSalesforceBaseUrl().getHost();
String server = host.substring(0,host.indexOf('.'));
//
It's easiest to check for 'my domain' sandboxes first
//
even though that will be rare
if(server.contains('--'))
return true;
//
tapp0 is a unique "non-cs" server so we check it now
if(server == 'tapp0')
return true;
//
If server is 'cs' followed by a number it's a sandbox
if(server.length()>2){
if(server.substring(0,2)=='cs'){
try{
Integer.valueOf(server.substring(2,server.length()));
}
catch(exception e){
//started with cs, but not
followed by a number
return false;
}
//cs followed by a number, that's a hit
return true;
}
}
//
If we made it here it's a production box
return false;
}
336. Consider we have overall 90% code coverage
however there is one class which has 0% code coverage. Can we still able to
deploy that class on production?
Yes. Minimum 1% required for every trigger and
there is no such restriction for Apex class.
338. In Ajax toolkit for custom Javascript button,
you have to explicitly login to API because global Session variable is not
available. In that case it is security vulnerable because anybody logged in can
see the javascript code and your username and password. So is there any way to
avoid this?
We can create a visualforce page with output
type as JavaScript. Global session variable is available in VF page.
Initialize the global javascript variable in
that VF page. include VF page as a javascript file and we are done!
339. In Custom Component How we can return value
to Custom Controller or Controller Extension?
In Apex, Objects are passed by reference. So supply an argument of wrapper class
(object) type to custom component. If its value is changed in Custom component
we will get updated value in controller also.
340. Let’s consider you had created outbound
changeset previously. After that, some class is modified which is part of that
old changeset. If you clone that Changeset, current updated class will be
included or that previous class will be included in changset? (This need to be
verified in recent versions)
Once changeset is created it cannot be
modified. After creation of changset, if we modify any component it will not
reflected and when we clone the changeset, all components (of course old copy
of component) will be added to changeset.
341. In trigger, let’s say we have system.debug()
statement after adderror() method. Will system.debug() be statement executed in
Trigger after adderror() method?
adderror() method is not error statement
rather its normal execution flow and all the statements written after
adderror() will be executed normally.
342. What will happen if you try to update record
in After Trigger Context?
You will get an error saying “record is Read
only”.
343. Can you use aggregate expressions inside
inner query?
Explanation – Can you use Group by clause inside inner query in SOQL?
Explanation – Can you use Group by clause inside inner query in SOQL?
Example: Something like :
SELECT Id, Name,(SELECT Count(Id),Name FROM Contacts Group By Name Havingcount(Id)
> 1 ) FROM Account
No. only root queries support aggregate
expressions. Return type is List<AggregateResult> for above query
However the root result expects List<Account> and there is no syntax or
provision available in Salesforce to specify that child results are of type
“AggregateResult“.
344. What is the best way to check whether
organization has PersonAccount enable or not using Apex?
Method 1:
// Test to see if person accounts are enabled.
public Boolean personAccountsEnabled()
{
try
{
//
Try to use the isPersonAccount field.
sObject
testObject = new Account();
testObject.get( 'isPersonAccount' );
//
If we got here without an exception, return true.
return true;
}
catch( Exception ex )
{
//
An exception was generated trying to access the isPersonAccount field
//
so person accounts aren't enabled; return false.
return false;
}
}
Method 2:
// Check to see if person accounts are
enabled.
public Boolean personAccountsEnabled()
{
// Describe the Account
object to get a map of all fields
// then check to see if
the map contains the field 'isPersonAccount'
return Schema.sObjectType.Account.fields.getMap().containsKey('isPersonAccount' );
}
345. How to get selected records ID from List View
using Javascript / Ajax Toolkit, when custom button is added on List View page?
Create a new Button on Lead of type List
Button. Add the button on Lead List View Layout and write below Javascript
code:
{!RequireScript("/js/functions.js")}
var recordsSelected =
{!GetRecordIds($ObjectType.Lead)}
for(var i=0; i < recordsSelected .length
; i++) {
alert('Selected ID
'+recordsSelected[i]);
}
346. What is the default timeout period while
calling webservice from Apex.
10 sec.
347. A single Apex transaction can make how many
callouts to an HTTP request or an API call?
Maximum 10 callouts
348. How to increase timeout while calling web
service from Apex?
docSample.DocSamplePort stub
= new docSample.DocSamplePort();
stub.timeout_x = 2000; // timeout in
milliseconds
349. How to show loading image while Ajax call in
Visualforce? OR how to show image in <apex:actionStatus> tag in
Visualforce?
<div style="position:absolute;top:20px;left:
50%;">
<apex:actionStatus id="refreshContent" >
<apex:facet name="start" >
<apex:image url="{!$Resource.LoadingImage}" />
</apex:facet>
</apex:actionStatus>
</div>
350. How to add the Document Header in Visualforce
page?
Directly there is no way to add the document
type in visualforce. However in most of the cases IE9 does not work with
Visualforce pleasantly. And then we need to add the Document type in header. So
following workaround will work.
<apex:outputText escape="false"
value="{!'<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0
Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">'}"/>
<html>
<head>
<title>test</title>
</head>
<body>test</body>
</html>
</apex:page>
Answer to 325 is wrong.
ReplyDeleteSelect Id, Name from Lead LIMIT 5 OFFSET 2 will return 5 leads starting from record number 3
Thank you for sharing such useful information. I really enjoyed while reading your article and it is good to know the latest updates. Do post more. And also read about leadingSalesforce Service Cloud Consultant
ReplyDelete