Sunday, June 19, 2022

ES12 new Features

ES12 is a version issued by the ECMA Association in 2021. Because it is the twelfth version of ECMAScript, it is also called ES12.

The following is the list of the latest javascript features.

  1. String.prototype.replaceAll()
  2. WeakRefs
  3. Logical Assignment Operator
  4. Numeric Separators
  5. Promise. any
  6. Private class methods

String.prototype.replaceAll():

This method addresses a specific lack in String.prototype.replace.

With the String.replaceAll you can easily replace all occurrences of a given string.

Syntax: String.prototype.replaceAll(searchString, replace string)

For example:
const string=" flyer is a good fly"
console.log(string.replaceAll("fly", "butterfly"));

Output: butterfly is a good butterfly

WeakRefs:

WeakRef is the shorthand for Weak References, and its primary use is to hold a weak reference to another object.

That means it does not prevent the garbage collector from collecting the object.

The Weak Reference is useful when we do not want to keep the object in the memory forever.

But why do we need the WeakRef in the first place?

In JavaScript, the object is not collected by the garbage collector as long as a reference to that object exists.

Thus, it keeps the object in the memory, which leaves you with less memory. The WeakRef implementation allows you to avoid that.

You can create a Weak Reference by using the new WeakRef, and you can read a reference by calling the deref() method.

A simple example would be:

const large object = new WeakRef({
name: "CacheMechanism",
type: "Cache",
implementation: "WeakRef"
});

large object.deref();

Logical Assignment Operator:

You might be familiar with logical operations like ??, &&, or || and the assignment operator =. The Logical Assignment Operator introduced in ES2021 combines logical operations like ??, && or || with an assignment operator =.

Let’s see an example:

var a = true
var b = false
// Old
if (!a) {
  a = b
}
// New
a ||= b // returns a
// Old
if (a) {
  a = b
}
// New
a &&= b // returns b

Numeric Separators:

This feature literally improves developer experience by enabling developers to make their numeric literals more readable by creating a visual separation between groups of digits.

It’s similar to the way we use commas to separate numbers in writing. For example:

const balance = 9_300_254_812

JavaScript
Using the underscore, deciphering the above number becomes a no-brainer, in contrast to not using the underscore as shown below.

const balance = 9300354812

Promise. any:

Promise. any() takes an iterable of Promise objects.

It returns a single promise that resolves as soon as any of the promises in the iterable fulfills, with the value of the fulfilled promise.

If no promises in the iterable fulfill (if all of the given promises are rejected), then the returned promise is rejected with an AggregateError, a new subclass of Error that groups together individual errors.

Example:

const promise1 = Promise.reject(0);
const promise2 = new Promise((resolve) => setTimeout(resolve, 100, 'quick'));
const promise3 = new Promise((resolve) => setTimeout(resolve, 500, 'slow'));
const promises = [promise1, promise2, promise3];
Promise.any(promises).then((value) => console.log(value));

Private Class Methods and Accessors:

The class methods and properties are public by default, but the private methods and properties can be created

by using a hash # prefix. The privacy encapsulation has been enforced from the ECMAScript 2021 update.

Tuesday, June 14, 2022

Simple Introduction to Web Workers in JavaScript

 JavaScript is an object-based scripting language which is lightweight and cross-platform. It is an interpreted, full-fledged programming language that enables dynamic interactivity on websites when applied to an HTML document.

Even though js had so many advantages, it is having some drawbacks. It is Single threaded language. This means it has one call stack and one memory heap. As expected, it executes code in order and must finish executing a piece code before moving onto the next.

To resolve the above one,we can use Web worker.

A web worker is a JavaScript code that runs in the background and does not influence the page’s performance.

Web Workers are background scripts and they are relatively heavy-weight, and are not intended to be used in large numbers. Although Web Workers cannot block the browser UI, they can still consume CPU cycles and make the system less responsive.

In HTML5 Web Workers are of two types:

Dedicated Web Workers:
The dedicated worker can be accessed by only one script which has called it. The dedicated worker thread end as its parent thread ends. Dedicated workers are only used by one or single main thread.

Shared Web Workers:
It can be shared by multiple scripts and can communicate using the port. Shared workers can be accessed by different windows, iframes or workers.

Common examples of web workers would be:

1)Dashboard pages that display real-time data such as stock prices, real-time active users, and so on
2)Fetching huge files from the server
3)Autosave functionality

You can create a web worker using the following syntax:

const worker = new Worker(".js");

Worker is an API interface that lets you create a thread in the background. We need to pass a parameter, that is a .js file. This specifies the worker file the API needs to execute.

A worker can be shared or used by multiple consumers/scripts. These are called shared workers. The syntax of the shared worker is very similar to that of the above mentioned workers.

const worker = new SharedWorker(".js");

Terminating the Web Worker:
If you want to immediately terminate the currently running worker in the main thread, then you can terminate it by calling the terminate() method of Web Worker. Here is the syntax for web worker termination:

worker.terminate();

Worker Example:

<!DOCTYPE html>  
<html>  
<head>  
  <style>  
    .div1{  
      margin-left: 350px;  
    }  
  </style>  
</head>  
<body>  

<div class="div1">  
  <h2>Example of Web Worker</h2>  
<label>Enter the number to find the square</label>  
<br><input type="text" name="num" id="num"><br>  
<br><button id="submit">Submit</button>  
<button id="other">Wait</button>  
<div id="text"></div>  
</div>  
<script type="text/javascript">  
  
document.getElementById("other").onclick=function() {  
  alert("Hey! Web Worker is working, and you can wait for the result.");  
}  
  
//Web-worker Code
  var worker= new Worker("worker.js");  
  worker.onmessage= function(event){  
  document.getElementById("text").innerText= event.data;}  
  document.getElementById("submit").onclick= function(){  
  var num= document.getElementById("num").value;  
  worker.postMessage(num);  
 }  
</script>  
<p>
</body>  
</html> 
  • var worker= new Worker("worker.js"); To create the web Worker object.
  • worker.onmessage= function(event): It is used to send the message between the main thread and Worker thread.
  • worker.postMessage(num); This is the method used to communicate between the Worker thread and main thread. Using this method Worker thread return the result to the main thread.

Note: Use the below link to test whether your browser is compatible with html5 feature.

http://html5test.com/

Saturday, June 4, 2022

Dependency Tree in Maven

Dependency management is a core feature of Maven. Managing dependencies for a single project is easy.

Managing dependencies for multi-module projects and applications that consist of hundreds of modules is possible.

Maven avoids the need to discover and specify the libraries that your own dependencies require by including transitive dependencies automatically.

This feature is facilitated by reading the project files of your dependencies from the remote repositories specified.

In general, all dependencies of those projects are used in your project, as are any that the project inherits from its parents, or from its dependencies, and so on.

A project's dependency tree can be filtered to locate specific dependencies.

Maven is powered with Dependency plugin by default.With this plugin, we can have a better understanding and control over the list of dependencies used in a specific project.The plugin comes with several goals.

mvn dependency:tree  is the Command

The main purpose of the dependency:tree goal is to display in form of a tree view all the dependencies of a given project.


Thursday, June 2, 2022

Create Executable from Python Script using Pyinstaller

 PyInstaller works by reading your Python program, analysing all of the imports it makes, and bundling copies of those imports with your program.

PyInstaller reads in your program from its entry point. For instance, if your program’s entry point is myapp.py, you would run pyinstaller myapp.py to perform the analysis.

PyInstaller can detect and automatically package many common Python packages, like NumPy, but you might need to provide hints in some cases.

After analyzing your code and discovering all the libraries and modules it uses, PyInstaller then generates a 'spec file'.

 A Python script with the extension. spec, this file includes details about how your Python app needs to be packed up.

PyInstaller can be installed using following command.

pip install pyinstaller

Steps to create Executable App in python:

1)Create a python file and write some code and save the file with .py extension (Example:Hellow.py).

2)cd\ to the saved file location.

3) Use the following template to create executable:

pyinstaller --onefile Hellow.py

4)Run the command in CMD.After executing step3 from CMD,executable file will be created in the same location.

5)After step 4, few folders and files will be added by pyinstaller into your App folder.

6)Identify dist folder and cd into the folder.


7)Now you will see the Hello App executable in same location. 

Now you will be able to launch your application successfully.

Content Security Policy in Salesforce

 The Lightning Component framework uses the Content Security Policy (CSP) to impose restrictions on content. 

The main objective is to help prevent cross-site scripting (XSS) and other code injection attacks.

 To use third-party APIs that make requests to an external (non-Salesforce) server or to use a WebSocket connection, add a CSP Trusted Site.


CSP is a W3C standard that defines rules to control the source of content that can be loaded on a page. All CSP rules work at the page level and apply to all components and libraries.

When you define a CSP Trusted Site, the site’s URL is added to the list of allowed sites for the following directives in the CSP header.

  • connect-src
  • frame-src
  • img-src
  • style-src
  • font-src
  • media-src

This change to the CSP header directives allows Lightning components to load resources, such as images, styles, and fonts, from the site. It also allows client-side code to make requests to the site.

Path

From Setup, enter CSP Trusted Sites in the Quick Find box, and then select CSP Trusted Sites.






1. Enter the site URL
2. Select the Context for this trusted site to control the scope of the approval.
All  -  (Default)CSP header is approved for both your organization’s Lightning Experience and Lightning Communities.

LEX - CSP header is approved only for your organization’s Lightning Experience.

Communities - CSP header is approved only for your organization’s Lightning Communities.

 


The framework enables these specific CSP rules:

 JavaScript libraries can only be referenced from your org

All external JavaScript libraries must be uploaded to your org as static resources. The script-src 'self' directive requires script source be called from the same origin.

 Resources must be located in your org by default

The font-src, img-src, media-src, frame-src, style-src, and connect-src directives are set to 'self'. As a result, resources such as fonts, images, videos, frame content, CSS, and scripts must be located in the org by default.

 You can change the CSP directives to permit access to third-party resources by adding CSP Trusted Sites.

 HTTPS connections for resources

All references to external fonts, images, frames, and CSS must use an HTTPS URL. This requirement applies whether the resource is located in your org or accessed through a CSP Trusted Site.

 

Inline JavaScript disallowed

Script tags can’t be used to load JavaScript, and event handlers can’t use inline JavaScript. The unsafe-inline source for the script-src directive is disallowed. For example, this attempt to use an event handler to run an inline script is prevented:

<button onclick="doSomething()"></button>

Note:

CSP isn’t enforced by all browsers. For a list of browsers that enforce CSP, see caniuse.com.

IE11 doesn’t support CSP, so we recommend using other supported browsers for enhanced security.

Finding CSP Violations

CSP policy violations are logged in the browser’s developer console. The violations look like the following message.

Refused to load the script 'https://externaljs.docsample.com/externalLib.js'

because it violates the following Content Security Policy directive: ...

If your app’s functionality isn’t affected, you can ignore the CSP violation.

Stricter CSP Restrictions

The Lightning Component framework uses Content Security Policy (CSP), which is a W3C standard, to control the source of content that can be loaded on a page. The CSP rules work at the page level, and apply to all components and libraries, whether Lightning Locker is enabled or not.

The “Enable Stricter Content Security Policy” org setting was added in the Winter ’19 release to further mitigate the risk of cross-site scripting attacks. This setting was enabled by default.

Saturday, May 28, 2022

Shadow DOM

 Shadow DOM is just normal DOM with two differences:

 1) how it's created/used and

 2) how it behaves in relation to the rest of the page. 

Normally, you create DOM nodes and append them as children of another element. 

With shadow DOM, you create a scoped DOM tree that's attached to the element, but separate from its actual children. This scoped subtree is called a shadow tree. 

The element it's attached to is its shadow host. Anything you add in the shadows becomes local to the hosting element, including <style>. This is how shadow DOM achieves CSS style scoping.

There are some bits of shadow DOM terminology to be aware of:

Shadow host: The regular DOM node that the shadow DOM is attached to.

Shadow tree: The DOM tree inside the shadow DOM.

Shadow boundary: the place where the shadow DOM ends, and the regular DOM begins.

Shadow root: The root node of the shadow tree.

A DOM element can have two types of DOM subtrees:

Light tree – a regular DOM subtree, made of HTML children. 

Shadow tree – a hidden DOM subtree, not reflected in HTML, hidden from prying eyes.

If an element has both, then the browser renders only the shadow tree. But we can setup a kind of composition between shadow and light trees as well. 



Tuesday, May 10, 2022

Trigger Order of Execution

In Salesforce there is a particular order in which events execute whenever a record is changed or inserted. 

Below are the steps of trigger execution:

Step 1:

 Load the original record or initialize on insert.

Step 2:

 Override the old record values with the new values.

Step 3:

 Execute all before triggers.

Step 4:

 Run the system & user-defined validation rules.

Step 5:

 Save the record but do not commit the record to the database.

Step 6:

 Execute all after triggers.

Step 7:

 Execute the assignment rules.

Step 8:

 Execute the auto-response rules.

Step 9:

 Execute the workflow rules.

Step 10:

 If there are workflow field updates then execute the field update.

Step 11:

 If the record was updated with a workflow field update then execute before and after triggers created on the  object in the context again but only once.

Step 12:

 Execute the processes on that record.

Step 13:

 Execute the Escalation rules.

Step 14:

 Update the roll up summary fields & cross object formula fields.

Step 15:

 Repeat the same process with the affected parent or grand-parent records.

Step 16:

 Evaluate criteria based sharing rules.

Step 17:

 Commit all DML operations to the database.

Step 18:

 Execute post commit logic such as sending E-mails

ES12 new Features