Tuesday, September 13, 2016

Dynamic Apex in Salesforce

You can fetch all sobject and their field information in apex by using describe methods. Apex gives 2 data types for sobject and field information.
  1. Token: A lightweight, serializable reference to an sObject or a field that is validated at compile time.
  2. Describe Result: It contains all the describe information about sobject and fields. Describe result objects are not serializable, and are validated at runtime.
It is easy to move from a token to its describe result, and vice versa. Both sObject and field tokens have the method getDescribe which returns the describe result for that token.
On the describe result, the getSObjectType and getSObjectField methods return the tokens for sObject and field, respectively.

Finding All object in Organization

Schema getGlobalDescribe method returns a map that represents the relationship between all sObject names (keys) to sObject tokens (values).
For example:
Map<String, Schema.SObjectType> schemaMapOfOrg = Schema.getGlobalDescribe();
The map has the following characteristics:
  • It is dynamic, that is, it is generated at runtime on the sObjects currently available for the organization, based on permissions.
  • The sObject names are case insensitive. 
  • The keys use namespaces as required. The keys reflect whether the sObject is a custom object.
Creating sObjects Dynamically

If we need to create contact record dynamically, then use below code:
String typeName='Contact';
Schema.SObjectType objToken = Schema.getGlobalDescribe().get(typeName);
sobject son= objToken.newSObject();
son.put('firstname','Execute1');
son.put('LastName','Kumar');
son.put('Email','sunil.kumar2@in.gmail.com');
insert son;

Apex code to find all sobject and their fields

Apex code to generate SOQL to fetch all fields of an object

Monday, September 12, 2016

RecordTypeId using Describe & SOQL

RecordTypeId of an object can be determined by using 2 different options:

For example we will find out the recordtypeId of "Renewal" recordtype of opportunity.

By Using Describe:
Id renewalRecordTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('Renewal').getRecordTypeId();
Advantage: Saves on SOQL limits but uses a describe call.

By using SOQL:
Id renewalRecordTypeId =[select id from recordType where  sobjectType='Opportunity' AND DeveloperName='Renewal'].Id;
Advantage of SOQL: If in future, someone change the name of recordtype, the code will work as it refers developername.

Sunday, August 28, 2016

HighCharts in Visualforce Page

We can use interactive charts provided by HighCharts in Visualforce page. Here I am going to display line chart using highCharts.

For example, we will display the count of opportunity group by stage.

Download  js files from below mentioned URL and store it in static resource:

  • https://code.highcharts.com/highcharts.js
  • https://code.highcharts.com/modules/exporting.js
  • https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js

Create VF page "HighChartDemo" and apex class "HighChartDemoController". Below is VF page and apex class code:



Chart Snapshot:




HighCharts gives option to download chart in PNG, JPEG, PDF and SVG vector image.

Tuesday, June 14, 2016

Data Load through Command line Interface in Salesforce


Purpose: To insert, extract and then delete Accounts records from Salesforce.

Steps to, install data loader.

1.       Download Apex data loader. Navigate to Set up->Administration Set up->Data management->Data Loader. Click on Download Data Loader link.
2.       Install apex data loader setup.  C:\Program Files (x86)\salesforce.com\Apex Data Loader 23.0 will be default location while installing.

Below are the steps in order to achieve our requirement:

1. Create a folder and name it as “data Loader Demo” in E drive.
2. Generate Key File.
Open Command Prompt (Go to run-type cmd press enter), change directory to bin:
cd Program Files (x86)\salesforce.com\Apex Data Loader 23.0\bin>   press enter
Now type :
Encrypt   –g  randomtext


key will be generated, copy the key in notepad and save it as keyToEncrypt.txt in data Loader Demo folder. Note the path of this Key.txt file. In our case path is E:\Data Loader Demo\keyToEncrypt.txt

3. Encrypt Password and security token.
In command prompt, type
Encrypt   –e password+securitytoken  “ path of key.txt file”
For example:
Encrypt  –e  xxxxxx129k19YRftloxFbgBMkb6NZsNK  “E:\Data Loader Demo\keyToEncrypt.txt"



Save the encrypted password for later use.
In our case generated password is:
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx6c75bb5c73f60175181c7aa5d1441aee65c

4. Create 4 new  folders as Mapping files, Log files, extracted Accounts and Account data      folder in Data Loader demo folder


Create mapping files for insert and delete from Apex Data Loader GUI and copy paste in Mapping files folder


Create insertAccounts.csv file in Account data folder which will be inserted into salesforce.


Log files folder will be used to store success and error files.

5. Copy config.properties from below mentioned directory:
C:\Program Files (x86)\salesforce.com\Apex Data Loader 23.0\conf


Paste this file in “Data Loader Demo” folder.

Also copy process-conf.xml file from below mention directory to “Data Loader Demo folder”
C:\Program Files (x86)\salesforce.com\Apex Data Loader 23.0\samples\conf


Data Loader Demo folder:


6. Now edit process-conf.xml file in notepad:


7. Create Batch file to do the operation in bin folder.

Create a new text file with following content:

call process "E:\Data Loader Demo" accountInsert
call process "E:\Data Loader Demo" csvAccountExtractProcess
call process "E:\Data Loader Demo" AccountDeleteProcess


Save the file as autorundataloadcommandlineinterface.bat and store it in bin folder
Path : C:\Program Files (x86)\salesforce.com\Apex Data Loader 23.0\bin
     

8. Run the batch.
Open cmd, change the directory to bin “C:\Program Files (x86)\salesforce.com\Apex Data Loader 23.0\bin” and type autorundataloadcommandlineinterface.bat, and press enter



OR you can double click on bat file to execute the process.

Now check your log files and extracted Accounts folder to see success and error files and extracted account file.


Steps to schedule the data upload process or to start execution of bat file

1. Control Panel->System and Security->Administrative Tools->task scheduler->create basic task->







Browse > C:\Program Files (x86)\salesforce.com\Apex Data Loader 23.0\bin \autorundataloadcommandlineinterface.bat file and click next


            Click on finish.



Friday, May 13, 2016

Salesforce Interview Questions-Data Management Part-2

6. Can we avoid duplicates using apex data loader which we can do through import wizard?
No.

7. What is Bulk API?
The Bulk API is used to upload high volume of data (millions of records).
The Data Loader uses the SOAP-based Web Services API by default. To use the Bulk API instead, check “Bulk API” checkbox in apex data loader settings page.
When you check Bulk API checkbox, increases the batch (upto 10000 records) which is usually 200 in normal upload.
Hard delete bypasses the Recycle Bin, so deleted records do not consume storage space and there is no way to retrieve them.

8. What is difference between “Export” and “Export All” in apex data loader?
Export: It will fetch only active records from salesforce.
Export All: It will fetch active as well as records from recycle bin.

9. True or False: Users can mass transfer records to which they do not have read access?
False

10. What is DateTime format supported in .csv file for upload in salesforce?
YYYY-MM-DDThh:mm:ss.00Z

11. Is there is any option to specify time zone for uploading records in apex data loader?
Yes. Present in settings page of apex data loader.

12. When “Hard Delete” button will be enabled in apex data loader?
When you enable Bulk API setting in apex data loader.

Salesforce Interview Questions-Data Management Part-1

1. Is it necessary to define an explicit primary key in custom objects?
No. Every object has a standard field called id. There is no need to define an explicit primary key in custom objects. The standard id field can be used as primary key.

2. In which order, we upload data in salesforce for related objects?
When loading data into a salesforce application dependencies between objects determine the order in which objects are loaded. If there is a one-to-many relationship between A and B, the data for A should be loaded before the data for B.

3. What is Upsert and how external id are beneficial?
Upsert is an API function that combines insert and updates into a single call. Upsert uses an indexed custom field or external ID to determine whether to create a new object or update an existing object.
-If the external ID is not matched, then a new object is created
-If the external ID is matched once, then the existing object is updated
-If the external ID is matched multiple times, then an error is reported
Use Upsert when importing data to prevent the creation duplicates.

4. What is import wizard?
It is easy to use tool to load Accounts, Contacts, Leads, Solutions, or Custom Objects.
-Load 50,000 records or less.
-Prevent duplicates
-Doesn’t support all standard object but supports all custom object

5. Which is API based tool supported by Salesforce and what are its advantages?
Apex Data Loader

Advantages are:-
-Is a fully supported salesforce.com product.
-Supports import from CSV or export to CSV.
-Can be used to import or export more than 50,00 records.
-Supports loading from or exporting to a database via JDBC.
-Supports custom relationships for upsert.
-Can be run from command line.

Salesforce Interview Questions-Reports & Dashboards Part-2

6. What is a Custom Report Type?
Custom report types allow you to build a framework in the report wizard, from which users can create and customize reports. You build custom report types off of the relationships (master-detail and lookup) between objects so that you can:
  • Choose which standard and custom objects to display to users creating and customizing reports
  • Define the relationships between objects displayed to users creating and customizing reports
  • Select which objects' fields can be used as columns in reports
Note that the visibility of custom report types in the report wizard is controlled by users' access to the objects in the report type.
You may define which related records from other objects are returned in report results by choosing a relationship to another object.
You can associate up to four objects to a custom report type.

7. What is difference between custom report types and standard report types?
Standard report types are report types which salesforce create itself when we create objects and relationship between them.
Custom report types allow admin to specify what all fields will be available to user while creating a report. Also its provide functionality to associate up to 4 objects.

8. How access to reports and dashboard is controlled in Salesforce?
Access to reports and dashboards are controlled by folder in which they are stored. If user has access to folder then they can run reports present in that folder.
In reports data displayed is as per running user's security access. Reports can be run on both standard and custom objects.
Reports data is always generated in real time. When a report is saved, reports configuration parameters are stored but the generated data is not stored.

9. What is analytical snapshot?
Analytical snapshot allows reports run at scheduled time to be stored as objects. Analytical snapshots are used to perform trend analysis. As an example if we want to view how monthly sales are growing, fields in a report with sales figure can be stored in a custom object every month using Analytical snapshot. Data in this custom object can then be used to perform trend analysis.
Analytical snapshot are available from the Data Management menu option. Source report in Analytical snapshot can be of the type Tabular or Summary.
Setup Analytical reports require a four step process
  • Select source report
  • Select custom object
  • Map source report fields to custom object fields
  • Schedule the frequency for taking the snapshots
10. What is dashboard?
Dashboards are graphical representation of reports. Dashboards can be generated for summary or matrix reports (and not for tabular reports). Dashboards display data as per last time report was run.
A dashboard can have upto 20 components.

11. Is it possible that data you see on dashboard and data you see on report after drilling down the report on dashboard are different?
Yes.
When a user views the drill-down report for a dashboard component, running user's access permissions determine what data is displayed on the drilldown report. Hence it is possible that data in the drill down report does not match the cumulative dashboard data.
Remember report runs based on current or logged in user and display real time data but dashboard store the information from reports when you refresh dashboard. In order to see real time data on dashboard, refresh the dashboard.
Also dashboard can run based on logged in user or specified user but reports always runs based on logged in user.

12. What are different chart types available for dashboards?
  • Vertical column
  • Horizontal bar
  • Line
  • Donut
  • Funnel
  • Pie
Funnel is used to show proportion of values against each other.
Pie is used to demonstrate proportion of single value against total.
Donut is used to demonstrate proportion of single value against total and also show the total value.

13. What are limitations of salesforce reports?
  • Support for trend analysis in Salesforce is fairly limited.
  • User Interface of Salesforce reports and dashboards is fixed. Salesforce does not support pixel perfect report.
  • Salesforce reports do not support importing data from other sources
  • When displaying objects and their children, Salesforce does not support reporting on objects that do not have any children.
  • If an object has two different related lists, then Salesforce reporting does not support displaying both these related lists together.

Reports & Dashboards-Part 1