Category Archives: Apex

Chrome Push Notifications using Pushbots from Salesforce

Now push notifications are available on web browser also along with mobile. You must have seen websites where websites request you for the access to allow notifications and if you allow the website to send notifications then even if the website is not open in any tab then also you get the notifications.

Software Requried:

Same thing could be used with salesforce to increase customer engagement in salesforce sites/communities. So even if the user has not opened your salesforce site/community then also you could notify your users about important product launches, new announcements, news about your company and list goes on.

Lets see how this can be achieved.   You would need to follow below steps to enable push notifications on your salesforce site. The same kind of implementation will work with the community as well as any internal salesforce community.

Here we would be using pushbots to deliver the notifications. Even its free account is sufficient to handle many notifications and based on its awesome dashboards you can see what is you user base and then you could go for paid service.

Push Notification will look like below:

Screen Shot 2017-05-27 at 8.32.34 PM

Push Notification

Let’s understand what are the steps to be followed in order to setup this push notifications on your salesforce site.

Step 1. Configure Google Project

Navigate to https://console.developers.google.com  and create a project. Go to the project settings and copy the project number. This project number would be used in the configurations of pushbot.

ProjectSetting

Project Setting

Activate the required APIs:  Now you need to enabled the Google Cloud Messaging for the push notifications.  Navigate to dashboard and there you would be able to see ENABLE API option. Select “Google Cloud Messaging” and enabled it.

EnableAPIs

Enable Google Cloud Messaging APIs

Create credential key:  Now we need the API key from the google project that you have created. Go to credentials and if there is no key already created and create a new server key. Copy this server key, you would need this while configuring the pushbot application.

GenerateAPIKey

Generate API Key

Step 2: Create site:

For the sake of example, we are going to create a site but it is not a required step. You can implement this for internal users also like using internal visualforce pages.

E.g: https://kmforce-chrome-developer-edition.ap2.force.com/

Step 3: Create Pushbot Application from https://pushbots.com/

Give name to your app

PushbotApp

Create Pushbot Application

Go to to Push tab of application, Add GCM Key, configure logo and configure site URL as below:

PushbotAppConfiguration

Step 4: Configure your site and deploy the code from https://github.com/kiran-machhewar/salesforce-chrome-pushbot-notification

Note: I have downloaded chrome SDK from https://pushbots.com/developer/docs/chrome-integration and modified it based on the needs of salesforce. At the time of writing of this blog static resource is up to date. But in future for any new features you might want to get it from Pushbots official site and modify it.

Once code is deployed you can set your site homepage as PushNotificatonPage for testing.

You would need to make below changes in your static resource file and PushNotificationHandler.cls

a. Configure PushNotificationHandler:

TriggerHandler

b. Configure pushbots-chrome.js from static resource:

pushbots-chrome

c. Configure service-worker.js from static resource:service-worker d. Configure manifest.js

manifest

How does this work: Now open your site and click on Enable Notification.

Screen Shot 2017-05-27 at 8.25.08 PM

Now click on Allow

Screen Shot 2017-05-27 at 8.27.02 PM

Once you you allow notifications from this site then chrome will allow itself to listen any notifications which are sent to chrome browser by Pushbots.com.

Now go to Pushbots Notification app and create a record for Push Notification

Screen Shot 2017-05-27 at 8.31.26 PM

Once you create a record a future method from trigger will get fired which will call pushbots api to add notification. Once Pushbots.com gets that notification it delivers that notification to all the users who have subscribed to notifications and every one will receive notification.

On chrome it will look like:

Screen Shot 2017-05-27 at 8.32.34 PM

On mobile it will look like:

Screenshot_20170527-203142

This is not limited to salesforce, this can be configured on any website in any framework.

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..

 

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

2. Page

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

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.

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.

 

Custom Picklist

Hi all, In Picklist you can not have more than 1k entries. But I ran into a scenario where I wanted to show State, City and Pincodes as Picklist which were more than 1K. So the option was to create City a dependent picklist of State and a Pincode which is dependent of City. States were very less, but the cities count exceeded the limit of 1k entries and Pincodes were way higher. So went with the decision of making Custom Objects for state, city and pincode and manage dependencies with lookups. City will have lookup to State and Pincode will have lookup to City. But then came the problems of writting much code on the side of controller and as well as page to populate State,City and Pincode options in controller and then managing action support so that when state changes City needs to be also changed. So I thought why not to create a component which takes care of all issues. I have created a Picklist component which can show any lookup as picklists and also manages dependencies.

Features

1: You can use with fieldset and every lookup can be changed to picklist.

2: Picklist(sobject) dependencies can be maintained. In demo page only those contacts are shown which are under selected account.

3. Fast response because Js Remoting is used.

4. No need to write any extra apex code to populate options and action supports to manage picklist dependencies.

5. View state less.

DEMO PAGE

Here is the code for Custom Picklist Component

 

Here is the code for Custom Piklist Controller

Demo Page Code

 

No Callout limit and doing dmls before callout :)

In salesforce there are strict limitations on how callouts are used. Because they take much resources. One of the most important limitations which needs to be considered while doing integrations with external systems is doing DML before the callout. Salesforce does not permit doing DMLs before the callout. This post is about using PageReference.getContent()  and doing as many callout as you want and also doing DML’s before callout.

Here is the code:

Create the page as follows:

Create the class as follows:

Thats it..Now you are ready.

Usage:

When you run this code in anonymous block, you can see in limit section callout counter still shows ZERO. Try doing more than 10 callouts, you will see that counter is ZERO which means you can make more than 10 callouts. 🙂

So you will get the response from this method. I tried making 24 callouts in a single transaction, which took nearly 20 seconds and code proves you can make DML’s before callout.

By this method you can make Http GET or POST callout. So this approach gives you the place where you will see some limits will not act. Like

1. DML’s will not get counted.

2. SOQL’s will not get counted.

Note: Add the urls in remote site settings. Limits in salesforce are there with good reasons. Use this only when you have no option.

[If you are not able to see code then follow this]

Feel free to leave your comments.