Sunday 25 January 2015

Using JSON.deserializeUntyped to create dynamically records from JSON

Few days ago, got a requirement of the webservice for the creation of the records from the data in the JSON response. Tried some old fashioned code that use object instance to insert the records, but I was not feeling to fulfill to use that one.

So I started doing some search on JSON de-serializing method of salesforce and then I got this one.
In the starting this method seems to be not that much helping, but later one found out that "deserializeUntyped" is one of the best method for JSON de-serialization.

Code Scope : This below code will dynamically create Salesforce Object records without specifying their instance in the code and field specified in the json response will be responsible for the field value of the records.
Its a generic code that can be used whenever you are creating a webservice for the creation of the records in Salesforce.

Here is code...

1:  public class DynamicRecordCreationFromJSONResponse {  
3:       public static void parseJSONCreateRecords() {  
5:            String jsonInput = '{\n' +  
6:                                  ' "Account" : [ ' +   
7:                                                            '{"Name":"Sample Account","CustomField__c":"BR22RRR","CustomBooleanField__c":true,"Lookup_Field__c":"a08g0000006c9EH"}, \n' +  
8:                                                            '{"Name":"Sample Account2","CustomField__c":"Peroni"} ],\n' +  
9:                                     ' "CustomObject__c" : [ ' +   
10:                                                            '{"Name":"Sample Record 1"}, \n' +  
11:                                                            '{"Name":"Sample Record 2","Activity_Description__c":"Testing"} ]\n' +  
12:                                     '}';  
14:            // Parse entire JSON response using deserializeUntyped  
15:         Map<String, Object> mapOfNameWithRecords = (Map<String, Object>)JSON.deserializeUntyped(jsonInput);  
16:            System.debug('mapOfNameWithRecords::::::::' + mapOfNameWithRecords.keySet());  
18:            //List of Objects  
19:            List<sObject> objList = new List<sObject>();  
20:            Map<String, List<String>> fieldswithDataType = new Map<String, List<String>>();  
22:            //Loop through mapOfNameWithRecords  
23:            for(String objName : mapOfNameWithRecords.keySet()) {  
25:                 //process to get the name of the object by removing curly braces  
26:                 String str = objName.replace('{',' ');  
27:                 String finalstr = str.replace('}',' ');  
28:                 finalstr = finalstr.trim();  
30:                 //Get the records of the object from the json  
31:                 List<Object> recordList = (List<Object>)mapOfNameWithRecords.get(finalstr);  
32:                 System.debug('recordList::::::::' + recordList);  
34:                 //Loop through the list of records of JSON  
35:                 for(Object obj : (List<Object>)mapOfNameWithRecords.get(finalstr)) {  
37:                      //Create new sObject instance  
38:                      SObject sobjectInstance = Schema.getGlobalDescribe().get(finalstr).newSObject();  
40:                      //Populating map with field name and values  
41:                      Map<String, Object> a2 = (Map<String, Object>)obj;  
43:                      //Loop through the keySet  
44:                      for(String st : a2.keySet()) {  
45:                           sobjectInstance.put( st, a2.get(st));  
46:             }  
48:                      //Add to list of sObjectk  
49:                      objList.add(sobjectInstance);  
50:                 }  
51:            }  
52:            System.debug('objList::::::::' + objList);  
54:            //Check for list size and insert  
55:            if(objList.size() > 0) {  
56:                 insert objList;  
57:            }  
58:       }  
59:  }  

Note : Date formate should be taken care of as it varies from Local of Salesforce User, so do provide right format for the Date and Date Time fields.

Happy Coding...cheers!!!

Sunday 4 January 2015

Passed Salesforce DEV 501 Multiple Choice - Sharing my experience

I passed Salesforce Certified Advance Developer Multiple Choice First of all, don't go without experience and preparation, its not that easy, being a hard core coder doesn't mean that you will go and pass, its not about coding knowledge, its all about coding basics i.e. Apex and Visualforce pages and Salesforce life cycle knowledge and best practice.

According to Study Guide for Certified Advanced Developer

Development Lifecycle                          13%                   9 Questions Code (Apex)                         33%                  23 Questions Pages (Visualforce)             38%                  26 Questions
Testing and Debugging                         16%                  11 Questions

Above table shows area covered in exam.

Listing out the high topics

1. Apex class basics and Best practice
2. Visualforce pages and tags, Templates.
3. Test classes - best practice.
4. Migration tool.
6. Sandbox and capabilities
7. IDE
8. Developer Console
9. Types of Controller

Here is the list of the things need to study with small descriptions as well. These are the high points that I feel should be at one place.

Sandboxes Types -- Developer Sandbox

Refresh Interval -- 1 day
Storage Limits -- 200 mb data and 200 mb file storage
Data Copy -- Metadata only
Sandbox Templates -- Not included

Description -- Developer sandbox environments are intended for coding and testing by a single developer. Multiple users can log in to and share a single Developer sandbox, but the primary purpose of a Developer sandbox is to provide an environment in which changes under active development can be isolated until those changes are ready to be shared. Developer sandboxes copy all of your production organization’s metadata, or Setup data. This includes custom settings, custom object definitions, Apex classes and triggers, Visualforce pages, reports, dashboards, price books, and so on.
Developer sandboxes provide a limited amount of file and data storage, which is enough for many development and testing tasks. 

Developer Pro Sandbox

Refresh Interval --- 1 day
Storage Limits --- 1 GB of data storage and 1 GB of file storage
Data Copy --- Metadata only
Sandbox Templates --- Not included
Description --- Developer Pro sandbox environments provide the same functionality as Developer sandboxes do, with increased file and data storage. With the added storage, a Developer Pro sandbox can host larger and more complete data sets, so you can use it for additional tasks such as data load and integration testing and user training.

Partial Copy Sandbox
Refresh Interval -- 5 days
Storage Limits -- 5 GB of data storage and 5 GB of file storage
Data Copy --- All metadata and sample of object data
Sandbox Templates --- Required
Description --- Partial Copy sandbox environments include all of your organization’s metadata and a sample of your production organization’s data that you define by using a sandbox template. To create a Partial Copy sandbox, you must apply a sandbox template at creation time. A Partial Copy sandbox is, at its base, a metadata copy of your production organization, just like Developer and Developer Pro sandboxes. In addition, the sandbox copy engine samples data from your production organization based on what is defined by a sandbox template. For each selected object in the sandbox template, the sandbox copy engine samples up to 10,000 records. For example, when you use a template that includes only Accounts to create a Partial Copy sandbox, up to 10,000 Account records are copied into the new sandbox, but no other records are copied.
The sandbox copy engine has a special copy strategy to handle Partial Copy sandbox creation. The copy strategy understands the data relationships that are defined in your production organization’s standard and custom object schema. The copy strategy ensures that sample records maintain valid relationships as defined in your production organization’s standard and custom object schema. For example, if you create a sandbox template that includes two custom objects that are called Master and Detail, and these objects have a Master-Detail relationship, the copy engine ensures that every sampled Detail record points to a Master. The copy engine also understands required relationships between objects, whether they are Master-Detail or required Lookup relationships. The copy engine samples the master records first and then uses the IDs of the master records to sample related detail records.
When you use sandbox templates to create valid subsets of your organization’s data, you can use Partial Copy sandboxes for virtually any development, testing, or training purpose. The only task for which they aren’t well-suited is full performance and load testing.
Full Sandbox
Refresh Interval --- 29 days
Storage Limits --- Same as production organization
Data Copy --- All metadata and data
Sandbox Templates -- Available
Description --Full sandbox environments are a replica of your entire production organization and all its data, including standard and custom object records, documents, attachments, code, settings, and so on.
When you create a Full sandbox, you can apply a sandbox template to limit the data that is copied, so that your sandbox contains only the records that you need for testing or other tasks. For example, you can omit confidential or sensitive data if it’s not needed for testing. Create a sandbox template that includes everything except the sensitive data. When you apply a sandbox template to aFull sandbox, the sandbox copy engine copies all of the records for the selected objects in the template. For example, when you use a template that includes only Accounts to create a Full sandbox, all of the Account records are copied into the new sandbox, but no other records are copied.
When you create a Full sandbox, you also have to decide how much field tracking history and Chatter activity to include.
The default is to omit field tracking, but you can include up to 180 days of field tracking. This might be an excessive amount of data if you track field history for many objects in your production organization.
§ Chatter activity data can be extensive, which can add a significant amount of time to your Full sandbox copy.
Limit the amount of field history that you copy, and copy your Chatter data only if you need it for your testing use cases.
You can use Full sandboxes for many purposes, but the size of the sandbox and length of the refresh interval don’t produce an environment that stays current with your production organization. We suggest that you use Full sandboxes for data load testing, integration testing, user acceptance testing, performance and load testing, and staging purposes. In particular, this environment is the only one that can support full performance and load testing.

Understanding Sandbox Refresh Intervals
The refresh interval for each sandbox environment is calculated from when the actual sandbox copying process begins. This corresponds to when the sandbox status changes from Pending to Processing.
If other sandbox copy requests were made before yours, your sandbox might remain in the Pending status for some time. The refresh interval timer for your sandbox won’t start until your request leaves this state.

Future Annotation

Methods with the future annotation must be static methods, and can only return a void type.
The specified parameters must be primitive data types, arrays of primitive data types, or collections of primitive data types.
Methods with the future annotation cannot  take  sObjects or objects as arguments.
Specify (callout=true) to allow callouts in a future method. Specify (callout=false) to prevent a method from making callouts.
Methods with the future annotation cannot be used in Visualforce controllers in  either  getMethodName  or  setMethodName  methods, nor in the constructor.
·         You cannot call a method annotated with future from a method that also has the future annotation. Nor can you call a trigger from an annotated method that calls another annotated method.
§  The getContent and getContentAsPDFPageReference methods cannot be used in methods with the future annotation.

Defining Templates with <apex:composition>

Define the section of the template using <apex:Insert >
Then create template using <apex:composition> with required child <apex:define>
All templates defined using <apex:composition> must have one or more child <apex:insert> tags.
An <apex:insert> tag indicates to pages that import the template that a section needs a definition. Any Visualforce page that imports a template using <apex:composition> must use <apex:define> to specify the content of each <apex:insert> section of the template.
<apex:insert> : Define a named section in VF template
<apex:define>: Provide content for named section in VF template
<apex:composition>: A particular area/section of visualforce page where VF template is to be used


ALL ROWS - returns all rows including those in the recycle bin and archived activities
(Ex: System.assertEquals(2, [SELECT COUNT() FROM Contact WHERE AccountId = a.Id ALL ROWS]);)

FOR UPDATE - locks the record for update from other means while the execution is happening.
(Ex:  Account [] accts = [SELECT Id FROM Account LIMIT 2 FOR UPDATE]; )


Returns a map of all sObject names (keys) to sObject tokens (values) for the standard and custom objects defined in your organization.

Understanding Apex Describe Information

You can describe sObjects either by using tokens or the describeSObjects Schema method.
Apex provides two data structures and a method for sObject and field describe information:
·         Token—a lightweight, serializable reference to an sObject or a field that is validated at compile time. This is used for token describes.
·         The describeSObjects method—a method in the Schema class that performs describes on one or more sObject types.
§  Describe result—an object of type Schema.DescribeSObjectResult that contains all the describe properties for the sObject or field. Describe result objects are not serializable, and are validated at runtime. This result object is returned when performing the describe, using either the sObject token or the describeSObjects method.

Order of Execution for Visualforce Page Get Requests

 A get request is an initial request for a page either made when a user enters an URL or when a link or button is clicked that takes the user to a new page. The following diagram shows how a Visualforce page interacts with a controller extension or a custom controller class during a get request:
1. Evaluates constructor on the controller and Extensions.
2. Custom Component on Page.
3. Evaluates action attribute on <apex:page>.
4. Checks for apex:form on page, to create view state.
Note : If the user is redirected to a page that uses the same controller and the same or a proper subset of controller extensions, a postback request is made. When a postback request is made, the view state is maintained.

Visualforce Email Templates

Although Visualforce email templates use standard Visualforce components, they are not created in the same way. Visualforce email templates always use components that are prefaced with the messaging namespace. In addition:
·         All Visualforce email templates must be contained within a single <messaging:emailTemplate> tag. This is analogous to regular Visualforce pages being defined within a single <apex:page> tag.
·         The <messaging:emailTemplate> tag must contain either a single <messaging:htmlEmailBody> tag or a single <messaging:plainTextEmailBody> tag.
§  Several standard Visualforce components are not available for use within <messaging:emailTemplate>. These include <apex:detail>, <apex:pageBlock> and all related pageBlock components, and all input components such as <apex:form>. If you attempt to save a Visualforce email template with these components, an error message displays.


A timer that sends an AJAX request to the server according to a time interval that you specify. Each request can result in a full or partial page update.
An <apex:actionPoller> must be within the region it acts upon. For example, to use an <apex:actionPoller> with an <apex:actionRegion>, the <apex:actionPoller> must be within the <apex:actionRegion>.


A component that provides support for invoking controller action methods directly from JavaScript code using an AJAX request. An <apex:actionFunction> component must be a child of an <apex:form> component.
Unlike <apex:actionSupport>, which only provides support for invoking controller action methods from other Visualforce components, <apex:actionFunction> defines a new JavaScript function which can then be called from within a block of JavaScript code.


Note that an <apex:actionRegion> component only defines which components the server processes during a request—it does not define what area(s) of the page are re-rendered when the request completes. To control that behavior, use the rerender attribute on an <apex:actionSupport>, <apex:actionPoller>, <apex:commandButton>, <apex:commandLink>, <apex:tab>, or <apex:tabPanel> component.

    <apex:inputField value="{!opportunity.stageName}" id="stage">
    <apex:actionSupport event="onchange" rerender="thePageBlock"



A component that inserts a second Visualforce page into the current page. The entire page subtree is injected into the Visualforce DOM at the point of reference and the scope of the included page is maintained.
If content should be stripped from the included page, use the <apex:composition> component instead.

Visualforce pages

Visualforce consists of a tag-based markup language that gives developers a more powerful way of building applications and customizing
the Salesforce user interface. With Visualforce you can:
• Build wizards and other multistep processes.
• Create your own custom flow control through an application.
• Define navigation patterns and data-specific rules for optimal, efficient application interaction.

Adding SOSL Queries to Unit Tests

To ensure that test methods always behave in a predictable way, any Salesforce Object Search Language (SOSL) query that is added to an Apex test method returns an empty set of search results when the test method executes. If you do not want the query to return an empty list of results, you can use the Test.setFixedSearchResults system method to define a list of record IDs that are returned by the search. All SOSL queries that take place later in the test method return the list of record IDs that were specified by the Test.setFixedSearchResults method. Additionally, the test method can call Test.setFixedSearchResults multiple times to define different result sets for different SOSL queries. If you do not call the Test.setFixedSearchResults method in a test method, or if you call this method without specifying a list of record IDs, any SOSL queries that take place later in the test method return an empty list of results.
The list of record IDs specified by the Test.setFixedSearchResults method replaces the results that would normally be returned by the SOSL query if it were not subject to any WHERE or LIMIT clauses. If these clauses exist in the SOSL query, they are applied to the list of fixed search results. For example:
private class SoslFixedResultsTest1 {
    public static testMethod void testSoslFixedResults() {
       Id [] fixedSearchResults= new Id[1];
       fixedSearchResults[0] = '001x0000003G89h';
       List<List<SObject>> searchList = [FIND 'test' IN ALL FIELDS RETURNING    Account(id, name WHERE name = 'test' LIMIT 1)];

Contents to go through before exam -

1. Apex Code Developer's Guide and Visualforce Guide.
2. Developer Guide.
3. Salesforce Object Query Language.

Happy Coding..!!