JavaScript Primitive (value) types

There are five primitive types; Number, String, Boolean, null and undefined. Their values are stored directly in the variable for a given context. We can use typeof operator to identify primitive types with exception of null, which must be compared directly against the special value null.

color1 = "red"
color2 = color1
color2 = "green"
Inspect type of variables;
typeof(color1)		//string
typeof(color2)		//string
typeof(10)		//number
typeof(true)		//Boolean
typeof(undefined)	//undefined

This is tricky value type.

typeof(null)		//object

This has been acknowledge by TC39 as an error, the committee that design and maintain JavaScript.

The best way to determine if a value is null is to compare it against null directly;

value = null
value === null	//true
value = false	//false
value === null
“10” == 10	//true
“10” === 10	//false

When you use the double equals, the string “10” and the number 10 are considered equal because the double equals converts the string into a number before it makes the comparison. The triple equals operator doesn’t consider these values equal because they are two different types.

console.log(undefined == null)		//true
console.log(undefined === null)		//false

Null is a data type that has a single value null. When you’re trying to identify null, use triple equals so that you can correctly identify the type.

Strings, numbers and Booleans primitive types have methods. The null and undefined types have no methods. Strings, in particular have numerous methods.

var name = "Shahzad Khan"
var lowerName = name.toLowerCase()	//convert to lowercase
var firstLetter = name.charAt(0)		////get first character
var middleOfName = name.substring(2,5)	//get character 2-4
s.length		//return number of characters
var count  =10
var fixedCount = count.toFixed(2)	//convert to “10.0”
var hexCount = count.toString(16)	//convert to “a”
var flag = true;
var stringFlag = flag.toString()		//convert to “true”

Primitive values are not objects though they have methods.

“Not a number” is used in cases where an arithmetic operation produces a result that is not a number.

a = 9/undefined		//display NaN
typeof a			//display number

Equality operator (>, <, ==, !=, >=, <=) return Boolean as their result.

var f = 10
var t = 20
f != t		//return true

The undefined data type is returned when we access a property on an object that does not exists or use it before it is declared or before it is assigned a value;

typeof(z)		//variable is not declared

There are some values in these types which evaluates to true and some evalues to false;

false, 0 (zero), “” (empty string), null, undefined, NaN (technically NaN is not true/false. It can only be detected with isNaN function)

To test this;

0 == false

All other values represent true values.

When evaluating the value of variables in conditional statement we do this;

var a = null
if (a == undefined || a == null)
{ a = 1;
}

It is possible to simple write

var a = null
if (!a) {
a = 10
}

Likewise, if a variable has a value, we can write something like;

If (a){
console.log(a)
}

This shortcut is useful and extensively used in JavaScript code.

JavaScript is a dynamically typed language. In a statically typed language, the compiler can perform type checking, if a variable is defined to store an integer. JavaScript variables derive their types based on the values they are assigned at run-time. Variables can change their type if they are assigned a new value.

As a result, it is not possible to perform static type checking in JavaScript.

Consider this example;

function add(v1, v2) { 
return v1 + v2 
}

If we invoke this function as;

add(1,1)		//return 2

This is expected result. We can also invoke this function as;

add("1",1)		//return 11

This is unexpected because JavaScript has performed string concatenation between number and the string. This is one of the reasons why the typeof operator is so important. It allows the function to be rewritten as;

function add(v1, v2) {
    if (typeof v1 === "number" && typeof v2 === "number") {
    return v1 + v2;
} else {
    throw "both argumens must be number";
    }
}

Now try to pass arguments;

add(“1”,1)		//return “both arguments must be number

On a side note, using the “+” operator on different data types produces a variety of random results;

{} + []		//return 0
[] + {}		//return object
Even using the “+” operator on the same data types produce meaningless results;
[] + [] 		//return empty string
{} + {}		//return object array

Uncaught Reference Error: jQuery is not defined

You are getting this error in your ASP.NET Core application. Your Layout page has the proper reference;

    <script src="~/lib/jquery/dist/jquery.js"></script>

When you try to navigate to your content page where you want to use jQuery;

$(function () {
      alert("Test");

You see above error. Dammit. What’s wrong. jQuery library is referenced in Layout page and suppose to work in content page.

Chances are that you have not defined script section in your Layout page.

@section Scripts {
  <script>
    $(function () {
      alert("Test"); 
    });
  </script>
}

This will solve the problem and pain will go away.

Install Angular9 or latest version using PowerShell

For fresh start, Uninstall Node.js and npm

Uninstall node.js and npm using Windows Installer (msi)

To uninstall node.js and npm, Open Windows “Control Panel” -> “Uninstall a program”, select Node.js and click on uninstall to uninstaill both node.js and npm

Cleanup directories

After the uninstall, look for the following folders and delete them if exists
* Nodejs installed directory
* npm and npm-cache directories from %appdata% directory
* npmrc directory from user home directory ( C:\Users\{User} )

Now to re-install

Go to Node.js page and install current version

https://nodejs.org/en/download/current/

Check node and npm version;

node -v

npm -v

Open PowerShell in admin mode;

If you want to uninstall angular;

npm uninstall -g @angular/cli

npm cache clean –force

npm cache verify

Install a specific version of angular;

npm install -g @angular/cli@9.0.0

If you see this error, don’t worry. Angular is installed.

ng –v

You might get PowerShell digitally signed error; run these commands;

To check current execution policy, Get-ExecutionPolicy. A convenient method is to change the Execution policy using this cmdlet.

PS C:\ Set-ExecutionPolicy unrestricted

Press Y to confirm. The policy change is updated in the registry and remains this way, at least until you change it again. The unrestricted means loading absolutely all configuration files and running all scripts.

If you don’t want to unrestrict policy but to bypass the policy for current process, run this command;

Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass

Now running ng -v will work.

If you want to Install latest version of angular;

npm install -g angular/cli

This is the Location where angular package are stored;

C:\Users\[UserName]\AppData\Roaming\npm\node_modules\@angular\cli\bin\ng

Resources

https://windowsreport.com/powershell-not-digitally-signed/

Connecting an Azure WebApp to a SQL Server VM inside a VNet

This article is about connecting an Azure WebApp to a SQL Server VM which is hosted inside an Azure Virtual Network. Typically a SQL Server VM would be hosted inside an Azure Virtual Network (VNet)  to isolate it from the internet by blocking all inbound and outbound internet traffic using a Network Security Group (NSG). In this scenario, connectivity  to the SQL Database is achieved by using the new VNet Integration feature found on the App Service component. Using this feature removes the requirement of an App Service Environment (ASE) for the WebApp thus reducing overall hosting costs.

Using VNet integration provides private outbound access from your App Service to resources in your VNet using the RFC1918 internal IP address allocation range (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16) by default.

 Scenario

A web application is hosted in a WebApp which requires a connection to the SQL Database hosted inside a VNet.

The network topology of this scenario is shown below which uses the Regional VNet Integration option where both the WebApp and SQL VM are in the same region. Here we have a VNet called LAN-VNET which has two subnets, one for the VNet Integration used for delegating called interdelg-subnet and the other to host the SQL Server VM called vm-subnet.

Configuration Walkthrough

The following are the sequence of steps used to setup VNet Integration between a Web App and SQL Server with the assumption the SQL Server VM is already hosted inside a VNet.

1. Adding a VNet subnet

2. Provisioning  an AppSvc Plan

3. Provisioning  a WebApp

4. Setting up the VNet Integration

5. Validating SQL Server Security Settings

6. Testing connectivity to the SQL Server

7. Updating the Web App SQL Connection String

1. Adding a VNet Subnet

A dedicated subnet used by the VNet Integration feature is required to be added to the existing VNet hosting the SQL Server VM. The IP range should match the maximum number of AppSvc plan instances when fully scaled out as each instance would require a IP address. For this scenario I will be using a /27  prefix giving a total range of 32 address, however  5 address are used internally by Azure leaving 27 usable addresses for each plan instance.

2. Provisioning App Svc Plan

To use VNet Integration, you will need to provision an App Service plan using newer V2 scale units. Note if you are currently using V1 App Services, you will need to provision a new plan using V2 and migrate you apps to this new plan.

To confirm if you have selected the newer V2 App Services, the Premium plans should be shown as P1V2, P2V2 and P3V2. Here I will be using a Standard Plan S1 for this scenario highlighted below.

3. Provisioning Web App

Create a new Web App and ensure it is in the same region as the VNet. Also ensure you have selected the  App Service Plan you created above.

4. Enable VNet Integration

Under the Web App that was provisioned above, click on the Networking menu item to view the networking options and then click on “Click here to configure” under the VNet Integration heading.

Go to your app and click on networking. Click on vnet configuration;

Once the VNet Configuration form opens, click on the “Add VNet” to open the Network Feature Status blade. Select the VNet that hosts the your environment and then the Subnet that was created earlier for the VNet Integration. Then press OK to save the changes.

After you hit OK, the VNet Integration should be connected and ready for testing the connectivity. Remember the VNet Integration will route all outbound RFC1918 traffic from the WebApp into your VNet.

5. Validating SQL Server Security Settings

To reduce the surface area of attack, ensure the SQL Server can only accept connections within the VNet. This is done by setting the “SQL connectivity” option to Private (within Virtual Network) under the Security menu of the SQL Virtual Machine.

Also check the NSG attached to the SQL Server VM to ensure there is a rule to disable all outbound internet traffic. If there is a inbound rule called default-allow-sql as highlighted below, it is advisable to delete this rule if not required. This inbound rule default-allow-sql is normally created when the security on the SQL Server VM allows SQL connectivity via Public (Internet) connections.

6. Testing connectivity

To check connectivity between the Web App and the SQL server, we can use the  tcpping command from a console window. Go to the Web App that was created previously and click on the Console menu item to open a console window similar to below.

In the console window type the command tcpping <sql vm private ip address>:1401. All going well you should get a reply similar to that below where 10.0.2.4 was the private IP address of my SQL Server VM using the default port 1401.

For some strange, if tcpping doesn’t work, check Inbound Rule in your server windows firewall for SQL Server Database Engine (Tcp-in) port;

Sometimes portal changes doesn’t apply to database. why? don’t know.

Make sure that ICMP for IP is enabled on your server firewall otherwise ping will fail.

7. Updating the Web App SQL Connection String

Once the connectivity has been verified, the next step is to update the connection string on the Web App to use the private IP address of the SQL Server VM. Typically the connection string should look something like this:- Server=10.0.2.4;Database=MyDb;User Id=myusername;Password=mypassword;MultipleActiveResultSets=true

After the connection string has been updated to use the private IP address, you should be able to test your application.

VNet Integration provides an easy and cost effective solution to access databases hosted within a VNet without resorting to a dedicated  ASE. Also using rules on the NSG applied to the SQL Server VM provides the capability to block all internet traffic and allow only RFC1918 internal addresses to have access.

Resource

https://docs.microsoft.com/en-us/azure/app-service/web-sites-integrate-with-vnet

Multiple environments, do I need Azure Key Vault for each environment?

I started getting this problem today when I try to use same secret for my second application in a single key vault;

Multiple resources/entities can access a single Key Vault instance – provided they’re all in the same location (data center).

You may choose to segment your keys, secrets and certificates, either by placing them in different Key Vaults or by using different access methods/identities, however that’s not necessary.

The only time you need a separate Key Vault instance is when the resources/entities accessing it are in another location (data center/region).

It’s worth noting that you don’t need to worry too much about provisioning Disaster Recovery for resources using Key Vault, as the SLA Microsoft provide is unsurprisingly good: https://docs.microsoft.com/en-gb/azure/key-vault/key-vault-disaster-recovery-guidance. One caveat to that would be if you’re running IaaS/PaaS instances and want to run a DR fail-over yourself to another data center, at which point you’d need to manually migrate the keys/secrets/certificates in your main Key Vault into another instance (and re-point your VMs accordingly)

Resources

https://docs.microsoft.com/en-us/answers/questions/77182/key-vault-for-multiple-app-service-should-i-create.html

https://docs.microsoft.com/en-us/azure/key-vault/general/best-practices