Thursday, October 16, 2014

How to use Streaming API in visualforce Salesforce

Ok so as per new enhacnement Slaesforce has introduced streaming API in force.com. The cool thing is that it works on "Comet" model, its accually a long-held HTTP request model. So if a connection is open it will get the new updates through polling. The server will pust the new data into the stream and thus we will get notification in page without even using page reload or API request.


Result:

Hope this helps you!!

Tuesday, October 7, 2014

How to get all property of a javascript [object object]

Ok so sometime when usings others code in javascript me might not be knowning the property that returning object has. So to get the property just use this code after initilizing and record all the available property and values and then use accourdingly.

Option 1:
for(var key in conn) {

    var value = key +" : "+ conn[key]; console.log("***"+value); 
} 
Option 2:
console.log(conn);  

Hope this helps you!!

Sunday, October 5, 2014

How to use workflow outbound message to send xml to other systems

Ok so I was not finding any good articals to learn how to use outbound message in Salesforce.

So to begin just create a workflow at your desired object.
Now create a action of type "Outbound Message" and give the field information.
Now in the "Endpoint URL" give the URL you want to post data to eg: http://example.in/wscd.asmx etc.
Now give the fields in the multy select box to be sent with request.

And this the output you will receive on the end point.













Salesforce automatic gives it a XML formate and the reciver endpoint service must parse this to get the posted data.

Hope this helps you!!

Thursday, October 2, 2014

How to understand and use Interface, Abstract and Virtual definition modifier in apex Salesforce

Ok so this is a very conceptual module in apex or OOPs programming.

Interface is a which none of the methods have been implemented but when its implemented then it is mandatory to define all of its declared method in the implementing class. Also we cannot define any fields in interface and all the method are final and pubic.

Example:

public interface custom_Interface{
    void CallFirst();
    Void CallSecond();
}
public class Implement_custom_Interface implements custom_Interface{
    public void CallFirst(){
        //
        system.debug('***First**');
    }
    public void CallSecond(){
        //
        system.debug('***Second**');
    }
}

Abstract class is class with only declaration and no definition but its mandatory to override all the method.

Example:

public abstract class custom_Abstract{
    public abstract string AbstractFirst();
    public abstract string AbstractSecond();
    public void noReturn(){
    }
}
public class Implement_custom_Abstract extends custom_Abstract{
    public override string AbstractFirst(){
        system.debug('***From Abstract Extends Class***');
        return null;
    }
    public override string AbstractSecond(){
        system.debug('***From Abstract Extends Class***');
        return null;
    }
}

Virtual class is having definition of the method and if you need you can override the method, but its not mandatory to implement all the methods.

Example:


public virtual class coustom_Virtual{
    public virtual void OverFirst(){
        system.debug('****From  Defination****');
    }
    public virtual void OverSecond(){
        system.debug('****From  Defination****');
    }
}
public class Implement_coustom_Virtual extends coustom_Virtual{
    public override void OverFirst(){
        system.debug('!!!From  Declairation!!!');
    }
}
Hope this helps you!!

Wednesday, September 24, 2014

How to display an Image in richtext area field when Image is in attachments

Ok so now if I want to display the same image that is in the attachment of a record? Confused I know as images are stored by salesforce in the back end are not available by simple URL access an Eg:


<img alt="User-added image" height="281" src="https://c.ap2.content.force.com/servlet/rtaImage?eid=00390000018kf3r&amp;feoid=00N9000000XXXX&amp;refid=0EM9000000XXX" width="500"></img>
This is how salesforce saves the image in the rich text box and now if we need to save any kind of image we can, as we just need the 18 digit Id of the saved image.

An attachment has a 18 digit Id and we can use this as Eg:


<img src="https://c.ap2.content.force.com/servlet/servlet.FileDownload?file=00P9000000DXXXX" width="500" height="300"></img>
Wola!! now we can save any image to richtext area form apex code or by query editor. give it a try and ask me if you have any questions.

Hope this helps!!

Note: Refer - http://ankit-rustagi.blogspot.in/2012/10/to-insert-image-into-rich-text-area.html

Tuesday, September 23, 2014

How to display a image if you have Bas64 sting on a visualforcfe page

Ok so recently I got a requirement that the image is saved in a Base64 format and when it is displayed it should be displayed as image.

What? Right and here is a small trick to do the job.

<img alt="<image_Name>" src="data:image/<image_File_Extension>;base64, <base64_Image_String>"></img>
http://developer.force.com/cookbook/recipe/converting-a-rich-text-area-fields-image-for-api-upload

Hope this helps!!

Thursday, August 28, 2014

How to do JSON parsing in Apex Visualforce

Ok so today we will be looking into the Json parsing. Json is "Javascript Object Notation" a new form of format which is widle used over the http responce in webservices. It is structured and can contain data in human readable format.

To make json data salesforce provide some standard class called as System.JSON. We will be using this class to parse and then un parse the data in json.

Parsing:

  1. Create a visualforce page with controller.
  2.  Now copy this code to make a wrapper class holding name,id and phone fields
    //Subclass : Wrapper Class 
        public class Accountwrap {
            //Static Variables 
            public string id;
            public string name;
            public string Phone;
            
            //Wrapper  Class Controller
            Accountwrap(string Phone, string name, string id) {
                this.Phone = Phone;
                this.name = name;
                this.id = id;
            }
        }
  3. Now to parse this wrapper class list into a json string use this code.
    public void getlstAccount(){
            List < Accountwrap > lstwrap = new List < Accountwrap > ();
            List < account > lstacc = [SELECT Id, Name, Phone FROM Account limit 2];
            for (Account a: lstacc) {
                Accountwrap awrap = new Accountwrap(a.Phone,a.name,a.id);
                lstwrap.add(awrap);
            }
            strJson = JSON.serialize(lstwrap);
        }
  4. strJson is a public string and will get the json string,
Un-Parsing:
  1. To convert the json string we will use the same wrapper class to provide structure to the values.
  2. To un parse the string use this code
    public static List<Accountwrap> parse(String str) {
            system.debug('*****str*****'+str );
            JSONParser parser = JSON.createParser(str);
            system.debug('*****parse*****'+parser );
            List<Accountwrap> jsonstatLst = new List<Accountwrap> ();
            while (parser.nextToken() != null) { System.debug('Current token: ' +  parser.getCurrentToken() + '****JSONToken.START_ARRAY****'+JSONToken.START_ARRAY);
                if (parser.getCurrentToken() == JSONToken.START_ARRAY) {
                    while (parser.nextToken() != null) {
                        // Advance to the start object marker to
                        //  find next invoice statement object.
                        if (parser.getCurrentToken() == JSONToken.START_OBJECT) {
                            jsonstatLst.add((Accountwrap)parser.readValueAs(Accountwrap.class));
                            parser.skipChildren();
                        }
                    }
                }
            }
            return jsonstatLst;
        }
  3. jsonstatLst is a List of type wrapper class and the method can populate any list of the same type with data in wrapper object form.
Hope this helps you!!

Wednesday, August 27, 2014

How to bootstrap with Visualforce

Ok so today I am going to show you a small and simple example of how to get started with bootstrap in visualforce. Bootstrap is the most popular HTML, CSS, and JS framework for developing responsive, mobile first projects on the web. So now first thing first:

  1. Download bootstrap lib zip file from "http://getbootstrap.com/" and upload it to your custom setting by name "Bootstrap".
  2. Now create a visualforce page name "Bootstrap_Mobile_CreateAccount".
  3. And include the bootstrap scripts as :

<!-- Load script here -->
    <apex:stylesheet value="{!URLFOR($Resource.Bootstrap, 'bootstrap-3.2.0-dist/css/bootstrap-theme.min.css')}"/>
    <apex:stylesheet value="{!URLFOR($Resource.Bootstrap, 'bootstrap-3.2.0-dist/css/bootstrap.min.css')}"/>
    <apex:includeScript value="https://code.jquery.com/jquery.js"/>
    <apex:includeScript value="{!URLFOR($Resource.Bootstrap, 'bootstrap-3.2.0-dist/js/bootstrap.min.js')}"/>
    4.   Now create div and give the class of bootstrap as shown here
<div class="container">
 <br/>
 <div class="panel panel-primary">
  <div class="panel-heading">
   <h3 class="panel-title">Create Account</h3>
  </div>
  
  <div class="panel-body">
   Details:
   <div class="row">
    <div class="col-md-4"><input id="inp1" type="text" placeholder="Account Name" class="form-control"/></div>
    <div class="col-md-4"><input id="inp2" type="text" placeholder="Description" class="form-control"/></div>
    <div class="col-md-4"><input id="inp3" type="text" placeholder="Phone" class="form-control"/></div>
   </div>
   <br/>
   <br/>
   <button class="btn btn-lg btn-primary btn-block" type="submit" onclick="createAcc();">Save</button>
  </div>
 </div>
</div>
     5.   Now provide this <javaScript> to the page to we can save the records.
<script>
 Visualforce.remoting.timeout = 120000; // Set timeout at page level
 var $j = jQuery.noConflict();        

 function createAcc(){
  $j('#basicModal2').modal('show');
  var accName= $j('#inp1').val();
  var accDes= $j('#inp2').val();  
  var accPhn= $j('#inp3').val();          
  Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.Bootstrap_Mobile_CreateAccountCon.createAccount}',accName,accDes,accPhn,handleResult);  
 } 
 function handleResult(result, event){
  if (event.status) {
   alert(result);
  } 
      
 }             
</script>  
6. Now create a controller and in that create this javascriptRemoting method
@RemoteAction
global static string createAccount(String accName, String accDes, String accPhn){
 Account acc = new Account();
 acc.name = accName;
 acc.Description = accDes;
 acc.Phone = accPhn;
 insert acc;
 return 'Success';
}
That is it, You have created a visualforce page that is using bootstrap css for view and apex controller for saving the records.

PS: For different type of element you can use different class as:
CheckBox:
<div class="checkbox col-md-4">
 <label>
   <input type="checkbox"> Check Box</input>
 </label>
</div>
//get the checkbox values as this or you can also get a array of objects and use .each
//for multiple checkboxes id starting with inp4
function checkId(){
   var inpVal= $j('#inp4').prop('checked');
   alert(inpVal);
}

Hope this helps you!!

How to use apex:dynamicComponent in visualforce page to generate DOM elements at run time

Ok so today I am sharing the code for how to generate apex component dynamically. Salesforce has introduced a new feature call as "apex:dynamicComponent", what this does is it will introduce visualforce markup in the page from controller just like a dynamic binging.

To do this use this in the visualforce page:
<apex:dynamicComponent componentValue="{!outPanel}"/>
Now in the class write this:
Public transient Component.Apex.OutputPanel outPanel{get;set;}
Public List<sObject> vNewLst{get;set;}
public void getdynPan(){      

vNewLst = database.query('Select Id,Name from Account limit 100');    
outPanel = new Component.Apex.OutputPanel();   
Component.Apex.DataTable datatable = new
Component.Apex.DataTable(var='row');    
datatable.expressions.value='{!vNewLst}';    
list<String> displayFieldLst= new list<String>{'Id','Name'};    
Component.Apex.column clm;   
Component.Apex.OutputText outText;      
  for(string s: displayFieldLst){          
    clm = new Component.Apex.column(headerValue= '' + s + '');         
    outText = new Component.Apex.OutputText();          
    outText.expressions.value = '{!row[\'' + s + '\']}';         
    clm.childComponents.add( outText );      
    datatable.childComponents.add( clm );
  }  
  outPanel.childComponents.add( datatable );
}

What this code will do it will create a output panel and bind a datatable inside it with Id and Name columns and then display it on the page.

Hope this will help you!!

How to use apex:dynamicComponent in visualforce page to generate DOM elements at run time

Ok so today I am sharing the code for how to generate apex component dynamically. Salesforce has introduced a new feature call as "apex:dynamicComponent", what this does is it will introduce visualforce markup in the page from controller just like a dynamic binging.

To do this use this in the visualforce page:
<apex:dynamicComponent componentValue="{!outPanel}"/>
Now in the class write this:
Public transient Component.Apex.OutputPanel outPanel{get;set;}
Public List<sObject> vNewLst{get;set;}
public void getdynPan(){      
vNewLst = database.query('Select Id,Name from Account limit 100');    
outPanel = new Component.Apex.OutputPanel();   
Component.Apex.DataTable datatable = new Component.Apex.DataTable(var='row');    
datatable.expressions.value='{!vNewLst}';    
list<String> displayFieldLst= new list<String>{'Id','Name'};    
Component.Apex.column clm;   
Component.Apex.OutputText outText;      
for(string s: displayFieldLst){          
clm = new Component.Apex.column(headerValue= '' + s + '');         
outText = new Component.Apex.OutputText();          
outText.expressions.value = '{!row[\'' + s + '\']}';         
clm.childComponents.add( outText );      
datatable.childComponents.add( clm );
}  
outPanel.childComponents.add( datatable );
}
What this code will do it will create a output panel and bind a datatable inside it with Id and Name columns and then display it on the page.

Hope this will help you!!

Wednesday, August 20, 2014

How to use Salesforce to Salesforce

Salesforce to Salesforce or commonly known as S2S is a data migration feature that is provided as OOB by Salesforce.com. When there is a requirement for data to be moved from one Salesforce Org to another then without using any third party tools as CastIron or Sap BODS we can move data. The idea is to provide a near runtime integration between org. Some points to consider when implementing S2S:


  •  You cannot publish fields that you do not have permission to edit.
  • Only some of the standers objects and all custom objects are permitted to send data.
Follow these steps to enable and configure S2S:

  1. Go to App Setup > Customize > Salesforce to Salesforce > Settings and click enable.

Tuesday, August 19, 2014

How to use "System.RunAs" in test class

Ok so few times we are facing a challenge that a piece of code that we are covering in test must be run under only for some specific users. in this case we can use "System.RunAs" to over come the limitations, here is an example so we can pass it:

// This code runs as the admin user
Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator']; 
User u = new User(Alias = 'tadmins', Email='testAdmin2014@testorg.com', 
EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
LocaleSidKey='en_US', ProfileId = p.Id, 
TimeZoneSidKey='America/Los_Angeles', UserName='testAdmin2014@testorg.com');
System.runAs(u) {
// here the code for test class
}

Hope this helps you!!

Thursday, August 14, 2014

How to get date based on fiscal year,quarter or month

Date startDate = [Select StartDate From Period Where type = 'Quarter' and StartDate = THIS_FISCAL_QUARTER].StartDate;

Date startDate = [Select StartDate From Period Where type = 'Month' and StartDate = THIS_FISCAL_Month].StartDate;

Date startDate = [Select StartDate From Period Where type = 'Year' and StartDate = THIS_FISCAL_Year].StartDate;

The above will get you the current start date for the custom fiscal year.
Note: Custom fiscal year has to be setup if you want any results.

Thursday, August 7, 2014

How to play video in visualforce from attachment

So we have developed many data driven pages but when it comes to multimedia then many of us didn't worked on it much. We are thing "Ok its just a video or a image I will display it by getting its path" but the problem arise when its(the MIME file) is an attachment. Attachments are stored in database unlikely if compared from static resource which has a direct access URL. So how can I display a multimedia file if its type is BLOB.

The answer is here, we can use <object> tag or we can have <video> tag of HTML5.
for <object> tag, here the {!crwAtt.id} is Attachment object.
hor <video> tag, remember to add "docType="html-5.0"" to page.

Tuesday, August 5, 2014

How to use escape sequences with SOQL

So you are trying to pass some quoted string in a SOQL query and hits a error as some thing like this "line break not allowed". Now to over come this you can use the escape sequence provided by salesforce. What it really does is that when ever a string ends by single quote then salesforce mark it as a non break sequence, but when you introduce another quote then it breaks the single string into two if "+" is not used. Ok fare enough but if we need more then one quote then it will be very diffycult to add all those "+" signs. So to do this we can use the below methods:

\n or \N New line
\r or \R Carriage return
\t or \T Tab
\b or \B Bell
\f or \F Form feed
\" One double-quote character
\' One single-quote character
\\ Backslash
LIKE expression only: \_ Matches a single underscore character ( _ )
LIKE expression only:\% Matches a single percent sign character ( % )

Example: database.query('Select Id from Account where Id IN ('0019000000txvCQ','0019000000txvCQ')'); wont work

database.query('Select Id from Account where Id IN (\'0019000000txvCQ\',\'0019000000txvCQ\')'); will work

Thursday, July 24, 2014

How to use sObject in Apex salesforce

Hi so today I was searching around the net to get some example to use sObjects of salesforce but I was not able to find some, so I decided to make one here with very easy approach.


  • Declaring a sObject - sOject objAcc = new sObject (); // without type
                                     sOject objAcc = new Account (); // with type
  • Getting field values - sOject objAcc = new Account ();
                                    Id oId = objAcc.Id;
                                    String nameAcc = objAcc.get('Name'); // "Name" is field's API name
  • Setting field values - sOject objAcc = new Account ();
                                    objAcc.put('Name','TestName');
Hope this helps someone.

How to solve cross domain parent URL access

So you are here because you were trying to access parent page's url with the child iframe and ran into this error:

"SecurityError: Blocked a frame with origin https://c.ap1.visual.force.com from accessing a frame with origin https://ap1.salesforce.com. Protocols, domains, and ports must match."

In simple words what this means that the site is not allowing you to gain access to the parent frame because it can be used in many hack attacks and is trying to safe guard the application. But if you still need this there is an alternative approach insted of doing this
window.parent.location.href()
You can do this:
var hurl = document.referrer;
So now you can access the cross domain parent url.
Hope this helps some one.

Wednesday, July 23, 2014

How to use Rest Api services in Salesforce

Ok so I am finding many post in which people want to learn Rest api or they already know the fundamental but are unable to create an example for some reason. So I will be showing you that how we can hit a REST GET service and retrieve data from salesforce.

We need the following things to do so:
  1. A rest api class definition in our saleforce org.  
  2. A rest callout tool.
  3. "Authorization" some kind of token so we can get in.
So first we need our Rest api class:


Now we need a rest callout tool so download a chrome extension called "Advance rest client" Link.

And now we need authorization so there are many ways for quick I will be showing the simplest way just to test it.
Open "https://login.salesforce.com/"> Login > Open Developer Console > Debug > Open Execute .. >
Type : system.debug('**'+userinfo.getSessionId()); > Execute.
Now search the debug log for "**" and copy the whole token eg: 00D90000000eCBG!AGHYT.BrtWEQdym9cDsUGcvPYEVKr4aEuNHSxqpMH_YQHS53.24x.HZxKDh1XGbNpjopkdylqvTv5tnFUOIUH.Epzxxxx

Now open the advance rest client tool and tupe this:
  • In the URL : https://<server>.salesforce.com/services/apexrest/showAcc?setquery=select Id,Name from Account limit 10
  • In the Header: Authorization: OAuth 00D90000000eCBG!AGHYT.BrtWEQdym9cDsUGcvPYEVKr4aEuNHSxqpMH_YQHS53.24x.HZxKDh1XGbNpjopkdylqvTv5tnFUOIUH.Epzxxxx
  • Click send.
That is it you will receive a response some thing like this:

Note: OAuth flow here: https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/intro_understanding_web_server_oauth_flow.htm


Hope this help you.

Tuesday, July 22, 2014

How to make dynamic reference in apex code

So we are used to develop apex code with static reference. What it means is the code is referencing the object directly and when this code is moved in a package then the referenced object will automatically be included in it. But it might happen that you only need the code to be included in the package as the object is already present in the install org.

Static reference code:

Dynamic reference code:

Thursday, July 10, 2014

How to create a baisc table to display the list of data in Visualforce

So this is a quick example to bind list of data from the controller or extension to the visualforce page. Below is the visualforce page and extensions:

<apex:page standardController="Account" extensions="VFBasic3"> <!-- Give the name for extension -->
<apex:form >

<!-- Declare a page block to contain every thing in  -->
    <apex:pageBlock title="Account List">

<!-- Declare a page block section for formating  -->
<apex:pageBlockSection columns="1">

<!-- Declare a page block table to display the data in  -->
            <apex:PageBlockTable var="row" value="{!accList}">
            <!-- {!accList} is our list in the extension and row is our variable for each record -->
<!-- Declare a column  -->
                <apex:column headerValue="Name">

<!-- Declare a field to bind the values with-->
                    <apex:outputField value="{!row.Name}"/>
                </apex:column>
                <apex:column headerValue="Phone">
                    <apex:outputField value="{!row.Phone}"/>
                </apex:column>
                <apex:column headerValue="Fax" >
                    <apex:outputField value="{!row.Fax}"/>
                </apex:column>
            </apex:PageBlockTable>
            <hr/>
            <apex:dataTable var="row" value="{!accList}">
                <apex:column headerValue="Name" width="200">
                    <apex:outputField value="{!row.Name}"/>
                </apex:column>
                <apex:column headerValue="Phone" width="200">
                    <apex:outputField value="{!row.Phone}"/>
                </apex:column>
                <apex:column headerValue="Fax" width="100">
                    <apex:outputField value="{!row.Fax}"/>
                </apex:column>
            </apex:dataTable>
            <hr/>
            <apex:repeat var="row" value="{!accList}">
                <apex:outputField value="{!row.Name}"/>
            </apex:repeat>
        </apex:pageBlockSection>
    </apex:pageBlock>
</apex:form>
</apex:page>
public class VFBasic3 {
public List<Account> accList{get;set;}
    //Initialize the list to avoid null pointers
    public VFBasic3(ApexPages.StandardController controller) {
        accList=getListAcc();
    }
    //Use SOQL to get records
    public List<Account> getListAcc(){
        List<Account> acc= [select Id,Name,Phone,Fax from Account limit 10];
        return acc;
    }
}
The above code is mostly self explanatory if you have any questions please post a comment.

Hope this helped you!! 

Wednesday, July 9, 2014

How to write basic trigger with bulk handling

So in Salesforce.com one of the basic things is to write trigger on objects to automate the functional flow according to the business logic. And many of us face the problem in the starting to how to get started with triggers in salesforce. The basic syntex is given below

<sObject Name>   = write the name without the angular parenthesis
<trigger events> = write events as before insert, before update, after insert, after update, before delete, after undelete
trigger on <sObject Name> <trigger Name> (<trigger events>) {
 //Logic for trigger events
}
Now to write it for single record.

trigger on Account tAccountBIBU (before insert, before update) {
 //Check for events
 if(trigger.isBefore && trigger.isInsert){
  trigger.new[0].Description = 'Hi This is test Insert'; 
 }
 if(trigger.isBefore && trigger.isUpdate){
  trigger.new[0].Description = 'Hi This is test Update'; 
 }
}
The above code is not bulkefied as it will only effect the [0] element in the list.
trigger on Account tAccountBIBU (before insert, before update) {
 //Check for events
 if(trigger.isBefore && trigger.isInsert){
  for(Account acc : trigger.new){
   acc.Description = 'Hi This is test Insert'; 
  }
 }
 if(trigger.isBefore && trigger.isUpdate){
  for(Account acc : trigger.new){
   acc.Description = 'Hi This is test Update'; 
  }
 }
}
Now the above code is bulkefied and will effect every record in the trigger.new list

Hope this helped you!!

Monday, July 7, 2014

How to understand "Apex CPU time limit exceeded"

Ok so have developed that one big data driven page with all the logic but when the data hits some thrashold point you receive this error: Apex CPU time limit exceeded. This is a common problem when your page is having very complex logic that the apex run time compiler cannot finish in a given synchronous cycle. In simple words the error is due to the logic to be very complex to be completed in CPU limit time.
Salesforce has 10000 millisecond for synchronous and 60000 millisecond for asynchronous.

There are few way we can resolve this error :

  1. Limit the data - if you know that after a certain amount of data this error occurs then provide a limit to your SOQL.
  2. Reduce the number to for, while etc loops - as number to iteration is lower the CPU compiles faster.
  3. Use Map and Sets. 

Saturday, June 28, 2014

How to configure your android device for office and personal work

Ok so this is a slity non saleforce related topic but it is very useful. It will also be helpful in facing some saleforce related task. So here it goes, if you need a proper configuration then get these things setup in your device:

1. Setup your gmail account and link it with your phone.

2. Setup your office mail in the mail application.

3. Use google calander to plan meeting and share it with people.

4. Install google drive, watsup, viber , skype, adobe reader, winzip and quick office.

5. For saleforce users install saleforce1 and saleforceA.

6. Use 3g networks for good speed.

7. Use google map to share path ways for office location or meeting halls.

Feel free to add more fetures by posting in the comments section.

10 things you must have if you are a traveling saleforce developer

The world of saleforce is so connected and vast that many time it may bappen that you have to go to other cities for work or meeting. And if you are a developer or admin it might happen you have to develop or config some of the changes that customer asked ASAP. Here are 10 things you must have so you can complete the task

1. A decient internet connection, if you have dongel its good but if not then at least a 3g enabled mobile phone with modem support. You can easly attach android to laptop via usb cable and share data connection by going in setting>tethadering port>usb tethadering.

2. Eclips helios for developing and depoloyment related task.

3. List of all username,password and security token.

4. SaleforceA installed in your device, believe me its very usefull for smaller task like resetting userpassword.

5. Saleforce1 for recent changes for mobile varification.

6. Link for database.io an online data loader.

7. Saleforce Soql guide for reference.

8. Wight list your ip if you are accessing the org from some other or new network. Note this has to be done before flying out or ask your admin to provoid you.

9. Microsoft excel or open office installed for accesing importand document. Or if not use chrome it has pdf and doc support in built.

10. If you have laptop that you carry then admin rights, some time we need to install thoes handy little software to debug webservice callout failure.

Hope this help you out have a nice day.

Friday, June 27, 2014

Hot to read debug logs in salesforce

There are times when we have that one buggy code and to get it sorted out we have to make our hands dirty. Reading the debug code log is a very frustrating task. If you have to do it keep the below points in mind it might help you.

1. Always search for "USER_DEBUG" chances are the may be some with logical values.
2. If the code is going in catch block search for "Exception" it will quickly show the error message.
3. The loop variables and flow will again return to the start of the execution.
4. Always read the line number in "[]" as we can quickly which line the code went in.
5. If the code debug is for trigger then remember that before events value changes are not captured in log implicitly.
6. If you have manage package with triggers then for the triggers the values will appear in separate limit log in side debug log.

Hop these tips help you get most out of debug logs.

Thursday, June 26, 2014

How to use "Savepoint" and "Rollback" in apex Salesforce

Many times when we are coding and handling exception we do not thing about transaction control. Transaction control is a process to handle the flow to data that is being committed to data base based on the condition that satisfy our logic. Consider this in a code flow you are updating Account and at the same time you are creating related Opportunity records, this is in try catch block and the yet to be created Opportunity records do not satisfy the validation condition and fails to insert, but the Accounts are already updated and because it is a try block the error is just thrown to catch which do not do any thing.


We can use "Savepoint" and "Rollback" to revert the changes that "Update" operation has done.

Example:
In the above code we are setting "Savepoint" at line 9 and reverting database at line 17.
Hope this help some one.

Wednesday, June 25, 2014

How to have sorting in list for visualforce Salesforce

Many time when working with visualforce page to display list of records to the user the commonly asked feature is to have sorting. Sorting can be easy achieved by using standerd saleforce having the below structure :

[ORDER BY fieldExpression ASC | DESC ? NULLS FIRST | LAST ?]

or simply it can be written as :

SELECT Name FROM Account ORDER BY Name DESC NULLS LAST

But that is not the only way, we can do this by the below mentioned ways:
  • Sorting (Order By) in SOQL.
  • Using List methods to sort list.
  • Custom sorting.
Sorting (Order By) in SOQL.
Example : SELECT Name FROM Account ORDER BY Name DESC NULLS LAST

Using List methods to sort list.
Example : List.sort();

Using this method, you can sort primitive types and sObjects (standard objects, custom objects, and SelectOption). For more information on the sort order used for sObjects, see List Sorting. You can also sort your own custom types if they


Custom sorting.
Example : 

Friday, June 20, 2014

How to check "undefined" in javascript in visualforce Salesforce

It is very important that if we are using javascript remoting that we check the result for undefined, as it might happen that no value is retrieved for the result and we are referring it in the page.
Take an example of this:
var res = result;
alert(res.Custom__c);
it returns "undefined" if the value of "Custom__c" is null.

To overcome this in javascript we can check the variable for typeof undefines as:

if (typeof(var) == 'undefined')  
or
if (typeof(var) != 'undefined')
Hope this helps some one :)

How to get records from inner SOQL query

Inner SOQL query are great way to get related child records when querying parent records. In back end its just file "Join" query so that results will be displayed encapsulated by parent records. I came up with this query when I need to get all attachments of a account and display it on the visualforce page as a download link.

List<Account> vAccLst = [SELECT Id, Name, Type, (SELECT Id,ContentType from Attachments) from Account where Id IN: vSetAcc];

This will return the result in some what this form :
You can use the attachment as mentioned below:

  • String IdAttach = vAccLst[0].Attachments[0].Id;

or a more robust approach is :

  • Set<String> attachId = new Set<String>();
  • for(Account acc: vAccLst){
  • for(Attachments a : acc.Attachments){
  •      attachId.add(a.Id);
  • }
  • }

Wednesday, June 18, 2014

How to get started with Salesforce1 visualforce development using Jquery mobile

Today application on force.com are very stable and are well integrated with each other, but as the new phase is coming we have to learn to develop mobile application on the same platform. As many application are now moving to mobile platform Salesforce has also joined in the race.

Salesfore1 platform enables you the develop and deploy the mobile version compatible application to cloud. Using the same technology with a little help of Jquery we can make mobile enable visualforce pages  to meet our requirement. 

Follow these steps to get the mobile version example and Jquery mobile zip installed in your organization.
Salesforce1 Mobile package for more information you can go to Getting Started.

After installing the above package create a new visualforce page and paste this code:

Now paste this class code:


The above code is for custom lookup, as we cannot get standard lookup in visualforce pages yet.
Hope this helps you.

How to use System.assert in Salesforce

So you are writing code and trigger a lot but as a mandatory step you need to have at lest 75% or greater of production code coverage to move your code. "Ok no problem I will write a test class for this trigger/class" will be your answer, but what happen if your code contains try catch block or you have some value returning from a method that you want to cross check. To cover the above scenario we can take help from "System.assert" method provided by salesforce.

Reference Link

Say I have a validation rule on opportunity that will only allow me to insert opportunity records if the probability is more then 50%. And I am inserting an "Opportunity" at the time of "Account" creation:


Now in my above if I try to give probability less then 50 then error will occur and my test will fail. To avoid this in my test class I can use try catch and inside catch I can use assert like this:

Hope this helps you.

How to get OAuth / Access token from Salesforce

Ok so you are doing integration and need to get the oauth token. There are many ways we can get it but if you need you can brows from these klinks :

Server Side Auth
Username and Password Auth
Understanding Auth

But for now we can just use this:

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

grant_type:password
client_id:********************************************
client_secret:***************
username:<Username>
password:<Password><Sec Token>

client_id: Is the client id of the connected app.
client_secret: Is the secret of the connected app.

The responce will be some thing like this with the access token:

Responce:
{ "id": "https://login.salesforce.com/id/XXXXXXXXX/XXXXXXXXXXXX",
"issued_at": "1399267999911",
"token_type": "Bearer",
"instance_url": "https://ap1.salesforce.com",
"signature": "XXXXQWXXXX/xXXXXXMsN/CCCCyrHzI=",
"access_token": "0FFGGGFFFG!AQEAQNpfMEtD1nccdssafaFFGGYCFneh8HGo9MHV9Eowl5zoNcNUwhWMb6RpdQcTPFakqxQSQmD_1jIBB78mjK95" }

How to access Connection User in debug log.

We all work with external points where data is created by connection user in salesforce. One example is the Salesforce to Salesforce connection record share. In this the data is created by a special user called as "Connection User". "That's ok what is the problem in that" well the problem is that if there is a trigger or validation rule that is not letting the data to be created in the receiving org then we cannot view "Connection User" in debug log.
But there is a little trick that you can use :

https://XXX.salesforce.com/p/setup/layout/AddApexDebugLogUser?retURL=%2Fsetup%2Fui%2FlistApexTraces.apexp&UserLookupInput_lkid=YYYYYYYYYYYYYY
&UserLookupInput=Connection%20User

Use this URL and replace "XXX" with your domain name and "YYYYYYYYYYYYYY" with the ID of the connection user (can get it if you have any record in the org created by that user, the Id will be in the OwnerId). Just put those there and hit enter the user will be added in the debug log.

Tuesday, June 17, 2014

Sunday, June 15, 2014

How to get Element Id using Jquery in Visualforce Salesforce

Ok so you have made a very nice page and want to add Jquery to get some visual effect or maybe for some validation, but stuck on how to get Id of an element. As in Javascript we can get Id using hardcoding as:
var eleId = documnet.getElementById("jO1:jO8");

The problem in Jquery is that we can use "#" tag to get the value but it is not effective as some time we may need to get array to values so in that case we can use the below approach, also we can use name to get jquery object.



Thursday, June 12, 2014

How to solve "unable to send email" problem in Salesforce

Some time an error occurs with a nature of "unable to send email" in apex or in workflow. The first place to look is in the "Email Administration".

Go to Setup > Administration Setup > Deliverability > Access to Send Email
and check the drop-down list : it should be "All email". If not change it to "All email" and save.

That's it.

Sunday, June 8, 2014

How to pass parameter from page to component in visualforce page

When we work with visualforce pages then it is a good practice to put the code that will be used more then once into a component. This approch is good but it is not dynamic say "Search". If you need a page to Search different objects and also need to use component then an fast approch is to pass the variable name as parameter and search on that bases.

Example:

Now if the page is passing the value in objName parameter then at the component side we can get this as :

Example:

Now the values passed from the page is assigned to the variable in component.

Thursday, June 5, 2014

How to use Hierarchy Custom Setting

Hierarchy Custom Setting is one of the powerful feature provided by salesforce. Powerful as because we can use it in Apex code, Workflow Process and Validation Rule. To use it in workflow and validation rule just use it as :
{!$Setup.CustomSettingName__c.CustomFieldName__c}
If you want to use it in code then see the below example:
CustomSetting__c cus = CustomSetting__c getInstance(Userinfo.getUserId());
string mPhone = cus.CustomField__c;

  • getInstance() Returns a custom setting data set record for the current user.
  • getInstance(ID) Returns the custom setting data set record for the specified user ID.
  • getInstance(ID) Returns the custom setting data set record for the specified profile ID.
  • getOrgDefaults() Returns the custom setting data set record for the organization.
  • getValues(ID) Returns the custom setting data set record for the specified user ID.
  • getValues(ID) Returns the custom setting data set for the specified profile ID.

Monday, June 2, 2014

How to use Aggregate SOQL

Aggregate functions in SOQL, such as SUM() and MAX(), allow you to roll up and summarize your data in a query. You can use aggregate functions without using a GROUP BY clause. To get result of aggregate Soql query we have to use AggregateResult array or list.

Aggregate Function : 
  • AVG()
  • COUNT() and COUNT(fieldName)
  • COUNT_DISTINCT()
  • MIN()
  • MAX()
  • SUM()
However, these functions become a more powerful tool to generate reports when you use them with a GROUP BY clause.