Wednesday, December 10, 2014

The Ajax Toolkit for Salesforce

Why overload SOQL queries, when you can play with API calls to retrieve, create and delete data using the set of unique features provided by salesforce with AJAX toolkit.
The Ajax toolkit gives anyone familiar with Java script the ability to write the code. It is simple and lightweight. It runs on a browser, which doesn’t require execution of code from Salesforce servers. Ajax toolkit doesn’t affect test coverage. And makes development and deployment quick and easy.
Ajax toolkit does not require a single line of Apex code. Because the Ajax toolkit is making purely API calls, and as Salesforce Professional Edition doesn’t allow API calls, don’t even think about using Ajax tool kit with the Professional Edition.
The Ajax toolkit handles errors easily and its flashing feature also supports parent-child relationship queries. We can query any S object using the Ajax toolkit with the API. Consider the below code:
result = sforce.connection.query(“Select Name, Id from User”);
 records = result.getArray(“records”);for (var i=0; i< records.length; i++) {
var record = records[i];
log(record.Name + ” — ” + record.Id);
}
In the above example, “result = sforce.connection.query” is the parameter which connects to the API to query records. The Salesforce server checks the incoming API from the browser for its IP address. If the IP address is in the trusted IP range, The API is allowed to access the database, else it is bounced back.
We can also access parent child relationship in Salesforce.
//Query the parent child or child parent relationship
var result = sforce.connection.query(“SELECT c.Id, c.firstname, ” +
“c.lastname, c.leadsource, a.Id, a.name, a.industry, c.accountId ” +
“FROM Contact c, c.account a ORDER BY leadsource LIMIT 10″);var it = new sforce.QueryResultIterator(result);

With the Ajax toolkit, you can make synchronous and asynchronous call outs from Salesforce. With Ajax toolkit, you can make your life easier. Give it a try!

Authored by: Nirmal Christopher,
 Salesforce.com Certified Developer, 
Technical Consultant, 
Global Tech & Resources, Inc. (GTR).

Thursday, October 30, 2014

Building charts Using Visualforce

Building charts Using Visualforce


There are so many types of charts available we can invoke these charts with your custom data and these charts can be completely created in Visualforce page. To name a few we have Apex Pie series , Apex bar series, Apex Line Series , Apex Area series, Apex Scatter Series. 

These components are lightweight and easily adaptable in a visualforce page. Also you can use these components in standard page as an Inline visualforce page.

How to Build one ??

Build a list and use the list data in the visualforce page enclosed within the  <apex:chart>
visualforce tag. Something like this
<apex:page controller="PieChartController" title="Pie Chart">
   <apex:chart height="350" width="450" data="{!pieData}">
       <apex:pieSeries dataField="data" labelField="name"/>
       <apex:legend position="right"/>
   </apex:chart>
</apex:page>


The above code will render a pie chart something like this
pages_charting_simple_pie_chart.png
The above diagram gets the plot values from the list variable “{!pieData}” which is associated with the controller.


The value Piedata is extracted from the list of a wrapper class as a String for Months and Integer of Pie Wedge Values respectively.


Similarly we have several other chart components like apex line series which renders line graph, Apex bar series which renders Bar graph, Apex scatter series are like line series except the lines connecting the plots are invisible.


All the data to the chart series can be bought using a wrapper list. These components are really powerful,without using any Javascript remoting we can make use of these tailor made charts and graphs for you custom data in few lines of code and it makes the life of a developer so ease to live.

Authored by

Nirmal Christopher
SFDC certified Techical consultant
Global Tech & Resorces

Friday, October 24, 2014

Using Apex Param tag setting reference for the page elements



            We all know that we can communicate with pages and controllers using Getter setter methods but sometime we will be stuck in the scenario like referencing the Visualforce parent components to the controller. Lets discuss an example we have a list of records say it’s a wrapper list and below are the data types I defined inside the wrapper
  • String Name
  • String Email
  • Integer counter wrap
So the collection of whole data type is added in to a list and display this list in a Visualforce page   which will look something like this
..

On clicking the delete link the entire row gets deleted but not the data.  Let’s ask some questions to ourselves how to achieve this


1.       How the compiler knows on which “Delete  “ link is invoked inorder to get deleted?


2.       How to pass the reference parameter to check which row the user intends to delete?


These questions will be answered by Apex Parameter tag


What does this apex param tag do??
Apex parameter tag always will be the child component for the following parent tags
<apex:commandlink>
<apex>commandbutton>
<Apex:actionstatus>
<apex:actionFunction>
<apex:actionSupport>
<apex:outputtext>
Let’s get back to our example


First things first before diving deep into any technical code let me give the answers for the questions I asked above


1.        How the compiler know on which “Delete  “ link of the row the list index position should get deleted ?
In the wrapper list I have set an Integer variable which will act as an index element for each record in a list and when the user click on the delete link the param tag will pass the value to the controller. There we can identify if the record is equal to the integer value obtained from the param tag. It its operation to delete or remove the row can be applied.

2.       How to pass the reference parameter to check which row the user indents to delete?
I have set the value attribute from the integer value counter wrap


Scenario
           Let’s look at some sample code here how we did this.
In the Visualforce page


<apex:pageBlockTable value="{!wrapkeyconlist2}" var="i">    <apex:column headerValue="Action">       <apex:commandLink value="Delete" action="{!remove}" immediate="true">           <apex:param name="index" value="{!i.counterWrap}"/>         </apex:commandLink>   </apex:column> <apex:column value="{!i.keyconlist1.name}"/> <apex:column value="{!i.keyconlist1.FF__Email__c}"/> </apex:pageBlockTable>

In the controller remove method


  Integer param = Integer.valueOf(Apexpages.currentpage().getParameters().get('index'));   for(Integer i=0;i<wrapkeyconlist2.size();i++){  
if(wrapkeyconlist2[i].counterWrap == param ){  wrapkeyconlist2.remove(i); 
} 
counter--; 

Nirmal Christopher
SFDC certified force.com developer
Global Tech and Resorces

Tuesday, October 21, 2014

New upcoming Features to be considered on Dream force 2014 Platform Upgrade

Salesforce 1 Lightning


It's always a nightmare to develop UI in force.com platform until the developer knows the various UI components used. For Instance if we are developing a custom UI there is a set or predefined drag and drop feature available to create UI in IDE's provided for other platforms. Example:netbeans, Eclipse, Dream viewer etc..

But in salesforce there is no such tools available until now. But in dreamforce 14 salesforce launched a new app "Salesforce Lightning" which allows the user to create rich UI light weight components.

Now business users and developers can create hazzle free rich UI's for desktop application and salesforce1 platform. using the new app. Now it's is in beta release

  


Salesforce wave(analytics cloud)



In dreamforce 14 salesforce has launched a new app known as "Analyics Cloud". Like its predessors(Sales cloud,service cloud,Marketing cloud) its a new app is built natively on the salesforce  platform.

Its a licenced  feature and it's the first mobile analytics platform. The UI and the dashboard components are so rich which allows the user to use scalable,precise and rich dashboard and analytics component at the finger tip.

The UI is crystal clear and alllow the user to view the trending data in different components simultaneously. They can filter and search for the results and the real tim UI adopts the user input so dynamically like a wave. Its a WOW feature...

Follow the link to know more about the platform


Nirmal Christopher
SFDC certified force.com developer
Global Tech and Resorces

Friday, August 8, 2014

Reasons Salesforce Enforces Governor Limits


Apex runs in a multi-tenant environment. The resources within that multi-tenant environment need to be available to all tenants. To be sure of that, Salesforce’s “run time engine” constantly checks to orgs and app to be sure they are not exceeding Salesforce’s imposed governor limits.


Salesforce imposes these limits to prevent any organization from monopolizing the shared server resources. While writing apex code, there are various possible ways to account for and stay within governor limits. There is also the possibility to raise a case with Salesforce support to increase your governor limits by paying extra money.


In our app, RPaaS, we encountered and had to work with governor limits in several instances.


1– In Apex triggers, when we used DML statements like ‘Insert’, ‘Update’, ‘Upsert’ or ‘Delete’  inside the For Loops; the loop executes  and hits the limit of the SOQL query, since this is executed in single instance.


2– The same limit applies to Send email methods inside of loops and many more....


To avoid problems like examples 1 and 2, we learned to not use statements inside loops.


3– Because of Heap Size Limits; when writing queries, usage of a proper ‘WHERE’ clause will slow down the total number of records returned by each collection type (Lists, Maps and Sets).


To avoid problem #3, make your SOQL Queries selective. See Link #2 for more Info.


Please refer to links below for an extensive list of code enforcements made by Salesforce:


Linke 1: General Definition  


Link 2 : Learn more about the enforcement


Link 3: Best Practice while writing the trigger


Let us build a stronger developer community by sharing our experience! Have you encountered similar issues? How did you handle them?

Nirmal Christopher
SFDC Technical Consultant
Global Tech & Resources| www.GTR.net

Thursday, July 3, 2014

Streaming API Use Case



A video demo by Nirmal Christopher on ‘push Topics’ & ‘streaming API’; using workbench and Visualforce page to test the Live streams.  The streaming API is defined with a given SOQL definition and then used to return real-time of notification events to the Salesforce dot com database. Streaming API can be published in either an external system or in a VF page.

Wednesday, May 21, 2014

ENFORCING CRUD-FLS Enforcements in Salesforce


ENFORCING CRUD-FLS Enforcements in Salesforce



Caution-Unauthorized-Entry-Prohibited-Sign-ES-0019_stake.gif
Security Authorizations are essential for every system in the universe.  Just like WBC cells in a human body which restricts access to foreign microbes or The Ozone layer in the atmosphere which inhibits the harmful radiations Entering inside,  Salesforce have something called CRUD FLS enforcement which prohibits the users to gain access to the records they don’t own. We were developing an app mostly with multiple visualforce pages and controllers. Usually all the standard pages in Salesforce are automatically enforce the CRUD and FLS settings. But when it comes for visualforce pages with Input text and Input text area  components  with lot of DML statements in their controllers. The system interprets the fields displayed in the visual force pages as the string values but  not as the fields from the Sobjects.

The damage done by this new evaluation procedure of Salesforce in our app took a huge toll on its release dates. When we submit the app for security review the app failed to pass due to the insufficient CRUD FLS enforcements checks. All we had his Salesforce’s own knowledge article and we started analyzing each and every classes we had with appropriate manual CRUD FLS checks. When the issue was finally resolved I thought of writing a blog on this which will help my fellow peers. Here is how we did this

In one of the security review findings related to CRUD FLS Enforcements Its given as “No manual CRUD enforcements on a DML event “ and the report document  listed the bunch of classes which needed modification.

For example if we instantiate a new record we have to make use of the statements such as Iscreateable(), IsUpdateable(), Isdeletable() appropriately to manually enforce the CRUD access something like this.   
  
 Cities__c city = new Cities__c__();  
   if(Schema.sObjectType.cities__c.fields.state__c.isCreateable()) city.state__c='American Samoa';
   if(Schema.sObjectType.cities__c.fields.name.isCreateable()) city.name ='Abeville';
   if(Schema.sObjectType.cities__c.isCreateable()) insert city;
But what if you want to implement the FLS settings for multiple fields like the example below,  It will take too much time to enforce the conditions


Job_Locations__c location = new Job_Locations__c();
  location.Account__c=a.id;
  location.City__c=city.id;
  location.Company__c='american textile';
  location.Description__c='testing';
  location.Employer_Wisdom__c='www.gmail.com';
  location.Latitude__c=3.5;
  location.Longtitude__c=3.5;
  location.Location_State__c='American Samoa';
  location.Region__c='south';

In this case you can iterate using a forloop and add the fields by adding all the field API names inside a string array and check the access if the object is Creatable, Updateable  or deletable refer the below example

Job_Locations__c location = new Job_Locations__c();
   String [] Job_LocationsFields = new String [] {'Account__c','City__c','Company__c','Description__c','Employer_Wisdom__c','Latitude__c','Longtitude__c','Location_State__c','Region__c'};
   Map<String,Schema.SObjectField> JLMap = Schema.SObjectType.Job_Locations__c.fields.getMap();
   Boolean isCreateable= true;
   for (String fieldToCheck : Job_LocationsFields ) {
   if (JLMap.get(fieldToCheck).getDescribe().isCreateable() == false) {
        isCreateable= false; break;   
        }}
        if (isCreateable== true){
   location.Account__c=a.id;
   location.City__c=city.id;
   location.Company__c='american textile';
   location.Description__c='testing';
   location.Employer_Wisdom__c='www.gmail.com';
   location.Latitude__c=3.5;
   location.Longtitude__c=3.5;
   location.Location_State__c='American Samoa';
   location.Region__c='south';   
   }
 if(Schema.sObjectType.Job_Locations__c.isCreateable()){
 insert location;
}
else{     
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Insufficient access'));
                return null;
}
This might be the easiest possible way to enforce the CRUD permission on DML statements.

External References:
Know more about permission settings and FLS settings in Salesforce
https://developer.salesforce.com/page/Testing_CRUD_and_FLS_Enforcement

Nirmal Christopher


Salesforce.com Technical Consultant
Global Tech and Resources Inc..,



Monday, May 19, 2014

SOQL INJECTION Attacks

What is SOQL Injection?

trojanhorseWe can compare the SOQL injection with the Trojan horse from Greek Mythology.  In Greek Mythology there is a tale about the Trojan War.  The Greeks used the selected soldiers and hide them into a giant wooden horse and pretended to leave the shores and people of Troy believed the horse as a war trophy and they brought it inside the city That night the Greek force crept out of the horse and opened the gates for the rest of the Greek army, which had sailed back under cover of night. The Greeks entered and destroyed the city of Troy, decisively ending the war. Here the beliefs of the people in the city of troy are used by the Greeks to bring down the city fortifications to ease the invading Greek Army.

Similarly if we don’t believe in validating  the user inputs in an Application there is a chance for the users might trick the application by providing the malicious inputs. So this is a serious security threat in an Application.

Just like SQL Injections Salesforce’s own query language SOQL also faces the similar problem.

Impact on Salesforce Database

Even though the database is different the attacks are similar just like SQL. Consider the SOQL query from one of my previous blogs How to Build a Simple Search Page Using Visualforce
String searchquery= 'SELECT Id FROM account WHERE ' +
'(IsDeleted = false and Name like \'%' + name + '%\')';
acc= Database.query(searchquery);
Here  the input for the query is not properly validated. Imagine if the user gives the malicious input something like this

User Input : test%') OR (Name LIKE '

Then query is modified something like this

String searchquery= 'SELECT Id FROM account WHERE ' +
'(IsDeleted = false and Name '%test%') OR (Name LIKE '%'))';

If you look in to the above line you can see the entire query is modified with three different where clauses.  Now the query will just not show the non deleted one’s  it will show all the accounts. This is a typical example for a SOQL injection.

Resolution

Usage of proper validations might solve the problem. All the user inputs in the UI have to be validated to check if the input contains special characters such as % ; ‘ etc…

Usage of static queries with dynamic binding of variable might also solve the issue. For example  the above query can be modified as follows

String searchquery = '%' + name + '%';
queryResult = [SELECT Id FROM account WHERE
(IsDeleted = false and Name like : searchquery)];

External References:

http://en.wikipedia.org/wiki/SQL_injection
https://www.salesforce.com/us/developer/docs/pages/Content/pages_security_tips_soql_injection.htm


Nirmal Christopher
Salesforce.com Technical Consultant
Global Tech and Resources Inc..,

Thursday, March 27, 2014

Analytic Snapshots-Business Analytics Salesforce

General Overview:

Analytical snapshots (Available in professional, Enterprise, Developer and Unlimited editions) in Salesforce help the users to produce historical trends in their data. The data is stored in a custom objects pushed by a snapshot scheduler.  The features of Analytic snapshots are

1.       Allows the users to build the historical trend of data.
2.       Sourced by tabular & summary reports.
3.       Data stored in custom object. So the data stored is secure from user tampering.
4.       The user can define mapping and scheduled runs.
There are several pros and cons in Analytical snapshots.

Pros:

·         Supports daily monthly and weekly trends.
·         Snapshots details or summary data from reports.
·         Protects data from deletion.
·         Control access for the custom objects through custom object permission

Cons:

·         2000 row limit per user.
·         Limits to # of user runs per day.

Typical use cases:

              If a customer service manager want to analyze the number of open cases on day to day basis . He/she can create an analytic snapshot and schedule it for a daily run. The snapshots are automatically pushed in to a user created custom object. From where historical trends will be analysed.

How to configure:
Please refer the links and a Salesforce Video webinar for your reference

·        Build a summary or a tabular report
·        Create a custom object with all the fields identical as the SFDC report.
·         Configure ananalytic snapshot  and map the fields.
·         Schedule the Analytic snapshot for daily weekly or monthly run.



External Blog links:

How to solve: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY: maximum trigger depth exceeded “S object” error?

(Wow that is the longest title I've ever given a blog! You searched on your error message and you found my post, right? Now, to the issue-at-hand.)
Trigger recursion is a big nightmare for the Salesforce developer. When a trigger with odd criteria (malformed?) fires; it subsequently starts auto firing and results in an exception error; something like:

CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, Update_Opportunity_Calculation_fields: maximum trigger depth exceeded “S object”

In order to solve this we use the help of a static variable.  Create an apex class with static Boolean variables and add a check in the trigger for specified Boolean  value results.

Here's an example:

My business case is that I wish to renew a subscription on an Account. I want to automatically create a new Opportunity. In this scenario, I wish to create another Opportunity, say a related child Opportunity, when a master Opportunity is inserted. I've created a after insert trigger on Opportunity. When I insert a new record, it gets fired.

Look at the code:
trigger recurssiontest on opportunity(after insert) {
     for(opportunity opp:trigger.new){
       opportunity o = new opportunity();
       o.Name='xyz child';
       o.parentid__c=opp.id; //id of the parent
       insert o;
     } 
}
This code will return: error CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, Update_Opportunity_Calculation_fields: maximum trigger depth exceeded “S object”

So what’s the work around ?

Create a apex class with global or public access specifier and call the apex class inside the trigger in an IF statement. This will check to see, if the static variables inside the apex class meets the specified conditions.

Like this:
public class stoprecurssion{
public static boolean flag=true;
public static boolean runonce(){
if(flag){
   flag=false;
  }
else {
   return flag;
  }
   return true;
 }
}
In the trigger, never forget to add the IF check, which is called from the instance of the above class.

It will look like this:
trigger recurssiontest on opportunity(after insert) {
     for(opportunity opp:trigger.new){
      if(stoprecurssion.runonce()){
       opportunity o= new opportunity();
       o.Name='xyz child';
       o.parentid__c=opp.id; //id of the parent
       insert o;
       }
     }
}
Writing our trigger in this manner, avoids recursive firing of triggers.

Sunday, February 16, 2014

Rendered,Render As, Re Render example in Visualforce

Imagine you want to generate a PDF report or a word document from a Visualforce page. Use the renderAs attribute to generate the entire Visualforce page in a described format.

renderAs- This attribute is used to render the whole document in a PDF or any other document format.

Rendered- the return type for this attribute is a boolean which is used to hide or show any Visualforce component. It is always defaulted to true.

rerenderThis attribute is used to refresh a particular section or a visual force code block.

Here the user types in the first text box the block inside the apex output panel refreshes and displays the second text box and again if the user starts typing in the second text box the third text box appears. Refer these images below.





 The Apex action support tag is used to handle the event of typing the text in the text box. All I have done is just matching the rerender value of the action support event with the Id of the output panel and using the rendered attribute to return a boolean value by using the LEN formula function in the Visualforce page to check the length of the previous text field.

1:  <apex:page controller="renderedex" >  
2:  <apex:form >  
3:   <apex:pageBlock title="User Input" id="thePageBlock">  
4:       <apex:outputText value="Text1"></apex:outputText>  
5:       <apex:inputtext value="{!text1}">  
6:       <apex:actionSupport reRender="refresh" event="onkeyup" />       
7:       </apex:inputtext><br/>   
8:        <apex:outputPanel id="refresh" >  
9:                            <apex:pageblocksection rendered="{!LEN(text1)>0}">  
10:                           <apex:inputText value="{!text2 }" id="theTextInput2" label="Input 2" rendered="true" tabindex="2">  
11:                            <apex:actionSupport reRender="refresh1" event="onkeyup" />   
12:                            </apex:inputtext>  
13:                      </apex:pageblocksection>  
14:        </apex:outputPanel>  
15:        <apex:outputPanel id="refresh1" >  
16:                            <apex:pageblocksection rendered="{!LEN(text2)>0}">  
17:                            <apex:inputText value="{!text3 }" id="theTextInput3" label="Input 3" rendered="true" tabindex="3">  
18:                            </apex:inputtext>  
19:                            </apex:pageblocksection>  
20:        </apex:outputPanel>  
21:       </apex:pageBlock>  
22:  </apex:form>  
23:  </apex:page>  
This example best shows the usage of render and re-render attributes. Feel free to comment if you have any questions.