3 Things I Learned This Week 2015-01-30

HTML Entity Decode in Javascript

Apparently javascript doesn’t have an out of the box function to decode html entities. But you can do it by forcing setting the innerHTML of a disconnected DOM element to your string, and then reading it back out. Quite a hack!

html-entity-decode.js
1
2
3
4
5
function htmlDecode(s) {
var textarea = document.createElement("textarea");
textarea.innerHTML = s;
return textarea.value;
}

Or if you have jQuery its a one-liner:

html-entity-decode-jquery.js
1
2
3
function htmlDecode(s) {
return $("<textarea/>").html(s).val();
}

Note that you have to use a text area or you open up some XSS vulnerabilities. Most browsers will start downloading assets and scripts even before the disconnected DOM element is added to the document.

BlockingCollection is nice for .NET producer-consumer contexts.

I’m building a tool that could benefit from a publish-subscribe threading model. BlockingCollection is one nice trick for that. It provides an IEnumerable interface that you can use as a task queue.

Threads will have their foreach block until items are added to the queue. The items will be yielded to only one of the waiting threads. You can mark the queue as complete and all the waiting threads will stop enumerating gracefully.

See Justin Etheredge’s BlockingCollection and IProducerConsumerCollection and especially note the first comment.

Building ASP.NET HttpModules

I had to create an HttpModule so we could check the status of something on each request. You just implement IHttpModule, wire up whatever events you want, and do your work. Register it in the web.config httpModules section and you’re good to go.