Thursday, 15 May 2014

Padding Text in Salesforce / Visualforce

Introduction

Last time I got a request from a client to limit a number to 6 digits and if the number has less than 6 digits, prepend 0 in front of it.

Example: 7007 must become 007007

I had to do this in 
  1. Javascript (for display in a disabled textbox) , 
  2. Visualforce (for display in a PDF), and 
  3. Apex (to send to a Web Service).

Javascript

For the Javascript version, I wrote a small function that would do the left padding of zeroes. This function is called when the page is loaded.
 function addZeroes(eId, size){  
      var elem = document.getElementById(eId)  
      while(elem.value.length < size)  
           elem.value = "0" + elem.value  
 }

The function takes the element Id and size as parameter to limit left padding. In my case the element was an input of type text:
 <input id="agent_number" type="text" value="{!$User.Agent__c}" disabled="true"/>  

The addZeroes() function was called as follows in a <script> tag after the form was loaded.
 <script>  
      addZeroes("agent_number", 6);  
 </script>  

Visualforce

The visualforce solution was hard to find but very simple to implement. I used the formula LPAD.
 {!LPAD($User.Agent_No__c,6,'0')}  

Apex

I could not find a solution that resembles the visualforce LPAD in Apex. I used two methods from the String Class to achieve the same result.
 String agentNum = '7007';  
 String agentNumber = agentNum.leftPad(6).replace(' ', '0');  
 system.debug('## agentNumber : ' + agentNumber);  
leftPad() method is used to pad spaces in front without exceeding the length parameter.
replace() method is used to replace all the spaces with 0.

Thnx & Cheers,
Gulshan.

Sunday, 4 May 2014

Twitter Application-only authentication in Salesforce Apex

Hello all,

Today I will be posting an example on how to implement the Twitter Application-only authentication using Salesforce Apex.

Overview


The Twitter Application-only authentication is used when no user sign-in with Twitter is required.
When using this type of authentication, we are allowed to call limited Twitter functionalities, namely :


  • Pull user timelines;
  • Access friends and followers of any account;
  • Access lists resources;
  • Search in tweets;
  • Retrieve any user information;

  • In our example, we will be implementing the Authentication flow described in Twitter Application-only authentication which involves two HTTP requests.

    Code


     public TwitterContr(){  
          HttpRequest req = new HttpRequest();  
          req.setMethod('POST');  
          req.setEndpoint('https://api.twitter.com/oauth2/token');  
            
          //// Step 1: Encode consumer key and secret  
            
          String consumerKey = 'xvz1evFS4wEEPTGEFPHBog';  
          String consumerSecret = 'L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg';  
            
          Blob headerValue = Blob.valueOf(consumerKey + ':' + consumerSecret);  
          String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(headerValue);  
         
          //// Step 2: Obtain a bearer token  
                 
          req.setHeader('Authorization', authorizationHeader);  
          req.setHeader('Content-Type','application/x-www-form-urlencoded;charset=UTF-8');  
          req.setBody('grant_type=client_credentials');  
         
          // Create a new http object to send the request object  
          // A response object is generated as a result of the request  
          // the server will respond with a JSON-encoded payload  
         
          Http http = new Http();  
          HTTPResponse res = http.send(req);  
          
          String jsonStr = res.getbody();  
          JSONParser parser = JSON.createParser(jsonStr);  
            
          // extract access token from JSON response  
          string accessToken;  
          while (parser.nextToken() != null) {  
               if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'access_token')) {  
                    // Get the value.  
                    parser.nextToken();  
                    accessToken = parser.getText();  
               }  
          }  
         
          // access token can now be used to perform other requests  
          //// Step 3: Authenticate API requests with the bearer/access token  
            
          // e.g. searching for tweets   
            
          HttpRequest req1 = new HttpRequest();  
          req1.setMethod('GET');  
          req1.setEndpoint('https://api.twitter.com/1.1/search/tweets.json?q=%23freebandnames');  
         
          String authorizationHeader1 = 'Bearer ' + accessToken;  
          req1.setHeader('Authorization', authorizationHeader1);  
         
          Http http1 = new Http();  
          HTTPResponse searchResponse = http.send(req1);  
          system.debug('## body1 : ' + searchResponse.getBody());  
     }  
    

    Cheers!!