Lightning Data Service – Standard Controller for Lightning Components

Best Practices for Salesforce Lightning Component. How Lightning Data Service can improve Lightning Component performance and solve inconsistent data problem without writing single line of Apex code. Demo source code, image and slides included.

If you have worked on Visualforce and started playing with Lightning Component, you must have identified one important missing feature, which is standard Controller.

Lets assume a scenario, you have two Lightning Components on Account page. One Lightning Component is used to show some fields and other component is used to edit same record.

Problem 1 :

To achieve this, both Lightning components would invoke Apex method separately at the cost of performance, by issuing duplicate server calls. Below image depicts problem, where multiple Lightning component requests same content by making separate server calls.

Lightning Components - Duplicate Server Calls
Lightning Components – Duplicate Server Calls

Continue reading “Lightning Data Service – Standard Controller for Lightning Components”

System mode or God mode in Apex – Gotchas

Gotchas of System mode or God mode in Apex and its impact by using “With sharing” keyword in Salesforce

In many of my previous implementations I have used advantage of Apex code running in System mode however never tried how far it can go in terms of capabilties. There is no specific Salesforce documentation which can explain that what is allowed or not allowed in System mode.

In this post, we will go through some scenario and will try to understand what really is possible in Apex System mode and when it can fail.

Before diving more lets discuss how many types of mode do we have in Apex ?

User Mode : As per this Salesforce post, all Profile level permissions, sharing rules and Field level security are enforced in Apex if it runs in User mode. Standard Controller and Anonymous Apex runs in User mode.

System Mode : Same post conforms that custom controller, trigger, Apex class, controller extension works in System mode. Means eventhough user does not have necessary profile level permission, record level permission or field level permission, but still they can perform any operation on it.

Continue reading “System mode or God mode in Apex – Gotchas”

All about Upsert and External ID in Dataloader and Apex – Videos

You may be wondering that there are tons of articles available for upsert operation and what is need of one more blog post. I wanted to note everything important about upsert operations using datalaoder and Apex with identified gotchas at single place, and that’s why its here 🙂 .

External ID is field in Salesforce to say that this field is primary key in external Database which can be used to identify that external record exists in Salesforce or not ? There are many benefits of external key like :

  • It can be used to identify if record exists or not and record automatically inserted or updated using upsert operation
  • Upsert operation is supported by Dataloader, Apex and API
  • Any field marked as external id is indexed and can be used in SOQL or report filter
  • You can create Parent child record in single statement in Apex

Using Upsert operation to create/update child record and relate to existing parent record with help of External Id

Lets assume that you have list of contacts and Account in external SQL Server database and you want to import those Account and contact weekly. It is possible that you have already imported contacts previously so don’t want to duplicate records if already created in Salesforce. To solve this problem we can use external Id on Contact and use upsert operation on dataloader. Let’s assume external Id field on Contact is “SQL_Server__Id__c” (I am assuming that Account records in Salesforce also have external Id and records are already imported. Same below steps can be used to import Account record as well). Continue reading “All about Upsert and External ID in Dataloader and Apex – Videos”

Salesforce interview questions – Part 19

Salesforce interview questions for developers and admins around Apex, Visualforce, getting Salesforce object name on basis of Id, Apex API limits

181. Lets consider your custom Object named “Training__c” has field “Trainer__c”. You have set some default value in that field. Will that default value apply to new record created by apex code ?
OR
How to make sure that record created from apex code should respect default value of fields ?
OR
Default value in field from Apex code.
Ans :

After API 20, it should automatically populate However there is known issue for same here, click here if it impacts you.
Workaround :
If Default value of field is not getting populated by Apex then we have to use “Dynamic Apex”.  Create instance of object from sObjectType like shown below:

Training__c tr= (Training__c) Training__c.sObjectType.newSObject(null, true);

//Check if Value in field "Trainer__c" is default value
System.assertEquals('Jitendra', tr.Trainer__c);

182. What is best practice to refer dynamic custom messages in Visualforce with multi-language support ?
Ans :
Using Custom Label or OutputField or InputField tag, Platform itself will take care of internationalization. However in some cases, Message needs to be dynamic at the same time it should also support muti-language. In Custom Label, we cannot save dynamic String.

Let’s assume we want to show message something like “DEVELOPERNAME is not authorized to access this page”.
Here, Developername should be dynamically changed in visualforce which supports multilanguage. For each developername, it is not feasible to create custom labels. So below workaround can be used :

Step 1 : Create a Custom Label with text “{0} is not authorized to access this page“. In every language, dynamic value should represented by {0}.

Step 2 : In Controller of Visualforce write something like this :

String developerName = 'Some DeveloperName';
String message = String.format(Label.DEVELOPERNA, new String[] { developerName });

Continue reading “Salesforce interview questions – Part 19”

Send Email with Generated PDF as attachment from Trigger – before Winter 16

There may be scenario in Salesforce that you need to send a Visualforce page rendered as PDF as a part of Email Attachment. This will be very easy if you want to perform this using Controller or Extension class, we just have to call getContentAsPDF() method of PageReference class and use returned blob data as a attachment in Email.

Update – 21 Oct 2015 (Winter 16)

After Winter 16 release, this solution will not work as getContent() method is treated as callout and if we try to call it from Async Apex or Rest API in this case, it will not return pdf content.

This solution will only work for you if you have not enabled critical update “PageReference getContent() and getContentAsPDF() Methods Treated as Callouts” in your Salesforce organization.

Note : If this solution is not working for you then try this.

If we are talking about achieving same in Trigger then it would be problem. Trigger does not support getContent() method of PageReference class. If you are thinking to use getContent() in future call then again we are not lucky, because @future methods does not support it. Also Apex job doesn’t support this method.

Now, I hope you understood that in which situation we are 🙂

So, In this article, I am going to explain how to resolve this issue. Not exactly resolve but workaround for above problem.

Solution is very simple, We will expose apex method as a REST API. Code for sending email will be written in APEX based REST API and our Trigger will call this method asynchronously using @future annotation. Continue reading “Send Email with Generated PDF as attachment from Trigger – before Winter 16”

FAQ and Best Practices of Test Classes in Apex

Here I am going to share few answers related to Test Classes, which is being asked many times to me by novice Programmers. Please feel free to post Comments if your question is not answered here. I will try my best to add those Questions in this article. If you want to learn Test Class from very basic, you can check this article also.

  1. Best Practices for Test Classes
  2. Use of SmartFactory to auto generate test data
  3. Test method of Controller Extension for StandardController
  4. Test method of Controller Extension for StandardSetController
  5. Why getSelected() method of StandrdSetController is not working
  6. sample Template of class which generates Dummy Data
  7. checking Error Page Messages in Test Classes
  8. Setting Visualforce Page Parameter

What are some Best Practices while writing Test Classes ?

Well, It differs from person to person, as every programmer has its own style of writing code. However I will list few of mine.

  • Very important and first, “Test Coverage Target Should not be limited to 75%”. It is not about coverage, It is about testing complete functionality. It will be always better if your code fails during test execution, It will be less devastating than failing functionality after product release.
  • If possible Don’t use seeAllData=true, Create your Own Test Data.
  • Always use @testSetup method dedicated to create test records for that class. This is newly added annotation and very powerful. Any record created in this method will be available to all test methods of that class. Using @testSetup method will improve test execution performance by creating test records only once for that class. If you are not using this, means test record is created in each TestMethod which will be very slow. Read this Salesforce documentation for more information.
  • Create Different Class which will create Dummy Data for testing, and use it everywhere (You have to be very careful, as sometimes it may slow down test class execution by creating unnecessary data which does not require by every test methods. So few developer prefer test data creation per Test class)
  • If your Object’s Schema is not changing frequently, you can create CSV file of records and load in static resource. This file will act as Test data for your Test Classes.
  • Use As much as Assertions like System.AssertEquals or System.AssertNotEquals
  • Use Test.startTest() to reset Governor limits in Test methods
  • If you are doing any Asynchronous operation in code, then don’t forget to call Test.stopTest() to make sure that operation is completed.
  • Use System.runAs() method to enforce OWD and Profile related testings. This is very important from Security point of View.
  • Always try to pass null values in every methods. This is the area where most of program fails, unknowingly.
  • Always test Batch Capabilities of your code by passing 20 to 100 records.
  • Use Test.isRunningTest() in your code to identify that context of class is Test or not. You can use this condition with OR (||) to allow test classes to enter inside code bock. It is very handy while testing for webservices, we can generate fake response easily.
  • @TestVisible annotation can be used to access private members and methods inside Test Class. Now we don’t need to compromise with access specifiers for sake of code coverage.
  • End your test class with “_Test”. So that in Apex Class list view, Main class and Test class will come together, resulting easy navigation and time saver.

Continue reading “FAQ and Best Practices of Test Classes in Apex”

How to access ListView in Apex | Using StandardSetController for Pagination

There are scenario in project lifecycle where developer creates SOQL or Dynamic SOQL to return expected result. Also if requirement changes they go back and change existing code to reflect updated SOQL. If you are good developer and avoid to change Apex code at most you will save your SOQL in “Custom Settings” and utilize in Dynamic SOQL.

However, There is very good design Developer can suggest to client. Instead of going to your code and changing code for new requirement, how it sounds if we can utilize existing List View inside Apex or Visualforce only 🙂 ? It will solve lots of problems and if requirement changed, just change or create new Listview and it will reflect in your Visualforce code. We can almost have same functionality like Navigation buttons and Paging without writing any complex code logic, thanks to StandardSetController capabilities.

There is also very good article on Salesforce blog on various approaches suggested for pagination and one of them is using StandardSetController.

To keep article simple, I am posting complete Visualforce and Apex code with Comments inside. Account object is used as an example here. Continue reading “How to access ListView in Apex | Using StandardSetController for Pagination”

Consuming External Web Service in Apex – Salesforce

One of the feature we have in Salesforce is that we can easily consume External Web Services. In this article, we will learn step by step demo of consuming Web Service in Apex. There are many public websites available to consume Web Service and one of them, I am using in this article is http://www.webservicex.net , from this location we are using Stock Quote Webservice. To consume this, we need WSDL.

The Web Services Description Language (WSDL) is an XML-based interface description language that is used for describing the functionality offered by a Web Service.

WSDL have to be downloaded from this location. We need this WSDL in later part of this tutorial.

Once, WSDL is downloaded and saved on local drive. We have to go to Salesforce and navigate to “Setup | Develop | Apex Classes”. On right hand side, you will find button named as “Generate from WSDL”. This button will generate equivalent Apex class to support Webservice call. In some Programming languages, these classes are known as Proxy classes or Stubs.

When we click on “Generate from WSDL” button, it will prompt for WSDL File. Select WSDL file downloaded previously and click on “Parse WSDL” button. On next page you will get this error : “Failed to parse wsdl: Found more than one wsdl:portType. WSDL with multiple portType not supported”.

In some cases you may also get error like : “Failed to parse wsdl: Found more than one wsdl:binding. WSDL with multiple binding not supported”.

Continue reading “Consuming External Web Service in Apex – Salesforce”

Apex Interview Question – Salesforce – Part 16

151. Give Sample Code Snippet of Apex that that will show that how Parent and Child record can be inserted in Single Statement ?
Ans : It can be done with help of External Id.

Date dt = Date.today().addDays(7);
Opportunity newOpportunity = new Opportunity(Name = 'shivasoft', StageName = 'Prospecting', CloseDate = dt);

/*
Create the parent reference. Used only for foreign key reference  and doesn't contain any other fields. If we provide any other value it will give following error

System.DmlException: Insert failed. First exception on row 1; first error: INVALID_FIELD, More than 1 field provided in an external foreign key reference in entity: Account: []
*/

Account accountReference = new Account(MyExtID__c = 'SHIVA1234567');
newOpportunity.Account = accountReference;

//  Create the Account object to insert.  Same as above but has Name field.  Used for the insert.
Account parentAccount = new Account(Name = 'Shiva', MyExtID__c = 'SHIVA1234567');

Database.SaveResult[]
    results = Database.insert(new SObject[] {  parentAccount, newOpportunity });


152 . Which SOQL statement can be used to get all records even from recycle bin or Achieved Activities?
Ans : We will need “ALL Rows” clause of SOQL.
Sample :

SELECT COUNT() FROM Contact WHERE AccountId = a.Id ALL ROWS

153. How can you lock record using SOQL so that it cannot be modified by other user.
Ans : we will need “FOR UPDATE” clause of SOQL.
Sample :

 Account [] accts = [SELECT Id FROM Account LIMIT 2 FOR UPDATE];

Continue reading “Apex Interview Question – Salesforce – Part 16”