Dynamically adding JavaScript and CSS using a resource-tracking object type

This is a quick demonstration of a few techniques in basic JavaScript: creating a custom JavaScript object type with properties and methods; dynamically adding both JavaScript and CSS references in a cross-browser-safe way; adding JavaScript async; and adding inline JavaScript and CSS. The resource loader tracks added resources, to ensure that they are loaded only once. Try it for yourself (open your browser’s developer tools to see logging output).

// A JavaScript type which manages references to scripts and stylesheets
function ResourceManager() {
  var addedReferences = {};
  var addedResources = {};
  
  this.isLoggingEnabled = false;
  
  this.referenceExists = function(url) {
  	if (url in addedReferences) {
    	this.log('Resource ' + url + ' already added');
      return true;
    }
    else return false;
  }
  
  this.resourceExists = function(text) {
  	if (text in addedResources) {
    	this.log('Text resource already added');
      return true;
    }
    else return false;
  }
  
  this.addScriptReference = function(url, addAsync, addDeferred) {
    if (typeof(url) == 'undefined' || this.referenceExists(url)) return;
    this.log('Adding script reference: ' + url + (addAsync ? ' [async]' : '') + (addAsync ? ' [deferred]' : ''));
        
    var script = document.createElement('script');
    script.src = url;
    if (addAsync) script.async = true;
    if (addDeferred) script.defer = true;
    document.head.appendChild(script); 
    
    addedReferences[url] = url;
  };
  
  this.addScript = function(text) {
    if (typeof(text) == 'undefined' || this.resourceExists(text)) return;
    this.log('Adding script');
      
    var script = document.createElement('script');
    script.appendChild(document.createTextNode(text));
    document.head.appendChild(script); 
    
    addedResources[text] = text;
  };
  
  this.addStyleSheetReference = function(url) {
    if (typeof(url) == 'undefined' || this.referenceExists(url)) return;
    this.log('Adding script reference: ' + url + (addAsync ? ' [async]' : '') + (addAsync ? ' [deferred]' : ''));
    
    var ss = document.createElement('link');
    ss.rel = 'stylesheet';
    ss.type = 'text/css';
    ss.href = url;
    head.appendChild(ss);
    
    addedReferences[url] = url;
  };  
    
  this.addStyleSheet = function(text) {
    if (typeof(text) == 'undefined' || this.resourceExists(text)) return;
    this.log('Adding style sheet');
    
    var ss = document.createElement('style');
    ss.type = 'text/css';
    
    if (ss.styleSheet){
      ss.styleSheet.cssText = text;
    } else {
      ss.appendChild(document.createTextNode(text));
    }
      
    document.head.appendChild(ss);  
      
    addedResources[text] = text;
  };    
    
  this.log = function(message) { if (this.isLoggingEnabled) console.log(message); };
}

Advertisements

Selecting unthemed HTML descendant elements using CSS :not()

In my recent work, I’ve been constructing a CSS framework that needs to support multiple themes: the ability to override many aspects of display formatting by applying a CSS class to a parent element, affecting all descendants. However, in order to make this work properly in actual practice, it’s may be desirable to apply default theming rules to even children without an ancestor theme-tagged element. (In my situation, this requirement applies because the mentioned CSS framework will be used to support microsites, which should be presented with a “good” look and feel even if the implementation of the site has been somewhat sloppy.)

The CSS :not() selector works well for this, as implemented in CSS3:

:not([class*=Theme]) * {
  // Sample selecting all unthemed elements, where themes are applied with *Theme class names on ancestors
}

This can easily, of course, be applied with different descendant selectors. Try the example.

Easily execute dynamic C# using extension methods

Code has now been released under the SharpByte project to execute dynamic C# scripts (and evaluate statements) more easily than ever before. Dynamic code execution during earlier days of .NET was a sore spot, with many lamenting the lack of a functional equivalent to the JavaScript eval() function. For years many developers attempted hacks like using ASP.NET’s DataBinder.Eval(), but results were often subpar and performance was lackluster. Compiling to the CodeDom and the newer .NET Compiler Platform, a.k.a. Roslyn, can be moderately simple to complex depending on need, but many developers just want a simple, easy-to-reuse solution for supporting dynamic code entry in an application.

Further documentation on the easy-to-use API will be forthcoming, but for now these steps will suffice for anyone wishing to play with the code:

1. Either build and reference the project’s core assembly in your project, or import the code directly into your project.

2. If the code was built with conditional compilation symbol GLOBAL_EXTENSIONS, all objects will be able to use the dynamic-execution extension methods. Otherwise, if COLOCATE_EXTENSIONS was used, add a using statement for the System.Runtime.CompilerServices namespace; if neither GLOBAL_EXTENSIONS nor COLOCATE_EXTENSIONS was used, add a using statement for the SharpByte.Dynamic namespace.

3. Call any version of .Execute() or .Evaluate() directly on any object. The former will execute any C#-compliant script composed of properly semicolon-terminated lines of code, with “this” references executed on the object on which the extension methods are called (i.e. the context object for the call); the latter will evaluate a C# expression and return the result.

Once these steps are done, calling a script is as easy as this:

someObject.Execute("[script statements go here, and may be many lines]");

To anyone curious enough to understand the working of these extension methods, the code will be illustrative. Essentially, the extension methods call into a facade for compilation features of the .NET framework, and can be used to front-end calls to the CodeDom, the .NET Compiler Platform (“Roslyn”), or any other compiler, vastly simplifying the most-needed dynamic code compilation and execution features of each.

Here’s an example of the relatively complex task of building code using the CodeDom (without any attempt to slam the useful-looking code at this page, just provide an example of the complexity hidden away). Roslyn provides many enhancements over CodeDom, but still to simply execute a script, such as user-entered code in a CMS or other data system, isn’t always completely simplified as it could be.

The provided reference code compiles code constructed on-the-fly using the referenced compiler. A code formatter emits source code, without needing any special knowledge of the underlying compiler. A quick review of the System.Object extension methods involved shows how easy it is to retain a reference to the compiled IExecutable instance as well, which can be used to inspect the built-in execution log and timings, as well as any exception generated by the last run of a compiled executable. A unique signature based on the executable code type (expression/statement or script), parameter names, and source code is used on subsequent calls to check for pre-existing compiled executables, stored in the ExecutableFactory hybrid factory/collection for reuse.

Each executable can be compiled successfully with numbered placeholder values, a la string.Format() (but using triple curly braces to avoid .NET and Handlebars-style format interference) and/or named parameter values. As mentioned above, the context object (when using extension methods, the object on which the method is called) is used for any references to “this” within any script or expression.

Since an object from each compiled executable type has a Copy() method, it can safely and cheaply be used to create further executables of the same type. Calling Execute() on any particular executable is guaranteed to be thread-safe due to use of synchronization; for that reason, it’s easiest to cache local copies of reusable expressions/scripts.

Performance-wise, on a fairly low-spec laptop, formatting source code for a new class tests in the 1-2 microsecond range; post-compilation, execution of a script or expression can take well under a microsecond (e.g. a two-parameter complex mathematical expression which tests in the 800-nanosecond range), depending of course on complexity. The bulk of this fairly small overhead is due to the use of dynamic variables within the compiled classes themselves. If warranted, type safety may be added to the context object and/or named parameters to boost peformance further.

This generic utility code was originally developed in support of the SharpByte CMS, but is provided separately under the MIT License. Happy coding!

Safely navigating object hierarchies in JavaScript using prototype methods

New: Dynamically evaluate C# expressions and execute C# scripts with a single statement, from anywhere in a .NET application. Click here for more info.

Anyone who’s dealt with a deeply nested set of properties in JavaScript, whether through use of an extensive third-party JavaScript API or a custom library, has likely run into the problem of safely accessing such structures. One can of course hand-roll many ugly, hard-to-read statements like the following, adding on to the maintenance burden of the code (splitting lines as necessary for length, of course):

if (a && a.b && a.b.c && a.b.c.d && a.b.c.d.e) { doSomethingWith(a.b.c.d.e); }

The main alternative to this approach is to make such accesses within a try-catch block, but this is generally slower by at least a couple of orders of magnitude when exceptions are thrown, so not always useful in tight loops and other performance-sensitive situations. It’s also arguably an abuse of the try/catch mechanism.

Luckily, a less unsavory solution with fairly good performance can be adopted using JavaScript prototype methods. Here’s a reference implementation, and you can also try it for yourself (with timings):

// Indicates whether an object has the indicated nested subproperty, which may be specified with chained dot notation 
// or as separate string arguments.
Object.prototype.hasSubproperty = function() {
	if (arguments.length == 0 || typeof(arguments[0]) != 'string') return false;  
  var properties = arguments[0].indexOf('.') > -1 ? arguments[0].split('.') : arguments;    
  var current = this;
  for(var x = 0; x  -1 ? arguments[0].split('.') : arguments;    
  var current = this;
  for(var x = 0; x < properties.length; x++) {
  	current = current[properties[x]];
    if ((typeof current) == 'undefined') return undefined;
  }  
  return current;
};

// Gets the indicated nested subproperty, which may be specified with chained dot notation or as separate arguments.
// If the specified subproperty (or any intervening object in the hierarchy) is not found, returns undefined.
Object.prototype.getSubproperty = function() {
	if (arguments.length == 0 || typeof(arguments[0]) != 'string') return false;  
  var properties = arguments[0].indexOf('.') > -1 ? arguments[0].split('.') : arguments;    
  var current = this;
  for(var x = 0; x < properties.length; x++) {
  	current = current[properties[x]];
    if ((typeof current) == 'undefined') return undefined;
  }  
  return current;
};

// Sets the indicated nested subproperty, which may be specified with chained dot notation or as separate arguments.
// If any intervening object in the hierarchy is not found, returns false, otherwise sets the value and returns true.
Object.prototype.setSubproperty = function() {
	if (arguments.length  -1 ? arguments[0].split('.') : Array.prototype.slice.call(arguments, 0, arguments.length - 1);    
  var parent, current = this;
  for(var x = 0; x < properties.length - 1; x++) {
  	current = current[properties[x]];
    if ((typeof current) == 'undefined') return false;
  }  
  current[properties[properties.length - 1]] = arguments[arguments.length - 1];
  return true;
};

Some observations: if you run the timings, you’ll note that the try-catch method is still quite fast when exceptions are not thrown, indicating that try-catch might be workable when exceptions are expected to be truly… exceptional. Still, in any but extraordinary conditions, the performance of the prototype-method approach should be quite fast enough, avoids worst-case performance, and is cleanest overall.

Emulating the Java BorderLayout in CSS

In putting together a CSS framework, I wanted to duplicate the functionality of the Java BorderLayout. There’s a fair amount of (generally partially complete) info on the web about how to do this, with many of the methods having one drawback or another, e.g. needing to put the center/body child container after both sidebars if using a float-based approach. As it turns out, the CSS table layout, introduced way back in CSS 2, makes it a snap. Try the JSFiddle for yourself.

The bone-simple CSS, with compass-point naming eschewed in favor of more standard CSS names:

.borderLayout {
  display: table;  
  width: 100%
}

.borderLayout .top {
	display: table-row;
}

.borderLayout .left {
    display: table-cell;
    vertical-align: middle;
    width: 10%;
  }

.borderLayout .center {
    display: table-cell;
    vertical-align: middle;
}

.borderLayout .right {
    display: table-cell;
    vertical-align: middle;
    width: 10%;
  }
  
.borderLayout .bottom {
	display: table-row;	
}

The layout is then quite simple to use, the main charm of BorderLayout, and can be safely nested as well. Try the JSFiddle for yourself.

A C# queue package designed for high performance and ease of use

New: Dynamically evaluate C# expressions and execute C# scripts with a single statement, from anywhere in a .NET application. Click here for more info.

I’ve recently published a carefully constructed set of generic queues as part of the SharpByte project. These were all developed pursuant to the SharpByte CMS (the first of its type–more about which will be forthcoming), but are publicly released under the MIT license for any who wish to use them.

The priority queue abstract data type is similar to a regular queue, but allows each item to have a priority associated with it. For certain types of server-side programming this can be extremely useful for controlling the flow of work items. Implementations in the package include PriorityQueue and ConcurrentPriorityQueue.

The double-ended queue can be just as useful in its own way, as it can function as a queue, list (if list semantics are supported, as they are with this implementation), or stack. As such it’s one of the most useful general-purpose data structures. Implementations in the package include DoubleEndedQueue and ConcurrentDoubleEndedQueue.

Each queue in the package supports full list operations, and in fact implements IList and IList<T>. Performance has been tested and throughput on the queues under load was seen to be fast under a range of different processing conditions, including multithreading.

All queues in the package can also serve as connectors or work routers within an application, as they can have one or more outputs added, which can be any .NET collection capable of receiving items of the generic type supported by a particular queue. The semantics for this can be seen in the IQueue interface. Strategies for distribution to child queues/collections include multicasting, simple load-balancing, and round-robin distribution.

Also in the same collections package are potentially helpful odds and ends, including read-only dictionary and list collections, as well as read-only views of mutable dictionaries and lists. These are different from the read-only interfaces now supported in .NET, as they cannot be cast successfully to mutable dictionaries and lists. The CharHashSet class is an implementation of ISet for chars which generally outperforms HashSet<char>, and can be useful for certain specialized operations dealing with strings.