Big Objects in Salesforce (Data Archival strategy)

Why Data Archival is important in salesforce?

Salesforce works better with Operational data and transaction data but when it comes large data volumes the performance goes down for the Reports, List Views, query performance, while Re assigning the owner or updating the role hierarchy will impact user experience.

So it is always better understand your storage limits and data grown trends well in advance.

How can we avoid it?

  1. Define your Operational data set and store only that data
  2. Delete the unnecessary data (Back up before mass deleting data and keep in mind that data integrity implications)
  3. Delete unnecessary object and their related data.
  4. Create an archiving policy

Different Archival/Data Backup processes which support in salesforce:

  1. Shadow Objects: Shadow Object is a custom object which will holds the same structure of base Object. That means same fields, same CRUD, OWD, field level security. We can move the records to this new object based on criteria. In this way we can reduce the volume in base object.
  2. Heroku : Cloud Based Service to move data to and from Salesforce to Heroku(Postgres). Using bi-directional synchronization between Salesforce and HerokuPostgres, HerokuConnect unifies the data in your Postgres database with the contacts, accounts and other custom objects in the Salesforce database
  3. Different app exchange Products: The most popular appexchange products to bachup are Backupify, Ownbackup for Salesforce, Spanning Backup, Odaseva
  4. External Objects: are similar to custom objects in salesforce, But external object record data is stored outside your salesforce Organization. Each external object is associated with an external data source definition in your Salesforce organization. An external data source specifies how to access an external system.
  5. Big Objects: By using Big objects you can store massive amount of data in salesforce platform. Big objects provide consistent performance for a Billion records or more.                                                                                                                        There are may more options to do data archival and data backup in salesforce based on requirement. Now Let us discuss more about Big Objects

We have two types of big objects

  • Standard big Objects: These are defined by salesforce and included in salesforce products. Ex : FieldHistoryArchive (Which allows you to store upto 10 years of archived field history data)
  • Custom Big Objects: You can not create big objects through Standard Slaesforce UI. However you can create big objects by following two ways.
  1. By using Metadata API : Custom Big Objects are defined and deployed by you through metadata api. To define a custom big object, you create an object file that contains its definition, fields, and index, along with a permissionset to define the permissions for each field, and a package file to define the contents of the object metadata. After inserting metadata file through workbench you can check the Big Object API Name ends with “__b” in org.

          There is a trailhead which will explain to create a big object using metadata api.

  1. Custom Big Object Creator: There is another way to create Big Object is, by installing “Custom Big Object Creator” managed package from Salesforce Labs. We can create Big object using Custom Big object creator lightning tab. In Big Objects OWD, CRUD, Field level security can be set as per requirement. As these objects are using for storage so it will support only 5 data types which are “Text, Long Text Area, DateTime, Number and Look Up”.

   Why I can use Custom Big Objects?

  1. 360 degree view of the customer
  2. Auditing and tracking
  3. Historical Archive

 How can I insert records to Big Objects?

There are different ways to create BigObject record, like using a csv file, use APIs like Bulk API or even Async SOQL or database.insertImmediate(record) apex method

Example: If I want to move records from CustomObj__c to CustomObjHistory__b using Apex ,  need to retrieve the records from VustomObj__c and insert records to CustomObjHistory__b,

CustomObj__c  actualrecords = [Select id, canbemerged__c, testfield1__c, testfield2__c from CustonObj__c limit 1];

String merged = actualrecords.canbemerged__c == true  ? ‘true’ : ‘False’

CustomObjHistory__b cbh = new CustomObjHistory__b();

cbh.canbemerged__c = merged;

cbh.testfield1__c = actualrecords. testfield1__c;

cbh.testfield2__c = actualrecords. Testfield2__c;

database.insertImmediate(cbh);

Using REST API:

You can insert the data into the object by using rest api post method through work bench:

“/Service/Data/v40.0/sObjects/CustomObjHistory__b”

You can expose the data by using visual force page or lightning component.

Big Objects Storage and capacity?

Eventhough Big Objects supports Millions or hundreds of millions or billions of records but the limit of the Big objects is actually limit to 1 million records without any cost. We can increase this limit by buying the storage space. The cost is approximately $16,800 AUD per year per 50M records (we can’t buy it in any smaller amounts)

Big Objects storage capacity

How can We Query Big Objects?

If we know that you are querying small amount of records then you can use SOQL

And the another way is “Async SOQL

AsyncSOQL: To manage millions and millions of records in your custom big objects salesforce introduced AsyncSOQL. But Async SOQL is included only with the licensing of additional big object capacity.

Big Objects Considerations:

  • You can create only 100 big objects per org. The limits for big object fields are similar to the limits on custom objects, and depend on your org’s license type.
  • Big Objects supports only Object and Field level security
  • Big Objects can be used in Einstein analytics but not for report builder and search.
  • We cannot track field history in Big Objects
  • Big Objects don’t support transactions that include big objects, standard objects, and custom objects.
  • You cannot write triggers, flows, processes on big objects.
  • You cannot use Salesforce Connect external objects to access big objects in another org.
  • The best practice when writing to a big object is to have a retry mechanism. (For example Retry the batch until you get a successful result from the API or Apex method)
  • You can delete the data in Big Objects using “deleteImmediate()” apex method.

 

 

 

Why Salesforce Lightning? (Things to consider while moving to Classic to Lightning)

Why Not Lightning Experience?

Lightning experience is the advanced UI which has redesigned modern look and feel. It is more user/mobile friendly. It provides efficient navigation between different tabs ,  Salesforce lightning has flexibility to fit multiple actions on a single screen which allows user to work fast with fewer clicks and increase productivity of users. 

While making the switch to Salesforce Lightning has its benefits, it’s important to truly evaluate whether it’s necessary and right for your organization

Benefits of Lightning Migration:

  • Efficient navigation and the ability to switch between custom brand apps
  • Advanced UI improves productivity of users
  • Quick access to productivity tools like Notes and Recent Items in the utility bar
  • New Record layouts which holds multiple Tabs (Detail, Related, News, Activity etc ) so you can focus on what is required
  • Turbocharged list views that let you easily filter and visualize your data
  • An intelligent Home page filled with Assistant, Performance charts, top deals, News, Key deals, Today’s Events, Today’s Tasks, Calendar, Items to approve, Customizable Dashboards, Customizable home page components.
  • Sales Reps can use Kanban view a visualization tool, to review deals organized by each stage in the pipeline.
  • On each lightning app you can add “Utility Bar component” on the footer as a widget with out using much real estate. We can add Recent Items, Chatter feed, Chatter publisher, Macros, CTI soft phone etc.
  • Enhanced report charts, Interactive filters when viewing reports, Hide Total and sub groups from Reports.
  • Interactive Global actions: We can set up actions to create different types of records with pre populated information (pre poulation only support for few data types.)
  • Favourite List : To quickly access the favourite or frequently using accounts, reports etc.
  • Beautiful dashboards with components that span both columns and rows and displays more than 3 columns
  • Rich styling component library(SLDS)

Before moving to Lightning migration please consider following points:

What will not be changed?

  • Data
  • Business logic which as validation rules, work flows etc
  • Security

What will be impacted?

  • User Interface
  • Technical debt as everything  not works as expected in lightning
  • VisualForce pages: what is your designing approach for existing VF pages? Are you going to rebuild by using lightning components or making lightning styling using SLDS
  • App exchange : Check your app exchanges are lightning Ready or not?
  • Package Installation : Check that packages are work in lightning? are there any other components in appexchange /Salesforce Labs which supports better than this package?
  • Business process – Check lightning will solve your problem in different way
  • All custom development is not compatible
  • Java script Buttons and URL hacks are not compatible
  • Reports – check all report features
  • Users Interaction: If user interaction changed User Training required

How to Evaluate your Org:

  • Preview: The Preview tool lets you see your apps in Lightning Experience before you actually enable it.
  • Run the Lightning Experience Readiness Check and Review Your Readiness Report
  • Prioritize potential functionalities
  • Review the gaps and analyze fit-gap
  • Test your goals
  • Roll out to pilot users
  • Documentation is important

 

Different sharing Mechanisms in Salesforce

Below are the different sharing mechanisms as best of my knowledge in sales force,

 

Access Type Description Objects Support Relationship support Considerations
Profile Object and Field Level access.

We have 6 standard Profiles and we can create Custom Profiles as well.

All standard and Custom objects MD: Detail Record access is controlled by Master record

LU : Child objects can have their own permissions

N/A
Permission Set Object and Field Level access. Extend the permissions without changing the Profile. All standard and Custom objects MD: Detail Record access is controlled by Master record

LU: Child objects can have their permissions

Take care while selecting the Permission Set License.

-Choose ‘–None–‘ if you plan to assign this permission set to multiple users with different user and permission set licenses.
-Choose a specific user license if you want users with only one license type to use this permission set.
-Choose a specific permission set license if you want this permission set license auto-assigned with the permission set.

OWD it provides Record level Access and Most Restrictive access. Different access types: Private, Public Read, public Read/Write

We can define Internal Users access and External user’s access. 

All standard and Custom objects MD: Detail Record access and ownership is controlled by Master record.

Grant access through hierarchies value is inherited from Master record.

LU: Child objects can have their own sharing access and ownership. Grant access through hierarchies can be disabled

 

1. All standard objects use sharing access through hierarchies and this cannot be disabled

2. If Person accounts are enabled can’t change Contacts access

Manual Share Record level share. Share the records manually by Record Owner or administrator. N/A N/A 1.  If Person Accounts are enabled, contact records can’t share.

2. The sharing will be discarded if Record Owner changes

3. The sharing will be discarded if the OWD becomes as permissive as the share

Sharing Rules Record Level Access and allow greater access to particular users.

1.      Owner Based sharing Rule : Sharing records to a User, Role, Public group is based on the record Owner

2.      Criteria Based sharing Rule: Sharing records to a user, Role, Public group is based on the field value

N/A N/A 1. You can’t include High-volume portal users in sharing rules because they don’t have roles and can’t be in public groups.

2. If multiple sharing rules give a user different levels of access to a record, the user gets the most permissive access level.

Recalculate Sharing Rules:

3. When you make changes to Users, Roles, Groups and territories the Sharing rules are reevaluated to add or remove access as necessary

4. Speed up sharing rule recalculation by running it asynchronously and in parallel.

Apex managed Sharing If no other sharing Rule works for you then go for Apex managed sharing.           Example scenarios:

1. Sharing records based on criteria being met on other Object

2.      Sharing records are being maintained by Owner change.

3.      A record can be shared multiple times with a user or group using different Apex sharing reasons.

4.      Sharing multiple records at once

 

 

N/A N/A
Sharing a record using Apex If you want to access sharing programmatically, must use the Share Object.

Ex: Object[Share]-for standard objects

CustomObject__[Share] for Custom Object

Share Object Properties:  ObjectNameAccessLevel: Level Of access (Edit, Read, all)

ParentID: ObjectID

Rowcause: is a Reason determines type of sharing

userorGroupId : user or group which you are granting access

All Standard and custom objects MD: Objects which are on Detail side do not have share object. The detail record’s access is determined by the master’s sharing object Share records are not created for the OWD(implicitly share), the role hierarchy, “View All” and “Modify All” permissions for the given object, “View All Data,” and “Modify All Data”  permissions
Implicit Sharing 1. Access to a Parent Account: If you have access to a child contact, opportunity or case record of an account, you have implicit Read Only access on that account.

2. Access to child Records: If you have access to a parent account, you may have access to the associated contact, opportunity or case records.

3. Access to a portal account: All associated contacts for all portal users under that Account

N/A N/A It cannot be disabled as it is Salesforce platform feature.

Implicit share only applicable for Account, Contact, opportunity and Case

Share Groups If you want to share records owned by HVP users with internal users, groups or roles (includes portals users with roles)  
Sharing Sets Grant portal or community users access to records that are associated with their accounts or contacts using sharing sets, based on their user profiles.

 

Available for High Volume Portal , Customer community and Community

  1.      Custom Object has Look up to account or contact

2.      Object is available for Custom Portal

3.      Sharing sets applicable to only object whose OWD is Private or Public Read Only(More permissive)

Winter’19 Release Highlights

Winter’19 Release development highlights:
1. Enable CDN(Content Delivery NetWork):
Load Lightning experience , all Salesforce apps(all versions), other apps that are build on lightning component framework fatser by enabling Akamai’s content delivery network (CDN).
This CDN improves the load time of static content by storing cached versions in multiple geographic locations. This setting turns on CDN delivery for the static JavaScript and CSS in the Lightning Component framework. It doesn’t distribute your org’s data or metadata in a CDN.
This setting is disabled by default for existing orgs and enabled default for new orgs.
How to enable CDN:
Setup-> in Quick Find box enter Session Settings -> Session settings -> Enable Conetent Delivery Network(CDN) for Lightning component frameworks -> Save.
Note: This setting does not affect Lightning Communities because CDN is automatically enabled for Lightning communities.
2. Apex Methods as Cacheable:
Winter’19 onwards, we can mark Apex calls as cacheable instaed of using setStorable() on every javascript action that calls apex menthds.
Making apex method storable can increase the performance of lightning component and avoid multiple trips to server call instead it will take the data from previous server call if parameters are same.
To cache data returned from an Apex method for any component with an API version of 44.0 or higher, annotate the Apex method with
@AuraEnabled(cacheable=true).
For Example:
@AuraEnabled(cacheable=true) public static Account getAccount(Id accountId) { // your code here }
To update an existing component to use an API version of 44.0, remove setStorable() calls in JavaScript code. Annotate the Apexmethod with @AuraEnabled(cacheable=true) instead of @AuraEnabled, or you’ll get an error response for the action.
3. Stricter Content security Policy (CSP) changed from a critical update to an Org Setting:
This setting prohibits the use of “unsafe-inline” for script-src to mitigate the risk of cross-site scripting attacks. Previously it was available through Lightning critical updates. But Winter’19 onwards moved to Org Setting.
How to Enable Stricter CSP:
Set up-> Quick Find box, serach session Settings -> Select Enable Stricter Content Security Policy -> Save.
When the setting is enabled, you can’t use code that loads JavaScript with script tags, or event handlers that use inline JavaScript. For example,this cbelow ode is not allowed,
<button onclick=”doSomething()”></button>
The setting is enabled by default.
4. New Lightning Components:
i. Lightning: Map: Winter’19 onwards, Maps will be supported by the platform using lightning:map. You can pass Markers to the component as corodinated pair of longitude and lattitude, or a set of address elemnets.
ii. Lightning:empAPI: Subscribe to streaming event channel and to recieve event notifications embed the lightning:empapi component in your component.
5. Opt in to fire Platform Events from batch class(Beta):
Batch Apex classes can now opt in to fire platform events when encountering an error or exception. Event records provide more granular tracking of errors than the Apex Jobs UI because they include the record IDs being processed, exception type, exception message, and stack trace. You can also incorporate custom handling and retry logic for failures
To fire a platform event the batch class must implement Database.RaisePlatformEvents interface.
public with sharing class YourSampleBatchJob implements Database.Batchable<SObject>, Database.RaisesPlatformEvents{ // class implementation }
6. Use Inherited sharing to secure your apex code:
Inherited Sharing allow you run the class on the sharing mode of the class that called it.
You can now specify the inherited sharing keyword on an Apex class, which allows the class to run in the sharing mode of the class that called it. Using inherited sharing enables you to pass security review and ensure that your privileged Apex code is not used in unexpected or insecure ways.

Inherited sharing ensures that the default is to run as with sharing. A class declared as inherited sharing runs only as without sharing when explicitly called from an already established without sharing context. 
For example, The  if a trigger calls an Apex class and the class has no sharing declaration, then the class runs as without sharing because Trigger always runs in System mode.

7.URL redirect parameters are no longer case-sensitive:

URl parameters like retURL, startURL, cancelURL, and saveURL—are no longer case-sensitive. If you change the parameter value from retURL to returl, the system now recognizes it as a protected parameter

8.Make API Calls to your own org without Remotesitesettings and Named credentials:

Winter’19 onwards you can use “System.Url.getOrgDomainUrl()” to access REST or SOAP APIs. This is useful to access API only restricted objects and we can make API calls using system methods.

Community Highlights:

1. New Option to Join the Community:  Instead of login by username and passowrd, Community users will allowed to login via email or Phone number.

Go to the Community -> Workspace -> Administrater -> Login& Registartion

login

2. Customizing the identity Verification emails: If your community using Two- factor authentication, you will be able to customize the email with the Identity verification code.

Go to the Community -> Workspace -> Administrater -> Email

Email

3. Filter Search Results in Communities: Community users and Portal users filter their search results on accounts, knowledge articles, cases, contacts, dashboards, files, leads, opportunities, people, and tasks.

Search filtering for communities is on by default in your Salesforce org.                                From Setup, in the Object Manager, go to Search Layouts
for each object you want to filter, Add the fields that users want to filter to the Search Results layout. Supported field types are checkbox, phone number, picklist, text, and URL. You can’t filter encrypted fields.

Select the Allow search result filtering checkbox in a community’s Global Search Results component properties.

4. Sharing sets for  All customer and Partner Licenses: Previously, when you upgraded to Customer Community Plus, you lost sharing access via sharing sets because they were limited to customer Community users. Now your Customer Community users retain sharing sets after upgrading and you can also use sharing rules and role-based sharing to control access to data. And you can even use sharing sets with users who have Partner Community licenses.

5. Enhance Community Privacy with Google IP Anonymizer: If you use Google Analytics, you can now also turn on Google’s IP Anonymization to help with privacy compliance or concerns. Protect the privacy of your customers with just a mouse click

Tips for Passing Data Management and Architecture exam

Recently I have cleared Data Architecture and Management Designer exam, My first step towards becoming a Salesforce Technical Architect. It is under Application Architect track.

Exam Outline:

  • Total Questions: 65 multiple choice questions (Out of which 5 non scored Questions)
  • Time : 120 minutes
  • Passing Score: 68%
  • Prerequisite : None
  • Exam Fee: 400$ + applicable Tax

Preparing for Exam:

When I am starting my preparation, first I have started with Sales force Official Trail mix as it will cover all the topics which is mentioned in the study guide. The Trailmix is divided in to 3 sections (Beginner Level, Intermediate Level and Advanced Level)and one hands on activity.  While preparing i have note down all important points, it will help me to revise the content easily once again.  And Sales force “Study Guide” as it has the complete outline of exam including 5 sample questions. What i have read for this exam,

My Experience:

This exam mainly concentrate on data at different systems like Legacy CRM, salesforce and ERP. How you managing architecture between these systems and how you can load data between systems? How you Load data from Different systems? How you can avoid time out errors. How you can archive Large data? How you can provide High –performing solutions on the Force.com platform as an architect. Here data is always talking about large volume of data.

Below are the Useful topics:

  1. Understand the Large Data Volumes: You should understand the large data volume consideration, mitigations.  You have to keep in mind few things while loading Large Volume Data(more than 2 million records)
    • Disable triggers and workflows
    • Defer calculation of sharing rules
    • Insert or Update is faster than Upsert
    • Group and sequence data to avoid parent record locking
    • Tune the batch size (HTTP keepalives, GZIP compression)
  2. Data Skewing : Very useful post
  3. Query Performance, Indexes:

                    Indexes:             

                 If your SOQL Queries running very slow salesforce uses Indexes to speed of                         the soql queries. We can create Custom Indexes by contacting Salesforce                                Customer support.

        Which Fileds automatically Indexed?

  •   RecordTypeID
  • Division
  • Created Date
  • Systemmodstamp
  • Name
  • Email (For Contacts and Leads)
  • Foreign key relationships (Look up and master Detail)
  • The unique Salesforce Record Id, Which is the primary key for every object
  • Unique Ids, External ID(Auto number, Email, Number, Text)
  • Salesforce also supports custom indexes on custom fields.

    Which fields cannot be added as Custom Index?

  • Multi-select picklists,
  • text areas (long),
  • text areas (rich),
  • non-deterministic Formula fields( A formula consider as not deterministic when it includes Owner, atonumber, Divisions , audit fields except CreatedDate and CreatedById,  Refernce other entities, use dynamic date and time functions like Today(). Now(), includes other formula fields)
  • encrypted text fields.
  1. Skinny Tables : Very useful post
  2. Bulk API: A must read topic. Be aware of Parallel Loading, Serial Loading. Default is parallel loading.
  3. PK chunking :  Understand how PK chunk works. Enable it by adding sforce-Enable-pkchunking to header 
  4.  MDM (Master Data Management) : Very Useful post
  5. Record Lock contention:       You should be aware on avoiding data locks during data load.
    1. Re-order the record id’s so that it will handle in sequence order
    2. Group by Master record id’s while loading child records
    3. Be aware of data locks occurring for Bulk API
  6. Duplicate Management :  By enabling duplicate and matching rules on Accounts,                   Contacts and Leads. And be aware of tools you can use for reduplication.
  7. Difference between Custom Metadata Type and Custom setting:  Custom metadata is customizable, deployable, packageable, and upgradeable application metadata.
  8. Difference between SOQL and SOSL? Best practices while using SOSL and SOQL? SOQL: Query for specified object. You can chooses Indexed fields in filters. Runs on  database level.  SOSL:  Searches for multiple objects. Search for indexes first. Best Practices:
    1. Replace Null with NA in where clause filter if it is pick list field
    2. Decompose the query—if you are using two indexed fields joined by an OR in the WHERE clause, and your search has exceeded the index threshold, break the query into two queries and join the results.
    3. If querying on formula fields is required, make sure that they are deterministic formulas
    4. Search for Specific value instead of wildcard (%)
    5. Search in all fields.
    6. Keep the number of fields to be searched or queried to a minimum.
  9. Difference between deterministic and non-deterministic formula fields
  10.  Work flow Rules, Outbound Messages, Validation Rules and Triggers
  11. Difference between Normalization and De-normalization
  12. Data Quality & Data Governance, Data.com
  13. Analytic Snapshot
  14. Testing Environment
  15. Use of External Ids
  16. Use of Appexchange Products and ETL tools

Useful Blogs:

Cory Cowgill

Always a blezard 

SalesforceMemo

 

 

 

Client side caching-Storable Actions (Improve performance of lightning components)

Storable Actions are a great way to enhance your lightning component performance.

By using storable actions,  We can cache the data at the client side and it can significantly reduce the number of server calls and improve the performance of your lightning component.

In Lightning terminology, a server action is an Apex method that you invoke remotely from your Lightning Component. A storable action is a server action whose response is stored in the client cache so that subsequent requests for the same server method with the same set of arguments can be accessed from that cache.

How does Storable action works? 

If you call setStorable method before calling the server side method, then the platform compares previous server call with the current server call. If the parameters to the both server calls same, then it skip the server call and return the response from client side cache. This saves the server round trip and improves the lightning component performance. 

Caching is especially beneficial for users on high latency, slow, or unreliable connections such as 3G networks.

For storable actions in the cache, the framework returns the cached response immediately and also refreshes the data if it’s stale. Therefore, storable actions might have their callbacks invoked more than once: first with cached data, then with updated data from the server.

While using storable actions , the cache behavior is controlled by two parameters set internally in the framework. Those are

Expiration Age (Default Expiration): This is the age of the cached response. Whenever the response is older then the existing one and same vice versa. Expiration age is currently set to 900 seconds in Salesforce lightning.

Refresh Age(defaultAutoRefreshInterval): Refresh age is the age of the response, when it gets refreshed, if the response is newer then the existing one, it will override the response, but lightning also calls the server method and get the response, if it different than the existing then it will override it as well. Refresh age is 30 second in lightning experience.

How to mark an Action as Storable?

To mark a server-side action as storable, call setStorable() on the action in JavaScript code using  Action.setStorable();

The setStorable function can take optional argument(ignoreExisting , the default value is : false), which is configuration map of key-value pairs representing the storage options and values to set.

Even though storable actions are automatically configured in Lightning Experience and Salesforce1, any Stand-alone Lightning apps that are used to host your components will NOT use caching by default.

For these apps to use storable actions, you must do following things:

  1. Create a component and include <aura:storage:init> tag

<aura:component isTemplate=”true” extends=”aura:template”>

    <aura:set attribute=”auraPreInitBlock”>

        <auraStorage:init

          name=”actions”    //the storage name must be “actions”

          persistent=”false”  // Set to true to preserve cached data between user sessions in the browser.

          secure=”true”        //Set to true to encrypt cached data.

          maxSize=”1024″   //

          defaultExpiration=”900″   //The duration in seconds that an entry is retained in storage.

          defaultAutoRefreshInterval=”30″  //The duration in seconds before an entry is refreshed in storage./>

    </aura:set>

</aura:component>

  1. Call above component in the aura:application tag of your Lightning Standalone app as below,

Template = “c.yourabovecomponentname”.

Once you do this, you should be able to see the caching working for any component used in that app that calls the action.setStorable().

That’s it!

Level of Data Access in Salesforce(Object Level, field Level and Record Level)

Level of Data Access in Salesforce:

As an admin, you can control which users have access to which data in your whole org, a specific object, a specific field, or an individual record.

Below are the different types used to access/restrict the data

  1. Object Level Security:

Using object permissions you can prevent a user from seeing, creating, editing, or deleting any instance of a particular type of object. Object permissions let you hide whole tabs and objects from particular users, so that they don’t even know that type of data exists.

Where we can specify Object Level Permissions:

You can specify Object permissions in Profiles and Permission Sets

  1. Field-Level Security:

If you want to protect sensitive fields without hiding whole object from user, you can choose Field level security.

Where we can specify Field Level Permissions:

You can specify Field permissions in Profiles and Permission Sets

Field-level security doesn’t prevent searching on the values in a field. When search terms match on field values protected by field-level security, the associated records are returned in the search results without the protected fields and their values.

  1. Record Level Security:

Record-level security lets you give users access to some object records, but not others. Every record is owned by a user or a queue. The owner has full access to the record. In a hierarchy, users higher in the hierarchy always have the same access to users below them in the hierarchy. This access applies to records owned by users, as well as records shared with them.

  1. Organization – Wide Sharing Default:

Admins can use Organization-wide sharing settings to define the default sharing setting for an organization. Use OWD to lock down your data, and then use Role hierarchies, Sharing Rules , Manual Sharing to open up the access.

Determine the org-wide defaults 

  1. Who is the most restricted user of this object?
  2. Is there ever going to be an instance of this object that this user shouldn’t be allowed to see?
  3. Is there ever going to be an instance of this object that this user shouldn’t be allowed to edit?

OWD access

Bases on your answers you can set one of these.

  • Private : Records visible to the owner of the Record and above them in the Role hierarchy(By enabling Grant Access Using Hierarchies)
  • Public Read-only: All users can view all Records for the object
  • Public Read/Write : All users can view and edit all Records for the object
  • Public Read/Write/Transfer (applicable for Leads and Cases)
  • Controlled By Parent: Users can perform actions (such as view, edit, delete) on a record on the detail side of a master-detail relationship if they can perform the same action on all associated master records

In environments where the Organization-wide sharing settings can be set to Private or Public Read-only, an administrator can grant users additional access to records by setting up a role hierarchy or defining sharing rules.

However, sharing rules can only be used to grant additional access—they cannot be used to restrict access to records beyond what was originally specified with the organization-wide sharing defaults.

How to Set Up Organization Wide Sharing Defaults?

  1. Setup -> Sharing Settings in Quick find box -> Sharing Settings
  2. Click Edit in the OWD area
  3. For Each object, Select the default access you want to use.
  4. If Grant Access using Hierarchies is deselected, users that are higher in the role or territory hierarchy don’t receive automatic access. However, some users—such as those with the “View All” and “Modify All” object permissions and the “View All Data” and “Modify All Data” system permissions—can still access records they don’t own

Considerations while Updating Organization-wide defaults?

When you updating OWD, Sharing Recalculation applies the access changes to your records. If you have lot of data the update will take longer.

  1. If you are increasing the default access, Such as from Public Read Only to Public Read/Write, your changes take effect immediately. All users get access based on the updated default access. Sharing recalculation is then run asynchronously to ensure that all redundant access from manual or sharing rules are removed.
  2. If you are decreasing the default access, such as from Public Read/Write to Public Read Only, your changes take effect after recalculation is run
  3. When the default access for contacts is Controlled by Parent and you increase the default access for accounts, opportunities, or cases, the changes take effect after recalculation is run.

External Organization-Wide Default:

External organization-wide defaults provide separate organization-wide defaults for internal and external users. They simplify your sharing rules configuration and improve recalculation performance. Additionally, administrators can easily see which information is being shared to portals and other external users.

External Users include the following:

  • Community Users
  • High-Volume Portal Users
  • Customer Portal Users
  • Partner Portal Users
  • Service Cloud Portal Users
  • Authenticated Website Users
  • Chatter External Users
  • Guest Users

All Objects supports External Organization – Wide Defaults?

No only following objects supports external organization-wide defaults

  • Accounts and their associated contracts and assets
  • Contacts
  • Opportunities
  • Cases
  • Users
  • Custom Objects

With separate organization-wide defaults, you can achieve similar behavior by setting the default internal access to Public Read Only or Public Read/Write and the default external access to Private. These settings also speed up performance for reports, list views, searches, and API queries.

How to set up External Organization-Wide Defaults?

First thing first, you need to enable External sharing Model before you set the external sharing model

Enable external Sharing

Set up -> Sharing Settings -> click the Enable External Sharing Model Button

When you first enable external organization-wide defaults, the default internal access and default external access are set to the original default access level.

 For example, if your organization-wide default for contacts is Private, the default internal access and default external access will be Private as well.

After Enabling External Sharing, Edit the OWD and for each object select the default access you want to use.

Click save.

External2

How to Disable External Organization-wide defaults:

Before disabling this feature, set Default External Access and Default Internal Access to the same access level for each object.

To disable the external organization-wide defaults:

  1. From Setup, enter Sharing Settings in the Quick Find box, then select Sharing Settings
  2. Click Disable External Sharing Model in the Organization-Wide Defaults area. After disabling the external organization-wide defaults, you’ll see the Default Access setting instead of the Default External Access and Default Internal Access settings in the organization-wide defaults area.

 If you have User Sharing, the Default External Access settings for the account, contact, case, and opportunity objects remain visible but they are disabled.

  1. Role Hierarchy:

Once you’ve specified organization-wide sharing settings, the first way you can give wider access to records is with a role hierarchy.

A Role Hierarchy represents a level of data access that a user or group of users needs. The Role hierarchy ensures that manager always have access to the same data as their employees, regard less of the OWD settings.

An organization is allowed 500 roles; however, this number can be increased by Salesforce. As a best practice, Keep the number of non-portal roles to 25,000 and the number of portal roles to 1,00,000

As a best practice keep the role hierarchy to no more than 10 levels of branches in the hierarchy.

If any user who will own millions of records , make sure that that user has no role to optimize performance issues.

  1. Sharing Rules:

Sharing rules can only be used to grant additional access. These are automatic exception to your OWD sharing settings for selected set of users. There are two types of sharing Rules.

  • Owner Based Sharing Rule: Share Records based on Owner

Set up -> Sharing Settings ->  Sharing rules (Select the object sharing rule for which you want to create Sharing rule) -> New

Sharing Rule

  • Criteria Based Sharing Rule: Determine what records to share based on field values other than ownership.

We can share records to: Individual Users Roles, roles and sub ordinates, Public Group

 

  1. Manual Sharing: Record owners can use manual sharing to give read and edit permissions to users who would not have access to the record any other way. Although manual sharing isn’t automated like organization-wide sharing settings, role hierarchies, or sharing rules, it gives record owners the flexibility to share particular records with users that need to see them. Temporary ownership assignment done by using this type.  

Sharing button

          By clicking the sharing button on Record level we can share records to users, Roles,           Roles and Subordinates, Public Groups.

  1. Apex Managed Sharing: If sharing rules and manual sharing don’t give you the control you need, you can use Apex managed sharing. Apex managed sharing allows developers to programmatically share custom objects. Every Object in the database has a “Share” Table. Using Apex, a developer can add entries to a Share table and thus grant access. When you use Apex managed sharing to share a custom object, only users with the “Modify All Data” permission can add or change the sharing on the custom object’s record, and the sharing access is maintained across record owner changes.
  2. Team SharingBy adding users to the Account Team or opportunity Team(sales Team) or Case Teams, we can share records to the users.

The below is the sharing architecture follow in salesforce.

123467

Shield Platform Encryption

In this post, I am sharing details about shield platform encryption.

What is Shield Platform Encryption:  Shield Platform Encryption gives your data a whole new layer of security while preserving critical platform functionality. 

It enables you to encrypt sensitive data at rest as well as while transmitted over network.

Shield Platform Encryption builds on the data encryption options that Salesforce offers out of the box. Data stored in many standard and custom fields and in files and attachments is encrypted using an advanced HSM-based key derivation system, so it is protected even when other lines of defense have been compromised.

Your data encryption key is never saved or shared across organizations. Instead, it is derived on demand from a master secret and your organization-specific tenant secret, and cached on an application server.

How to enable Shield Platform Encryption?

Generate Tenant key in the org:

Before you can encrypt data, an authorized administrator with the “Manage Encryption Keys” must generate a tenant key. (Enable Manage Encryption Keys at profile level or by using Permissionset)

      Go to Setup -> Platform Encryption -> Key Management

               Click on Generate Tenant Secret button

     generate tenant

Here we can choose two types of Tenant Secret types. Those are “Data in salesforce” and “Search Index”

  1. Which fields can be encrypted:

By using shield platform encryption we can encrypt standard fields, custom fields, files  etc.

 To encrypt Standard fields, navigate to setup->Platform Encryption->Encryption Policy

 Click on “Encrypt Fields” link.

Encrypt fields link

Edit the page and Select the fields you want encrypt and save.

standard field selection

To Encrypt Custom Fields: 

Go to the Custom Field -> Edit -> check “Encrypted checkbox.Custom field encryption

To Encrypt Files and Attachments:

Navigate to Setup-> Platform Encryption -> Encryption Policy

 Select Encrypt Files and Attachments

Hit Save.

Notes:

  • For newly created records the values will be automatically encrypted
  • If the field is created newly, then existing records needs to be updated(No changes required just hit on save button. The behavior is like any other operations). Other option would be by loading csv file through data loader but for those updates Last Modify By and Last Modify Date changes.
  • If you want to update records without effecting Last Modified Date and all contact salesforce.
  • Encrypted fields cannot be used in report filters and list views. But those fields can be used a column to display value. If field has been used in the report already, then making field as encrypted will automatically remove the filters from the report.
  • Encrypted fields are not sortable

How do we track whether the field is encrypted or nor?   

If you are an authorized user to access the record, the data will display normally in record. So how can we track whether the fields are encrypted or not. First thing we can check the filed information from Workbench

  1. WorkBench: you can log in to the Workbench

Info-> Standard & Custom Object -> Select the object

Then expand Fields folder -> Select the field which you have encrypted. In details you will get Encrypted to true

Field describe

2. By Destroying the Tenant Key:   If you destroy the tenant key you will directly see the encrypted fields result at record level. To get authorized access again to encrypted fields  import the tenant key.

Encryption Statistics:

Encryption Statistics will provide you complete report on how much data is encrypted by Shield Platform Encryption and how much of data is encrypted by an active tenant secret.

               Setup -> Platform Encryption -> Encryption Statistics

Select the object and click on Gather Statistics button. The result will shown as below

statistics

Encryption Best Practices:

  1. Define threat model for your org
  2. Encrypt only necessary data
  3.  Back up and Archive Tenant keys and data
  4.  Grant the “Manage Encryption Key” permission to authorized users

Considerations: 

  1. Lead and Case assignment rules, workflow rules, and validation rules work normally when Lead fields are encrypted. 
  2. You can’t use encrypted custom fields in criteria-based sharing rules.
  3.  Fields that are Unique or External Id , Fields on External data objects and fields that are used in account contact relation can not be encrypted
  4. You can not use schema builder to create encrypted fields
  5. Encrypted fields can not be used with the SOQL or SOSL functions like –  aggregate functions(Min(), Max(), Count_Distinct()), Where clause, Group By clause, Order By clause
  6.  If portals are enabled in your organization, you can not encrypt standard fields. Deactivate all customer portals and partner portals to enable
    encryption on standard fields. (Communities are supported.)
  7. You don’t get autosuggestions via the REST API when a field is encrypted.
  8. Campaign member search isn’t supported when you search by encrypted fields
  9. Items in an Activity History related list may be displayed in plaintext even if the fields they refer to are encrypted.
  10. When the standard Email field is encrypted, email to Salesforce can’t receive inbound emails
  11. When the standard Email field is encrypted, the detail page for Contacts, Leads, or Person Accounts doesn’t flag invalid email
    addresses. If you need bounce processing to work as expected, don’t encrypt the standard Email field.

Difference between Classic Encryption and Shield Encryption:

With Shield Platform Encryption, you can encrypt a variety of widely used standard fields, along with some custom fields and many kinds of files. Shield Platform Encryption also supports person accounts, cases, search, approval processes, and other key Salesforce features. Classic encryption lets you protect only a special type of custom text field, which you create for that purpose.
Feature Classic Encryption Platform Encryption
Pricing Included in base user license Additional fee applies
Encryption at Rest Checkmark Checkmark
Native Solution (No Hardware or Software Required) Checkmark Checkmark
Encryption Algorithm 128-bit Advanced Encryption Standard (AES) 256-bit Advanced Encryption Standard (AES)
HSM-based Key Derivation   Checkmark
Manage Encryption Keys Permission   Checkmark
Generate, Export, Import, and Destroy Keys Checkmark Checkmark
PCI-DSS L1 Compliance Checkmark Checkmark
Masking Checkmark  
Mask Types and Characters Checkmark  
View Encrypted Data Permission Required to Read Encrypted Field Values Checkmark  
Encrypted Standard Fields   Checkmark
Encrypted Attachments, Files, and Content   Checkmark
Encrypted Custom Fields Dedicated custom field type, limited to 175 characters Checkmark
Encrypt Existing Fields for Supported Custom Field Types   Checkmark
Search (UI, Partial Search, Lookups, Certain SOSL Queries)   Checkmark
API Access Checkmark Checkmark
Available in Workflow Rules and Workflow Field Updates   Checkmark
Available in Approval Process Entry Criteria and Approval Step Criteria   Checkmark

Summer’18 Development Highlights

Summer’18 Development Highlights:

  1. Switch Statement :

Apex now provides a “Switch” statement that test whether an expression matches one of several values and branches accordingly.

Syntax:

Switch on expression {

when value1 {  //when block1

//execute block 1

}

when value2, value5 {  // when block 2, block5

//execute block2, block5

}

when value 3 {   // when block 3

//execute block3

}

When else {  // when else block , optional

               // execute block4

}

}

 

The switch statement evaluates the expression and executes the code block for the matching when value. If no value matches, the code block for the when else block is executed. If there isn’t a when else block, no action is taken.

 

  1. Get the Developer Name for Record Types :

Till now Developer name for Record types accessed via SOQL on the RecordTypeSobject.

Ex: SELECT id, Name, DeveloperName FROM RecordType where SObjectType =”Account”

 

But summer’18 onwards we can get Developer Name for RecordTypes via Describe Method.

The following are the methods:

  • DescribeSobjectResult.getRecordTypeInfosByDeveloperName()
  • RecordTypeInfo.getDeveloperName()

 

  1. The SOQL Count() function does not towards limits:

Each Individual record retrieved via SOQL Count() and Count(field) functions counted towards the query row limit. It has significant impact on governor limits

Ex: Integer countOfAccounts = [select count() from Account];

Previously, The number of records matched by this query counted towards the governor limits.

Summer’18 onwards if the query using its function to return an integer then the query counts only one query row towards the limit. Now the above query counts as only One query row towards the limits.

If a query using one of these functions returns an array of AggregateResult objects, only the total number of AggregateResult objects counts toward the limit.

The following query uses the COUNT(fieldName) function.

AggregateResult ar = [SELECT COUNT(AccountId) rowcount FROM Contact]; // Count contacts with an account only

Integer rowCount = (Integer)ar.get(‘rowcount’);

If a query that uses the COUNT(fieldName) function contains a GROUP BY clause, only the number of resulting AggregateResult objects count toward the limit.

For example, in the query in the following example, only one item per aggregated result is counted toward the limit.

List res = [SELECT COUNT(id) FROM Contact GROUP BY AccountId]; System.assertEquals(res.size(), Limits.getQueryRows());

Previously, all the records matched by this query counted toward the query row limit.

  1. Clear Messages on Visualforce pages:

Summer’18 onwards we can use the System.Test.clearApexPageMessages() method to test the success or failure of each call to controller methods.

Using this function along with the ApexPages.hasMessages() and ApexPages.getMessages() methods allows you to test Visualforce controllers more easily

  1. Apex code Size limit Increased:

The maximum amount of Apex code that you can use in an org has been doubled, from 3 MB to 6 MB. . If your org was previously approved for an increase above 6 MB, it remains unchanged.

  1. Apex Exception Email Recipients Can receive Process and Flow Error Emails:

Previously the Apex Exception Email page was used only for Apex exceptions. Now you can also use it for process and flow error emails.

  1. New Apex Enums:

The following enumerations are introduced in this release

  • VerificationMethod Enum:

This enum has the following values, which correspond to identity verification methods.

  • Email
  • Salesforce_Authenticator
  • SMS
  • TOTP
  • U2F
  • TriggerOperation Enum

This enum has the following values, which correspond to trigger events.

  • AFTER_DELETE
  • AFTER_INSERT
  • AFTER_UNDELETE
  • AFTER_UPDATE
  • BEFORE_DELETE
  • BEFORE_INSERT
  • BEFORE_UPDATE
  1. Update Multiple validation Rules with Custom MetadataType Records:

With custom metadata type records available to reference in validation rules, you don’t need to hard code values. Reference the records directly within the validation rules to avoid adding the same values to each rule. The ability to reference custom metadata type records helps subscriber orgs, too. Previously, when you added a validation rule to a managed package, a subscriber could not edit it. Now you can define the logic and leave customization to a subscriber.

Consider a validation rule that limits the discount on a brand to 10%. You decide to change the discount, so the validation rules that use this value need updating. Rather than update multiple rules that check the discount amount, reference a custom metadata record within the validation rules. Then, you can update the discount amount in the custom metadata record without modifying the validation rule

 

 

 

 

 

Switch Statement in Apex and Trigger

Switch statement in Apex:

Summer’18 onwards Apex supports “Switch” statement and that supports whether an expression is matches one of several values and branches accordingly.

Below are few benefits of using Switch :

  • We can simplifies long if/else logic chains
  • Reduce code duplication
  • It will improve Trigger flow with help of context enum
  • Familiar to developers from all back ground
  • Handle fields over polymorphic Sobject type (implicit casting)

Considerations: 

  • Performance might be slow when compared to If/Else (it is my personal opinion)

Obstacles:

  • Case is not a keyword in Apex as we have Case Sobject in salesforce

Syntax of the Switch:

witch on expression {

    when value1 {              // when block 1

        // code block 1

    }  

    when value2 {              // when block 2

        // code block 2

    }

    when value3 {              // when block 3

        // code block 3

    }

    when else {          // default block, optional

        // code block 4

    }

}

Where value can be a single value, multiple values, or Sobject types.

Improvement of Trigger Flow by using “Trigger.OperationType” context variable:

Till now we have 7 boolean context variables Those are,

  • Before insert,
  • Before Update
  • Before Delete
  • After Insert
  • After Update
  • After Delete
  • After Undelete

With the new Switch statement we can use new context variable called “Trigger.OperationType

 The following example illustrates the usage of trigger.operationType

trigger triggerSyntax on custObj (before insert, after insert, before update, after update, before delete, after delete, after undelete) {

        triggerHandler.handleTrigger(Trigger.new, Trigger.old, Trigger.operationType);

}

Handler Class:

public with sharing class triggerHandler {

    public static void handleTrigger(List<CustomObject__C> newRecords, List<CustomObject__c> oldRecords, System.TriggerOperation triggerEvent ) {

           switch on triggerEvent {

                   when AFTER_INSERT, AFTER_UPDATE {

                    // Do required stuff

                           }

            when BEFORE_INSERT {

                        // Do required stuff

            }

            when AFTER_DELETE {

                //prevent deletion of sensitive data

            }

            when else {

                //do nothing for AFTER_UNDELETE, BEFORE_DELETE, or BEFORE_UPDATE

            }

        }

    }

}