Monday, April 22, 2019

Platform Events : Way to Deliver Custom Notifications within Salesforce or to external Applications

Salesforce provides Platform events which can be used create custom notification which can be used within Salesforce app or can be send to external applications. These notification are secure and scalable.

Platform events are part of Salesforce’s enterprise messaging platform. It utilizes publish and subscribe flow. One or many subscribe to same event and carry out different actions.

In lightning events, we define event and then create attributes through which information can shared between lightning components. Similar to this, you create platform event through point and click and then create custom fields which will be used to publish information by using platform events and subscriber can utilize this information.

Platform Events v/s Streaming API

  • In Streaming API (using Push Topics), subscriber receive notification based on changes or updates to records.
  • You can not edit or delete platform event records. You can only create or insert platform events.
  • Visualforce and Lightning component apps can subscribe to platform events using CometD similar to push topics.
  • You can not view platform event in Salesforce user interface and cannot query it through SOQL.
  • You can handle or subscribe platform events through triggers by using after insert.
  • Only "AfterInsert" event is available for platform event objects.
  • Platform events can be published by Process builder, Process Flow, apex, REST API by inserting an sObject.
  • Platform events persist for 24 hours only.
Permission for platform events is controlled through profile or permission sets.

Platform events can be used to publish information and has no dependency on existing salesforce records.

In order to create platform events, navigate to Setup --> Platform Events --> New Platform Event.

I have created a platform event "Demo Event" and going to use apex in order to publish event and subscribe this event through triggers.

When you create a platform event, the system appends the __e suffix to create the API name of the event.

How to fire/publish platform event
  • You have to create record in order to fire platform event.
To publish event messages, you create an instance of the event and pass it to the EventBus.publish method. Use below code snippet to publish event:

// Create an instance of the Demo event 
Demo_Event__e demoEvent = new Demo_Event__e(
           Event_Info__c='Demo event is fired using Apex', 
           Is_Event_Valid__c=true, 
           Event_Publisher__c='Apex Code');
// Call method to publish events
Database.SaveResult sr = EventBus.publish(demoEvent);
// Inspect publishing result 
if (sr.isSuccess()) {
    System.debug('Successfully published event.');
} else {
    for(Database.Error err : sr.getErrors()) {
        System.debug('Error returned: ' +
                     err.getStatusCode() +
                     ' - ' +
                     err.getMessage());
    }
}
  • You can create record using process builder or process flow.
  • You can create event using REST API. Below is details of HTTP Request:
Endpoint- /services/data/v45.0/sobjects/Demo_Event__e/
body
{
   "Event_Info__c" : "Demo event is fired using REST API CALL",
   "Is_Event_Valid__c" : true,
   "Event_Publisher__c" : "REST API CALL"
}
Method - POST
HTTP Response:

{   
   "id" : "e00xx0000000ccf",
   "success" : true,
   "errors" : [ ],
   "warnings" : [ ] 
}

How to Subscribe Platform Events using Apex Triggers

Whenever a record is created for platform event, after insert trigger gets fired. You can use below code to subscribe for platform event and perform logic as per your need:

trigger DemoEventTrigger  on Demo_Event__e (after insert) {
List<Task> taskList = new List<Task>();
for (Demo_Event__e event: Trigger.New) {
if (event.Is_Event_Valid__c == true) {
//perform logic based on event information
}
   }
}

Below is snapshot explaining Platform Events.
Hope this will help!!!




Friday, April 19, 2019

Way to export Code Coverage of Individual ApexClass or Trigger in .csv format

Salesforce provide Tooling API (REST API) through which we can find org metadata information.  Tooling API provide object called "ApexCodeCoverage" which can be used to find code coverage information about individual class or trigger or Org complete code coverage information.

I have created a apex script which can be run in developer console in "Execute Anonymous Window". After running this script, you will receive an email with .csv file which will contain information about code coverage for each apex class or trigger.

Below is snapshot of .csv file which you will recieve:


By using Tooling API you can find overall code coverage of your organization. Below is script which you can use in "Execute Anonymous Window".

Important things to consider in order to get have reliable coverage details:

  • Go to setup --> apex test execution ---> click on Options ---> deselect the Store only aggregate code coverage option.
  • Go to Setup --> Apex test execution ----> Clear all test history.
  • Go to Setup --> Apex classes ---> Compile all classes.
  • Go to Setup ---> Apex test execution ---> Run all test.
Once Run All Test is completed, then above scripts to get actual code coverage details of all classes or trigger or to get overall Org code coverage percentage.

You can also run the queries on "apexCodeCoverage" and "ApexOrgWideCoverage" object in developer console query editor by selecting tooloing api checkbox.

To get Org Overall Code coverage use below Query:

"SELECT PercentCovered FROM ApexOrgWideCoverage "



To get code coverage of specific apex class or trigger use below query:

SELECT Coverage FROM ApexCodeCoverage WHERE ApexClassOrTriggerId = 'xxxxxxxxx'
where xxxxxxxxx = 15 or 18 digit apex class or apex trigger id.



Hope this will help!!

Looking forward for everyone comments and suggestions...