Sunday 18 December 2016

Custom roll up summary on lookup _ count number of attachments attached on the tasks.

 Count number of attachments attached on the tasks.

 the field (NumberOfAttachments__c)updates when you edit the attachment and save the attachment. Also works if deleting the attachment updates the field. 

trigger CountAttachment on Attachment (after insert, after update, after delete, after undelete) {
    // Contains the IDs of all the parent tasks
    Set<Id> parentTaskIdSet = new Set<id>();

    if (trigger.new != null)
    {
        for (Attachment a: trigger.new)
        {
            parentTaskIdSet.add(a.parentId);
        }
    }
    
    if (trigger.old != null)
    {
        for (Attachment a: trigger.old)
        {
            parentTaskIdSet.add(a.parentId);
        }
    }    
    
    // List of tasks that needs to be updated
    List<Task> parentTaskList = [SELECT id, (SELECT id FROM Attachments) FROM Task WHERE id in: parentTaskIdSet];
    
    for (Task t: parentTaskList)
    {
        t.NumberOfAttachments__c = t.Attachments.size();
    }
    
    update parentTaskList;
}
-----------------------------------------------------------------------------
when you create attachments on a task, you need to edit the task, create the attachments, then save the task. When you are saving the task, we are probably writing over the trigger's update on task. So to fix this we will actually need to write another trigger, this time on Task. And since we will be updating task in the task trigger, we need a class to prevent recursion. Here's what the trigger on Task would look like:

-------------------------------------------------------------------------------
trigger UpdateAttachmentCount on Task (after insert, after update) {
    
    if (checkRecursive.runOnce())
    {
        List<Task> taskList = new List<Task>();
        Set<ID> taskIDSet = new Set<ID>();
        
        if (trigger.old != null)
        {
            for (Task t: trigger.old)
            {
                taskIDSet.add(t.ID);
            }
        }
        
        if (trigger.new != null)
        {
            for (Task t: trigger.new)
            {
                taskIDSet.add(t.ID);
            }
        }
        
        // Query for the attachment children of the tasks
        taskList = [SELECT id, (SELECT id FROM attachments) FROM Task WHERE ID in: taskIDSet];
    
        for (Task t: taskList)
        {
            t.NumberOfAttachments__c = t.Attachments.size();
        }
        
        update taskList;
    }
-----------------------------------------------------------------------------

the class that prevents recursion looks like:
------------------------------------------------------------------------------
public Class checkRecursive{
    private static boolean run = true;
    public static boolean runOnce(){
        if (run){
            run = false;
            return true;
        }
        else
        {
            return run;
        }
    }
}

Tuesday 18 October 2016

Salesforce Certified Platform App Builder - Summer '16 Release Exam Dumps

App Builder Maintenance:
 S.No
Question
Answer
1
Universal Containers has an app page active for Salesforce1. What two ways can the App Builder activate the app page in Lightning?
>> Use the activation feature in the Lightning App Builder
>> Add the app page’s Lightning Page tab to a custom Lightning Experience navigation menu in Setup.
2
What three chart types are available in Lightning Experience?
>> Funnel
>> Combo
>> Scatter
3
Universal Containers wants to relate a Contact to multiple Accounts. What are the expected two behaviors when the App Builder enables this feature?
>> On Account records, the Related Contact list includes direct Contact and all indirect Contacts.
>> On Contact records, the Related Account list includes primary Account and all indirectly related Accounts.
4
Where are two places Salesforce Knowledge Articles are accessed?
>> Salesforce1
>> Salesforce Classic
5
Which two objects can be customized on a Lighting Experience record page?
>> Lead >> Opportunity


Wednesday 21 September 2016

example using LIST and MAP | When to use Map Over List | When do we use set, map, list

While working on Developer forum i found lots of question for List ,Set and Map,  like below
1) When we should use Map over the list
2) When do we use set, Map,List
3) Bulkify code with Map
4) Using Maps and Sets in Bulk Triggers
5) Use of Map in Apex class.
6) Map over list to avoid query inside for loop

Solution :-

List, Set, Map are called collections in Apex:
List : A list is an ordered collection
1) so use list when you want to identify list element based on Index Number.
2) list can contain Duplicates

EX: List<Account> accList = new List<Account>();

Set A set is an unordered collection 
1) Do not contain any duplicate elements. So, use set if you want to make sure that your collection should not contain Duplicates.

EX: Set<Account> accSet = new Set<Account>()

 
Set<String> setString = new Set<String>();
// Add two strings to it
setString .add('item1');
setString .add('item2');

Map : A map is a collection of key-value pairs 
Each unique key maps to a single value. Keys can be any primitive data type, while values can be a primitive, sObject, collection type or an Apex object.

EX: Map<Id, Account> accMap = new Map<Id, Account>();

Map<Integer, String> mapOfString = new Map<Integer, String>();
mapOfString.put(1, 'Amit');               
mapOfString.put(2, 'Rahul');              
System.assert(mapOfString.containsKey(1)); 
String value = mapOfString.get(2); 
System.assertEquals('Rahul', value);
Set<Integer> s = mapOfString.keySet();



Map<StringString> myMap = new Map<StringString>{'a' => 'b''c' => 'd'};






Example 1:-  Using trigger populate the Account Field on the Contact record (only insert scenario) 

If we use List and not Map

Apex Class

trigger ContactTriggerWithList on Contact (before insert) 
{
Set<Id> SetAccountId = new Set<Id>(); // Use set to collect unique account ID

for(Contact con: Trigger.new) 
{
 if(con.AccountId != null) 
 {
  SetAccountId.add(con.AccountId); // add Account in Set
 }
}

if( SetAccountId.size() >0 ) 
{
 List<Account> listAccount = [ Select Id, Name, Type from Account where Id IN :SetAccountId ]; // Query Related Account
 
 for(Contact con: Trigger.new) 
 {
  if(con.AccountId != null)
  {
   for(Account acc: listAccount)
   {
    if(con.AccountId == acc.Id)
    {
     con.Type__c = acc.Type;
    }
   }
  }
 }
} 
}

 
NOTE:- In this we are using List of Accounts, Where we have to loop through the matching Account every time to populate the Type__c in the second for loop. In this case need to use nested loop.

To Above the Nested Loop We can use the Map .

Same Trigger using the Map:


trigger ContactTriggerWithMap on Contact (before insert) 
{
    Set<Id> SetAccountId = new Set<Id>();
    for(Contact cont: Trigger.new) 
 {
        if(cont.AccountId != null) 
  {
            SetAccountId.add(cont.AccountId);
        }
    }
    
    if(SetAccountId.size() > 0 ) 
 {
        Map<Id, Account> mapAccount = new Map<Id, Account>([Select Id, Name, Type from Account where Id IN :SetAccountId ]);
        for(Contact cont: Trigger.new) 
  {
            if(cont.AccountId != null && mapAccount.containsKey(cont.AccountId) ) 
   {
                cont.Type__c = mapAccount.get(cont.AccountId).Type;
            }
        }
    }
}
NOTE:- Here we are using map of Account so we can directly use the Map to get the Account record. No need of 2nd for loop here

Tuesday 5 July 2016

Salesforce Developer Certification Maintenance 401 - Spring 16 Release Exam Dumps


Salesforce Certified Force.com Developer - Spring '16 Release Exam
1 of 5.
 Which Quick Actions can contain a "Custom Success Message?"
  Choose 2 answers
A.  Send an Email
B.  Update a Record
C.  Log a Call
D.  Visit a website

 Create a Record, Update a Record, and Log a Call action
 BC
Update a Record
 Log a Call


Salesforce Certified Force.com Developer - Spring '16 Release Exam
Time Remaining: 29:00
2 of 5.
 What is true about dataloader?
  Choose 3 answers
 
A.  It can be used with SAML Authentication.
B.  It can be used with Password Authentication.
C.  It can be used with OAuth Authentication
D.  It can be used with only a PC.
E.  It can be used with both Mac and PC.


C. It can be used with OAuth Authentication
B. It can be used with Password Authentication.
E. It can be used with both Mac and PC.


Salesforce Certified Force.com Developer - Spring '16 Release Exam
Time Remaining: 28:15
3 of 5.
 Which standard field can be updated using formal rules in process builder?
 
A.  Deleted
B.  Owner Id
C.  Id
D.  Created Date

B. Owner Id


Salesforce Certified Force.com Developer - Spring '16 Release Exam
Time Remaining: 27:10
4 of 5.
 What must be true when accessing a user's private reports and dashboards?
  Choose 2 answers
 
A.  Having the "Manage All Private Reports and Dashboards" permission.
B.  Using the "allPrivate" with the "scope" condition in a SOQL query.
C.  Having the "Administrator Access to Private Files" permission.
D.  Using the "allPrivate" with the "where" condition in a SOQL query.

A B
Having the "Manage All Private Reports and Dashboards" permission.
Using the "allPrivate" with the "scope" condition in a SOQL query.


New “Set by Record” Access for Shared Files
When a link is created between a file and a record with inferred sharing type via the API, the access level when sharing the file in
the UI is Set by Record. The Set by Record access level means that access to the file is determined by the level of access to the
record that the file is linked to. This feature is available in both Lightning Experience and Salesforce Classic



Salesforce Certified Force.com Developer - Spring '16 Release Exam
Time Remaining: 25:06
5 of 5.
What is true about the file sharing "Set by Record?"
 
A.  It is used to infer sharing via the parent record.
B.  It is used to infer sharing via the record owner.
C.  It is used to infer sharing via the record type.
D.  It is used to infer sharing via the associated record.


D. It is used to infer sharing via the associated record.

Friday 3 June 2016

stop sending email to setTargetobjectId in single email message even using Email template

child__c (child) is custom object Contact (parent) lookup relationship.
i need to send a mail to email field which is present in child object with email template.
when ever we are using Email template setTargetObjectId is mandatory .
if our requirement is like we dont want to send mail to TargetObjectId , only need to send to email field which is present on child object.

to achieve this we need to use setTreatTargetObjectAsRecipient(false) Boolean method so it will stop sending email to TargetObjectId .


setTargetObjectId(targetObjectId)

Required if using a template, optional otherwise. The ID of the contact, lead, or user to which the email will be sent. The ID you specify sets the context and ensures that merge fields in the template contain the correct data.

setTreatTargetObjectAsRecipient(treatAsRecipient)

Optional. If set to true, the targetObjectId (a contact, lead, or user) is the recipient of the email. If set to false, thetargetObjectId is supplied as the WhoId field for template rendering but isn’t a recipient of the email. The default is true.

Signature

public void setTreatTargetObjectAsRecipient(Boolean treatAsRecipient)

Visual force page:

<apex:page controller="WrapperClsOnContactMass">
    <apex:form >
    <apex:pageMessages >
    </apex:pageMessages>
        <apex:pageBlock >
            <apex:pageBlockTable value="{!wrapperObj}" var="x">
                <apex:column value="{!x.conobj.name}"/>
                <apex:column value="{!x.conobj.email__c}"/>
                <apex:column >
                  <apex:inputcheckbox value="{!x.checkBox }"/>
                </apex:column>
            </apex:pageBlockTable>
            <apex:pageBlockSection >      
                               
            <apex:commandButton value="SendEmail" action="{!sendEmail}"/>

            </apex:pageBlockSection>
            </apex:pageBlock>
             <apex:pageBlock >
           
           <apex:pageBlockSection columns="1">
    <apex:pageBlockSectionItem >
        <apex:outputLabel value="Select template" for="template"/>
      <apex:selectList value="{!selectedTemplateId}" id="template" size="1">
                     <apex:actionSupport event="onchange" reRender="table" />
             <apex:selectOptions value="{!myPersonalTemplateOptions}"/>
         </apex:selectList>
            </apex:pageBlockSectionItem>
    <apex:pageBlockSectionItem >
      <apex:outputLabel value="File" for="file_File"/>
     <!-- <apex:inputFile id="file_File" value="{!fileBody}" filename="{!fileName}"/> -->
  <!--   <apex:inputFile value="{!fileBody}" fileName="{!filename }" contentType="{!conType}"/> -->

    </apex:pageBlockSectionItem>

   <!--<apex:commandButton value="sendEmail" action="{!sendEmail}" id="table"/> -->

               </apex:pageBlockSection>
         
           </apex:pageBlock>
    </apex:form>
</apex:page>

Apex Class :

public with sharing class WrapperClsOnContactMass {

    public List<WrapperClassEx> WrapperList{get;set;}
    public String selectedTemplateId { get; set; }
    public WrapperClsOnContactMass(ApexPages.StandardController controller) {
        
    }
    public WrapperClsOnContactMass() {

    }
    public List<SelectOption> getMyPersonalTemplateOptions() {
        List<SelectOption> options = new List<SelectOption>();
        for (EmailTemplate t : [
            select Id,Name 
            from EmailTemplate
            // Each User has a 'My Personal Templates' folder
            // of EmailTemplates, whose Id is the User's Id
            //where FolderId = :UserInfo.getUserId()
        ]) {
            options.add(new SelectOption(t.Id,t.Name));
        }
        return options;
    }
    public List<WrapperClassEx> getwrapperObj(){
        List<Child__c> conList =[select id, name, email__c,physition__r.email  from Child__c limit 5];   
        WrapperList = new List<WrapperClassEx>();
        for(Child__c con: conList){
            
            
            WrapperList.add(New WrapperClassEx(con,false));  
        }
        return WrapperList;  
    }
    
    public class WrapperClassEx{
        
       public WrapperClassEx(){
            
        }
       public Child__c conObj{get;set;}
       public Boolean checkBox{get;set;}
       public WrapperClassEx(Child__c conRec, boolean SelectedBox){               
          conObj= conRec;
          checkBox = SelectedBox;
       }
    }
        
       public void sendEmail(){
         List<Messaging.SingleEmailMessage> lstEmailId=new List<Messaging.SingleEmailMessage>();
         EmailTemplate et = [Select Id from EmailTemplate where id =:selectedTemplateId ];
          
         for(WrapperClassEx w: WrapperList){
            if(w.checkBox == true){
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                mail.setToAddresses(new String[] {w.conObj.Email__c});
                 mail.setTemplateId(et.Id);
                 mail.setWhatId(w.conObj.id);
                 mail.setTargetObjectId(w.conObj.physition__r.id);
                 mail.setTreatTargetObjectAsRecipient(false);
                mail.setReplyTo('hareeshn2008@magicsw.com');
                //mail.setplainTextBody('Hello');
               

                mail.setSenderDisplayName('Your Company Name');
                lstEmailId.add(mail);    
                                
                    
            }
          }
            if(lstEmailId.size()>0){
                try{
                    Messaging.sendEmail(lstEmailId);
                    ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.Confirm,'Sent!'));
                    
                }Catch(Exception ee){
                    ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.Error,ee.getMessage()));
                }
                
            }
       }     
}

Saturday 21 May 2016

the Salesforce Certified Platform App Builder Transition exam

Salesforce.com has introduced 3 new exams among others in the recent past. These exams are:
1. Salesforce Certified Platform App Builder
2. Salesforce Certified Platform Developer I
3. Salesforce Certified Platform Developer II
Salesforce has tried to break out the declarative capabilities of the platform and utilize the App Builder cert to test our knowledge about it.

If you hold the developer certification, then you are eligible to write a short transition exam to get the new App Builder cert.

Please Refer Below imp links:

http://www.salesforce.com/campaigns/success-services/developer-certification-in-progress.jsp
http://www.salesforce.com/campaigns/success-services/certified-force-developers.jsp


STUDY GUIDE :
Salesforce Certified Platform App Builder 
Transition Exam
Study Guide



Pre-Requisites and additional info:
  1. You should have passed the Developer certification. ðŸ™‚
  2. You are not expected to have programming experience (APEX, Visualforce, Lightning components using APEX or JS). But great if you do.
  3. But you ARE expected to have the following experience:
    • Familiarity with the declarative capabilities of the Force.com platform.
    • Awareness of Salesforce license types and the related considerations.
    • You know to design applications to support business processes and reporting requirements.
    • Familiarity with the social and mobile capabilities of the platform. Think Salesforce1.
    • Familiarity with the Salesforce development environments and the options available to deploy applications and manage changes on the Force.com platform.

Thursday 19 May 2016

Add or Remove rows dynamically Functionality using apex and visual force page salesforce

<apex:page controller="creatingListOfRecordsController" showHeader="false" sidebar="false">
    <apex:form >
   
        <apex:pageBlock title="Creating List Of Account Records">
        <apex:pageMessages ></apex:pageMessages>
            <apex:pageBlockButtons location="top">
                <apex:commandButton value="Add Row" action="{!addRow}" reRender="table" immediate="true"/>
            </apex:pageBlockButtons>
                <apex:pageBlockTable value="{!accountwrapperList}" var="page" id="table">
                    <apex:column headerValue="Name">
                        <apex:inputField value="{!page.account.name}"/>
                    </apex:column>
                    <apex:column headerValue="Phone">
                        <apex:inputField value="{!page.account.Phone}" />
                    </apex:column>
                    <apex:column headerValue="Action">
                        <apex:commandLink value="Delete" action="{!removingRow}" immediate="true">
                            <apex:param name="index" value="{!page.counterWrap}"/>
                        </apex:commandLink>
                    </apex:column>
                </apex:pageBlockTable>
                <apex:commandButton value="Save" action="{!saving}" />
           
        </apex:pageBlock>
    </apex:form>
    </apex:page>

apex class:
public with sharing class creatingListOfRecordsController {
   
    public list<Account> accountList{get;set;}
    public list<Accountwrapper> accountwrapperList{get;set;}
    public Integer counter{get;set;}
   
    public creatingListOfRecordsController(){
           counter = 0;
           accountList = new list<Account>();
           accountwrapperList = new list<Accountwrapper>();
           for(Integer i=0;i<5;i++){
               Accountwrapper actWrap = new Accountwrapper(new Account());
               counter++;
               actWrap.counterWrap = counter;
               accountwrapperList.add(actWrap);
             
           }
     
    }
   
    public PageReference addRow(){
        //accountList.add(new Account());
        Accountwrapper actWrap = new Accountwrapper(new Account());
       
        counter++;
        actWrap.counterWrap = counter;
        accountwrapperList.add(actWrap);
        return null;  
    }
    public PageReference removingRow(){
   
        Integer param = Integer.valueOf(Apexpages.currentpage().getParameters().get('index'));
       
        for(Integer i=0;i<accountwrapperList.size();i++){
            if(accountwrapperList[i].counterWrap == param ){
                accountwrapperList.remove(i);    
            }
        }
       
       
        counter--;
        return null;  
    }
   
    public PageReference saving(){
        list<Account> updateAccountList;
        updateAccountList = new list<Account>();
        if(!accountwrapperList.isEmpty()){
            for(Accountwrapper accountWrapper:accountwrapperList){
                updateAccountList.add(accountWrapper.account);
            }
        }
        if(!updateAccountList.isEmpty()){
            upsert updateAccountList;
        }
       ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.Info,'Record Saved Successfully.');
       ApexPages.addMessage(myMsg);
        return null;
    }
   
    public class Accountwrapper{
        public Account account{get;set;}
        public Integer counterWrap{get;set;}
       
        public Accountwrapper(Account act){
            this.account = act;
           
        }
    }
   
}

Friday 22 January 2016

salesforce interview questions and answers for experienced

  • Pictorial representation of internet is Cloud.
  • Cloud Computing is nothing but internet computing.
  • With this approach everything can be done in internet (Using Application, Developing Application and distributing the hardware), no need of any minimum hardware requirements and no need to install any software in local system.
  • Cloud Computing is an approach to provide the following services -
    1. SAAS (Software As A Service)
    2. PAAS (Platform As A Service)
    3. IAAS (Infrastructure As AService)             
      1. Salesforce is a company which provides a web based tool called Salesforce
      2. Salesforce by following the Cloud Computing approach, providing SAAS and PAAS
      3. SAAS: Providing Sales, Marketing and Call Center applications as a service
      4. PAAS: Providing Force.com platform in which we can develop Apex (Programming language similar to Core Java) and Visualforce (Mark up language similar to HTML) logic
        1. Number of DML statements per transaction: 150 (as a whole including insert, update, delete and undelete)
        2. Number of rows processed per DML stmt: 10000 
        3. Name three Governor Limits.
        4. When do you use a before vs. after trigger?
        5. What’s the maximum batch size in a single trigger execution?
        6. What are the differences between 15 and 18 digit record IDs?
        7. Provide an example of when a Custom Setting would be used during development.
        8. When should you build solutions declaratively instead of with code?
        9. Give an example of a standard object that’s also junction object.
        10. Describe a use case when you’d control permissions through each of the following:
          – Profiles
          – Roles
          – Permission Sets
          – Sharing Rules
        11. When should an org consider using Record Types?
        12. What are some use cases for using the Schema class?
        13. A trigger is running multiple times during a single save event in an org. How can this be prevented?
        14. Why is it necessary for most sales teams to use both Leads and Contacts?
        15. What is the System.assert method and when is it commonly used?
        16. What are the differences between SOQL and SOSL?
        17. Order the following events after a record is saved:
          – Validation rules are run
          – Workflows are executed
          – “Before” triggers are executed
          – “After” triggers are executed
        18. What is Trigger.old and when do you normally use it?
        19. When should you use a lookup instead of a master-detail relationship?
        20. What are the advantages of using Batch Apex instead of a trigger?
        21. What are the pros and cons when using a Workflow Rule Field Update vs. a Formula Field?
        22. What are the differences between a Map and a List?
        23. What are the advantages of using Batch Apex instead of a trigger?
        24. Describe a use case for Static Resources.
        25. Provide an example of when a Matrix report would be used. How about a Joined report?
        26. A group of users must be prevented from updating a custom field. What’s the most secure method of preventing this?
        27. When would you use the @future annotation?
        28. List three different tools that can be used when deploying code.
        29. When should an Extension be used instead of a Custom Controller?
        30. What are the advantages of using External Id fields?
        31. What are the uses of the <apex:actionFunction> tag?
        32. What are the differences between static and non-static variables in Apex?
        33. What are some best practices when writing test classes?
        34. What does the View State represent in a Visualforce page?
        35. What are three new features in the most recent Salesforce release?
        36. Describe the benefits of the “One Trigger per Object” design pattern.
        37. Write a SOQL query that counts the number of active Contacts for each Account in a set.
        38. Declaratively create logic in your org that prevents two Opportunities from being created on a single Account in a single day.
        39. Declaratively create logic in your org that prevents closed Opportunities from being updated by a non System Administrator profile.

customize omni channel logic to distribute cases based on Case Creation Date

Omni Channel queues distributes cases, based on Date/Time the case is assigned to the queue. we can customize this logic to look for some ...