Simple Bootbox message with callback

bootbox.js is a nice simple replacement for alerts. Here’s a quick extension that shows a message by hiding any existing boxes, then showing the new one. Since it’s using Bootstrap’s event-based modals, you have to wait for one to finish loading before closing it or expecting it to be open.

function showMessage(title, body, callback, noButton){
    bootbox.hideAll();
    var data = { title: title, message: body };
    if (callback) {
        data.onShown = callback;
    }
    if (noButton) {
        bootbox.dialog(data);
    } else {
        bootbox.alert(data);
    }
}

showMessage("Loading", "Working...", function () {
    // Do something
    showMessage("Second Message", "This is the real message");
}, true);

Javascript random characters

// Asynchronous
const crypto = require('crypto');


function getRandomChars(len, callback) {
   const CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
   const NUM_CHARS = CHARS.length;
   crypto.randomBytes(len, (err, buf) => {
      let result = "";
      buf.forEach(b => {
         let idx = Math.floor(b * NUM_CHARS / 256);
         result += CHARS[idx];
      });
      callback(null, result);
   });
}

Javascript default parameters

"use strict";

// no IE support
// no Safari support

function doSomething(a = 1, b = 2) {
	console.log(`a=${a}`);
	console.log(`b=${b}`);
}

doSomething(); // 1, 2
doSomething(10); // 10, 2
doSomething(undefined, 20); // 1, 20
doSomething(10, 20); // 10, 20
doSomething(null, null); // null, null

// default value can be a function call, like an argument exception:
function go(val = missingValue("val")) {

}

function missingValue(paramName) {
	throw new Error(`Parameter ${paramName} is missing`);
}

try { go(34); console.log("ok"); } catch (ex) { console.log(ex); } // ok
try { go(); console.log("ok"); } catch (ex) { console.log(ex); } // error message

Send AWS SES email with javascript

Using the node-ses package:

"use strict"; 

var ses = require('node-ses'),
    client = ses.createClient({  
        key: 'mykey',  
        secret: 'mysecret' , 
        amazon: "https://email.us-west-2.amazonaws.com"
    }); 

// Give SES the details and let it construct the message for you.  
client.sendEmail({ 
    to: 'someone@example.com', 
    ,from: 'someone@example.com', 
    , cc: 'someone@example.com', 
    , bcc: ['canbearray@example.com, 'someone@example.com'] 
    , subject: 'Test Message ' + new Date() 
    , message: 'your <b>message</b> goes here' 
    , altText: 'plain text' 
    }, function (err, data, res) { 

        if (err) { 
            console.log("ERROR"); 
            console.log(err); 
        } else { 
            console.log("Done"); 
        } 
    }
);

Replace alert with SweetAlert

SweetAlert is a nice simple solution for displaying alert messages. Here’s the basic way to replace the built-in alert, so you don’t have to use the custom swal function:

<link href="/styles/sweetalert.css" rel="stylesheet" type="text/css">   
<style type="text/css">
   .sweet-alert h2 { font-size: 21px; font-weight: 500; line-height: 23.1px; }
</style>

<!-- SweetAlert does not work in IE8 or prior -->
<!--[if gt IE 8 | !IE]><!-->
   <script src="/scripts/sweetalert.min.js" type="text/javascript"></script>
   <script type="text/javascript">
       window.alert = function () {
           if (arguments == null) {
               swal(" ");
           } else if (typeof arguments[0] === "number") {
               swal(arguments[0].toString());
           } else {
               swal(arguments[0] || " ");
           }
       };
   </script>
<!--<![endif]-->

Queue and Stack in javascript

Using basic array functions, you can treat an array as a queue (first in first out) or a stack (last in first out);

To act as a queue, use the shift function:

while (arr.length) {
  let val = arr.shift();
  console.log(val);
}

To act as a stack, use the pop function:

while (arr.length) {
  let val = arr.pop();
  console.log(val);
}

Handlebars in NodeJS

"use strict";

(function() {
    const handlebars = require("handlebars");
    const source = "{{title}}\n"
        + "Hello {{person.name}}, I see that you are {{person.age}} years old.\n"
        + "You have the following cars:\n"
        + "{{#each cars}}\n"
        + "    {{year}} {{make}} {{model}} {{#if color}}(Color={{color}}){{/if}}\n"
        + "{{/each}}\n";

    const template = handlebars.compile(source);
    const data = {
        title: "My Data Object",
        person: { name: "Billy", age: 34 },
        cars: [
            { year: 2015, make: "Ford", model: "Mustang", color: "Red" },
            { year: 2014, make: "Chevy", model: "Corvette" },
            { year: 2013, make: "Dodge", model: "Aries", color: "Yellow" }
        ]
    };
    const result = template(data);
    console.log(result);
})();

/****** OUTPUT *******
My Data Object
Hello Billy, I see that you are 34 years old.
You have the following cars:
    2015 Ford Mustang (Color=Red)
    2014 Chevy Corvette
    2013 Dodge Aries (Color=Yellow)
******* OUTPUT ******/

AJAX in Angular

Regular GET/POST:

$http({
    method: "POST",
    url: "someUrl",
    headers: {
        "Content-Type": "application/json; charset=utf-8"
    },
    data: JSON.stringify({ name: "John Doe" })
}).then(function(response) {
    console.log("Successful response: " + response);
}, function(response) {
    console.log("Error response: " + response);
});


JSONP (in a factory)

// Make sure you include it in DI:  app.factory("myFactory", function ($http, $sce) {
factory.getSomething = function (callback) {

    const URL = "http://something.../?param=someval¶m2=otherval";

    var url = $sce.trustAsResourceUrl(URL);

    $http.jsonp(url, {
        jsonpCallbackParam: "callback"
    }).then(function (response) {
        console.log("Successful response: " + response);
    }, function (response) {
        console.log("Error response: " + response);
    });
};
/*
response:
    data – {string|Object} – The response body transformed with the transform functions.
    status – {number} – HTTP status code of the response.
    headers – {function([headerName])} – Header getter function.
    config – {Object} – The configuration object that was used to generate the request.
    statusText – {string} – HTTP status text of the response.
*/

JSONP with jQuery and ASP.NET

JSONP allows you to execute something similar to AJAX, across domains without worrying about whether the request is across domains, or any special CORS configuration.

It’s not generally a huge deal to set up CORS, but JSONP is guaranteed to work in all browsers and servers without any special handling.

Javascript

function go() {
    jQuery.ajax({
        // url: "/Home/DoSomething", // Regular MVC
        // url: "/Handler1.ashx", // WebForms
        data: {xyz:"World"},
        dataType: "jsonp",
        type: "get"
    }).done(function (result) {
        console.log(result);
    });
}

ASP.NET

// Regular MVC - no special filters, return types, etc. 
public ActionResult DoSomething(string xyz) 
{
    Response.ContentType = "application/json";
    var foo = new { FirstName = "John", LastName = "Doe", Message = "Hello " + xyz };
    Response.Write(string.Format("{0}({1});", Request["callback"], JsonConvert.SerializeObject(foo)));
    return null;
}

// WebForms
public class Handler1 : IHttpHandler 
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "application/json";
        var foo = new { FirstName = "John", LastName = "Doe", Message = "Hello " + context.Request["xyz"] };
        context.Response.Write(string.Format("{0}({1});", context.Request["callback"], JsonConvert.SerializeObject(foo)));
    }

    public bool IsReusable { get { return false; } }
}

jQuery noConflict

If you need to inject a specific version of jQuery into a webpage that may or may not already have a different version of jQuery, or if you specifically need two different versions loaded, then you can use jQuery.noConflict.

You might use this if you’re building a custom control that gets injected into a page, where you want to make sure your stuff works as intended, but you don’t want to accidentally upgrade or downgrade the main page’s jQuery.

Sample Code

This sample will show how to load jQuery 1.8.3 into a page which may or may not already have a different version loaded.

var _jq183;

function load183() {
    if (typeof window.jQuery === "function" && window.jQuery.fn && window.jQuery.fn.jquery === "1.8.3") {
        _jq183 = window.jQuery;
        return;
    }

    if (typeof window.jQuery === 'undefined' || !window.jQuery.fn || (window.jQuery.fn.jquery !== "1.8.3")) {

        var done = false;

        var body = document.getElementsByTagName("body")[0];
        var scr = document.createElement("script");
        scr.setAttribute("src", "https://code.jquery.com/jquery-1.8.3.min.js");
        scr.onload = scr.onreadystatechange = function () {
            if (!done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete")) {
                done = true;
                _jq183 = jQuery.noConflict(true);
                scr.onload = scr.onreadystatechange = null;
                body.removeChild(scr);
            };
        };
        body.appendChild(scr);
    };
}

function showVersion() {
    if (typeof $ === "undefined") {
        console.log("$ is undefined");
    } else {
        console.log("$: " + $.fn.jquery);
    }
    if (typeof jQuery === "undefined") {
        console.log("jQuery is undefined");
    } else {
        console.log("jQuery: " + jQuery.fn.jquery);
    }
    console.log("_jq183: " + (_jq183 ? _jq183.fn.jquery : "N/A"));
}

You may get an error message, like:

Refused to load the script 'https://code.jquery.com/jquery-1.8.3.min.js' because it violates the following Content Security Policy directive: "script-src somethingsomething.com".</code>

From what I’ve read, if you get this, you’re out of luck because the site won’t allow you to inject a script from another domain.