Showing posts with label Salesforce. Show all posts
Showing posts with label Salesforce. Show all posts

Thursday, 12 May 2016

Apex batch Auto Monitoring

Many a times you may have been in a situation where Salesforce Apex jobs gives a strong time and you are left with scratching your head due to Apex Job status unavailability. Salesforce Geeks can use an awesome object provided by Salesforce for Apex job Monitoring i.e.- AsyncApexJob . It is a backend object automatically maintained by Salesforce to track past/current Jobs. 

Although Salesforce has provided a great User Interface for same purpose i.e. Setup>Monitor>Jobs>Apex Jobs but sometimes it behaves strangely or you are not able to get proper status for your batch job, so in that case you may use Developer Console/Workbench(My personal favorite) to query AsyncApexJob object and check other details about your Apex Jobs

Lets assume your batch class is names "myBatch" then below SOQL would help you to get data related to your batch job Record

SELECT Id, MethodName, JobItemsProcessed, ApexClassId, ApexClass.Name, CompletedDate, NumberOfErrors, Status, ExtendedStatus, TotalJobItems FROM AsyncApexJob where ApexClass.Name='myBatch' order by CompletedDate Desc Limit 10

Above SOQL will return Status(and other fields) for Batch Job and hence you can identify the exact stage, number of records processed, Reason for failure etc.
********Hopefully it helps your Debugging********
Keep doing Great Work

Thursday, 11 February 2016

Salesforce Dynamic Visualforce Components

Use Salesforce Dynamic Visualforce Components and Custom Label for predefined String(helpful for displaying Apex Messages etc)

Visualforce is mainly intended for create static pages by using Different namespace tag and dynamically populating the values based on controller binded variables but sometimes Developers need to customize the Pages in such a way to reduce maintainance Development effort and the changes could be carried out in few point and clicks. To adapt this strategy, Salesforce provided -"Dynamic Visualforce Components", Under this approach VF components are dynamically populated in APEX class and then rendered onto the VF page.

Custom Label usage: Developers can use Custom Labels in Apex by using following expressions - System.Label.labelName

VF Page :
1:  <apex:page standardController="Contact" extensions="DynCompExample">  
2:    <apex:dynamicComponent componentValue="{!headerWithDueDateCheck}"/>  
3:    <apex:dynamicComponent componentValue="{!ErrorLabelString}"/>  
4:  </apex:page>  

APEX Class:
1:  public class DynCompExample {  
2:    public DynCompExample(ApexPages.StandardController con) { }  
3:    public Component.Apex.SectionHeader getHeaderWithDueDateCheck() {  
4:      date dueDate = date.newInstance(2016, 2, 8);  
5:      boolean overdue = date.today().daysBetween(dueDate) < 0;  
6:      Component.Apex.SectionHeader sectionHeader = new Component.Apex.SectionHeader();  
7:      if (overdue) {  
8:        sectionHeader.title = 'This Form Was Due On ' + dueDate.format() + '!';  
9:        return sectionHeader;  
10:      } else {  
11:        sectionHeader.title = 'Form Submission';  
12:        return sectionHeader;  
13:      }  
14:    }  
15:       // This method return the String value for the Error Label id   
16:    public Component.Apex.OutputText getErrorLabelString(String labelName){   
17:            Component.Apex.OutputText outputError = new Component.Apex.OutputText();   
18:            outputError.expressions.value = '{!$Label.' + labelName + '}';   
19:            return outputError;   
20:       }   
21:  }  

Note from Salesforce : Dynamic Visualforce components are not intended to be the primary way to create new Visualforce pages in your organization. Existing Visualforce pages shouldn’t be rewritten in a dynamic manner and, for most use cases, standard Visualforce components are acceptable and preferred. You should only use dynamic Visualforce components when the page must adapt itself to user state or actions in ways that can’t be elegantly coded into static markup.

Documentation  Link : https://help.salesforce.com/HTViewHelpDoc?id=cl_about.htm&language=en_US

Wednesday, 10 February 2016

Using NewLine in APEX String

String is an awesome DataType provided by Language designers to store any Text Literals(alphabets, numbers, special chars etc) but sometimes Developers need to display Newline Character in the APEX String which can be used on VisualForce Page.

Trick : This can be easily done adding \n for NewLine Character in Apex String and then each \n will be replaced by <br/> in VF page with help of SUBSTITUTE(JSENCODE(Variable), '\\n', '<br/>').

VF Page :
1:  <apex:page controller="Returns">   
2:    <apex:outputLabel value="{!SUBSTITUTE(JSENCODE(choosenText), '\\n', '<br/>')}" escape="false"/ >   
3:   </apex:page>  

Apex Class :
1:  public class Returns{  
2:  public String choosenText{get;set;}  
3:  public Returns(){  
4:  choosenText = 'Hi Salesforce' + '\n' + ' This is a Salesforce Techie Blog.' + '\n' + 'Please share your Feedback';  
5:  }  
6:  }  

Output :
 

Hope this trick is Helpful!!!

Saturday, 31 May 2014

Salesforce Live Agent

Now a day the competition has raised its bar and in each industry everyone believes in quick reception to his/her queries. Live agent is an awesome functionality provided by salesforce for managing chats with client contact on various standard object/Custom objects. It enables the external users to have a web chat with agents to know more about their product queries (or solution)
This feature is available at Developer and Performance editions organizations created after June 14, 2012 and for Enterprise and Unlimited Editions it’s available with an additional cost.

Steps to enable Live agent for an Org:
1. Navigate through Name>Setup>App Setup>Customize>Live Agent>Settings

2. Check the checkbox for “Enable Live agent”.
3. Enable Live Agent user check box in your user detail page. 
(Note: - Live Agent users require API Enabled administrative permission on profile. Agents also need at least the “Read” permission on Live Chat Visitors and Live Chat Transcripts to review visitor and transcript records.)
4. After enabling live agent for your org, several objects are automatically enabled and created in your org e.g.
a.       Live Chat Visitors – The Live Chat Visitor tab contains information about visitors that have participated in chat sessions. Below you can see sample live chat visitor record
b.      Live Chat Transcripts: - The Live Chat Transcripts tab contains the transcripts of completed chat sessions. Below you can see sample live chat transcript record
c.       Live Chat Transcript Events: - Contain all information that contains chat request; accept request or route details and Visitor Left. Below you can see sample live chat transcript event record
d.      Live Agent Sessions: - This Live Agent Sessions tab contains information about agent session, time spent online, time spent on chat etc. Below you can see sample live chat session  record
e.      Live Agent Supervisor:-This tab contains information about your department’s chat buttons and chat agents, all in one place. It will look like below screen shot
f.        Live Agent :- This tab contains information about Chat transcript and from here you can launch live agent console
g.       Quick Text: - Quick Text lets users create standard messages, such as greetings and answers to common questions, which support agents can easily insert into communications with customers. Quick Text is automatically enabled for organizations that have enabled Live Agent. If you want to create quick text click on Quick text (Tab) | New and fill the details as per your choice, you can take help from below screen shot
Setup Skills for the Live Agent
1. Go to Name>Setup>App Setup>Customize>Live Agent>Skills.

2. Create new Skill by clicking “New” Button.(as shown below)
3. After setting Skills, Go to Name>Setup>App Setup>Customize>Live Agent>Chat Buttons and create one by clicking “New” (as shown below).
4. Select type, Name, Skills (Mandatory fields). Also you can set various other attributes like Custom agent name, Auto greeting message, Language, online image, offline image etc.


5.  After setting up button, the detail page would provide a code snippet for chat button copy the code and paste it in a text file.
6. Then Go to Name>Setup>App Setup>Customize>Live Agent>Deployment. Create a Deployment record by inserting required fields (or you can customize it according to the company branding). After creating deployment record it would also result in a short code snippet. Copy this code snippet and paste it in same file(as previous) and save it as filename.Html
Test the Live agent:  You have to embed this live agent configuration into an application
1. Create a Service Cloud Console Application from Create --> Apps and click "New" button.
2.  While creating a service cloud Application enable the checkbox for “Include Live agent in this App” and choose the records or pages to open as sub tabs
After Creating App in Salesforce, Select the App and Open the .html file which contains the code snippet generated during the process. On click of online image on html page, A Request to Agent would be sent to accept the Chat Conversation. After the agent accept the chat, they can start chatting and the agent can save or create appropriate object record related to this chat conversation.(as shown below)


Thursday, 22 May 2014

Salesforce Analytic Snapshot


Sometimes Business Analysts have a requirement to have a better GUI for reporting on particular set of data which must refresh by itself. So this use case can be solved by Salesforce awesome feature known as “Analytic Snapshot”. An analytic snapshot lets you report on historical data. The user have to create a custom object and then authorized users configures tabular or summary report results to fields on the custom object, then map those fields to corresponding fields on a target object. They can then schedule when to run the report to load the custom object's fields with the report's data. Analytic snapshots enable you to work with report data similarly to how you work with other records in Salesforce.
     
     Steps to setup Analytic snapshot:
  1. Create a report into salesforce (and you can use various reporting features like grouping, custom summary formulas etc.) using appropriate filters.
  2.      Create a new custom object which is mainly used to capture to capture data/information from report at scheduled time intervals. You need to create the schema for the custom object like fields to be added on this object to capture various information from report ;e.g. the number of records appearing on report, Date on which the snapshot was taken etc.
  3. Then you need to create analytic snapshot, go to Setup > Admin Setup > Data Management > Analytic Snapshots. Select the Source report and the target custom object. Finally map the fields from the source report.

  4. Furthermore, you need to schedule the analytic snapshot job to schedule at desired frequencies.
To analyse the historical data stored in the custom object, you‘ll need to create another report (make sure to group them by snapshot date so that the analysts can have a graphical view for the same). Finally you can schedule the report or display them on the record detail page layout.

Sunday, 18 May 2014

Salesforce Deployment Methods

Salesforce Deployment Methods
There are three ways of deployment to Salesforce:
1)      Deployment Changeset, Disadvantage-> can only be deployed to sandbox or connected org.
2)      Force.com Eclipse IDE
3)      Force.com Java based ANT Scripts
In this blog post we are going to learn about retrieving salesforce components through ANT. To use ANT one should have:
1)      Java installed in local machine
2)      Apache ANT installed into local machine
3)      Ant-Salesofrce.jar file from Salesforce (which is to be copied into Home_Folder>ant>lib).
ANT Setup
  1.   Download ANT from http://ant.apache.org/bindownload.cgi
  2.   Extract the folder and paste it into Home_Folder.
  3.   Also Download the ant-salesforce.jar from salesforce org. To download follow the steps Setup>Develop>Tools. Click Force.com Migration Tool and paste the .jar file into Home_Folder>ant>lib.
  4.  Setup the Environment variable from My Computer>Rightclick-Properties>Advanced Syatem setting>Click Environment variable. Add new System variable, Enter name as ‘ANT_HOME’ and location as drive location of bin folder for ant. Also check whether Java classpath is set in system variable.
  5.  Optional, we can check whether ant and java is installed by using commands ‘ant –version’ and ‘java –version’.

  1. Building ANT package.xml, Build.xml and Build.properties
Build.properties file(please change the username and password in below file)
 1. # build.properties  
 2. #  
 3.    
 4. # Specify the login credentials for the desired Salesforce organization  
 5. sf.username = DemoUsername  
 6. sf.password = Password  
 7. #sf.pkgName = <Insert comma separated package names to be retrieved>  
 8. #sf.zipFile = <Insert path of the zipfile to be retrieved>  
 9. #sf.metadataType = <Insert metadata type name for which listMetadata or bulkRetrieve operations are to be performed>  
 10.   
 11. # Use 'https://login.salesforce.com' for production or developer edition (the default if not specified).  
 12. # Use 'https://test.salesforce.com for sandbox.  
 13. sf.serverurl = https://login.salesforce.com  
 14.   
 15. sf.maxPoll = 20  
 16. # If your network requires an HTTP proxy, see http://ant.apache.org/manual/proxy.html for configuration.  
 17. #  

Build.xml
 <project xmlns:sf="antlib:com.salesforce" basedir="." default="test" name="org to org">  
 2.   <property file="build.properties" />  
 3.   <property environment="env" />  
 4.      
 5.   <target name="retrieve_dev" depends="">  
 6.     <echo message="retrieving metadata to ${metadata.root}" />  
 7.         <mkdir dir="retrieveOutput"/>  
 8.     <sf:retrieve retrieveTarget="retrieveOutput" singlePackage="true" serverurl="${sf.serverurl}" password="${sf.password}"username="${sf.username}" unpackaged="MyPkg/package.xml"/>  
 9.   </target>  
 10. </project>  

Package.xml
 <?xml version="1.0" encoding="UTF-8"?>  
 2. <Package xmlns="http://soap.sforce.com/2006/04/metadata">  
 3.   <types>  
 4.     <members>*</members>  
 5.     <name>ApexClass</name>  
 6.   </types>  
 7.     
 8.     
 9.   <version>29.0</version>  
 10. </Package>  

Deployment Commands
Type ‘ant TARGET_NAME’ where TARGET_NAME=name attribute of target tag in Build.xml(in this case retrieve_dev. The Build process will start after creating a folder named ‘retrieveOutput’ under which the required salesforce components will be saved in file system(Please ensure that the current folder location in which ’ retrieveOutput’ is created, must have sufficient admin rights for creating and editing file contents .

Deployment through Eclipse:
ANT is by dedault the part of Eclipse IDE just we need to add the ant-salesforce.jar from salesforce org. Follow the below steps:

  1.  Open Eclipse, then go to Windows>Preferences.
  2.  Select ANT>Runtime and choose Ant Home Entries(Default)

  3.  Click Add JAR and choose the ant-salesforce.jar, then click apply.
  4. Save the setting by clicking Ok.
  5. Now Create a new project in Eclipse and import the build.properties and build.xml
  6.  Right click build.xml in your project>Run as>Build ant.
  7.  Select the configuration target from list which performs the desired action
  8.    Optionally we can setup the arguments for build.properties separately(by clicking Main tab in above fig) for e.g : -Dsf.srcdir="DIR _SRC_ PATH "
  9.  Finally click Run and observe the Eclipse console for logs.
  10. After the complete process we’ll get the message as Build Succeeded (or Build Failed).