Pardot : marketing automation platform

What is Pardot ?

Pardot is Salesforce’s B2B marketing automation solution. If you’re a business with marketing and sales teams that work to drive pipeline and grow revenue, Pardot can automate your marketing activities and unite your marketing and sales departments so that they can work better together.

Pardot gives you a central location to manage your marketing initiatives and report on their success. Not only that, but it tracks prospects as they interact with your company marketing channels, like your website, emails, and forms, so your marketing and sales teams can deliver a personalized experience.

Marketing automation terms :

Funnel Stages : Marketing automation terms

Lead (or demand) generation: The act of creating interest in your products or services through marketing efforts.

Visitor: An anonymous person who visits your website and is now tracked in Pardot. 

Conversion: Once a visitor gives you their contact information, such as an email address, by submitting a Pardot landing page or form, they are converted to a prospect.

Prospect: An anonymous visitor that has converted and is now identified. A record of the prospect will exist in Pardot, similar to a lead record in Sales Cloud or other CRMs.

Lead nurturing: Sending targeted messages at specific intervals based on a prospect’s actions and whether or not they’ve met certain qualifying criteria. 

Lead qualification: You probably have thousands (or even hundreds of thousands) of people interacting with your organization. Your sales teams can’t contact each of them, so as marketers it’s your job to help send them the best prospects. This process of finding the gold needles in the haystack of prospects is called lead qualification. You decide the threshold for when a prospect is ready to be assigned to a salesperson for them to follow up.

Pardot uses two metrics for lead qualification: score and grade. 

  • Prospect score: A prospect’s score is a numerical value indicating how interested they are in your product or service. A prospect’s score can increase or decrease based on how they interact with your marketing materials.
  • Prospect grade: A prospect’s grade is represented by a letter (A, B, C, D, etc.).  It indicates how closely a prospect fits the profile of your ideal prospect.

You can leverage score and grade to determine which prospects are ready to reach the end of the funnel and have a salesperson follow up with them. With the help of Pardot automation, you can quickly assign qualified prospects to the appropriate salesperson.

Campaigns: Campaigns help you understand how your marketing initiatives are performing. Campaigns are used a few different ways in Pardot.

For example, every prospect in Pardot has an assigned campaign that tells you the first marketing-related contact they had with your company. You can also use campaigns to group relevant marketing materials together. And most importantly, you can use Pardot automation with campaigns to track all the marketing touchpoints in a prospect’s journey, which opens the door to better ROI reporting.

When to use Pardot ?

Pardot is a great fit when you want to: 

  • Generate more leads and move them quickly through the pipeline
  • Engage buyers on their terms with dynamic, personalized campaigns
  • Understand each step from click to close, capturing true marketing ROI
  • Remove silos across organizations that lead to disjointed customer experiences
  • Make data driven decisions
  • Strengthen or build your account-based marketing (ABM) strategy

Reference : Salesforce Trailhead

Salesforce Best Practices

Data Model Design

  • Reuse the maximum standard objects of the platform.
  • Be aware of the behavior for these objects, especially on Lead (that becomes an Account and a Contact) and Opportunity (stage, probability…).
  • Be careful of relationship type you want to implement, sometimes lookup is enough but try to identify future needs to select the right relation (for example when a field of the parent object should be updated -by workflow- when the child changes, it’s only possible with a master-detail relationship…).
  • Be careful when choosing the right field type and name as when they’re deployed it’s a high risk to modify them.
  • Consider making a field required when he’s updatable by both the UI and web service or other apex code.
  • Identify the different kinds of users/actors, their relation (visibility of records), their rights (profile).
  • Field API Name should be as short as possible. Avoid using underscores, use a capital letter for each word, and abbreviate words.
  • Create a default record type when creating an object. This will prevent data migration later when you will need to manage record types
  • Ensure you have Field Level Securities giving access to all fields for a technical profile, to be able to backup all your data
  • Custom Settings: Optimize the length of your text fields. You have limited storage, even if you put data with a shorter length it will really be estimated with full length.
  • Visibility: Think twice before defining Org Wide Defaults for external users as “public” on an object.
  • When defining an existing field as required, ensure (or migrate) existing records have no empty value for that field
  • If “Strictly enforce picklist values” option enabled, picklist values must be aligned with your data

Integration Design

  • Identify the volume of data exchanged.
  • Identify the direction: inbound, outbound.
  • Identify the type: sync / async.
  • Identify the integration process: batch, oneshot.
  • Favor inbound message using the standard Enterprise / Partner API as custom inbound or outbound are expensive to develop (except for outbound call using the workflow).

Logic Design

  • Match each need with available Force.com technology to build the logic (Validation Rule, Workflow, Approval Process…).
  • Manage configuration limits: number of workflows, of filtered lookups…
  • Use Apex code in a last consideration.
  • Any item configured should have comments in the description attribute
  • Enforce naming conventions

Code – general

  • Keep the right visibility. Use “with sharing” for your class, or document why you would run without sharing
  • Don’t code if you can configure it. Allowed exception is related to performance.
  • Comment your code
  • Do not hard code IDs. If you need some invariant Ids in some circumstance you can put them in a System Label
  • Keep your code small. This will better manage the 3Mb limit, make you think on an optimized algorithm, and most of the time make your code faster. Ex: is it necessary to define a temporary variable that will be used only once?
  • Always code for performance.
  • Ensure system.debug() is consistent to the context (ex: do not log “after insert” if you are in a “before insert” trigger)
  • Avoid multi-line tests. This could have negative impact on code coverage if part of the test is false.
  • Remove commented code to have clean classes
  • Never use try..catch when the purpose is only to hide errors (with no code in the catch, or just a system debug). The user or admin should be notified by the error
  • Do not have a different behavior when testing vs when running (spaghetti code using if(System.Test.isRunningTest())
  • Apex Callouts – Do not hard code credentials in the code. Use named credentials as endpoints to simplify authenticated Apex callouts and manage credentials through the Setup user interface.
  • Do not hardcode email addresses
  • Put outside the FOR loops invariants. Ex: Contact.sObjectType.getDescribe() or Schema.SObjectType.Contact.fields.getMap();
  • Do not call @future methods inside FOR loops. These methods should be bulkified and called after the loop.
  • Use only one return statement par method.
  • Remove unnecessary local variables, empty blocks and empty methods

SOQL in Apex

  • Avoid SOQL queries statements inside loops (for, while..)
  • Leverage SOQL capability to reduce Apex code
    • Capability to order results, filter, query multiple objects in 1 query through relationships
    • Capability to aggregate date and do computation (select SUM()…)
    • Put the result directly in a map instead of doing this in a for..loop
    • Nested for..loop with a SOQL query in the container loop can implicitly manage batch records, reducing heap consumption and increasing speed (because of smaller lists). for(Account[] accs:[Select Name from Account limit 10000])for(Account a:accs){do something}
  • Make efficient SOQL queries. Ex: [select Name from Profile where id in (select ProfileId from User where Id=:UserInfo.getUserId())] could be rewritten as [select Name from Profile where Id=:UserInfo.getProfileId()]
  • Limit returned records. If a query is returning multiple records, you must add “limit xxx” at the end of the query to manage governor limits
  • Whenever it is possible, try to use 1 query for multiple records on the same object, instead of 1 query per record.
  • Do not query on fields that you will not use
  • When querying users, don’t forget to filter on the isActive field
  • To filter your query, use the DeveloperName field instead of the Name field when the queried object has both (i.e.: Group, RecordType…)
  • When doing a query on RecordType object, filter on SObject name as you can have the same recordType developerName across multiple objects
  • Reduce joins in queries. If you need an id of the record from a lookup, do not code select theLookup__r.id from theObject__c. Prefer this one: select theLookup__c from theObject__c

DML

  • Use a DML for a list of records instead of 1 DML per record (bulk)
  • Do not perform DML inside of loops

Triggers

  • Don’t forget that trigger handle up to 200 records per execution.
  • Don’t put the logic (incl. SOQL or DML) in the trigger, use a handler class.
  • Don’t push trigger.New to the handler class method, you should filter on records that are in related scope. You will increase performance, reduce governor limits consumption, and limit regression risks when updating the class.
  • Create 1 trigger per event and per object. Multiple triggers for the same event of an object would not ensure that the execution order would always be the same, giving unpredictable behavior in production. Managing multiple events in the same trigger would reduce maintainability with spaghetti code.
  • Put bypass logic in the trigger for each handler class. This would prevent running some code for some users. For instance, a technical user doing data migration will have improved performance if some business logic is not triggered. For this purpose, you should use PAD framework. Ensure that each bypass keyword used in triggers is defined in the bypass multi-picklist definition.
  • Always optimize. Even if you think it is not needed, as your trigger can be run from another trigger, which can reach governor limits.
  • Beware of over optimization side effects; when optimizing SOQL queries and DMLs, you will probably use structured maps indexed by IDs. This consumes a lot in memory as triggers are limited in heap size and each trigger in the transaction can consume much heap. Free memory if such structures are not needed after usage.

Controllers

  • Bind your pages with the code using “Page.VisualforcePageName” instead of “new PageReference(‘/apex/VisualforcePageName’)”. Impact and dependencies will be better managed (ex: when renaming the page), and this is the only way to be compatible with CRSF protection.
  • Reduce ViewState to get better performance.
  • Secure your code (SOQL injection, etc.). If you leverage an URL parameter you should make sure that it is of the expected type with a correct value.

Test Classes

  • Prefer creating multiple testMethods in a test class instead of one big method. Benefit is maintainability
  • Avoid using seealldata=true in test classes to avoid conflict (locking contention) with real production data
  • Always assert() in test methods
  • Leverage a @testSetup method to reduce execution time and increase maintainability
  • Test the limits (bulk)
  • Use test.startTest() after data preparation and test.stopTest() before asserts
  • It is better to do Test Driven Development. It is more productive development.
  • Prefer target 85% code coverage per class

Visualforce

  • Keep you page light (few fields, simple DOM, avoid frameworks), for performance and usage.
  • Remove commented code (<!– … –>) to increase maintainability and improve server parsing performance
  • Do not hardcode access to Visualforce Pages (value=”/apex/PageName”) as it will break when CRSF is enabled. Use either {!$Page.PageName} or {!URLFOR($Page.PageName)}
  • Reduce frameworks usage to keep the page light and performant (RAM footprint, network impact, CPU consumption…)
  • Manage errors. An error can still occure, warn the user with putting one of the following tags on the top of your page: <apex:pageMessages /> or <apex:messages />

Profiles

  • Keep the number of profiles low. Use permission sets if one profile as a few more permissions than another existing profile.
  • Remove unused custom profiles
  • Profiles should not be API enabled, except when really necessary, for security reasons.

Roles

  • Keep your role hierarchy simple. If you have one role per user, and some roles without users, you probably have a design issue

Validation Rules

  • Don’t use hard coded IDs
  • Put a bypass system in the logic
  • When adding a Validation Rule, migrate existing records that don’t match this rule.
  • Keep the quantity of VR low to manage performance
  • Define the error message at the field location instead of at the top of the page.
  • Remove inactive Validation Rules

Workflow rules and actions

  • Don’t use hard coded IDs
  • Put a bypass system in the logic
  • Don’t create multiple workflows with the same rule
  • Remove Workflow actions that are not used by workflow rules
  • Remove rules that have no actions
  • Keep the quantity of WR low to manage performance
  • Remove inactive workflows
  • Don’t update fields if the current value is already correct

Process Builder

  • Put a bypass logic within each test
  • Don’t update fields if the current value is already correct

Static Resources

  • Do not host credentials (security risk)
  • Use the description field to tell where the resource is being used
  • Optimize picture compression and size. Use the appropriate file format.

Custom Labels

  • Avoid duplicate labels with the same value

Naming conventions

  • Avoid using underscores
  • Classes: Use UpperCamelCase
  • Variables and methods: use camelCase with the first letter in lowercase
  • Test classes: Append “Test” to the name of the covered class
  • Trigger: [ObjectName][Event]. Example: AccountBeforeInsert

Salesforce Best Practice For Test Class

Please follow below salesforce Best Practice for Test Classes.

1. Test class must start with @isTest annotation if class class version is more than 25
2. Test environment support @testVisible , @testSetUp as well
3. Unit test is to test particular piece of code working properly or not .
4. Unit test method takes no argument ,commit no data to database ,send no email ,flagged with testMethod keyword .
5. To deploy to production at-least 75% code coverage is required
6. System.debug statement are not counted as a part of apex code limit.
7. Test method and test classes are not counted as a part of code limit
9. We should not focus on the  percentage of code coverage ,we should make sure that every use case should covered including positive, negative,bulk and single record .
Single Action -To verify that the the single record produces the correct an expected result .
Bulk action -Any apex record trigger ,class or extension must be invoked for 1-200 records .
Positive behavior : Test every expected behavior occurs through every expected permutation , i,e user filled out every correctly data and not go past the limit .
Negative Testcase :-Not to add future date , Not to specify negative amount.
Restricted User :-Test whether a user with restricted access used in your code .
10. Test class should be annotated with @isTest .
11 . @isTest annotation with test method  is equivalent to testMethod keyword .
12. Test method should static and no void return type .
13. Test class and method default access is private ,no matter to add access specifier .
14. classes with @isTest annotation can’t be a interface or enum .
15. Test method code can’t be invoked by non test request .
16. Stating with salesforce API 28.0 test method can not reside inside non test classes
17. @Testvisible annotation to make visible private methods inside test classes.
18. Test method can not be used to test web-service call out . Please use call out mock
19. You can’t  send email from test method.
20.User, profile, organization, AsyncApexjob, Corntrigger, RecordType, ApexClass, ApexComponent ,ApexPage we can access without (seeAllData=true) .
21. SeeAllData=true will not work for API 23 version eailer .
22. Accessing static resource test records in test class e,g List<Account> accList=Test.loadData(Account,SobjectType,’ResourceName’).
23. Create TestFactory class with @isTest annotation to exclude from organization code size limit .
24. @testSetup to create test records once in a method  and use in every test method in the test class .
25. We can run unit test by using Salesforce Standard UI,Force.com IDE ,Console ,API.
26. Maximum number of test classes run per 24 hour of period is  not grater of 500 or 10 multiplication of test classes of your organization.
27. As apex runs in system mode so the permission and record sharing are not taken into account . So we need to use system.runAs to enforce record sharing .
28. System.runAs will not enforce user permission or field level permission .
29. Every test to runAs count against the total number of DML issued in the process .

Salesforce Admin and Development Scenario Based Questions -1

1.When ever a record is inserted to the account automatically inserted to the contact.

trigger SCENARIO1 on Account (after insert) {
list c=new list();
for(account a:trigger.new)
{
contact b=new contact();
b.LastName=a.Name;
b.AccountId=a.Id;
c.add(b);
}
insert c;

}


2.When ever a record is inserted to the contact automatically inserted to the account.

trigger scenario2 on Contact (after insert) {
if(Recursive.flag)
{
Recursive.flag=false;
lista=new list();
for(contact c:trigger.new)
{
account a1=new account();
a1.Phone=c.Phone;
a1.Name=c.LastName;
a.add(a1);

}

insert a;

}


3.How to avoid recursive trigger in salesforce ?

public class Recursive {
public static boolean flag=true;

}


3.When ever a created opportunity object record, update total opportunities and total amount in account object.

trigger scenario24 on Opportunity (after insert) {
setids=new set();
for(Opportunity op:trigger.new)
{
ids.add(op.accountid);
}
listac=[select Total_opportunities__c,Total_Amount__c,(select id,Amount from Opportunities ) from account where id=:ids];
for(account a:ac)
{
a.Total_opportunities__c=a.opportunities.size();
decimal sum=0;
for(opportunity p:a.opportunities)
{
sum=sum+p.amount;
}
a.Total_Amount__c=sum;

}
update ac;
}

4.On contact object ,when ever department equal to cse automatically insert email on email field.

trigger scenario4 on Contact (before insert) {
for(contact c:trigger.new)
{
if(c.Department==’CSE’)
{
c.Email=’sfdcforum@gmail.com’;
}
}

}


5.When ever we modifying inputout__c object doctor name automatically update on droppoff__c object text field on relationship.

trigger SCENARIO32 on Inputout__c (after update) {
listd=[select id,name,Text__c from Dropoff1__c where Text__c=’naveen’];
string name;
for(Inputout__c c:trigger.new)
{
name=c.Doctor_Name__c;
}
for(Dropoff1__c dp:d)
{
dp.Text__c=name;
}
update d;

}

6.Limit reached the records.

trigger SCENARIO6 on Account (before insert,before update) {
integer count=0;
lista=[select id,name from account where createddate=today or lastmodifieddate=today];
for(account ac:trigger.new)
{
count=a.size();
ac.NumberofLocations__c=count;
if(count>2)
{
ac.adderror(‘reached limit today’);
}
}

}


7.can not insert/update/delete that user account object records

trigger scenario30 on Account (before insert,before update,before delete) {
user u=[select id,name from user where username=’naveensfdc98@gmail.com’];
if(u.id==userinfo.getUserId())
{
if(trigger.isdelete)
{
for(account a:trigger.old)
{
a.adderror(‘cant delete record’);

    }

    }

    if(trigger.isupdate)

    {

        for(account b:trigger.new)

        {

            b.adderror(‘can not update’);

        }

    }

    if(trigger.isinsert)

    {

        for(account c:trigger.new)

        {

            c.adderror(‘can not insert’);

        }

    }

}

}

8.Already existing records display an error message.

trigger scenario8 on Contact (before insert) {
listst=new list();

for(contact c:trigger.new)

{

   list<contact>a=[select id,name,Email,lastname from contact where Email=:c.Email];

    if(a.size()>0)

    {

        c.Email.adderror(‘already existing’);

    }

}

}

9.for loop without query.

trigger duplicatetrigger on Inputout__c (before insert) {
sets=new set();
for(Inputout__c op:trigger.new)
{
s.add(op.Doctor_Name__c);
}
listd=[select id,Doctor_Name__c from Inputout__c where Doctor_Name__c=:s];
setdupids=new set();
for(Inputout__c don:d)
{
dupids.add(don.Doctor_Name__c);
}
for(Inputout__c c:trigger.new)
{
if(c.Doctor_Name__c!=null)
{
if(dupids.contains(c.Doctor_Name__c))
{
c.Doctor_Name__c.adderror(‘already existing record’);
}
}
}


9.count of related contacts and accounts field display size

public class rollupsummery {

public static void increment(list<contact>con)

{

    set<id>ids=new set<id>();

    for(contact c:con)

    {

        ids.add(c.accountid);

    }

    list<account>a=[select id,name,NumberOfEmployees,(select id,lastname from contacts) from account where id=:ids];

    for(account ac:a)

    {

        ac.NumberOfEmployees=ac.contacts.size();

    }

    update a;

}

trigger:

trigger scenario11 on Contact (after insert) {
rollupsummery.increment(trigger.new); }

  1. when ever opportunity stagename =closedwon automatically update the account field rating=hot.

trigger scenario12 on Opportunity (after insert,after update) {
setids=new set();
listac=new list();
for(opportunity op:trigger.new)
{
ids.add(op.AccountId);

ac=[select id,name,rating from account where id=:ids];

    if(op.StageName==’Closed won’)

    {

        for(account a:ac)

        {

            a.Rating=’hot’;

        }

        update ac;

    }

    }

}


11.when ever account name is “SFDCForum” automatically update the contact all lastnames.

trigger scenario13 on Account (after update) {

    string names;

    list<contact>c=[select id,lastname,firstname from contact where lastname=:names ];

    for(account a:trigger.new)

    {

        names=a.name;

    }

for(contact con:c)

{

    con.lastname=names;

}

update c;

}


12.When ever a opportunity created record amount field is calculated by account total field

trigger scenario21 on Opportunity (after insert,after update,after delete) {
setids=new set();
mapopp=new map();
Decimal oldVal;
Decimal newVal;
if(trigger.isinsert)
{
for(opportunity op:trigger.new)

    {

        ids.add(op.AccountId);

        opp.put(op.AccountId, op);

    }

    list<account> acc=[select id,Total_Amount__c from account where  id=:ids];

    for(account a:acc)

    {

        if(a.Total_Amount__c==null )

        {

        a.Total_Amount__c=opp.get(a.Id).amount;

        }

        else

        {

        a.Total_Amount__c= a.Total_Amount__c+opp.get(a.Id).amount;

        }

    }

    update acc;

}

if(trigger.isUpdate)

{

for(opportunity op:trigger.new)

    {

        ids.add(op.AccountId);

        opp.put(op.AccountId, op);

        newVal=op.Amount;

    }

    for(Opportunity  ops:trigger.old){

        oldVal=ops.Amount;

    }

    list<account> acc=[select id,Total_Amount__c from account where  id=:ids];

    for(account a:acc)

    {

        if(a.Total_Amount__c==null )

        {

        a.Total_Amount__c=opp.get(a.Id).amount;

        }

        else

        {

        a.Total_Amount__c= a.Total_Amount__c+opp.get(a.Id).amount-oldVal;

        }

    }

    update acc;

    }

}
}

13.when ever a create a lead object automatically converted account ,contact,opportunity.

trigger scenario19 on Lead (after insert) {
listacc=new list();
listcon=new list();
listop=new list();
for(lead l:trigger.new)
{
account a=new account();
a.Name=l.lastname;
a.Phone=l.Phone;
acc.add(a);
contact c=new contact();
c.LastName=l.Name;

    con.add(c);

    opportunity o=new opportunity();

    o.Amount=l.AnnualRevenue;

    o.CloseDate=system.today();

    o.StageName=’closed won’;

    op.add(o);

}

insert acc;

insert con;

insert op;

}


14.when ever create a contact automatically update opportunity fields.

trigger scenario17 on Contact (after insert) {
listop=[select id,name,stagename,Description,amount from opportunity limit 50];
for(contact c:trigger.new){
for(opportunity o:op)
{
if(o.amount<5000||o.Amount==null)
{
o.amount=5000;
o.Name=o.Name+’Mr’;
o.StageName=’prospecting’;

        }

        else{

        o.Amount=o.Amount+1000;

        o.Name=o.Name+’Dr’;

    }

    update o;

    } 

}

}

  1. What is Action poller in salesforce.

public class actionpoller1 {
public datetime dateandtime{get;set;}
public void datetimemethod()
{
dateandtime=system.now();

Visualforce page :

<apex:page controller=”actionpoller1″>

    <apex:form>

        <apex:pageBlock id=”pb”>

            <apex:actionPoller action=”{!datetimemethod}” reRender=”pb” interval=”5″ />

             time:{!dateandtime}

                refresh 5 mins

           </apex:pageBlock>

  </apex:form>

</apex:page>

16. What is Action : status

public class actionstatus {

Integer count = 0;
public PageReference incrementCounter() {

count++;

return null;

}

public Integer getCount() {

return count;

}

}

visualforce page:

<apex:page controller=”actionstatus”>

<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=” (processing…)” stopText=”(completed)”/>

</apex:form>

</apex:page>



17.What is Aggregate functions in salesforce?

public class aggregatefunctions {
public listac{get;set;}
public integer count{get;set;}
public decimal sum{get;set;}
public decimal min{get;set;}
public decimal max{get;set;}
public aggregatefunctions()
{
ac= [select id,name,AnnualRevenue from account where name=:’naveen’];
count=[select count() from account];
aggregateresult res=[select sum(AnnualRevenue)sumt,min(AnnualRevenue)mint,max(AnnualRevenue)maxt from account ];
sum=(decimal)res.get(‘sumt’);
min=(decimal)res.get(‘mint’);
max=(decimal)res.get(‘maxt’);

}

Visualforce page:

<apex:page controller=”aggregatefunctions” >

    <apex:form >

        <apex:pageBlock >

            <apex:pageBlockSection >

                <apex:pageBlockTable value=”{!ac}” var=”n”>

                    <apex:column value=”{!n.name}”/>

                    <apex:column value=”{!n.AnnualRevenue}”/>

               </apex:pageBlockTable>

                   </apex:pageBlockSection>

            {!sum}

            {!min}

            {!max}

        </apex:pageBlock>

    </apex:form>

</apex:page>


18.Sending email outbound email message

public class emailprogramme1 {
public void myemails()
{
messaging.SingleEmailMessage m1=new messaging.SingleEmailMessage();
string[] toadd=new string[]{‘naveengorentla1@gmail.com’};
string[] tocc=new string[]{‘naveen123sfdc@gmail.com’};
m1.setToAddresses(toadd);
m1.setCcAddresses(tocc);
m1.setSubject(‘accenture’);
m1.setPlainTextBody(‘this is interview call letter’);
messaging.email[] m2=new messaging.Email[]{m1};
messaging.sendEmail(m2);
}

}

Executions:

emailprogramme1 v=new emailprogramme1();
v.myemails();

18.Outbound message pdf file.

public class emailprogramme2 {
public void emailbody()
{
messaging.SingleEmailMessage m1=new messaging.SingleEmailMessage();
string[] toadd=new string[]{‘naveengorentla1@gmail.com’};
m1.setToAddresses(toadd);
m1.setSubject(‘Pdf file’);
m1.setPlainTextBody(‘THIS IS BILL OF TELEPHONE’);
messaging.EmailFileAttachment m2=new messaging.EmailFileAttachment();
pagereference p=page.page1;
blob body=p.getContentAsPDF();
m2.setBody(body);
m2.setFileName(‘jan-feb-march’);
messaging.EmailFileAttachment[] eft1=new messaging.EmailFileAttachment[]{m2};
m1.setFileAttachments(eft1);
messaging.Email[] m3=new messaging.Email[]{m1};
messaging.sendEmail(m3);

}

Output :

emailprogramme2 v=new emailprogramme2();
v.emailbody();

19.sending email template to outbound message

public class emailprogramme3 {
public void emailmethod()
{
messaging.SingleEmailMessage m1=new messaging.SingleEmailMessage();
emailtemplate et=[select id from emailtemplate where name=’doctor’ ];
m1.setTemplateId(et.Id);
contact c=[select id,lastname,phone from contact where phone=’999′];
m1.setTargetObjectId(c.id);
Inputout__c D=[select id,Doctor_Name__c from Inputout__c limit 1];
m1.setWhatId(D.Id);
messaging.Email[] m2=new messaging.Email[]{m1};
messaging.sendEmail(m2);

}

}

output:
emailprogramme3 v=new emailprogramme3();
v.emailmethod();


20.Sending email trigger.

trigger sendingmailtrigger on Inputout__c (before insert) {
for(Inputout__c i:trigger.new)
{
if(i.Check_box__c==true)
{
messaging.SingleEmailMessage m1=new messaging.SingleEmailMessage();
string[] toadd =new string[]{‘naveengorentla1@gmail.com’};
m1.setToAddresses(toadd);
m1.setSubject(‘accenture’);
m1.setPlainTextBody(‘this is interview call letter’);
messaging.Email[] mail1=new messaging.Email[]{m1};
messaging.sendEmail(mail1);

}

    }

}

Salesforce Lightning and LWC Interview Questions


1.How to call a controller method in javascript?

var action=component.get(“methodname”)

2.What is the use of do init method?

It will be loaded on loading of lightning applicationIt  is pretty much similar to constructor.


3.What is the use of attribute?

Attribute is like a variable. If you want to store the datathen we should go with attribute.

4.What is bounded expression?

We will able to get the new value. syntax: {!v.attribute name}


5.What is unbounded expression?

we will not able to get the new value. syntax:{#v.attributename}

6.What is the use of AuraEnabled annotation?

if you want to access the data in the lightning applicationthen we should write AuraEnabled annotation->we will not able to access the data in lightning application without auraEnabled


7.What is the use of global action in the controller?

$A.enqueueAction(action)It’s used to execute the server side logic


8.Can we write void method in lightning?

No


9.How to get the response from callback?

reponse.getReturnValue()

10.How to  get the state in controller?

response.getState()


11.Why helper method is a best practice in lightning?

It’s used for re usability.


12.What is reusability in lightning?

We will able to access the value from one method to other method.
method1:

function(component){var name=’sfdcscenarios’;this.method2(name);
},

method2:

function(name){//reusabilityconsole.log(‘name from method1 is’+name);}

13.Does it happens in the controller?

No. It will happens in the helper.


14.what framework lightning will follow?

aura framework.


15.How many tags we have in lightning?

ui tagsLightning tags.


16.What is exends=”force:slds”?

It will acquire the properties of lightning design system?

17.What happens if you don’t put exends=”force:slds”  in lightning application?

It will look like normal html file.


18.What is v in attribute?

It’s a value provider. If you want to access the value from the attribute then we willuse {!v.attrname} or{#v.attributename}


19.When we should go with unbounded expression?

If you are simply dealing with read operation then we should go withunbounded expression

20. Does reusability is possible in  controller?

No


21.What is Lightning component bundle?


component controller helper design svg Documentation style renderer.


22.What is renderer?

If you want to override the standard rendering mechanism in salesforce lightningthen we should go with renderer.


23.What are the events in salesforce lightning?

1.component event
2.application event
3. system events

24..Which interface should you use if you want to get the id of the record from the record Detail page?


force:hasRecordId

25. can we call one component to another component?

Yes,we can call.


26.how to call lightning component in visual force page?


<aura:application access=”GLOBAL” extends=”ltng:outApp”>
    <aura:dependency resource=”c:FlipCard”/>
</aura:application>
*Add the <apex:includeLightning /> component to your Visualforce page.
*Reference a Lightning app that declares your component dependencies with $Lightning.use().
*Write a function that creates the component on the Visualforce page with $Lightning.createComponent().

27.how to pass the parameters in controller?


action.setParams

28.How to  Navigate From One Lightning Component to Another Lightning Component?


“e.force:navigateToComponent”

29. How to go from one lightning page to another lightning page through a click?


 var urlEvent = $A.get(“e.force:navigateToURL”);

30.Best practices for lightning?


1.Do not put so many console logs.
2.Make the use of Salesforce lightning design system for consistent ui design.
3.Make the use of Lightning data services to avoid server calls for Dml operations.2.
4.Use unbounded expressions if the data across components are not required to be in synch.
5.Before you decide to use a third-party library in a Lightning component, you should reevaluate if you really need that library. DOM manipulation libraries (like jQuery) and UI libraries (like Bootstrap or jQuery UI) in particular may no longer be needed when working with the Lightning Component Framework.
6.When possible, use the (sprite-based) Lightning Design System icons (using <lightning:icon> and <lightning:buttonIcon>) instead of custom icons.
7.Salesforce is slower for users who have debug mode enabled. So, do not enable in Production.
8.When appropriate consider passing the data in different components(using attributes,events or methods) rather than retrieving the same data in different components.
9.When making a call to the server limit the columns and rows of the result set. Only select the columns you need.
10.Set a limit on the query and provide paging mechanisum if needed. Don’t return huge number of rows at once.
11.Consider combining several requests(actions) in a single composite request.
Cache the data when possible.
12.Caching the data at the client side can significantly reduce the number of server round trips and improve the performance tips. A storable action is a server action whose response is stored in the in the client cache so that subsequent requests for the same server method with the same set of arguments can be accessed from that cache.
13.Try to limit number of event handlers in your Lightning component. As you can guess, multiple event handler means your component would be busy in listening event changes resulting in performance overload.
14.Always try to use a component event instead of an application event, if possible. Component events can only be handled by components above them in the containment hierarchy so their usage is more localized to the components that need to know about them. Application events are best used for something that should be handled at the application level, such as navigating to a specific record. Application events allow communication between components that are in separate parts of the application and have no direct containment relationship.
15.Use helper methods.
16.To improve runtime performance, set @AuraEnabled(cacheable=true) to cache the method results on the client. To set cacheable=true, a method must only get data. It can’t mutate data.

30. Where we can use Lightning Components?


We can use Lightning Components in the following places:
1.Drag-and-drop Components in the Lightning App Builder and Community Builder.
2.Add Lightning Components to Lightning Pages.
3.Add Lightning Components to Lightning Experience Record Pages.
4.Launch a Lightning Component as a Quick Action.
5.Override Standard Actions with Lightning Components.
6.Create Stand-Alone Apps.

31. Which interface should you use if you want your component to be available for all pages?


You can use the flexipage:availableForAllPageTypes interface.

32. Which interface should you use if you want to override a standard action?


You will need to use the Lightning:actionOverride interface.

33.Which interface should you use if you want your component to be available only on the record home page?


You will need to use the flexipage:availableForRecordHome interface.

34.Which interface should you use if you want your component to be used a tab?


You will need to use the force:appHostable interface.

35.Which interface should you use if you want your component to be used a quick action?


You will need to use the force:lightningQuickAction interface.

36.How can you call the controller method based on a component load?


“<aura:handler  name=”init” value=”{!this}” action=”{!c.doInitialization}”/

37. What are component events?


Component events are events which are fired by child components and handled by the parent component. We can make use of this event when we need to pass a value from a child component to parent component.

38. What are application events?


Application events can be fired from any component and can be handled by any component. They do not require any kind of relationship between the components, but these components must be a part of a single application.

39. What is force:recordData, and what are its advantages?


force:recordData is a standard controller of a Lightning Component. We can perform an operation such as creating a record, editing a record,deleting a record using force:recordData. If we are using force:recordData, it identifies and eliminates the duplicate request going to the server if they are requesting for the same record data (which in turn improves performance).

40.What are the phases in component events propagation?

There are two phases in component event propagation.
1.Bubble Phase
2.Capture Phase

41.  What are the phases in application events propagation?

1.Bubble Phase
2.Capture Phase
3.Default Phase

42.How do the bubble phase and the capture phase propagate?

Bubble phase: propagates from Bottom to Top.
Capture phase: propagates from Top to Bottom.

43.What is Aura:method in Salesforce Lightning component?

we can directly call a child component controller method from the parent component controller method using Aura:method. This method is used to pass value from parent component controller to the child component controller.

44.What is Lightning:overlayLibrary in Salesforce Lightning component?

To create a modal box we use Lightning:overlayLibrary. To use Lightning:overlayLibrary in component we need to include tag <lightning:overlayLibrary aura:id=”overlayLib”/> in component, here aura:id is unique local id. Modal has header,body and footer which are customizable.

45. what are the lightning webcomponent bundle?

LWC bundle contains an HTML file, a JavaScript file, and a metadata configuration file and these files are created once we create a Lightning web component.We can also create a .css file for styling purpose and We can also create SVG file for the purpose of displaying icon.

46.What are the types of decorators in lightning web components?

We have 3 Decorators in Lightning Web Components.
1) @api

2) @track

3) @wire

47.  Is there any limit on how many component to have in one Application ?

There is no limit.

48. Is Lightning Components replacing Visualforce ? 

No.

49. What are the advantages of lightning ?

The benefits include an out-of-the-box set of components, event-driven architecture, and a framework optimized for performance.
Out-of-the-Box Component Set -: Comes with an out-of-the-box set of components to kick start building apps. You don’t have to spend your time optimizing your apps for different devices as the components take care of that for you. Rich component ecosystem-: Create business-ready components and make them available in Salesforce1, Lightning Experience, and Communities.
Performance – :Uses a stateful client and stateless server architecture that relies on JavaScript on the client side to manage UI, It intelligently utilizes your server, browser, devices, and network so you can focus on the logic and interactions of your apps.
Event-driven architecture -: event-driven architecture for better decoupling between components
Faster development – : Empowers teams to work faster with out-of-the-box components that function seamlessly with desktop and mobile devices.
Device-aware and cross browser compatibility – : responsive design,supports the latest in browser technology such as HTML5, CSS3, and touch events.

50. How can we  deploy components to production org ?

we can deploy component by using managed packages, Force.com IDE, Force.com Migration Tool or Change Sets.

51. How we can access Custom Label in Lightning?

Syntax : $A.get(“$Label.namespace.labelName”)

52. How we can use component in the community builder?

Implements “forceCommunity:availableForAllPageTypes” interface on the component.

Asynchronous Apex Interview Questions

1.Can we call the batch in to another batch apex?

Yes, we can call from finish method.

2.Can we call batch apex in to another batch in excute method?

Only in batch class finish method, We can call another batch class. If you will call another batch class from batch class execute and start method, then Salesforce will throw below runtime error.

System.AsyncException: Database.executeBatch cannot be called from a batch start, batch execute, or future method.

3.Can we call the batch apex from triggers in salesforce?

Yes, it is possible. We can call a batch apex from trigger but we should always keep in mind that we should not call batch apex from trigger each time as this will exceeds the governor limit this is because of the reason that we can only have 5 apex jobs queued or executing at a time.

4.Can we call webservice callout from batch apex?

To make a Webservice callout in batch Apex, we have to implement Database.AllowsCallouts interface.

5.How many times start,execute,finish methods will excute in batch apex?

Start method,finish method one time, execute method it depends on requirement. Based on the batch size and data retrieved in Start method.

6.What is the Batch executions limit per day?

The maximum number of batch executions is 250,000 per 24 hours.

7.Can we call the future method in batch class?

No,we can’t call.

8. Is Future method support primitive data types? Why sobject parameters not supported?

The reason why sObjects can’t be passed as arguments to future methods is that the sObject might change between the time you call the method and the time it executes. In this case, the future method will get the old sObject values and might overwrite them.

9.How can I perform Callouts from Future methods?

We need to add a parameter callout=true in @future.

10.Can I write a future call in Trigger?

Yes.

11.What are the limitations of future methods?

It is not a good option to process large numbers of records.

Only primitive data types supported.

Tracing a future job is also typical.

Can’t call future from batch and future contexts, 1 call from queueable context is allowed.

12.What is future method?

Use of future methods to isolate DML operations on different sObject types to prevent the mixed DML error. Each future method is queued and executes when system resources become available. That way, the execution of your code doesn’t have to wait for the completion of a long-running operation. A benefit of using future methods is that some governor limits are higher, such as SOQL query limits and heap size limits

NOTE :-
1) Methods with the future annotation must be static methods

2) can only return a void type

3) The specified parameters must be primitive data types, arrays of primitive data types, or collections of primitive data types

4) Methods with the future annotation cannot take sObjects or objects as arguments.

5) You can invoke future methods the same way you invoke any other method. However, a future method can’t invoke another future method

6) No more than 50 method calls per Apex invocation

7) Asynchronous calls, such as @future or executeBatch, called in a startTest, stopTest block, do not count against your limits for the number of queued jobs

8) The maximum number of future method invocations per a 24-hour period is 250,000 or the number of user licenses in your organization multiplied by 200, whichever is greater

9) 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 synchronousl

13.How does Queueable Apex differ from Future methods?

Queueable Apex is similar to future methods in that they’re both queued for execution, but they provide us these additional benefits.

When you queue a Queueable Apex, you get a job ID, that can be used to trace it easily, which is not possible in case of future methods.

You can use non-primitive datatypes in Queueable Apex, like objects and sObjects, which is not possible in case of future methods, because it supports only primitive data types as params.

You can chain jobs, by calling another starting a second job from a running job, which is not possible in case of future methods, because we can’t call another future method from a future context.

14.Can you write a sample Queueable Job?

Create a class, implement the Queueable interface, and override the execute method.

public class QueueableApexExample implements Queueable {
public void execute(QueueableContext context) {
//some process
}
}

15.How can I use this Job Id to trace the Job?

Just perform a SOQL query on AsyncApexJob by filtering on the job ID.

AsyncApexJob jobInfo = [SELECT Status,NumberOfErrors FROM AsyncApexJob WHERE Id=:jobID];

16.Can I do callouts from a Queueable Job?

Yes, you have to implement the Database.AllowsCallouts interface to do callouts from Queueable Jobs.

17.How many numbers of jobs, I can queue using System.enqueueJob() at a time?

You can add up to 50 jobs to the queue with System.enqueueJob in a single transaction in Synchronous apex. In asynchronous transactions, you can add only one job to the queue.

18.Can I call Queueable from a batch?

Yes, But you’re limited to just one System.enqueueJob call per execute in the Database.Batchable class. Salesforce has imposed this limitation to prevent explosive execution.

19.If I have written more than one System.enqueueJob call, what will happen?

System will throw LimitException stating “Too many queueable jobs added to the queue: N”

20.I have a use case to call more than one Queueable Jobs from a Batch apex, how can I achieve it?

Since we can’t call more than one Queueable Job from each execution Context, We can go for scheduling the Queueable Jobs.

The approach is we need to first check how many queueable jobs are added in the queue in the current transaction by making use of Limits class. If the number has reached the limit, then call a schedulable class and enqueue the queueable class from the execute method of a schedulable class.

How to deactivate trigger in Production

Requirement : Consider the consequences of disabling a trigger in the production environment during work hours. It is highly recommended to perform this during off-hours. Also, disable access to the application to non-administrators during the maintenance period.

In certain circumstances, we need to deactivate trigger temporary or permanently. But, if you open the trigger in Salesforce production environment, you will not see Edit and Delete button.

screenshot from production org.

screenshot from sandbox org.


So, how to deactivate trigger in production? In short, deactivate the same trigger in sandbox and deploy it to production. You can deploy with Ant, Force.com IDE, or simple Change Set.

after inactive trigger deployed to production

The other option is to keep the trigger active, but comment all the content. Although this is not ideal, but you can use the same concept to remove any logic in Apex Class.

Reference : https://help.salesforce.com/articleView?id=000327373&type=1&mode=1

Overview of Packages

package is a container for something as small as an individual component or as large as a set of related apps.

After creating a package, you can distribute it to other Salesforce users and organizations, including those outside your company.

Packages come in two forms—unmanaged and managed:

Unmanaged packages: 

Unmanaged packages are typically used to distribute open-source projects or application templates to provide developers with the basic building blocks for an application.

Once the components are installed from an unmanaged package, the components can be edited in the organization they are installed in.

The developer who created and uploaded the unmanaged package has no control over the installed components, and can’t change or upgrade them.

Unmanaged packages should not be used to migrate components from a sandbox to production organization. Instead, use Change Sets.

As a best practice, install an unmanaged package only if the org used to upload the package still exists. If that org is deleted, you may not be able to install the unmanaged package.

Managed packages :

Managed packages are typically used by Salesforce partners to distribute and sell applications to customers.

These packages must be created from a Developer Edition organization.

Using the AppExchange and the License Management Application (LMA), developers can sell and manage user-based licenses to the app.

Managed packages are also fully upgradeable.

Managed packages also offer the following benefits:

  1. Intellectual property protection for Apex
  2. Built-in versioning support for API accessible components.
  3. The ability to branch and patch a previous version.
  4. The ability to seamlessly push patch updates to subscribers.
  5. Unique naming of all components to ensure conflict-free installs.

Packages consist of one or more Salesforce components, which, in turn, consist of one or more attributes.

Components and their attributes behave differently in managed and unmanaged packages.

Unmanaged and Managed Packages:Managed and Unmanaged Packages

Components :

A component is one constituent part of a package. It defines an item, such as a custom object or a custom field. You can combine components in a package to produce powerful features or applications. In an unmanaged package, components are not upgradeable. In a managed package, some components can be upgraded while others can’t.

 

Attributes :

An attribute is a field on a component, such as the name of an email template or the Allow Reports checkbox on a custom object. On a non-upgradeable component in either an unmanaged or managed package, attributes are editable by both the developer (the one who created the package) and the subscriber (the one who installed the package). On an upgradeable component in a managed package, some attributes can be edited by the developer, some can be edited by the subscriber, and some are locked, meaning they can’t be edited by either the developer or subscriber.

 

Reference : https://developer.salesforce.com/docs/atlas.en-us.packagingGuide.meta/packagingGuide/