266. What is apex scheduler?
Apex scheduler is used to
invoke Apex classes to run at specific times, first implement
the Schedulable interface for the class, then specify the schedule
using either the Schedule Apex page in the Salesforce user
interface, or the System.schedule method.
The Schedulable interface
contains one method that must be implemented, execute.
The implemented method must
be declared as global or public.
The following example
implements the Schedulable interface for a class
called mergeNumbers:
global void
execute(SchedulableContext SC) {
mergeNumbers M = new
mergeNumbers();
}
}
The following example uses
the System.Schedule method to implement the above class.
String sch = '20 30 8 10 2 ?';
system.schedule('Merge Job',
sch, m);
You can also use
the Schedulable interface with batch Apex classes. The
following example implements the Schedulable interface for a
batch Apex class called batchable:
global void
execute(SchedulableContext sc) {
batchable b = new batchable();
database.executebatch(b);
}
}
Use the SchedulableContext
object to keep track of the scheduled job once it's scheduled. The
SchedulableContext method getTriggerID returns the ID of the CronTrigger object associated with this scheduled job
as a string. Use this method to track the progress of the scheduled job.
To stop execution of a job
that was scheduled, use the System.abortJob method with the ID
returned by the.getTriggerID method.
267. Write a syntax and structure
of scheduler class?
Sample class
global class ScheduleDemo
implements Schedulable{
global
void execute(SchedulableContext sc){
BatchClass
b = new BatchClass();
database.executeBatch(b);
}
}
268. What is Scheduler class in Apex?
The Apex class which is programmed to run at
pre defined interval.
Class must
implement schedulable interface and it contains method named
execute().
There are two ways to invoke scheduler:
1.
Using UI
2.
Using System.schedule (Schedule method of
System class)
The classes which implements interface
schedulable get the button texted with “Schedule”, when user clicks on that
button; new interface opens to schedule the classes which implements that
interface.
To see what happened to scheduled job, go to
“Monitoring | Scheduled jobs “
Example of scheduling:
scheduledMerge m
= new scheduledMerge();
String sch = '20 30 8 10 2 ?';
system.schedule('Merge Job', sch, m);
Here:
20 represents seconds
30 represents minutes
8 represents hour of the day
10 represents 10th day of month
2 represents month of the year
? represents day of the month
269. Write a apex code to send a
email?
Sample code snippet to send
an email using apex code
Messaging.SingleEmailMessage
mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new
String[]{‘talk2srikrishna@gmail.com’};
mail.setToAddress(toAddresses);
mail.setSubject(‘Sample Mail
Subject’);
mail.setPlainTextBody(‘Hello
World!’);
Messaging.sendEmail(new
Messaging.SingleEmailMessage[]{mail});
270. What are the aggregate
functions supported by salesforce SOQL?
Following aggregate functions
are supported by salesforce SOQL
1.
SUM()
2.
MIN()
3.
MAX()
4.
COUNT()
5.
AVG()
6.
COUNT_DISTINCT()
271. Write a sample aggregate
query or explain how to write a aggregate queries?
The return types of Aggregate
functions are always an array of AggregateResult.
Sample Code
AggregateResult[] ar = [select
AVG(Amount) aver from Opportunity];
Object avgAmt =
ar[0].get(‘aver’);
272. Write a code to find the
average Amount for all your opportunities by campaign?
AggregateResult[] arList =
[select CampaignId, AVG(amount) from Opportunity group by CampaignId];
for(AggregateResult ar :
arList){
System.debug(‘CampaignId
’ + ar.get(‘CampaignId’));
System.debug(‘Average
Amount’ + ar.get(‘expr0’));
}
273. What are email services in
salesforce and explain how we can use them in code?
Email services are automated
processes that use apex class to process the contents, headers and attachment
of an inbound email.
Sample code
Use Case: create a contact
record if the inbound email subject is Create Contact and body contains contact
name
global CreateContactFromEmail
implements Messaging.InboundEmailHandler{
global
Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email,
Messaging.InboundEnvelop envelop){
Messaging.InboundEmailResult
res = new Messaging.InboundEmailResult();
String
strToCompare = ‘Create Contact’;
If(email.subject.equalsIgnoreCase(strToCompare)){
Contact
c = new Contact();
c.LastName
= email.plainTextBody();
insert
c;
//save
text attachments
for(Messaging.InboundEmail.TextAttachment
att : email.textAttachments){
Attachment a = new Attachment();
a.Name = att.fileName;
a.Body = att.Blob.valueOf(att.Body);
a.ParentId = c.Id;
insert attachment;
}
//save
binary attachments
for
(Messaging.Inboundemail.BinaryAttachment bAttachment : email.binaryAttachments)
{
Attachment attachment = new
Attachment();
attachment.Name = bAttachment.fileName;
attachment.Body = bAttachment.body;
attachment.ParentId = c.Id;
insert
attachment;
}
}
res.Success = true;
return res;
}
}
274. What is the row limit for
apex:dataTable and apex:pageBlockTable?
The data set for both
apex:dataTable and apex:pageBlockTable can have up to 1000 items.
275. What is the difference
between apex:pageMessages, apex:pageMessage, apex:Message and apex:Messages?
apex:PageMessages:
This component displays all messages that were
generated for all components on the current page, presented using the
salesforce styling. This will display both salesforce generated messages as
well as custom messages added to the ApexPages class
apex:PageMessage:
Apex:PageMessage is a component that adds single
message on the page. This is used to display custom message using the
salesforce formatting
apex:Message:
apex:Message is used to display an error on only
a specific field. It is used to allow developers to place field specific errors
in specific location.
apex:Messages:
apex:Messages is similar to apex:Message but it
displays all errors
276. How can we hard delete a
record using a Apex class/by code?
ALL ROWS key word can be used
to get all the records including records in the recycle bin.
Below is the sample code to
delete contact records from recycle bin
List<Contact> dContactList=[Select ID From
Contact Where IsDeleted = true limit 199 ALL ROWS];
Database.emptyRecycleBin( dContactList );
Database.emptyRecycleBin( dContactList );
278. Write a syntax and structure
of batch class?
Sample class
global Class BatchDemo
implements Database.Batchable<sObject>{
global Database.QueryLocator
start(Database.BatchableContext bc){
return
Database.getQueryLocator(query);
}
global void
execute(Database.BachableContext bc, List<sObjects> scope){
}
global void
finish(Database.BachableContext bc){
}
}
Below code will call the
batch class
BatchDemo bd = new BatchDemo();
database.executebatch(bd);
279. What is batch apex?
Batch Apex is exposed as an
interface that must be implemented by the developer. Batch jobs can be
programmatically invoked at runtime using Apex.
Need of Batch Apex: - As you
all might know about the salesforce governor limits on its data. When you want
to fetch thousands of records or fire DML on thousands of rows on objects it is
very complex in salesforce and it does not allow you to operate on more than
certain number of records which satisfies the Governor limits.
But for medium to large
enterprises, it is essential to manage thousands of records every day.
Adding/editing/deleting them when needed.
Salesforce has come up with a
powerful concept called Batch Apex. Batch Apex allows you to handle more number
of records and manipulate them by using a specific syntax.
We have to create a global
apex class which extends Database.Batchable Interface because of which the
salesforce compiler will know, this class incorporates batch jobs. Below is a
sample class which is designed to delete all the records of Account object
(Lets say your organization contains more than 50 thousand records and you want
to mass delete all of them).
Examples:-
global class deleteAccounts
implements Database.Batchable
{
global final String Query;
global deleteAccounts(String q)
{
Query=q;
}
global Database.QueryLocator
start(Database.BatchableContext BC)
{
return
Database.getQueryLocator(query);
}
global void
execute(Database.BatchableContext BC,List scope)
{
List <Account> lstAccount
= new list<Account>();
for(Sobject s : scope)
{
Account a = (Account)s;
lstAccount.add(a);
}
Delete lstAccount;
}
global void
finish(Database.BatchableContext BC)
{
//Send an email to the User after your batch completes
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[]
{‘sforce2009@gmail.com’};
mail.setToAddresses(toAddresses);
mail.setSubject('Apex Batch Job
is done‘);
mail.setPlainTextBody('The batch
Apex job processed ');
Messaging.sendEmail(new
Messaging.SingleEmailMessage[] { mail });
}
}
//This is how the batch class
is called.
id batchinstanceid =
database.executeBatch(new deleteAccounts(‘select Id from Account’));
280. What are web service
callouts?
Apex Code supports the
ability to expose Apex methods as a Web service. Apex also supports the ability
to invoke external web services and this will refer to as 'Callouts.' The
former is involved in creating a web service that a client can invoke, while
the latter is invoking an external web service.
281. What are wrapper classes?
A wrapper or container class
is a class, a data structure, or an abstract data type whose instances are
collections of other objects.
282. How do you hide header and
sidebar on visualforce page?
Below is the code to hide
sidebar and header
<apex:page
showHeader="false" sidebar="false">
</apex:page>
283. What is the difference between standard and custom
controller?
The standard controller is
auto generated by SF for all objects.
Custom controllers are
written by you and do what your code tells them to do.
284. How do you read parameter in
visualforce page?
Below syntax can be used to
read parameters in visualforce page
<apex:inputField
value="{!$CurrentPage.parameters.Paramtervalue}"/>
Additional code:
If you're writing a custom
controller, use the ApexPages global object variable
and currentPage() and getParameters() methods to get query
string parameters. For example, to get the value of the name query parameter in
the URL: https://na1.salesforce.com/001/e?name=value, use the following
line in your custom controller:
·If you're editing a page, use
the $PageContext global variable in a merge field.
For example, suppose you want
to add the Open Activities related list to an account detail page, but instead
of showing the account's activities, you want to show the activities of a
specified contact. To specify the contact, the following page looks for a query
string parameter for the contact's ID under the name relatedId:
<apex:pageBlock
title="Hello {!$User.FirstName}!">
You belong to the {!account.name}
account.<br/>
You're also a nice person.
</apex:pageBlock>
<apex:detail
subject="{!account}" relatedList="false"/>
<apex:relatedList
list="OpenActivities"
subject="{!$CurrentPage.parameters.relatedId}"/>
</apex:page>
For this related list to
render in a saved page, valid account and contact IDs must be specified in the
URL. For example, if 001D000000HRgU6 is the account ID
and 003D000000OXDIx is the contact ID, use the
URLhttps://na3.salesforce.com/apex/MyFirstPage?id=001D000000HRgU6&
relatedId=003D000000OXDIx.
To set a query string
parameter:
· If you're writing a custom controller, use
the setParameters() method with ApexPages.currentPage() to
add a query parameter in a test method. For example:
String value = 'Caroline';
ApexPages.currentPage().setParameters().put(key,
value);
Note
The setParameters() method
is only valid inside test methods.
· If you're editing a page, you can either
construct a URL manually:
Search Google
</apex:outputLink>
Or you can use
the <apex:param> tag as a child tag to write cleaner code:
Search Google
<apex:param
name="q" value="{!account.name}"/>
</apex:outputLink>
285. How can we pass javascript variable to apex class?
VF Page (Use assign input
variable to VF using $Component.FieldId)
<apex:page
controller="Js_Test_Class">
<apex:form>
<script>
function
setVal()
{
document.getElementById("{!$Component.hdnField}").value
= "TestValue";
}
</script>
<apex:inputHidden
id="hdnField" value="{!theValue}" />
<apex:commandButton
value="Post Page" action="{!post}" />
</apex:form>
<script>
setVal();
</script>
</apex:page>
Controller (Declare setter
and getter for the variable being used in VF page)
public class Js_Test_Class {
public
String theValue { get;set;}
public void post() {
System.Debug('The value is : ' +
theValue);
}
}
286. Is it possible to call apex
method in javascript code? If yes, explain?
Yes, we can call apex methods
using javascript. We can achieve this using ActionFunction. ActionFunction
allow you to tie an apex method to a javascript function name and invoke
synchronously. ActionFunction must be a child of apex:form component.
Example VF Page
<apex:page controller="t">
<script>
function myJavascriptFunc()
{
alert('Entered Javascript') ;
CallApexMethod() ;
}
</script>
<apex:form >
<apex:actionFunction
name="CallApexMethod" action="{!myActionInController}"
onComplete="alert('After apex method') ;"/>
<apex:pageBlock >
<apex:pageBlockButtons>
<apex:commandButton
value="Hit Me" onclick="myJavascriptFunc() ;"/>
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
</apex:page>
Example Controller
public class t
public PageReference
myActionInController(){
return null ;
}
}
287. What is commandLink? Explain
the usage?
CommandLink is a link that
executes an action defined by a controller, and then refreshes the current page
or navigate to the different page based on the PageReference variable that is
returned by the action.
commandLink component must be
a child of an form component.
Example:
<apex:commandLink
action=”{!save}” value=”Save” id=”theCommandLink”/>
288. What is outputLink? Explain
the usage?
OutputLink is a link to URL.
This component is rendered in HTML as an anchor tag with an href attribute. The
body of the OutputLink is a text or image that displays as the link
Example:
<apex:outputLink
value=”http://www.google.com” id=”theLink”>www.google.com</outputLink>
289. How to get URL parameters in
Visuaforce page?
If the URL is something link
this
https://<salesforce
instance>/apex/getQueryStringParam?id=001d000000B1Gj5&cid=003d000000BIjFh
and if we want to read cid in
our visualforce page then,
Use:
$CurrentPage.parameters.cid
Or
If there is a single
parameter in the URL string link this
https://xxx.visual.force.com/apex/NewPage?TestValue=value1&retURL=a0HS000000450UD
Then Use:
$CurrentPage.parameters.Paramtervalue
290. How to set URL parameters in
Visuaforce page?
Setting a Query String
parameter can be achieved by two ways.
One:
Construct a URL manually
like,
<apex:outputLink
value="http://google.com/search?q={!account.name}">
Search Google
</apex:outputLink>
Two
<apex:outputLink
value="http://google.com/search">
Search Google
<apex:param
name="q" value="{!account.name}"/>
</apex:outputLink>
291. How to get URL parameters in
APEX class?
If the URL is something link
this
https://<salesforce
instance>/apex/getQueryStringParam?id=001d000000B1Gj5&cid=003d000000BIjFh
And if we want to read cid in
our visualforce page then,
Use:
String id =
ApexPages.currentPage().getParameters().get('id');
String id =
ApexPages.currentPage().getParameters().get('cid');
292. How to set URL parameters in
APEX class?
To set a URL parameter using
Apex code use below syntax
String key = 'name';
String value = 'Caroline';
ApexPages.currentPage().getParameters().put(key,
value);
Or
ApexPages.currentPage().getParameters().set(‘value’);
293. Explain how MVC architecture
fit for Salesforce?
In salesforce, Apex Classes
works as Controllers, Visualforce Pages works as View and Custom objects works
as Model.
294. How to use actionFunction,
actionSupport and actionPollar in salesforce?
actionFunction : provides
support for invoking controller action methods directly from JavaScript code
using an AJAXrequest
Used when we need to perform
similar action on various events. Even though, you can use it in place of
actionSupport as well where only event is related to only one control.
Example:
actionFunction: provides
support for invoking controller action methods directly from JavaScript code
using an AJAXrequest
Example :
<!-- Page: -->
<apex:page
controller="exampleCon">
<apex:form>
<!-- Define the JavaScript
function sayHello-->
<apex:actionFunction
name="sayHello" action="{!sayHello}"
rerender="out"
status="myStatus"/>
</apex:form>
<apex:outputPanel
id="out">
<apex:outputText
value="Hello "/>
<apex:actionStatus
startText="requesting..." id="myStatus">
<apex:facet
name="stop">{!username}</apex:facet>
</apex:actionStatus>
</apex:outputPanel>
<!-- Call the sayHello
JavaScript function using a script element-->
<script>window.setTimeout(sayHello,2000)</script>
<p><apex:outputText
value="Clicked? {!state}" id="showstate" /></p>
<!-- Add the onclick event
listener to a panel. When clicked, the panel triggers
the methodOneInJavascript
actionFunction with a param -->
<apex:outputPanel
onclick="methodOneInJavascript('Yes!')"
styleClass="btn">
Click Me
</apex:outputPanel>
<apex:form>
<apex:actionFunction action="{!methodOne}"
name="methodOneInJavascript"
rerender="showstate">
<apex:param
name="firstParam" assignTo="{!state}" value=""
/>
</apex:actionFunction>
</apex:form>
</apex:page>
/*** Controller ***/
public class exampleCon {
String uname;
public String getUsername() {
return uname;
}
public PageReference sayHello()
{
uname = UserInfo.getName();
return null;
}
public void setState(String n) {
state = n;
}
public String getState() {
return state;
}
public PageReference methodOne()
{
return null;
}
private String state = 'no';
}
ActionSupport: A
component that adds AJAX support to another component, allowing the component
to be refreshed asynchronously by the server when a particular event occurs,
such as a button click or mouseover.
Used when we want to perform
an action on a particular event of any control like onchange of any text box or
picklist.
Example:
<!-- Page: -->
<apex:page
controller="exampleCon">
<apex:form>
<apex:outputpanel
id="counter">
<apex:outputText
value="Click Me!: {!count}"/>
<apex:actionSupport
event="onclick"
action="{!incrementCounter}"
rerender="counter"
status="counterStatus"/>
</apex:outputpanel>
<apex:actionStatus
id="counterStatus"
startText="
(incrementing...)"
stopText="
(done)"/>
</apex:form>
</apex:page>
/*** Controller: ***/
public class exampleCon {
Integer count = 0;
public PageReference
incrementCounter() {
count++;
return null;
}
public Integer getCount() {
return count;
}
}
ActionPolor: A
timer that sends an AJAX update request to the server according to a time
interval that you specify. The update request can then result in a full or
partial page update. You should avoid using this component with enhanced lists.
Used when we want to perform
an action on server again and again for a particular time interval.
Example:
<!-- Page -->
<apex:page
controller="exampleCon">
<apex:form>
<apex:outputText
value="Watch this counter: {!count}" id="counter"/>
<apex:actionPoller
action="{!incrementCounter}" rerender="counter"
interval="15"/>
</apex:form>
</apex:page>
/*** Controller: ***/
public class exampleCon {
Integer count = 0;
public PageReference
incrementCounter() {
count++;
return null;
}
295. What is the difference
between actionFunction and actionSupport tags?
Sl No |
ActionSupport
|
ActionFunction
|
1)
|
Directly call action method
without javascript
|
Call action method from
javascript with AJAX
|
2)
|
It can be used to call
action method on single event
|
It can be used to call
action method on different event
|
3)
|
It cannot be called from
javascript function. It only invoke controller action methods from other
Visualforce components
|
It defines a new JavaScript
function which can then be called from within a block of JavaScript code.
|
296. How do you do File Upload
using visualforce?
Below is the code sample of
file upload in visualforce
<!-- Page: -->
<apex:page
standardController="Document" extensions="documentExt">
<apex:messages />
<apex:form
id="theForm">
<apex:pageBlock>
<apex:pageBlockSection>
<apex:inputFile
value="{!document.body}" filename="{!document.name}"/>
<apex:commandButton
value="Save" action="{!save}"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
/*** Controller ***/
public class documentExt {
public
documentExt(ApexPages.StandardController controller) {
Document d = (Document)
controller.getRecord();
d.folderid = UserInfo.getUserId();
//this puts it in My Personal Documents
}
}
298. Explain Apex Data Types
Apex primitive data types include
• String
• Blob (for storing binary data)
• Boolean
• Date, DateTime and Time
• Integer, Long, Decimal, Double
• ID (Force.com database record identifier)
• String
• Blob (for storing binary data)
• Boolean
• Date, DateTime and Time
• Integer, Long, Decimal, Double
• ID (Force.com database record identifier)
Example:
• DateTime dt = System.now() + 1;
• Boolean isClosed = true;
• String sCapsFirstName = ‘Andrew’.toUpperCase();
• DateTime dt = System.now() + 1;
• Boolean isClosed = true;
• String sCapsFirstName = ‘Andrew’.toUpperCase();
Apex sObject Types
Sobject (object representing a Force.com standard or custom object)
Sobject (object representing a Force.com standard or custom object)
Example:
• Account acct = new Account(); //Sobject example
• Account acct = new Account(); //Sobject example
Apex has the following types of collections
• Lists
• Maps
• Sets
• Lists
• Maps
• Sets
Example:
• List myList = new List();
• myList.add(12); //Add the number 12 to the list
• myList.get(0); //Access to first integer stored in the List
• List myList = new List();
• myList.add(12); //Add the number 12 to the list
• myList.get(0); //Access to first integer stored in the List
Enums
• Enum (or enumerated list) is an abstract that stores one value of a finite set of specified identifiers.
• To define an Enum, use enum keyword in the variable declaration and then define the list of values.
• By creating this Enum, you have created a new data type called Season that can be used as any other data type.
• Enum (or enumerated list) is an abstract that stores one value of a finite set of specified identifiers.
• To define an Enum, use enum keyword in the variable declaration and then define the list of values.
• By creating this Enum, you have created a new data type called Season that can be used as any other data type.
Example:
• public enum Season {WINTER, SPRING, SUMMER, FALL}
• public enum Season {WINTER, SPRING, SUMMER, FALL}
299. Explain Apex Variables?
Local variables are declared with Java-style
syntax.
For example:
• Integer i = 0;
• String str;
• Account a;
• Account[] accts;
• Set s;
• Map<ID, Account> m;
For example:
• Integer i = 0;
• String str;
• Account a;
• Account[] accts;
• Set s;
• Map<ID, Account> m;
300. Explain Static Methods and Variables?
• Class methods and variables can be declared
as static. Without this keyword, the default is to create instance methods and
variables.
• Static methods are accessed through the class itself, not through an object of the class:
• Static methods are accessed through the class itself, not through an object of the class:
Example:
public class blogReaders {
public static boolean firstScript = false;
}
• Static methods are generally utility methods that do not depend on an instance. System methods are static.
• Use static variables to store data that is shared with in the class.
• All instances of the same class share a single copy of static variables.
• This can be a technique used for setting flags to prevent recursive
public class blogReaders {
public static boolean firstScript = false;
}
• Static methods are generally utility methods that do not depend on an instance. System methods are static.
• Use static variables to store data that is shared with in the class.
• All instances of the same class share a single copy of static variables.
• This can be a technique used for setting flags to prevent recursive
Hi Yadav,
ReplyDeleteThanks for your posts because I faced technical interview last week and I was able answer 90% of question by referring this blog. You are doing great job thank you so much again please update blog frequently.
Wow, this is amazing, come here by mistake and what a jackpot :)
ReplyDeleteThank you very much for sharing this!!!!
it's my pleaser you got it's and help full for you, Please refer to other....
DeleteHai!
ReplyDeleteLoved the tutorials, hope you keep writing more of these!
I’m new to Salesforce, but it’s guys like yourself that make me want to push myself to learn as much of it as efficiently as possible.
salesforce training in chennai
Really helpful for me. Thanks keep posting more.
ReplyDeleteThanks for this post. It's Very helpful.
ReplyDeleteHi There,
ReplyDeleteThis is indeed great! But I think perhaps you are generally referring Apex Interview Questions Answers And Tutorial which is getting unsustainable.
I have an apex datatable returning some User fields from a list in my apex class. I would like to include a column "This Month's Sales" which would return the total $ of opps closed won this month. I can run the SOQL in my class but I'm not sure how to get the correct result per user into the table, i.e. how to put it into the correct row and column in my table. Can I attach this $amount to each user without creating a custom field?
I am so grateful for your blog. Really looking forward to read more.
Kind Regards,
Preethi.