Thursday, 26 December 2019

Lightning web Components


why using Lightning web components ?
1.Re-usability     - Imports,Exports and Templates allows us to reuse the components.
2.Composition      - Breaking components to smaller chunks
3.Encapsulation    - Using the shadow DOM
4.Standardization  - Part of W3C specs and supported by majority of browser.

Core Elements of web Components ?

1.HTML Templates
2.Custom Elements
3.Shadow DOM
4.ES Modules

Templates and Slots :
=====================
1.Templates allow us to load HTML tags without rendering them on initial load.
2.Write once and reuse in multiple pages or multiple apps.
3.Attach them to Shadow DOM or DOM.
4.Slots are placeholders in template that allow you to insert your own HTML markup.

Custom Elements :
=================
Allows us to define an element and let browser learn about the new tag.

class MyCustomElement extends HTMLElement{
 
  constructor(){
    // always call super() first in your constructor to inherit from your Parent class
super();
  }

}
customElements.define('my-custom-element',MyCustomElement);

Shadow DOM :
==============
1.Shadow DOM allows the web browser to render DOM elements without putting them into the main document DOM tree.
2.One can attach shadow DOM to an element using the API Element.attachShadow(mode:open}).
3.You can attach the Shadow to the custom element.
4.Offers encapsulation (CSS in outer DOM cannot bleed into the shadow DOM).

Lightning Web Components (LWC)

1.Lightning Components used aura framework and its renamed as Aura Components.
2.Components built using Web Components standard now are referred as lightning web components.
3.Lightning web components(LWC) adheres closely to the web components standards.
4.Modules for Data services, UI API and provides reactive properties.


Note : Shadow DOM
1.The elements in each Lightning web component are encapsulated in a shadow tree.
2.This part of the DOM is called a shadow tree because it's hidden from the document that contains it.
3.The shadow tree affects how you work with CSS,events and the DOM.
4.Since not all browsers that Salesforce supports implement Shadow DOM,LWC uses a shadow DOM polyfill.

ex :
<c-todo-app>
 #shadow-root
   <div>
    <p>Your To Do List</p>
   </div>
   <c-todo-item>
    #shadow-root
<div>
   <p>Go to the store</p>
</div>
</c-todo-item>
</c-todo-app>

Shadow tree for todoApp
Shadow tree for todoItem

Javascript Properties :
======================
1.Reactive Property - Change in property value automatically reRenders the template.
2.To create a public property use @api.
3.To create a private property and reRender DOM use @track.

Lightning Data Service :
==========================
1.Mark the property with @wire if you want the property to receive the changes when data change happens to record.
2.LWC supports UI APIs and Metadata describes.

Life Cycle Hooks :
===================
1.constructor()             - When Component Created
2.connectedCallback()       - When Component inserted in DOM.
3.disconnectedCallback()    - When Component removed from DOM.
4.render                    - Called after ConnectedCallBack.For Complex rendering Logic.
5.renderedCallback()        - After render
6.errorCallback(error,stack)- If any error in component life-cycle methods.

Important point :
==================

Handle Event When Component not in Same DOM

1.Use pub sub model

Component :
============
1.Component HTML File
2.Component Javascript File.
3.Component Configuration File.

Javascript files in Lightning web components are ES6 modules.
By default, everything declared in module is local-it's scoped to the module.

To import a class,function or variable declared in module,use the export statement.

ex :

import { LightningElement } from 'lwc';
export default class MyComponent extends LightningElement{

}

lwc is core module from wher we import LightningElement.
LightningElement is custom wrapper of the standard HTML element creates javascript class for LWC.

Decorators :
=============
The Lightning Web Components programming model has three decorators
that add functionality to a property or function.
The ability to create decorators is part of ECMAScript,but these three decorators
are unique to Lightning Web Components.

1.@api :

To expose a public property,decorate it with @api.
An owner component that uses the component in its markup can
access the component's public properties.

2.@track :

To track a private property's value and re render a component
when it changes,decorate the property with @track.
Tracked properties are also called private reactive properties.

3.@wire :

To read Salesforce data, Lightning web components use a reactive wire
service . When the wire service Provisions data, the component rerenders.

Components use @wire in their javaScript class to specify a wire adaptor or an Apex method.

Components use @wire in their javaScript class to read data from one of the wire adapter
in lightning/ui*Api namespace.

wire adapters :
==============
1.getListUi
2.getObjectInfo
3.getPicklistValues
4.getPicklistValuesByRecordType
5.getRecord
6.getRecordUi

Note :
The wire service delegates control flow to the Lightning web Component engine.
Delegating control is great for read operations,bit it isn't great for create and
delete operations.As a developer ,you want complete control over operations
that change data.use Javascript API instead of wire service.


Call Apex Method using wire service :
=====================================

ex:
import { LightningElement,track,Wire } from 'lwc';
import findContacts from '@salesforce/apex/ContactController.findContacts';

export default class ApexWireMethodToProperty extends LightningElement{
  @track searchkey='';
  @wire (findContacts,{ searchkey : 'searchkey'}) contacts;
 
}

Imperative Methods :
=====================
import { LightningElement,track,Wire } from 'lwc';
import getContactList from '@salesforce/apex/ContactController.getContactList';

export default class ApexImperativeMethod extends LightningElement{
 
   @track contacts;
   @track error;
 
   handleLoad(){
       getContactList()
        .then(result => {
           this.contacts=result;
         })
         .catch(error => {
          this.error=error;
         });  
 
   }

}

Javascript logic :
===================
1. ES6 classes are used to define logic.
2. ES6 module imports/exports are used to import and export logic.

ex :

 @api recordId;
 @wire(getRecord,{recordId : $recordId',fields});

 In the wire adapter's configuration object,prefix a value with $ to reference a property of the component instance.
 The $ prefix tells the wire service to treat it as a property of the class and evaluate it as this.PropertyName.
 The property is reactive. If the property's value changes,new data is provisioned
 and the component rerenders.

 Lightning web component Communication :
 ========================================

 1.Public Properties (Passing data down)

 ex :
   child component
 
   import { LightningElement,api} from 'lwc';
 
   export default class ChildComponent extends LightningElement{
     @api myProperty ='DeafultValue';
   }
 
  Parent Component
 
  <template>
     <c-child-component my-property={parentCmpProperty}></c-child-component>
  </template>
 
  Note : In child component you can assign a default value to a public property,
  but you should never change the value of a public property in the component itself.
  Remember the purpose of this property is to the Public API of the component,
  so only the parent component should set or change its value.
 
 2.Public methods (passing data down)

 public methods can receive parameters and return values.

  ex :
 
  child Coponent
 
  import { LightningElement, api } from 'lwc';

export default class ChildComponent extends LightningElement {
    @api
    doWhatever(param1) {
        // Do whatever...
        return 'Finished!';
    }
}

 Parent component

 import { LightningElement } from 'lwc';

export default class ParentComponent extends LightningElement {
   
   
        const returnValue = this.template.querySelector('c-child-component').doWhatever('My param');     
   
}

3.Custom Event (Passing data up)

ex :

 child component

 import { LightningElement } from 'lwc';

export default class ChildComponent extends LightningElement {
 
        const myEvent = new CustomEvent('eventname',
                                        {
                                            detail: {
                                                prop1: value
                                            }
                                        });
        this.dispatchEvent(myEvent);
   
}

parent component (event listener declaratively)

<template>
    <c-child-component oneventname={handleEvent}></c-child-component>
</template>

import { LightningElement } from 'lwc';

export default class ParentComponent extends LightningElement {
    handleEvent(event) {
        // Do whatever with event.detail
    }
}

Note : Event type Naming conventions ( Here "eventname" is Event Type)
1.No uppercase letters.
2.No spaces
3.Use underscores to separate words.
4.Don't prefix your event name with string 'on'.


ex : event Listener Pro-grammatically

child component

import { LightningElement } from 'lwc';

export default class ChildComponent extends LightningElement {
    handleResponse(event) {
        event.target.disabled = true;
        const btnName = event.target.label;
        const answerEvent = new CustomEvent("answer", { detail: btnName, bubbles: true });
        this.dispatchEvent(answerEvent);
    }
}

Parent Component

import { LightningElement, track } from 'lwc';

export default class ParentComponent extends LightningElement {
    @track answer = "Child: ";
    question = "Parent: Have you completed study for today?";

    constructor() {
      super();   
      this.template.addEventListener('answer', this.handleAnswer.bind(this));
    }
 
    handleAnswer(event) {
      /*eslint-disable-next-line*/
      console.log("res--&gt;" + event.detail);
      const res = event.detail;
      this.answer = this.answer + res;
    }
}

Note :

1.Add an event Listener to an element with in a shadow boundary, use this.template.addEventListener() method.
2.Add an event Listener to an element that the template doesn't own, use this.addEventListener() method directly.

 -> "this" refers to the default class.
 -> Container component can add event listeners and access elements directly on "this".
    so,we should use this.addEventListener and this.querySelector.
 -> Owner component has to add event-listeners and identification through "template".
    so,we should use this.template.addEventListener and this.template.querySelector.

ex : consider 3 components Grandparent, Parent and child

GrandParent

<template>
    <div>Grandparent:</div>
    <c-parent>
        <span slot='myslot'>
            <c-child></c-child>
        </span>
    </c-parent>
</template>

export default class Grandparent extends LightningElement {
    constructor() {
        super();
        console.log('this => ', this);       
        this.template.addEventListener('myevent', this.myeventHandlerTemplate);
    }
    renderedCallback() {       
        console.log("Grandparent renderedCallback template => ", this.template.querySelector('c-child'));
    } 
    myeventHandlerTemplate(event) {
        console.log('Grand parent template - myevent handled');
    }
}

Note :
GrandParent component is the owner of c-child component.
c-parent component is the container of c-child component.

Parent component

<template>
    <div>
        <slot name='myslot'></slot>
    </div>
</template>

export default class Parent extends LightningElement {
    constructor() {
        super();
        console.log('this => ', this);
        this.addEventListener('myevent', this.myeventHandler);
       
    }
    renderedCallback() {
        console.log("parent renderedCallback => ", this.querySelector('c-child'));
     
    }
    myeventHandler(event) {
        console.log('parent - myevent handled');
    }   
}

child component

export default class Child extends LightningElement {
    connectedCallback() {
        this.dispatchEvent(new CustomEvent('myevent', { bubbles: true }));
    }
}

Note :
bubbles:true and composed:false (default is false) will make the event bubble up until shadow boundary.

Out put :

this =>  Grandparent {setAttribute: ƒ}
this =>  Parent {setAttribute: ƒ}
parent - myevent handled
Grand parent template - myevent handled
parent renderedCallback =>  c-child
Grandparent renderedCallback template =>  c-child



4.pubsub event

1.pubsub is a singleton library that follows publish subscribe pattern.
2.Each component that subscribes to the event receives the event.

ex :

fire the event

 <template>
    <lightning-card title="Source" >
        <div class="slds-m-around_medium">
            <lightning-input type="text" onchange={handleChange} class="slds-m-bottom_small" label="Enter Text"></lightning-input>
        </div>
    </lightning-card>
</template>

import { LightningElement,wire} from 'lwc';
import { CurrentPageReference } from 'lightning/navigation';
import { fireEvent } from 'c/pubsub';
export default class Publishsource extends LightningElement {
    @wire(CurrentPageReference) pageRef;
    handleChange(event) {
        fireEvent(this.pageRef, 'inputChangeEvent', event.target.value);
    }
}

subscribe event

<template>
    <lightning-card title="Target">

        {inpVal}
    </lightning-card>
</template>

import { LightningElement, track, wire } from 'lwc';
import { CurrentPageReference } from 'lightning/navigation';
import { registerListener, unregisterAllListeners, fireEvent } from 'c/pubsub';

export default class Publishreceiver extends LightningElement {
      @track inpVal;
      @wire(CurrentPageReference) pageRef;

      connectedCallback() {
          // subscribe to inputChangeEvent event
          registerListener('inputChangeEvent', this.handleChange, this);
      }

      disconnectedCallback() {
          // unsubscribe from inputChangeEvent event
          unregisterAllListeners(this);
      }

      handleChange(inpVal) {
          this.inpVal = inpVal;
      }
}


Lightning Data service :
=========================
1.Caches results on the client.
2.Invalidates cache entry when data and meta data changes.
3.Optimizes server calls.

UI API :
============
1.Public Salesforce API to build UI.
2.Gives data and metadata in a single response.
3.UI responses respect CRUD,FLS and Sharing settings.

Base Lightning Components :
==========================
1.Lightning Record Form

supports edit,view and read-only modes.

2.Lightning Record View Form

displays a read-only form.

3.Lightning Record Edit Form

displays an editable form.

These Base Lightning Components works on top of the Lightning Data service.

Advantages of Base Lightning Components :
1.Metadata aware (data types etc).
2.Does not require Apex code
3.Provide Form Layout
4.Field labels are displayed based on Org's defaults.
5.Built on Lightning Data service and UI API.
6.Can access model statically.
7.Can also access model dynamically.


Overriding Standard Actions :
=============================
we can not directly override action with Lightning web component directly.
You need to call your component in Aura Component and use that aura component to override the action.

Lwc in Lightning Out :
======================
its possible to use LWC in visualforce as lightning out.


Composition :
==============

Owner

1.Set public properties on child.
2.Call public methods on child.
3.Listen for any events from child.

Container

1.Can read public properties on child.
2.Call public methods on child.
3.Listen for events bubbled from child.


Event Propagation Phases
========================
Event propagation can be controlled using two properties on the event.
1.bubbles
2.composed

bubbles :

1.A Boolean value indicating whether the event bubbles up through the DOM or not.
2.Defaults to false.

composed :

1.A Boolean value indicating whether the event can pass through the shadow boundary.
2.Defaults to false.

controlling Event Propagation :
===============================

1.bubbles:false and composed:false
The event doesn't bubble up through the DOM and doesn't cross the shadow boundary.

2.bubbles:true and composed:false
The event bubbles up through the DOM,but doesn't cross the shadow boundary.

3.bubbles:true and composed:true

The event bubbles up through the DOM,crosses the shadow boundary,and continues bubbling up through the DOM to the document root.

4.bubbles:false and composed:true

Lightning web components doesn't use this configuration.


Working with Third-Party Libraries :
=====================================

In LWC static resource is imported through "import" command
and then loadScript or loadStyle methods can be used to load the third-party library.

ex :

import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { loadScript, loadStyle } from 'lightning/platformResourceLoader';
import D3 from '@salesforce/resourceUrl/d3';
import DATA from './data';

export default class LibsD3 extends LightningElement {
    svgWidth = 400;
    svgHeight = 400;

    d3Initialized = false;

    renderedCallback() {
        if (this.d3Initialized) {
            return;
        }
        this.d3Initialized = true;

        Promise.all([
            loadScript(this, D3 + '/d3.v5.min.js'),
            loadStyle(this, D3 + '/style.css'),
        ])
            .then(() => {
                this.initializeD3();
            })
            .catch(error => {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error loading D3',
                        message: error.message,
                        variant: 'error',
                    }),
                );
            });
    }

Lightning Locker :
==================

Lightning Locker is a layer which sits in between your browser and DOM (document object).
In other words, Lightning Locker is a virtual browser that allows only secure request to go through.
This virtual browser sits in front of your real browser which is unsafe as you get access to complete DOM and can easily manipulate it.

Sunday, 20 October 2019

Strip inaccessible fields in salesforce

To enforce FLS and CRUD in Apex.

ex :

List<Campaign> campaigns = new List<Campaign>{
    new Campaign(Name='Campaign1', BudgetedCost=1000, ActualCost=2000),
    new Campaign(Name='Campaign2', BudgetedCost=4000, ActualCost=1500)
};
insert campaigns;
// Strip fields that are not readable
SObjectAccessDecision decision = Security.stripInaccessible(
    AccessType.READABLE,
    [SELECT Name, BudgetedCost, ActualCost FROM Campaign]
);
// Print stripped records
for (SObject strippedCampaign : decision.getRecords()) {
    System.debug(strippedCampaign); // Does not display ActualCost
}
// Print modified indexes
System.debug(decision.getModifiedIndexes());
// Print removed fields
System.debug(decision.getRemovedFields());
//Lines from output log
//|DEBUG|Campaign:{Name=Campaign1, BudgetedCost=1000, Id=701xx00000011nhAAA}
//|DEBUG|Campaign:{Name=Campaign2, BudgetedCost=4000, Id=701xx00000011niAAA}
//|DEBUG|{0, 1}
//|DEBUG|{Campaign={ActualCost}}

Note :

1. You can use it remove inaccessible fields from sObjects before a DML operation
to avoid exceptions.

2. you can use the stripInaccessible() method to sanitize sObjects that
have been deserialized from an untrusted source.

Saturday, 7 September 2019

Platform cache in salesforce


Platform Cache can increase performance,replace Custom settings
and Custom Meta data Types by storing data temporarily without
any need of extra storage,and eliminates the need to use web callouts.


Note : session cache doesn't support synchronous Apex.
For example, you can't use future methods or batch Apex with
session cache.

Platform cache to improve the API callouts.


ex : access token for external service

Cache.OrgPartition orgPart = Cache.Org.getPartition('local.SomePartitionName');
orgPart.put('IntegrationAccessToken','123w12e12wzws1jnds3rbhh3');
orgPart.put('IntegrationTokenExpiry','10/03/2018');
system.debug((string)orgPart.get('IntegrationAccessToken'));


1.Org cache

Org cache can store Org-wide data such that anyone in the org can access
it.Org cache is accessible across sessions,requests, and org users and profiles.
For Org cache,data can live upto 48 hours in the cache.
By default, the time-to-live (TTL) value for org cache is 24 hours.


global values for all users
exists for upto 48 hours

2.Session Cache
specific to user sessions
Expires in 8 hours or if session ends

enterprise - 10MB (Mega bytes)
unlimited and performance - 30 MB (Mega bytes)
All others -0MB (mega bytes)

Maximum partition size - 5 MB (mega bytes)

Use Case :
============
1. Want to get top 10 by annual Revenue
2. Want to get number of VIP Accounts in each region (7 regions)

ex :

List<Account> accounts = [select Name,Region__c,BillingAddress,Description,
   Industry,Status__c,Type,Opportunity_count__c,AnnualRevenue
   from Account order by AnnualRevenue DESC NULLS LAST LIMIT 10];

   // Add to Cache
   Cache.Org.put('local.AcctPartition.TopAccounts',accounts);
 
   // Get the cache Partition
 
   cache.OrgPartition orgPart = cache.Org.getpartition('local.AcctPartition);
 
   // Get the data and cast it to the right datatype
 
   List<Account> accuntsCache = (List<Account>) orgPart.get('TopAccounts);
 
   if(accuntsCache !=null){
     return accountsCache;
   }
    return accountscache;

ex :

Map<String,Integer> accountsByRegion = new Map<String,Integer>();
List<Schema.PicklistEntry> regions = Account.Region__c.getDescribe().getPicklistValues();
for(Schema.PicklistEntry pe : regions){
  accountsByRegion.put(pe.value,0);
}

for(String regionName : accountsByRegion.keyset()){
   Integer count =[ select count() from account where Region__c =: regionName and Type ='VIP'];
   accountsByRegion.put(regionName,count);
  }
   // put any data structure into the cache
 
   Cache.Org.put('local.AcctPartition.VIPAccounts',accountsByRegion);
 
   Map<String,Integer> accountsByRegion = (Map<String,Integer>)cache.Org.getPartition('local.AcctPartition').get('VIPAccounts');
 
   if(accountsByRegion !=null){
      return convertMapToDetail(accountsByRegion);
   }
 
 return getAccountsByRegion();

 Note :
 The Cache Diagnostics user permission allows you to see detailed
 information about the platform Cache feature.

 Session cache :
 ================
 Session cache stores data that are tied to a user's session
 such that other users in the Org cannot access this data.
 The maximum life of a session cache is 8 hours.

 use the Cache.Session and cache.SessionPartition classes
 to access values stored in the session cache.

 Cache.Session.put(Key,value);


 CacheBuilder Interface :
 ========================
 public class Accountcache implements Cache.CacheBuilder{
   Public Object doLoad(String topTen){
 
   List<Account> accounts = (List<Accounts>)[select Id,AnnualRevenue,Name,Region__c
    FROM Account ORDER BY AnnualRevenue DESC NULLS LAST LIMIT 10];
  return accounts;

   
   }

 }

 CacheBuilder Interface has method with 1 parameter.
 CacheBuilder use the class and key to request.

 //populate the cache
 List<Account> myAccounts = (List<Account>) Cache.Org.get(AccountCache.class,'TopTen');

 // Retrieve from cache
 List<Account> myAccounts2 = (List<Account>) Cache.Org.get(AccountCache.class,'TopTen');

 Interface checks if value is cached.

 If cached return value else calculate,cache and return.

 Note :
 Instead of storing and retrieving cache, it is better to provide
 loading strategy toPlatform cache, so upon cache miss,Salesforce
 automatically calls the class to load the cache for that key.
 This reduces the code and handles cache miss much more gracefully.

Monday, 2 September 2019

Handling MIXED_DML_OPERATION Exception in Salesforce

you can easily run into this error if you are trying to perform DML on setup and non-setup objects in the  same transaction.

Non-Setup objects are standard objects like Account or any custom object.

Setup objects are Group1,GroupMember,QueueSObject,User2,UserRole, UserTerritory,Territory, etc..

ex :
you cannot insert an account and then insert a user or a group members in a single transaction.

1. Avoid MIXED_DML_OPERATION using system.runAs in test classes.

ex :

@isTest
static  void test_mixed_dmlbug() { 
    User u;
    Account a;     
    User thisUser = [ select Id from User where Id = :UserInfo.getUserId() ];
    System.runAs ( thisUser ) {
        Profile p = [select id from profile where name='(some profile)'];
        UserRole r = [Select id from userrole where name='(some role)'];
        u = new User(alias = 'standt', email='standarduser@testorg.com',
            emailencodingkey='UTF-8', lastname='Testing',
            languagelocalekey='en_US',
            localesidkey='en_US', profileid = p.Id, userroleid = r.Id,
            timezonesidkey='America/Los_Angeles',
            username='standarduser@testorg.com');
        a = new Account(Firstname='Terry', Lastname='Testperson');
        insert a;
    }
    System.runAs(u) {
        a.PersonEmail = 'test@madeupaddress.com';
        update a;
    }

}

2. Avoid MIXED_DML_OPERATION Exception by using Future Method.

ex : 

trigger Automatecontact on Account(after insert) {
     List<contact> lc = new List<contact>();

for (Account acc : Trigger.new) {
   lc.add( new contact(lastname ='dk',accountId =acc.id) );
}
insert lc;

UtilClass.userInsertWithRole('dineshd@outlook.com', 'Dinesh','dineshd@outlook.com', 'Dineshdk');

}
public class UtilClass {
  @future
  public static void userInsertWithRole(String uname, String al, String em, String lname)
   {
Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
UserRole r = [SELECT Id FROM UserRole WHERE Name='COO'];
// Create new user with a non-null user role ID
User u = new User(alias = al, email=em,
emailencodingkey='UTF-8', lastname=lname,
languagelocalekey='en_US',
localesidkey='en_US', profileid = p.Id, userroleid = r.Id,
timezonesidkey='America/Los_Angeles',
username=uname);
insert u;
  }
 }



Note :

System.RunAs(User)

1.The system method runAs enables you to write test methods that change the user context to an existing user or a new user.

2.The original system context is started again after all runAs test methods complete.

Advantage of Trigger Framework in Salesforce

According to trigger framework
1) we should create single trigger for each object.
2) One handler class which will call Action
3) Create one action class with business logic same function you can use for other activity also. You can call from VF page  or batch job if required.

1) One Trigger Per Object
A single Apex Trigger is all you need for one particular object. If you develop multiple Triggers for a single object, you have no way of controlling the order of execution if those Triggers can run in the same contexts

2) Logic-less Triggers
If you write methods in your Triggers, those can’t be exposed for test purposes. You also can’t expose logic to be re-used anywhere else in your org.

3) Context-Specific Handler Methods
Create context-specific handler methods in Trigger handlers

4) Bulkify your Code
Bulkifying Apex code refers to the concept of making sure the code properly handles more than one record at a time.

5) Avoid SOQL Queries or DML statements inside FOR Loops
An individual Apex request gets a maximum of 100 SOQL queries before exceeding that governor limit. So if this trigger is invoked by a batch of more than 100 Account records, the governor limit will throw a runtime exception

6) Using Collections, Streamlining Queries, and Efficient For Loops
It is important to use Apex Collections to efficiently query data and store the data in memory. A combination of using collections and streamlining SOQL queries can substantially help writing efficient Apex code and avoid governor limits

7) Querying Large Data Sets
The total number of records that can be returned by SOQL queries in a request is 50,000. If returning a large set of queries causes you to exceed your heap limit, then a SOQL query for loop must be used instead. It can process multiple batches of records through the use of internal calls to query and queryMore

8) Use @future Appropriately
It is critical to write your Apex code to efficiently handle bulk or many records at a time. This is also true for asynchronous Apex methods (those annotated with the @future keyword). The differences between synchronous and asynchronous Apex can be found

9) Avoid Hardcoding IDs
When deploying Apex code between sandbox and production environments, or installing Force.com AppExchange packages, it is essential to avoid hardcoding IDs in the Apex code. By doing so, if the record IDs change between environments, the logic can dynamically identify the proper data to operate against and not fail


Custom Iterator (Iterable) in Batch Apex

1.If you use an iterable the governor limit for the total number of records retrieved by soql queries is still enforced.

2.if your code accesses external objects and is used in batch Apex, use iterable<sobject> instead of Database.QueryLocator.

global class CustomIterable implements Iterator<Contact>{

  List<Contact> con {get;set;}
   Integer i {get;set;}
 
   public CustomIterable(){
      con = [select Id,LastName From Contact LIMIT 5];
  i=0;
   }
     // This is Iterator interface hasNext() method, it will
// return true if the list 'con' contains records else it
// will return false;

   global boolean hasNext(){
      if(i>=con.size()){
    return false;
  }else{
    return true;
  }
   }
 
   // This is Iterator interface next() method, it will keep on
   // returning next element on the list until integer i reaches 5
   // and 5 in if loop is the size of the list returned by soql query
   // in above code
 
   global Contact next(){
     if(i==5){return null;}
i++;
return con[i-1];
   }
 
}

Note :
If your code accesses external objects and used in batch Apex, use Iterable<sObject> instead of Database.QueryLocator.

In Batch Apex , the start method return a Database.QueryLocator ,but you can return an Iterable.

global class batchClass implements Database.batchable<Contact>{
 global Iterable<Contact> start(Database.batchableContext info){
   return new CustomIterable();
 }
 global void execute(Database.batchableContext info,List<Contact> scope){
    List<Contact> conToUpdate = new List<Contact>();
for (Contact c :scope){
   c.LastName='Test123';
   conToUpdate.add(c);
}
update conToUpdate;
 }
 global void finish(Database.batchableContext info){

 }
}

Note :
1. Use the Database.QueryLocator object when you are using a simple query to generate the scope of objects used in the batch job. In this case, the SOQL data row limit will be bypassed.

2. Use iterable object when you have complex criteria to process the records.

External ID in Salesforce

The External ID field allows you to store unique record IDs from an external system,typically for integration purposes.

If we create External Id field, it will be indexed by default by salesforce.

During upsert operation

1. If External Ids are matched, it will update the records.
2. If External Ids are not matched, it will create a new record.
3. If External Ids are matched more than once,it will throw an error.

The fields with below data types can only be external Id

1.Number
2.Text
3.Email

You can designate up to 25 External ID fields per object.

External Ids are set with the unique property so that the IDs will be unique to each roecord.

Note :
Unique fields are not used in the UPSERT . it determine the uniqueness.

Indirect Lookup Relationship vs External Lookup Relationship

Types of relationships in salesforce :
======================================
1.Master - detail relationship
2. Lookup relationship
3. self- relationship
4. External lookup relationship
5. Indirect lookup relationship
6. Many-to-many relationship (junction object)
7. Hierarchical relationship

Indirect lookup relationship :
=====================
Indirect lookup relationship links a child external object to a parent standard or custom object.

you select a custom unique, external ID field on the parent object to match against the child's indirect lookup relationship field,whose values are determined by the specified External Column Name.

In Indirect lookup relationship, Salesforce standard or custom object will be the parent and External Object will be the child.

External lookup relationship :
=====================
External lookup relationship links a child standard,custom or external object to a parent external object.

The values of the standard External ID field on the parent external object are matched against the values of the external lookup relationship field.For a child external object, the values of the external lookup relationship field come from the specified External Column Name.

In External lookup relationship, External Object will be Parent.

Sunday, 11 August 2019

OAUTH AUTHENTICATION IN SALESFORCE


OAuth endpoints are the URLs that you use to make OAuth
authentication requests to Salesforce. When your application
makes an authentication request,make sure you're using the
correct Salesforce OAuth endpoints.

The primary endpoints are :

Authorization : https://login.salesforce.com/services/oauth2/authorize

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

Revoke : https://login.salesforce.com/services/oauth2/revoke



OAUTH 2.0 Web Server Authentication Flow :
===========================================
1. Request Authorization Code
 
   https://login.salesforce.com/services/oauth2/authorize?
    client_id = consumer key &
redirect_uri=call back Url
response_type=code

 The response_type is code , indicating that we are using the authorization code grant type.

 your application directs the browser to the Salesforce Sign-in Page.where the
 user authenticates.

 The browser receives an authorization code from your salesforce authorization server.

 The authorization code is passed to your application.

 https://localhost:5001/salesforce/callback?code=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

 Your application sends this code to salesforce, and salesforce returns
 access token and optionally a refresh token.

 https://login.salesforce.com/services/oauth2/token?
   client_id     = consumerkey &
   client_secret = Consumer secret &
   redirect_uri  = callback_url    &
   grant_type    = authorization_code &
   code          = authorization code
 
 grant_type is authorization_code,indicating that we are using the
authorization code grant type.

code is the authorization code that you got from the /authorize endpoint.

 If the code is still valid ,your application will receive back access token.

 {
   "access_token": "eyJhbG[...]9pDQ",
    "token_type": "Bearer",
    "expires_in": 3600,
   "refresh_token": "eyJhbG[...]9pDQ",
   "instance_url": "https:n57.salesforce.com"
 }
 

 your application can now use these tokens to call the resource server(Salesforce)
 on behalf of user.

 Note :
 1. This flow is mainly used by applications hosted on web server.
 2.This flow is not recommended for application (like ETL or middleware's)
 which will access salesforce using APIS's and no UI is involved.
 3.This flow uses a client secret (CS) as an extra authorization
 parameter to prevent spoofing servers.
 4.This flow should be used for any serever/cloud applications.


 OAUTH 2.0 User Agent Flow :
 ===========================
 1. your application directs the browser to the Salesforce sign-in Page,
 where the user authenticates.

 https://login.salesforce.com/services/oauth2/authorize?
   client_id= consumer key &
   redirect_uri = callback url,
   response_type = token

 2.Salesforce redirects the browser back to the specified redirect URI,
 along with access token as a hash fragment in the URI.

 http://localhost:8080/#access_token=eyJhb[...]erw&token_type=Bearer&expires_in=3600

 {
   "access_token": "eyJhbG[...]9pDQ",
    "token_type": "Bearer",
    "expires_in": 3600,
   "refresh_token": "eyJhbG[...]9pDQ",
   "instance_url": "https:n57.salesforce.com"
 }

 3.your application extracts the token from the URI.
 4.Your application can now use these tokens to call the resource server(salesforce)
 on behalf of user.

 Note : This flow is recommended when you build mobile
 and desktop application.

 The benefit of the flow is that salesforce issues a refresh token,
 meaning that even when your access token expires, you are able to
 obtain a new one by executing the refresh token flow.

 It allows a user to authenticate to a partner application
 using their salesforce login credentials.

 OAUTH 2.0 JWT Bearer Token Flow :
 =================================
 External application send request for access token by passing
 JWT token in body. SFDC server validate JWT and return access
 token to external app.

 This flow requires you to upload a certificate to your connected app
 that will be used to validate the JWT token.

 JWT token is basically a JSON file consisting of a header and
 claims object, where header contains the signature algorithm
 and the claims object contains specific information such as the
 username and consumer key.

 At the high level, you will then sign the JSON object with the Private
 key of your certificate and send the JWT to salesforce to obtain
 an access token.


 https://login.salesforce.com/services/oauth2/token
     assertion = JWT token
grant_type = urn:ietf:params:oauth:grant-type:jwt-bearer

{
   Header { "alg":"RS256"}
   Claims {
      "iss" : issuer= consumer key,
  "sub" : subject= username,
  "aud" : audience = login url (login.salesforce)
  "exp" expiry=epoch=Now+5 min
   }

}
 1.Base64url encoded the Header and JWT claims Set.
 2.Chain them divided with a "."
 3.Create a Signature by Signing the resulting string using SHA256 with RSA.
 4.Chain resulting string with signature divided with "."
 5.JWT is done

 Note :
 No refresh token is returned in this flow. So if access token
 expires then send request to generate access token again.

 OAUTH 2.0 SAML Bearer Assertion Flow :
 =====================================
 Important pre-requisite is that the connected app in salesforce
 has a certificate uploaded who's private key is used when signing
 the assertion.

 A SAML assertion is an XML security token issued by an identity provider
 and consumed by a service provider.

 if your organization uses a central access control such as an active
 directory or LDAP store, it is likely that you would SSO to authenticate
 to your application.

 In this scenario , you may also want to use the SAML assertion
 from your SSO flow to obtain an access token to salesforce.

 This flow takes the SAML assertion (an XML token issued by your IDP)
 and applies a digital signature to it using a certificate.

 https://login.salesforce.com/services/oauth2/token
        assertion = SAML assertion Base64 encoded
grant_type = urn:ietf:params:oauth:grant-type:saml2-bearer


{
  issuer = client_id
  audience=https://login.salesforce.com
  recipient = https://login.salesforce.com/services/oauth2/token
  subject = username
 
}
   
 The assertion must be signed according to the XML Signature specifications,
 using RSA and either SHA-1 or SHA-256.

 Note :
 This flow also return only access token not refresh token.

 SAML Assertion Flow :
 ========================
 Use the OAuth 2.0 Token endpoint when accessing Salesforce via the API using SAML.
 you can use the SAML assertion flow only inside a single org.
 you don't have to create a connected app to use this assertion flow.

 https://login.salesforce.com/services/oauth2/token?
      assertion_type = urn:oasis:names:tc:SAML:2.0:profiles:SSO:browser
  grant_type     = assertion
  assertion = SAML assertion
If you have SSO configured specially for the Salesforce org that your partner
application is authenticating to, you can also use SAML Assertion Flow.

The benefit of this flow is that you can use a Base-64 encoded , then URL encoded,
SAML assertion that is normally used for web single sign-on.
 


Note :
No refresh token is issued in this flow.

OAUTH 2.0 Username and Password flow :
======================================
The OAUTH 2.0 Username and Password flow quite simply issues an
access token in exchange for a username and password.

https://login.salesforce.com/services/oauth2/token
      client_id = consumer key
  clent_secret = secret
  grant_type = password
  username   = testUsersalesforce.com
  password  = mypassword
 
Note :
No refresh token is issued in this flow.
Avoid using this flow because you have to send username and password
un-encrypted to salesforce.

OAUTH 2.0 Refresh Token :
========================

https:login.salesforce.com/services/oauth2/token
       client_id = consumer key
       grant_type = refresh_token
       refresh_token = your token here
To obtain a new access token from a refresh token use the
OAUTH 2.0 Refresh token flow.

The OAuth 2.0 refresh token flow renews tokens issued by the
web server or user-agent flow.

Note
when a user is logging out of your application you can revoke
tokens by using "/revoke" endpoint.

https://login.salesforce.com/services/oauth2/revoke?

 token = access token

OAUTH 2.0 Device Authentication Flow :
=======================================
 It should be used when you want to allow access to salesforce
 for an application that runs on a device with limited capabilities.

 ex: Tv,IOT devices and connected aircon etc.

 In this flow device is requesting a "device" and "User" code from salesforce.

 https://login.salesforce.com/services/oauth2/token?
       client_id = Consumer Key
   response_type=device_code
 
 response_type : Value must be device_code for this flow.

 The user code should be displayed alongside the verification_url
 that is returned by salesforce.
{
 "device_code":"M01WRzlQaFI2ZzZCN3BzN1RUSTRjUDdNcHBnM2w3dHUuTVJBWVVMeVZxY21BOWhHTHBIaWlTLlE3ck​85eWpsbWZmaUJVTTZ0RnBZQWxYRWtSakhiOTsxMC4yMi4zNC45MjsxNDc3Njc0NDg3NTA1O1gxRDlTRUVU",
 "user_code":"X1D9SEET",
 "verification_uri":"https://acme.my.salesforce.com/connect",
 "interval":5
}

 The user working with a device navigates to the displayed URL
 on their mobile or laptop and enter the user code that was provided.

 They then log into salesforce and approve access to the application.

 https://login.salesforce.com/services/oauth2/token?
       grant_type = device
   client_id = consumer key
   code = device_code

code : should be used device_code which you got in previous response.

In the meantime ,the application running on the device should keep
polling salesforce (polling interval is also returned by salesforce)
and once the user has approved access,the application on the device
will get an access token is used.

{
"access_token": "00DD00000008Uw2!ARkAQGppKf6n.VwG.EnFSvi731qWh.7vKfaJjL7h49yutIC84gAsxM​rqcE81GjpTjQbDLkytl2ZwosNbIJwUS0X8ahiILj3e"
"refresh_token": "your token here"
"signature": "hJuYICd2IHsjyTcFqTYiOr8THmgDmrcjgWaMp13X6dY="
"scope": "api"
"instance_url": "https://yourInstance.salesforce.com"
"id": "https://login.salesforce.com/id/00DD00000008Uw2MAE/005D0000001cAGmIAM"
"token_type": "Bearer"
"issued_at": "1477674717112"
}

OAUTH 2.0 Asset Token Flow :
=============================
Client applications use the OAUTH 2.0 asset token flow to request
an asset token from Salesforce for connected devices.

This flow requires the device to obtain an access token (in any of the above ways)
and use this token alongside additional information to create an actor token.

This token contains valuable information about the asset which is then send to salesforce
where it is exchanged for an asset token.

Subsequent requests to protected resources at salesforce
can then be made with the asset token.

   

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.