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

Monday, May 9, 2022

Salesforce DX Setup Guide

 The Salesforce Developer Experience (DX) is a set of tools that streamlines the entire development lifecycle. It improves team development and collaboration, facilitates automated testing and continuous integration, and makes the release cycle more efficient and agile.

Advantages of Salesforce DX

·         It helps improve team collaboration and development

·         It makes the release cycle process more agile and efficient

·         It allows developers to use any tool to modify the code such as CLI, VIM, Sublime, Atom, etc.

·         Facilitates automated testing for your code and enables continuous integration

·         Requires a local development setup for developers to get hands-on expertise

Components of Salesforce DX:

·         VS Code: Visual Studio Code is the go-to code editor for Salesforce developers. It’s free, open-source, and available for Windows, Linux, and macOS. This editor has easy-to-install extensions for syntax highlighting, code completion, and more.

·         Salesforce CLI (command-line interfaces): The Salesforce CLI is a powerful command-line interface that simplifies development and builds automation when working with your Salesforce org. Use it to aggregate all the tools you need to develop with and perform commands against your Salesforce org. Synchronize source to and from scratch orgs.

·         Extensions in VS Code: The features that Visual Studio Code includes out-of-the-box are just the start. VS Code extensions let you add languages, debuggers, and tools to your installation to support your development workflow. VS Code’s rich extensibility model lets extension authors plug directly into the VS Code UI and contribute functionality through the same APIs used by VS Code. 

The Salesforce Extension pack includes tools for developing on the Salesforce platform in the lightweight, extensible VS Code editor. These tools provide features for working with development orgs (scratch orgs, sandboxes, and DE orgs), Apex, Aura components, and Visualforce.

Setup Dx Environment:

Install the CLI on Windows

You install the Salesforce CLI on Windows with an .exe file.

Download and run the Windows installer.

 Verify your Installation:

Run this command to verify the Salesforce CLI version:

Sfdx –version

 Run this command to verify the Salesforce CLI plug-in version:

sfdx plugins –core

 

This command returns a list of the other plug-ins installed in the CLI:

Sfdx plugins

Download and Install VS Code:

VS code can be downloaded from the below link.

https://code.visualstudio.com

Setup Salesforce DX with VS Code

Step 1: To setup Saleforce in VS Code, first install “Salesforce Extension Pack”.



Step 2: To go for a Lightning Web Component in VS Code, first you need to install “Lightning Web Components”.



These are the steps required to set up and configure Salesforce DX on your system.

Create a Salesforce DX Project via Command Palette

·         In Visual Studio Code, open the Command Palette by pressing Ctrl+Shift+P on Windows or Cmd+Shift+P on macOS

·         Type SFDX

·         Select SFDX: Create Project

·         Enter HelloWorldLightningWebComponent as the project name

·         Press Enter

·         Select a folder to store the project

·         Click Create Project. You should see something like this as your base setup:




Authorize Your Non-DevHub Org via Command Palette

·         In Visual Studio Code, open the Command Palette by pressing Ctrl+Shift+P on Windows or Cmd+Shift+P on macOS

·         Type SFDX

·         Select SFDX: Authorize an Org

·         Select the login option accordingly. Select login.salesforce.com to log into your developer org or select test.salesforce.com to log in to the sandbox. You can also use a custom domain URL to log in.

·         Log in using your org.

·         If prompted to allow access, click Allow.

·         After you authenticate in the browser, the CLI remembers your credentials. The success message should look like this:


 Points to Remember:

  1. Make sure that you have installed Java 8 or Java 11 and configure the path on your system.
  2. If you are not able to retrieve or deploy components and you’re getting “UNSUPPORTED_API_VERSION: Invalid Api version specified on URL” message, then execute the following command: “sfdx force:config:set apiVersion=48.0” and select the previous version in it.

 

ES12 new Features