Sunday, 30 June 2019

Composite calls in REST API

OAUTH Flow :
===========
1. web server flow

1.Client app directs user to Salesforce authorization endpoint.
2. User logs into Salesforce page with their credentials
3. If successful login user routed to callback URL with
authorization code.
4.Client app sends authorization code to Salesforce for access token.
5.Salesforce returns an access token, refresh token, and instance URL.
6.Application uses the access token to access salesforce.

2. User - agent flow

1.client app directs user to salesforce authorization endpoint.
2. User logs into salesforce page with their credentials.
3. If successful login, user routed to callback URL with access token more.
4. Application uses the access token to access salesforce data.

3. User -password Flow

1. Client app requests token using username and password.
2. Salesforce verifies credentials and returns access token and instance url.
3. Application uses the access token to access salesforce data.

call back url :
================
it would route that authenticated user back to with either the authorization code or
event the token back in the mesage.

client-side caching :
======================
if- match header
if-None-Match headers
Requires use of an Etag(s)

if-Modified
if-Unmodified
works against individual records.

omposite calls :
================

By using composite resources we can make multiple request
in single REST API call.

1.Composite

Executes a series of REST API requests in a single call.
you can use the output of one request as the input to a
subsequent request.

/services/data/v45.0/composite


ex :


"compositeRequest":[ 
  { 
"method":"POST",
"url":"/services/data/v41.0/sobjects/Account",
"referenceId":"refAccount",
"body":{ 
"Name":"Walt Disney Account",
"BillingStreet" : "Walt Disney World Resort",
                "BillingCity" : "Orlando",
                "BillingState" : "Florida"
}
  },
  { 
"method":"POST",
"url":"/services/data/v38.0/sobjects/Contact",
"referenceId":"refAccountContact",
"body":{ 
"AccountId":"@{refAccount.id}",
"FirstName" : "Walt",
                "LastName" : "Disney"
}
  }
]
}

2. Batching Rest Resources.

Execute a set of subrequests in a single request.
Subrequests are executed independently and information
can't be passed between subrequest calls.

a. A single Batch REST request can execute upto 25 sub-requests.
b. Sub-requests contains the resource (URI) and the method to execute.
c. Each sub-request is an unrelated API call.
d. Sub-requests are executed serially, in order,and as the running user.
e.As each sub-request completes, the call is committed.
f. haltOnError - is optional parameter
   Indicates if the batch should stop on any error that is encountered.
 

   ex : post
   /services/data/v45.0/composite/batch
 
 {"batchRequests": haltonerror:true, [
  {
   "method":"GET",
   "url":"v45.0/sobjects/account/0010K0000221VRSQA2" 
  },
 {
   "method":"GET",
   "url":"v45.0/sobjects/contact/0030K00001p6tf9QAA" 
  },
  {
  "method":"GET",
  "url":"v45.0/sobjects/account/0010K0000221Va0QAE?fields=Name,BillingPostalCode"}
]}

2. TreeSave REST Resource

Creates one or more sObject trees with root records of the
specified type. A Sobject tree is a collection of nested,
parent-child records with a single root record.

a. only insert is supported
b. All records are rolled back on any error.
c. upto to a total of 200 records across all trees.
d. up to five records of different Types.
e. SObject trees up to five levels deep.

ex :

/services/data/v45.0/composite/tree/Account

   {"records":[
  {
   "attributes":{"type":"Account","referenceId":"ref1"},
   "Name":"NewTree1" 
  },
 {
    "attributes":{"type":"Account","referenceId":"ref2"},
   "Name":"NewTree2" 
  },
  {
  "attributes":{"type":"Account","referenceId":"ref3"},
   "Name":"NewTree3"
 }
]}

ex :

/services/data/v45.0/composite/tree/Account

{
"records" : [
                {
                    "attributes" : {
                        "type" : "Account",
                        "referenceId" : "DisneyAccount"
                    },
                 
                    "Name" : "Walt Disney World Resort",
                    "BillingStreet" : "Walt Disney World Resort",
                    "BillingCity" : "Orlando",
                    "BillingState" : "Florida",                   
                    "Contacts" : {
                        "records" : [
                            {
                                "attributes" : {
                                    "type" : "Contact",
                                    "referenceId" : "WaltDisneyContact"
                                },                               
                                "FirstName" : "Walt",
                                "LastName" : "Disney"
                            },
                            {
                                "attributes" : {
                                    "type" : "Contact",
                                    "referenceId" : "RoyDisneyContact"
                                },                               
                                "FirstName" : "Roy",
                                "LastName" : "Disney"
                            }
                        ]
                    }                   
                }
            ]
}

Sunday, 23 June 2019

Integration APIs in salesforce


why use force.com api?

To connect things and automate things so that it can be more productive with salesforce platform.

1.Connect stuff

Build systems that span applications,cloud and on-premises.

2.Automate stuff

Reduce manual effort and establish consistent operations.


Force Integration Patterns :
==============================
we have Four Integration patterns


1.RPC (Remote procedure call) - Request and Reply

salesforce is invoking a process on the remote system and waiting for the response.

2.RPC (Remote procedure call) - Fire and Forget

salesforce is invoking something in the remote system, but it's doesn't wait for the response.it's asynchronous.

3.Batch Data sync

pulling data into salesforce or pushing data out with bulk data on a schedule or a regular rhythm.

4.Remote call In

external systems calling into salesforce to grab data, create records, update records and delete records.

Request and Reply :
===================
1.Synchronous call to remote system.
2.Initiated by event or batch (Apex triggers and Apex batch classes)
3.Require idempotency and duplicate check

It's important to ensure that the remote procedure being called is idempotent,otherwise repeatedly calling the same message can have
different results and can result in data integrity issues.Also, duplicates before inserting must be checked if an operation create records on the external system.


ex :

   GET,PUT,DELETE (Idempotent)
   POST (Non-idempotent)

4.Careful security.

Any call to a remote system must maintain the confidentiality,integrity and availability of the request.

1.Two-way SSL can be used to maintain authenticity of both the client and server.
2.Consider using digital signatures using the Apex Crypto class methods to ensure request integrity.
3.Appropriate firewall mechanisms should always be implemented to protect the external system.


Fire and Forget :
=================
1.Asynchronous call to remote system.

salesforce doesn't wait for the completion of the process.

 ex : Outbound messaging through workflow.

2.Initiated by user or system event.

Apex triggers and apex batches

Note : In Fire and Forget, I am sending a message off and maybe it got there,maybe it didn't .I don't know for sure that it reached it because I'm(salesforce) not
waiting to get that acknowledgment in the same way.

3.Security considerations

Two-way SSL can be used together with the salesforce outbound messaging certificate though,one-way SSL is enabled by default.

Whitelist Salesforce server IP ranges for remote integration servers.

c.Appropriate firewall mechanisms should be implemented to protect the remote system.

Batch Data synchronization :
============================
1.Import and export large amount a of data.
2.Initial or ongoing load
3.optimize refresh schedule.
4.Consider post processing
5.Avoid contention

Remote call -in :
=================
1.External system interacts with salesforce.
2.Consider source system characteristics.
3.choices based on data volume.


Force.com's Integration-Related services:
=========================================
REST API
SOAP API
Lightning Connect
Data Loader
Bulk API
Platform Cache
External Objects
Streaming API
Outbound Messaging
Apex Callouts


SOAP API :
========
SOAP protocol access to salesforce data and functionality.
Using the Force.com SOAP API to Integrate with Enterprise APPS.

you're posting to one endpoint whether you're getting data or putting data or retrieving or updating,deleting,you're always posting.

When do you Use it ?

when i want to point my code language or code tools to a particular WSDL and generated some strongly typed objects that know how to talk with that , that is convenient,and it can be convenient to enterprise to enterprise apps that want to work with it or for developers who don't want to deal with
raw HTTP messages.

when i want to access the most functions, whether it's accessing things around users or around objects or around metadata.


1.SOAP API is enterprise friendly.
2.Broad coverage of UI capabilities.

  you are not just dealing with objects, but dealing with resetting passwords or sending emails or   doing all kinds of other things in salesforce,you have    a lot of functionality in the SOAP API.

3.multiple WSDL interfaces
  a. Enterprise WSDL
  b. Partner WSDL
4.xml-based


Note :
serverUrl,sessionId

these two are important for subsequent requests.

SOAP API WSDL :
==============
1. Enterprise WSDL
2. Partner WSDL

Enterprise WSDL :
================
1.strongly typed .

Note : so every built in standard or custom object gets represented in that WSDL, even any custom
sort of operation,things like that,that WSDL is meant to be a representation of your organization,your account.

2.Easy to use

just reference that WSDL,generate some code,call it.

3. standard,custom objects

 standard and custom objects shows up in that WSDL.

4.Best for single org solutions

Partner WSDL :
=============
1. weakly typed

you're dealing with the raw sobject,which is really the underlaying type of every object,and so you're dealing with it as an sobject type.

2.Flexible to use

3.describeSobject() for details

you can call that describe API to actually find out what objects are in there,and then be using this weakly typed things

4.Best for apps targeting multiple orgs.


Server URL's for the various APIs :
===================================
1.Enterprise API
https://server-api.salesforce.com/services/Soap/c/45.0/orgId

2.Partner API
https://server-api.salesforce.com/services/Soap/u/45.0/orgId

3.Metadata API

https://server-api.salesforce.com/services/Soap/m/45.0/orgId

4. Apex API

https://server-api.salesforce.com/services/Soap/s/45.0

5. Tooling API

https://server-api.salesforce.com/services/Soap/T/45.0/orgId


what are SOAP Objects ?

1.Objects represent database tables.
2.Records are like database rows
3.Multiple types of objects.
  a. standard objects
  b. custom objects
  c. external objects

Data types :
=============
1.Primitive types
2.Field types
3.Compound fields
4.system fields
5.Required fields
6. field properties


Compound fields :
================
A set of fields that represent one thing. The compound field itself is readonly.

relationships :
==================
Master-detail (1:n)
Many to many
Lookup ( 1: n)

Types of SOAP API Calls :
==============================
1.core calls

core calls dealing with sobjects really,create ,delete ,get deleted, where you can pull everything that's been deleted from a preset time ,get all the updated things ,invalidate the sessions,
log in,log out , merge records, query records, query all the records ,which include things like that have been deleted , retrieve things based on an individual ID, search, update ,upsert.

2.Describe calls

describe all the tabs, describe the app menu , describe all the quick actions avaialable, describe global, all the objects in my org or describe the layout , which gives me all the page layouts for a particular object,describe an sobject.

so these are things that are almost metadata driven ,they're telling me about that user's experience, they're telling me about my org, they're telling me about my objects.

3.Utility calls

These are things the API or your client can call to obtain system timestamps, user information, change user passwords, send emails, all those sorts of things.

ex :
<urn:query>
<urn:queryString> SELECT Id,Name from Account</urn:queryString>
</urn:query>

utility call to get server time stamp put the below tag in body and sent to salesforce you will get server time stamp.

ex : <urn:getServerTimestamp/>

Handling faults :
=================
API Fault Element with Exception Code.

when you get faults back from salesforce , from the soap api, you get back a fault element with an exception code.so you get back an actual element in the SOAP payload, you're not getting back an HTTP error,you're actually getting back a fault within the message itself.

ex :

<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Body>
    <soapenv:Fault>
      <faultcode>soapenv:Client</faultcode>
      <faultstring>Element {urn:partner.soap.sforce.com}convertedStatus invalid at this location</faultstring>
    </soapenv:Fault>
  </soapenv:Body>
</soapenv:Envelope>



The soap fault element must appear as a body entry and must not appear more than once within a body element.

Error with Status code

Resolution Handled Client Side


Mru(most recent update) Header API call :
=============================
SOAP Header called mruUpdate is used to update most recent update record in the Recent Item Section.By default false.

If you want to see the recent record in the recent item section then you need to sent that flag to TRUE.

<urn:MruHeader>
<urn:updateMru> true</urn:updateMru>
</urn:MruHeader>

if you want to import bulk of records through SOAP and i don't want to just pollute that feed lot of information

Custom SOAP Service :
=======================

ex :

global class SoapVoterService{

webService static Voter__c getVoter(String voterId){

Voter__c voter = [SELECT ID,Name FROM Voter__c WHERE ID = : voterId];
 return voter;

 }

}


invoke service :

https:na30.salesforce.com/services/Soap/class/SoapVoterService

API Limits :
=============
1.you can have 10 concurrent queries per user, so you can have 10 query cursors open
at the same time.

2.you can have 25 concurrent calls in a production org of 20 seconds or longer,
so 5 in a dev edition,25 in a production and sandbox account.

3.you can do a 1 million daily API calls in a production organization.

4. 200 maximum records in a create or update request,keeping that in mind and even a 50 MB maximum request size.

Monitoring API Usage :
================
There are 3 way you can analysis the API Usage

    1. Last 24 hours usage
    2. Notification for API Usage
    3. API Usage Report
Notification for API usage is push notification when i am getting close to LIMIT .

API Usage Report :
==============
Copy and append “/00O?rt=104” URL with your domain URL then you will see the “API Calls Made Within Last 7 Days” report.


REST API :
=========

The REST API is simple access to salesforce data and functionality
via RESTful endpoint.

REST where you're hitting different endpoints for different
resources.

Note :
1.Mobile,web friendly
2.Supports composite operations.
3.Standard interface
4. xml and json supported


Salesforce does use the OAuth protocol to allow users of these diferent apps
to securely access that data without having to give up their username
and password.

To authenticate the OAuth you have to create this connected app that defines
your application's OAuth's settings for your specific Salesforce org.

1.OAuth 2.0 User Agent Flow
These apps often use a scripting language,such as javascript,running within the browser.
This flow uses the OAuth 2.0 implicit grant type.

2.OAuth 2.0 Web Server Authentication Flow
  server must be able to protect the client secret.
 This flow uses an OAuth 2.0 authorization code grant type.

3.OAuth 2.0 JWT Bearer Token Flow
  The main use case of the JWT Bearer Token Flow
is server-to-server API integration.This flow uses
a certificate to sign the JWT request and doesn't
require explicit user interaction.

4.OAuth 2.0 SAML Bearer Assertion Flow
An app can also reuse an existing authorization by
supplying a signed SAML 2.0 assertion.

5.SAML Assertion Flow
This flow is an alternative for orgs that are using
SAML to access Salesforce and want to access the web services API in the same way.
6.OAuth 2.0 username and Password Flow
Use it only for testing, when a user is not present
at app startup.In these cases, set user permissions to minimize
access and protect stored credentials from unauthorized access.
7.OAuth 2.0 Refresh Token Flow
8.OAuth 2.0 Device Authentication Flow
 Command-line apps or applications that run on devices with limited
input and display capabilities such as TVs,appliance and other IOT devices,
can use this flow.

9.OAuth 2.0 Asset Token Flow
This flow combines issuing and registering asset tokens for efficient token
exchange and automatic linking of devices to service cloud asset data.
Web Server Flow :
===================

1.Client app directs user to salesforce authorization endpoint.
2.User logs into salesforce page with their credentials.
3.If successful login,user routed to callback URL with authorization code.
4.Client app sends authorization for access token.
5.Salesforce returns an access token, refresh token , and instance URL.
6.Application uses the access token to access salesforce data.

User-agent Flow :
=================
1.Client app directs user to salesforce authorization endpoint.
2.User logs into salesforce page with their credentials.
3.If successful login, user routed to callback URL with access token,more.
4.Application uses the access token to access Salesforce data.

Username - Password Flow :
==========================

1. Client app requests token using username and password.
2. Salesforce verifies credentials and
returns access token and insatnce URL.
3.Application uses the access token to
access Salesforce data.



ex :
create connected App

Consumer Key
Consumer Secret

Call back URL :
Depending on which OAuth flow you use. Callback URL
is typically the URL that a user's browser is redirected
to after successful authentication.

https://login.salesforce.com/services/oauth2/token

grant_type
client_id
client_secret
username
password

you will get back these payloads

access_token
instance_url
id
token_type
issued_at
signature


Types of REST API Calls via Standard Interface

core calls
Describe calls
Utility calls

The idea of core calls, getting sobject rows,
creating and updating records,querying,processing
rules and approvals,searching,composite operations,
all those things are kind of core calls working
with the core objects within salesforce.

Describe calls :
================
i can describe an sobject.
i can describe global, which gives me back all objects.
i can get layouts or tabs or themes.

switching between xml and json :
==================================
Append .xml or .json to the URI

For more complex , i could choose to
use the accept header,to get either text xml
or text json.


Three types of composite calls

1.batch up a set of operations.
2.create nested records.
3.create a set of unrelated records.

batch query :
============

https://na30.salesforce.com/services/data/v35.0/composite/batch

nested records :
===============

https://na30.salesforce.com/services/data/v35.0/composite/tree/Precinct__c

Custom REST API:
=================

@RestResource(urlMapping='/VotersWithDonation/*')
global class CustomVoterDonationService{

@HttpGet
global static VoterDonation GetVoter()
{
  // get voter Id from request

  RestRequest request = RestContext.Request;
  String voterId = request.requestURI.substring(request.RequestURI.lastIndexOf('/')+1);
  Voter__c voter = [SELECT ID,Name,Political_Party__c FROM Voter__c where ID = : voterId];

  VoterDonation vdon= new VoterDonation();
  vdon.VoterName = voter.Name;
  vdon.VoterParty = voter.Political_Party__c;

  // donation list
  vdon.Donations = [ select Candidate_Name__c,Amount__c,Donation_Date__c FROM Voter_Donation__c Where
   voter__r.ID = : voterId ];

 return vdon;

}

global class VoterDonation{

String VoterName {get;set;}
String VoterParty {get; set;}
List<Voter_Donation__c> Donations {get;set;}

}

}

Bulk API :
============
1.Bulk loading of data.
2.Issue bulk queries
3.Asynchronous processing.

Programmatic access to quickly load into,
and retrieve data from salesforce.

Note :
when do you use it ?

Data synchronization between systems.

one -time data loads

Transferring significant number of records.

Lifecycle of a bulk api interaction :
=====================================

1.create job
2.add batches
3.close job
4.check status
5.retrieve results

Note :
========
Batch processing doesn't wait for closure

Jobs deleted after 7 days,regardless of status.

Batch :
=========
Batch is a set of records sent via an
HTTP POST.

Each Batch is processed independently by the server,
not even necessarily in the order received,you're
not guaranteed it's going to be in a
particular order.

1. A batch can be queued,meaning the process hasn't
actually started yet.
2.A batch can be inprogress,meaning it's processed.
3.if the job is aborted, this batch will still complete.
4.it can be in a completed state , that means that
processing is done.

Bulk API Limits :
===================

1. 10 minutes to process a batch
2. 5,000 Batches per rolling 24 hour period
3. 10,000 Maximum record count per batch
4. 10MB Max size for single CSV or XML file

Outbound messaging for Real-time Push Integration :
===================================================

Outbound Messaging :
===================

React to data changes by triggering
messages to Internet - facing endpoints.

Event-driven messaging
Asynchronous,but reliable delivery
Receiver is Internet - accessible

Note :
=======
1.Triggered by workflow rules based on
field changes.

2.Message reliably sent to endpoint.

3. Listeners implement WSDL

4.Support for callbacks

When do you use it ?
1.Replace polling-based solutions.
2.Create real - time ,responsive cloud systems.
3.Trigger business activities.

Securing Outbound Messaging Solutions :
=======================================

1. SSL/TLS endpoint

2.whitelist Salesforce IP addresses in client listener

3.validate against Salesforce Certificate.

Flow for Creating Outbound Messages :
=====================================
1.Create Outbound Message
2.Choose sObject
3.Set name,endpoint URL
4.Choose fields to send
5. Save Outbound Message
6. Associate with workflow rule.

Tracking Outbound Messages :
===========================
1.View items queued for delivery.
2.Observe any failures
3. Edit or delete items in the queue
4. Manually retry or wait for automatic interval.

Streaming API :
===============


Receive a live stream of data changes
based on an SOQL query that you define.

Event-driven messaging
Asynchronous, but not reliable delivery.
Receiver can be behind the firewalls.

Note :

1. "Topics" based on SOQL queries
2. Client(s) subscribe to "topics"
3. Poll ,not push
4. No guaranteed delivery,ordering.

When do you use it ?

1.Replace custom polling-based solutions.
2.Scale data events to multiple recipients.

Bayeux and CometD :
====================
1.Bayeux is a protocol for async messaging.
2.CometD is event bus, implementing Bayeux.
3. Uses long polling, WebSockets in 3.0.
4. Salesforce uses CometD 2.0

Implements : connect,disconnect,handshake,
subscribe,unsubscribe.

Authenticating Streaming API Users :
====================================
1.can use SOAP session ID
2.can use OAuth token
3.User,object,field security applies

Push Topics :
================
1.Record relates to CometD channel.
2.Notifications generated on record match.
3.Developer controls record match criteria.
4.Can deactivate or delete PushTopics.

5.One entity per query
6.Fields specified make up body of notification.
7.Changes take effect immediately.
8.Support for standard and Custom objects.
9. Basic subset of SOQL available.
Note :
semi-joins,anti-joins,aggregate queries,
count limit,relationships,order by,group by,
compound address are unsupported.

Notification rules :
===================
1.NotifyFor OperationCreate
2.NotifyFor OperationUpdate
3.NotifyFor OperationDelete
4.NotifyFor OperationUndelete
5.NotifyFor Fields
Note :
you have a few different options for what sort
of field should i be looking for, all of them,
referenced fields, select fields, where fields,
that will determine kind of which one
i'am checking to figure out, to trigger these events.

ex :

PushTopic pushTopic = new PushTopic();
pushTopic.Name ='UpdatedDonations';
pushTopic.Query = ' SELECT Id,Name,Amount__c,Donation_Date__c FROM voter_Donation__c';
pushTopic.ApiVersion = 35.0;
pushTopic.NotifyForOperationCreate = false;
pushTopic.NotifyForOperationUpdate = true;
pushTopic.NotifyForOperationUndelete = false;
pushTopic.NotifyForOperationDelete = 'Referenced';
insert pushTopic;

query :
=========
SELECT id,name from PushTopic

List<PushTopic> pts = [SELECT Id FROM PushTopic WHERE Name='UpdateDonations'];
pts[0].NotifyForFields = 'All';
Database.update(pts);


ex :
PushTopic pushTopic = new PushTopic();
pushTopic.Name ='AllDonations';
pushTopic.Query = ' SELECT Id,Name,Amount__c,Donation_Date__c FROM Voter_Donation__c';
pushTopic.ApiVersion = 35.0;
pushTopic.NotifyForOperationCreate = true;
pushTopic.NotifyForOperationUpdate = true;
pushTopic.NotifyForOperationUndelete = true;
pushTopic.NotifyForOperationDelete = true;
pushTopic.NotifyForFields ='Referenced';
insert pushTopic;

Generic Streaming :
===================
1.Send notifications on general events
2. Send events through REST endpoint
3. Can target subset of subscribers.

Streaming Channel : /u/notications/DemoGenericChannel

select Id, Name FROM StreamingChannel;

Streaming API Limits :
======================

1.50 (for enterprise)Topics per organization,up to 100
depending on your account type.

2.The maximum number of client subscribers per topic
is 1000 for enterprise, up to 2000 if you
have the performance or unlimited account.

3. The maximum number of events per day,any sort of
24 hour period, is 2,00,0000 (200k)

4. Maximum generic streaming events per day is
10,000(10k).

Apex Callouts :
=================

Make a call from Apex code to an external
web service and receive a response.

Note :

Aggregate Salesforce and external data

Create VisualForce pages based on data
from other systems.

Doing long-running async queries

Salesforce doesn't allow any DML operation
before a callout in the same transaction.
or

Typically not allowed after DML operations in the same transaction.

Remote Site Settings :
======================

1.Register/authorize external sites.
2.provide name,URL
3.can disable SSl

Named Credentials :
===================
1.Separate code from URL,authentication.
2.Use same code for different environments.
3.Anonymous,Basic or Oauth supported.
4.Use merge fields for custom authentication.

you can use merge fields if you want to do a
custom authentication or authorization scheme.

Long Running callouts in VisualForce :
======================================

1.User perceives faster response
2.Continuation server manages callout requests.
3.Make calls simultaneously,or through chaining.

Callout Limits :
================
20 concurrent callouts within an organization.

10/120 Default seconds for a timeout,maximum seconds for a timeout

100 Maximum callouts in a single transaction.



Monday, 17 June 2019

Aura.Action in Lightning component


Aura.Action :
==============
Use Aura.Action type of attribute if you want to pass the reference of parent lightning component controller.js function to nested/child lightning component .

ex : child Component

<aura:component >
    <aura:attribute name="ltngMessage" type="string"></aura:attribute>
    <aura:attribute name="closeChildDivFunction" type="Aura.Action" default="{! c.defaultCloseAction}"></aura:attribute>
   
    <div aura:id="maincontainer" style="background-color:#E6E6FA;border-style: solid;height:100px;margin:2%;padding:1%;">
        <b>This is Child component inside AuraActionDemoCmp</b>
        <br/>
        <lightning:button label="Close via ChildCmp JS function" variant="neutral"  onclick="{!c.defaultCloseAction}"/>
       
        <lightning:button label="Close via Parent JS function" variant="brand"  onclick="{!v.closeChildDivFunction}"/>
       
    </div>
</aura:component>

defaultCloseAction : function(component, event, helper) {
          debugger;
        //perform you logic and close the modal dialog
        component.set("v.ltngMessage","Close via ChildCmp JS function button clicked.Please refresh your browser if you again want to load this demo component");
        var mc=component.find("maincontainer");
        $A.util.addClass(mc, "slds-hide");
    }

Parent Component :

<aura:component >
   
    <aura:attribute name="ltnguserActionMessage" type="string" default="Waiting for User Action"/>
    <div style="background-color:#e7eff8;border-style: solid;padding:2%;">
        <b> This is Parent(AuraAction Parent) component </b>
        <br/>
        ltnguserActionMessage value-<b>{!v.ltnguserActionMessage}</b>
        <br/>
       
        <div aura:id="childContainer" >
            <p>This content is inside childContainer div</p>
            <ul class="slds-list--ordered">
                <li>If user clicks on "Close via Parent JS function" button,then this content will also get removed</li>
                <li>If user clicks on "Close via ChildCmp JS function" button,then only child component body will be removed</li>
            </ul>
            <c:AuraActionChild ltngMessage="{!v.ltnguserActionMessage}"  closeChildDivFunction="{!c.destroyChildCmp}"/>
        </div>
    </div>
</aura:component>

 destroyChildCmp: function(component, event, helper) {
        debugger;
        component.set("v.ltnguserActionMessage","Close via Parent JS function button clicked. Please refresh your browser if you again want to load this demo component.");
        var cmp = component.find('childContainer');
        cmp.set("v.body",[]);
    }

App :

<aura:application extends="force:slds" >
    <c:AuraActionParent></c:AuraActionParent>
</aura:application>

Note :
======
1.It is discourged to use component.set() with the  Aura.Action attribute types.
2.It is discourged to use $A.enqueueAction() in the child component to enqueue the action passed to the Aura.Action
attribute.

Sunday, 16 June 2019

Eevnts in salesforce lightning

Lightning Events can be classified into 3 types

1.system Events
2.Custom Events
3.Lightning Application Events from Library


System Events in Lightning Framework :
=======================================
System events are fired automatically by lightning framework and during component initialization, rendering or attribute value change etc.

No need to register the event and also no need to fire the event manually.system will do for us.

1. aura:valueInit

This event automatically fired once the component instance successfully created.

or

This event is fired when an app or component is initialized, prior to rendering . Handle this event using the aura:handler tag.

ex :

<aura:handler name="init" value="{!this} action={!c.doInit}"></aura:handler>



2. aura:valueChange

This event automatically fired once the component  attribute value changed.

This event is fired when an attribute value changes.Handle this event using the aura:handler tag.

<aura:handler name="change" value="{!v.items}" action="{!c.handlevalueChange}" />

The valueChange event gives you access to the previous value and the current value.

handleValueChange : function (component, event, helper) {
        alert("old value: " + event.getParam("oldValue"));
        alert("current value: " + event.getParam("value"));
    }

3. aura:valueRender

Indicates that an app or component has been rendered or rerendered.

This event is fired when an app or component is rendered or rerendered. Handle this event using the aura:handler tag.

<aura:handler name="render" value="{!this}" action="{! c.handleValueRender}"></aura:handler>

The render event is fired after the init event,which is fired after component construction but before rendering.

4. aura:valueDestroy

Indicates that a component has been destroyed.

This event is fired when a component is destroyed . handle this event if you need to do custom cleanup when a component is destroyed.

<aura:handler name="destroy" value="{!this}" action="{! c.handleDestroy}" />

The aura:valueDestroy event is triggered when you tap on a different menu item on the salesforce mobile navigation menu, and your component  is destroyed.

5. aura:noaccess


6. aura:locationChange

Indicates that the hash part of the URL has changed.

This event is fired when the hash part of the URL has changed. Handle this event using the aura:handler tag.

<aura:handler event="aura:locationChange" action="{! c.update}" />

update : function (component,event,helper){
      var loc = event.getParam("token");
}

aura:locationChange tracks changes to the hash fragment in the url, it's not useful for tracking navigation with the new URL format.

7. aura:doneRendering
 This event is automatically fired if no more components  need to be rendered or rerendered due to any attribute  value changes. (OR) Indicates that the initial rendering  of the root application has completed.

For example, you want to customize the behavior of your app after it’s finished rendering the first time but not after subsequent rerenderings.     Create an attribute to determine if it’s the first rendering.


 ex :
  <aura:handler event="aura:doneRendering" action="{!c.doneRendering}"/>
  <aura:attribute name="isDoneRendering" type="Boolean" default="false"/>

   doneRendering: function(cmp, event, helper) {
    if(!cmp.get("v.isDoneRendering")){
      cmp.set("v.isDoneRendering", true);
      //do something after component is first rendered
    }
  }
 
  This client-side controller checks that the aura:doneRendering    event has been fired only once.
 
8. aura:donewaiting

This event automatically fired when all server response (apex) complete.
aura:donewaiting indicate that the lightning component is done waiting for server response.

or

The aura:doneWaiting application event is fired for every server response , even for responses from other components in your app.

This event is automatically fired if no more response from the server is expected.

 <aura:handler event="aura:doneWaiting" action="{!c.hideSpinner}"/>
 <ui:spinner aura:id="spinner"/>

 hideSpinner : function (component, event, helper) {
        var spinner = component.find('spinner');
        var evt = spinner.get("e.toggle");
        evt.setParams({ isVisible : false });
        evt.fire();   
    }




9. aura:systemError

This event is automatically fired when an error is encountered during the execution of a server-side action.

ex :

<aura:handler event="aura:systemError" action="{!c.showSystemError}"/>
<aura:attribute name="response" type="Aura.Action"/>
<lightning:button aura:id="trigger" label="Trigger error" onclick="{!c.trigger}"/>

This client-side controller triggers the firing of an error  and handles that error.

trigger: function(cmp, event) {
        // Call an Apex controller that throws an error
        var action = cmp.get("c.throwError");
        action.setCallback(cmp, function(response){
            cmp.set("v.response", response);
        });
        $A.enqueueAction(action);
    },
    showSystemError: function(cmp, event) {
        // Handle system error
    }

10. aura:waiting

The aura:waiting event is deprecated.Execute logic after queueing an action instead of using this event.A component is waiting for a response for an action until the
action's callback is invoked.


<aura:handler event="aura:waiting" action="{!c.showSpinner}"/>
 <ui:spinner aura:id="spinner"/>

showSpinner : function (component, event, helper) {
        var spinner = component.find('spinner');
        var evt = spinner.get("e.toggle");
        evt.setParams({ isVisible : true });
        evt.fire();   
    }

Note : The aura:doneWaiting application event is fired for every server request,
even for requests from other components in your app.



Custom Events :
===============
1.Application Events

Application events follow a traditional publish-subscribe model.An application event is fired from an instance of a component.All components that provide a handler for the event are notified.

sequence of application event propagation  :

1. Event fired - An application event is fired. The component that fires the event is known as the source component.

2.Capture phase - The framework executes the capture phase from the application root to the source component until all components are traversed.Any handling event can stop propagation by calling
stopPropagation() on the event.

3.Bubble phase - The framework executes the bubble phase from the source component to the application root until all components are traversed or stopPropagation() is called.

4.Default phase - The framework executes the default phase from the root node unless preventDefault() was called in the capture  or bubble phases. If the event's propagation wasn't stopped in a previous phase, the root node defaults to the application root.If the event's propagation was stopped in a previous phase, the root node is set to the component whose handler invoked
event.stopPropagation().


Note :
The default application events are handled in a non-deterministic order, which just means we should not rely on the order in which the handlers receive the event.


2.Component Events

The component that fires an event is known as the source component.

Sequence of Component event Propagation :

1.Event fired - A component event is fired.

2.Capture Phase - The framework executes the capture phase from the application root to the source component until all components are traversed.
Any Handling event can stop propagation by calling stopPropagation() on the event.

3.Bubble Phase - The framework executes the bubble phase from the source component to the application root until all components are traversed or stopPropagation() is called.

By default ,component events are handled in the bubble phase , and that's what most developers use.
To handle capture phase, add a phase ="capture" attribute  to your event handler.

ex :

<aura:handler name="cmpEvent" event="c:cmpEvent" action="{! c.handleCmpEvent}" Phase="capture" />

To get the events current propagation phase by calling event.getphase() in your handling function which in-turn will either return capture or bubble.

 handleCmpEvent : function(component, event) {
    var phase = event.getPhase();
 }

 By default , in Lightning component hierarchy only parent  components that create subcomponents (either in their markup   or programmatically ) can handle events which does not include
 container component.

 ex :

 <!-- Owner -->
 <aura:component>
   <c:container>
      <c:eventEmitter></c:eventEmitter>
   </c:container>
 </aura:component>

 If you want a container component to handle a component event,  add an includeFacets="true" attribute to its handler

 <!--c:container component -->
 <aura:component>

  <aura:handler name="cmpEvent" event="c:cmpEvent"
    action="{! c.handleCmpEvent}" includeFacets="true" />
   {! v.body }
 </aura:component>

 You can stop the event at any point by calling   event.stopPropagation() regardless of the current
 propagation phase.

 Lightning Framework also gives us an option to resume  and pause the event which can be a typical use case  for this is asynchronous processing.

 handleEvent:function(component, event, helper){
    event.pause();
    Var action = $component.get(“c.getABeer”);
    action.setcallback(this, function(response){
     if(response.getState() == “SUCCESS”) {
        event.resume();
      }  else if (state === "ERROR") {
       event.stopPropagation();
    }
});
   $A.enqueueAction(action);

}


Note :
1.The event handler and event registration name attribute is name.It should be same to bind the event
registration with event handler.

2. Capture event handler is fired first before bubble event handler. if event.stopPropagation is called from capture event handler then all other event handler including all bubble event handler are cancelled and not executed.


Lightning Application Events  From Library:
===========================================
1. force:closeQuickAction
2. force:createRecord
3. force:editRecord
4. force:navigateToComponent
5. force:navigateToList
6. force:navigateToObjectHome
7. force:navigateToRelatedList
8. force:navigateToSObject
9. force:navigateToURL
10. force:recordSave
11. force:recordSaveSuccess
12. force:refreshView
13. force:showToast
14. lightning:openFiles

Quick Actions/ Lightning Actions :
==================================
create and update records related to existing records.

Quick Action/Lightning Actions is an object-specific action.Object-specific actions let users create records that have  automatic relationships to other records, make updates to specific records.

To display a lightning component as a Quick action to an object, it must be implemented with

force:lightningQuickAction (or)
force:lightningQuickActionWithoutHeader

Note :
1. we cannot add both force:lightningQuickAction and force:lightningQuickActionWithoutHeader action to a single lightning component.
2.we cannot add lighning application as a quick action.

To close action Manually

var dismissActionPanel = $A.get("e.force:closeQuickAction");
dismissActionPanel.fire();

After closing quick action panel refresh the main view

$A.get('e.force:refreshView').fire();


force:createRecord in Salesforce Lightning :
===============================

Opens a page to create a record for the specified entityApiName

ex : Account,MyObject__c

 var createRecordEvent = $A.get('e.force:createRecord');
        if ( createRecordEvent ) {
            createRecordEvent.setParams({
                'entityApiName': 'Account',
                'defaultFieldValues': {
                    'Type' : 'Prospect',
                    'Industry' : 'Apparel',
                    'Rating' : 'Hot'
                }
            });
            createRecordEvent.fire();

force:editRecord in Salesforce Lightning :
==============================

Opens the page to edit the record specified by recordId


 var editRecordEvent = $A.get("e.force:editRecord");
        editRecordEvent.setParams({
             "recordId": component.get("v.recordId")
       });
       editRecordEvent.fire();
    }

force:navigateToComponent in salesforce Lightning :
====================================
Navigates from one Aura component to another.

 var evt = $A.get("e.force:navigateToComponent");
        evt.setParams({
            componentDef : "c:ComponentTwo",
            componentAttributes: {   
                Text : component.get("v.Txt")
            }
        });
        evt.fire();


force:navigateToList in salesforce Lightning :
================================
To navigate to a list view , set the list view ID on the listViewId attribute and fire the event.

@AuraEnabled
public static List<ListView> getListViews() {
    List<ListView> listviews =
        [SELECT Id, Name FROM ListView WHERE SobjectType = 'Contact'];
   
    return listviews;
}

gotoList : function (component, event, helper) {
    var action = component.get("c.getListViews");
    action.setCallback(this, function(response){
        var state = response.getState();
        if (state === "SUCCESS") {
            var listviews = response.getReturnValue();
            var navEvent = $A.get("e.force:navigateToList");
            navEvent.setParams({
                "listViewId": listviews.Id,
                "listViewName": null,
                "scope": "Contact"
            });
            navEvent.fire();
        }
    });
    $A.enqueueAction(action);
}

force:navigateToObjectHome in salesforce Lightning :
=====================================
This event enables you to navigate to the object home specified by the scope attribute.

navHome : function (component, event, helper) {
    var homeEvent = $A.get("e.force:navigateToObjectHome");
    homeEvent.setParams({
        "scope": "myNamespace__myObject__c"
    });
    homeEvent.fire();
}

force:navigateToRelatedList in salesforce Lightning :
====================================
Navigates to the related list specified by parentRecordId.

gotoRelatedList : function (component, event, helper) {
     var relatedListEvent = $A.get("e.force:navigateToRelatedList");
        relatedListEvent.setParams({
            "relatedListId": "Opportunities",
            "parentRecordId": component.get("v.accId")
        });
        relatedListEvent.fire();
}

force:navigateToSObject in salesforce Lightning :
===================================

Use this event to Navigate to an sObject record specified by record Id.

slideDevName : Specifies the slide within the record view to display initially .

Valid Options are :

1.detail : The record detail slide .This is the default value.
2.chatter : The Chatter slide
3.related : The related information slide.

 gotoSObjectdetail : function(component, event, helper) {
 var navEvent = $A.get("e.force:navigateToSObject"); 
        navEvent.setParams({
            "recordId": component.get("v.accId"), 
            "slideDevName": "detail"
        });       
        navEvent.fire();
}

force:navigateToURL in salesforce Lightning :
=================================

Relative and absolute URLs are supported.
Relative URLs are relative to the Salesforce mobile web domain, and retain navigation history. External URLs open in a separate browser window.

ex :

GotoURL : function(component, event, helper) {
        var viewRecordEvent = $A.get("e.force:navigateToURL");
        viewRecordEvent.setParams({
            "url": "/006/o"
        });
        viewRecordEvent.fire();
    },
 GotoGoogle :function(component, event, helper) {
             
        var urlEvent = $A.get("e.force:navigateToURL");
        urlEvent.setParams({
            "url": 'https://www.google.com/maps/place/' + 'Hyderabad, Telangana'
        });
        urlEvent.fire();
    }

force:

force:recordSaveSuccess is used with the force:recordEdit component

1. e.recordSave is used to fire the save event of force:recordEdit.
2. force:recordSaveSuccess event is used with onSaveSuccess after the record is successfully updated. Fired when  record saving was successful.

ex :

<aura:component>
 <aura:attribute name="isErrorOnSave" type="Boolean" default="false" />
 <aura:handler name="onSaveSuccess" event="force:recordSaveSuccess" action="{!c.handleSaveSuccess}"/>
 <aura:handler event="aura:doneWaiting" action="{!c.handleDoneWaiting}"/>

  <aura:attribute name="account" type="Account" />
    <force:recordEdit aura:id="edit" recordId="{!v.account.Id}"/>
    <lightning:button label="Save" onclick="{!c.save}"></lightning:button>
</aura:component>

save  : function(component, event, helper) {
        component.set(“v.isErrorOnSave”, true);
component.find("edit").get("e.recordSave").fire();

},
 handleSaveSuccess : function(component, event, helper) {
   // because there were no errors
   // handle save success
 
   component.set(“v.isErrorOnSave”, false);
 
    var toastEvent = $A.get("e.force:showToast");
        toastEvent.setParams({
            "title": "Success!",
            "message": "The record has been updated successfully."
        });
        toastEvent.fire();
 
   },
handledoneWaiting : function(component, event, helper) {
 // if there were errors during save,
 // the handleSaveSuccess doesn’t get fired
  if(component.get(“v.isErrorOnSave”) === true) {
           var toastEvent = $A.get("e.force:showToast");
        toastEvent.setParams({
            "title": "Error",
            "message": "The record is not saved."
        });
        toastEvent.fire();
    }
  }
 
 lightning:openFiles in salesforce lightning   :
 ===============================
 open the file and preview after file upload


 ex :

  handleUploadFinished : function(component, event, helper) {
        var uploadedFiles = event.getParam("files");
        var documentId = uploadedFiles[0].documentId;
        var fileName = uploadedFiles[0].name;
        var toastEvent = $A.get("e.force:showToast");
        toastEvent.setParams({
            "title": "Success!",
            "message": "File "+fileName+" Uploaded successfully."
        });
        toastEvent.fire();
       
        $A.get('e.lightning:openFiles').fire({
            recordIds: [documentId]
        });
       
    }

Saturday, 8 June 2019

Different Annotations in Apex



Apex supports the following annotations:

1. @Deprecated
2. @Future
3. @IsTest
4. @ReadOnly
5. @RemoteAction
6. @TestVisible

Apex REST annotations:

1. @RestResource(urlMapping='/yourUrl')
2. @HttpDelete
3. @HttpGet
4. @HttpPatch
5. @HttpPost
6. @HttpPut



@ReadOnly annotation :
======================
The @ReadOnly annotation allows you to perform unrestricted queries
against the Force.com database.

All other limits still apply.

it's important to note that this annotation, while removing the
limit of the number of returned rows for a request, blocks you
from performing the following operations within the request :
1.DML operations,
2.call to system.schedule
3.calls to method annotated with @future
4. sending emails.

Note : only webservice, RemoteAction and Schedulable.execute()
methods can be marked readonly.

ex:

public class TestVFPage{
 @RemoteAction
 @readonly
 public static List<Task> getTask(){
   return [select Id from Task];
 }

}

<apex: page controller="TestVFPage">
  <script>
   Visualforce.remoting.Manager.invokeAction( 
   '{!$RemoteAction.TestVFpage.getTask}',
                        function(result){
                            alert('Total Records: '+result.length);
                        }
   );
  </script>
  <div id="totalAccounts" ></div>
</apex:page>


ex 2 :


 global class DuplexScheduler implements Schedulable 
 { 
   public String aggregatorQuery; 
   public String fieldInQuery; 
    global DuplexScheduler() 
    { 
      aggregatorQuery = 'Select Count(Id),Name from teacher__c Group By Name Having Count(Id)>1'; 
      fieldInQuery = 'Name'; 
    } 
   @ReadOnly 
   global void execute (SchedulableContext ctx) 
   { 
   String body = fieldInQuery; 
   for(AggregateResult res : database.query(aggregatorQuery)) 
   { 
     body += '\n'+String.valueOf(res.get(fieldInQuery)); 
   } 
   System.debug('****body'+body); 
   } 
 } 

 Note : To use the @readonly annotation, the top level request
 must be in the schedule execution or the web service invocation .

 For example , if a visualforce page calls a web service that
 contains the @Readonly annotation , the request fails because
 visualforce is the top level request, not the web service.

 @AuraEnabled Annotation :
 =========================
 1.Use @AuraEnabled on Apex class static methods to make them accessible as
 remote controller actions in your Lightning Components.
 2.Use @AuraEnabled on Apex instance methods and properties to make them serializable
 when an instance of the class is returned as data from a server-side
 action.

 ex :
    public class classController {

@auraEnabled
public List<account> lstOfAccount{get;set;}

@AuraEnabled
    public static classController initClass(){
   classController obj = new classController();
       obj.lstOfAccount = [select id,name from account LIMIT 10];

       // return class instance
       return obj ;
     }
}

 @Future Annotation :
 ======================
 Use the future annotation to identify methods that are executed
 asynchronously. When you specify future, the method executes
 when salesforce has available resource.
 ex :

 public class AccountProcessor
{
  @future
  public static void countContacts(Set<id> setId)
  {
      List<Account> lstAccount = [select id,Number_of_Contacts__c , (select id from contacts ) from account where id in :setId ];
      for( Account acc : lstAccount )
      {
          List<Contact> lstCont = acc.contacts ;
         
          acc.Number_of_Contacts__c = lstCont.size();
      }
      update lstAccount;
  }
}

@InvocableMethod Annotation :
===============================
While the Process builder is very flexible out of the box,there
are few business use cases those are not achievable using it.

For example

1. It doesn't support outbound messages.
2. it doesn't support creation of multiple records.
3. It doesn't support us to delete a record.

when no other process action can get the job done, add
customized functionality to your salesforce processes by
calling an Apex method.

To call an APex method , add the Call Apex action to your
process and select an Apex class with an @invocable method
Annotation.

It means they allows us to extend the Process Builder by writing Apex code
that meets certain criteria, and then invoking the Apex from our
Processes.

If the class contains one or more invocable Variables,
manually enter values or reference field values from the related
record.

@InvocableMethod Annotation support bulk operations.



 ex:

 public class DeleteUnacceptedQuotes
 {
  @InvocableMethod
  public static void QuoteDelete(List<Id> oppIds){
    List<Quote> quotes =[select Id from Quote where
                      Opportunity.Id in : oppIds
  and Status !='Accepted'];
delete quotes;  
 
  }

 }

 ex 2 :

public class InvocableSetQ
{
  @InvocableMethod
  public static void SetQ(List<Id> ListID)
  {
    List<Object__c > bidR=[select id , Attribute__c from Object__c where id in :ListID];
    for (Object__c b:bidR )
{
  b.ownerid = c.Queue_ID__c  ;
}
    update bidR;
   
  }
}


@InvocableVariable Annotation :
===============================
To invoke apex from process builder , we have to use annotations
" InvocableMethod" for method and "InvocableVariable" for variable.

ex :

global class InvocableMethodcls {

// An invocable variable used as input or output variables in the process builder

 global class ActionRequest{
  @InvocableVariable(required=true)
  public ID leadId;
  @InvocableVariable
  public string phone;
  @InvocableVariable
  public string email;
  @InvocableVariable
  public Lead leadobj;
  @InvocableVariable
  public string firstName;
  @InvocableVariable
  public string lastName;

 }
 // This invocable method is used for processing the business by taking the input from Process builder

 @InvocableMethod(label='Invoke Business Logic')
 global static void invokeService(List<ActionRequest> requests){
    for(ActionRequest requestObj:requests){
   //Accessing the values from process builder when record is inserted
            System.debug('requestObj.leadId@@:'+requestObj.leadId);
System.debug('requestObj.firstname@@:'+requestObj.firstname);
            System.debug('requestObj.lastname@@:'+requestObj.lastname);     
           
                     
}

// we can write our own business logic here
 }

}

@isTest Annotation :
=====================
Use the @isTest annotation to define classes and methods
that only contains code used for testing your application.

@isTest
private class MyTestClass {

   // Methods for testing
   @isTest static void test1() {
      // Implement test code
   }

   @isTest static void test2() {
      // Implement test code
   }

}

@testSetup Annotation :
=======================
To Set up test Data for an Entire Test class in Salesforce,@testSetupis used.

Note : @testSetup avoids creation of same set of records to be used in
different test methods in the same test class

ex :

@isTest
private class CommonTestSetup {
 /* Method to setup data */
    @testSetup static void setup() {
        /* Create common test Accounts */
        List<Account> testAccts = new List<Account>();
        for(Integer i=0;i<2;i++) {
            testAccts.add(new Account(Name = 'TestAcct'+i));
        }
        insert testAccts;   

   /* Create common test Contacts */
        List<Contact> testContacts = new List<Contact>();
        for(Integer i=0;i<2;i++) {
            testContacts.add(new Contact(FirstName = 'TestAcct'+i, LastName = 'TestAcct'+i));
        }
        insert stName = 'TestAcct'+i; 
    }

    @isTest static void testMethod1() {
        /* Testing class with Accounts and Contacts */
    }

    @isTest static void testMethod2() {
        /* Testing class with Contacts */
 
    }
}

@TestVisible Annotation :
=========================
TestVisible annotation  allows test methods to access private or
protected members of another class outside the test class.
These members include methods , member variables, and inner classes.

ex :

public class TestVisibleExample {
    // Private member variable
    @TestVisible private static Integer recordNumber = 1;

    // Private method
    @TestVisible private static void updateRec() {
    }


@isTest
private class TestVisibleExampleTest {
    @isTest static void test1() {
        // Accessing private variable annotated with TestVisible
        Integer i = TestVisibleExample.recordNumber;
        System.assertEquals(1, i);

        // Accessing private method annotated with TestVisible
        TestVisibleExample.updateRecord();
    }
}

@Deprecated Annotation :
==========================

Use the deprecated annotation to identify methods, classes, exceptions, enums, interfaces, or variables that can no longer be referenced in subsequent releases of the managed package in which they reside.
This is useful when you are refactoring code in managed packages as the requirements evolve. New subscribers cannot see the deprecated elements, while the elements continue to function for existing subscribers and API integrations.

@RemoteAction Annotation :
==========================

Javascript remoting in visualforce provides support for
some methods in Apex controllers to be called via javascript.



ex :

global class sample
{
    public String accountName { get; set; }
    public static Account account { get; set; }
    public sample() { }
   
    @RemoteAction
    global static Account getAccount(String accountName)
    {
        account = [select id, name, phone, type, numberofemployees from Account where name = :accountName ];
        return account;
    }
}

<apex:page controller="sample">
    <script type="text/javascript">
    function getAccountJS()
    {
        var accountNameJS = document.getElementById('accName').value;       
        sample.getAccount( accountNameJS,
        function(result, event)
        {
            if (event.status)
            {
                // demonstrates how to get ID for HTML and Visualforce tags
                document.getElementById("{!$Component.theBlock.thePageBlockSection.theFirstItem.accId}").innerHTML = result.Id;
                document.getElementById("{!$Component.theBlock.thePageBlockSection.theSecondItem.accNam}").innerHTML = result.Name;
            }
            else if (event.type === 'exception')
            {
                document.getElementById("errors-js").innerHTML = event.message;
            } else
            {
                document.getElementById("errors-js").innerHTML = event.message;
            }
        }, {escape:true});
    }
    </script>
    Account Name :<input id="accName" type="text" />
    <button onclick="getAccountJS()">Get Account</button>
    <div id="errors-js"> </div>
    <apex:pageBlock id="theBlock">
        <apex:pageBlockSection id="thePageBlockSection" columns="2">
            <apex:pageBlockSectionItem id="theFirstItem">
                <apex:outputText id="accId"/>
            </apex:pageBlockSectionItem>
            <apex:pageBlockSectionItem id="theSecondItem" >
                <apex:outputText id="accNam" />
            </apex:pageBlockSectionItem>
        </apex:pageBlockSection>
    </apex:pageBlock>
</apex:page>

Note :

1. we can return value to the visualforce page i.e callback.
2. we can call the apex methods fromany apex class.
3. Remote function can submit the form.

@SuppressWarnings Annotation :
===============================
The @SuppressWarnings annotation does nothing in Apex but can be used
to provide information to third party tools.

PMD has way to suppress warnings in Apex.

Note : PMD ( programming Mistake Detector)

Using @SuppressWarnings, which works on any element that is annotateable
(classes,fields,methods etc).

ex :

// This will suppress all the PMD warnings in this class
@SuppressWarnings("PMD")
public class Bar {
    void bar() {
        int foo;
    }
}

@RestResource Annotation :
==========================
The @RestResource annotation is used at the class level
and enables you to expose an Apex class as a REST resource.
@RestResource is at the class level.It is used to expose a
class as rest source.

ex :

Apex REST annotations:

1. @RestResource(urlMapping='/yourUrl')
2. @HttpDelete
3. @HttpGet
4. @HttpPatch
5. @HttpPost
6. @HttpPut

ex :

@RestResource(urlMapping='/Account/*')
global with sharing class sampleRest {
 
    @HttpGet
    global static Account doGet() {
        RestRequest req = RestContext.request;
        String memberId = req.requestURI.substring(req.requestURI.lastIndexOf('/') + 1);
        Account result = [SELECT Id, Name FROM Account WHERE Id = :memberId];
        return result;
    }
 
    @HttpPost
    global static String doPost(String name, String descrp) {
        Account a = new Account(Name = name, Description = descrp);       
        insert a;
        return a.Id;
    }

    @HttpDelete
    global static void doDelete() {
        RestRequest req = RestContext.request;
        String memberId = req.requestURI.substring(req.requestURI.lastIndexOf('/') + 1);
        Account memb = [SELECT Id FROM Account WHERE Id = :memberId];
        delete memb;
    }
   
}

Sunday, 2 June 2019

Salesforce DEV 401

triggers disable in production :
=================================
 we cannot disable triggers in production (triggers are not editable once deployed).

solution 1 :

using Force.com IDE/change Sets,Inactive/disable trigger and deploy to production.

solution 2 :

1. create configuration ( Custom Settings/Custom Metadata Types) to maintain the flag for each trigger execution.
2. Execute the trigger logic based on the above flag selection.

Note : custom settings aren't automatically transferred between sandboxes and production, so make sure you
include them in both places or your code will break.

purpose of Test.startTest() and Test.stopTest() :
=================================================
The code before Test.startTest() and after Test.stopTest() have new set of
Salesforce Governor Limits and code between Test.startTest() and Test.stopTest()
have new set of Salesforce Governor Limits.

ex :
@isTest
public class TestClass{

 @isTest
 static void test(){
 /*
   Declare the variables ,Fetch the required records,create and update
   sample records
 */
   
  Test.startTest();
   /*
     call the controller for code coverage
   */
   Test.stopTest();
   }
}

Exception Handling in Triggers :
===================================
In salesforce you can use addError method over an sObject or over an sObject field.

trigger AccountTrigger on Account (after update){
      for(Account acct : Trigger.new){
     acct.addError('Error added to account on trigger);
}
}

1.DMLException
2.ListException
3.NullPointerException
4.QueryException
5.sObjectException


object - oriented programs :
============================
1.Inheritance : This is the ability to extend an existing class to add a new functionality.
2. Polymorphism : This is the ability to perform different actions by calling the same method.
3. Abstraction : This is the ability to hide complex implementation.
4. Encapsulation : This is the ability to bind data attributes and behavior together.

Note :
======
To use inheritance in Apex, we need to use the "Virtual" or
"abstract" keywords in the base class and methods.


Use Visualforce Page in Lightning experience(LEX):
=======================================

1. use visualforce in Lightning Tab,Page layout, custom action, standard action
2.Styling Visualforce like Lightning <apex lightningStylesheets="true"/>
3.Using Lightning out to bring lightning into visualforce

1.Using App launcher to run a Visualforce page.
2.Adding Visualforce page in Lightning App Builder.
3.Display a visualforce page within a Standard Page Layout
4.Display visualforce page using custom buttons and links
5.Display visualforce page by Overriding Standard buttons or links.

Sandbox Types :
===============
1.Developer sandbox
2.Developer pro sandbox
3.Partial copy sandbox
4.Full Sandbox

Debug logs :
==============

A Trace Flag includes,

1. debug level
2. a start time
3. an end time
4. a log type

log category :
The type of information logged, such as information from Apex or
work flow rules.
log level
Event type

Development Tools :
======================
1.Developer Edition Environment
2.Scratch orgs
3. Salesforce Extension for vs code
4. Salesforce CLI
5.Developer console
6.Ant Migration Tools
7.Salesforce Lightning Inspector
8.Workbench

deployment tools :
=====================
1.Change sets :

Change sets are the simplest way of doing deployments
which uses point and click tool to migrate metadata
instead of using xml files or scripts.it works between
sandbox and production only.

2. Force.com Migration Tool - ANT/Java based :

3.Eclipse with Force.com IDE

4.Salesforce Package

Sandbox Types and Templates :
==============================
Sandbox Template :

Sandbox data templates allow you to pick specific objects
and data to copy to your partial or full sandbox,so you can
control the size and content of each sandbox.Sandbox data templates
are only available for use with partial or full sandbox.

Sandbox Types :
1. Developer
  A developer sandbox includes a copy of your production org's configuration (metadata).

   Refresh Interval : 1 day
   Storage Limit : Data storage : 200 MB,File storage : 200 MB
   what's copied : metadata only
   Sandbox Template : Not available
2. Developer pro
   Refresh Interval : 1 day
   Storage Limit : Data storage : 1 GB,File storage : 1 GB
   what's copied : metadata only
   Sandbox Template : Not available
3. Partial copy
   Refresh Interval : 5 day
   Storage Limit : Data storage : 5 GB,File storage : 5 GB
   what's copied : metadata and Sample data
   Sandbox Template : Required
4. Full copy

   Refresh Interval : 29 day
   Storage Limit : Same as your production org
   what's copied : metadata and all data
   Sandbox Template : available