Sunday, December 30, 2018

Use of Inherited Sharing in Apex Class


This post explains the use of inherited sharing in apex class
If you specify inherited sharing Keyword on an Apex class,  which allows the class to run in the sharing mode of the class that called it. Using inherited sharing enables you to pass security review and ensure that your privileged Apex code is not used in unexpected or insecure ways.

  1. An Apex class with inherited sharing runs as with sharing when used as a Visualforce page controller, Apex REST service, or an entry point to an Apex transaction.
  2. An Apex class with Inherited Sharing is being called from some other class which is having without sharing setting, then it will run in without sharing mode.
Example
This example declares an Apex class with inherited sharing and a Visualforce invocation of that Apex code. Because of the inherited sharing declaration, only opportunities for which the running user has sharing access are displayed. If the declaration is omitted, even opportunities that the user has no rights to view are displayed due to the insecure default behavior of omitting the declaration.
Apex Class
public inherited sharing class OpportunityMethods {
    public list<Opportunity> getAllTheOpps(){
        return [SELECT Id, Name, StageName FROM Opportunity];
    }
}
Visualforce page
<apex:page controller="OpportunityMethods">
    <apex:repeat value="{!getAllTheOpps}" var="record">
        {!record.Name}
    </apex:repeat>
</apex:page>

Happy Learning!!

Saturday, December 29, 2018

How to Enforce Field-Level Security Permissions for SOQL Queries?


This post explains how to enforce field level security permissions for SOQL queries,
In Spring' 19 release salesforce introducing this feature, at the time of writing this post this feature in Beta stage.
Use the WITH SECURITY_ENFORCED clause to enable checking for the field- and object-level security permissions on SOQL SELECT queries, including subqueries and cross-object relationships. Although performing these checks was possible in earlier releases, this clause substantially reduces the verbosity and technical complexity in query operations.

How it Works?

If fields or objects referenced in the SELECT clause using WITH SECURITY_ENFORCED are inaccessible to the user, an exception is thrown, and no data is returned.

Example: 1
SELECT Id, Name, StageName, ClosedDate FROM Opportunity WITH SECURITY_ENFORCED
if the stage name is inaccessible to the user it throws an exception insufficient permissions. and no data return.

Example: 2
SELECT Id, (SELECT FirstName, LastName FROM Contacts), (SELECT Description, StageName, CloseDate FROM Opportunities) 
       FROM Account WITH SECURITY_ENFORCED
if the First Name, stage name is inaccessible to the user it throws an exception insufficient permissions. and no data return.

Resource
http://releasenotes.docs.salesforce.com/en-us/spring19/release-notes/rn_apex_select_with_security_enforced.htm

Wednesday, December 26, 2018

How to remove all special characters from String in Apex

This post explains how to remove special characters from the string in Apex
Example:
String strText = 'Welcome - to! % $sale&sforce \\ /code # crack %';
strText = strText.replaceAll('[^a-zA-Z0-9\\s+]', '');
System.debug('strText ======> '+strText);

Result
Happy Learning!!!

Sunday, December 23, 2018

How to get Record Type Developer Name in Apex?


This post explains how to get the record type developer name in the apex.

Getting Record Type Id using Developer Name

Let assume Record Type Developer Name  is "Customer_Account" on Account Object
you want id of the Record type use below sample code

Example

Id idRecordId = Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName().get('Customer_Account').getRecordTypeId();
System.debug('RecordTypeId based on Developer Name ---> '+idRecordId);
the above code returns the Record type Id based on developer name

Getting Record Type Developer Name

Let assume Record Type Name  is "Cluster Account" on Account Object
you want Developer Name of the Record type use below sample code

Example

String strRecordDevName = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Cluster Account').getDeveloperName();
System.debug('Record Developer Name ====> '+strRecordDevName);
the above code returns the developer name based on the record type name
Assume you have record type id instead of name use below sample code
String strRecordDevName = Schema.SObjectType.Account.getRecordTypeInfosById().get('012w0000000kgdfAAQ').getDeveloperName();
System.debug('Record Developer Name ====> '+strRecordDevName);
Let us know if have any queries
Happy Learning!!!

Friday, December 21, 2018

How to get current Month last date in Apex?

This post explains how to get the current month last date in the apex.

Example:

Date dLastDate = Date.today().addMonths(1).toStartOfMonth().addDays(-1);
System.debug(' current month last date ===> '+dLastDate);

Result
Let us know if you have any queries
Happy Learning!!!

Wednesday, December 19, 2018

How to Read REST API GET Parameters in Apex

This post explains How we can read the REST API GET parameters in Apex
We can read the parameters based on URL

Example:1

URL: /services/apexrest/getContactdetails?accountId=Accountd&leadSource=Web
Rest Method: GET
Demo:
@RestResource(urlMapping='/getContactdetails/*')
global class RESTServiceDemoClass {
    
    @HttpGet
    global static list<Contact> getContactList() {
        String strAccId = '';
        String strLeadSource = '';
        list<Contact> lstCons;
        RestRequest restReq = RestContext.request;
        RestResponse restRes = RestContext.response;
        // Reading parametrs from URL
        strAccId = restReq.params.get('accountId');
        strLeadSource = restReq.params.get('leadSource');
        if(!String.isBlank(strAccId) && !String.isBlank(strLeadSource)) {
            lstCons = [Select Id, Name, Email FROM Contact WHERE AccountId =:strAccId AND LeadSource =: strLeadSource];
        }
        return lstCons;
    }
}
above class return the list of contacts based on passing parameters accountId and lead source
Example URL
/services/apexrest/getContactdetails?accountId=0017F00000idCUi&leadSource=Web
Result:

Example: 2

URL: /services/apexrest/getContactdetails/Accountd&Web
Rest Method: GET

Demo:
@RestResource(urlMapping='/getContactdetails/*')
global class RESTServiceDemoClass {
    
    @HttpGet
    global static list<Contact> getContactList() {
        String strAccId = '';
        String strLeadSource = '';
        list<Contact> lstCons;
        RestRequest restReq = RestContext.request;
        RestResponse restRes = RestContext.response;
        // Reading parametrs from URL
        strAccId = restReq.requestURI.substring(restReq.requestURI.lastIndexOf('/') + 1);
        strAccId = strAccId.left(strAccId.lastIndexOf('&'));
        strLeadSource = restReq.requestURI.substring(restReq.requestURI.lastIndexOf('&') + 1);
        if(!String.isBlank(strAccId) && !String.isBlank(strLeadSource)) {
            lstCons = [Select Id, Name, LeadSource FROM Contact WHERE AccountId =:strAccId AND LeadSource =: strLeadSource];
        }
        return lstCons;
    }
}

Example URL:
/services/apexrest/getContactdetails/0017F00000idCUi&Web
Result:



Let Us know if you have any queries.
Happy Learning!!

Sunday, December 16, 2018

Introduction to Lightning Web Components(LWC)


This post explains the
1. What is Lighting Web Component(LWC)?
2. How to Create a Lightning Web Component with Non-scratch org.

What is Lighting Web Component(LWC)?
1. LWC is a new Programming Language modal for building a Lightning Components
2. LWC uses modern web programming standards, shadow DOM, modules and ECMAScript7.
3. LWC coexist and interoperate with the original Aura programming model, and delivers unparalleled performance.
How to Create a Lightning Web Component?
You cannot create LWC directly from your developer console. you need to SFDX to create your lightning web component.

Step 1: Steps to set up an SFDX with vs code

1. Download and Install Salesforce CLI
2. Download vs code From this link and install.
Note: Once install the Salesforce CLI You can verify using below command
sfdx --version

Installing Salesforce Extensions in vs code
1. Open vs code install Salesforce extension pack

2. Install Lightning Web Components Extension

Step 2: Signup to pre-release org

Sign up for a pre-release Developer Edition Org using below link
Note: Once you create the Pre-release developer org add my domain for the Org otherwise custom developed components are not visible in the app builder

Step 3: Upgrade Pre-Release version of Salesforce CLI

Use below command to upgrade the Pre-release version of Salesforce CLI
sfdx plugins:install salesforcedx@pre-release

Step 4: Creating the SalesforceDx Project

Go to your vs code editor
Press "CTRL + SHIFT + P" then select SFDX:Create Project with Manifest

Enter project Name and Select Folder

Step 5: Authorize an org

Press "CTRL + SHIFT + P" then select SFDX: Authorize an Org
this command opens your default browser then login to your pre-release developer org
once logged in to your org you may close your browser

Step 6: Creating Lightning Web Components

Press "CTRL + SHIFT + P" then select SFDX: Create Lightning Web Component
Then Select Folder where you want to save your LWC component
Then give your component name
verify component under lwc folder


Example

LWCDemoComponent.html
<template>
    <lightning-card title="Contact" icon-name="standard:contact">

        <lightning-record-form object-api-name={objectApiName} record-id={recordId} 
                               fields={fields}></lightning-record-form>

    </lightning-card>
</template>
LWCDemoComponent.js
import { LightningElement , api, track} from 'lwc';

export default class LWBDemoComponent extends LightningElement {
    @api recordId;
    @api objectApiName;
    @track fields = ['Name', 'Title', 'Phone', 'Email'];
}
LWCDemoComponent.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="LWBDemoComponent">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
      <targets>
    <target>lightning__AppPage</target>
    <target>lightning__RecordPage</target>
    <target>lightning__HomePage</target>
  </targets>
</LightningComponentBundle>

Step 7: Deploy your component in Org

once you complete the code, go to your lwc folder then right click on the component folder
select SFDX: Deploy Source to Org
go to contact record page editor you can verify your components
That's it

Resources
Trailhead Link

Let us know if you have any queries
Happy Learning!!!

Sunday, December 9, 2018

lightning:fileUpload component in lightning

This post explains how to use lightning:fileupload in lighting component

lightning:fileUpload component provides an easy and integrated way for users to upload multiple files. The file uploader includes drag-and-drop functionality and filtering by file types.

Limitations
  • By default we can upload max 10 files, Admins can contact Salesforce to request a changeup to a maximum of 25 files uploaded at one time
  • The maximum file size we can upload is 2 GB.
  • Guest users can't add files to Communities
Note:
1. This component is not supported in Lightning Out or standalone apps.
2. we can't upload files with the following file extensions: .htm, .html, .htt, .htx, .mhtm, .mhtml, .shtm, .shtml, .acgi, .svg
File Uploder Example
FileuploaderComponent
<aura:component implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction" access="global" >
    
    <lightning:notificationsLibrary aura:id="notifLib"/>
    <div class="slds-theme_default">
        <lightning:fileUpload title="Upload Files"
                              name="fileuploader"
                              label="Upload Files"
                              recordId="{!v.recordId}"
                              multiple="true"
                              accept=".pdf,.png,.jpg"
                              onuploadfinished="{!c.afterFinish}"/>
    </div>
    
</aura:component>
FileUploaderComponentController.js
({
    afterFinish : function(component, event, helper) {
        //  Geting the list of uploaded files
        var uploadFiles = event.getParam("files");
        
        var strFileNames = '';
        
        // getting uploaded file names
        for(var i=0; i<uploadFiles.length; i++) {
            strFileNames += uploadFiles[i].name + ', ';
        }
        
        // Showing Success message
        component.find("notifLib").showToast({
            "variant": "success",
            "title": strFileNames,
            "message": uploadFiles.length + " Files are Uploaded Successfully!"
        });
        $A.get("e.force:refreshView").fire();
    }
})
Demo

Let us Know if you have any queries
Happy Learning!!

Saturday, December 8, 2018

How to add Recycle Bin tab in Lightning Experience?

This post explains how to add recycle bin tab in Lightning Experience

Currently, Recycle bin page not available in Lighting Experience, to overcome this we can directly access recycle page using web tabs, this is a small workaround
Note: we are directly accessing classic UI recycle page so we can't except the lightning look and feel to the page.

Demo:
Path
Go to setup ---> Tabs ----> Click new under web tabs
1st Page


2nd Page

Click Next
3rd Page


Click Next
Under “Button or Link URL” section, enter below URL
/search/UndeletePage

Click Next ----> Assign to desired profiles ----> Click Save
That's it.
Let us Know if you have any queries
Happy Learning


Monday, December 3, 2018

Show Modal box using lightning:overlayLibrary in Lightning component

This Post explains the how to show modal box using lightning:overlayLibrary

What is Modal?
1. Modal blocks everything else on the page until it’s dismissed.
2. Modal is triggered by user interaction, which can be a click of a button or link.
3. The modal header, body, and footer are customizable. Pressing the Escape key or clicking the close button closes the modal.

Demo:
OverlayLibrarydemoComponent
<aura:component implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction" access="global" >
    <aura:attribute name="strRecId" type="String" />
    <lightning:overlayLibrary aura:id="overlayLibDemo"/>
    <div class="slds-theme_default">
        <p>
            <h1>Lightning OverlayLibrary Example</h1>
            <lightning:button variant="brand" label="Account Edit" title="Account Edit" onclick="{!c.showModal}" />
        </p>
    </div>
</aura:component>

OverlayLibrarydemoComponentController
({
 showModal : function(component, event, helper) {
  helper.showModalHelper(component, event, helper);
 }
})

OverlayLibrarydemoComponentHelper
({
    showModalHelper : function(component, event, helper) {
        var strAccId = component.get("v.recordId");
        console.log('Account Id ====>'+strAccId);
        $A.createComponent("c:AccountEditComponent", 
                           {strRecordId : strAccId},
                           function(result, status) {
                               if (status === "SUCCESS") {
                                   component.find('overlayLibDemo').showCustomModal({
                                       header: "Account Edit Form",
                                       body: result, 
                                       showCloseButton: true,
                                       cssClass: "mymodal", 
                                   })
                               }                               
                           });
    }
})

OverlayLibrarydemoComponent.css
.THIS {
    text-align: center;
    vertical-align: middle;
    line-height: 90px;  
    font-size: 20Px;
}

below component shows in the modal box  when clicking the button
AccountEditComponent
<aura:component implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction" access="global" >
    <aura:attribute name="strRecordId" type="String" />
    <lightning:overlayLibrary aura:id="overlayLibDemo1"/>
    <lightning:notificationsLibrary aura:id="notifLib"/>
    <div class="slds-theme_default">
        <lightning:recordEditForm aura:id="editform"
                                  onsubmit="{!c.handleSubmit}"
                                  onsuccess="{!c.handleSuccess}"
                                  recordId="{!v.strRecordId}"
                                  objectApiName="Account">
            <lightning:messages />
            
            <lightning:inputField fieldName="Name" aura:id="accName" />
            <lightning:inputField fieldName="Industry" />
            <lightning:inputField fieldName="Phone" />          
            <lightning:inputField fieldName="Type" />
            <div class="slds-m-top_medium">
                <lightning:button variant="brand" type="submit" name="save" label="Save" />
            </div>
        </lightning:recordEditForm>
    </div>
</aura:component>
AccountEditComponentController
({
    handleSubmit : function(component, event, helper) {
        component.find('editform').submit();
    },
    
    handleSuccess : function(component, event, helper) {
        var strAccName = component.find("accName").get("v.value");
        component.find('notifLib').showToast({
            "variant": "success",
            "title": strAccName,
            "message": "Account Updated Successfully!!"
        });
        component.find("overlayLibDemo1").notifyClose();
    },
})

Let us Know if you have any queries
Happy Learning!!

Monday, November 19, 2018

How to get Salesforce Object key prefix

if we look at the Salesforce record Id, we can observe
001G000001umxxX
001 ----------->  Object ID Prefix
G0 ------------>  Server-Id
00001umxxX -------->  Identifier

If you want to get any Salesforce object key prefix use below code
String strObjPrefix = Account.sObjecttype.getDescribe().getKeyPrefix();
System.debug('OBJ prefix ====> '+strObjPrefix);
Let us know if you any queries
Happy Learning!!!

Saturday, November 17, 2018

SOQL(Salesforce Object Query Language) is not SQL

Salesforce SOQL is not working same as SQL, Why?
  1. Salesforce using Multitenant Architecture – Many organization using single instance including database but each org will have their own virtual hardware.
  2. Salesforce using Force.com platform – It is metadata-driven architecture.
  3. SOQL directly integrated with Apex no need to establish the connection to the database.
Force.com platform having the governor limits to allow the access Multitenant Architecture
Differences between SOQL and SQL
SOQL
  • It supports only SELECT statements.
  • we can not include all columns at a time(Does not support SELECT * (must specify fields to include).
  • It supports only “relationship queries,” which are written using parent-child syntax 
  • It supports the dot notation syntax to traverse table relationships.
  • It is governed by LIMITS(e.g., returned rows, heap, etc.)
SQL
  • It Supports statements for DML, transaction control, and SELECT statements.
  • It Support SELECT * (include all columns) 
  • It Support joins, which are written using “left,” “right,” "inner," "outer" syntax.
  • It does not support dot notation syntax to traverse table relationships.
  • No governer Limits.
Let us know if you have any queries.
Happy Learning!!!

Tuesday, October 30, 2018

lightning:notificationsLibrary in lightning

This post explains the use of lightning:notificationLibrary in lightning component
lightning:notificationLibrary is supported in Lightning Experience, Salesforce app, and Lightning communities.
include one <lightning:notificationsLibrary aura:id=”notifLib”/> tag in the component that triggers all the notifications, and aura:id is a unique local id in the component.



Messages can be displayed in notices and toasts.
Notices
  1.  Notices alert users to system-related issues and updates.
  2. Notices interrupt the user's workflow and block everything else on the page. Notices must be acknowledged before a user regains control over the app again.
  3. To dismiss the notice, only the OK button is currently supported.

Toasts
  1. Toasts enable you to provide feedback and serve as a confirmation mechanism after the user takes an action.
  2. Toasts are less intrusive than notices and are suitable for providing feedback to a user following an action, such as after a record is created. 
  3. A toast can be dismissed or can remain visible until a predefined duration has elapsed.

Demo
To create and display a notice, pass in the notice attributes using component.find('notifLib').showNotice(), where notifLib matches the aura:id on the lightning:notificationsLibrary instance.

To create and display a toast, pass in the toast attributes using component.find('notifLib').showToast(), where notifLib matches the aura:id on the lightning:notificationsLibrary instance.

Check below code sample for more information
Lightning Component
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction" access="global" >
    <lightning:notificationsLibrary aura:id="notifLib"/>
    <lightning:buttonGroup>
        <lightning:button variant="Neutral" label="Notice Info" onclick="{!c.showNoticeInfo}"/>
        <lightning:button variant="Neutral" label="Notice Error" onclick="{!c.showNoticeError}"/>
        <lightning:button variant="Neutral" label="Notice Warning" onclick="{!c.showNoticeWarning}"/>
        <lightning:button variant="Neutral" label="Toast Info" onclick="{!c.showToastInfo}"/>
        <lightning:button variant="Neutral" label="Toast Warning" onclick="{!c.showToastWarning}"/>
        <lightning:button variant="Neutral" label="Toast Success" onclick="{!c.showToastSuccess}"/>
        <lightning:button variant="Neutral" label="Toast Error" onclick="{!c.showToastError}"/>
    </lightning:buttonGroup>
</aura:component>
Javascript Controller
({
    showNoticeInfo : function(component, event, helper) {
        component.find('notifLib').showNotice({
            "variant": "info",
            "header": "Something has gone wrong!",
            "message": "Unfortunately, there was a problem updating the record.",
        });
    },
    
    showNoticeError : function(component, event, helper) {
        component.find('notifLib').showNotice({
            "variant": "error",
            "header": "Something has gone wrong!",
            "message": "Unfortunately, there was a problem updating the record.",
        });
    },
    
    showNoticeWarning : function(component, event, helper) {
        component.find('notifLib').showNotice({
            "variant": "warning",
            "header": "Something has gone wrong!",
            "message": "Unfortunately, there was a problem updating the record.",
        });
    },
    
    showToastInfo : function(component, event, helper) {
        component.find('notifLib').showToast({
            "variant": "info",
            "title": "Notif library Info!",
            "message": "The record has been updated successfully."
        });
    },
    
    showToastWarning : function(component, event, helper) {
        component.find('notifLib').showToast({
            "variant": "warning",
            "title": "Notif library Warning!",
            "message": "The record has been updated successfully."
        });
    },
    
    showToastSuccess : function(component, event, helper) {
        
        component.find('notifLib').showToast({
            "variant": "success",
            "title": "Notif library Success!",
            "message": "The record has been updated successfully."
        });
    },
    
    showToastError : function(component, event, helper) {
        component.find('notifLib').showToast({
            "variant": "error",
            "title": "Notif library Error!",
            "message": "The record has been updated successfully."
        });
    },
})
Let us know if you have any queries.
Happy Learning!!!

Thursday, October 25, 2018

Checking UI Theme Detection in Visualforce and Apex

UI Theme Detection can be done in one of two ways:

Accessing global variables:
$User.UITheme – Returns the theme that is supposed to be used.
$User.UIThemeDisplayed – Returns the theme that is actually being used.

Calling Apex utility methods:
UserInfo.UITheme() – Returns the theme that is supposed to be used
UserInfo.UIThemeDisplayed() – Returns the theme that is actually being used

Currently, Salesforce supports below themes
Theme1—Obsolete Salesforce theme
Theme2—Salesforce Classic 2005 user interface theme
Theme3—Salesforce Classic 2010 user interface theme
Theme4d—Modern “Lightning Experience” Salesforce theme
Theme4t—Salesforce mobile app theme
Theme4u—Lightning Console theme
PortalDefault—Salesforce Customer Portal theme
Webstore—Salesforce AppExchange theme

UI theme detection using global variables
check below sample code

<apex:page>
    <apex:pageBlock title="My Content" rendered="{!$User.UITheme == 'Theme2'}">
        // this is the old theme...
    </apex:pageBlock>

    <apex:pageBlock title="My Content" rendered="{!$User.UITheme == 'Theme3'}">
       // this is the classic theme ...
    </apex:pageBlock>
</apex:page>

UI theme detection Using Apex Utility Methods
Check below sample code

public with sharing class UIThemeController {
   @AuraEnabled
    public static String getUIThemeDescription() {
        String theme = UserInfo.getUiThemeDisplayed();
        return theme;
    }
}

Use the UI theme detection based on your requirement.
Let us know if you have any queries.
Happy Learning!!!

Wednesday, October 3, 2018

How to get governor limits of current org using REST API Callout

This Post explains the how to get the governor limits of current org using REST API Callout.

Some Cases we need to check the Max limit value and remaining limits values of current org in the apex.
For Example
Single Email Limit Values, Max limit value of Single Emails of Current org(Based on Licences it will depend) and How many are already invoked in a day.
Check below link to get limits by using the workbench
https://www.salesforcecodecrack.com/2018/09/how-to-check-your-org-governor-limits.html

if you need to check limits in Apex code, this post may help for you

Note: 
your salesforce instance URL must be added in your org remote site settings.

Check below class
/*
purpose: This Class gives response based on resource name you entered.
Author: Shaik Nagajani
Date: 10/3/2018
*/

public class OrgREST {
    
    public static String retriveResult(String strResourceName) {
        String response;
        String strEndPonitURL = URL.getSalesforceBaseUrl().toExternalForm() + '/services/data/v43.0/' + strResourceName;
        if(String.isNotBlank(strResourceName)) {
            HttpRequest httpRequest = new HttpRequest();  
            httpRequest.setMethod('GET');   
            httpRequest.setHeader('Authorization', 'OAuth ' + UserInfo.getSessionId());        
            httpRequest.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID()); 
            httpRequest.setEndpoint(strEndPonitURL); 
            
            try {  
                Http http = new Http();   
                HttpResponse httpResponse = http.send(httpRequest);  
                if (httpResponse.getStatusCode() == 200 ) {  
                    response = httpResponse.getBody();  
                } 
                else {  
                    throw new CalloutException(httpResponse.getBody());  
                }   
            } 
            catch(Exception ex) {  
                throw ex;  
            }  
        } 
        return response;
    }
}
Open Developer Console, Execute below code from the anonymous window
String response = OrgREST.retriveResult('limits');
above class returns the response,
the response looks like(the small part of response) below.

"HourlyODataCallout" : {
    "Max" : 1000,
    "Remaining" : 1000
  },
  "HourlySyncReportRuns" : {
    "Max" : 500,
    "Remaining" : 500
  },
  "HourlyTimeBasedWorkflow" : {
    "Max" : 50,
    "Remaining" : 50
  },
  "MassEmail" : {
    "Max" : 10,
    "Remaining" : 10
  },
  "Package2VersionCreates" : {
    "Max" : 50,
    "Remaining" : 50
  },
  "PermissionSets" : {
    "Max" : 1500,
    "Remaining" : 1497,
    "CreateCustom" : {
      "Max" : 1000,
      "Remaining" : 997
    }
  },
  "SingleEmail" : {
    "Max" : 15,
    "Remaining" : 15
  },

Go to developer console, open execute anonymous window, copy below code and past in anonymous window
Integer iMax = 0;
Integer iRemaining = 0;
// Sending Request to the Server
String response = OrgREST.retriveResult('limits');

// deserializing the response
map<String, Object> mapJsonData = (map<String, Object>)JSON.deserializeUntyped(response);

// getting single Email max limit value and Remaining limit value 
map<String, Object> mapLimitValues = (map<String, Object>)mapJsonData.get('SingleEmail');
iMax = (Integer)mapLimitValues.get('Max');
iRemaining = (Integer)mapLimitValues.get('Remaining');

System.debug('Single Email Max Limit Vlaue====> '+iMax);
System.debug('Single Email Remaining Limit Vlaue====> '+iRemaining);

map<String, Object> mapLimitValues1 = (map<String, Object>)mapJsonData.get('DailyWorkflowEmails');
iMax = (Integer)mapLimitValues1.get('Max');
iRemaining = (Integer)mapLimitValues1.get('Remaining');

System.debug('DailyWorkflowEmails Max Limit Vlaue====> '+iMax);
System.debug('DailyWorkflowEmails Remaining Limit Vlaue====> '+iRemaining);
from above code, I checked single Email Max Limit, Remaining Limit Value and DailyworkfowsEmails invocation limit values.
Check below screenshot for more information about the result.

Output:

Based on Your Requirement, get the max limit and remaining limit values.
Let us Know if you have any queries.
Happy Learning!!!