Sfdc Develoment Interview Questions.docx

  • Uploaded by: RajaSekhar
  • 0
  • 0
  • August 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Sfdc Develoment Interview Questions.docx as PDF for free.

More details

  • Words: 2,870
  • Pages: 18
SOQL Queries : Salesforce object query language is used to fetch the records from database.com based on the requirement. There are two types of SOQL statements:  Static SOQL  Dynamic SOQL

Static SOQL : The static SOQL statement is written in []

(Array Brackets).

Eg : string srearchfor = “Jones”; Contact[] contacts = [select Firstname, Lastname from contacts where Lastname=:searchfor];

Dynamic SOQL : The Dynamic SOQL used to refer to the creation of SOQL string at runtime with apex code.  Dynamic SOQL enables you to create more flexible application.  To create dynamic SOQL query at runtime use Database.Query() method in one of the following ways.  Returns single SObject when the query returns a single record. SObject s= Database.query(string_limit_1);  Returns a list of SObjects when the query returns more than a single record. Ex : String myteststring = “TestName”; List<SObject> L = Database.Query(‘ select id from contacts where name=: myteststring ‘); Q) Write a query to fetch customer name, balance from customer object where balance is more than 10000. QUERY : List<customer__c> customers = [ select id, customer_name__c, balance__c from customer__c where balance__c > 10000 ]; Q) Write a query to fetch TID, type__c from transaction if mode is cash. QUERY : List tra = [ select Name, Type__c from Transaction__c where mode__c = ‘cash’ ]; Querying Multiselect picklist values : When you want to write a query with a condition based on multiselect picklist in which multiple item values are selected then we can use following operations to write the condition. Note : First let us create proof field with datatype multiselect with the values.    

Passport Aadhar Voter Id Pancard

Q) Write a query to fetch all customer names and account types who has submitted pancard as a proof. QUERY : List<customer__c> customer = [ select id, customer_name__c,account_type__c from customer__c where proof__c = ‘pancard’ ]; Q) Write a query to fetch customer name, balance from customer object where proof is aadhar card or pancard. QUERY : List<customer__c> customer = [select customer_name__c, balance from customer_c where proof__c INCLUDES (‘Aadhar card’,’pan card’) ]; IN : If the value equals any one of the specified values in a where clause QUERY : select name from account where billingstate IN(‘california’,’new yark’); Not IN : If the value doesn’t equal any of the specified values in a where clause QUERY : select name from account where billingstate NOT IN(‘california’,’new yark’); Sub Query : Q) Write a query to return list of accounts that don’t have any open opportunities. QUERY : select id,name account where id IN(select AccountId from Opportunities where ISClosed = false) Group By : QUERY : select LeadSource, count(name) from Lead group by LeadSource. Group By Rollup : This allows you to query calculate subtotals so you don’t have to maintain the logic in your code. QUERY : select LeadSource,count(name) from Lead group by rollup(LeadSource).

Relationship Query : There are two types of relationship queries 1.child to parent relationship. 2.parent to child relationship. Child to parent relationship on Standard Objects:

In the above diagram contact is child of account object. In the child to parent relationship relationship name will be parent object. Example : Write a query to fetch list of contacts and account names from contact object where account industry is media. QUERY : select id, name, account.name from contact where account.industry = ‘Media’; Child to parent relationship on custom objects :

Note : When we use relationship name from custom object in SOQL queries we should append Objectname__r to the relationship name.

Ex : Write a query to fetch list of transactions along with account type and customer names whose transaction type is deposit. QUERY : List tr = [select id,customer__r.customername__c, customer__r.accounttype__c, name from transaction__c];

Write a program to display first five contact details from contact object along with account name and industry. Apex Class :

public class GetContactDetails { public List cont {get;set;}

public pagereference show() { cont = [select id,name,account.Name,account.Industry from contact Limit 5]; return null; } } VF Page :

Parent to child relationship on standard objects : When we are trying to write a query to refer the child object records from the parent object then the child object name would be the relationship name.

Select account.Name,[select contact.FirstName, contact.LastName from account.contact] from account

Email Programming : When you want to send an email from the salesforce to external system or a receiving a mail from external system to salesforce then we use email services. There are two types of email services 1. Inbound Email Messaging 2. Outbound Email Messaging Outbound Email : This is used to send an email to external system using apex code. There are two types of outbound mails. 1. Single Email Message 2. Mass Email Message Note : Messaging namespace provides classes and methods for salesforce outbound and inbound email functionality.

Single Email Message : This is an instantiates an email object used for sending a single email message. Syntax : Messaging.SingleEmailMessage msg = new Messaging.SingleEmailMessage(); This class contains methods of sending single email message. When we want to send a message first, we have to create the object of SingleEmailMessage. List of methods available in the SingleEmailMessage. 

setBCCAddress(string[]) : This method will set BCC Address to whom the mail should be sent. we can set up to 25 email addresses.

Ex : String[] tobccaddress = new String[]{‘[email protected]’,’[email protected]’}; Myemail.setBCCAddresses(tobccaddress); 

setCCAddress(string[]) : This method will set CC Address to whom the mail should be sent. we can set up to 25 email addresses.

Ex : String[] toccaddress = new String[]{‘[email protected]’,’[email protected]’}; Myemail.setCCAddresses(toccaddress); 

setToAddresses(string[]) : This method will set the addresses, we can set up to 100 addresses.

Ex : String toaddress = new String[]{‘[email protected]’,’[email protected]’}; Myemail.setToAddresses(toaddress); 

setSubject(String) : This method will set the subject of the mail.

Ex : Myemail.setSubject(‘Test Email’);



setPlainTextBody(String) : This method will set the TextBody of the mail.

Ex : Myemail.setPlainTextBody(‘Hello Rajasekhar’); 

setHtmlBody(String) : This method will set the main body of the mail.

Ex : Myemail.setHtmlBody(‘

This is Raja

’);

Apex Class : public class SingleEmailMessage { public pagereference show() { Messaging.SingleEmailMessage msg = new Messaging.SingleEmailMessage(); String[] toaddresses = new String[]{'[email protected]','[email protected]'}; String[] tobccaddresses = new String[]{'[email protected]','[email protected]'}; msg.setToAddresses(toaddresses); msg.setBccAddresses(tobccaddresses); msg.setSubject('Sample Test Mail'); msg.setPlainTextBody('Hi Team Welcome To Salesforce'); msg.setHtmlBody('

Hello CRM

'); Messaging.sendEmail(new Messaging.SingleEmailMessage[] {msg}); return null; } }

VF Page :

Mass Email Message : We can send a mass email message to a recipient list that consists of contacts, leads, person accounts and users you can view in salesforce. Messaging.MassEmailMesage : This class has all the methods defined in the email class and also email base class methods. Methods :

 Public void setDescription(String Description) : This will give the description about the mail.

 Public void setTargetObjectIds(ID[] targetobjectIds) : We can add up to 250 IDs per mail. If you specify a value for the target object Ids field optionally specify a what Id’s as well.

 Public void setWhatIDs(ID[] whatIds) : The value can be any one of the following contracts, case, opportunity and product. Syntax : Messaging.MassEmailMessage msg = new Messaging.MassEmailMessaging();

Example : Send a mass emails for all contacts created on Today. Apex Code : public class MassEmails { public pagereference sendmail() { List con = [select id,email from Contact where CreatedDate=ToDay]; List contactIds = new List(); for(Contact c:con) { contactIds.add(c.id); system.debug('Contact Emails are : '+c.email); } EmailTemplate et= [select id from EmailTemplate where id='00X6F000002g7I5']; Messaging.MassEmailMessage msg = new Messaging.MassEmailMessage(); msg.setTargetObjectIds(contactIds); msg.setTemplateId(et.id); Messaging.sendEmail(new Messaging.MassEmailMessage[] {msg}); return null;

} }

Vf Page :

Sending a document through mail :

 Public void setDocumentAttachments(ID[]) : This method will send the documents that we got in the salesforce in the email using messaging concept. Step 1: Create a document in salesforce. ->Go to the document object click on new documents. ->Enter the name, description of the document. ->Select external file, choose the document file and save. Step 2: In the Apex program write a query to fetch the id of the document.

Inbound Email Service : http://sfdcsrini.blogspot.com/2014/11/inbound-email-service-in-salesforce.html Inbound email service will receive a mail from external system to salesforce and apex class will process the email and attachments and perform requested operations.

 Messaging.InboundEmailClass : This class object represents email received by the salesforce. Public string textAttachments; Public string Subject; Public string replyTo; Public string toAddress;

Public string plainTextBody; Public string messageId; Public string inReplyTo{get;set;} Public string ccAddress; Public string fromAddress; Public string fromName;

 Messaging.InboundEnvelope : The object of this class stores the envelop information (from address and to address) associated with inbound email. Public string toAddress; Public string fromAddress; Ex: Messaging.InboundEnvelope em = new Messaging.InboundEnvelope(); em.fromAddress = ‘[email protected]’; em.toAddress = ‘[email protected]’;

 Messaging.InboundEmailResultClass : The object of this class is used to return the result of the email services. Note : If the object is null the result is achieved to be successful. Public boolen success : This attribute indicates wether the email received successfully processed or not. Incase if the email was not successfully processed, salesforce reject the inbound email and sends replay to original set up. Public string message : This message stores the message written by the salesforce in the reply mail. Any apex class which want to process Inbound email should implement an interface ( Messaging.InboundEmailHandler ). This interface has a method

globalMessaging.InboundEmailResult handleInboundEmail ( Messaging.InboundEmail email , Messaging.InboundEnvelope envelope );

DML Operations : Insert Update Delete Upsert There are two ways to perform DML operations. 1. By using DML Statements. 2. By using Database Class.

By using DML Statements : List acc = new List(); acc.add(new Account(Name = ‘TCS’)); acc.add(new Account(Name = ‘HCL’)); insert acc;

By using Database Class : List acc = new List(); acc.add(new Account(Name = ‘TCS’)); acc.add(new Account(Name = ‘HCL’)); Database.saveResult[] sr = Database.insert(acc,false); Note : In a single transaction we can’t make more than 150 DML statements.

Database.QueryLocator class : Database.QuerLocater class stores the record set return by the Database.getQueryLocator. There are two methods in QueryLocator class

getQuery() : syntax : public string getQuery(); this method returns the query used to instantiate the Database.QueryLocator object. Database.QueryLocator dq = Database.getQueryLocator( [select name from Account] ); String str = dq.getQuery();

Iterator() : Syntax : public Database.QueryLocatorIterator().

This will return new instance of QueryLocatorIterable Example : List acc = new List(); Database.QueryLocator dq = Database.getQueryLocator(); Database.QueryLocatorItterable iq = dq.iterator(); While(iq.hasNext()) { Account a = (Account)iq.next(); Acc.add(a); }

Batch Apex : A Batch class allows you to define a single job that can be broken up into manageable chunks that will be processed separately.

When to use Batch Apex One example is if you need to make a field update to every Account in your organization. If you have 10,001 Account records in your org, this is impossible without some way of breaking it up. So in the start() method, you define the query you're going to use in this batch context: 'select Id from Account'. Then the execute() method runs, but only receives a relatively short list of records (default 200). Within the execute(), everything runs in its own transactional context, which means almost all of the governor limits only apply to that block. Thus each time execute() is run, you are allowed 150 queries and 50,000 DML rows and so on. When that execute() is complete, a new one is instantiated with the next group of 200 Accounts, with a brand new set of governor limits. Finally the finish() method wraps up any loose ends as necessary, like sending a status email.

Sample Batch Apex 1) Start method is automatically called at the beginning of the apex job. This method will collect record or objects on which the operation should be performed. These records are divided into subtasks & passes those to execute method.

2) Execute Method performs operation which we want to perform on the records fetched from start method.

3) Finish method executes after all batches are processed. Use this method to send confirmation email notifications. global class AccountUpdateBatchJob implements Database.Batchable<sObject> { global Database.QueryLocator start(Database.BatchableContext BC) { String query = 'SELECT Id,Name FROM Account';

return Database.getQueryLocator(query); } global void execute(Database.BatchableContext BC, List scope) { for(Account a : scope) { a.Name = a.Name + 'Updated by Batch job'; } update scope; } global void finish(Database.BatchableContext BC) { } }

Calling on Batch Apex AccountUpdateBatchJob obj = new AccountUpdateBatchJob(); DataBase.executeBatch(obj);

Example for Batch Apex : global class BatchapexExample implements Database.Batchable<sObject> { global final String Query; global final String Field; global final String Value;

global BatchapexExample(String q, String f, String v) { Query = q; Field = f; Value = v; } global Database.QueryLocator start(DataBase.BatchableContext BC) { return DataBase.getQueryLocator(query); } global void execute(DataBase.BatchableContext BC, List scope) { for(Contact s: scope) { s.put(Field,Value); } update scope; } global void finish(DataBase.BatchableContext BC) {

} }

How to execute Batch Apex : String q = 'SELECT FirstName FROM Contact'; String f = 'FirstName'; String v = 'BatchApex'; Id batchInstanceId = Database.executeBatch(new BatchapexExample(q,f,v));

Order of execution of batch Apex job when we invoke through DataBase.Execute Batch() : Step 1 : Create object for class which has implemented Database.Batchable interface. Step 2 : Pass this object which you have created in the first step as a parameter to the DataBase.Batchable interface. Step 3 : When DataBase.executeBatch() method is called it will add the batch job to the queue. Step 4 : Once the resource is available in the queue automatically start() method will be invoked and it will collect all the records on which we need to perform the operation. Step 5: The records that are fetched from start() method are divided in to small group/batch size given in the DataBase.execute() method. Note : In case if you don’t specify the space by default it takes 200.

Step 6 : On every batch of records execute method will be invoked. Step 7 : Once all the batches are executed, finis method will be called.

Governing Limits : 1.only one batch apex job’s start method can run at a time in an organization. 2.up to 5 queued or active batch jobs are allowed for apex. 3.The maximum number of batch apex method executions per a 24-hours period is 2,50,000 4.The Batch Apex start method can have up to 15 query cursors open at a time per user. 5.A Maximum of 50 million records can be returned in the DataBase.QueryLocater object. 6.The start, execute and finish methods can implement up to 10 callouts each. Note : If we have 1000 records with scope of 200 records, then they are divided in to 5 batches. So, execute method will call 5 times which means every execute() we call 10 callouts.so, in this scenario we call Start()  10 callouts. Execute()  10*5 = 50 callouts. Finish()  10 callouts. 70 callouts in entire operations.

Scheduler Class For Batch Apex : It will invoke Apex class to run at specific time. Anybody who want to schedule their class they have to implement schedulable interface. global class Myschedule implements Schedulable { global void execute(SchedulableContext sc) { Account a = new Account(Name = ‘Sekhar’); Insert a;

} }

Navigation : Set Up ->Build ->Develop ->Apex Classes ->Click on Schedule Apex

How to Schedule scheduler class There are two option we have schedule the scheduler classes. 1) By System Scheduler. 2) By Developer console

System Scheduler.

Step 1) Click on Setup->Apex class. Then search Schedule Apex button.

Step 2) Select the scheduler class and set Time like below screen shot.

By Developer console Execute below code from developer console :AccountUpdateBatchJobscheduled m = new AccountUpdateBatchJobscheduled(); String sch = '20 30 8 10 2 ?'; String jobID = system.schedule('Merge Job', sch, m);

The following are some examples of how to use the expression. Seconds Minutes Hours Day_of_month Month Day_of_week Optional_year

Before Insert :  Before insert trigger will fire when we are trying to insert a new record into specified object.  Operations which we have written in the trigger will be implemented before new records are saved to the database.  In before insert Trigger.New stores the list of new records which we are trying to insert.

Scenario 1 : Check duplicate candidate with candidate name and emailid Apex Class : public class Candidate_Duplicate_Before_Insert { public static void Candidate_Duplicate(List canList) { for(Candidates__c c:canList) { List can = [select id,Name,Email__c from Candidates__c where Name=:c.Name or Email__c=:c.Email__c]; if(can.size() > 0) { c.addError('Duplicate Candidate'); } } } }

Trigger : trigger Candidate_Duplicate_Check_Before_Insert on Candidates__c (before insert) { Candidate_Duplicate_Before_Insert.Candidate_Duplicate(trigger.new); }

Test Class : @isTest public class Candidate_Duplicate_Testclass { public static testMethod void testinset() { string addError; string myname = 'Raja'; string email = '[email protected]'; Candidates__c c = new Candidates__c(name=myname); List can = [select Name from Candidates__c where Name=:myname or Email__c=:email];

if(can.size() < 1) { system.assertEquals(0, can.size()); insert c; } else { addError = 'existing'; system.assertEquals('existing', addError); } } }

After Insert :  This trigger will be fired after new records are successfully saved to the database.  After trigger will performed after committing the new records into database.

Scenario : Whenever the new contact is created for an account update the corresponding account phone with the new contact field.

Related Documents

Sfdc Questions
August 2019 27
Interview
May 2020 20
Interview
May 2020 17
Interview
August 2019 31

More Documents from "Jason Crews"