Monday, October 23, 2017

Tips for passing Data Architecture & Management Designer (SU'17)

Today (22nd Oct'2017), I have successfully passed Data Architecture and Management Designer (SU17) and acquired Salesforce certified Application Architect credential.

I have faced total 60 questions. Unlike Sharing and Visibility exam there are no additional questions. It has taken around 100 hours of preparation mostly one and half months time frame.






Exam Objective

The Salesforce Certified Data Architecture and Management Designer exam has the following characteristics:
  • Content: 60 multiple-choice/multiple-select questions* (2-5 unscored questions may be added)
  • Time allotted to complete the exam: 90 minutes (time allows for unscored questions)
  • Passing Score: 67%
  • Registration fee: USD 400, plus applicable taxes as required per local law
  • Retake fee: USD 200, plus applicable taxes as required per local law
  • Delivery options: Proctored exam delivered onsite at a testing center or in an online proctored environment. Click here for information on scheduling an exam.
  • References: No hard-copy or online materials may be referenced during the exam.
  • Prerequisite: None

Preparing myself

Before I started my preparation, I have prepared a document and noted down all the points and advice mentioned by these guys. Thanks to all of them.


Topics I have received on Exam


  • Strategies for data migration, data archieval
  • How to resolve timeout issues
  • Skinny table
  • PK Chunking
  • Use of Bulk API
  • Use of rollup summary
  • Different types of locking and how to overcome those
  • Master data management
  • Reports and Dashboards
  • Integration with external system
  • Validation rule, workflow rule, outbound message.
  • Indexing
  • Use of External Ids
  • Use of AppExchange product and third party ETL tool
  • Field History tracking
  • Metadata API.
  • Analytic snapshot.
By the way, Salesforce recommended training guide doesn't cover 100% areas of the exam. Around 10-15% of the questions were outside of the material which I could assume so far.



Sunday, October 8, 2017

Visualforce webservice callout synchronously & asynchronously

Overview

Recently we have received a business case to perform a webservice callout from our Custom Visualforce page.

There are following ways we can make callout from Visualforce page.
  • Asynchronously
  • Synchrounously

Approach: Asynchronous callout (@future method)


From visualforce page, first we will verify all standard and business validations and then perform callout and any error message during save will be displayed on the UI.

For example if Customer Name is blank if will show the error message in the UI and will not perform callout.

Visualforce

From commandbutton action, save method will get called.

<apex:page id="MyVisualforcePage" controller="MyController"  showHeader="false">
    <apex:pageMessages id="msgId"/>   
    <apex:form id="MyForm">
        <apex:inputText id="customerNm" value="{!CustomerName}"/><br/>
        <apex:commandButton value="Save" action="{!save}" reRender="msgId"/>
    </apex:form>
</apex:page>

Controller

In the save method, it will verify if customer name is blank and show the error in UI, otherwise call performRestCallout().


public class MyController
{
 public String CustomerName {get;set;}
 
 public PageReference save()
 { 
  if(String.isBlank(CustomerName))
  {
   ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.Error, 'Name cannot be null');
   ApexPages.addMessage(msg);
   return null;
  }
  else
  {
   //perpare JSON and then callout
   MyWebService.performRESTCallout(JSONString);
  }
  //navigate to view page
  PageReference pg =  (new ApexPages.StandardController (new CustomObject__c(Id=recordId))).view();
  pg.setRedirect(true);
  return pg;
 }
}

WebService Class

public class MyWebService
{
    @future(callout = true)
    public static void performRESTCallout(string JSONString)
    {
 //perform callout
    }
}

If any error messages from callout occurs that can be handled following ways:

(Taken from bob_buzzard's answer)

(1) Post a chatter message to the user
(2) Send an email to the user
(3) Create a custom object/setting, add the message to that and write a visualforce page for the sidebar that displays the message.


Approach: Synchronous callout (using commandbutton oncomplete method)


Salesforce doesn't allow to commit data and perform callout in a single transaction as it will throw error message "Uncommited task is pending".

The following approach works well.

From commandbutton's action, we will call save method, it will commit the data and then oncomplete method with the help of javascript and actionFunction we will perform second action and hence perform callout. So, there will be two different transactions and no more errors.

That looks good!!!

Now, what will happen if during save, UI validation and business validations to be performed and if any error occurs that needs to be shown on UI and will not perform oncomplete call.

Secondly, since it is synchronous call, so any exceptions or errors returned from webservice call must be displayed on the UI.

Here is the most tricky part (where I have spend hours to find the work around, finally Eric from StackExchange helped me retaining the error message in UI. My question & Eric's answer).

Visualforce

Here conditionally oncomplete needs to be called.


  • So hasError property has been defined on controller. 
  • Access hasError values in the outputPanel which is getting rendered from commandbutton reRender attribute
  • Using oncomplete javascript function, first verify if error exists (hasMessages == 'false') and then call submit action with the help of actionFunction.

Error will be displayed like this:



Thats nice!!!

<apex:page id="MyVisualforcePage" controller="myExampleController"  showHeader="false">
    <apex:pageMessages id="msgId"/>
    <script>
        function performCallOutMethod()
        {
            if(hasMessages == 'false') {
                performCallOut();
            }
        }
    </script>
    <apex:form id="myForm">
        <apex:actionFunction name="performCallOut" action="{!submit}" reRender="script-block,msgId"/>
        <apex:inputText id="customerNm" value="{!CustomerName}"/><br/>
        <apex:commandButton value="Save" action="{!save}"
                            oncomplete="return performCallOutMethod();" reRender="script-block,msgId"/>
    </apex:form>
 <!-- this is main trick -->
    <apex:outPutPanel layout="block" id="script-block">
        <script>
            var hasMessages = '{!hasError}';
        </script>
    </apex:outPutPanel>
</apex:page>

Controller

Save method will perform validations and then will commit the changes into database. If Customer name is blank then it will show error message.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public class MyController
{
 public String CustomerName {get;set;}
 
 public Boolean hasError { 
  get { 
   return ApexPages.hasMessages(); 
  }  
 }
 
 public PageReference save()
 { 
         if(String.isBlank(CustomerName))
  {
          ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.Error, 'Name cannot be null');
   ApexPages.addMessage(msg);
   return null;
  }
                //commit all data here, not giving full code for simplicity.
                insert customObj;
  return null;
 }
 
 public PageReference submit()
 {
  try
  { 
   //prepare JSON string and perform callout
   MyWebService.performRESTCallout(JSONString);
   
   //navigate to view page
   PageReference pg =  (new ApexPages.StandardController (new CustomObject__c(Id=recordId))).view();
   pg.setRedirect(true);
   return pg;
  }
  catch (Exception ex)
  {
   System.debug('Error in submit ' + ex);
                        ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.Error, ex.getMessage());
                        ApexPages.addMessage(msg);
                        return null;
  }
 }
}

WebService Class

Just a simple method and if any error occurs it will be propagated to calling method and finally be displayed at UI.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public class MyWebService
{
 public static void performRESTCallout(string JSONString)
        {
  try
  {
   MyWebService.performRESTCallout(JSONString);
  }
  catch(Exception ex)
  {
   throw new CustomException(ex.getMessage());
  }
 }
}

Conclusion



Which approach to be taken for implementation it will be based on business scenarios, data volumes, performance and that is a separate topic all together.

Here, I have tried to put my proof of concepts and approach to perform callouts from Visualforce and necessary error handling.

Hope it helps!

Tuesday, July 25, 2017

Tips for passing Salesforce Certified Sharing and Visibility Designer




Today (24th July'2017) I have successfully passed after around 100 hours of studying which have taken around 4 weeks though I didn't get a chance to prepare everyday.

So, before preparing the exam, I have registered the exam and then started preparing exam.

Exam Outline

Content: 60 multiple-choice/multiple-select questions*

  • Time allotted to complete the exam: 120 minutes
  • Passing Score: 68%
  • Registration fee: USD 400; Retake fee: USD 200
  • Delivery options: Proctored exam delivered onsite at a testing center or in an online proctored environment. Click here for information in scheduling an exam.
  • References: No hard-copy or online materials may be referenced during the exam.
  • Prerequisite: None



I have faced 65 questions, some of the them are very descriptive and I was running out of time. Even if few questions I have marked for review to revisit, but didn't get time of review. But finally I am happy to see me passed.


Preparing myself


Before I started my preparation, I have prepared a document and noted down all the points mentioned by these guys which helped me focusing on certain areas.




And if anyone follows those blogs and prepare the way they have mentioned then anybody can pass this exam and I am really thankful to those guys.

I have also prepared an excel on Group Membership operation and sharing recalculation for my understanding and revision.






The worksheet can be downloaded from here : Notes on Designing Record Access

Topics I have received on Exam

  • Difference between profile and permission set
  • Use of System.runAs()
  • Login Hours and Login IP changes
  • How to restrict or grant access to the records by using Role Hierarchy, Public Groups, Team, Territory, Partners.
  • Default sharing model for Internal and External users
  • Given a code snippet to identify the security threat
  • When to use territory management
  • Encryption in rest and transit
  • Use of Protected Custom metadata types, Protected Custom settings, Crypto class
  • Locking related issues and how to overcome that.
  • Use of Salesforce Shield
  • Apex managed sharing and reason and when to use what.
  • Sharing Set
  • Manual sharing and what happens if ownership is changed.
  • Use of FLS, Recordtype, page layout, permission set and custom permissions
  • How reports and dashboards and files can be shared.
  • Listview

Read thoroughly following study materials: 


If you have a firm understanding then you can surely pass the exam.

Related Posts


Note: I have not used any dumps and didn't prepare those, so please don't ask me for dumps.

Wednesday, June 28, 2017

Send Email from Custom Button Click

Objective

Sometimes, we get a requirement to send email from Record detail page, clicking on Custom Button (naming Send Email).

I was answering this question in Salesforce Stackexchange Send email on Custom button click? and thought that it might help others.

Solution

Here is an approach to handle this requirement.

Create a Javascript Custom Button (Detail Page) button and use the following code:


{!REQUIRESCRIPT("/soap/ajax/31.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/31.0/apex.js")}
var message = new sforce.SingleEmailMessage(); 

message.targetObjectId = "{!Contact.Id}";
message.toAddresses = "{!Contact.Email}";
message.templateId = "00Xq0000000HwSw"; //predefined email template
message.whatId = "{!Case.Id}"; 

var result = sforce.connection.sendEmail([message]); 
if(result[0].success == 'true') 
{ 
    alert("Email sent successfully"); 
} else 
{ 
    alert("Sending failed"); 
} 
alert(result);

Note: Only User, Contact, Lead, or Person Account objects are allowed for targetObjectId

If you need to refer specific attributes then download Partner WSDL and refer complexType SingleEmailMessage



<complexType name="SingleEmailMessage">
<complexContent>
<extension base="tns:Email">
<sequence>
<element name="bccAddresses" minOccurs="0" maxOccurs="25" type="xsd:string" nillable="true"/>
<element name="ccAddresses" minOccurs="0" maxOccurs="25" type="xsd:string" nillable="true"/>
<element name="charset" type="xsd:string" nillable="true"/>
<element name="documentAttachments" minOccurs="0" maxOccurs="unbounded" type="tns:ID"/>
<element name="entityAttachments" minOccurs="0" maxOccurs="unbounded" type="tns:ID"/>
<element name="fileAttachments" minOccurs="0" maxOccurs="unbounded" type="tns:EmailFileAttachment"/>
<element name="htmlBody" type="xsd:string" nillable="true"/>
<element name="inReplyTo" minOccurs="0" type="xsd:string" nillable="true"/>
<element name="optOutPolicy" type="tns:SendEmailOptOutPolicy" nillable="true"/>
<element name="orgWideEmailAddressId" minOccurs="0" maxOccurs="1" type="tns:ID" nillable="true"/>
<element name="plainTextBody" type="xsd:string" nillable="true"/>
<element name="references" minOccurs="0" type="xsd:string" nillable="true"/>
<element name="targetObjectId" type="tns:ID" nillable="true"/>
<element name="templateId" type="tns:ID" nillable="true"/>
<element name="toAddresses" minOccurs="0" maxOccurs="100" type="xsd:string" nillable="true"/>
<element name="treatBodiesAsTemplate" type="xsd:boolean" nillable="true"/>
<element name="treatTargetObjectAsRecipient" type="xsd:boolean" nillable="true"/>
<element name="whatId" type="tns:ID" nillable="true"/>
</sequence>
</extension>
</complexContent>
</complexType>

It's a fun! Share this post to others in case it helps!

Monday, May 8, 2017

Update Case Action on feed based layout

Introduction

With the use of feed based layout and actions, user can perform multiple updates at one goal.

For example, if user wants to perform following updates in a single update button click event instead of multiple clicks.

- Change Case Owner
- Update Case Fields
- Update Case Comments.

The feed view action will look like this:


Solution


1. Create new Case Action called "Update Case"  as follows:

  • Setup --> Cases --> Buttons, Links and Actions.
  • Click New Action Button and enter following details


2. Click on Edit Layout and place desired fields on the layout


3. Create Feedback page layout and in the Quick Actions section, add this "Update Case" action.



4. Assign the page layout to respective profiles.

5. You can also track those fields from Chatter, for that follow these steps:
  • Setup --> Chatter --> Feed tracking
  • Choose Case object
  • Choose "Enable Feed Tracking" checkbox
  • Choose desired fields for feed tracking. You can select maximum 20 fields for tracking.


6. Now open a Case record and click on Feed icon


7. Select "Update Case" tab (refer 1st screen) and enter attribute values and click on Update.

8. System will update all the field values in one single update. 

9. You will see the updates in Feed (like below) as well as Case Details Page.


Saturday, April 1, 2017

Keyword Search Series : Custom Controller Pagination ~ easiest way

Motivation

So far we know, pagination can be easily be achieved by StandardSetController class.

I have seen cases where developer has a notion like until and unless we use controller extension and StandardSetController as an argument in Constructor, pagination is difficult to achieve. For this, I have tried this approach in Custom Controller with the search input from Visualforce screen.

Use Case


User will provide the input and clicking on Search button, the results will be displayed in paginated format. User can change the page size and system will fetch the records based on selected page size.

Solution

For the sake of learning, I have created a visualforce page as below.


Visualforce

It will take Opportunity Name as input search criteria and clicking on Search button it will pass to the controller.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<apex:page id="filterPage" controller = "FilterSearch">
 <apex:form style="overflow-y:auto;overflow-x:auto;margin-right: 5px;margin-left: 5px;margin-top: 3px;" id="searchForm">
        <apex:actionFunction name="refreshPageSize" action="{!refreshPageSize}" status="fetchStatus" reRender="searchBlock"/>
        
  <apex:outputLabel value="Search By Opportunity Name:"/>          
        <apex:inputText value="{!searchString}" label="Opportunity Name:"/>            
        <apex:commandButton value="Search " action="{!showAll}"/>
  
        <apex:pageBlock title="Results" rendered="{!showResult}" id="searchBlock"> 
            <apex:pageblockTable value="{!Opps}" var="a" id="tabId">  
                <apex:column>
     <a href="/{!a.id}" target="_blank"> {!a.name}</a>
    </apex:column>
    <apex:column rendered="false" id="id">
     <apex:outputField value="{!a.id}" />
    </apex:column>
    <apex:column headerValue="Account Name">
     <apex:outputField value="{!a.account.name}" />
    </apex:column>

    <apex:column headerValue="Stage">
     <apex:outputField value="{!a.stagename}" />
    </apex:column>

    <apex:column headerValue="Forecast Category" >
     <apex:outputField value="{!a.ForecastCategoryName}"  />
    </apex:column>

            </apex:pageBlockTable>
            <apex:panelGrid columns="8">             
                <apex:selectList value="{!size}" multiselect="false" size="1" onchange="refreshPageSize();">
                    <apex:selectOptions value="{!paginationSizeOptions}"/>
                </apex:selectList>           
                <apex:commandButton status="fetchStatus" reRender="searchBlock" value="<<" action="{!setCon.first}" disabled="{!!setCon.hasPrevious}" title="First Page"/>
                <apex:commandButton status="fetchStatus" reRender="searchBlock" value="<" action="{!setCon.previous}" disabled="{!!setCon.hasPrevious}" title="Previous Page"/>
                <apex:commandButton status="fetchStatus" reRender="searchBlock" value=">" action="{!setCon.next}" disabled="{!!setCon.hasNext}" title="Next Page"/>
                <apex:commandButton status="fetchStatus" reRender="searchBlock" value=">>" action="{!setCon.last}" disabled="{!!setCon.hasNext}" title="Last Page"/>
                <apex:outputText >{!(setCon.pageNumber * size)+1-size}-{!IF((setCon.pageNumber * size)>noOfRecords, noOfRecords,
                     (setCon.pageNumber * size))} of {!noOfRecords}
                </apex:outputText>                 
                <apex:outputPanel >                      
                </apex:outputPanel>
            </apex:panelGrid>                                      
      </apex:pageBlock> 
    </apex:form>    
</apex:page>


Custom Controller

It has following activities:

1. In the Constructor, assigning default page size and preparing the list of page size options.

2. showAll() - This method is getting called with Search button is clicked. In this method, searchString is getting collected and getting passed into dynamic query.

Now, main important part, this line, create QueryLocator object using Database.getQueryLocator(query) and assign that into ApexPages.StandardSetController constructor to create StandardSetController object.

Rest is easy. StandardSetController will take all burden for pagination.


setCon = new ApexPages.StandardSetController(Database.getQueryLocator(query));


3. getOpps() - This method return List of records based on pageSize.

4. refreshPageSize() - This method is getting called when paginated size is changed on screen.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
public class FilterSearch  
{
    public String searchString{get;set;}
    public Boolean showResult{get;set;}
    public Integer noOfRecords{get; set;}
    public Integer size{get;set;}
    public ApexPages.StandardSetController setCon{get;set;}    
    public List<SelectOption> paginationSizeOptions{get;set;}
 
    String errorStr = '';    
         
    /**
    * FilterSearch
    * Constructor to initiate the default values at the time of Loading
    */    
    public FilterSearch()
    {
        size=10; //default page size

  //pagination size options
        paginationSizeOptions = new List<SelectOption>();
        paginationSizeOptions.add(new SelectOption('10','10'));
        paginationSizeOptions.add(new SelectOption('20','20'));
        paginationSizeOptions.add(new SelectOption('30','30'));
              
    }
    
    public void showAll()
    {
        try
        {
            if(String.isNotBlank(searchString))
            {  
              //build SOQL query string
             String query='Select Id,Name, account.name, stagename, ForecastCategoryName FROM Opportunity WHERE Name LIKE \'%' + searchString + '%\' order by Name LIMIT 1000';
    
               //return querylocator to an instance of StandardSetController
                setCon = new ApexPages.StandardSetController(Database.getQueryLocator(query));            
                if(setCon.getResultSize() >0)
                {
                    showResult = true;
                }else{
                    showResult = false;
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO,'No Records Found.'));
                }        
            }            
        }catch(Exception ex)
        {
            errorStr ='Error Occured while Searching.';
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, 'errorStr:' +ex.getMessage()));
        }   
    }

    public List<Opportunity> getOpps() 
    {
        if(setCon.getResultSize() >0)
        {
          setCon.setPageSize(size);  
          noOfRecords = setCon.getResultSize();
          return (List<Opportunity>)setCon.getRecords();
        }else
        {
          return null;
        }
        return null;
    }
      
    /**
    * refreshPageSize
    * Changes the size of Pagination.
    * @param    
    * @return void
    */
    public void refreshPageSize() 
    {
        setCon.setPageSize(size);         
    }
}

Results



Hope it helps! and if so, then share with your friends.

Link to my answer in stackexchange: My Answer in Stackechange

Further Reading


Wednesday, March 29, 2017

Simple way to generate XML, parse and retrieve values from XML

Use Case

We usually get a requirement to store Salesforce records in XML format. Later, we may need to parse the XML and retrieve the data from XML and store them into a Map for future use.

Solution

I have created this class to generate some hard coded data. Later through usable parseXML method that has been parsed.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
public class XMLParserClass
{
    public Map<String, String> xmlDataMap = new Map<String,String>();
    
    public String generateXML()
    {
        Dom.Document doc = new Dom.Document();
        Dom.Xmlnode rootNode = doc.createRootElement('TestReport', null, null);
        
        Dom.Xmlnode headerNode = rootNode.addChildElement('header', null, null);
        //assign header attributes
        headerNode.setAttribute('id', 'TEST1'); 
        
        Dom.Xmlnode childNode = headerNode.addChildElement('detail', null, null);               
        childNode.setAttribute('id','CHILD1');              
        childNode.setAttribute('Amount','1000');  
        
        String xmlString = doc.toXmlString();
        System.debug('xmlString =' + xmlString);
        return xmlString;
    }
    
 //generated xml
 /*
    <?xml version="1.0" encoding="UTF-8"?>
    <TestReport>
    <header id="TEST1">
    <detail id="CHILD1" Amount="1000" />
    </header>
    </TestReport>
    */
 
 
    public void parserXML(String toParse)
    {
        xmlDataMap = new Map<String,String>();
        DOM.Document doc = new DOM.Document();
        try{
            doc.load(toParse);
            DOM.XMLNode root = doc.getRootElement();
            traverseThroughXML(root);
        }catch(Exception ex){
            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.Error, ex.getMessage());
            ApexPages.addMessage(msg);
       }  
    }
    
    /**
     * traverseThroughXML
     * This method traverse through the xml, read the data from XML.
     * @param
     * @return void.
     */
    private void traverseThroughXML(DOM.XMLNode node) 
    {
        if (node.getNodeType() == DOM.XMLNodeType.ELEMENT) 
        {
            System.debug('node.getName()=' + node.getName());
            if(node.getName().equalsIgnoreCase('detail'))
            {
                if (node.getAttributeCount() > 0) 
                { 
                  xmlDataMap.put(node.getAttributeValue(node.getAttributeKeyAt(0), node.getAttributeKeyNsAt(0))
                                ,node.getAttributeValue(node.getAttributeKeyAt(1), node.getAttributeKeyNsAt(1)));
                }
            }
            for (Dom.XMLNode child: node.getChildElements()) 
            {
              traverseThroughXML(child);
            }
        } 
    }
}

Usage

1
2
3
4
XMLParserClass cls = new XMLParserClass();
String xmlStr = cls.generateXML();
cls.parserXML(xmlStr);
System.debug(cls.xmlDataMap);

Outcome in Debug Log