Wednesday 30 December 2015

How to set your own Created Date for the inserted salesforce record in test class - Salesforce Spring 16 Release

Until Winter 16, You won't able to set created date for records which you are creating in Test class. By default, Created Date will be the current date while running test.

Beginning from Spring 16, You can set your own custom date as Created Date in test class.

Syntax:

  1. setCreatedDate(Id recordId, Datetime createdDatetime);

Sample Code:

  1. @isTest
  2. private class SetCreatedDateTest {
  3.     static testMethod void testSetCreatedDate() {
  4.         Account a = new Account(name='myAccount');
  5.         insert a;
  6.         Test.setCreatedDate(a.Id, DateTime.newInstance(2012,12,12));
  7.         Test.startTest();
  8.         Account myAccount = [SELECT Id, Name, CreatedDate FROM Account
  9.                              WHERE Name ='myAccount' limit 1];
  10.         System.assertEquals(myAccount.CreatedDate, DateTime.newInstance(2012,12,12));
  11.         Test.stopTest();
  12.     }
  13. }


Note:

1. All database changes are rolled back at the end of a test.
2. You can’t use this method on records that existed before your test executed. 
3. You also can’t use setCreatedDate in methods annotated with @isTest(SeeAllData=true), because those methods have access to all data in your org.
4. This method takes two parameters—an sObject ID and a Datetime value—neither of which can be null.

Reference:

Tuesday 15 December 2015

How to check list size in visualforce page

Most of peoples wanted to display the table if the list has records. For this you can use the below approach,

Apex Class:

  1. public class AccountController
  2. {
  3.     public List<Account> accList{get; set;}
  4.     public AccountController()
  5.     {
  6.         accList = [SELECT Id, Name FROM Account LIMIT 10];
  7.     }
  8. }

Visualforce Page:

  1. <apex:page controller="AccountController">
  2.     <apex:pageBlock title="Account List" >
  3.         <apex:outputPanel rendered="{! IF(ISBLANK(accList), false, true) }">
  4.             <apex:pageBlockTable value="{!accList}" var="acc" rendered="{!accList.size > 0}">
  5.                 <apex:column headerValue="Account Name"> {!acc.Name} </apex:column>
  6.             </apex:pageBlockTable>
  7.         </apex:outputPanel>
  8.     </apex:pageBlock>
  9. </apex:page>

Two conditions are checked in the above visualforce page,

Condition 1:

{!IF(ISBLANK(accList), false, true)}

This will ensure to prevent from displaying table in the following conditions,
1. LIST not yet initialized. 
2. LIST has been initialized, but no records.

Condition 2:

{!accList.size > 0}

Table will be displayed only if the LIST contains at least one record.

Thursday 10 December 2015

PageReference getContent() and getContentAsPDF() Methods Behave as Callouts - Critical Updates Salesforce

Important Note:

Please note down the below points as per the salesforce documentation,

To ensure a smooth transition, each critical update has an opt-in period, which ends on the auto-activation date that’s displayed on the Critical Updates page in Setup. During this period, you can manually activate and deactivate the update as often as you need to evaluate the impact on your organization and modify affected customization. After the opt-in period has passed, the update is automatically activated. 

Released history about Actual changes on getContent() and getContentAsPDF() methods:

In Summer ’15 we made a change to the behavior of the getContent() and getContentAsPDF() methods of the PageReference object. This change was released as a critical update named “PageReference getContent() and getContentAsPDF() Methods Behave as Callouts” and was scheduled for auto-activation in Winter ’16. 

Auto activation date:

This critical update will automatically activated in Spring 16 release.

Note: On the scheduled auto-activation date, Salesforce permanently activates the update. After auto-activation, you cannot deactivate the update.

Faced issue:

Recently we have faced an real time issue due to this critical update. The issue follow as,

     From visualforce page, I have inserted a record and created a save point. After a savepoint i am rendered a page as PDF by using getContentAsPDF method. So i have received an error as "You cannot make callout after creating a Savepoint".

How to test a Restful web services in Salesforce by using Advanced Rest Client chrome app

      The below article will help you to create a basic Rest API class to insert an account record in salesforce by creating a method with @HttpPost annotation. Also this guide will help you to test the functionality by using using Advanced Rest Client chrome app. 

Step 1: 

Create a REST API class with @HttpPost annotation method. 

  1. @RestResource(urlMapping='/AccountMapping/*')
  2. global with sharing class RESTAccountController {

  3. @HttpPost  
  4.   global static String createNewAccount(String accountName, String accountNumber) {
  5.      System.debug('Account Name: '+accountName);
  6.      System.debug('Account Number: '+accountNumber);
  7.      try
  8.      {
  9.          Account acc = new Account();
  10.          acc.Name = accountName;
  11.          acc.AccountNumber = accountNumber;
  12.          insert acc;
  13.          return 'Account has been inserted succesfully: '+acc.Id;
  14.      }
  15.      catch(DMLException de)
  16.      {
  17.         return de.getDmlMessage(0);
  18.      }
  19.                
  20.      return null;
  21.   }
  22. }

Note:
The @RestResource annotation is used at the class level and enables you to expose an Apex class as a REST resource.

1. The URL mapping is relative to https://instance.salesforce.com/services/apexrest/
2. URL mapping is case-sensitive

Read this documentation well before setting up urlMapping

Step 2: 

Install Advanced Rest Client from the below link,


Note: You can also use Postman tool, if you like.

Step 3:

Create a "Connected App" by referring this documentation.

After you created the "Connected App", Go to Create --> Apps --> Connected App --> Select your connected app which you created.

Your connected app looks like below,


After you created a connected app ensure the app permission is given at profile level. Also Copy the "Consumer Key" and "Consumer Secret" code for authentication in Advance Rest Client.

Step 4:

Open Advanced REST Client app in Chrome and follow the below steps.

Steps to obtain an access token:

URL:
https://login.salesforce.com/services/oauth2/token

METHOD:
POST

BODY:
grant_type=password&client_id=3MVG9Ad93Bn17huFzcp2LseGauyeShr6X9TmixGMGQ5MuS2hoPxlEHAvyVQzZVzdhClK6WUFdMY8FzXqNxc4&client_secret=2536602822064617993&username=testuser@force.com&password=psmu97VQzZVzdhClK6WUFdMY8FzXqNxc

Client_id and Client_secret: Copied from connected app.
Username: Your salesforce user name.
Password: Your salesforce account password with security token.
(If you are in White list IP ranges, then you don’t need to add a security token with password).

CONTENT TYPE:
application/x-www-form-urlencoded

Sending Request:


Access Token:

After you send a request your will get an access token. This will looks like below,



Copy the access token from the response.

CALLING REST SERVICE:

REST URL:
https://na15.salesforce.com/services/apexrest/AccountMapping

Adding access token:

Authorization  OAuth "Your access token"

JSON Body:

{"accountName":"Arunkumar",
"accountNumber":"128393"}

Response From Sever:


Thanks for reading this post...!

Activities: Assign Tasks to a Queue Salesforce Lightning

Salesforce announced to assign Tasks to a Queue beginning from Spring'20 release. How does it work? In Setup, enter Queues in th...