Thursday, November 27, 2014

calculate Case Age Based On Working (Business) Hours

To track the time spent by an agent on a case taking into consideration the business hours, you will need to request the "Enable Case Duration/Age in Business Hours" feature to be enabled for your org. This will give you a field called "Business Hours Age" that can only be included in your reports.

**NOTE: The "Business Hours Age" field will not be available in reports if the business hours for the Organization is set to 24/7.

If you require information that can be displayed on the case record itself you can create a complex formula. An example of what a formula for CST and standard M-F business hours (these business hours need to be configured under Setup | Company Profile | Business Hours)  is below:

IF(DATEVALUE(CreatedDate) = DATEVALUE(ClosedDate),  
(ClosedDate - CreatedDate) * 24,  
((CASE(MOD(DATEVALUE(CreatedDate) - DATE(1985,6,24),7),  
0 , CASE( MOD(DATEVALUE(ClosedDate) - DATEVALUE(CreatedDate) ,7),1,2,2,3,3,4,4,5,5,5,6,5,1),  
1 , CASE( MOD(DATEVALUE(ClosedDate) - DATEVALUE(CreatedDate) ,7),1,2,2,3,3,4,4,4,5,4,6,5,1),  
2 , CASE( MOD(DATEVALUE(ClosedDate) - DATEVALUE(CreatedDate) ,7),1,2,2,3,3,3,4,3,5,4,6,5,1),  
3 , CASE( MOD(DATEVALUE(ClosedDate) - DATEVALUE(CreatedDate) ,7),1,2,2,2,3,2,4,3,5,4,6,5,1),  
4 , CASE( MOD(DATEVALUE(ClosedDate) - DATEVALUE(CreatedDate) ,7),1,1,2,1,3,2,4,3,5,4,6,5,1),  
5 , CASE( MOD(DATEVALUE(ClosedDate) - DATEVALUE(CreatedDate) ,7),1,0,2,1,3,2,4,3,5,4,6,5,0),  
6 , CASE( MOD(DATEVALUE(ClosedDate) - DATEVALUE(CreatedDate) ,7),1,1,2,2,3,3,4,4,5,5,6,5,0),  
999)  
+ (FLOOR((DATEVALUE(ClosedDate) - DATEVALUE(CreatedDate))/7)*5)  
- 2) * 9)  
+  
MAX((  
DATETIMEVALUE(TEXT(YEAR(DATEVALUE(CreatedDate))) & "-" & TEXT(MONTH(DATEVALUE(CreatedDate))) & "-" & TEXT(DAY(DATEVALUE(CreatedDate))) & " 01:00:00am") - CreatedDate + 1) * 24, 0))  
+  
MAX((ClosedDate -  
DATETIMEVALUE(TEXT(YEAR(DATEVALUE(ClosedDate))) & "-" & TEXT(MONTH(DATEVALUE(ClosedDate))) & "-" & TEXT(DAY(DATEVALUE(ClosedDate))) & " 16:00:00pm")) * 24, 0)

Note: This is only an example and should only be used as a reference. It is not advised that you copy/paste this formula in your environment as different time zones/business hours will make it behave differently. Lastly, this formula may not work properly on List Views/Reports, for reports, use the  "Business Hours Age" field.  

Monday, October 20, 2014

Reading QRcodes in Salesforce1

Get the Static Resource File QRCode From the below url
https://github.com/LazarSoft/jsqrcode

Visual force page:
<apex:page >
    <script type="text/javascript"
      src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.2.min.js"></script>
 
<script type="text/javascript" src="{!URLFOR($Resource.QRCode, 'jsqrcode-master/src/grid.js')}"></script>
<script type="text/javascript" src="{!URLFOR($Resource.QRCode, 'jsqrcode-master/src/version.js')}"></script>
<script type="text/javascript" src="{!URLFOR($Resource.QRCode, 'jsqrcode-master/src/detector.js')}"></script>
<script type="text/javascript" src="{!URLFOR($Resource.QRCode, 'jsqrcode-master/src/formatinf.js')}"></script>
<script type="text/javascript" src="{!URLFOR($Resource.QRCode, 'jsqrcode-master/src/errorlevel.js')}"></script>
<script type="text/javascript" src="{!URLFOR($Resource.QRCode, 'jsqrcode-master/src/bitmat.js')}"></script>
<script type="text/javascript" src="{!URLFOR($Resource.QRCode, 'jsqrcode-master/src/datablock.js')}"></script>
<script type="text/javascript" src="{!URLFOR($Resource.QRCode, 'jsqrcode-master/src/bmparser.js')}"></script>
<script type="text/javascript" src="{!URLFOR($Resource.QRCode, 'jsqrcode-master/src/datamask.js')}"></script>
<script type="text/javascript" src="{!URLFOR($Resource.QRCode, 'jsqrcode-master/src/rsdecoder.js')}"></script>
<script type="text/javascript" src="{!URLFOR($Resource.QRCode, 'jsqrcode-master/src/gf256poly.js')}"></script>
<script type="text/javascript" src="{!URLFOR($Resource.QRCode, 'jsqrcode-master/src/gf256.js')}"></script>
<script type="text/javascript" src="{!URLFOR($Resource.QRCode, 'jsqrcode-master/src/decoder.js')}"></script>
<script type="text/javascript" src="{!URLFOR($Resource.QRCode, 'jsqrcode-master/src/qrcode.js')}"></script>
<script type="text/javascript" src="{!URLFOR($Resource.QRCode, 'jsqrcode-master/src/findpat.js')}"></script>
<script type="text/javascript" src="{!URLFOR($Resource.QRCode, 'jsqrcode-master/src/alignpat.js')}"></script>
<script type="text/javascript" src="{!URLFOR($Resource.QRCode, 'jsqrcode-master/src/databr.js')}"></script>

  <form>
      <div style="float:right;">
    <input type="file" onchange="previewFile()" /><br/>
    </div>
  <h1>Preview</h1>
   <div style="height:200px">
    <img src="" id="preview" height="200" alt="Image preview..." />
   </div>
  </form>

    <p>If the image above looks clear, click the decode button.  If not, try again!</p>
    <button id="decode" onclick="decode()">Decode</button>
  <script>

  function read(a)
  {
        alert(a);
        if( (typeof sforce != 'undefined') && (sforce != null) ) {
            sforce.one.navigateToSObject(a);
        }
        else {
            window.location="/" + a;
        }      
  }      
     
  $(document).ready(function() {
        qrcode.callback = read;
  });


function previewFile() {
  var preview = document.querySelector('#preview');
  var file    = document.querySelector('input[type=file]').files[0];
  var reader  = new FileReader();

  reader.onloadend = function () {
    preview.src = reader.result;
  }

  if (file) {
    reader.readAsDataURL(file);
  } else {
    preview.src = "";
  }
}

function decode() {
    try
    {
    var preview=document.querySelector('#preview');
    qrcode.decode(preview.src);
    }
    catch (e)
    {
       alert('Error - ' + e);
    }
}

</script>
</apex:page>


Check the Available for Salesforce mobile apps checkbox

Create a visualforce tab for this visualforce page

click Setup-> Mobile Adminstration -> Mobile navigation -> Move the Tab to the right

Login to salesforce1 you can see the tab and click on the chose file. That will prompt you to take snap
and when the scan completes click on decode.

Encrypting and decrypting String

Blob data = Blob.valueOf('Test data to encrypted');
Blob cryptoValue = Crypto.generateAesKey(256);
Blob encryptedData = Crypto.encryptWithManagedIV('AES256', cryptoValue, data);
Blob decryptedData = Crypto.decryptWithManagedIV('AES256', cryptoValue, encryptedData);
String decryptedDataString = decryptedData.toString();
System.debug(decryptedDataString);

How do you convert a Blob to string?

Blob b;
String b64;
String strUrlUTF8;
String strOriginal;

strOriginal = 'Joe’s CafĂ© & Bar ♫';
System.debug('String strOriginal: [' + strOriginal + ']');

strUrlUTF8 = EncodingUtil.urlEncode(strOriginal, 'UTF-8');
System.debug('String strUrlUTF8: [' + strUrlUTF8 + ']');

b = Blob.valueOf(strUrlUTF8);
System.debug('Blob b: [' + b.toString() + ']');

b64 = EncodingUtil.base64Encode(b);
System.debug('String b64: [' + b64 + ']');

b = EncodingUtil.base64Decode(b64);
System.debug('Blob b: [' + b.toString() + ']');

strUrlUTF8 = b.toString();
System.debug('String strUrlUTF8: [' + strUrlUTF8 + ']');

strOriginal = EncodingUtil.urlDecode(strUrlUTF8, 'UTF-8');
System.debug('String strOriginal: [' + strOriginal + ']');

Wednesday, September 17, 2014

Display images on visualforce page from the attachment/document

The image can be displayed in the VF page by using <apex : image> tag. Image source is specified by "URL" attribute.
But the url should be in the form : " /servlet/servlet.FileDownload?file=xxxxxxxxxxx" where  xxxxxxxxxxx is the the unique id of theDocument/Attachment record containing the image.


Example :

A sample Visual Force page along with the custom controller. For this example, I have stored an image in the Document object with name"sample pic".

Controller :
=================================
public with sharing class ImageController {
 public String imageURL{get;set;}
 
  public ImageController()
  {
    imageURL='/servlet/servlet.FileDownload?file=';
    List< document > documentList=[select name from document where
                                    Name='SamplePic'];
 
    if(documentList.size()>0)
    {
      imageURL=imageURL+documentList[0].id;
    }
  }
}
====================================

Here I have taken a String variable declared as public. I am initializing this variable in controller with "servlet/servlet.FileDownload?file=" value. This variable will be used in VF page as a URL parameter in <apex : image> tag.

The controller fetches the document record from the Document object based on the "name" field specified in the SOQL query.

The only thing remaining in the imageURL is the unique id of document record. So after fetching record from the object, append "id" to the imageURL variable.



Visual Force Page :
=====================

<apex:page controller="ImageController" showheader="false" sidebar="false">

    <apex:form>
      <apex:image url="{!imageURL}">
    </apex:image></apex:form>

</apex:page>
========================

Here we are binding the imageURL ( String variable of controller class ) to the url attribute of <apex : image> tag.

Tuesday, September 9, 2014

Query Using Java Script and display in Pageblock Table using custom html

Sometime we need to create table in visual force page with html elements with same look and feel as standard pageblocktable. So we did not need to add extra style class in html table. We can do it with the standard style classes.

the data to the pageblocktable will be queried from the javascript using sforce.execute.query
We need to do a little work to search the standard class name from pageblockTable and add those classes to custom html table:
As I have taken a simple example to show how to use the standard style class:

Visual Force page code:

<apex:page >
<style>
    tr.dataRow {
       background-color:white;
    }
    tr.dataRow:hover {
       background-color: #e3f3ff;
    };
</style>
<script type="text/javascript">
        var __sfdcSessionId = '{!GETSESSIONID()}';
    </script>
<script src="../../soap/ajax/31.0/connection.js" type="text/javascript"></script>
<script type="text/javascript">
    window.onload = setupPage;
    function setupPage() {
           sforce.connection.query("Select Id,Name,BillingCity,BillingState from  Account 1000",
           {onSuccess : layoutResults,
              onFailure : queryFailed,
                  source : {
                         output : document.getElementById("output"),
                         startTime : new Date().getTime()
                     }
              });
 }
    function queryFailed(error, source) {
       source.output.innerHTML = "<font color 'red'>An error has occurred: </font> <p>" + error;
       }
       
                     
function layoutResults(queryResult, source) {

     if (queryResult.size > 0) {
     var output = "<table class='list' border='0' cellpadding='0' cellspacing='0'><tr class='headerRow'>";
         output +="<th class='headerRow'> Account Name</th><th class='headerRow'> Billing City </th><th class='headerRow'> Billing Country</th>";

     //get the records array
     var records = queryResult.getArray('records');

     //loop through the records and construct html string
     for (var i = 0; i < records.length; i++) {
          var account = records[i];
          output += "<tr class='dataRow'><td class='dataCell'>"+ account.Name + "</td><td class='dataCell'>" + account.BillingCity +
            "</td><td class='dataCell'>" + account.BillingState + "</td></tr>";
     }
        output =output+"</td></tr></table>"
     //render the generated html string
     source.output.innerHTML = output;
     }
}
</script>
<apex:pageBlock >
     <div id="output"  ></div>
</apex:pageBlock>

</apex:page>


Wednesday, August 27, 2014

Paypal Integration With Salesforce

1. Need to set up developer account in paypal
http://developer.paypal.com
nd create one account there. After creating, login there only. In the left menu you will find "Test Accounts" link. Click on that.
From the right side screen, you can create multiple test accounts.
For testing purpose generally you need two type of accounts. One is "Seller" and one is "Buyer". Its always better to create preconfigured accounts.

Page:
<apex:page controller="PaypalProcessor" />
<apex:form>
<apex:inputText value="{!firstName}"/>
<apex:inputText value="{!lastName}" />
<apex:inputText value="{!Addy1}" />
<apex:inputText value="{!Addy2}" />
<apex:inputText value="{!CardType}" />
<apex:inputText value="{!CardNo}" />
<apex:inputText value="{!expMo}" />
<apex:inputText value="{!expYe}" />
<apex:commandbutton value="submit" action="{!doDirectPayment}" />
</apex:form>

</apex:page>

Controller:
global class PaypalProcessor{

    public  string amount {set;get;}
    public  String result {set;get;}
    public  string FirstName{get; set; }
    public  string LastName{get; set; }
    public  string Addy1{get; set; }
    public  string Addy2{get; set; }
    public  string Country{get; set; }
    public  string CardType{get; set; }
    public  string CardNo{get; set; }
    public  string expMo{get; set; }
    public  string expYe{get; set; }
    public  string CVV{get; set; }
    public  string city{get; set; }
    public  string state{get; set; }
    public  string zip{get; set; }
    public  string payer{ get; set; }
    public  string transid {get; set;}
    public  string message {get; set; }
    public  string err {get; set; }
    public  string rawResponse {get; set; }
    public XmlStreamReader reader;

    public PaypalProcessor(){
      city = '';
      state = '';
      zip = '';
      CVV = '';
      expYe = '2019';//2019
      expMo = '04';//04
      CardNo = '4256541603152055'; //4256541603152055
      CardType = 'Visa'; //Visa
      FirstName = '';
      LastName = '';
      Country = 'US'; //US
      Addy1 = '';
      Addy2 = '';
      payer = '';
      err = '';
      message = '';
    }

    public String doDirectPayment()
    {
      //Use the username password credentials of your Paypal account
    // this below credentials will now work
        String url =https://api-3t.sandbox.paypal.com/2.0/;
        string un =ssanebina-ftator_api1.gmail.com ;
        string pw =13968266;
        string sig =An5nso7MWUdW4QKJi4-ALQdI5p2aNE1c5OKgKgV6zf5tPo3 ;
        Http h = new Http();
        HttpRequest req = new HttpRequest();
                req.setHeader('Host','api-aa.sandbox.paypal.com');}
              this host is for paypal production
               // req.setHeader('Host','api-aa.paypal.com');
             }
        }
        if(CardType == 'AMEX'){
            CardType='Amex';
        }
    String doDirectRequest;
      doDirectRequest =  '<soap:Envelope xmlns:soap=' + '\'' + 'http://schemas.xmlsoap.org/soap/envelope/'  + '\'' + ' xmlns:xsi=' + '\''+ 'http://www.w3.org/2001/XMLSchema-instance'  + '\'' + ' xmlns:xsd=' + '\''+ 'http://www.w3.org/2001/XMLSchema' + '\'' + '>';
      doDirectRequest += '<soap:Header><RequesterCredentials xmlns="urn:ebay:api:PayPalAPI"><Credentials xmlns="urn:ebay:apis:eBLBaseComponents">';
      doDirectRequest += '<Username>' + un + '</Username><ebl:Password xmlns:ebl="urn:ebay:apis:eBLBaseComponents">' + pw;
      doDirectRequest += '</ebl:Password><Signature>' + sig + '</Signature>';
      doDirectRequest += '</Credentials></RequesterCredentials></soap:Header><soap:Body><DoDirectPaymentReq xmlns="urn:ebay:api:PayPalAPI">';
      doDirectRequest += '<DoDirectPaymentRequest><Version xmlns="urn:ebay:apis:eBLBaseComponents">1.00</Version>';
      doDirectRequest += '<DoDirectPaymentRequestDetails xmlns="urn:ebay:apis:eBLBaseComponents">';
      doDirectRequest += '<PaymentAction>Authorization</PaymentAction><PaymentDetails><OrderTotal currencyID="USD">' + amount + '</OrderTotal>';
      doDirectRequest += '<ShipToAddress><Name>' + FirstName + ' ' + LastName + '</Name><Street1>' + Addy1 + '</Street1><Street2>' +Addy2 + '</Street2>';
      doDirectRequest += '<CityName>' + city + '</CityName><StateOrProvince>' + state + '</StateOrProvince><PostalCode>' + zip + '</PostalCode>';
      doDirectRequest += '<Country>' + country + '</Country></ShipToAddress>';
      doDirectRequest += '</PaymentDetails><CreditCard><CreditCardType>' + CardType + '</CreditCardType><CreditCardNumber>' + CardNo + '</CreditCardNumber>';
      doDirectRequest += '<ExpMonth>' + expMo + '</ExpMonth><ExpYear>' + expYe + '</ExpYear><CardOwner><PayerStatus>verified</PayerStatus>';
      doDirectRequest +=
       '<PayerName><FirstName>' + FirstName+ '</FirstName><LastName>' + LastName + '</LastName></PayerName><PayerCountry>' + country + '</PayerCountry>';
      doDirectRequest += '<Address><Street1>' + Addy1 + '</Street1><Street2>' + Addy2 + '</Street2><CityName>' + city + '</CityName>';
      doDirectRequest += '<StateOrProvince>' + state + '</StateOrProvince><Country>' + country + '</Country><PostalCode>' + zip + '</PostalCode></Address>';
      doDirectRequest += '</CardOwner><CVV2>' + CVV + '</CVV2></CreditCard></DoDirectPaymentRequestDetails>';
      doDirectRequest += '</DoDirectPaymentRequest></DoDirectPaymentReq></soap:Body></soap:Envelope>';
 
      System.debug('Request Value:'+doDirectRequest);
 
      req.setEndpoint(url);
      req.setMethod('POST');
      req.setHeader('Content-length', '1753' );
      req.setHeader('Content-Type', 'text/xml;charset=UTF-8');
      req.setHeader('SOAPAction','');
      req.setTimeout(120000);
 
      HttpResponse res = h.send(req);
      String xml = res.getBody();
      rawResponse = xml;
      system.debug('::' + rawResponse);
      reader = res.getXmlStreamReader();
      result = readXMLResponse(reader,'Ack');
      reader = res.getXmlStreamReader();
      err = readXMLResponse(reader, 'LongMessage');
 
      if (result == 'Success')
      {
        reader = res.getXmlStreamReader();
        transid = readXMLResponse(reader, 'TransactionID');
        if(transid == null){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error,err));
        }
      }
      else
      {
        result = err;
      }
      return result;
    }

    public String readXMLResponse(XmlStreamReader reader, String sxmltag)
    {
      string retValue; // Read through the XML
      while(reader.hasNext())
      {
        if (reader.getEventType() == XmlTag.START_ELEMENT)
        {
          if (reader.getLocalName() == sxmltag) {
            reader.next();
            if (reader.getEventType() == XmlTag.characters)
            {
              retValue = reader.getText();
            }
          }
        }
        reader.next();
      }
      return retValue;
    }

    /*public String processPayment(){
 
     message = doDirectPayment();
      if (message != 'Success'){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error,message));
      }
      return message;
    }*/

    webservice static String doVoidPayment(String objtransaction)
    {
         //Use the username password credentials of your Paypal account
        // this below credentials will now work

        String url =https://api-3t.sandbox.paypal.com/2.0/;
        string un =ssanebina-ftator_api1.gmail.com ;
        string pw =13968266;
        string sig =An5nso7MWUdW4QKJi4-ALQdI5p2aNE1c5OKgKgV6zf5tPo3 ;
   
        Http h = new Http();
        HttpRequest req = new HttpRequest();
             req.setHeader('Host','api-aa.sandbox.paypal.com');
               //This Host is for production
               // req.setHeader('Host','api-aa.paypal.com');
           
     String doVoidRequest='';
   
      doVoidRequest += '<soap:Envelope xmlns:soap=' + '\'' + 'http://schemas.xmlsoap.org/soap/envelope/'  + '\'' + ' xmlns:xsi=' + '\''+ 'http://www.w3.org/2001/XMLSchema-instance'  + '\'' + ' xmlns:xsd=' + '\''+ 'http://www.w3.org/2001/XMLSchema' + '\'' + '>';
      doVoidRequest += '<soap:Header><RequesterCredentials xmlns="urn:ebay:api:PayPalAPI"><Credentials xmlns="urn:ebay:apis:eBLBaseComponents">';
      doVoidRequest += '<Username>'+un+'</Username><ebl:Password xmlns:ebl="urn:ebay:apis:eBLBaseComponents">'+pw;
      doVoidRequest += '</ebl:Password><Signature>'+sig+'</Signature>';
      doVoidRequest += '</Credentials></RequesterCredentials></soap:Header><soap:Body><DoVoidReq xmlns="urn:ebay:api:PayPalAPI"><DoVoidRequest xmlns="urn:ebay:api:PayPalAPI"><Version xmlns="urn:ebay:apis:eBLBaseComponents">86.0</Version>';
      doVoidRequest += '<AuthorizationID>'+objtransaction+'</AuthorizationID></DoVoidRequest></DoVoidReq></soap:Body></soap:Envelope>';
     
      req.setBody(doVoidRequest);
     
 
      System.debug('Request Value:'+doVoidRequest);
      req.setEndpoint(url);
      req.setMethod('POST');
      req.setHeader('Content-length', '1753' );
      req.setHeader('Content-Type', 'text/xml;charset=UTF-8');
      req.setHeader('SOAPAction','');
      req.setTimeout(120000);
 
      HttpResponse res = h.send(req);
      String xml = res.getBody();
      System.XmlStreamReader reader = res.getXmlStreamReader();
      PaypalProcessor proc=new PaypalProcessor();
      String result = proc.readXMLResponse(reader,'Ack');
      system.debug(xml);
      return result;
    }

     webservice static String doRefundPayment(String objtransaction)
    {
   
      //Use the username password credentials of your Paypal account
    // this below credentials will now work
        String url =https://api-3t.sandbox.paypal.com/2.0/;
        string un =ssanebina-ftator_api1.gmail.com ;
        string pw =13968266;
        string sig =An5nso7MWUdW4QKJi4-ALQdI5p2aNE1c5OKgKgV6zf5tPo3 ;

        Http h = new Http();
        HttpRequest req = new HttpRequest();

             req.setHeader('Host','api-aa.sandbox.paypal.com');}
              // This host is for production
               // req.setHeader('Host','api-aa.paypal.com');
           
     String doReFundRequest;
   
      doReFundRequest =  '<soap:Envelope xmlns:soap=' + '\'' + 'http://schemas.xmlsoap.org/soap/envelope/'  + '\'' + ' xmlns:xsi=' + '\''+ 'http://www.w3.org/2001/XMLSchema-instance'  + '\'' + ' xmlns:xsd=' + '\''+ 'http://www.w3.org/2001/XMLSchema' + '\'' + '>';
      doReFundRequest += '<soap:Header><RequesterCredentials xmlns="urn:ebay:api:PayPalAPI"><Credentials xmlns="urn:ebay:apis:eBLBaseComponents">';
      doReFundRequest += '<Username>'+un+'</Username><ebl:Password xmlns:ebl="urn:ebay:apis:eBLBaseComponents">'+pw;
      doReFundRequest += '</ebl:Password><Signature>'+sig+'</Signature>';
      doReFundRequest += '</Credentials></RequesterCredentials></soap:Header><soap:Body><RefundTransactionReq xmlns="urn:ebay:api:PayPalAPI"><RefundTransactionRequest><Version xmlns="urn:ebay:apis:eBLBaseComponents">86.0</Version>';
      doReFundRequest += '<TransactionID>'+objtransaction+'</TransactionID><RefundType>Full</RefundType><Memo>customer requested refund.</Memo></RefundTransactionRequest></RefundTransactionReq></soap:Body></soap:Envelope>';
     
      req.setBody(doReFundRequest);
 
      System.debug('Request Value:'+doReFundRequest);
 
      req.setEndpoint(url);
      req.setMethod('POST');
      req.setHeader('Content-length', '1753' );
      req.setHeader('Content-Type', 'text/xml;charset=UTF-8');
      req.setHeader('SOAPAction','');
      req.setTimeout(120000);
 
      HttpResponse res = h.send(req);
      String xml = res.getBody();
      System.XmlStreamReader reader = res.getXmlStreamReader();
      PaypalProcessor proc=new PaypalProcessor();
      String result = proc.readXMLResponse(reader,'Ack');
      system.debug(xml);
      return result;              
    }
}

Monday, August 25, 2014

Creating Calendar event in Google from salesforce using Oauth

To Create a calendar event in google you need to set up OAuth between Salesforce and Google.

You need to create an app in Google. Navigate to
https://code.google.com/apis/console and create a project.

Vf Page:
<apex:page controller="CalenderConnect">
<apex:form >
  <apex:commandButton value="Google" action="{!doGoogleConnectCall}"/><br/>
</apex:form>
</apex:page>

Controller:
public class CalenderConnect {
    private final string googleClientID = ' Your Project ID';
    private final string googleSecretCode = 'Your Project Secret';
    private final string redirectURI = 'https://c.ap1.visual.force.com/apex/calender';
    private string authorizationCode = '';
    private string state = '';
    private string accessToken;
    private string refreshToken;
    private string expiresIn;
    private string tokenType;
 
     public CalenderConnect(){
        authorizationCode = System.currentPageReference().getParameters().get('code');
        if(authorizationCode != null){
            state = System.currentPageReference().getParameters().get('state');
            accessToken = '';
                retrieveGoogleAccessToken();
                if(accessToken <> ''){
                    addCalendarEntry();
                }              
        }
    }

    public pageReference doGoogleConnectCall(){

        PageReference pr = new PageReference('https://accounts.google.com/o/oauth2/auth' +
            '?response_type=code' +
            '&client_id=' + googleClientID +
            '&redirect_uri=' + redirectURI +
            '&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar' +
            '&state=' + 'vcalender ' +
            '&access_type=online' +
            '&approval_prompt=auto' +  //auto, force
            '&login_hint=xxxx@gmail.com');
            System.debug(pr);
        return pr;
    }
    private void retrieveGoogleAccessToken(){
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        string endPointValue = 'https://accounts.google.com/o/oauth2/token';  
        req.setEndpoint(endPointValue);
     
        string bodyRequest = '';
        bodyRequest = 'code=' + EncodingUtil.urlEncode(authorizationCode, 'UTF-8');
        bodyRequest += '&client_id=' + EncodingUtil.urlEncode(googleClientID, 'UTF-8');
        bodyRequest += '&client_secret=' + EncodingUtil.urlEncode(googleSecretCode, 'UTF-8');
        bodyRequest += '&redirect_uri=' + EncodingUtil.urlEncode(redirectURI, 'UTF-8');
        bodyRequest += '&grant_type=authorization_code';
        req.setBody(bodyRequest);    
        req.setHeader('Content-length', string.ValueOf(bodyRequest.length()));
        req.setHeader('Content-Type', 'application/x-www-form-urlencoded');
        req.setMethod('POST');
        req.setTimeout(10000);
        HttpResponse res = h.send(req);  
        map<string, string> jsonValues = new map<string, string>();
     
        System.debug('Response Value:'+res.getBody());
        jsonValues = parseJSONToMap(res.getBody());
        if(jsonValues.containsKey('error')){
        }else{
            //Try to get a cell value in the Google Spreadsheet
            accessToken = jsonValues.get('access_token');
            refreshToken = jsonValues.get('refresh_token');
            expiresIn = jsonValues.get('expires_in');
            tokenType = jsonValues.get('token_type');        
        }    
    }
      private void addCalendarEntry(){
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        string endPointValue = 'https://www.googleapis.com/calendar/v3/calendars/primary/events';
        //This end point does seem to work, but it is not creating an event, just creating a new calendar
        //endPointValue = 'https://www.googleapis.com/calendar/v3/calendars?key=' + googleClientID;
        req.setEndpoint(endPointValue);  
        string bodyRequest = '';
        bodyRequest = '{';
        bodyRequest += '\r\n';
        bodyRequest += '"summary": "Sales Call",';
        bodyRequest += '\r\n';
        bodyRequest += '"location": "Conference Room A",';
        bodyRequest += '\r\n';
        bodyRequest += '"start": {';
        bodyRequest += '\r\n';
        bodyRequest += '"dateTime": "2014-07-26T08:00:00.000-07:00",';
        bodyRequest += '\r\n';
        bodyRequest += '"timeZone": "America/Los_Angeles"';
        bodyRequest += '\r\n';
        bodyRequest += '},';
        bodyRequest += '\r\n';
        bodyRequest += '"end": {';
        bodyRequest += '\r\n';
        bodyRequest += '"dateTime": "2014-07-26T08:30:00.000-07:00",';
        bodyRequest += '\r\n';
        bodyRequest += '"timeZone": "America/Los_Angeles"';
        bodyRequest += '\r\n';
        bodyRequest += '},';
        bodyRequest += '\r\n';
        bodyRequest += '"recurrence": [';
        bodyRequest += '\r\n';
        bodyRequest += '"RRULE:FREQ=WEEKLY;UNTIL=20131226T000000Z"';
        bodyRequest += '\r\n';
        bodyRequest += '],';      
        bodyRequest += '\r\n';
        bodyRequest += '"attendees": [';
        bodyRequest += '\r\n';
        bodyRequest += '{';
        bodyRequest += '\r\n';
        bodyRequest += '"email": "xxxxx@gmail.com"';
        bodyRequest += '\r\n';
        bodyRequest += '}';
        bodyRequest += '\r\n';
        bodyRequest += ']';
        bodyRequest += '}';
     
        req.setBody(bodyRequest);    
        System.debug(bodyRequest);
        req.setHeader('Authorization', 'Bearer ' + accessToken);
        req.setHeader('Content-length', string.ValueOf(bodyRequest.length()));
        req.setHeader('Content-Type', 'application/json; charset=UTF-8');
        req.setMethod('POST');
        req.setTimeout(10000);
        HttpResponse res = h.send(req);
        System.debug(res.getBody());
    }
 
    private map<string, string> parseJSONToMap(string JSONValue){
        JSONParser parser = JSON.createParser(JSONValue);
        map<string, string> jsonMap = new map<string, string>();
        string keyValue = '';
        string tempValue = '';
        while (parser.nextToken() != null) {
            if(parser.getCurrentToken() == JSONToken.FIELD_NAME){
                keyValue = parser.getText();
                parser.nextToken();
                tempValue = parser.getText();
                jsonMap.put(keyValue, tempValue);            
            }
        }
        return jsonMap;
    }
 
}

Accessing FaceBook from Salesforce

Here is an example to get connected to Facebook and get the Facebook information

Need to create 2 visual force pages and 2 controllers.

Before creating the vf pages and controller you need to create an app in facebook.
To create an app navigate to
https://developers.facebook.com/
and create an app you will get Client Id and secret. Paste those values in FBRedirectURI class .

Vf Page:
<apex:page controller="FaceBookApp" showHeader="false" sidebar="false" action="{!getAccessToken}">
</apex:page>

Controller:
public class FaceBookApp {
    String ClientId='Your Facebook App Id';
    public PageReference getAccessToken() {
        PageReference pgReference=new PageReference('https://graph.facebook.com/oauth/authorize?client_id='+ClientId+'&redirect_uri=https://ap1.salesforce.com/apex/facebook/FaceBookRedirecturi&scope=user_about_me&state=/FaceBookApp');
pgReference.setRedirect(true);
return pgReference;
        pgReference.setRedirect(true);
        return pgReference;
    }
}

Vf Page :
<apex:page controller="FBRedirectURI" action="{!init}"  sidebar="false" showHeader="false">
<html>
<body>
<h2 style="align:middle">Congratulations, You have added the app to your account </h2>
</body>
</html>
</apex:page>

Controller:
public class FBRedirectURI {
    public PageReference init() {
         String ClientId='Your Facebook App Id';
         String Secret='Your Facebook App Secret';
        try{
            if (! ApexPages.currentPage().getParameters().containsKey('code')) {
                ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.FATAL, 'Missing code parameter');
                ApexPages.addMessage(msg);
            }
        String code = ApexPages.currentPage().getParameters().get('code');
        System.debug('Facebook OAuth Step 2 - code:'+code);
        String state =  ApexPages.currentPage().getParameters().get('state');
        System.debug('state:'+state);
        String tokenURI = 'https://graph.facebook.com/oauth/access_token?client_id='+ClientId+'&redirect_uri='+
            +'https://ap1.salesforce.com/apex/FaceBookRedirecturi'+
                        + '&client_secret='+decrypt(Secret)+'&code='+code;                  
        System.debug('tokenURI is:'+tokenURI);
             
        HttpRequest req = new HttpRequest();
        req.setEndpoint(tokenURI);
        req.setMethod('GET');
        req.setTimeout(60*1000);
     
        Http h = new Http();
        String response;
        if (code != '' || code != null) {
            HttpResponse res = h.send(req);
            response = res.getBody();
        }
        if(response.contains('access_token'))
        {
        System.debug('Facebook response is:'+response);
        String accessToken = '';
        Integer acc = response.indexOf('access_token');
        Integer amp = response.indexOf('&');
        if ( amp == -1 ) {
            accessToken = response.substring(acc + 13, response.length());
        } else {
            accessToken = response.substring(acc + 13, amp);
        }
        System.debug(accessToken);
                String me=doGet('https://graph.facebook.com/me?access_token='+accessToken);
                System.debug(me);
            }
        }catch(Exception e){
            System.debug(e.getMessage()+e.getStackTraceString());
        }
        return null;
    }

    public FBRedirectURI(){
    }

    private static String doGet(String url) {
        String response;
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setEndpoint(url);
        req.setMethod('GET');
        req.setTimeout(60*1000);
        HttpResponse res;
            res = h.send(req);
            response = res.getBody();        
     
        //fb returns a 302 temp redirect with the url for the profile image
        if(res.getStatusCode() == 302)
        {
            System.debug('Received a 302, Header Location value is:'+res.getHeader('Location'));
            response = '{"data": [{"url": "'+res.getHeader('Location')+'"},]}';
        }
     
        System.debug('API RESP: '+response);

        return response;
    }
    public static String decrypt(String data) {
        EncryptionSettings__c settings = EncryptionSettings__c.getOrgDefaults();
        /*if (settings.key__c == null) {
            throw new FacebookException('Cannot decrypt without a key!');
        }*/
        Blob key = EncodingUtil.base64Decode('Ad40G2d8aNE3z9YD1cHRLtiO4vCxMrZg5ZHcs6jm/cc=');
        return Crypto.decryptWithManagedIV('AES256', key, EncodingUtil.base64Decode(data)).toString();
    }
}

You Can find the example in the below link:
http://skm.force.com/facebook

Monday, August 4, 2014

Extract all field names from an SObject

public class ExtractFields {
   public static void queryAllFields(String objTypeName) {
        Schema.DescribeSObjectResult[] descResult = 
            Schema.describeSObjects(new String[]{objTypeName});
        
        Map<String, Schema.SObjectField> fsMap = descResult[0].fields.getMap();
        List<String> fieldNames = new List<String>(fsMap.keySet());
        for(String f:fieldNames){
            System.debug(f);
        }

String queryString = 'SELECT '+String.join(fieldNames, ',')+' FROM '+objTypeName+' LIMIT 1';
        SObject obj = Database.query(queryString);
        
        System.debug(obj);
    }
}

In Execute Method: Call ExtractFields.queryAllFields(Account);

REST queries using JQuery.

<apex:page >
  <apex:includeScript value="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"/>
  <script>
    jQuery(document).ready(function($) {
      $('#queryform').submit(function(){
        $.ajax($('#query').val(),
        {
          beforeSend: function(xhr) {
            xhr.setRequestHeader('Authorization', 'Bearer {!$Api.Session_ID}');
          },
          success: function(response) {
            $('#results').text(JSON.stringify(response, null, '  '));
          },
          error: function(jqXHR, textStatus, errorThrown) {
            alert(jqXHR.status + ': ' + errorThrown);
          }
        });
        return false;
      });
    });
  </script>
  <h1>Test REST API from JavaScript</h1>
  <form id="queryform">
    <input id="query" size="120" value="/services/data/v28.0/query?q=SELECT+Name+FROM+Account+LIMIT+10"/>
    <input type="submit" id="submit" value="Submit" />
  </form>
  <p>Results:</p>
  <pre id="results">
  </pre>
</apex:page>

Friday, April 4, 2014

Create Calender from salesforce to Google,Yahoo, Outlook

Adding an event from salesforce

Visualforce page:

<apex:page controller="CalenderConnect">
<apex:form >
  <apex:commandLink value="Add Event to My Calender" action="{!displayCalender}"/><br/>
  <apex:outputPanel rendered="{!calenderShow}">
  <apex:pageMessages ></apex:pageMessages>
  <apex:outputLabel value="Outlook Email:"></apex:outputLabel>
  <apex:inputText value="{!emailValue}"/>
  <apex:commandLink action="{!outlookConnect}" value="OutLook"/><br/>
  <apex:commandLink target="_blank" action="{!doYahooconnectCall}" value="Yahoo"/><br/>
  <apex:commandLink target="_blank" action="{!googleConnectCall}" value="Google"/>
  </apex:outputPanel>
</apex:form>
</apex:page>

Apex Controller

public class CalenderConnect {
    public Boolean calenderShow { get; set; }
    public String emailValue { get; set; }

    public PageReference displayCalender() {
        calenderShow =true;
        return null;
    }
    public PageReference outlookConnect() {
        System.debug(emailValue);
        if(emailValue ==''){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO,'Email Address Should be specified')); }
        try{
        String vCal = 'BEGIN:VCALENDAR'+ '\n'
                            +'VERSION:1.0' + '\n'
                            +'BEGIN:VEVENT' + '\n'
                            +'URL:Site Url'+ '\n'
                            +'DTSTART:20140329T223000Z'+ '\n'
                            +'DTEND:20140330T023000Z'+ '\n'
                            +'SUMMARY:Message'+ '\n'
                            +'DESCRIPTION:Body Message'+ '\n'
                         +'LOCATION:Class of 1923 Ice Rink - 3130 Walnut St - Philadelphia, PA 19104'+'\n'
                            +'END:VEVENT'+ '\n'
                            +'END:VCALENDAR'+ '\n';
        List<String>toAddresses = new List<String>();
        toAddresses.add(emailValue);
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        email.setSubject('Test');
        email.setToAddresses(toAddresses);
        email.setHtmlBody('Test');
        email.setPlainTextBody('Test');
        Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
        efa.setFileName('invite.ics');
        efa.setBody(Blob.ValueOf(vCal));
 
        //attachments.add(efa);
        efa.setContentType('text/calendar');
        email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
         Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
        }
        catch(Exception e){
            System.debug(e.getMessage()+e.getStackTraceString());
        }
        return null;
    }
    public PageReference googleConnectCall() {
        PageReference pr = new PageReference('https://www.google.com/calendar/render?action=TEMPLATE'+
                            '&text=Scheduling the Meeting at Test Message'+
                            '&dates=20140329T223000Z/20140330T023000Z'+
                            '&details=Body of the event'+
                            '&location=Location Where the meeting is going to hel    d'+
                            '&output=xml');
            System.debug(pr);
        return pr;
    }
    public Pagereference doYahooconnectCall(){
        PageReference pr = new PageReference('https://calendar.yahoo.com/?v=60&view=d'+
                               '&type=20'+
                               '&title=Scheduling the Meeting at Test Message'+
                               '&st=20140329T223000Z&dur=0400'+
                               '&desc=Body of the event' +
                               '&in_loc=Location Where the meeting is going to held');
            System.debug(pr);
        return pr;
    }
}
 
   
 

Bar Code and QR code From Vf page to Email

Create a formula field in Contact object with any of the code(QR,Bar Code).  Before clicking on the email button in the vf page pass the id as the parameter in the url.

The formula would be
QR Code
IMAGE('https://chart.googleapis.com/chart?chs=150x150&cht=qr&chl=MECARD:N:' + FirstName + ' ' + LastName +';ADR:'+ MailingStreet +',' + MailingCity + ',' + MailingState + ',' + MailingCountry + ',' + MailingPostalCode + ';TEL:'+ MobilePhone +';EMAIL:' + Email + ';', 'Scan the QR code' )

Bar Code
IMAGE("http://www.barcodesinc.com/generator/image.php?code="+Id+"&style=325&type=C128B&width=200&height=50&xres=1&font=3" ,"Barcode")

Vf Page Code
<apex:page standardController="Contact" extensions="BarcodeController">
<apex:form >
<!-- <apex:inputField value="{!contact.QR_Code__c}"/>
<apex:inputField value="{!contact.Bar_Code__c}"/> -->

<apex:commandButton value="sendEmail" action="{!sendEmail}"/>
</apex:form>
</apex:page>

Apex Controller
public class BarcodeController {
    public Contact cont;
    public Id contactId; 

    public BarcodeController(ApexPages.StandardController controller) {

        //cont=(Contact)controller.getRecord();
        contactId=controller.getId();
    }
    
    public void sendEmail(){
        if(contactId !=null || contactId != ''){
            Cont=[select Id,Bar_Code__c,Qr_Code__c from Contact where id = : contactId limit 1];
        }
        String email='xxx@gmail.com';
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.setToAddresses(new String[] { email });
            mail.setSubject('Bar Code and the Q.R Code Demo');
           
            String body = cont.Bar_Code__c+
                        +cont.Qr_Code__c;
            mail.setHtmlBody('Scan the Qr code and the Bar code'+body );
     
        // Send the email
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }

}


Labels

visualforce page ( 13 ) apex integration ( 5 ) apex trigger ( 4 ) csv file from vf page ( 4 ) javascript ( 4 ) csv visualforce page ( 3 ) Too many ( 2 ) call out ( 2 ) integration ( 2 ) rest api ( 2 ) salesforce rest api ( 2 ) salesforce to salesforce integration ( 2 ) sfdc rest api ( 2 ) trigger ( 2 ) 15 digit to 18 digit ( 1 ) DML rows in Apex ( 1 ) Date Conversion ( 1 ) Date/Time conversion ( 1 ) Deploy ( 1 ) Objects to Future Annotated Methods ( 1 ) SFDC limits ( 1 ) Sobject to Future Annotated Methods ( 1 ) Test Class ( 1 ) TimeZone Conversion ( 1 ) Too many dml rows ( 1 ) Too many future calls ( 1 ) annotations ( 1 ) apex code ( 1 ) closed opportunities ( 1 ) commit ( 1 ) convert ( 1 ) create records ( 1 ) csv create records ( 1 ) custom setting ( 1 ) deployment ( 1 ) deployment changeset ( 1 ) disable apex class ( 1 ) disable apex trigger ( 1 ) disable in production ( 1 ) document ( 1 ) download ( 1 ) field name ( 1 ) formula fields ( 1 ) iframe ( 1 ) inactive ( 1 ) intellisense ( 1 ) jsforce ( 1 ) limits ( 1 ) matrix report in vf page ( 1 ) multi select ( 1 ) multi select salesforce ( 1 ) multiselect ( 1 ) paypal ( 1 ) picklist ( 1 ) record type ( 1 ) rollback ( 1 ) salesforce limits ( 1 ) salesforce list ( 1 ) salesforce map ( 1 ) salesforce rest ( 1 ) salesforce set ( 1 ) salesforce1 ( 1 ) sandbox deployment ( 1 ) sfdc collection ( 1 ) sfdc list ( 1 ) sfdc map ( 1 ) sfdc rest ( 1 ) sfdc set ( 1 ) uncommitted ( 1 ) updated field ( 1 ) user ( 1 ) validation rule opportunity ( 1 ) validation rules opportunities ( 1 ) vf page ( 1 )

Ad