Tag Archives: Examples

Create configurable Angular services using providers

With Angular 2 on its way, it seems like a lot of developers are now afraid of Angular 1.x. I have nothing bad to say about Angular. Sure, some things could be made easier but that’s why Angular 2 is on its way. I’ve played with Angular 2 a bit, and it only works in Chrome. I’m fairly confident Angular 1.x will be around for quite a while.

In that light, let’s talk about creating configurable services. One reason why AngularJS is so popular is because you can easily create modular, reusable code. This code can encapsulate logic, directives, extensible services and factories (via decorators), as well as configurability. I’ll talk about creating directives and decorators in future articles.

This example will be a simple URL constructor for placekitten.com. Any AngularJS service can be written to be configurable (if there’s reason to configure the service, of course).

First of all, let’s see how this service will be used.

.controller('View1Ctrl', ['$scope', 'kittyService', function ($scope, kittyService) {
    $scope.kittycat = kittyService.getUrl();
}])
  <p>How about a kitty cat?</p>
  <p><img ng-src="{{kittycat}}"/></p>

Pretty simple. We’ll call kittyService.getUrl() and use the string returned from the service as the src for an image.

To create a configurable service, we’ll use an angular provider instead of a service or factory. The structure I use for a provider is this:

(function () {
    'use strict';
    var module = angular.module('myApp.services', []);

    module.provider('serviceName', function ServiceName() {
        // use `this` for configurable properties or functions

        this.$get = [function () {
            var service = {};
            // This can be any valid return that you'd normally use
            // with module.service or module.factory
            return service;
        }];
    });
})();

This structure is only a little different from a service or factory. Rather than return an object or constructor function, you use this.$get to create your reusable code. What you assign to this property is the array injector for your service definition. You’ll feel comfortable with this syntax if you define your services using the array-based dependency injection:

angular.module('myApp')
.service('serviceName', [function (){
            var service = {};
            // This can be any valid return that you'd normally use
            // with module.service or module.factory
            return service;
}]);

You can use instance properties and methods on the provider definition to configure your service, then use the private context of your provider to share the configuration with the service. Here’s the full code for the kittyService:

(function () {
    'use strict';
    var module = angular.module('myApp.services', []);

    module.provider('kittyService', function KittyServiceProvider() {
        var height = 100,
            width = 100;

        this.setHeight = function (h) {
            height = h;
        };
        this.setWidth = function (w) {
            width = w;
        };

        this.$get = [function () {
            var service = {};

            service.getUrl = function () {
                return 'http://placekitten.com/g/' + width + '/' + height;
            };

            // This can be any valid return that you'd normally use
            // with module.service or module.factory
            return service;
        }];
    });
})();

The provider has two private variables: height and width. The two methods on the provider object allow you to update these values, but only during the config phase. After your application’s config function has completed, your provider’s functions are no longer accessible.

One problem with this service is that placekitten.com shows the same image for a given combination of height and width. In the config phase of our application, the service’s height and width can be configured randomly:

.config(['kittyServiceProvider', function (kittyServiceProvider) {
    var widths = [200,300,400,500,600];
    var heights = [300,400,500,600,700];
    kittyServiceProvider.setHeight(heights[Math.floor(Math.random()*heights.length)]);
    kittyServiceProvider.setWidth(widths[Math.floor(Math.random()*widths.length)]);
}]);

The name injected into the config phase is kittyServiceProvider and not kittyService. This is important. AngularJS knows that when you request kittyServiceProvider in the config phase, you want the object containing your service definition (the KittyServiceProvider function in the example above). Once the config phase completes, the $injector service will prepare your service from the this.$get definition of your service.

If you load the example code, refresh the page a few times and you’ll receive a new kitty image.

NOTE: The heights and widths may not always combine in a way that retrieves an image. Just refresh for another example.

Why not do this in a service?

True, you could do this directly in the service if this was just your code. The benefit here is when you want to share a service with other developers, perhaps on a different project within your company or publicly on GitHub. What if your team wants a 200×300 kitty and HR wants a 500×500 kitty? In these situations you can’t just modify the code with your hard-coded values. True, in this example you could use constants or values instead but then your service would have a dependency on the consumer (this is bad).

A service that dumps a string for displaying a cat image is probably not that useful in the real world. Consider other possibilities. I’ve used providers for creating a reusable notification display which allows you to define whether a notification will automatically close and how long notifications will be displayed if they auto-close. Suppose your application often receives 40x errors when users leave their browsers unattended long enough for an authenticated session to time out; you could create a provider which caches failed requests and retries up to X (configurable) times before giving up. Or, you could create a configurable service which caches those failed requests, displays a login dialog, then automatically retries the failed requests X (configurable) milliseconds after logging in successfully. Those examples would require the use of an http interceptor, and would have been quite a bit more complex than a kitty image linker.

Code

Sample code for this blog post is available on github at jimschubert/blogs.

Further Reading

If you really want to dig into the guts of Providers (versus services, factories, constants, or values), check out Adrian Castillo’s blog post, AngularJS Providers under the hood.

For reference to each recipe, check out AngularJS Provider Recipes on the official docs.

Flattr this!

Your IDE’s font matters: Fantasque Sans Mono

A good development environment is crucial to your productivity, there’s no question about it. The phrase ‘good development environment’ is subjective. For example, I’m pretty efficient using WebStorm and VisualStudio. I use vim pretty often but I’m nowhere near ‘efficient’. Matias Niemelä, on the other hand can easily manipulate text in vim.

A year or two ago, I read a blog post somewhere that suggested a font is just as important as your tool of choice. I thought, “yeah, right!”, but downloaded the font anyway. After a day of using the font, I realized how much more quickly I could read through code and how much easier it was to visually identify code blocks. I know that sentence sounds trivial, but after two years of using what I consider a better font I definitely notice a difference when I’m not using the font.

My font of choice these days is called Fantasque Sans Mono.

Here’s a screenshot comparison of Arial and Fantasque Sans Mono, both at 14pt.

Atom: arial 14pt
Atom: arial 14pt
Atom: fantasque sans mono 14pt
Atom: fantasque sans mono 14pt

The first thing to notice is how uncluttered letters are in Fantasque. On line 17, the word ‘function’ feels like it runs together in Arial but the letters clearly stand out in Fantasque. Also notice how the letter ‘g’ is unmistakable on line 18. On line 21, the kerning between parentheses, braces, brackets, and vertical pipes all make the line of code slightly easier to read. On line 23, the zero in Arial and many other fonts often resembles the capital letter ‘O’. For literals, this is obviously a number but it can be an easy typo to overlook within a string. In Fantasque, a zero has a line through it to clearly differentiate the number from the letter. Line 25 is easily consumed in the Arial screenshot mostly because the Atom editor clearly distinguishes between patterns and operations in the regex literal. Take a look at the difference without JavaScript syntax highlighting:

Atom: arial 14pt plain text
Atom: arial 14pt plain text
Atom: fantasque sans mono 14pt
Atom: fantasque sans mono 14pt

The actual code tends to be wider than other fonts. In the Arial screenshot, the image stops at the 80 character vertical indicator, which can easily be seen in the Fantasque screenshot. I actually like to use a 12pt or 13pt font size with Fantasque, which gives me a little more code on screen.

Although these points may seem trivial, I challenge you to at least give a few different fonts a try. You’ll be as surprised as I was to find that subtle differences in your font can improve productivity.

Download Fantasque Sans Mono from OpenFontLibrary.

Flattr this!

Manually debugging Angular scope

While a utility like Angular Batarang is invaluable, you’ll sometimes want to quickly and effectively inspect what exists on a given scope. If you’ve used Angular Batarang, you know that can be a pain in the ass. Here’s a quick alternative that works in Google Chrome, Firefox, and Safari.

Right-click on some element you want to inspect in your AngularJS-backed page. Select Inspect Element. This will open an ‘Elements’ inspector tab. Leave the element selected in that tab and go to ‘Console’. Type out the following:

angular.element($0).scope();

This will dump the scope to the console. You can assign this to a variable or navigate the parent/child scopes from here. This works because most browsers’ developer consoles support some extras in their Command Line API. The $0 refers to the most recently selected DOM element (try $0 through $4!).

You can test this out on the AngularJS Phone Catalog Tutorial. Here’s what you should see:

Android element debugging.

Flattr this!

Data at the root level is invalid. Line 1, position 1.

Recently, I encountered a really weird problem with an XML document. I was trying to load a document from a string:

var doc = XDocument.parse(someString);

I received this unhelpful exception message:

Data at the root level is invalid. Line 1, position 1.

I verified the XML document and retried two or three times with and without the XML declaration (both of which should work with XDocument). Nothing helped, so I googled for an answer. I found the following answer on StackOverflow by James Brankin:

I eventually figured out there was a byte mark exception and removed it using this code:

string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
if (xml.StartsWith(_byteOrderMarkUtf8))
{
    xml = xml.Remove(0, _byteOrderMarkUtf8.Length);
}

This solution worked. I was happy. I discussed it with a coworker and he had never heard of a BOM character before, so I thought “I should blog about this”.

Byte-Order Mark

The BOM is the character returned by Encoding.UTF8.GetPreamble(). Microsoft’s documentation explains:

The Unicode byte order mark (BOM) is serialized as follows (in hexadecimal):

  • UTF-8: EF BB BF
  • UTF-16 big endian byte order: FE FF
  • UTF-16 little endian byte order: FF FE
  • UTF-32 big endian byte order: 00 00 FE FF
  • UTF-32 little endian byte order: FF FE 00 00

Converting these bytes to a string (Encoding.UTF8.GetString) allows us to check if the xml string starts with the BOM or not. The code then removes that BOM from the xml string.

A BOM is a bunch of characters, so what? What does it do?

From Wikipedia:

The byte order mark (BOM) is a Unicode character used to signal the endianness (byte order) of a text file or stream. It is encoded at U+FEFF byte order mark (BOM). BOM use is optional, and, if used, should appear at the start of the text stream. Beyond its specific use as a byte-order indicator, the BOM character may also indicate which of the several Unicode representations the text is encoded in.

This explanation is better than the explanation from Microsoft. The BOM is (1) an indicator that a stream of bytes is Unicode and (2) a reference to the endianess of the encoding. UTF8 is agnostic of endianness (reference), so the fact that the BOM is there and causing problems in C# code is annoying. I didn’t research why the UTF8 BOM wasn’t stripped from the string (XML is coming directly from SQL Server).

What is ‘endianness’?

Text is a string of bytes, where one or more bytes represents a single character. When text is transferred from one medium to another (from a flash drive to a hard drive, across the internet, between web services, etc.), it is transferred as stream of bytes. Not all machines understand bytes in the same way, though. Some machines are ‘little-endian’ and some are ‘big-endian’.

Wikipedia explains the etymology of ‘endianness’:

In 1726, Jonathan Swift described in his satirical novel Gulliver’s Travels tensions in Lilliput and Blefuscu: whereas royal edict in Lilliput requires cracking open one’s soft-boiled egg at the small end, inhabitants of the rival kingdom of Blefuscu crack theirs at the big end (giving them the moniker Big-endians).

For text encoding, ‘endianness’ simply means ‘which end goes first into memory’. Think of this as a direction for a set of bytes. The word ‘Example’ can be represented by the following bytes (example taken from StackOverflow):

45 78 61 6d 70 6c 65

‘Big Endian’ means the first bytes go first into memory:

45 78 61 6d 70 6c 65
<-------------------

‘Little Endian’ means the text goes into memory with the small-end first:

45 78 61 6d 70 6c 65
------------------->

So, when ‘Example’ is transferred as ‘Big-Endian’, it looks exactly as the bytes in the above examples:

45 78 61 6d 70 6c 65

But, when it’s transferred in ‘Little Endian’, it looks like this:

65 6c 70 6d 61 78 45

Users of digital technologies don’t need to care about this, as long as they see ‘Example’ where they should see ‘Example’. Many engineers don’t need to worry about endianness because it is abstracted away by many frameworks to the point of only needing to know which type of encoding (UTF8 vs UTF16, for example). If you’re into network communications or dabbling in device programming, you’ll almost definitely need to be aware of endianness.

In fact, the endianness of text isn’t constrained by the system interacting with the text. You can work on a Big Endian operating system and install VoIP software that transmits Little Endian data. Understanding endianness also makes you cool.

Summary

I don’t have any code to accompany this post, but I hope the discussion of BOM and endianness made for a great read!

Flattr this!

Generating sprites with HTML5 canvas (node-canvas)

About a week ago, I posted about drawing simple shapes in HTML5. HTML5’s Canvas isn’t only useful on the client side.

About a year ago, I rewrote my Quaketracker mashup which pulls rss content from USGS and displays markers on a Google Map. For part of this rewrite, I wanted to use custom markers to indicate the magnitude of the earthquake, both numerically and colorfully. That task was more involved than I realized it would be. There doesn’t seem to be any easy way to generate such a sprite in The Gimp or other graphics software, so I set out to generate a sprite of magnitudes 0.0 through 9.9 with a color range from yellow to orange using node-canvas. This actually made the task very simple.

base.png
marker

Before writing the script, I had to decide on an image. I created a pretty simple quote-bubble-like marker with a white background and a black outline. The image is 35×35 square with some transparency padding the actual marker image. This allows me to calculate the layout pretty easily. The white background on black outline gives me a very specific color to replace with the desired color of intensity.

node-canvas is a custom implementation of Canvas for node.js. When I originally wrote this script, I had a few issues compiling node-canvas. When I tweaked the script today, I had no issues. However, it seems like some things are not well-documented or incomplete (PixelArray).

Scripting it in node.js

A lot of times, if your script writes out to files, it’s best to check for dependencies and cause your script to exit if they’re not met. For example, I know this script is completely useless without node-canvas, so I can probe for the availability of that module and provide directions for installation. I’d do this before attempting to load any other functions from the canvas module. You could also check for versions at this point. If someone runs this script with node-canvas 0.6.0 it will still work, but this may not be the case with other modules. Here’s how I start off the script.

var p = require('util').puts;

try {
    var probe = require('canvas');
} catch(e) {
    p("Cannot find node-canvas module.");
    p("Did you install dependencies:\n");
    p("\tnpm install -d");
    process.exit();
}

var fs = require('fs');
var Canvas = require('canvas');
var Image = Canvas.Image;

var canvas, ctx, baseImage, outImage, img;

I don’t usually use ‘global’ variables like those in the last line of the above snippet for applications or client-side scripting. For a script like this, you could have everything as a global variable as long as the names don’t clash with your imported modules.

To initialize shared variables, I like to define an init() function and call that function at the end of the script. This is pretty common in other languages like Ruby and Python, so why node server-side JavaScript?

var init = function() {
	// our working image is 35x35, we want 10x10 sheet of sprites
	canvas = new Canvas(35*10,35*10);
	ctx = canvas.getContext('2d');
	baseImage = __dirname + '/base.png';
	outImage = __dirname + '/markers.png';

	// pre-load the image
	img = new Image;
	img.onload = function() {
		processImage(fileProcessingComplete);
	};
	
	img.src = baseImage;
};

The cool thing about node-canvas is that the usage is very similar to the Canvas API implemented in browsers supporting the HTML5 Canvas. In fact, aside from the __dirname special property of node.js, you should be able to drop this init function into a browser with no problems. For this script, I want 100 different magnitudes to be generated from 0.0 through 9.9 (00-99 is 100) so the canvas is initialized to 10 rows and 10 columns of 35×35 squares. Just like a client-side Image object, we want to bind any post-processing of the image via the onload() function.

I’m going to Memento you a bit, and for that I’m sorry but the end is the easier concept. When all the processing is complete, we want to pull image data from the Canvas element and write it out to a file.

var fileProcessingComplete = function() {
	var out = fs.createWriteStream(outImage),
            stream = canvas.createPNGStream();

	stream.on('data', function(chunk){
	  out.write(chunk);
	});

	// when PNG stream is done, drain WriteStream
	stream.on('end', function(){
	  p('saved ' + outImage);
	  out.destroySoon();
	});
};

Accessing streams in node.js is usually done asynchronously. We can take chunks of data from the ReadStream of createPNGStream() and pump that to the WriteStream of the output file. When the data from the PNG is done streaming, we tell the output stream to finish writing its buffered data and destroy itself. It sounds intense, but it’s pretty straightforward.

Processing the colors and marker images is the fun part. To match the function call in the init function, we just create a function with a callback in the standard way.

var processImage = function(cb) {
        // other code removed
	if(typeof cb === "function") {
		cb.call(this);
	}
}

If there’s a callback function passed as a parameter, when processImage is finished, it will call that function passing the current scope as the execution scope and no parameters.

To draw out the custom marker, we’ll want to define how we want to display the text and at what color we want to have the 0.0 marker start.

ctx.font = 'normal 12px Impact';
ctx.textAlign = 'center';
var color = [255, 255, 0, 235];

The color array represents red, green, blue, and alpha channel (opacity). This may look odd if you’re used to specifying alpha channels in css as “rgba(255,255,0,0.92)”, but that value of 235 will give roughly 92% opacity.

We can make the script run pretty quickly by using a second canvas 2d context for the recolor phases (which modifies every white pixel).

// use a temp Canvas and Context of 35x35 size.
var tempCanvas = new Canvas(35,35);
var tempCtx = tempCanvas.getContext('2d');

This is an optimization I made today when tweaking the original script. In the original version of this script, I would write the base image to the output canvas then iterate over ‘NxN’ pixels on the output canvas to change the color of one pixel. Using a temporary canvas context, we only have to iterate over 35 pixels wide by 35 pixels high for every new marker. This not only speeds up the process, but it could be a difference of having a script that won’t run on slower machines.

For each of the desired 100 magnitudes, we’ll want to find the x and y values (top-left pixel) to which we’ll write the updated marker. For every 1/2 magnitude, the Green color value decrements by 13 points.

for(var magnitude = 0; magnitude <= 100; magnitude++) {
	var y = 35 * Math.floor(magnitude/10),
		x = ( 35*(magnitude % 10) );

	// This increments the color slightly
	if(magnitude % 5 == 0){
		color[1] = color[1] - 13;
	}

        // some code removed

	ctx.fillText("" + parseFloat(magnitude / 10, 1), x + (35/2), y + (35/2), 35);
}

The last line of the above snippet fills the magnitude text on the output canvas. This could be moved to the next part of the script for a further optimization: instead of just modifying each white pixel’s color, we could recolor and apply the text.

The part of the script which changes the color according to the magnitude looks like this:

tempCtx.drawImage(img, 0, 0, 35,35);
var imgData = tempCtx.getImageData(0, 0, 35, 35);
var data = imgData && imgData.data;
if(data) {
	try {
		for(var pixel=0;pixel<data.length;pixel=pixel+4) {
			var red = data[pixel]
			var green = data[pixel+1];
			var blue = data[pixel+2];
			var alpha = data[pixel+3];

			if(red == 255 && green == 255 && blue == 255) {
				data[pixel] = color[0];
				data[pixel+1] = color[1];
				data[pixel+2] = color[2];
				data[pixel+3] = color[3];
			}
		}
	} catch (err) { console.error(err.message); }

	// Write our temp image data to the final canvas context
	/* imageData, dx, dy, sx, sy, sw, sh */
	ctx.putImageData(imgData,x,y,0,0, 35, 35);
}

Writing to the temporary canvas’s 2d context gives us access to a data buffer which represents a 35×35 image where each pixel is represented by 4 bytes (rgba). Iterating this buffer by 4’s, we can check that the given pixel (excluding alpha because that doesn’t matter in this case) is white or rgba(255,255,255). If the pixel is white, we replace those 4 indexes with the values in our color array. When we’re done iterating the buffer representing the 35×35 image, we can call putImageData on the output canvas. With that, the sprite is complete and our callback handles writing the file.

A note about putImageData

putImageData can be a strange beast. Notice the comment imageData, dx, dy, sx, sy, sw, sh… these are the parameters accepted by the function. Even the HTML5 Specs might make you go, “Uhm… what?” The idea is pretty simple once you understand it. You want to write a buffer (imgData) where the top-left pixel is at dx,dy. sx and sy (or dirtyX and dirtyY) represent a dirty rectangle of size sw x sh (or dirtyWidth by dirtyHeight).

If the imageData passed to the function is the same height and width as the target canvas context, you wouldn’t want to overwrite every single pixel would you? You’d only want to overwrite pixels that have changed. Suppose in this script, I had an imageData object of 350×350 to complement the output canvas. When putting the modified imageData, I would have to calculate the current 35×35 box offset and write out the imageData to 0,0. As an example, if I wanted to overwrite the 35×35 box for the 9.9 magnitude marker with an imageData buffer of 350×350, I might write:

ctx.putImageData(imgData, 0, 0, 315, 315, 35, 35);

This would tell the context that although my buffer is 350×350, I’ve only changed a 35×35 rectangle starting at 315×15. Canvas is smart enough to only update those pixels rather than every pixel in the canvas.

On the other hand, in the script I’ve written, I only have an imageData object which represents a 35×35 buffer. So, I can tell putImageData to start at the point defined by (x,y) and write the buffer into a 35×35 rectangle. I like this method a little more, but it may not always be the case that you’re writing a smaller buffer to the context.

The code

As always, the code for this blog post is available on github at jimschubert/blogs.

The sprite

Here’s what the generated sprite looks like.

Markers generated for Quaketracker

Flattr this!

Getting started with jQuery plugins

jQuery plugins aren’t that difficult to write, but some folks seem to have a hard time understanding how to get started, so I thought I would write a quick blog post about that. I’ll show how to make a pretty simple keyword highlighter which also wraps your pre/code elements in a div with a header span element.

I’ve written a few jQuery plugins before. One of my favorites is jquery.empuzzle. This is a favorite not only because it’s incredibly fun, but because it covers a few areas of jquery plugin development:

  1. default options
  2. merge options
  3. custom selectors
  4. plugin structure

It also covers a particular gotcha when your plugin interacts with images (i.e. images may load after document ready is fired). It’s definitely worth checking it out, but I’d like to show a much simpler plugin here.

The structure

jQuery plugins are commonly written as an *immediate function*. This is creates a closure which executes immediate on the jQuery object itself:

;(function($) {
    // your plugin goes here.
})(jQuery);

I often wrap a jQuery plugin in semicolons as you see above to prevent any automatic semicolon insertion errors. This is something I would consider a ‘best practice’ and I suggest you do the same.

Within this structure, you’ll want to extend jQuery to include your plugin’s code.

$.fn is a pointer to the jQuery prototype object. When you execute a jQuery call like this:

var examples = $('.test-elements');

.. you will receive a jQuery object. This object represents an array of results matching the selector passed to the jQuery function. You can use console.log() from within your plugin function to see how you might interact with this object.

;(function($) {
    $.fn.example = function(arg) {
        console.log(this);
    };
})(jQuery);

You now have the start to a plugin called ‘example’. You can execute this ‘plugin’ in the normal way.

var examples = $('.test-elements');
examples.example();

// same as: $('.test-elements').example();

Now, you’ll want to iterate over each object found by the query selector and perform whatever functionality your plugin will provide. Let’s define some functionality so we can have a (somewhat) useful plugin. We’ll keep with the ‘example’ theme and write a plugin which stylizes a <code> tag and adds a small box in the top-left corner which says ‘Example’. (I got this idea from Twitter’s Bootstrap framework, see here). We’ll also ‘highlight’ a few keywords within our example.

Here’s what we want our final product to look like (after some hideous styling, of course):

For the goal screenshot, I’ve used Google’s prettify plugin, which is licensed under Apache 2.0. I don’t use this in the final product.

There will be a few things we’ll need to do in this plugin:

  1. Merge settings specified by the user with our default settings
  2. Wrap the code block in a styled ‘example’ box
  3. “parse” the contents for a select set of keywords
  4. Wrap any found keywords with a style span

For the parsing bit, I’ll just use a global RegEx replace on the contents of the code element.

Providing defaults

Providing defaults in a jQuery plugin and allowing a user to pass options to merge isn’t difficult. Your plugin function will accept a parameter I like to call ‘opts’ and return a `this.each` function. Within the `.each` function, you’ll extend the defaults object with those options passed into your plugin function and store the merged options into a new object called ‘options’. A very simple example which writes out to console.log might look like this:

;(function($) {
    var defaults = {
        arr: [1,2,3,4,5,6],
        sample: "sample",
        style: "style"
    };

    var example = function(opts) {
        return this.each(function() {
            // merge opts with defaults into new object
            // so changes don't change defaults
            var options = $.extend({}, defaults, opts);
            console.log({ 
                elem: this.innerText,
                options: options
            });
        });
    };

    $.fn.example = example;
})(jQuery);

Here are some options we might want to allow for the example plugin:

  1. A class name for the box and a class name for the label
  2. An object mapping keywords to class names.
  3. A parse error callback
  4. A data attribute to specify a different ‘Example’ box text (so each element can define its own label)

Our defaults object will look like this (more or less):

    var defaults = {
        boxCss: "example-box",
	labelCss: "example-label",
        keywords: { "function":"blue", "this":"blue", "jQuery":"red" },
        onError: function() { },
        exampleAttr: ""
    };

Wrapping our targets

To make our lives simple, we’ll first wrap the target element with a div for our example box. Then, we’ll add a span just before the code block. We can improve performance by creating the wrapper div’s HTML outside of the ‘.each’ function. Because we’re allowing the option of pulling the labeling span’s text from the code element itself, we’ll have to build that HTML within the ‘.each’ function.

Here’s what we have so far.

;(function($) {
    var defaults = {
        boxCss: "example-box",
        labelCss: "example-label",
        keywords: { "function":"blue", "this":"blue", "jQuery":"red" },
        onError: function() { },
        exampleAttr: ""
    };

    var example = function(opts) {
        var options = $.extend({}, defaults, opts);
        
        var wrapperHtml = [
            '<div class="',
            options.boxCss,
            '"></div>'
        ].join('');

        var labelArr = [
            '<span class="',
            options.labelCss,
            '">',
            "Example",
            '</span>'
        ];

        return this.each(function() {
            var labelText = "Example";
            if(options.exampleAttr) {
                labelText = $(this).attr(options.exampleAttr);
            }

            var labelHtml = [
                '<span class="',
                options.labelCss,
                '">',
                labelText,
                '</span>'
            ].join('');

            $(this).wrap(wrapperHtml);
            $(this).before(labelHtml);
        });
    };

    $.fn.example = example;
})(jQuery);

onError function

The onError function we allow in the options object does nothing more than provide a message if we don’t have a code element to update with keyword highlights. We will supply a message to the callback function and return from the current iteration of ‘.each’. This goes at the beginning of the ‘this.each’ function.

// Find node for replacing text.
var replacementNode = $(this).children('code').andSelf().filter('code');

if(replacementNode.length == 0) {
    if(typeof options.onError === "function"){
        options.onError("No code nodes found");
    }
    
    return;
}

With the combination of children/andSelf/filter in the above code, we allow the plugin to operate on both ‘pre’ and ‘code’ elements.

When allowing users to pass functions as callbacks or to provide added functionality to a plugin, *always* check that it is a function.

“Parsing” contents

In the interest of saving some time, I’m going to use a regular expression to replace text within the code block. This isn’t necessarily the most efficient way to achieve a budget syntax highlighter, but it will work.

To do this, we’ll need to grab the text from our code node in which we’ll replace keywords. Then, for every keyword in the hash of keywords-to-classes, we’ll create a span to represent the highlighted keyword. Then, we’ll do a search and replace using a global regular expression object, substituting each found keyword with the keyword wrapped in a span element. This goes at the end of the ‘this.each’ function.

    var originalText = replacementNode.text();
            
    Object.keys(options.keywords).forEach(function(key,idx){
        var replacement = [
            '<span class="',
            options.keywords[key],
            '">',
            key,
            '</span>'
        ].join('');
        
        var re = new RegExp(key,"g");
        originalText = originalText.replace(re, replacement);
    });

The only thing left to do is to add styles to your document and you’re all set with a customized syntax highlighter!

There are a few issues with this simple implementation. First, keywords don’t get merged (I’ll leave that as an exercise for you). Second, this only highlights keywords. It doesn’t provide regex matching for full-text highlights. In other words, this won’t highlight comments.

If you’re unfamiliar with jQuery plugins, or you’re planning to begin writing a keyword highlighter plugin, this should at least get you started!

Try it out!

Check out the jsfiddle.

Get the code

The code for this blog post is available on Github.

Flattr this!

ServiceStack’s Markdown Razor Engine. Wow.

ServiceStack is a pretty sweet-looking alternative to WCF. It provides strongly-typed, well-designed, REST/RCP+SOAP services for .NET and Mono. Check out the README in the repository to see how ridiculously easy it is to setup a service. Unfortunately, I haven’t yet had a chance to use the stack. I was looking through the code today and saw a Markdown-Razor Engine.

I was like, “Wha….?

Yes, they offer an alternative view engine which blends Markdown and Razor. These are my two favorite syntaxes, so I had to see how well it compiles.

I compiled the ServiceStack.RazorEngine from source (in Ubuntu 12.04/Mono, no less!) to test a simple markdown file.

I created this markdown file, example.md, to throw at the framework.

# Example ServiceStack.Markdown

## Showing @examples.Count items

@foreach (var item in examples) {
  - @item.Name: @item.Number 
}


**Note: The template requires a space after the item.Number value**

For more information, check out 
[the docs](http://www.servicestack.net/docs/markdown/markdown-razor).

Also, *don't forget* to check out the code at 
[gh:ServiceStack/ServiceStack](https://github.com/ServiceStack/ServiceStack)

Here are some _other_ attempts to **break** 
the markdown **generation_of_html**. **escaped\_underscore\_in\_tags**

A space after double-asterisk (&lt;strong&gt; tags) will ** break **

Now, when I say simple, I mean it has most elements of markdown that I use regularly. It also uses the markdown-razor foreach syntax which iterates over a collection of Example objects. This view is not strongly-typed, so this is equivalent to a dynamic Razor view.

The code to compile this view is really simple. You create the template engine, and provide a markdown page object which takes a full path (.e.g /fakepath/Debug) and the template contents (e.g. the above markdown snippet).

// Create the markdown-razor template compiler
MarkdownFormat format = new MarkdownFormat();
string contents = File.ReadAllText(template);
var page = new MarkdownPage(format, path, "example", contents );
format.AddPage(page);

Then, you create your view object (ViewBag?).

// Create our view container (ViewBag)
var view = new Dictionary<string, object>() 
{
	{ "examples", examples }
};

All that’s left is to pass in the view object and compile it to html!

// Compile and output. 
// This can be redirected to html file 
// e.g. RazorExample.exe > output.html
var html = format.RenderDynamicPageHtml("example", view);
Console.WriteLine(html);

The Code

As always, the code for this post is available on github. More examples on the Markdown Razor syntax available in ServiceStack are available in the test project in ServiceStack’s repository.

Flattr this!

System76 Ubuntu NetBook and Tethering on Verizon Droid (Android)

One of the first things I wanted to do when I got my netbook was to setup tethering.  However, I don’t want to pay $30 more a month just to view the same pages I’d otherwise be viewing on my phone (i.e. Facebook, Twitter, Google News/Gmail).  The answer to this is an application called EasyTether.  It’s currently only $10 on the Android Market.  Click here to download EasyTether.

The setup guide in EasyTether will walk you through getting the application configured on your phone and connecting that to your computer.  However, some people may have Linux-based NetBooks and not have the technical knowledge to write a simple script to startup ‘easytether’ in a console.  I’d like to provide those steps.  Please read on if you’re interested!

Note: You *MUST* have your sudo password to proceed. Continue reading System76 Ubuntu NetBook and Tethering on Verizon Droid (Android)

Flattr this!

Using DataAnnotation attributes to validate Membership password

As a follow-up to my post on DataAnnotations in ASP.NET Web Forms, I’d like to demonstrate yet another custom attribute. Although ASP.NET offers a CreateUserWizard, if your custom membership provider is way more complicated, you will probably be better off creating a control from scratch. If you go this route, you’ll have to provide some of the functionality from the CreateUserWizard. Here is a simple attribute which checks *only* password complexity and builds an ErrorMessage without ever calling the CreateUser method.

This attribute can be added to a password property and validate against the *Default* Membership Provider.

Here is the code:


    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
    public class MembershipPasswordRequiredAttribute : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            if (value == null || !(value is string) || string.IsNullOrEmpty(value.ToString()))
            {
                return false;
            }

            MembershipSection membershipConfig = (MembershipSection)WebConfigurationManager
                                                                    .GetSection("system.web/membership");
            var providerSettings = membershipConfig.Providers[membershipConfig.DefaultProvider];
            string minLength = providerSettings.Parameters["minRequiredPasswordLength"];
            string minAlpha = providerSettings.Parameters["minRequiredNonalphanumericCharacters"];

            if (string.IsNullOrEmpty(this.ErrorMessage) && !string.IsNullOrEmpty(minLength))
            {
                string message = String.Empty;
                message = String.Format("Password must be at least {0} characters in length", minLength);
                if (!string.IsNullOrEmpty(minAlpha))
                {
                    message = String.Format("{0} and contain at least {1} special character", message,  minAlpha);
                }

                this.ErrorMessage = message;
            }
                /* Validate against your provider and return true or false */
        }
    }

Usage:

[MembershipPasswordRequired]
internal string Password {get;set;}

The cool thing about this attribute is that you can decorate a property without specifying the ErrorMessage and it will build one dynamically from your default membership. Of course, you can change this up if you’re using multiple providers by getting the key of the current provider. But, the project I’m working on will always only have one provider, so this is how I’ll leave it.

A caveat: You can only set the ErrorMessage property once. If you try to assign to it more than once, you will receive an exception telling you this.

I won’t post the code for validating against the provider, because there are a number of ways to do this. Probably the safest way to do so is to use regex validation and pull that property from the provider’s parameters and just return whether the regex matches the string or not.

Anyway, I thought this was a pretty cool usage of DataAnnotations, and hooking it up on a custom CreateUser control was trivial with the DataAnnotation validator (from a few posts ago).

Flattr this!

My Development Blog

When I began my internship with Agility Healthcare Solutions (now part of GE Healthcare), I thought it would be beneficial to keep a blog of my activities. Originally, I intended to keep a blog of problems I found or areas I found difficult, in case I ever encountered these problems again. Then, I realized my blog could be beneficial to others if I post random code. Earlier stages of my blog focus on difficulties I have had, while later stages are just examples of my code.

Please, feel free to follow my blog and make comments!

The Link: Blogger: James Schubert

Flattr this!