Sunday, 14 July 2019

single sign on (SSO)


single sign on (SSO)
===================
User just remember one username and password that will allow us to logon to all other different applications.

It's like having a magic key that automatically opens up all the other doors once you enter through one door.

Salesforce provides different options to configure single sign on.

1.Federated Authentication using SAML
2.Delegated Authentication
3.OpenID Connect

Main concepts in SSO

1.The concept of IDP/SP
2.The Concept of IDP Initiated login and SP initiated login.

IDP stands for Indentity provider and SP stands for service provider.

In IDP Init SSO the Federation process is initiated by the IDP sending an SAML Response to the SP.

In SP-Init, the SP generates an AuthRequest that is sent to the IDP as the first step in the Federation process and the IDP then responds with the SAML Response.

IDP initiated Login :
=====================
User can logon to IDP and then from there, clicks on links to access other systems(i.e SP).This is called IDP initiated login.

   user    ---->      Identity provider
                           |
   |
   |  SAMl Assertion
                          V
                        salesforce (SP)

SP Initiated Login :
=====================
User can go directly to an SP application to access the application.
In this case, SP will redirect the user toIDP login page where user will provider
his/her username and password, IDP will authenticate the user and pass control
back to SP asserting whether user is authenticated or not.SP will then allow
user to access the application.

Note : Identity provider is the instance where users have an active session.
And service provider is the one which identifies the certificate from
the identity provider saying the user is coming from the authenticated source.


                                              saml Auth Request
   user ---->  salesforce (sp)  ------>
                                              <-------   Identity provider
 saml assertion


Federated Authentication using SAML :
=====================================
1.Federated authentication uses SAML, an industry standard for secure integrations.Investing in SAML with Salesforce.com

2.org-wise level

3.Salesforce admins can enable.

Authentication and authorization between two entities : service provider and identity provider

The service provider agrees to trust the identity provider to authenticate users.

Note :

SAML stands for security Assertion Markup Language.

SAML is an XML-based protocol for exchanging identity and authorization information.

The SAML,which is basically XML documents that are going  to be exchanged. Some are going to be exchanged at setup time, and some are going to be exchnaged when you try to
login.

That XML has a packet of information that contains authentication information, but it's built into that XML data model essentially.

Just-in-time user Provisioning :
============================
The just-in-time provisioning is basically the idp has the authority to create or update user information inside of the service provider.


relay :
========
SP init does it carries your original destination that you were trying to get to as part of the relay state.

The RelayState is meant to direct the user after a successful login to a specific location in the application they're logging into. If you need to include query parameters,make sure they're URL encoded.

RelayState=var1%3Dvalue1%26var2%3Dvalue2

SAML Assertion Validator :
===========================
1. Available in single sign-on settings.
2. used to check for failed logins of sso.


Delegated Authentication Flow :
===============================
Delegated Authentication is specific to salesforce only(not industry standard)
where external webservice only retruns "TRUE" and "FALSE" saying Authentication is complete
or not.

1.Require salesforce support to enable.
2.Permission level.

Note:
when the user submits the login page with their credentials, Salesforce look up the user from the username.If Delegated Authentication(DA) is configured for this org and user,
we send the supplied password to the configured Delegated Authentication (DA)
endpoint for verification,otherwise we verify the password against the hash
we have on record for that user.Either way, if the password is successfully
verified,we create a session, issue the cookie, and redirect the user to
the requested page.


1. We can integrate with the LDAP server - Lightweight Directory Access Portocol or authenticate with the access token rather with the password.

2.We can also manage authentication at the permission level which gives us more flexibility.

3. with the above feature, we can set delegated authentication for particular users rest will use their salesforce credentials for login.

4.If user tries to login through online or API, salesforce checks permission settings and access settings after validating the UserName.

5.if user has enabled the single sign on permission setting then salesforce doesn't validates the login credentials.Rather it makes an web service call to org for validating the login credentials.

6. When above permission setting is enabled then salesforce no longer manages the password policies

ex : Password must be required minimum length.

7.Then delegated authentication comes into action, the endpoint service enforces the policies for password.

Note :
The webService validates username,password and Source IP

Source IP : The IP address that originated the login request.


security Modes :
================
1.Simple Passwords (User salesforce login page)
2.Tokens ( Private login page on your company webserver that may be behind your corporate firewall)
3.Mixed (use mobile and client apps)


OpenID Connect :
====================

OpenID Connect is a modern Identity Protocol that leverages OAUTH.

It provides an ID token and UserInfo endpoint.

you can use it for single sign-on (SSO).

Salesforce can act as an OpenID Connect client.

 ex: Sign in with Google.

Salesforce can act as an OpenID connect Provider.

Example Login with Salesforce.


OpenID Connect - for social Sign-on into the org.
 Login to salesforce org with Google+.

 Steps for social sign-on with Google+ into Enterprise Org.

 1. Setup MyDomain in the org.
 2.Configure an OpenID Connect type Authentication provider  pointing to Google.
 3.Set a google plus user ID field on user record - for account linking.
 4.Update a user record with a valid google plus userID.
 5.Configure enterprise branding page to enable Login with Google.
 6.Test Login with Google into the enterprise org.


OpenID Connect - For salesforce login into the community.

 Login to community with any Salesforce org.

 Steps for Single Sign On into Community with any Salesforce Org.

 1. Setup OpenID Connect Auth Provider pointing to a Connected  App in IDP.
 2.Registration Handler code can do user checks based on Email  or FederationID.
 3.Set the Community Login Page to use this Auth Provider.


 Authorization Request

 https://ogin.salesforce.com/services/oauth2/authorize

Authorization Response

https://www.example.com/oauth/callback/?

Token Request

Token Response

access_token
id_token

Note :
Client uses ID token to authenticate the end user.

The ID token is represented as a JSON Web Token (JWT).The JWT is singed using a JSON web signature and consist of three parts separated by "."

An ID token has the following syntax :

Base64(JOSE header).Base64(Payload).Base64(Signature)

Every Client must validate the ID-token it receives.It must validate the iss, aud and exp claims. The rest are optional if presented.

what OpenID connect adds?

1.ID token
2.UserInfo endpoint for getting  more user information
3.Standard set of scopes
4.Standardized implementation.

OAuth and OpenID Connect :
======================

Use OpenID Connect for (Authentication):

1.Logging the user in
2.Making your accounts avaialble in other systems

Use OAuth 2.0 for (Authorization) :

1.Granting access to your API
2.Getting access to user data in other systems.


Connected App :
=============

Consumer key is essentially the API key associated with
the application (Twitter, Facebook, etc.). This key
(or 'client ID', as Facebook calls it) is what
identifies the client. By the way, a client is a
website/service that is trying to access an end-user's
resources.

Consumer secret is the client password that is used to
authenticate with the authentication server, which is a
Twitter/Facebook/etc. server that authenticates the
client.

Access token is what is issued to the client once the client successfully authenticates itself (using the consumer key & secret). This access token defines the privileges of the client (what data the client can and cannot access). Now every time the client wants to access the end-user's data, the access token secret is sent with the access token as a password (similar to the consumer secret)

Sunday, 7 July 2019

20 ways to share records in salesforce

1.profile/permission Set level object Settings (CRED)
2.Profile/Permission Set Level object Settings (View All,Modify All)
3.Profile Level System Permissions (View All Data,Modify All Data)
4.Organization Wide Defaults (OWD)
5.Record Ownership
6.Role Hierarchy
7.Teams
8.Queues
9.Sharing Rules
10.Groups
11.Manager Group
12.Territory Management
13.Sharing sets
14.Sharing groups
15.Super User Access
16.Manual Sharing
17.Programmatic/apex sharing
18.Visualforce with Apex
19.Implicit sharing
20. Master-detail Relationship

1.Profile/Permission Set Level Object Settings (CRED)

-> The first minimum thing that the user needs to have
'Read','Create','Edit' or 'Delete'(CRED) permission on
the object either through profile or permission Set.

-> In Fact the user's profile/permission set must have
these Object level Permissions(CRED) for other sharings
to work.

-> For profile tied to specific license types (e.g Community User Licenses),
you can't set CRED on some of the objects.
E.g. for "Customer Community" License, the 'Lead' object is
not available.

Note :
Different License Types
1.Customer Community License
2.Customer Plus Community License
3.Partner Community License

Customer Community Plus users have greater access to sharing
features.They can have up to 3 roles, and therefore are able to
utilize sharing rules.

Partner Community licenses features the same benefits as
Customer community plus, and also have access to sales- related
objects (Lead,campaigns and Opportunities).

Note :
There are no workaround for Customer Community Profile
user to access leads.
You need to upgrade to Partner Community License
(Opportunities,Leads,Quotes,Campaigns objects available).

2.Profile/Permission Set Level Object Settings (View All/Modify All)

-> The next option that you have is to grant 'View All' and/or
'Modify All' at the object level.

-> Once these permissions are granted to the user's
profile/permission set, they can view/edit all records in that
object, irrespective of the sharing model.

-> For profiles tied to specific license types,
view all/modify all options will not be available on some of the objects.

3.Profile Level System Settings (View All Data, Modify All Data)

-> Probably one of the most powerful permission that you grant
is to specify 'view All Data' / 'Modify All Data' at the system level
on user's profile.with this option the user will be able to view/modify
all records across all objects.

-> For profiles tied to specific license types,
view all data/modify all data system privilege is not available.

-> use this option sparingly and with caution.

4.Organization Wide Defaults (OWDs)

-> Another way to grant users access to records is by setting
the OWD to "Public Read only" or "Public Read/Write" for individual
objects.

-> When set to "Public Read Only" or "Public Read/Write ",
All users in your Org will have view/edit privileges
provided the user has CRED permissions on the object(s)
through profile/permission set.

5. Record Ownership

-> if the user is the owner of the record, they automatically
have read/edit/transfer privileges on that record.

-> However, if you have removed the object level CRED permission
from user's profile/permission set, then they won't be able to
view/edit the records EVEN IF they are owner of the record.

-> This can happen if the user's profile/permission set had CRED
privileges, they created some records and later CRED permissions
were removed.

6.Role Hierarchy

-> All the users who have above in the role hierarchy
chain of the user who has access to the records, will
automatically inherit the same permissions as their subordinates
on that record.

-> User must have CRED permissions on the object(s) through
profile/permission set.

Note :
Community users having 'Customer Community' license type
cannot be assigned a role and hence this rule does not apply
to them.

7. Teams (Account,case,Opportunity)

-> To share records in Account,Case & Opportunities,
you can enable teams and add user to the team.

-> For each user being added to the team, you can define
whether they canjust 'View' the record or 'Edit' the record.
In Case of 'Account Team' , you can define whether the users
in the 'Account Team' has access to the 'Cases' & 'Opportunities'
for that Account.

-> User must have CRED permissions on the object(s) through
profile/permission set.

Note : Community users having 'Customer Community'
license cannot be added to the team and hence this rule
does not apply to them.

8.Queues

-> you can create Queues in salesforce, assign the user to
the queue and set the queue as the owner of the record.

-> Users assigned to the queue will then automatically
have "Owner" like access to those records.

-> User must have CRED permissions on the object(s)
through profile/permission set.

Note :
1. you can't set the queue as the owner on the 'Account'
and 'Task' objects.
2.Community users having 'Customer Community' license
cannot be added to the queue and hence this rule does not apply
to them.

9. Sharing Rules

-> Create sharing Rules on the object. You can define the following
type of sharing rules.

1.Ownership Based Sharing Rule - Where you can share records
owned by a specific set of users with another specific
set of users.

2.Criteria Based sharing Rule - Where you can share records
meeting a specific criteria with specific set of users.

-> User must have CRED permissions on the object(s) through
profile/permission set.

Note : cannot be used for sharing records with Community
users having 'Customer Community' license type.

10. Groups

-> you can create Groups in salesforce and assign users
to the groups (you can also assign roles, territories or
other groups to a group).

-> Then use Sharing Rules to grant access to the records
to this group of users.

-> User must have CRED permissions on the object(s) through
profile/permission set.

Note :
Community users having 'Customer Community' license type cannot
be added to groups and hence this rule does not apply to them.

11.Manager Group

-> you can enable 'Manager Group' sharing option to share records
with the 'Manager' of user defined on the 'User' object.

-> Use Manager groups to share records with your management chain
instead of ll managers in the same role based on the role hierarchy.

-> Then use Sharing Rules to grant access to the records to this
group of users.

-> User must have CRED permissions on the object(s) through
profile/permission set.

Note : Manager groups can contain standard and chatter only users only
and doesn't include portal users.

12. Territory Management

-> Another powerful way to share records with users -
Create Territories and assign users to territories.

-> For sharing Account records, define the Account Assignment rule
on the Territories.

-> For sharing records in other objects, define sharing rules and
use Territories in the sharing rules.

-> User must have CRED permissions on the object(s) through
profile/ permission set.

Note :
Community users having 'Customer Community' license type
cannot be assigned to territories and hence this rule does not
apply to them.

13. Sharing Set

-> Use Sharing Set to share records with users having 'Customer Community' license type.

-> This is the only way to share records with these types of users.

-> User must have CRED permissions on the object(s) through
profile/permission set.

Note :
 -> Applicable only for community users having 'Customer Community' license type. 
 -> NOT applicable for any other user type.

 14. Sharing Group

 -> Use this option to share records created by 'Customer Community'
 license users with other internal/community users.

 -> Works together with Sharing Set.

 -> While Sharing Set is used to share records created by other
 usres with 'Customer Community' license users,sharing Group
 is used to share records created by 'Customer Community' license users
 with other users .

 -> User must have CRED permissions on the object(s) through
 profile/permission set.

 15. Super User Access

 -> Applicable only for users with license type 'Partner community'
 & 'Customer community Plus'.

 -> Used to share records created by the community user
 belonging to the same Account.

 -> User must have CRED permission on the Object(s) through
 profile/permission set.

 16. Manual Sharing

 -> Owner of a record/person higher in the role hierarchy
 of the owner/ System Administrator, can grant manual access to other
 users, groups, roles. This is done manually on record by record basis.

 Note : if you change the owner of the record or transfer the record
 to someone else, Salesforce will remove all the manual sharing.

 -> User must have CRED permission on the Object(s) through
 profile/permission set.

 17. Programmatic/apex Sharing

 -> You can also share records with other users, groups, roles programmatically.

-> This is usually done by defining a sharing reason and inserting a record in <object_name>__share object.

-> A use case is you want to share the ‘Job’ record with the Hiring Manager of that job.
So as soon as the hiring manager is assigned to the job record, the record should then automatically be shared with that hiring manager.
This is achieved by writing a trigger on the ‘Job’ object and using programmatic sharing

-> User must have CRED permissions on the object(s) through profile/permission set.

Note :
Cannot be used to share records with Community users having 'Customer Community' license type.

18. Visualforce with Apex


->If nothing else works, then you can create a Visualforce Page with Custom Apex Controller in "without sharing" mode
and grant users view/edit access to the record.

-> This option requires heavy custom development and maintenance.

-> Before going down this route, do ensure that you will not be flouting Salesforce licensing rules
when exposing records through this method.

E.g.

Salesforce Licensing model does not grant access to 'Lead' object to Customer Community Plus users.
If you are creating a Visualforce page with Custom Apex Controller
to expose lead object records to Customer Community Plus user, this may not be allowed.

19.Implict Sharing


->Salesforce grants implicit access to the records when you have access to other related records.

-> For example if you have access to a 'Contact', 'Case' or 'Opportunity' record,
Salesforce will grant you implicit read only access to the corresponding Account.
This is known as 'Implicit Parent'

-> Or if you have access to the Account through Role Hierarchy / Account Team
and have selected the option to grant access to 'Contact', 'Case' or 'Opportunity'
when defining Account Team or Role Hierarchy, then Salesforce will grant you implicit Access to
'Contract', 'Case', or 'Opportunity' records. This is known as 'Implicit Child'.

->User must have CRED permissions on the object(s) through profile/permission set.

20.Master-detail Relationship

->If you have objects in Master-Detail relationship, then the sharing rules defined on the master
automatically cascades to the object on the ‘Detail’ side of the relationship.

-> You cannot define separate sharing rule on the child object as the sharing rules are inherited from the Master.

-> This means that if a user has ‘View’ access on a record in the Master object,
he will also be able to view the corresponding child records in the detail object.

->User must have CRED permissions on the object(s) through profile/permission set.


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;
    }
   
}