Differences between the ways resources are referenced in href/src

Sometimes small items takes too much of time. I always face issues when it comes to providing correct location of the resource so this post is an effort to minimize such issues.

Let’s understand differences in which resources are referenced. Consider the index.html has script in below ways:

    <script src="myscripts.js"> 
  1. Browser will look in the current directly of the file where this script tag is mentioned. So if you move the index.html into any other directly then browser will not be able to reference the myscript.js
  2. <script src="./myscripts.js"></script>
  3. This will be exactly same as example in #1. This is only different way of mentioning that refer the file from the current directory.
  4. <script src="/myscripts.js"></script>
  5. Here browser will look into the root directory of the website, no matter where the index.html having this tag is present.
  6. <script src="../myscripts.js"></script>
  7. Here browser will go to the parent directory of the index.html and then will look for the myscript.js

This blog post is small but thought of sharing, whenever I used to face issue then I used to try different formats and some or the other used to work. Never paid close attention but if you have so many file references and then your try outs permutation and combination increases. Having clear understanding of how references work would save some hassles.

Scheduled Report Export using Analytics API in Apex

In salesforce we cannot have scheduled email export. Below solution could help to get the scheduled export of the reports as CSV. For this I have used “Execute a Custom Action” feature when we subscribe to email notification. Salesforce has provided feature where Apex code can be executed if the condition specified while subscribing report is met.

Screen Shot 2017-04-08 at 7.11.30 PM

EmailReportExport class

You can use code from : https://gist.github.com/kiran-machhewar/ff0f2ca55b89b793ad88973f7701feb0

In order to get the scheduled export of Report data, report has to be subscribed and while subscribing report select “Execute a Custom Action” and select EmailReportExport class. As per the schedule provided as soon as the conditions are met then execute method from EmailReportExport will get invoked. In the execute method csv data is created by Analytics api in Apex.

Subscribe the report in below way:

Screen Shot 2017-04-08 at 7.47.10 PM

When the condition for the report subscription is met at scheduled time you will get the email notification as in below snapshot:

Screen Shot 2017-04-08 at 7.50.53 PM

Features:

  1. No email limits are consumed since email would be sent to the user who has subscribed the email.
  2. Same EmailReportExport handler can be used with different reports.

Limitation:

Only 2000 records will be available as a csv export.

Happy learning  🙂

 

Integration via Outbound Messages-SF API Call Manager

This article is for exploring integration possibilities via outbound messages and solving below problems:

  1. Timeout issue – In salesforce there is strict limit of 120 seconds for callout. This could be solved if API calls are carried outside of salesforce like in heroku app where no such limit for callout is there.
  2. API Calls which requires polling – Polling for response becomes difficult in salesforce as in order poll for result batch is required which runs at regular interval but there cannot be more than 5 batches running simultaneously. This can be solved by implementing polling logic in heroku app where threading could be used for polling and making inbound call to salesforce when results are available.

This idea came up when I was having discussion with my colleague Tushar Kaore on integration approaches. We thought that lets try to analyze the performance and reliability of outbound messages in integration.

Here is the design of this framework:

OutboundMessagesIntegration

Integration via Outbound Messages

Lets see how this would work

  1. Whenever API Call has to be made then in salesforce API Call record has to be created which would include below details
    • Endpoint
    • Request
    • Headers
  2. On create of such API Call records salesforce would initiate an outbound message call to the heroku application with all the details which would be required to make API call
  3. Actual API Call will be made by heroku app to the external system. Here an API call which takes more than 120 seconds can be made and it is required to do polling then heroku app can handle that by polling in regular intervals of time.
  4. Heroku app will receive the response.
  5. Inbound API call would be made to salesforce to pass on the response received by heroku app.
  6. Response would be updated in API Call record and on trigger of API Call record response could be processed and proper actions could be taken.

In this structure two applications are involved Salesforce App and Heroku app.

Steps to configure app:

  1. Heroku App: Install the Heroku App  : heroku-api-call by using deploy to heroku button from repository home page.
  2. Salesforce App: Insall the Salesforce App : sf-api-call by using Deploy to Salesforce button from repository home page.
  3. Configure workflow rule: Create workflow rule on API Call object with the outbound message action as per below screenshot.

    sf-api-call

    Outbound Message Action

  4. Add Remote Site setting: Add the remote configured endpoint as remote site setting.

How to test:

Create an API Call record in salesforce with the endpoint. As soon as the record gets created salesforce will make outbound message call to heroku app. Heroku app will make API call to the endpoint and it will be update the received response to salesforce via making inbound api call.

I will be be testing this for performance and will check its reliability to use in production applications. Currently only GET API calls are supported and will update the code to have below featues:

  1. Headers support
  2. POST call support

features list will go on…..

Whenever real time integration is not required and this approach could be used to solve issues of

  1. Callouts taking more than 120 seconds
  2. Whenever polling for response is required.

Result of this exercise:

I created nearly 50K API calls (thats lots of API calls) and tried to see how many API calls will get processed by this mechanism. Results are very promising

APIPerformanceReport

Results shows that 20K API calls are fulfilled within 3 minutes i.e. 113 fulfilled API call/second. My heroku instance was bombarded with outbound messages calls and now it is down.. 🙂

Note these are the results with free heroku instance with one dyano only. So imagine if you have a heroku app with good number of dynos to fulfill requrest then you can think of very promising results.

API Call is made to http://headers.jsontest.com/ for testing.

Happy learning and keep exploring..

 

Disabling standard style sheets – Salesforce

Everywhere we have lightning and Salesforce is in process to provide all classic features in lightning. In this process there would be some features which would not be available in lightning. So sometimes we need to use the best of both worlds classic and lightning. Here is similar problem and its solution.

Problem : Custom click to dial functionality can be used in visualforce pages with the below code

<apex:page standardController="Account" showHeader="true">
    <support:clickToDial         number="415-555-1234"         entityId="001XB000000HFUM"         params="myparam1,myparam2"     />
</apex:page>

Ref: https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_compref_support_clickToDial.htm

As of now this only works with the visualforce page where showHeader is enabled. Now if we enable showHeader then visualforce includes standard style sheets but then such standard style sheets  could get mixed up with LDS in visualforce page and creates css conflict issues.

Solution : Lets consider what we want here-

  1. ShowHeader = true, on page level showheader has to be enabled other wise click to dial functionality from visualforce page would not work.
  2. Don’t want any impact on lightning design system css

Here solution is to dynamically remove the standard style sheets which gets loaded because of showheader set to true. The problem with that approach is that whenever any section of page is reRendered then standard style sheets are loaded back which again distorts the LDS css. There is one way to solve this is instead of removing standard stylesheets disabling it by below code:

<script>
 function disableStandardStylesheets(){ 
       $('link[rel=stylesheet]').each(function(){
          if(this.href.indexOf('/sprites/')!=-1 &amp;&amp; this.href.indexOf('/CTI.css') == -1){ 
               $(this).attr("disabled", "disabled");
          }
       });
 }
 disableStandardStylesheets(); 
</script>

Advantage of disabling standard style sheets instead of removing is that after every reRender it will not get loaded back. This solution will other places in Salesforce where you want to disable effect of any standard stylesheets gets loaded by Salesforce.

LDSmixedWithStandardStylesheets

Visualforce page with LDS and Standard Style Sheets

LDSwithDisabledStandardStylesheets

Visualforce page with LDS and disabled Standard Style Sheets

User Creation in Salesforce

This post is for the best practices to be kept in mind while loading users in the system. If client business users starts getting notification when they are not supposed to then that could create chaos. Below are the points which needs to be considered while loading users in the system.

  1. User Template: User data should be gathered before hand, to make sure that we are not missing any information which we are supposed to be asked to client. Template should be used so that no data would be missed. Attached is the user template using which we could ask client to provide all user details UsersTemplate.
  2. SSO consideration: If the salesforce org is using SSO then federation id should be asked before hand and should be part of user template.
  3. Multicurrency: If salesforce org uses multicurrency then it would be good to include that CurrencyIsoCode column in the user template.
  4. External Id: No matter how much you plan but you could have some wrong data like incorrect firstname, lastname etc. It would be a good practice to create external id in user object so that users could be upserted and data could be corrected.
  5. Email Id change: Whenever user’s email ids are changed then users gets notification for confirming the email address and also notification is sent to the email id which you are changing. If you want to change the email ids without any notification to users then you can turn of the Email Deliverability to “No Access”. This will make sure that email id is changed without creating any chaos of notifications.
  6. Reset Password: Whenver user loading process is going on it would be good to turn off Email Deliverability. When you think that now its the time to welcome users then you can reset the password. Users will get the email to set their passwords.
  7. Feature Licenses: If you want to activate some feature licenses then that could be added as a part of user template.

    FeatureLicenses

    Feature Licenses

  8. Welcome Email: If you want to send welcome emails to user for helping with the documents to understand salesforce and with next steps. To implement this you would need to create email template and which would be used by workflow rule on user object.

Above list could act as a checklist for your plan of creating users in salesforce.

Using Picklist in Integrations- After Spring 17 Release

In integrations mainly information is communicated to other System by passing id/code values instead of Labels. In Salesforce picklist has values and labels but before Spring 17 release there was not provision to have different value and label for picklist items.

Whenever different Label has to be shown to user and different code has to be passed to other system then some workarounds were required to be done like having code label mapping in code or keeping code values in custom object and passing those values in integrations. Such solutions were error prone and requires maintenance since in code it is required to do String comparison to get the proper code to be sent to other system.

Now we have a relief, in Sprint 17 salesforce has provided much required feature where we can have separate code and label for picklist items.

picklistvaluelable

Different code and label

picklistvaluevslabelincode

Apex code showing how to get Label and Code which could be used while passing data in integrations to other system

Now using this we could minimize the extra maintenance which was required initially. This is a great feature and should be considered in integrations.

Communication between Lightning Component and VisualForce

I have been playing with lightning components. Now it has confirmed that Salesforce is going to use only lightning and will provide most of its features via lightning experience. So how can we move from visualforce to lightning. Visualforce and lightning components uses different design methodologies MVC vs MVCC. So its not very easy to get migrated from visualforce to lightning once. There is a hope, salesforce has provided lightning out by which we can add lightning component in visualforce page. Isn’t that great? So we can start building lightning component and start including it in visualforce and gradually replace visualforce with lightning.

But in this migration process we would have some functionality in visualforce and some of the functionality in lighting. Now here we would want that visualforce should be able to communicate with lightning components and lightning components should be able to communicate with visualforce page. By this there are limitless possibilities of mashup of lightning components with visualforce.

Here below code demonstrates how lightning event model could be used to have communication between visualforce component and lightning component.

Code for LightningOutExampleController

public with sharing class LightningOutExampleController {
@AuraEnabled
public static List<Contact> getContacts(){
return [SELECT Id, Name From Contact ];
}
}

Code for LightningOutExample component:

<aura:component controller="LightningOutExampleController">
<aura:attribute name="contacts" type="Contact[]" default="[]"></aura:attribute>
<aura:handler name="init" value="{!this}" action="{!c.initialize}" />
<aura:handler event="c:lightningAppEvent" action="{!c.lightningAppEventHandler}"/>
<aura:registerEvent name="lightningAppExternalEvent" type="c:lightningAppExternalEvent" />
<aura:iteration items="{!v.contacts}" var="contact">
<h1>{!contact.Name}</h1><br/>
</aura:iteration>
<ui:button label="Call Visualforce code from Lightning" press="{!c.callExternalFunction}"/>
</aura:component>

Code for LightningOutExampleController.js

({
initialize : function(component, event, helper) {
var action = component.get("c.getContacts");
var self = this;
action.setCallback(this, function(a) {
var contacts = a.getReturnValue();
component.set("v.contacts", contacts);
console.log('Contacts are loaded.');
});
$A.enqueueAction(action);
},
callExternalFunction : function(component, event, helper){
console.log('Inside lightning controller function-->callExternalFunction');
var lightningAppExternalEvent = $A.get("e.c:lightningAppExternalEvent");
lightningAppExternalEvent.setParams({'data':component.get('v.contacts')});
lightningAppExternalEvent.fire();
},
lightningAppEventHandler : function(component, event, helper){
console.log('Inside lightning controller function-->lightningAppEventHandler');
console.log('Value of TestDataKey',event.getParam('data').TestDataKey);
}
})

Code of lightning out events:

a.lightningAppEvent.evt

<aura:event type="APPLICATION" description="Event template" >
<aura:attribute name="data" type="Object"/>
</aura:event>

b.lightningAppExternalEvent.evt

<aura:event type="APPLICATION" description="Event template" >
<aura:attribute name="data" type="Object"/>
</aura:event>

LightingOutExampleApp.app

<aura:application access="GLOBAL" extends="ltng:outApp">
<aura:dependency resource="c:LightningOutExample"/>
</aura:application>

Visualforce page:

<apex:page >
<apex:includeLightning />
<div id="lightning" />
<button type="button" onclick="callLightningEvent();">Call Lightning Code From VF</button>
<script>
window.onload = function() {
$Lightning.use("c:LightningOutExampleApp", function() {
var comapp=$Lightning.createComponent("c:LightningOutExample",
{},
"lightning",
function(component) {
console.log('Lightning out -->Component has been loaded.');
$A.eventService.addHandler({ "event": "c:lightningAppExternalEvent", "handler" : myFunctionFromVisualforce });
});
});
}
function callLightningEvent(){
var lightningEvent = $A.get("e.c:lightningAppEvent");
lightningEvent.setParams({'data':{'TestDataKey':'TestDataValue'}});
lightningEvent.fire();
}
function myFunctionFromVisualforce (event){
console.log('This message is from visualforce function');
console.log('Data which is coming from lightning component',event.getParam('data'));
debugger;
}
</script>
</apex:page>

In the code you can see we have used lightning event model to call methods from visualforce which are in lightning and vice versa.

I tried to have this as demo by exposing this page on site but unfortunately lightning out is currently not supported on pages hosted on public site.

This code is also present on public repo which you can check:

https://github.com/kiran-machhewar/sf-kmforce

 

Now you can experiment with lighting components in visualforce and create awesome implementations.

 

Code Comparison Utility

What happens when the code gets pushed to production which you don’t want to. Crisis !!!. This normally happens when developer A works on some file and developer B make changes to same file (mostly for bug fix/new req). So developer A thinks that only he had worked on the file and it is safer to move changes to production but when page is pushed to production unexpected things starts because of unwanted changes being pushed to production. How such situations can handled? Before any code movement to production comparing the code copy from Sandbox with Production. There are good tools available to do that like WinMerge,SVN, Eclipse inbuilt code comparison. This takes time to take fresh copy from sandbox and production and then comparing to find out which changes are getting pushed. I normally do this code comparison before moving any code to production. Being a lazy person sometimes I skip comparison because it takes time (most precious commodity :P). So to make this process faster I have used tooling api to make things automated. Here is the page developed which takes Source org (Sandbox) and Target Org (Production Org) credentials for signing in. Once you are logged in, it provides list of metadata components (currently ApexClasses,ApexPages and Triggers) to select. On selection of component it pulls the fresh code from both the orgs and gives a code comparison.

For comparing code I have used this awesome library Mergely created by Jamie Peabody Github repo : https://github.com/wickedest/Mergely

Here is the demo url : http://kmforce-developer-edition.ap1.force.com/sfcompare

You will be able to see code comparison in below manner:compare

Here left panel would be Target org (Production) and right panel would be source org (Sandbox)

Source code:

1. Controller

/**
* @ApexClass : SFCompareController
* @Description : This provides services to SFCompare page, which can be accessed by js remoting. It provides below services.
* 1. Logging into SF orgs for obtaining session and instance url.
* 2. Fetches code from the SF org.
* */
public class SFCompareController {
/**
* @description : This method does the login to sf orgs and provides session id and
* instance url wrapped in SFOrgLogin wrapper instances.
*/
@RemoteAction
public static List<SFOrgLogin> doSFLogins(String sorgType,String susername,String spassword,String torgType,String tusername,String tpassword){
List<SFOrgLogin> sfOrgLogins = new List<SFOrgLogin>();
sforgLogins.add(getSessionId(susername,spassword,sorgType));
sforgLogins.add(getSessionId(tusername,tpassword,torgType));
return sforgLogins;
}
/**
* @description : This gets the sesssion id and instance url from any SF org based on
* username, password and orgType(Production/Sandbox)
*/
public static SFOrgLogin getSessionId(String username, String password,String orgType){
HttpRequest req = new HttpRequest();
HttpResponse res = new HttpResponse();
Http http = new Http();
req.setEndpoint('https://'+orgType+&#39;.salesforce.com/services/oauth2/token');
req.setMethod('POST');
req.setBody('grant_type=password&client_id=<yourclientid>&client_secret=<yourclientsecretekey>&username='+EncodingUtil.urlEncode(username, 'UTF-8')+'&password='+EncodingUtil.urlEncode(password, 'UTF-8'));
req.setHeader('Content-Type', 'application/x-www-form-urlencoded');
try {
res = http.send(req);
System.debug(res.getBody());
Map<String,Object> response = (Map<String,Object>)JSON.deserializeUntyped(res.getBody());
SFOrgLogin sforg = new SFOrgLogin();
sforg.sessionId = ''+response.get('access_token');
sforg.instanceURL = ''+response.get('instance_url');
if(sforg.sessionId == '' || sforg.sessionId == 'null'
|| sforg.instanceURL == '' || sforg.instanceURL == 'null'){
throw new SFCompareException('Username/Password is incorrect - Please check details for '+username);
}
return sforg;
} catch(System.CalloutException e) {
System.debug('Callout error: '+ e);
System.debug(res.toString());
}
return null;
}
/**
* @ApexClass : SFOrgLogin
* @Description : Wrapper to hold session id and instance url.
*/
public class SFOrgLogin{
String sessionId;
String instanceURL;
}
/**
* @Returns the metadata options for selected metadata types.
*/
@RemoteAction
public static Map<String,Object> getMetadata(SFOrgLogin sforgLogin){
List<String> metadataItems = new List<String>();
metadataItems.add('ApexClass');
metadataItems.add('ApexPage');
metadataItems.add('ApexTrigger');
//metadataItems.add('CustomObject');
Map<String,Object> result = new Map<String,Object>();
for(String metadata : metadataItems){
result.put(metadata,getOptions(sforgLogin,metadata));
}
return result;
}
/**
*@Description : For selected metadata type it returns all the entries in the org wrapped in Option(Wrapper class).
*/
private static List<Option> getOptions(SFOrgLogin sforgLogin,String metadataItem){
String query = ' SELECT Id, Name FROM '+metadataItem + ' Order By Name ';
query = EncodingUtil.urlEncode(query, 'UTF-8');
String response = makeToolingApiRequest(sforglogin.instanceURL+'/services/data/v28.0/tooling/query/?q='+query,sforglogin.sessionid);
List<Option> result = new List<Option>();
Map<String,Object> responseMap = (Map<String,Object>)JSON.deserializeUntyped(response);
List<Object> records = (List<Object>)responseMap.get('records');
for(Object record : records){
Map<String,Object> recordObj = (Map<String,Object>) record;
result.add(new Option(metadataItem + '/'+recordObj.get('Id'),''+recordObj.get('Name')));
}
return result;
}
/**
*@description : Helps making tooling api call.
*/
private static String makeToolingApiRequest(String endpoint,String sessionId){
HttpRequest req = new HttpRequest();
//Set the tooling api endpoint
req.setEndpoint(endpoint);
/*Set authorization by using current users session Id*/
req.setHeader('Authorization', 'Bearer ' + sessionId);
req.setHeader('Content-Type', 'application/json');
req.setMethod('GET');
Http http = new Http();
HTTPResponse res = http.send(req);
return res.getBody();
}
/**
* @description : It returns the id of selected metadata element from target org.
*/
private static String getTargetOrgMetadataItemId(SFOrgLogin sforgLogin,String metadataItem,String metadataType){
String query = ' SELECT Id, Name FROM '+metadataType+' WHERE Name =\''+metadataItem+'\' ';
query = EncodingUtil.urlEncode(query, 'UTF-8');
String response = makeToolingApiRequest(sforglogin.instanceURL+'/services/data/v28.0/tooling/query/?q='+query,sforglogin.sessionid);
Map<String,Object> responseMap = (Map<String,Object>)JSON.deserializeUntyped(response);
List<Object> records = (List<Object>)responseMap.get('records');
for(Object record : records){
Map<String,Object> recordObj = (Map<String,Object>) record;
return ''+recordObj.get('Id');
}
return null;
}
/**
* @description : It returns the code of metadata element(ApexClass,ApexTrigger or ApexPages)
*/
private static String getCode(SFOrgLogin sforgLogin,String metadataURL){
String result=null;
String response = makeToolingApiRequest(sforglogin.instanceURL+'/services/data/v28.0/tooling/sobjects/'+metadataURL,sforglogin.sessionid);
Map<String,Object> responseMap = (Map<String,Object>)JSON.deserializeUntyped(response);
if(responseMap.get('Body') != null){
result = ''+responseMap.get('Body');
}else if(responseMap.get('Markup') != null){
result = ''+responseMap.get('Markup');
}
return result;
}
@RemoteAction
public static Code getCode(SFOrgLogin source,SFOrgLogin target,String metadataURL,String metadataItem){
Code result = new Code();
String metadataType = metadataURL.split('/')[0];
String targetMetadataURL = metadataType + '/'+ getTargetOrgMetadataItemId(target,metadataItem,metadataType);
result.sourceCode = getCode(source,metadataURL);
result.targetCode = getCode(target,targetMetadataURL);
return result;
}
/**
*@ApexClass : Code
*@Description : Wrapper class to hold source code and target org used for comparison
*/
public class Code{
String sourceCode;
String targetCode;
public Code(){}
public Code(String sourceCode,String targetCode){
this.sourceCode = sourceCode;
this.targetCode = targetCode;
}
}
/**
*@ApexClass : Option
*@Description : Wrapper class to hold value and label of metadata element
*/
public class Option{
String value;
String label;
public Option(String value,String label){
this.value = value;
this.label = label;
}
}
/**
* @ApexClass : SFCompareException
* @Description : Custom Exception
*/
public class SFCompareException extends Exception {}
}

2. Page

<!--
This page has functionality to compare code from two different orgs.
Here following libraries are used.
Select2 : Gibhub: http://select2.github.io/
Mergely : An Awesome code comparison javascript library by jamie.peabody@gmail.com
Github: https://github.com/wickedest/Mergely
JQuery and Bootstrap
-->
<apex:page sidebar="false" controller="SFCompareController" showHeader="false" standardStylesheets="false">
<apex:includeScript value="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"/>
<apex:stylesheet value="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0-beta.3/css/select2.min.css" />
<apex:includeScript value="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0-beta.3/js/select2.min.js"/>
<apex:includeScript value="{!URLFOR($Resource.mergely,'/codemirror.min.js')}"/>
<apex:stylesheet value="{!URLFOR($Resource.mergely,'/codemirror.css')}" />
<apex:includeScript value="{!URLFOR($Resource.mergely,'/mergely.js')}"/>
<apex:stylesheet value="{!URLFOR($Resource.mergely,'/mergely.css')}" />
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"/&gt;
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css"/&gt;
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script&gt;
<style>
.CodeMirror {
font-family: monospace;
height: 500px;
}
</style>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">SF Code Compare</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li ><a href="#">By Kiran Machhewar</a></li>
<li ><a href="javascript:logout();">Logout</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</nav>
<div class="container">
<h1>`</h1>
<div id="loginDetailSection">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Source Org Creds:</h3>
</div>
<div class="panel-body">
<form class="form-inline">
<div class="form-group">
<label for="exampleInputName2">Org Type</label>
<select class="form-control" id="sourceOrgType" >
<option value="login">Production</option>
<option value="test">Sandbox</option>
</select>
</div>
<div class="form-group">
<label for="exampleInputName2">Username</label>
<input type="text" class="form-control" placeholder="john@salesforce.com.uat" id="sourceUsername"/>
</div>
<div class="form-group">
<label for="exampleInputEmail2">Email</label>
<input type="password" class="form-control" id="sourcePassword" placeholder="Password"/>
</div>
</form>
</div>
</div>
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Target Org Creds:</h3>
</div>
<div class="panel-body">
<form class="form-inline">
<div class="form-group">
<label for="exampleInputName2">Org Type</label>
<select class="form-control" id="targetOrgType" >
<option value="login">Production</option>
<option value="test">Sandbox</option>
</select>
</div>
<div class="form-group">
<label for="exampleInputName2">Username</label>
<input type="text" class="form-control" id="targetUsername" placeholder="john@salesforce.com"/>
</div>
<div class="form-group">
<label for="exampleInputEmail2">Email</label>
<input type="password" class="form-control" id="targetPassword" placeholder="Password"/>
</div>
</form>
</div>
</div>
<center><button type="submit" onclick="doSFlogin();" class="btn btn-default">Login</button></center>
</div>
<div class="panel panel-primary" id="selectionPanel" style="display:none;">
<div class="panel-heading">
<h3 class="panel-title">Select Metadata Component to Compare</h3>
</div>
<div class="panel-body">
<center>
<div >
<select style="width: 400px;" id="metadataOptions" onchange="showDifference();">
</select>
</div>
</center>
</div>
</div>
</div>
<div id="codeCompareParent">
<div id="compare"></div>
</div>
<script>
var sourceOrgLogin ;
var targetOrgLogin ;
var codeCompare ;
jQuery(function(){
var allValuesCached = true;
if(localStorage.getItem('sourceOrgType') != 'null' ){
jQuery('[id$=sourceOrgType]').val(localStorage.getItem('sourceOrgType'));
}else{
jQuery('[id$=sourceOrgType]').val('test');
allValuesCached = false;
}
if(localStorage.getItem('sourceUsername') != 'null'){
jQuery('[id$=sourceUsername]').val(localStorage.getItem('sourceUsername'));
}else{
allValuesCached = false;
}
if(localStorage.getItem('sourcePassword') != 'null'){
jQuery('[id$=sourcePassword]').val(localStorage.getItem('sourcePassword'));
}else{
allValuesCached = false;
}
if(localStorage.getItem('targetOrgType') != 'null'){
jQuery('[id$=targetOrgType]').val(localStorage.getItem('targetOrgType'));
}else{
allValuesCached = false;
}
if(localStorage.getItem('targetUsername') != 'null' ){
jQuery('[id$=targetUsername]').val(localStorage.getItem('targetUsername'));
}else{
allValuesCached = false;
}
if(localStorage.getItem('targetPassword') != 'null' ){
jQuery('[id$=targetPassword]').val(localStorage.getItem('targetPassword'));
}else{
allValuesCached = false;
}
});
function doSFlogin(){
//fetch details of source org
var sourceOrgType = jQuery('[id$=sourceOrgType]').val();
var sourceUsername = jQuery('[id$=sourceUsername]').val();
var sourcePassword = jQuery('[id$=sourcePassword]').val();
localStorage.setItem('sourceOrgType',sourceOrgType);
localStorage.setItem('sourceUsername',sourceUsername);
localStorage.setItem('sourcePassword',sourcePassword);
//fetch details for targetorg org
var targetOrgType = jQuery('[id$=targetOrgType]').val();
var targetUsername = jQuery('[id$=targetUsername]').val();
var targetPassword = jQuery('[id$=targetPassword]').val();
localStorage.setItem('targetOrgType',targetOrgType);
localStorage.setItem('targetUsername',targetUsername);
localStorage.setItem('targetPassword',targetPassword);
login(sourceOrgType,sourceUsername,sourcePassword,targetOrgType,targetUsername,targetPassword);
}
function login(sourceOrgType,sourceUsername,sourcePassword,targetOrgType,targetUsername,targetPassword){
startSpinner();
//doing login for getting session ids
SFCompareController.doSFLogins(sourceOrgType,sourceUsername,sourcePassword,targetOrgType,targetUsername,targetPassword,function(result,event){
stopSpinner();
if(event.status){
if(result && result.length == 2){
sourceOrgLogin = new SFOrgLogin(result[0].sessionId,result[0].instanceURL);
targetOrgLogin = new SFOrgLogin(result[1].sessionId,result[1].instanceURL);
populateMetadataOptions(sourceOrgLogin);
jQuery('[id$=loginDetailSection]').hide();
}
}else{//error occured
alert(event.message);
}
});
}
//SFOrgLogin object to hold login details- It is similar to SFOrgLogin wrapper (apex)
function SFOrgLogin(sessionId,instanceURL){
this.sessionId = sessionId;
this.instanceURL = instanceURL;
}
//Get metadata files from the source org
function populateMetadataOptions(sforglogin){
startSpinner();
SFCompareController.getMetadata(sforglogin,function(result,event){
stopSpinner();
if(event.status){
if(result){
for(key in result){
var groupStart = '<optgroup label="'+key+'">';
var groupBody = '';
for(index in result[key]){
groupBody +='<option value="'+result[key][index].value+'">'+result[key][index].label+'</option>';
}
var groupEnd = '</optgroup>';
jQuery('[id$=metadataOptions]').append(groupStart+groupBody+groupEnd);
}
jQuery('[id$=metadataOptions]').select2();
jQuery('#selectionPanel').show();
}
}else{//error occured
alert(event.message);
}
});
}
function showDifference(){
if(codeCompare){
$('#compare').mergely('lhs', 'Fetching Code...')
$('#compare').mergely('rhs', 'Fetching Code...')
}
var metadataURL = jQuery('[id$=metadataOptions]').val();
var metadataItemName = jQuery('#selectionPanel').find('select option:selected').text();
startSpinner();
SFCompareController.getCode(sourceOrgLogin,targetOrgLogin,metadataURL,metadataItemName,function(result,event){
stopSpinner();
if(event.status){
if(!codeCompare){
codeCompare = true;
jQuery('#compare').mergely({
cmsettings: { readOnly: true, lineNumbers: true },
lhs: function(setValue) {
setValue(result.targetCode);
},
rhs: function(setValue) {
setValue(result.sourceCode);
},
ignorews : true,
editor_height : '500px',
editor_width : ((window.innerWidth-80)/2)+'px'
});
}else{
$('#compare').mergely('lhs', result.targetCode)
$('#compare').mergely('rhs', result.sourceCode)
}
}else{//error occured
alert(event.message);
}
},{escape : false});
}
function logout(){
//clearing local storage
localStorage.setItem('sourceOrgType',null);
localStorage.setItem('sourceUsername',null);
localStorage.setItem('sourcePassword',null);
localStorage.setItem('targetOrgType',null);
localStorage.setItem('targetUsername',null);
localStorage.setItem('targetPassword',null);
//setting default values
jQuery('[id$=sourceOrgType]').val('test');
jQuery('[id$=sourceUsername]').val('');
jQuery('[id$=sourcePassword]').val('');
jQuery('[id$=targetOrgType]').val('login');
jQuery('[id$=targetUsername]').val('');
jQuery('[id$=targetPassword]').val('');
jQuery('#loginDetailSection').show();
jQuery('#codeCompareParent').hide();
jQuery('#selectionPanel').hide();
}
//accessing spinner componet via javascript
function startSpinner(){
jQuery('[id$="LoadingStatusSpinner.start"]').show();
}
function stopSpinner(){
jQuery('[id$="LoadingStatusSpinner.start"]').hide();
}
</script>
<!--Spinner showing compoent- You can have your own-->
<c:loadingStatusSpinner ></c:loadingStatusSpinner>
</apex:page>
view raw SFCompare.page hosted with ❤ by GitHub

If you find this utility useful, please comment and let me know your views/suggestions on it.

Salesforce Integration with external Systems

In Salesforce for integrations before deciding on any approach ask yourself following questions so that you can make a better decision about an approach.

A. What is expectation of response. Is it instantaneous or can user wait? If user can wait then what is the threshold value for which user will wait?
Why: 1. If the response is returned in the same call then its very good, but if is giving request identifier then for fetching results you will need Schedulable batch option which can make callout and get the results for you. Always remember that this will delay the completion of whole cycle by min 2 mins to 15 min depending upon how sales force executes batch.
2. There is very hard limit of 10 callouts in a transaction so consider this before doing any architecture.

A. Generating XML by String concatenating?
1. Try to divide XML generation by dividing whole logic in methods.
2. Have one method for every kind of XML generation which cleans up the value based on type. Eg. Applying appropriate date format, handling null values. This gets varied based on the system with which you are integrating. So it gives you the ability to keep formatting things at common place.

B. What is the expected time of the response?
There is a limit of 120 seconds limit for overall call out time in a transaction and cap of 60 seconds for a single callout.

C. Are you sending any DB generated data in integration?
If you are sending any DB generated data like autonumber, then you need break transaction, since sales force does not allow any dml before the call out. Normally changing transaction means normally doing ajax call after the DML making transaction is done.

D. Do you need to store information received after making callout and handling network failure or system error?
So basically you are doing a DML after call out which is allowed, but just think what if the dml fails and you rolled back everything. But my friend you can not rollback the call out you had done, so have planning for such scenario like submitting the data again and asking the other end system to ignore the first call. This save lot of efforts and panic when system goes live.

If you have any integration related question please comment below. Happy learning!!

Notifications for Scheduler if they don’t run.

Hi all, We use schedulers and batches in salesforce for many reasons like daily cleanup, daily processing of data and there comes the need of checking that if your scheduler is running properly with the specified time interval. Here is the solution to get the notification if your scheduler did not run within a particular interval. You will get a nice email alert if the scheduler is not running.

Follow the following steps.

1. Create one object Notification with name as text field and a checkbox as notify (Notify__c).

2. Create the “Notify_after_one_hour__c” datetime field in the notification object.

3. Create the following method in your Notification class.

public class Notification{
/**
* @description :
* @param jobName Name of the scheduler
* @param durationInMinutes Greater duration than the time interval between scheduler executions.
*/
public static void addNotificationFor(String jobName, Integer durationInMinutes){
Notification__c notification = new Notification__c(
Name = jobName,
External_Code__c = jobName,
Notify__c = false
);
upsert notification External_Code__c;
//This makes sure that it will meet the criteria to send email
notification.Notify__c = true;
notification.Notify_After_One_Hour_Of_This_Time__c = System.Now().addHours(-1).addMinutes(durationInMinutes);
notification.Last_Run__c = System.now();
update notification;
}
}

4. Create the workflow rule as follows

notification_workflow

This workflow rule adds an action to send the email after one hour of the “Notify_after_one_hour__c” date time field from the notification object. Here just call the method from the notification method and specify the greater time interval in minutes than the duration between two consecutive executions of scheduler. Call this Notification.addNotificationFor(‘<JobName>’,<duration in minutes>). Let’s say there is a scheduler which runs at the interval of two hours and you want to get notified it the scheduler did not run after 2 hours. Then just add this line to the start of the schduler as

Notification.addNotificationFor(‘SchedulerRunningAfterEvery2Hours’,130);

Here I have set time as 130 minutes. Here first time when this method gets executed it will add an action to send email after 2hours and 10 minutes. If the scheduler runs properly after 2 hour then this method will get again executed and the time dependent action will get recalculated and email notification will be forwarded ahead by 2 hours and suppose if scheduler did not run after 2 hours then email notification will not get again forwarded and you will get email notification after 2hours and 10 minutes.

This can be used in schedulers, regularly running jobs.

I hope this will help to get notified if your important job is not running after specified time interval.

 

Create your own website, free on WordPress.com.Create your own website.
Start free