Showing posts with label Integration. Show all posts
Showing posts with label Integration. Show all posts

Saturday, 21 June 2014

#Salesforce Integration With Twilio

I was searching Twilio integration with salesforce on the web but didn't find any, so am posting this a simple POC of sending SMS to the mobile using Twilio from the Salesforce UI.


Its simple but just you need to do something extra two make this functionality working.

We will go step by step for this
First of all create a new account on Twilio click here 
Twilio will provide you a number, via which it will sent you SMS.

Now login to your salesforce account and create a Remote Site Setting.
In Remote Site URL enter https://api.twilio.com, like shown below

And then create a custom setting named as Twilio Configuration.
We are gonna use them in our apex classes.
Create fields on the custom setting you've just created, with same API name as below shown.


Now we need to provide some values to the fields ofthe custom setting click on Manage button shown above.

Before entering any values to the fields click on these links
For Auth Token and Account SID Click Here
For Test Credetials i.e. Test Account SID and Test Auth Token Click Here

For Account Name enter the name from which you registered like your email id.
For From Phone Number enter that number which got when you created account on Twilio.
After that save your custom setting.

Custom Setting should look something like this


After that you can save the code provided here GitHub 

Page will look something like this




See that was a piece of cake :)
Hope everything works just fine.
Happy coding..!!!

Wednesday, 25 December 2013

Google Map Integration With Salesforce

I got a requirement of showing google map of Account Billing address on detail page of Account. In the starting I was thinking how to do it, but didn't get anything, but now at the end I tried this below code and everything is working as fine as visible down there.

In this below scenario user don't have to submit their APIKey of Google Map to get the Map of the Address. and one more thing here am not using any Controller/Apex class only and only page is doing everything.

Here it is the Detail Page of Account and the Location of Account billing address using Google Map


Below is the Visual force Page

<!--
/**
* Description : Component for showing google map of Account Address.
*
* Created Date : 12/25/2013
*
* Created By : Abhi Tripathi
*
* Version : V1_0
**/
-->
<apex:page standardController="Account">
    
    <!-- Import Necessary Jquery js File and StyleSheets-->
    <apex:includeScript value="{!URLFOR($Resource.jQuery_GoogleMap, 'js/GSensor.js')}"/>
    <apex:includeScript value="{!URLFOR($Resource.jQuery_GoogleMap, 'js/jquery-1.6.2.min.js')}"/>
    <script>
    var map,geocoder,infowindow;
    var latLngs = [];
    $j = jQuery.noConflict();
    $j(document).ready(function(){
        initialize();
    });
    
    function initialize() {
        geocoder = new google.maps.Geocoder(37.09024, -95.712891);
        //initial cordinates for map init
        var latlng = new google.maps.LatLng();
        var myOptions = {
            center: latlng,
            zoom: 2,
            maxZoom: 14,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        
        //load the map
        map = new google.maps.Map($j('#map')[0], myOptions);
        codeAddress();
    }
    
    /*This function codes the address using the Billing Address in the Acoount*/
    function codeAddress(){
        //prepare a string for geocoding
        var address = '{!JSENCODE(Account.BillingStreet)},{!JSENCODE(Account.BillingCity)},{!JSENCODE(Account.BillingCountry)},{!JSENCODE(Account.BillingPostalCode)}';
        console.log(address);
        
        //geocode the address
        geocoder.geocode( { 'address': address }, function(results, status) {
            //if it is a success
            if (status == google.maps.GeocoderStatus.OK) {
                var location = results[0].geometry.location;
                var marker=addMarker(location );
            }
            else {
                // alert(status);
            }
        });
    }
    
    /*
*This method adds a marker to the provided location
**/
    function addMarker(location) {
        marker = new google.maps.Marker({
            position: location,
            map: map
        });
        //set the bounds and initial zoom
        var latlngbounds = new google.maps.LatLngBounds();
        latlngbounds.extend(marker.getPosition());
        map.fitBounds(latlngbounds);
        map.setZoom(14);
        return marker;
    }
    
    </script>
    <style>
        #map {
        width:100%;
        height:500px;
        margin-left:59.5%;
        }
    </style>
    <div id="map" class="ui-widget-content ui-corner-all ui-state-default"></div>
</apex:page>


Save that above code before that save this Jquery files and after that save them into your static resource with their corresponding name

Click Below Links for the JQuery files

GSensor
jquery-1.6.2.min
jquery-ui-1.8.16.custom.min

After saving the above jquery files in Static Resource and saving your visualforce page.

Go to
Customize --> Accounts --> Page Layout --> Edit(One of page layout) --> Visualforce Pages(sidebar of layout)

Search your page and add it to the page layout. and see the magic
Note: Billing address need to be filled with correct addres otherwise its will show a default map.

Happy Coding..!!

Sunday, 24 November 2013

Salesforce launches the internet of Customers "Salesforce1"

Salesforce1 is meant to allow the rapid creation of apps that can work across Salesforce's sales, service, and marketing apps, as well as on top of its Force.com, Heroku, and ExactTarget Fuel platforms, all at the same time. Salesforce1 is a free, automatic upgrade for existing Salesforce customers.


Salesforce1 is a new social, mobile and cloud customer platform built to transform sales, service and marketing apps for the Internet of Customers. As the pioneer of enterprise cloud computing, salesforce.com is launching the next generation of the world’s #1 cloud platform, Salesforce1, for the new connected world. Now every company can connect with customers in a whole new way.

New Salesforce1 is the first CRM platform for developers, ISVs, end users, admins and customers moving to the new social, mobile and connected cloud.
Developers can create next generation apps. Salesforce1 was built API-first to enable developers to build the next generation of connected apps.

Built for next generation applications, Salesforce1 has 10 times more APIs and services built-in, for developers to build quickly, and easily create personalized experiences for connect smartphones and wearable smart devices. With Salesforce1, every ISV can accelerate their growth by building, selling and distributing apps for the connected customer.

ISVs such as Evernote and Kenandy are building mobile-ready apps on the platform and leveraging the power of the Salesforce1 AppExchange to market and sell these apps. A new mobile app built on the Salesforce1 Customer Platform allows users to access and experience Salesforce everywhere on any form factor.


“It’s not about thousands of new computers, it’s about 50 billion connected things,” said Benioff. “Everything is on the net. The airplane engine is on the net. The Caterpillar tractor is on the net. The Coca-Cola vending machine is on the net.”

Salesforce1 is a new home base for Salesforce mobile, providing access to core customer relationship management (CRM) features as well as custom and partner apps. It’s also a platform for developers, who have access to 10 times more Salesforce APIs than they did before.

Wednesday, 20 November 2013

Salesforce Integration With Klout




Recently from the client side got a requirement of getting Twiitter Account rating in Salesforce using Klout.
Go to Klout
Here what we are doing is just creating a visualforce page which is having custom fields of Account on the click of a button on detail page, our visualforce page will open, where user will get its Twitter Account rating.
It can be easily understand by the snaps below

Write your twitter Screen Name and click on the button "Get Rating"


After clicking that button user will get its Twitter rating as shown


Now the question rises how to do this thing?

So first of all, create an Account in Klout(Link provided above) then on the dashboard Click on "REGISTER AN APP", fill all the formalities and then you'll find this, marked in red is the key which we'll use to get Twitter score.


Here is the apex class

/**     Description    :    Ths class will Integrate Salesforce with Klout. 

  *

  *    Created By     :    Abhi Tripathi

  *

  *    Created Date   :    07/30/2013

  *

  *    Revisison Log  :    v1.0 - Created

  *

  *    Version        :    V1.0

**/



public with sharing class KloutWithSalesforceTwitterRatingUpdate {



  //Wrapper Class for First Response

  public class firstResponseParsingWrapper {

   

    //Response variables

    public String id;

    public String network;

   

    //Constructor

    public firstResponseParsingWrapper(String id, String network) {

      this.id = id;

      this.network = network;

    }

  }

 

  //Wrapper for second response

  public class KloutFinalResponseWrapper {

   

    //Score from the response

    public String score;

   

    //Constructor

    public KloutFinalResponseWrapper(String score) {

      this.score = score;

    }

  }

 



  //account

  public Account account { get; set; }

  public String twitterScore { get; set; }

 

  //constructor

  public KloutWithSalesforceTwitterRatingUpdate(ApexPages.StandardController stdController){

   

    //Initiallize

    twitterScore = '';



    //account record

    this.account = (Account)stdController.getRecord(); 

  }

   

    //Method for making callout and populating values retrieved from response is going to be diplayed on Visualforce Page

    public void kloutTwitterRating() { 



    try {

      //Http

      Http http = new Http();

     

      //Request

      HttpRequest req = new HttpRequest();

      req.setEndpoint('http://api.klout.com/v2/identity.json/twitter?screenName='+ twitterScore +'&key=4j6pe8zamj4dmh2by9tzv5sc');

      req.setMethod('GET');

     

      //Send request

      HTTPResponse firstResponse = http.send(req);

      System.debug('res::::::' + firstResponse.getBody());

     

      //Body

      String body = firstResponse.getBody();

     

      //Deserializing response

      KloutWithSalesforceTwitterRatingUpdate.firstResponseParsingWrapper parsedResponse = (KloutWithSalesforceTwitterRatingUpdate.firstResponseParsingWrapper)JSON.deserialize(body, firstResponseParsingWrapper.class);

      System.debug('parsedResponse:::::::' + parsedResponse);

     

      //String for id in response

      String responseId = parsedResponse.id;

      System.debug('responseId:::::::' + responseId);

   

      //Second request for score

      HttpRequest finalReq = new HttpRequest();

      finalReq.setEndpoint('http://api.klout.com/v2/user.json/'+ responseId +'/score?key=4j6pe8zamj4dmh2by9tzv5sc'); 

      finalReq.setMethod('GET');

     

      //Send request

      HTTPResponse lastResponse = http.send(finalReq);

      System.debug('lastResponse::::::' + lastResponse.getBody());

     

      //Body

      String finalBody = lastResponse.getBody(); 

     

      //Deserializing response

      KloutWithSalesforceTwitterRatingUpdate.KloutFinalResponseWrapper parseFinalResponse = (KloutWithSalesforceTwitterRatingUpdate.KloutFinalResponseWrapper)JSON.deserialize(finalBody, KloutFinalResponseWrapper.class);

      System.debug('parseFinalResponse::::::' + parseFinalResponse);

     

      //Assigning value

      account.Twitter_Rating__c = parseFinalResponse.score;

      account.Validate_Score_Successfully__c = true;

      account.Validate_Score_Last_Attempt__c = date.today();   

   



    }catch (exception e) {

     

      //Error messages

      ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'UserName Not Found, Sorry Try Again');

            ApexPages.addMessage(errormsg);

      System.debug('e:::::::' + e); 

    }   

   

  }

}


Here is the Visualforce Page

 <apex:page standardController="Account" extensions="KloutWithSalesforceTwitterRatingUpdate">  
    <!-- heading-->    
   <apex:sectionHeader title="Screen Name" subtitle="Twitter Rating"/>  
   <!-- form -->  
   <apex:form >  
     <!-- page messages-->  
     <apex:pageMessages />  
     <!-- page block -->  
     <apex:pageBlock mode="edit">  
         <!-- button -->  
         <apex:pageBlockButtons >   
           <apex:commandButton value="Get Rating" action="{!KloutTwitterRating}" />  
           <apex:commandButton value="Cancel" action="{!cancel}" />  
         </apex:pageBlockButtons>  
       <!-- block section -->  
       <apex:pageBlockSection title="Twitter Screen Name">  
         <!--Input Text>-->  
         <apex:pageBlockSectionItem >  
           Your Twitter Screen Name  
           <apex:inputText value="{!twitterScore}"/>  
         </apex:pageBlockSectionItem>  
       </apex:pageBlockSection>  
       <apex:pageBlockSection title="Rating With Related Values">  
         <!--Score-->  
         <apex:outputField value="{!account.Twitter_Rating__c}" />  
         <apex:outputField value="{!account.Validate_Score_Successfully__c}" />  
         <apex:outputField value="{!account.Validate_Score_Last_Attempt__c}" />   
       </apex:pageBlockSection>  
     </apex:pageBlock>   
   </apex:form>  
 </apex:page>  


Now get your Twitter Rating in your salesforce.
Cheers.......!!!!!


Monday, 21 October 2013

360° With Test Class for Beginners #Salesforce

Here is have provided some of the basics to write perfect test class in salesforce



Here I'll explain with short snippets for the test classes
As the first one below

1:  @isTest(seeAllData=false)  
2:    private class Test_CountContactOfAccount {   
3:      //Method  
4:      static testMethod void CountContactOfAccountUnitTest() {  
5:      }  
6:    }  

(seeAllData=false)
You can set it true or false on your own, there are two condition for setting it true or false

1. If you are querying any object and fetching records from the database in the test class then set it to true as well there are few object we can't create in our test like "OpportunityLineItem" so to test with this object records, we need to query it with "seeAllData = true".

2. But if you are inserting test records of an object an then querying it in the test class, then you need to set it false otherwise test class won't be executed.


TESTING CUSTOM CONTROLLER AND STANDARD CONTROLLERr
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

How to cover custom controller in the test class?
If you need to cover constructor in the test class then simply define it in the test class, like CountContactOfAccount is the name of the class, just define it in the test class as in below, it will cover you whole constructor.

1:  //Calling contructor  
2:  CountContactOfAccount controller = new CountContactOfAccount();  

How to call StandardController (ApexPages.StandardController stdController)?
If you are using standard controller in the class then you need to define it in the test class too

1:  //Insert you object that you are using in your class  
2:  Account acc = new Account(Name = 'test');  
3:  insert acc;  
4:  //Define standard controller and pass inserted object   
5:  ApexPages.StandardController stdController = new ApexPages.StandardController stdController(acc);  
6:  //Now define your controller then pass standard controller you've just defined  
7:  CountContactOfAccount controller = new CountContactOfAccount(stdController );  

TESTING WITH STATIC AND VOID METHODS
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

How to call methods in the test class?
As you have seen above we have called controller , by using controller we can call static and void methods easily

So if the method is void like "public void something() {"

1:    //Calling contructor  
2:    CountContactOfAccount controller = new CountContactOfAccount();  
3:    //Calling void method  
4:    controller.something();  

But if the method is static like "public static list something() {"

then you can directly call the method no need to use deifned controller

1:    //Calling static method  
2:    CountContactOfAccount.something(listOfAccount);   

TESTING ApexPages.currentPage().getParameters().get('ID')
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

In this scenario you just need to put the value in the test of the variable that you fetching from the the URL

1:  //this method will put Id in the URL in the test class  
2:  currentPageReference().getParameters().put('id', '001c384348247811');  

ASSERTS (Most Important thing for test classes)

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

There as three most commonly used asserts are there shown below, use asserts to check that your method are returning the correct values or not.

1:  System.assert(pBoolean)  
2:  System.assertEquals(pANY, pANY)  
3:  System.assertNotEquals(pANY, pANY)  

TESTING ERROR MESSAGES
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

If you have error message in your test class and you want to cover it in test class then use this snippet

1:  //List of Message  
2:  List msgs = ApexPages.getMessages();  
3:  //Define a boolean variable  
4:  boolean msg = false;  
5:  //Loop through the messages of the page  
6:  for(Apexpages.Message msg:msgs){  
7:  //if there is error message then set the boolean to true  
8:  if (msg.getDetail().contains(‘Search requires more characters’)) msg = true;  
9:  }  
10:  //Assert  
11:  system.assert(msg);  
12:  //Single Assert on Error Messages  
13:  System.assert(ApexPages.getMessages()[0].getDetail().contains( 'User not found with given username' ));  

I think these are the most common scenarios for the Test classes that makes some mess.

Some key points:

1. Whole orgs average code coverage should be 75%, NOT each class.
2. Each trigger must more then 0% code coverage.

Hope I've helped you
CHEERS....!!!!