How single page application works

Single page applications use hash-based or pushState navigation to support back/forward gestures and bookmarking. The best known example probably is Gmail but now there are other too. If you’re not familiar with how that technique works, here is a brief explanation;

For hash-based navigation, the visitor’s position in a virtual navigation space is stored in the URL hash, which is the part of the URL after a ‘hash’ symbol (e.g., /my/app/#category=shoes&page=4). Whenever the URL hash changes, the browser doesn’t issue an HTTP request to fetch a new page; instead it merely adds the new URL to its back/forward history list and exposes the updated URL hash to scripts running in the page. The script notices the new URL hash and dynamically updates the UI to display the corresponding item (e.g., page 4 of the “shoes” category).

This makes it possible to support back/forward button navigation in a single page application (e.g., pressing ‘back’ moves to the previous URL hash), and effectively makes virtual locations bookmarkable and shareable.

pushState is an HTML5 API that offers a different way to change the current URL, and thereby insert new back/forward history entries, without triggering a page load. This differs from hash-based navigation in that you’re not limited to updating the hash fragment — you can update the entire URL.

Debounce and Throttle in JavaScript

Debounce and throttle are two concepts that we can use in JavaScript to increase the control of our function executions, specially useful in event handlers.

Both techniques answer the same question “How often a certain function can be called over time?” in different ways:

  • Debounce: Think of it as “grouping multiple events in one”. Imagine that you go home, enter in the elevator, doors are closing… and suddenly your neighbor appears in the hall and tries to jump on the elevator. Be polite! and open the doors for him: you are debouncing the elevator departure. Consider that the same situation can happen again with a third person, and so on… probably delaying the departure several minutes.
  • Throttle: Think of it as a valve, it regulates the flow of the executions. We can determine the maximum number of times a function can be called in certain time. So in the elevator analogy.. you are polite enough to let people in for 10 secs, but once that delay passes, you must go!

Event handlers without debouncing or throttling are like one-person-capacity elevators: not that efficient.

Use cases for debounce

Use it to discard a number of fast-pace events until the flow slows down. Examples:

  • When typing fast in a textarea that will be processed: you don’t want to start to process the text until user stops typing.
  • When saving data to the server via AJAX: You don’t want to spam your server with dozens of calls per second.

Use cases for throttle

Same use cases than debounce, but you want to warranty that there is at least some execution of the callbacks at certain interval

  • If that user types really fast for 30 secs, maybe you want to process the input every 5 secs.
  • It makes a huge performance difference to throttle handling scroll events. A simple mouse-wheel movement can trigger dozens of events in a second. Even Twitter had once problems with scroll events, so learn from others mistake and avoid this easy pitfall.

Here is visual guide to these concepts.

Resource

https://redd.one/blog/thinking-in-functions-higher-order-functions

JavaScript: How to construct an array of json objects using map

What does map do ?

Answer: It creates a new array with the results of calling a function on every element in the calling array.

Example:

var numbers = [ 1, 2, 3, 4];
var multiplesOfTen = numbers.map( function(num) {
    return num * 10;
});
console.log(numbers); //prints [1, 2, 3, 4]
console.log(multiplesOfTen); //prints [10, 20, 30, 40]

How does JSON object look like?

Answer: JSON objects are written as key/ value pairs

Example:

var Person = { "name" : "Amy", "Age" : 15 }
console.log(Person.Age); //Prints 15

Let us solve a problem using map method. We have a JSON object say “orders” with lot of keys like name, description, date, status. We need an array of orders whose status is delivered. This array of orders will have information about order name and order description only.

Answer:

var orders = [ { "name" : "chain", "description" : "necklace chain", "status": "shipped"} , {"name": "pen", "description" : "ball pen", "status": "shipped"}, {"name": "book", "description" : "travel diary", "status": "delivered"},{"name": "brush", "description" : "paint brush", "status": "delivered"}];
console.log(orders); 
var orderInfo = orders.map( function(order) {
 if( order.status === "delivered"){
     var info = { "orderName": order.name,
                  "orderDesc": order.description
                 }
     return info;
 }
});
console.log(orderInfo);

Reference

https://www.w3schools.com/js/js_json_objects.asp

Decode JWT Token

Decoding JWT token and return value;

protected string GetCalimValue(string token)
{
   var handler = new JwtSecurityTokenHandler();
   var jsonToken = handler.ReadToken(token);
   var tokenJWT = jsonToken as JwtSecurityToken;
   //var jwtSecurityToken = handler.ReadJwtToken(token);

   var jti = tokenJWT.Claims.First(claim => claim.Type == "jti").Value;
   return jti;
}

Validating and Decoding JWT Token and return value;

protected string ValidateTokenAndGetClaimValue(string token)
{
    string secret = "this is a string used for encrypt and decrypt token";
    var key = Encoding.ASCII.GetBytes(secret);
    var handler = new JwtSecurityTokenHandler();
    var validations = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(key),
        ValidateIssuer = false,
        ValidateAudience = false
    };
    var claims = handler.ValidateToken(token, validations, out var tokenSecure);

    var tokenJWT = tokenSecure as JwtSecurityToken;
    var emailAddress = tokenJWT.Claims.First(claim => claim.Type == "email").Value;
    return emailAddress;
}

We want to keep token inside cookies on a successful token acquisition;

Response.Cookies.Append("X-Access-Token", login.JwToken, new CookieOptions() { HttpOnly = true, SameSite = SameSiteMode.Strict });
Response.Cookies.Append("X-Email", login.Email, new CookieOptions() { HttpOnly = true, SameSite = SameSiteMode.Strict });

References

https://stackoverflow.com/questions/38340078/how-to-decode-jwt-token

https://www.codemag.com/Article/2105051/Implementing-JWT-Authentication-in-ASP.NET-Core-5

Handle back-slash “\” in Razor View and JavaScript

We are passing following view bag value;

ViewBag.Alphabets = "a\\b\\c";

We are retrieving this value in JavaScript in Razor view;

console.log('@ViewBag.Alphabets');

JS Output
console.log('a\b\c');

Console Output
a_c

Where did the “\” goes? Since this is a part of escape characters so JS automatically removes “\\” and replaced it with “_”. “\b” is a metacharacter so it’s gone as well.

We can fix it by using Replace command on ViewBag.

console.log('@ViewBag.Alphabets.Replace("\\", "\\\\")');

JS Output
console.log('a\\b\\c;');

Console Output
a\b\c

References

https://www.tutorialspoint.com/escape-characters-in-javascript