Wednesday, 29 December 2021

MFA (Multi-Factor Authentication) in Salesforce

 There are two ways to set up MFA in Salesforce:

1.Profile Settings

2.Session Settings

Note :

To enable MFA via session security levels, which is not recommended due to the risk of breaking API integrations or connections.

Profile Settings (recommended) :

You can set a profile setting either with a profile or with a permission set. If you set via a profile, 

all users with that profile will be required to use MFA. If you set via a permission set, 

you can manage which users get MFA and develop a rollout strategy.


To set this, open the profile (or permission set) and open the System Permissions. You can select the Multi-Factor Authentication 

for User Interface Login setting and mark it to True. Do not select the Multi-Factor Authentication for API Logins setting.


Session Settings (not recommended) :

You can set the session settings with two steps:

In Setup ⇒ Session Settings, you can move Multi-Factor Authentication to the "High Assurance" category for Session Security Settings.

In Setup ⇒ Profile ⇒ Session Settings, you can set a profile to require high-assurance settings when logging in.

This is not recommended because it can break API use and logins. Contrary to the Profile Settings method described above, this will require MFA on all logins, including for accounts used for an API Integration or Connected App.

Dedicated Integration Users

Salesforce will not require MFA for API Only users, so if you use a dedicated API User, these steps won't be relevant.

Note :

If you're setting up MFA for a client, we recommend using the System Permissions rather than the Session Settings. 

If a client's API integration suddenly starts failing (with an error such as "Response content: 

[{'message': 'This session is not valid for use with the REST API', 'errorCode': 'INVALID_SESSION_ID'}]" or similar), verify if the session settings have changed. 

MFA Solutions for Salesforce :

MFA is useful to provide an increased level of security to your system, as well as effective ways to help prevent unauthorized account access.

Salesforce supports these types of verification methods

1.Salesforce Authenticator mobile app  : Fast free authentication sfdc.co/IntrotoAuthenticator

2.Third-Party Authenticator App        : Such as: Google Authenticator, Microsoft Authenticator, Authy

3.Security Key                         : Such as: Yubico’s Yubi Key Google’s Titan Security Key 


Not Supported below option

1.SMS (Text) verification : 

Two-factor authentication by SMS is a less secure option, and is available to use only with communities, partners, and customers.

Contact Salesforce Customer Support to enable.

2.Phone call verification

3.Email verification


Email, SMS text messages, and phone calls aren’t allowed as MFA verification methods because email credentials are more easily compromised, 

and text messages and phone calls can be intercepted.


Important: While MFA will not be mandated in Salesforce Communities, if you do implement MFA in communities, SMS is an option for verification.

How is this different than when I log in on a different browser?

There are two types of identity verification in Salesforce, service-based and policy-based security. 

Whenever we log into Salesforce from a different browser or from a new computer, we must provide verification of our identity. 

This is called service-based identity verification, which is available out-of-the-box. 

Now, with MFA, you can add a new layer of security on top of it with policy-based identity verification.

Service-based (device activation) :

 -> Auto enabled for all orgs

 -> User must provide verification from unrecognized browser or application

 -> Not considered as part of MFA (insecure)

Policy-based (MFA) :

 -> Admin enabled

 -> Multi-factor


What should you keep in mind with MFA?

Here are several things to keep in mind when rolling out MFA.

What are the System Permissions related to MFA for user interface logins?

Multi-Factor Authentication for User Interface Logins :

Require users to provide an additional verification method in addition to their username and password when logging in to Salesforce orgs.

Manage Multi-Factor Authentication in User Interface :

Use tools in the user interface to manage and provide user support for multi-factor authentication.

What about MFA for API logins?

API logins are not currently part of Salesforce’s mandate to use MFA. 

What happens if a user loses or forgets their device?

Admins can generate temporary verification code that can be set to expire 1 – 24 hours by adding the Temporary Code field to a User list view and clicking "Generate".

Sunday, 19 December 2021

Salesforce : RowCause in Share object

 RowCause is the reason why the share exists. There are a large number of reasons why shares may exist. 

A non-exhaustive list of standard shares are as follows:


Owner             - The user in OwnerId

Manual            - A manual share from the UI or code

Rule              - A sharing rule created this entry

ImplicitChild     - A parent record shares access with its children

ImplicitParent    - A child record shares access with its parent

ImplicitPerson    - Person Account Sharing (?)

Team              - The user is a member of a team (AccountTeam, OpportunityTeam)

Territory         - The user is in a given territory

TerritoryManual   - The record was manually shared to a territory

Territory2AssociationManual - The record was manually assigned to a territory

TerritoryRule     - A territory rule shared the record

Territory2Forecast - Territory forecasting calculations shared the record


Only manual shares and custom shares can be created, modified, and deleted, although some shares can also have their AccessLevel fields modified (e.g. Team sharing entries). 

All of the others are generated by the system based on sharing calculations. 

For example, the user specified by OwnerId automatically gains a sharing entry for Owner. 

You can't remove this entry because they own the record. Likewise, you can't add a new Owner this way. 

Instead, you would change the OwnerId field, and the system recalculates the Owner sharing entries based on that change.


I may have a few descriptions not quite right, and there may be some missing options; 

I simply pulled these values from the describe for the RowCause field and extrapolated based on my knowledge of Salesforce.

There's a lot of information about these various sharing settings in the documentation, but they're spread out across many topics. 

You'll want to do more research on it.


For anything other than manual shares, you must correct the situation that caused the share. 

For example, if the share reason is Team, then you must delete the appropriate AccountTeamMember or OpportunityTeamMember record.

Sunday, 21 November 2021

Salesforce Marketing Cloud Basics

 


Marketing Cloud Enables you to communication with your customers utilizing an omni-channel strategy.

This Platform allows you to capture data, connect to your CRM and personalize each touch point.


Marketing Cloud is a sophisticated marketing automation tool that enables a business to communicate with their customers across channels they prefer.

These channels include email, text, push notification, ads, and web experience. Marketing Cloud enables this communication, but also enables you to automate when and on what channels your customers will receive these touchpoints.


Super Messages :


They are simply the way that Salesforce keeps track of the customer‑facing messages or experiences that come from Marketing Cloud. 

Each customer likely does have a different volume of messages as this varies based on their tier of purchase and also how many messages you plan to send out and what channels.


Well, the number of Super Messages is really going to vary based on the location of your subscribers, but let's say that we're sending out to only people in the United States. 

The cost of one SMS message in the United States is currently 10 Super Messages. 


So in our example, after we send out this message to the 10,000 audience, we've sent out 1000 SMS messages, but it's incremented up to 10,000 Super Messages. 

It's really important you monitor your sending behaviors throughout the year, and also, look into how many Super Messages you have in order to stay within your limits, and if you need to, purchase more throughout the year.


Marketing cloud Automation :


Marketing automation is technology that manages marketing processes and multifunctional campaigns, across multiple channels ,automatically.


What does Marketing Automation do ?


1.Messaging


Marketing automation allows you to communicate with your customers across multiple channels.

  (or)

Communication across multiple channels. 

 

2.Automation 


Automate when and what channel you send messages.


How does Marketing Automation affect my business ?


1.Grow your business 


Increase your volume, conversion and ROI


2.Customer Experience


Create more satisfied customer with your brand.


Studio's and Builders :


Within Marketing Cloud, there are two different types of apps, studios and builders.


Studios :


Apps that enable you to create messages that your customers interact with.


Email Studio 


Email Studio is used to develop email templates, messaging, and personalization that can send your customers.


Mobile Studio


Mobile Studio, which is where you can build and send SMS and push notifications and chat app messages across your channels.


Interaction Studio


Interaction Studio, which enables real‑time orchestration of content across channels and also provides next best actions to customers.

 

Social Studio 


Social Studio is a listening, publish, and engaging platform that enables you to manage your social media accounts such as Facebook and Twitter.


Advertising Studio


Advertising Studio uses your first‑party data to securely build a one‑to‑one advertising campaign across multiple social channels such as Google, Facebook, LinkedIn, Twitter, and Pinterest.


Automation Studio


Automation Studio, which is where you're able to build the automation of your messaging to your customers across multiple channels. 


Builders :


Apps that are used to build the piping,automation,track how everything is permorming.


Journey Builder


Journey Builder is where you pull all of this cross‑channel communication and messaging together, so that you can orchestrate the lifecycle of a customer's experience.


Analytics Builder


Analytics Builder, which is used to track how those communications are performing and gain insights into how your customers are behaving.


Contact Builder


Contact Builder is the ability to store data from multiple sources and stitch it together, and it is the app that is used to segment and personalize your data.

 

Datorama


Datorama, which is a cross-platform marketing intelligence tool.


Content Builder


Content Builder, which is where you store your assets, develop your email communication, and develop your templates to scale across all of your communication.


Foundational Elements of Marketing Cloud :


1.Business Units

2.Users & Roles 

3.Sending Reputation

4.Data


Business Units :


Business units are a way to control how information is shared across Marketing Cloud. 

This provides you the ability to manage data control and brand separation inside of your single instance of Marketing Cloud.


Note : 

it's really important that before creating new business units, you map out the intended structure based on your organization.


Users & Roles :


They are a collection of permissions you have access to within marking cloud which make up the type of role you'll perform. 

Currently, there are 10 standard roles that are a good start to separate out the levels of access of people requirements. 


Some examples of these standard roles include system admin, data manager, analyst, content creator. 

My suggestion is always being with the standard roles and determine if there are any gaps you need to separate out your users permission above the standard roles.


sending reputation :


Sending reputation is one of those elements that can be easily overlooked as you think about building a solid marketing cloud foundation, 

but it is one of the most essential elements you need to understand.


Sender reputation is how the world's ISPs(Internet Service Providers) see your email communication, is it legit, is it spam? Should I put it in the main inbox or file it away into promotions? 

When you start with a new brand and a new instance, you have a very neutral reputation. You have a fresh new IP, which is your company's address on the open web.


As you begin to send email communication, the type of content, higher customers react to that message, will begin to build a positive or negative reputation. 

Prior to sending any communications though, you need to set up your sender authentication package, which is a package that pulls together your IP address in your domains. 

The sender authentication package, as I mentioned before, is made up of two big elements, IPs and domains. Each instance has an IP address. 

It's most common to have a dedicated IP address, but in some cases you may have a shared one with a few other accounts depending on your limited volume. 

On the other side, you have domains, which will be used to link what will be shown in your emails in the landing pages and images to your brand and your SAP(Sender Authentication Package) package.


Data :


1.sources


This is where the data is stored in Marketing Cloud. In most cases you'll be utilizing data extensions 

which are a flexible way to store small and large data that can either be your customers directly or information about them.


2.inputs


Inputs are how the data gets into Marketing Cloud, this typically includes out-of-the-box integrations with Sales Cloud, but can also include APIs and FTP integrations to bring new data into Marketing Cloud.


3.Automation


Once you have your data in Marketing Cloud, you typically need to transform or segment it in some way to get to the right audience, 

that's where queries and filters come into the picture.


Salesforce Marketing cloud Security,Compliance and Governance :

==============================================================


Security :


Within security, there are three main categories.

1.Logins


This includes your information for your login, your FTP information, but it also includes the settings you have inside of your instance. 

How long it takes an account to log out when you've logged in and it's been idle. Do you have SSO set up? Is there an authenticated app in play here?

Ensuring that you have your security standards set up correctly for logins can prevent a lot of miss access of data.


Note : Timeouts SSO and Authenticated Apps


2.Data


we have data, which includes data encryption, how that data is accessed through business units, and import and export of data. 

Data is the key of your business, so it's really important to understand what are the compliance requirements of your industry and, also, 

how are you going to keep that data secure?


Note : Data Encription,business units and access.


3.Landing Pages


Because Marketing Cloud has a capability to display landing pages on the open and public web, 

you need to make sure that how you're displaying that information, what type of information, 

and how you capture information about your customers is set up properly so that the information is secure in that transfer.


Note : Secure display and capture of data from the web.


Roles :


1.Marketing Manager 


At the top of the list, you have our Marketing Manager. This person is responsible for directing the team where they're going to be heading and bringing the requirements to the table to define what is being built in Marketing Cloud. 


2.Marketing Cloud architect


Marketing Cloud architect who is responsible in finding how the overall solution will be constructed based on the business requirements.

Key activities include defining how data will be used in the platform, building for scale, and ensuring the proper use of platforms, and so much more.


3.Content Manager


Generally, the Content Manager is responsible for asset creation and will bring the email from concept to life.


4.Data and analytics analyst


Data and analytics analyst will work in tandem with the Content Manager to build up the necessary filters, transformations, and ensure the company is sending to the right audience.


5.Marketing Cloud Developer

 

Marketing Cloud Developer role is critical as you begin to mature your communication and begin to bring personalization that will require AMPscript into life.


Governance Models :


There are a lot of different types of governance models in the world. For marketing automation, I've seen three typical models that have been developed in order to really provide the scale you need for your instance. 


1.Hub and Spoke


Hub and spoke, which is a centralized methodology where the best practices are centralized, but the resources are distributed.


2.Centralized


where our centralized resources really do live in a single team and support the multiple lines of business and business units across the entire corporation.


3.Multi-hub and Spoke model


This is essentially a large scale distribution model of the hub and spoke, but depending on the complexity of a business, this may extend further and further out.


Common compliance regulations :


CAN-SPAM, CASL, GDPR and others.

Saturday, 20 November 2021

Salesforce Territory Management

 Territory Management is a tool for sharing account records with users.


Territories organized by specific criteria.


Orgs can increase Sales and lower costs.


Territory Types are used to categorize territories.


Territory Models offer way to preview/test strategy.



Role Hierarchy vs Territory Management :


Role hierarchies are great for representing your organization's entire management structure, but each user will be assigned to one role.


A territory hierarchy however, is just specific to managing sales territories. In this structure, you can have one salesperson assigned to multiple territories.


Territory Management :


Territory Management starts with an account record.

Territory Management revolves around an account record.

Each account record is typically associated with one or more contact records, along with cases and opportunities.


Default Access Levels :


Territory Management is not enabled by default, but in addition to enabling this feature, you will also need to configure access to certain data objects.

That being said, it is important for you to realize that for account records, you will need to configure access that allows users to either view an account, or view and edit an account, or view, edit, transfer and delete an account record.


Since territory management revolves around an account record, any objects that are associated with an account, such as a contact, well, these will be configured a little differently. 

And most importantly, which associated objects needs to be configured will depend on how you have defined the org-wide defaults or sharing settings in your org.


You also have an option to allow users to view any related contacts or view and edit related contact records, and these default access options apply to any related account objects, and that includes cases, as well as opportunities.


Opportunity Territory Assignment :


One optional configuration option you need to be aware of involves access to opportunities that are associated with a parent territory.

Territories can be organized into a hierarchy, and there can be one parent territory that is associated with multiple children territories.

It is possible for there to be opportunities that are assigned to some of these children territories, and when configuring access, you have the option of determining what kind of access to these children is allowed.


Opportunity Territory Assignment allows you to optionally Enable Filter-Based Territory Assignment. 

Salesforce does provide some Apex code that you can modify to suit your needs, but this is really an edge case that most orgs will never utilize.


Note :

When Contact sharing is set to 'Controlled by parent', access to the Contact is the same as access to the Account.


Account Territory Assignment :


To avoid performance issues during account inserts, turn assignment rules off.

When your account insert job is finished, turn assignment rules back on.



Territory Type :


Territory types help you categorize and define individual territories. Creating territory types is the first step in building your territory model in Salesforce.


Territory Model :


When it comes to creating a new territory, each territory will need to be associated with both a territory type and a territory model.

The Territory model is used to connect a territory with user and account assignments.

Each territory model will always be in one of the following states.

1.P1anning

2.Active

3.Archived


By default, each new model begins in the planning state.

Once a model is well defined and previewed, it can move to an active state.

There is always the option of moving a once active model to an archived state.


One of the big benefits of Territory Management is that a sales team can define up to four different territory models; however, only one of these models can be in an active state.


Territory Hierarchy :


The territory hierarchy defines a model’s territory structure and serves as its main point of interaction.


Collaborative Forecasts :


Collaborative forecasting is a tool that quite simply provides a prediction, or forecast, of future sales.

It all revolves around the Opportunity object, which, as you know, is one of the objects impacted by territory management.

Forecasting involves working with multiple factors like what time period is involved, what kind of revenue is expected, and what kind of adjustments might need to be made, things like that.


Note : Territories must have a forecast manager assigned.


Summary 


1.Territory Management must be enabled and default access defined.

 --> Access levels available depend on OWD

2.You  can have four different territory models, but only one will be active.

3.A territory hierarchy can be nested and should not duplicate your sales structure.

4.Enable Customizable forecasting.

 --> You will need to enable Customizable Forecasting, and any territories you create should have a forecast manager assigned.



Territory Assignments :


1.Territory Assignments are actually a few things that can be assigned to a territory.

2.Accounts are the main thing you will assign.

3.And even though accounts are owned by users, which by default means that if an account is assigned to a territory, well, 

so is the user that owns it; however, you can also assign salespeople that operate in a specific territory to that territory 

regardless of whether they own any accounts that are assigned to it.

4.Opportunity Territory Assignment setting allows you to assign opportunities to territories.

5.One or more assignment rules can be assigned to a territory.


ways to handle Territory Assignment :


When it comes to assigning territories, we have two ways to do this.


1.Assignment Rules

2.Assign manually


Assignment Rules :

Assignment rules, which you can be assigned to a territory, are the automated way to make this happen.

Assign Manually :

You have the option of assigning one or more territories manually to an account, and this includes users, opportunities, and even assignment roles.

 

The Territory models include a territory hierarchy.

This hierarchy can be nested, and parent territories can be associated with multiple children territories. 

It is important to realize that a parent-to-child relationship exists for these hierarchies, and children will inherit the sharing access of their parents if that is configured so.


Note : 

Salesforce does offer a granular locking feature that enables organizations to lock a portion of records and not an entire group maintenance table 

when certain events take place, for example, events like adding and deleting territories or even just adding or moving users from a territory.


View and Manage Assignment Rules :


what permissions allow users to view and manage territory assignments?

1.Manage Territories

2.View Setup and Configuration


Assignment Rules :


Define criteria used to select accounts

- Amount of company revenue

- Number of employees

- where company is located

- what industry they belong to

Limit to 10 criteria fields

-You should know that these rules are limited to no more than 10 criteria fields.


when an assignment rule is assigned to a parent territory, you have an option to have it automatically applied to all children territories. 

Applying a rule to children territories from the parent territory is actually considered a territory management best practice.


Manually Assigned Accounts :


why Manually Assign Accounts?


There are always special considerations that need to be made, and manual assignments could be thought of as a workaround.

It is also possible to assign an account to more than one territory, and a manual assignment may be the best way of accomplishing that.


Manually Assigned Users :


When it comes to territory assignments, accounts that are assigned to a specific territory are assigned independently of any users that are assigned to that same territory. 



Note : Assignment rules must be run before account sharing rules are applied.


Any users assigned to that territory will automatically have access to the account regardless of whether they own that account or have been granted access through some other way.

 

Run Assignment Rules :


When it comes to running rules for any territory model, that model can be in either an active or a planning state.

You can essentially preview which accounts will be assigned to which territories before you actually activate that model.

Remember, you can have up to four different models, but only one of those models can be active.


Note : Just don't forget that previewing assignments should be done in a full sandbox before running or activating a model in a production org.


Just don't forget when creating new rules that the assignment will not happen until the rule has been assigned to a specific territory. 

It would be very easy to forget this step and not understand why the assignments were not happening.


Summary :


Territory Assignment includes 

Accounts, users, Opportunities(may be), Assignment rules

Territories assigned using rules or manually.

Territory updates can result in record locks.

--> Large orgs should plan very carefully.

Children territories can inherit rules from a parent.

Users that manage territories need :

--> Manage Territories

--> View Setup and Configuration

Assignment rules can be run when model is in planning or active state.

--> Rules must first be assigned to at least one territory.

--> Best practice is to apply to all children.

Sunday, 31 October 2021

SALESFORCE LIMITATIONS AND BEST PRACTICES

 Sharing Rules :


The limit is across both Standard and Custom Objects as 300 Maximum rules with 50 Criteria Based rules on Enterprise and Unlimited/Performance Editions only.

You can create up to 50 criteria-based sharing rules per object.


Note :

On an object where the OWD setting is 'Controlled by Parent' you will not be able to set up sharing rules, so you need to change this, 

e.g. On Contact to either 'Private', 'Public Read only' or 'Public Read/Write' to add sharing rules on this specific object.


As a best practice, keep the number of ownership-based sharing rules to 100 per object, 

and keep the number of criteria-sharing rules to 50 per object.



Note : 

1.Removing an Account team member doesn't remove an Opportunity team member.

2.Know that platform out of the box 'implicit' sharing doesn't apply to Apex sharing.

3.You can create up to 10 Apex sharing reasons per custom object.


Not Possible with permission set :


The only things that must to be controlled by Profiles and can't be structured in Permission Sets are:

Page Layout Assignments

Desktop Client Access

Login IP Hours

Login IP Ranges


Saturday, 30 October 2021

runAs method in Apex Test Classes

 1.RunAs will use the record sharing view-ability of a record when viewing. It doesn't respect user permissions or FLS.

2.You can only use RunAs in test methods, and it doesn't respect user license limits.

The runAs method ignores user license limits. You can create new users with runAs even if your organization has no additional user licenses.

3.RunAs can be used for mixed DML exceptions that would normally occur.

4.RunAs can take a package version as an argument.


ex :

      // Run test as managed package version 1.0

      System.runAs(new Version(1,0)){

          try{

              insert o;

          }

          catch(System.DMLException e){

              System.assert(false, e.getMessage());

          }

      }

Salesforce Implement Sharing and Data Skews

 


Implement sharing is defined and maintained by the system.


1.Parent 

2.child

3.Portal

4.Case

5.Share Groups (High Volume)


Parent Implicit Sharing :


'Parent implicit sharing' provide read-only access to parent records(Account only),

when user has access to children record,such as : Opportunities,Cases,or Contacts for that account.

This does not mean the user must be the record owned of the child ecord.


(or)


The Parent Implicit sharing provides read-only access to parent record if the user 

is having access to the child record.


Note :


Only affects Account to Case, Contact and Opportunity.

Account = private and Child !='Controlled by Parent'

As soon as a user has atleast Read access to a Case,Contact or Opportunity the user has Read access to the related Account.


Child Implicit Sharing :



Child Implicit Sharing is ability for Account owner to access child records (contacts, opportunities, and cases),even they are not owned by Account owner. 

The account owner's role determines the level of access to child records (read-only or read/write).



The child Implicit sharing provides Read/Write access to child record if the user is the owner of the parent record.



Access to child records for the owner of the parent account.

Not used when sharing on the child is 'Controlled by Parent'.

Controlled by child access settings for the account owner's role.

Supports account sharing rules that grant child record access.

Supports account team access based on team settings.

When a user loses access to the parent, Salesforce needs to remove all the implicit childern for that user.


Note :

Only affects Account to Case, Contact and Opportunity.

Only affects Account Owner.

Each role independently can define whar child-record access the Account Ownership provides. 


Portal Implicit Sharing :


Portal Implicit Sharing will provide Read-only access to portal account 

and all associated portal user's contact record using portal role sharing.


Access to portal account and all associated contacts for all portal users under that account.

Shared to the lowest role under the portal account.


High Volume Portal Implicit Sharing :


In this Implicit sharing any record owned by high volume portal users will be shared 

with other high volume users who are part of sharing set.


High Volume Parent Implicit Sharing :


In this implicit sharing, read only access will be given to parent account 

of records shared through a sharing set to other user members.



Controlled by Parent vs  Implicit Sharing :


Note : Controlled by Parent isn't the same as Implicit Sharing.


Implicit Sharing :


Implicit Sharing is when a user gains access to a child record and also gains read-only access to the parent.

e.g. a contact is assigned to a user, and thus gains read-only access to the account.

Implicit sharing only has an effect when the parent object is Private and the child is not Controlled by Parent


Controlled by Parent :


Controlled by Parent, in contrast, grants read or read-write access to the child records when access is granted to the parent. 

It has an effect in all parent share modes (private, read-only, and write).


Using Controlled by Parent will decrease row lock time on the parent, but not eliminate it. 

There has to be a lock on the parent while the children are being updated. 

Controlled by Parent will increase performance because there's no child share table while in this mode 

(the children's access is checked using the parent's share table).


Case share  :


If a portal or customer community plus user is a contact on a case,then the user has read and write access on the case.


The contact for a Case has Read & Edit Access on that Case.

Only affects Partner and Community Plus Licenses.

Community License Users need Sharing-Set.


Share Group (High Volume) :


Access to data owned by high volume users associated with a sharing set for users member of the sharing set's access group.


All members of the sharing set access group gain access to every record owned by every high volume user associated with that sharing set.


profile : Customer Community


Record Ownership by User is necessary.

Affects(almost?) all objects.

Record Owner needs Profile in share Set.

Any Record owned by a profile mentioned in the Share Set is shared with any user mentioned in the related share group.


Record Locks & Skews :

======================

Record Locks can happen


1.Business-related 

  Defined by business process and implemented intentionally (e.g.Approval Process,read-only record types).

2.System-related 

  Done by Salesforce, available and implemented out of the box (cannot be changed)


System Related Record Locks :


Quality of a database is often measured by its data integrity:

1.Data accuracy

2.Data Completeness

3.Data consistency


One measure by Salesforce (and many other databases) to maintain data integrity is to place record locks on records(and their parent records)

while they are being edited.


Note :

A given transaction can only wait a maximum of 10 seconds for a lock to be released,

otherwise it will throw and UNABLE_TO_ROW exception.


Data Skews :


In a database, a skew refers to a situation in which there is an uneven distribution of data.


Data Skews in Salesforce 


In salesforce, data skews happen when records relate to one another and child records are unevenly distributed across the parent records.

They will typically result in performance issues.


There are three kinds of data skews that can occur :


1.Account Skew

2.Ownership Skew

3.Lookup Skew


Lookup Skew :


Lookup Skew happens in object relationships when a large number of child records are associated to one parent record.


When a child record is inserted or updated, Salesforce locks the parent record the child will be associated to in order 

to maintain data inegrity.When you work with large data, and there are processes (e.g. custom code, automated processes, integrations)

you can easily run into lock contention.


Lookup skews happen in lookup relationships AND master-detail relationships.

Lookup skews can effect standard AND custom objects.


How to identify a Lookup Skew :


There is no exact identifier by which you will be able to identify a lookup skew .

Don't wait until somebody complains, try to address to problem right away.


Take a look at the following 


1.Objects with a lot of records.

2.Objects where a lot of inserts and updates happening in parallel.

3.Objects where you get complaints about locks from users.


How to avoid Lookup Skews?


1.Reduce Record Save Time (Apex Best Practices,Asynchronous Processing,Consolidate Automation).

2.Picklist fields.

3.Distributing the skew.  

4.Reducing the load (Serial loading, order by Parent Id and chunk the data carefully).


Account Skew :


An Account Skew arises, when a large number of child records (>10,000) are related to a single account.


There are two main problems that can be caused by an Account Skew:


1.Record Locking

2.Sharing Problems


Account skew - sharing problems 


Sharing problems arise because of Salesforce built-in parent implicit sharing.

(Users with access to contacts,cases and opportunities get read access to the related account).


If sharing of a child record of a certain object is updated, Salesforce will have to check all other 

children of that object to check, if the implicit share for the Account can be removed.


Depending on the amount of childern, the recalculation can take long and will cause performance issues.


During the whole operation, a lock is placed on the account preventing other from editing it.


How to avoid Account Skews?


Limit the amount of Account Children per object to 10,000.

If you need generic Accounts, create a pool of accounts and use a round robin algorithm to distribute them.

Consider setting the Account OWD to 'Public Read/Write'(The record locking 


Ownership Skew :


An ownership skew happens, if a single user owns more than 10,000 records of one object.


Performance issues caused by an ownership skew will most typically appear in large organisation where 

data chnages that require sharing recalculation happen frequently. These changes could happen on :


Ownership based sharing rules

Record ownerships

Group members/ Role Hierarchy


How to avoid Ownership Skews?


1.Ensure that the 'Skewed' owner is not part of the role hierarchy or put them in a role 

at the top of the hierarchy/ within its own branch.

2.Don't move the user into another role/move the role within the role hierarchy.

3.Keep the user out of public groups used for sharing.

4.For organization wide sharing, review OWDs(is private necessary?)



In Overall to avoid DataSkew :


Avoid Large number (>10,000)of child records in master/Detail relationship 

Avoid Large Number of records owned by one user

Avoid RecordLocking

Wednesday, 27 October 2021

Lightning Web Component Navigation Service

 The navigation service adds two APIs to your component's class. Since these APIs are methods on the class, invoke them from this.


1.[NavigationMixin.Navigate](pageReference,  [replace])

A component calls this[NavigationMixin.Navigate] to navigate to another page in the application.

ex :

navigateToObjectHome() {

        // Navigate to the account object home page.

        this[NavigationMixin.Navigate]({

            type: 'standard__objectPage',

            attributes: {

                objectApiName: 'Account',

                actionName: 'home'

            }

        });

    }


2.[NavigationMixin.GenerateUrl](pageReference)

A component calls this[NavigationMixin.GenerateUrl] to get a promise that resolves to the resulting URL. 

The component can use the URL in the href attribute of an anchor. 

It can also use the URL to open a new window using the window.open(url) browser API.


ex :


recordPageUrl; // variable to be associated to anchor tag.

 

// Generate a URL to a User record page

generateURLforLink() {

    this[NavigationMixin.GenerateUrl]({

        type: 'standard__recordPage',

        attributes: {

            recordId: '005B0000001ptf1XXX',

            actionName: 'view',

        },

    }).then(generatedUrl => {

        this.recordPageUrl = generatedUrl;

    });

}

// NavigationMixin.GenerateUrl returns the Generated URL in the promise.

// We can even use this in  window.open(generatedUrl) command.


Sunday, 24 October 2021

Salesforce Shield

 Salesforce Shield is made up of three components.

1.Platform Encryption (Natively encrypt sensitive data)

2.Event Monitoring (Detailed data & Monitoring)

3.Field Audit Trail (Prevents Data loss)


Platform Encryption :


1.Encrypt sensitive data when it's stored at rest in the salesforce cloud.


it means encrypts data metadata layer at place where it is stored.

In database it stored in an encrypted manner.


2.Support customer-controlled encryption key lifecycles.

  Manage the lifecycle of data encryption keys.

  


Note :

Data stored in many standard and custom fields and in files and attachments can be encrypted using an advanced Hardware Security Module-based (HSM)

key derivation system, so it is protected even when other lines of defense have been compromised.

  

  

Tenant Secret Key :


Generated and rotated by customers. A New Tenant Secret can only be generated once every 24 hours in a production

organization and every 4 hours in sandbox environment. The option is disabled, if the Tenant Secret is generated in last 24 hours

in production and 4 hours in sandbox environment.  


Master Secret Key : 

Generated and rotated by Salesforce. 

Master secrets used in the key derivation function are rotated with each major Salesforce release.


How Platform Encryption works ?


The salesforce user submits a save request the first thing that gets invoked is the encryption service.

The encryption service checks if there is any encryption policy applied to that particular operation.

If yes it takes in the cache if there is a encryption key available for encryption.

If not it sends a request to the key derivation server which generates a key of the tenant secret which 

is generated in the particular org.


The Master secret which is generated at the start of every release by salesforce itself.

so it generates a encryption key and it sends it sends back to the encryption service.


Now as soon as the encryption service receives the encryption key it generates a random initialization vector

which is used to encrypt the data.The data which is encrypted and the initialization vector against that particular

operation gets stored in the salesforce.



Probabilistic Encryption :

By default, Salesforce encrypts data using a probabilistic encryption scheme.  

Probabilistic encryption is the use of randomness in an encryption algorithm so that when encrypting the same text several times,

it will, in general, yield different cipher texts.


Probabilistic encryption is so secure that it can often cause issues when logic is executed in the database or when encrypted values are compared to a string or to each other.  When these types of configuration

changes are made within a Salesforce org, filtering isn’t possible because the data has been turned into random, patternless strings. 


For example, you might run a SOQL query in custom Apex code against the Contact object, where LastName = ‘Jones’.

If the LastName field is encrypted with probabilistic encryption, you can’t run the query because each instance of the value 

‘Jones’ represents a different text string. 


It is recommended to use probabilistic encryption whenever data in a field will not need to be filtered on.


Deterministic (Filter-Preserving) Encryption


Deterministic encryption addresses the issue with probabilistic encryption by securing the Salesforce org while retaining the 

benefits of filtering data. 


To be able to use filters when data is encrypted, we have to allow some patterns in our data.  

Deterministic encryption uses a static initialization vector (IV) so that encrypted data can be matched to a 

particular field value.  The system can’t read a piece of data that’s encrypted, but it does know how to retrieve 

the cipher text that stands for that piece of data because of the static IV.  The IV is unique for a given field in a given org 

and can only be decrypted with your org-specific encryption key.  The Salesforce Shield Platform Encryption at rest approach 

is to expose just enough determinism to enable users to filter on encrypted data while limiting it enough to ensure that a 

given plain text value does not universally result in the same cipher text value across all fields, objects, or orgs.  

In this way, deterministic encryption only decreases encryption strength as minimally necessary to allow for filtering.


Deterministic encryption allows for the user to specify if case sensitivity on record values needs to be accounted for 2 Types

of Deterministic Encryption:


Case-Sensitive – Allows for the ability to filter data on a case-sensitive basis. ‘ACME’ and ‘Acme’ will be 

considered 2 unique values and the encryption scheme would use different cipher text strings to identify these 2 records.

Case-Insensitive – Allows for the ability to filter data but does not factor the case of the value. ‘ACME’ 

and ‘Acme’ would be considered the same value and the encryption scheme would use the same cipher text value 

for both (assuming the record is in the same field / object / org)


Note :

What’s Data Encryption?


Data encryption is the process of taking information in readable form and translating it to a non-readable form.  

It converts data into a secret code and is the most effective way to achieve data security.  To read an encrypted file, 

you must have access to a secret key or password that enables you to decrypt it.

Unencrypted data is called plain text; encrypted data is referred to as cipher text.  

When data is encrypted, each bit of data is turned into a fully random cipher text string.  

Encryption will not generally impact users who are authorized to view the data.


Deterministic(Static IV)

ex :

   value      cipher Text

   BOB           1234az96

   BOB           1234az96

Probabilistic(Random IV)


ex :

   value      cipher Text

   BOB           1234az96

   BOB           6924wh12




Event Monitoring :


1.Monitor data loss

2.Increase adoption

3.Optimize performance


Event monitoring lets you to easily see what data users are accessing, from what IP address, and the actions done to that data.


e.g. API calls, user logins, users who are running reports, exporting reports, downloading files, and etc.


Event Monitoring data can be accessed via the API.


Use the SOAP API and REST API resources to retrieve event log files that contain information useful 

for assessing organizational usage trends and user behavior.


You can track up to 28 different event types. Log data is read only. You can’t insert, update, or delete log data.


You can access those data via API and pull the data into any visualization tools. For example Salesforce Analytics.


Field Audit Trail :


1.with up to 60 fields per object selected for tracking changes.

2.Tracked changes may be displayed in a related History list.

3.Stored in a related object for upto 18 months.


Note : Any historical data that is captured before platform encryption

was enabled is still in readable state.it is not encrypted.

Any data that was created or updated prior to enabling platform encryption

that is still in readable mode. If you want to get it encrypted we need to reach salesforce.


User with "Manage Encryption Keys" Permission can generate,export,import and destroy organization-specific keys.

Monitor the key management activities of these users regularly with the setup audit trail.


Protected fields are only visible to the users who have the “View Encrypted Data” permission. Encrypted data can only be accessed with appropriate Tenant Secret.


Considerations :


1.Custom Fields - You can't use encrypted custom fields in criteria-based sharing rules,filtering or sorting contexts.

2.SOQL/SOSL - Encrypted fields that use encryption scheme can't be used with aggregate functions & few SOQL and SOSL clauses.

3.Portals - If a portal is enabled in your organization,you can't encrypt standard fields.

If legacy portals are active, shield platform encryption can't be enabled.

4.Field Audit Trail - Data in a previously archived Field Audit Trail isn't encrypted when you turn on Platform Encryption.

5.Apps like Commerce cloud, Quip, Marketing Cloud, Salesforce CPQ etc. don't support data encrypted with Shield Platform encryption.


Platform Encryption :

===================== 

1.Advanced Settings :


For encryption policy tasks, also require that admins have the Manage Encryption Keys permission.


Deterministic Encryption

Use deterministic encryption when you want to filter on encrypted data. 

Apply this scheme to specific fields from the Encryption Policy page.


Allow BYOK to Opt Out of Key Derivation

Lets you disable Salesforce’s key derivation process, and use your uploaded key material as the final data encryption key.


Encrypt Custom Fields in Managed Packages

Lets you encrypt custom fields in installed managed packages.


Encrypt Field History and Feed Tracking Values

Includes field history and feed tracking changes in data encrypted during the synchronization process.




2.Encryption Policy 


Shield Platform Encryption also supports custom fields in installed managed packages. 

Apply encryption to custom fields from the management settings for each object. 

For best results, encrypt the least number of fields possible. When you add encryption to a field, all new data in that field is encrypted.





3.Encryption statistics :


we get to know that the data which already exists is encrypted (or) not.

which records in my org are encrypted and how many are still in readable state.

we can gather statistics once in every 24 hours.





4.Key Management


Salesforce allows us to generate a tenant secret or else we can go ahead and import our own key which is generated by some other external systems.




Note :

As soon as generate a new key, the first key becomes archived.

All 50 keys available in org, of which only one can be active either could be archived or destroyed state.


Sunday, 17 October 2021

Sharing and Visibility in Salesforce

Most objects in Salesforce have associated sharing objects.

Standard objects have associated sharing objects with the word share appended to them.

 ex : AccountShare,ContactShare

Custom objects also have associated sharing objects with the word __share appended next to the name.

  ex: Robot__share

For a custom object called Robot, Robot__share will hold sharing records for that object.

Standard sharing objects differ from each other, but have very similar fields.



ex:
Opportunity :

The OpportunityShare object has a field called Opportunity, which is a lookup to Opportunity.
Every row in the sharing object corresponds to exactly one Opportunity record, and this lookup holds the ID of that record.

UserOrGroup :

We have another field called UserOrGroup. This is a lookup to either a user or a group the related opportunity is being shared with.

OportunityAccessLevel :

OpportunityAccessLevel holds the access level granted as a result of this row. Read, which grants read access, Edit, which grants edit access,
 and All, which grants full access including edit, transfer, delete, and sharing rights are three possible values in this field.
 
 e.g.  Read,Edit and All
 
RowCause :

RowCause holds the reason this row exists in the sharing object.Record owners get a row in this object with all access by virtue of being owners.
Sharing rules end up creating rules with RowCause rule. Manual shares also result in roles in this object with the RowCause Manual. 
There are many other possible values for RowCause which can differ by object

e.g. Owner,Manual or Rule

Other standard sharing objects have similar fields, but may have differences.




Let's take AccountShare as an example. It has the fields you would expect, Account, UserOrGroup, AccountAccessLevel, and RowCause. 
You find similar fields on almost every standard sharing object, but there's also some fields you did not expect. 
This includes CaseAccessLevel, ContactAccessLevel, and OpportunityAccessLevel fields. This is because of implicit sharing behavior in Salesforce. 
When the user gains access to an account, depending on the account owner's role and OWD settings, the user can also gain implicit access to children cases, contacts, and opportunities.
These fields capture the access level that should be given to these related records.

Custom objects get their own sharing object too, and they are simpler than the standard ones because all of them have the same fields.




Let's talk about Robot__Share, which would be the sharing object for a custom object named Robot. 
The sharing object will have a field called Parent, which is a lookup to the parent robot record. 
It will have a field called UserOrGroup, which would be a lookup to the user or group the record is being shared with. 
The FieldAccessLevel with values Read, Edit, and All just like the standard share objects will also be present. And finally, the field RowCause, 
which stores the reason this row exists.


Note :
Inserting share records for the same parent, same user, and same RowCause as an existing share results in an update of the existing record, not a new insert.

Facts about Sharing object :

1.There are cases when sharing objects are just not available.
 e.g. An object has public read/write OWD.
2.This makes sense because such an object wouldn't need any sharing. An object on the detail side of a master‑detail relationship is another example.
This is because such an object inherits sharing from its master and cannot have its own sharing model.
 e.g. Master-details
3.Some objects have their own access control mechanisms such as tasks, events, or files and hence do not have a sharing object available.

Sharing objects don't give a complete picture of why a user may be seeing a record.

1.Access given out through the role hierarchy is not shown in sharing objects.
2.Access given out through organization by defaults is not tracked in this object.
  Everyone can see records of a public read-only object, but you won't see any sharing records and sharing tables.
3.Access given out through record‑level profile and permission set settings, such as view all and modify all settings, is also not tracked in sharing objects.

Roles: They're Just Groups :

Setting up the role hierarchy results in a few things behind the scenes.
Salesforce creates two groups for each role that we have defined.
Every role gets a Role group and a RoleAndSubordinates group.

Note : Salesforce creates two Groups for each role 
 --> Role Group
 --> RoleAndSubordinates group
You may have seen these special groups when creating sharing rules, queues, or public groups. 
That's when Salesforce gives you the option to share records with a role or with roles and subordinates.

RoleAndInternalSubordinates group:

There is also a third group that Salesforce would create for every role known as the RoleAndInternalSubordinates group, 
but this is only when Digital Experiences and external org-wide defaults are enabled in your org.
In case these options are enabled, this group excludes partner and customer portal users.

Group object :

We can actually look at these groups(Role Group,RoleAndSubordinates group,RoleAndInternalSubordinates group) in the Group object.

SELECT Id,DeveloperName,Type FROM Group

If you run the above SOQL query you can see the Role and RoleAndSubordinate groups defined for each role.

You can see there are two groups.One is of the type Role, and other is of the type RoleAndSubordinates.

Role group  :

A Role group has all members assigned that role as direct members, but also all users assigned a higher role as indirect members of that group.

Note : 
Role Contains users with the given role as members, and everyone with higher roles as indirect members.

RoleAndSubordinates group :

Contains users with given role and subordinate roles as members, and users with higher roles as indirect members.

Note : Both these groups contain users with higher roles as indirect members.

GroupMember Object :



With queues and public groups,The GroupMember object stores members, but not for role-related groups.

The membership for these role-related groups is not visible to us.

Note :

These "group maintenance" records in conjunction with "sharing" records allow Salesforce to get results fast.

Profile and Permission Set Settings :

View All Data :

View Access to all records, regardless of sharing settings.

If a user has the system-level permission checked on their permission set or profile, they have view access to every single record in the system.
Object-level and field-level permissions still apply. But as long as a user with this permission has read access to an object, they would get to view all records of that object.

Modify All Data :

Edit access to all records,regardless of sharing settings.

It gives edit access to every record in the system as long as the write‑object level and field‑level permissions are present.

View All (Object-level)

View access to all records for the given object.

The View All permission, unlike the View All Data permission, is defined for each object. 
If I have View All permission on the Account object along with read access to the object, 
it means I will be able to read all account records regardless of other sharing settings. 

Modify All(Object-level) :

Edit access to all records for given object.

Modify All is an object-level permission that gives edit access to all records of an object. 
If a user has this permission to the account object along with read and edit object-level permissions, 
they would be able to view and edit all account records.
 
Sharing Calculations and ReCalculations  :

Sharing Calculations :

Calculations Salesforce performs behind the scenes to ensure a rapid application
of sharing and visibility any time someone requests records from the database.

Note : 
The sharing architecture for orgs with large data volumes should consider the impact of recalculations.

When designing a sharing model for orgs with large data volumes, it is very important to keep in mind what impact recalculations can have.

Recalculations Scenarios :

1.Adding, removing or editing a sharing rule.
Asynchronous
 -> Can be seen on the background job page
 -> Email when completed

This recalculation, like most recalculations, is run asynchronously and can be seen on the Background Jobs page and set up, and you receive an email once the recalculation is complete.
The more records impacted by the sharing rule, the longer the calculation.

There is an exception to this rule, when the number of impacted records from an ownership-based sharing rule insert or update is less than 25,000.
In this case, the job is run synchronously, it is not available on the Background Jobs page, and you won't receive an email when it's done.

Note : Synchronous,no email,and not visible under background jobs.

2.While this recalculation is in progress, you cannot change the OWD or make changes to sharing rules for the object being processed.

Note : No changes to OWD or sharing rules on object while recalculation is in progress.

You can still make changes to sharing settings on other objects.

3.Changing OWD settings

Changing organization-wide defaults on an object can also result in a long-running recalculation.
 
-> Changing to a more permissive OWD means removing sharing records.

If you change the organization-wide default from save private to a more permissive setting, some sharing records may no longer be necessary. 
That is when Salesforce runs jobs to clean up access.

-> Changing to a more restrictive OWD means creating sharing records.

If you change the organization‑wide defaults to a more restrictive setting, for example from public read/write to private, 
Salesforce may now need to include sharing rules that previously did not exist.

Note :
-> Sharing rules can exist on objects with a Public Read/Write OWD.

Remember that if your object has a public read/write OWD, it can still have sharing rules defined on it. 
The sharing rules will have no impact of course, but they still exist. 
That's a good thing because if you change your object's OWD setting to public read/write, you don't want your sharing rules to just disappear.

-> Need recalculation when OWD is set to less permissive.

This does mean that when you switch to a more restrictive setting, these rules would need to be recalculated.

-> changing a user's role resulted in a sharing recalculation.

changing the user's role resulted in a change to a role group that was used as a source for a sharing rule.

Note : A role group that changed was used as a source group for an ownership-based sharing rule.

Changes to membership in groups that are used as a source for ownership-based sharing tools can result in long-running recalculations 
because the sharing rule now needs to be re calculated. 
Examples of actions that can impact group membership is changing user roles,changes to queues and public groups, changes to the role hierarchy itself, and changes to territories.

-> Changes to role Settings 

Implicit access through role settings is tracked in sharing objects.

Every role has settings for implicit access to contacts, opportunities, and cases. 
Access given through a role hierarchy is not tracked in sharing objects, but access given through these 
implicit settings is tracked in the sharing object and needs to be recalculated if the role settings change or if a user's role changes.
Group Membership Calculations:
==============================
The GroupMember object, which contains data on which users are part of which groups.

-> Membership for queues and public groups is visible and editable.

For queues and public groups, we can see group members in this object and even insert records to change group membership.

-> Membership for other system-managed groups is not visible to us.

But for hierarchy groups, membership data is not visible in the GroupMember object and is managed internally by Salesforce.

Note : The Two kinds of groups that Salesforce created for every role, the Role group and the RoleAndSubordinates group.

Territory Hierarchy :

Territory hierarchy also results in creation of two groups.

1. Territory group 

  -> All users in the territory
  -> All users in a higher territory
  
2. Territory and subordinates group  

   -> All users in the territory
   -> All users in a higher territory
   -> All users in a lower territory

Group Membership Calculations :

Changes to any of the hierarchies, Salesforce needs to recalculate group membership. 
Changing a user's role, for example, results in changes to group memberships for groups associated with roles above and below the user's old and new role. 
Changing the hierarchy itself also results in changes to group members from multiple groups.

Mmembership recalculations can be costly too, especially if you are making changes to a large number of users, roles, or territories. 
When recalculating group memberships, there can also be concerns around locking and timeouts.

Note :
Create more roles: In Salesforce orgs created in Spring ’21 or later, you can create up to 5,000 roles. 
In existing orgs, the default limit hasn’t changed. You can create up to 500 roles and can contact Salesforce Customer Support to increase this limit.

group membership calculations cause :

Database Lock :

Databases allow operations to lock entire tables or some rows in the table. Until the operation completes, 
all other operations that want to work with the locked data are forced to wait until the lock is released.
Databases do this for the same reason you might lock an entire document while working on it, to prevent 
others from overwriting your work or to prevent others from reading a half-complete document.

Granular Locking :

-> Lock only a subset of records.

e.g. when modifying a role group, only lock rows related to groups being modified.

Salesforce uses granular locking when performing group membership calculations. 
This means Salesforce locks only relevant group membership records instead of locking the whole group membership object.

-> Enables Parallel Processing 

Group membership operations that modify unrelated groups can proceed in parallel without worrying about locks.

This means if two group membership operations are modifying unrelated groups, they can proceed in parallel because they need to lock different sets of rows.

Granular Locking Conflict :

-> Operations need to wait

Group membership operations ususally do not take a very long time and can wait on each other.

what if two group membership operations need to lock the same set of rows, for example operations that modify role groups that have a hierarchical relationship. 
A group membership operation that needs to acquire a lock on rows locked by another group membership update can usually wait for the other operation to release the lock.

Note : These operations usually don't take too long.

-> Timeout when waiting

If an operation waits too long,Salesforce terminates it with an error saying it was unable to acquire a lock.

If the operation does take too long, you can see an error stating that Salesforce was unable to acquire a lock. 
The probability of such loss increases when you are dealing with a large number of changes to users and groups at the same time.

Group Membership Update Considerations :

1.Ownership-based sharing rules

A group membership change causing a sharing recalculation can hold longer locks.

This is a case where a group membership operation can take a much longer time, preventing you from performing other group membership operations. 

2.Schedule at different time

Running operations at different times, including apex tests,reduces locks.

You should also make an effort to schedule such operations at different times if possible to reduce the probability of locking errors. 
A release that includes changes to group memberships or includes Apex tests that make changes to group memberships could be scheduled for a different time from a major role reassignment, 
for example. Apex tests cannot make permanent changes to group membership, but they still lock group membership rows.

3.Build resilient operations

Automated operations should attempt to retry of there are failures due to locks.

Automated processes that make such changes to group membership should have resiliency built into them. 
They should attempt to retry if such operations fail due to locking errors.

Defer Sharing Calculations :

1.suspend sharing calculations
2.Make changes without triggering calculations.
3.Resume calculations and run a full sharing recalculation.
4.Useful when performing multiple operations that can trigger calculations.
5.Not enabled by default.

You can suspend sharing calculations, make all the changes you want without triggering expensive recalculations, and then have Salesforce run a single full recalculation right after you resume.
This is a great option if you need to perform multiple operations that could result in expensive recalculations, like a number of sharing rules or major role realignments.

This feature isn't enabled by default. If you need this enabled in your org, you would need to reach out to Salesforce Support.

Note :
With Defer Sharing Calculation you can avoid this by suspending sharing rule calculations from evaluating immediately after you make sharing rule changes. 
You can resume sharing rule calculations during maintenance windows to have minimal impact on users.

Defer Sharing Calculations :

1.Defer Sharing Rule Calculations
2.Defer Group Membership Calculations

"Manage Sharing Calculation Deferral" permission and "Manage Users" permission have to users.

In Setup, I can navigate to the Defer Sharing Calculations page to use these features. Even without this permission set, 
I would have been able to navigate to this page, but the permission gives me access to suspend, resume, and recalculate.



Avoding Data Skew :
===================
1.Ownership Data Skew

Ownership data skew is when a single user or queue owns over 10,000 records of an object.

To avoid performance problems, distribute records so that no single user or queue owns over 10,000 records.

When Ownership Skew is unavoidable :

ex: A single user owned all records.

1.Ensure user has no role, or role stays at the top of the hierarchy.
2.Ensure user is not in any group used as a source for an ownership-based sharing rule.

2.Parent-child Data Skew 

when you have over 10,000 child records associated with the same parent.

Let's take Accounts and Contacts as examples. Every time a user gains access to a contact, Salesforce implicitly gives that user access to the parent account.
And when a user loses access to a contact, Salesforce needs to, but it cannot immediately take away access to the account. 
Salesforce needs to check every child record to ensure the user does not have access to them. Once confirmed, Salesforce can remove the implicit account access.

Another example of parent-child skew is when a user owns a skewed account, and their role settings give the user implicit access to all child contacts.
An example of what could go wrong in this scenario, if the user loses ownership of the skewed account, Salesforce would have to remove sharing for every child contact. 

Resolving parent-child Skew :

1.Person Accounts

Person accounts are one option of course, but not everybody loves all the baggage that comes with person accounts.

2.1:1 Model

Another model is to just create an account for every contact using some automation, a 1:1 model just like person accounts, but maintained by you.

3.Household Model

Yet, another popular option is a household model where you group contacts under households. 
This option can be attractive if the company's products or services are used by whole households.

Apex Managed Sharing :
=====================
Similar to manual sharing - grant access to individual records by inserting rows in sharing objects.

Insert a Share Record through Apex

ex :
Follower__Share objFollowerShare  = new Follower__Share();
objFollowerShare.ParentId = 'a032x00000AViTgAAL';
objFollowerShare.UserOrGroupId = '0052x000002Yj03';
objFollowerShare.AccessLevel = 'Edit';
objFollowerShare.RowCause = 'Manual';
Database.SaveResult sr = Database.insert(objFollowerShare,false);

The code will work just fine, but having RowCause set to Manual can be a problem.

User Managed Sharing :

1.Sharing button can be added to page layouts.
2.Available to users with "full" record access.
  -> Record Ownership
  -> Users with a higher role
  -> Users with Modify All or Modify All Data
3.Allows users to add,remove or update sharing records that have RowCause set to "Manual".

Implications of RowCause "Manual" :

1.Managed by users

Users can delete sharing records created through Apex or the Data Loader.
This means users can go and delete or modify these sharing records as long as the user has full access to the record.

2.Deleted if owner is changed

Salesforce removes all manual sharing from a record when the owner changes.

Note :

In User Managed Sharing is, a user who has full access on the record shares the records with others, but when the record owner is changed, this record will be removed from Sharing table.
Similarly, when apex sharing is defined as “Manual” on RowCause, it will remove record from sharing table when the record owner is changed.

Apex Managed Sharing :

1.Use a different value for RowCause.
 -> Create an Apex sharing reason
 -> Assign the new Apex sharing reason to RowCause instead of "Manual".

A sharing record inserted with an Apex sharing reason as the RowCause is visible to users with full access through the Sharing button, 
but it is not managed by the user, which means the record owner will not be able to edit or delete it. Such a record will also persist through ownership changes,
which is the behavior we would want. 

Note : Apex sharing reasons can currently only be created in Salesforce Classic.

why Recalculate Apex Managed Sharing ?

1.We deployed the trigger,but older records need sharing too.
2.Possibility of a bug in current trigger.
3.Changing OWD settings can require Apex sharing recalculation.

Manager Group Sharing :
======================
Manager groups allow users to share records with their direct management chain and direct subordinates.

Manager lookup on user Record :

Can be used to capture direct reporting relationships.

A user record in Salesforce has a standard Manager field, which is a lookup to user.
This field can be used to model direct reporting relationships not possible or feasible through the role hierarchy.

Groups based on direct managers :

Records can be shared with management chain or subordinates.

Salesforce uses this management hierarchy to build manager groups that records can be shared with. 
These groups, as we're about to see, allow users to share records with people's managers or their subordinates.

These are relationships modeled through the Manager field on the user object.

Salesforce creates  2 groups for each user, a managers group and a subordinates group.

Managers and Subordinates Groups :

Manager Group :
Members include the user's manager, the manager's manager and so on.

Subordinates Group :

Members include the user, the user's direct reports and the user's indirect reports.

Enable Manager Groups :

As admin, you can enable Manager Groups from Setup | Security Controls | Sharing Settings, look for Organization-Wide Defaults and click Edit button,
 scroll down to Other Settings and select Manager Groups and then click Save.

SELECT Id,DeveloperName,Type FROM Group

To run a SOQL query on the Group object to see the new groups that were created.

As you can see, there are ManagerUp and ManagerDown groups with user IDs appended to the group's name. 
These are not very user‑friendly names and you don't see them on the user interface, but these are the names Salesforce uses internally.
Just like role groups, the members for these groups are not visible to us. They are managed internally. 
If we ran a query on the GroupMember object, we would not see any members for these groups.
Once created, these groups are available for manual sharing.
We can even create sharing rules based on manager groups.

Limitations of manager groups:

1. we can only pick specific manager groups when creating sharing rules.
2. Apex sharing reasons not suppoeted.

Manager groups do not support Apex sharing reasons.
This means we would need to use RowCause Manual, and the records would be deleted on ownership change and can be managed by users.

3.Cannot be added to other groups.

Salesforce lets us add role groups and public groups into other public groups and into queues, but manager groups cannot be added into any other groups.

Summary :

-> Different ways record access is granted
1.Explict grants in sharing objects.
Explicit grants and sharing tables associated with objects and includes things like manual sharing and sharing rules.
Salesforce sometimes needs to recalculate these access grants.
2.Group Membership grants
Group membership grants where users obtain access to records by virtue of being in a group. For example, if an explicit grant gives a group access to a record, users part of their group gain access through this mechanism.
3.Inherited grants (Roles and terrirories)
Inherited grants where users gain access to records by virtue of being part of a role or territory hierarchy.
4.Implicit grants(built-in sharing)
Implicit grants, which supports implicit or built‑in sharing behavior, for example users obtaining access to parent accounts for cases or opportunities they can access.

-> Recalculation is sometimes necessary 

Salesforce sometimes needs to recalculate sharing and group membership, and we discussed techniques for dealing with them, 
including deferring calculations, avoiding data and ownership skews, scheduling changes at different times, 
and designing a sharing model that reduces the need for expensive recalculations.

-> Apex Managed Sharing

Apex managed sharing, which is essentially just inserting records into sharing objects using Apex. We learned that using an Apex sharing reason as the RowCause ensures that Apex manages these sharing records instead of the user.

-> Manager group sharing

Manager groups, which allow sharing records with the user's management chain or subordinates.

Note : Based on manager lookup , not roles.

It's easy to confuse this with the role hierarchy because Salesforce often uses the word manager to refer to higher ups in the role hierarchy. 
A key difference here is that manager groups are based on the manager listed on the manager lookup on the user record, 
while the role hierarchy is based solely on how the role hierarchy is set up, regardless of direct reporting relationships.