Sentiment Analysis in Salesforce – A Part of Artificial Intelligence

Screen Shot 2017-06-07 at 11.23.42 AM

v1 (1)

What is Sentiment Analysis:
Sentiment analysis is extremely useful us to gain an overview of the public opinion behind certain topics and feedbacks. Automatically classifying text by sentiment allows you to easily find out the general opinions of people in your area of interest. For example, you might want to analyze reviews of a product to help you improve the customer experience, or to find the most or least popular product.

The Obama used sentiment analysis to gauge public opinion to policy announcements and campaign messages ahead of 2012 presidential election.

How can we get this?
There is lots of tool for sentiment analysis. But I found haven on demand easy to use API.

About HavenOnDemand Sentiment Analysis API:
The Sentiment Analysis API analyzes text to return the sentiment as positive, negative, neutral, or mixed. It contains a dictionary of positive and negative words of different types and defines patterns that describe how to combine these words to form positive and negative phrases.

 

How to implement in Salesforce:

Use Case:
You can use this API as you want but in my blog, i am using an example of feedback’s mails.

The user will send an email to Salesforce and here I am saving this email to a custom object and analyzing the sentiment of that email. So support and sales person know that which email is top to pick in morning. Because a team can have tons of emails. In these mail, most negative emails are important to work on because we want the positive feedback from clients. So it is very hard to read one by one email. But from this API you can get the sentiment score and sort them by the score.

Screen Shot 2017-06-08 at 1.38.57 AM

Implementation-
A. Get API key from HavenOnDemand:
1. Go here and register yourself.
2. After registration, Go here.
3. Then click on Generate Key button. Here you will get a popup for the name of the key. Fill this and click on Continue.
4. You will see a key here. Copy this key and save it on your computer. we need this on salesforce apex code.

B. Coding Part: Download Source Code from here.
After the code deployment. Add your API key in EMailHandler Class.
Screen Shot 2017-06-08 at 12.19.28 AM

API Explanation:

We need to send request on https://api.havenondemand.com/1/api/sync/analyzesentiment/v2

It is GET call. So you need to pass 2 params in URL.
-apikey = Your API key
-text = set the text for sentiment analysis.

Read more about API here

C. Now create an Email Services:
1. Go to Setup –> Develop –> Email Services
2. Create Email Service here as below
Email Service Name = SentimentAnalysis
Apex Class = EMailHandler
Active = Checked (It should be checked to get inbound emails.)
3. After that create new Email Addresses under Email Service.

D. Add Sentiment View Page: Now add feedback VF page to your page layout. I added in lightning view at the top.

Time to run:
Open your mailbox and send an email to an above-created email address. Salesforce will create a record of Feedback object. You can see the sentiment score and sentiment in the record.

If you have any concern then please feel free to contact me.

Please send your feedback to this email address. I will share your sentiment score on my facebook and twitter page.

sentimentanalysis@2ivr6p1y22tgkbwb5z8jsznyk9v7z0ssyk21pi9yrhx3ohl5we.7f-rozfuaq.ap5.apex.salesforce.com

Cheers!!
Happy Salesforce

Salesforce Voice Search Chrome Extension Release

icon128

You must have read the article where i wrote how can we create voice search extension. It is good for dev guys.

But all are not Dev’s so i released this. Now just install it and make your words stronger than hands. 🙂

This extension provides Speech to Text functionality. Right now you can search by typing text. It’s little time-consuming.

How does it work?
You just have to click on salesforce search bar and speak here, you will be redirected to search result as salesforce providing.

After Installing the extension refresh or open new salesforce page, click on the search bar.

Then it will ask for permission. Here allow it to Use your microphone. It is just one time setup.

Install it from here

If you like this extension then please don’t forget to give your review and feedback.🙂

Speak and Cheers!!
Happy Salesforce!!

Convert Visualforce Checkboxes And Radio Buttons in Lightning Design System Using Javascript

vf2lds
Hi Everyone

As we know that with the Lightning Design System(LDS) we can build custom applications with a look and feel that is consistent with Salesforce core features — without reverse engineering our styles. See here more about LDS.

We have lots of standard visualforce pages. Now a days we all are facing some problems to convert standard visualforce pages in Lightning design system. We need to customize all of the standard things.

We can easily implement LDS to many standard components like checkbox, picklist etc. But in these days i am facing problem in convert list of checkboxes And list of  Radio Buttons to LDS view.

So for this I have written a script to convert list of checkboxes and list of radio buttons to LDS. Using this, we don’t loose our binding with controllers as well.

Update : Previously this script is used for  list of checkboxes, now I have updated it, for list of radio buttons as well.

Script :

    function convertCheckBoxToLDS() {
        var Row = document.getElementsByClassName("convertToLSD");
        for (var k = 0; k < Row.length; k++) {
            var colTds = Row[k].getElementsByTagName("td");
            for (var i = 0; i < colTds.length; i++) {
                var inrHtml = colTds[i].innerHTML;
                var chkId = inrHtml.substring(inrHtml.indexOf("id=") + 4, inrHtml.indexOf("\"", inrHtml.indexOf("id=") + 4));
                var chkBx = inrHtml.substring(inrHtml.indexOf("<input"), inrHtml.indexOf(">") + 1);
                var chkLable = colTds[i].getElementsByTagName("label")[0].textContent;
                var typeOfInput = colTds[i].getElementsByTagName("input")[0].getAttribute("type");
                var newChkBox = '<label class="slds-' + typeOfInput + '" for="' + chkId + '">' + chkBx +
                    '<span class="slds-' + typeOfInput + '--faux"></span>' +
                    '<span class="slds-form-element__label">' + chkLable + '</span>' +
                    '</label>';
                colTds[i].innerHTML = newChkBox;
            }
        }
    }

Here is example :
Create a class :

public class VFToLDSController{
    public List<SelectOption> lstSelOpt{get;set;}
    public VFToLDSController(){
        lstSelOpt = new List<SelectOption>();
        for(integer i=1 ; i<100 ; i++ ){
           lstSelOpt.add( new SelectOption( 'ID-'+i, 'CheckBox'+i ) ); 
        }
    }
}

Create a VisulaforcePage :

<apex:page controller="VFToLDSController" sidebar="false" showHeader="false" standardStylesheets="false">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<link href="{!URLFOR($Resource.SLDS080,'SLDS080/assets/styles/salesforce-lightning-design-system.css')}" type="text/css" rel="stylesheet" />

<style>
    body{
        background-color: whitesmoke;
    }
</style>

<script>
    $( document ).ready(function() {
        convertCheckBoxToLDS();
    });
    
    //Convert standard checkboxes to Lightning Design System
    function convertCheckBoxToLDS() {
        var Row = document.getElementsByClassName("convertToLSD");
        for (var k = 0; k < Row.length; k++) {
            var colTds = Row[k].getElementsByTagName("td");
            for (var i = 0; i < colTds.length; i++) {
                var inrHtml = colTds[i].innerHTML;
                var chkId = inrHtml.substring(inrHtml.indexOf("id=") + 4, inrHtml.indexOf("\"", inrHtml.indexOf("id=") + 4));
                var chkBx = inrHtml.substring(inrHtml.indexOf("<input"), inrHtml.indexOf(">") + 1);
                var chkLable = colTds[i].getElementsByTagName("label")[0].textContent;
                var typeOfInput = colTds[i].getElementsByTagName("input")[0].getAttribute("type");
                var newChkBox = '<label class="slds-' + typeOfInput + '" for="' + chkId + '">' + chkBx +
                    '<span class="slds-' + typeOfInput + '--faux"></span>' +
                    '<span class="slds-form-element__label">' + chkLable + '</span>' +
                    '</label>';
                colTds[i].innerHTML = newChkBox;
            }
        }
    }
</script>

<html xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<div class="slds-page-header nav" role="banner">
  <div class="slds-grid">
    <div class="slds-col slds-has-flexi-truncate">
      <div class="slds-media">
        <div class="slds-media__figure">
          <b>VF<font style="font-size:40px;color: blue;">2</font>LDS</b>
        </div>
        <div class="slds-media__body">
            <p class="slds-text-heading--label" style="font-size: 15px;margin-top: 13px;">Convert Visualforce checkboxes And Radio Buttons in Lightning Design System Using Javascript</p>
        </div>
      </div>
    </div>    
  </div> 
</div>
<apex:form >       
    <table style="width:100%;margin-left: 16%;">       
        <tr> 
            <td>           
                <h1><b>Before</b></h1>         
                <div style="height:200px;width:200px;" class="slds-scrollable--y">                        
                    <apex:selectCheckboxes layout="pageDirection">
                        <apex:selectOptions value="{!lstSelOpt}"/>
                    </apex:selectCheckboxes>
                </div>
            </td>
            <td>                   
                <h1><b>After</b></h1> 
                <div style="height:200px;width:200px;" class="slds-scrollable--y">                        
                    <apex:selectCheckboxes styleClass="convertToLSD" layout="pageDirection">
                        <apex:selectOptions value="{!lstSelOpt}"/>
                    </apex:selectCheckboxes>
                </div>
            </td>
        </tr>
    </table>        
</apex:form>
</html>
</apex:page>

Happy LDS !!!

Create Chrome Extension for Voice Recognition Search in Salesforce

icon128

Hi All,

After this post you can search using voice recognition system in salesforce search bar. Right now you can search by typing text. Its little time-consuming. This extension provides Speech to Text functionality.
This post also gives you basic things for how to create a chrome extension.
Please read “Voice Recognition Search in Salesforce (VF-Page)” post to understand this post better.
How it works ?
You just have to click on salesforce search bar, after this speak and you will redirected to search result as salesforce providing.

Search enable

Implementation of Extension :
We need five components :
1. manifest.json
2. inject.js
3. jquery.min.js
4. background.js (Read here)
5. icon.png

manifest.json

Every extension has a JSON-formatted manifest file, named manifest.json, that provides important information. Read more about manifest file. In this file we defines that on which domain extension will work, in this example it works for *.salesforce.com . we can enable for salesforce community as well.

{
 "name": "Salesforce Voice Search",
 "version": "1.0",
 "description": "A utility do search by speech.",
 "icons": {
 "128": "icon.png"
 },
 "permissions": [
 "tabs", "https://*.salesforce.com/*"
 ],
 "background": {
 "scripts": [
 "jquery.min.js",
 "background.js"
 ]
 },
 "content_scripts": [
 {
 "matches": [
 "https://*.salesforce.com/*" 
 ],
 "js": [
 "jquery.min.js",
 "inject.js"
 ]
 }
 ],
 "manifest_version": 2
}

inject.js

This file contains javascript which will injected on salesforce pages.

//Creating script for enable voice recognition 
var ScriptStr = '(function() {'+
					'\'use strict\';'+
					'if (! (\'webkitSpeechRecognition\' in window) ) return;'+
					'var talkMsg = \'Speak now\';'+
					'var patience = 6;'+
					'function capitalize(str) {'+
						'return str.length ? str[0].toUpperCase() + str.slice(1) : str;'+
					'}'+
					'var speechInputWrappers = document.getElementsByClassName(\'searchBoxClearContainer\');'+
					'[].forEach.call(speechInputWrappers, function(speechInputWrapper) {							'+
						' var inputEl = document.getElementById(\'phSearchInput\');'+
						'var micBtn = document.getElementById(\'phSearchInput\');	'+
						'var inputHeight = inputEl.offsetHeight;'+
						'var inputRightBorder = parseInt(getComputedStyle(inputEl).borderRightWidth, 10);'+
						'var buttonSize = 0.8 * inputHeight;'+
						'var finalTranscript = \'\';'+
						'var recognizing = false;'+
						'var timeout;'+
						'var oldPlaceholder = null;'+
						'var recognition = new webkitSpeechRecognition();'+
						'recognition.continuous = true;'+
						'function restartTimer() {'+
							'timeout = setTimeout(function() {'+
								'recognition.stop();'+
							'}, patience * 500);'+
						'}'+
						'recognition.onstart = function() {'+
							'oldPlaceholder = inputEl.placeholder;'+
							'inputEl.placeholder = talkMsg;'+
							'recognizing = true;'+
							'micBtn.classList.add(\'listening\');'+
							'restartTimer();'+
						'};'+
						'recognition.onend = function() {'+						
							'if( document.getElementById(\'phSearchInput\').value != \'\' ){'+
								'document.getElementById(\'phSearchButton\').click();'+
							'}						'+
							'recognizing = false;'+
							'clearTimeout(timeout);'+
							'micBtn.classList.remove(\'listening\');'+
							'if (oldPlaceholder !== null) inputEl.placeholder = oldPlaceholder;'+
						'};'+
						'recognition.onresult = function(event) {'+
							'clearTimeout(timeout);'+
							'for (var i = event.resultIndex; i < event.results.length; ++i) {'+
								'if (event.results[i].isFinal) {'+
									'finalTranscript += event.results[i][0].transcript;'+
								'}'+
							'}'+
							'finalTranscript = capitalize(finalTranscript);'+
							'inputEl.value = finalTranscript;'+
							'restartTimer();'+
						'};'+
						'micBtn.addEventListener(\'click\', function(event) {'+
							'event.preventDefault();'+
							'if (recognizing) {'+								
								'recognition.stop();'+
								'return;'+
							'}'+
							'inputEl.value = finalTranscript = \'\';'+
							'recognition.start();'+
						'}, false);'+
					'});'+
				'})();';
//Injecting script on page
	var elem = document.createElement("script");
	elem.type = "text/javascript";
	elem.innerHTML = ScriptStr;
	document.head.appendChild(elem);

How install it in google chrome ?
1. Create a folder name as “Salesforce Now”
2. Put all files in this folder
3. Type chrome://extensions/ in your browser
4. Check the Developer Mode CheckBox
5. Click on Load unpacked extension..
6. It will open a window, in this window define path of your chrome extension folder.

After all setup it will appears in your extension list.
Capture

Whenever your browser will opens, it ask for continue with developer mode that time select continue.

Now refresh or open new saleforce page, click on search bar. Allow it to Use your microphone.
Capture

Email me on vishnukumarramawat@gmail.com for complete code.

If you have any suggestion, will be appreciated. 🙂