I've written another Chrome extension that I consider in beta, but so far it works. Really ugly makeshift code, but I am not gathering data about the way I will use it, then I am going to refactor it, just as I did with Bookmark Explorer. You may find the code at GitHub and the extension at the Chrome webstore.

This is how it works: Every time you access anything with the browser, the extension will remember the IPs for any given host. It will hold a list of the IPs, in reverse order (last one first), that you can just copy and paste into your hosts file. The hosts file is found in c:/Windows/System32/drivers/etc/hosts and on Linux in /etc/hosts. Once you add a line in the format "IP host" in it, the computer will resolve the host with the provided IP. Every time there is a problem with DNS resolution, the extension will add the latest known IP into the hosts text. Since the extension doesn't have access to your hard drive, you need to edit the file yourself. The icon of DNS resolver will show the number of hosts that it wants to resolve locally or nothing, if everything is OK.

The extension allows manual selection of an IP for a host and forced inclusion or exclusion from the list of IP/host lines. Data can be erased (all at once for now) as well. The extension does not communicate with the outside, but it does store a list of all domains you visit, so it is a slight privacy risk - although if someone has access to the local store of a browser extension, it's already too late. There is also the possibility of the extension to replace the host with IP directly in the browser requests, but this only works for the browser and fails in case the host name is important, as in the case of multiple servers using the same IP, so I don't recommend using it.

There are two scenarios for which this extension is very useful:
  • The DNS server fails for some reason or gives you a wrong IP
  • Someone removed the IP address from DNS servers or replaced it with one of their own, like in the case of governments censorship

I have some ideas for the future:
  • Sharing of working IP/host pairs - have to think of privacy before that, though
  • Installing a local DNS server that can communicate locally with the extension, so no more hosts editing - have to research and create one
  • Upvoting/Downvoting/flagging shared pairs - with all the horrible head-ache this comes with

As usual, let me know what you think here, or open issues on GitHub.

I had this crazy idea that I could make each word on my page come alive. The word "robot" would walk around the page, "explosion" would explode, "rotate" would rotate, color words would appear in the color they represent, no matter how weird named like OliveDrab , Chocolate , Crimson , DeepPink , DodgerBlue and so on, "radioactive" would pulse green, "Siderite" would appear in all its rocking glory and so on. And so I did!

The library is on GitHub and I urge you to come and bring your own ideas. Every effect that you see there is an addon that can be included or not in your setup.



Also see directly on GitHub pages.








Update 29 August 2017 - Version 3.0.4: The extension has been rewritten in EcmaScript6 and tested on Chrome, Firefox and Opera.

Update 03 March 2017 - Version 2.9.3: added a function to remove marketing URLs from all created bookmarks. Enable it in the Advanced settings section. Please let me know of any particular parameters you need purged. So far it removes utm_*, wkey, wemail, _hsenc, _hsmi and hsCtaTracking.

Update 26 February 2017: Version (2.9.1): added customizing the URL comparison function. People can choose what makes pages different in general or for specific URL patterns
Update 13 June 2016: Stable version (2.5.0): added Settings page, Read Later functionality, undelete bookmarks page and much more.
Update 8 May 2016: Rewritten the extension from scratch, with unit testing.
Update 28 March 2016: The entire source code of the extension is now open sourced at GitHub.

Whenever I read my news, I open a bookmark folder containing my favorite news sites, Twitter, Facebook, etc. I then proceed to open new tabs for each link I find interesting, closing the originating links when I am done. Usually I get a number of 30-60 open tabs. This wreaks havoc on my memory and computer responsiveness. And it's really stupid, because I only need to read them one by one. In the end I've decided to fight my laziness and create my first browser extension to help me out.

The extension is published here: Siderite's Bookmark Explorer and what it does is check if the current page is found in any bookmark folder, then allow you to go forward or backwards inside that folder.

So this is my scenario on using it:
  1. Open the sites that you want to get the links from.
  2. Open new tabs for the articles you want to read or YouTube videos you want to watch,etc.
  3. Bookmark all tabs into a folder.
  4. Close all the tabs.
  5. Navigate to the bookmark folder and open the first link.
  6. Read the link, then press the Bookmark Navigator button and then the right arrow. (now added support for context menu and keyboard shortcuts)
  7. If you went too far by mistake, press the left arrow to go back.

OK, let's talk about how I did it. In order to create your own Chrome browser extension you need to follow these steps:

1. Create the folder


Create a folder and put inside a file called manifest.json. It's possible structure is pretty complex, but let's start with what I used:
{
"manifest_version" : 2,

"name" : "Siderite's Bookmark Explorer",
"description" : "Gives you a nice Next button to go to the next bookmark in the folder",
"version" : "1.0.2",

"permissions" : [
"tabs",
"activeTab",
"bookmarks",
"contextMenus"
],
"browser_action" : {
"default_icon" : "icon.png",
"default_popup" : "popup.html"
},
"background" : {
"scripts" : ["background.js"],
"persistent" : false
},
"commands" : {
"prevBookmark" : {
"suggested_key" : {
"default" : "Ctrl+Shift+K"
},
"description" : "Navigate to previous bookmark in the folder"
},
"nextBookmark" : {
"suggested_key" : {
"default" : "Ctrl+Shift+L"
},
"description" : "Navigate to next bookmark in the folder"
}
}
}

The manifest version must be 2. You need a name, a description and a version number. Start with something small, like 0.0.1, as you will want to increase the value as you make changes. The other thing is that mandatory is the permissions object, which tells the browser what Chrome APIs you intend to use. I've set there activeTab, because I want to know what the active tab is and what is its URL, tabs, because I might want to get the tab by id and then I don't get info like URL if I didn't specify this permission, bookmarks, because I want to access the bookmarks, and contextMenus, because I want to add items in the page context menu. More on permissions here.

Now, we need to know what the extension should behave like.

If you want to click on it and get a popup that does stuff, you need to specify the browser_action object, where you specify the icon that you want to have in the Chrome extensions bar and/or the popup page that you want to open. If you don't specify this, you get a default button that does nothing on click and presents the standard context menu on right click. You may only specify the icon, though. More on browserAction here.

If you want to have an extension that reacts to background events, monitors URL changes on the current page, responds to commands, then you need a background page. Here I specify that the page is a javascript, but you can add HTML and CSS and other stuff as well. More on background here.

Obviously, the files mentioned in the manifest must be created in the same folder.

The last item in the manifest is the commands object. For each command you need to define the id, the keyboard shortcut (only the 0..9 and A..Z are usable unfortunately) and a description. In order to respond to commands you need a background page as shown above.

2. Test the extension


Next you open a Chrome tab and go to chrome://extensions, click on the 'Developer mode' checkbox if it is not checked already and you get a Load unpacked extension button. Click it and point the following dialog to your folder and test that everything works OK.

3. Publish your extension


In order to publish your extension you need to have a Chrome Web Store account. Go to Chrome Web Store Developer Dashboard and create one. You will need to pay a one time 5$ fee to open it. I know, it kind of sucks, but I paid it and was done with it.

Next, you need to Add New Item, where you will be asked for a packed extension, which is nothing but the ZIP archive of all the files in your folder.

That's it.

Let's now discuss actual implementation details.

Adding functionality to popup elements


Getting the popup page elements is easy with vanilla Javascript, because we know we are building for only one browser: Chrome! So getting elements is done via document.getElementById(id), for example, and adding functionality is done via elem.addEventListener(event,handler,false);

One can use the elements as objects directly to set values that are related to those elements. For example my prev/next button functionality takes the URL from the button itself and changes the location of the current tab to that value. Code executed when the popup opens sets the 'url' property on the button object.

Just remember to do it when the popup has finished loading (with document.addEventListener('DOMContentLoaded', function () { /*here*/ }); )

Getting the currently active tab


All the Chrome APIs are asynchronous, so the code is:
chrome.tabs.query({
'active' : true,
'lastFocusedWindow' : true
}, function (tabs) {
var tab = tabs[0];
if (!tab) return;
// do something with tab
});

More on chrome.tabs here.

Changing the URL of a tab


chrome.tabs.update(tab.id, {
url : url
});

Changing the icon in the Chrome extensions bar


if (chrome.browserAction) chrome.browserAction.setIcon({
path : {
'19' : 'anotherIcon.png'
},
tabId : tab.id
});

The icons are 19x19 PNG files. browserAction may not be available, if not declared in the manifest.

Get bookmarks


Remember you need the bookmarks permission in order for this to work.
chrome.bookmarks.getTree(function (tree) {
//do something with bookmarks
});

The tree is an array of items that have title and url or children. The first tree array item is the Bookmarks Bar, for example. More about bookmarks here.

Hooking to Chrome events


chrome.tabs.onUpdated.addListener(refresh);
chrome.tabs.onCreated.addListener(refresh);
chrome.tabs.onActivated.addListener(refresh);
chrome.tabs.onActiveChanged.addListener(refresh);
chrome.contextMenus.onClicked.addListener(function (info, tab) {
navigate(info.menuItemId, tab);
});
chrome.commands.onCommand.addListener(function (command) {
navigate(command, null);
});

In order to get extended info on the tab object received by tabs events, you need the tabs permission. For access to the contextMenus object you need the contextMenus permission.

Warning: if you install your extension from the store and you disable it so you can test your unpacked extension, you will notice that keyboard commands do not work. Seems to be a bug in Chrome. The solution is to remove your extension completely so that the other version can hook into the keyboard shortcuts.

Creating, detecting and removing menu items


To create a menu item is very simple:
chrome.contextMenus.create({
"id" : "menuItemId",
"title" : "Menu item description",
"contexts" : ["page"] //where the menuItem will be available
});
However, there is no way to 'get' a menu item and if you try to blindly remove a menu item with .remove(id) it will throw an exception. My solution was to use an object to store when I created and when I destroyed the menu items so I can safely call .remove().

To hook to the context menu events, use chrome.contextMenus.onClicked.addListener(function (info, tab) { }); where info contains the menuItemId property that is the same as the id used when creating the item.

Again, to access the context menu API, you need the contextMenus permission. More about context menus here.

Commands


You use commands basically to define keyboard shortcuts. You define them in your manifest and then you hook to the event with chrome.commands.onCommand.addListener(function (command) { });, where command is a string containing the key of the command.

Only modifiers, letters and digits can be used. Amazingly, you don't need permissions for using this API, but since commands are defined in the manifest, it would be superfluous, I guess.

That's it for what I wanted to discuss here. Any questions, bug reports, feature requests... use the comments in the post.

F# has an interesting feature called Active Patterns. I liked the idea and started thinking how I would implement this in C#. It all started from this StackOverflow question to which only Scala answers were given at the time.

Yeah, if you read the Microsoft definition you can almost see the egghead that wrote that so that you can't understand anything. Let's start with a simple example that I have shamelessly stolen from here.
// create an active pattern

let (|Int|_|) str =
match System.Int32.TryParse(str) with
| (true, int) -> Some(int)
| _ -> None

// create an active pattern

let (|Bool|_|) str =
match System.Boolean.TryParse(str) with
| (true, bool) -> Some(bool)
| _ -> None

// create a function to call the patterns

let testParse str =
match str with
| Int i -> printfn "The value is an int '%i'" i
| Bool b -> printfn "The value is a bool '%b'" b
| _ -> printfn "The value '%s' is something else" str

// test

testParse "12"
testParse "true"
testParse "abc"

The point here is that you have two functions that return a parsed value, either int or bool, and also a matching success thing. That's a problem in C#, because it is strongly typed and if you want to use anything than boxed values in objects, you need to define some sort of class that holds two values. I've done that with a class I called Option<T>. You might want to see the code, but it is basically a kind of Nullable class that accepts any type, not just value types.
Click to expand

Then I wrote code that did what the original code did and it looks like this:
var apInt = new Func<string, Option<int>>(s =>
{
int i;
if (System.Int32.TryParse(s, out i)) return new Option<int>(i);
return Option<int>.Empty;
});
var apBool = new Func<string, Option<bool>>(s =>
{
bool b;
if (System.Boolean.TryParse(s, out b)) return new Option<bool>(b);
return Option<bool>.Empty;
});

var testParse = new Action<string>(s =>
{
var oi = apInt(s);
if (oi.HoldsValue)
{
Console.WriteLine($"The value is an int '{oi.Value}'");
return;
}
var ob = apBool(s);
if (ob.HoldsValue)
{
Console.WriteLine($"The value is an bool '{ob.Value}'");
return;
}
Console.WriteLine($"The value '{s}' is something else");
});

testParse("12");
testParse("true");
testParse("abc");

It's pretty straighforward, but I didn't like the verbosity, so I decided to write it in a fluent way. Using another class called FluidFunc that I created for this purpose, the code now looks like this:
var apInt = Option<int>.From<string>(s =>
{
int i;
return System.Int32.TryParse(s, out i)
? new Option<int>(i)
: Option<int>.Empty;
});

var apBool = Option<bool>.From<string>(s =>
{
bool b;
return System.Boolean.TryParse(s, out b)
? new Option<bool>(b)
: Option<bool>.Empty;
});

var testParse = new Action<string>(s =>
{
FluidFunc
.Match(s)
.With(apInt, r => Console.WriteLine($"The value is an int '{r}'"))
.With(apBool, r => Console.WriteLine($"The value is an bool '{r}'"))
.Else(v => Console.WriteLine($"The value '{v}' is something else"));
});

testParse("12");
testParse("true");
testParse("abc");

Alternately, one might use a Tuple<bool,T> to avoid using the Option class, and the code might look like this:
var apInt = FluidFunc.From<string,int>(s =>
{
int i;
return System.Int32.TryParse(s, out i)
? new Tuple<bool, int>(true, i)
: new Tuple<bool, int>(false, 0);
});

var apBool = FluidFunc.From<string,bool>(s =>
{
bool b;
return System.Boolean.TryParse(s, out b)
? new Tuple<bool, bool>(true, b)
: new Tuple<bool, bool>(false, false);
});

var testParse = new Action<string>(s =>
{
FluidFunc
.Match(s)
.With(apInt, r => Console.WriteLine($"The value is an int '{r}'"))
.With(apBool, r => Console.WriteLine($"The value is an bool '{r}'"))
.Else(v => Console.WriteLine($"The value '{v}' is something else"));
});

testParse("12");
testParse("true");
testParse("abc");

As you can see, the code now looks almost as verbose as the original F# code. I do not pretend that this is the best way of doing it, but this is what I would do. It also kind of reminds me of the classical situation when you want to do a switch, but with dynamic calculated values or with complex object values, like doing something based on the type of a parameter, or on the result of a more complicated condition. I find this fluent format to be quite useful.

One crazy cool idea is to create a sort of Linq provider for regular expressions, creating the same type of fluidity in generating regular expressions, but in the end getting a ... err... regular compiled regular expression. But that is for other, more epic posts.

The demo solution for this is now hosted on Github.

Here is the code of the FluidFunc class, in case you were wondering:
public static class FluidFunc
{
public static FluidFunc<TInput> Match<TInput>(TInput value)
{
return FluidFunc<TInput>.With(value);
}

public static Func<TInput, Tuple<bool, TResult>> From<TInput, TResult>(Func<TInput, Tuple<bool, TResult>> func)
{
return func;
}
}

public class FluidFunc<TInput>
{
private TInput _value;
private static FluidFunc<TInput> _noOp;
private bool _isNoop;

public static FluidFunc<TInput> NoOp
{
get
{
if (_noOp == null) _noOp = new FluidFunc<TInput>();
return _noOp;
}
}

private FluidFunc()
{
this._isNoop = true;
}

private FluidFunc(TInput value)
{
this._value = value;
}

public static FluidFunc<TInput> With(TInput value)
{
return new FluidFunc<TInput>(value);
}

public FluidFunc<TInput> With<TNew>(Func<TInput, Option<TNew>> func, Action<TNew> action)
{
if (this._isNoop)
{
return this;
}
var result = func(_value);
if (result.HoldsValue)
{
action(result.Value);
return FluidFunc<TInput>.NoOp;
}
return new FluidFunc<TInput>(_value);
}

public FluidFunc<TInput> With<TNew>(Func<TInput, Tuple<bool,TNew>> func, Action<TNew> action)
{
if (this._isNoop)
{
return this;
}
var result = func(_value);
if (result.Item1)
{
action(result.Item2);
return FluidFunc<TInput>.NoOp;
}
return new FluidFunc<TInput>(_value);
}

public void Else(Action<TInput> action)
{
if (this._isNoop) return;

action(_value);
}

}

On the 9th of February I basically held the same talk I did at Impact Hub, only I did better, and this time presented to the ADCES group. Unbeknownst to me, my colleague there Andrei Rînea also held a similar presentation with the same organization, more than two years ago, and it is quite difficult to assume that I was not inspired by it when one notices how similar they really were :) Anyway, that means there is no way people can say they didn't get it, now! Here is his blog entry about that presentation: Bing it on, Reactive Extensions! – story, code and slides

The code, as well as a RevealJS slideshow that I didn't use the first time, can be found at Github. I also added a Javascript implementation of the same concept, using a Wikipedia service instead - since DictService doesn't support JSON.

Today I was the third presenter in the ReactiveX in Action event, held at Impact Hub, Bucharest. The presentation did not go as well as planned, but was relatively OK. I have to say that probably, after a while, giving talks to so many people turns from terrifying to exciting and then to addictive. Also, you really learn things better when you are preparing to teach them later, rather than just perusing them.

I will be holding the exact same presentation, hopefully with a better performance, on the 9th of February, at ADCES.

For those interested in what I did, it was a code only demo of a dictionary lookup WPF application written in .NET C#. In the ideal code that you can download from Github, there are three projects that do the exact same thing:
  1. The first project is a "classic" program that follows the requirements.
  2. The second is a Reactive Extensions implementation.
  3. The third is a Reactive Extensions implementation written in the MVVM style.

The application has a text field and a listbox. When changing the text of the field, a web service is called to return a list of all words starting with the typed text and list them in the listbox, on the UI thread. It has to catch exceptions, throttle the input, so that you can write a text and only access the web service when you stop typing, implement a timeout if the call takes too long, make sure that no two subsequent calls are being made with the same text argument, retry three times the network call if it fails for any of the uncaught exceptions. There is a "debug" listbox as well as a button that should also result in a web service query.

Unfortunately, the code that you are downloading is the final version, not the simple one that I am writing live during the presentation. In effect, that means you don't understand the massive size reduction and simplification of the code, because of all the extra debugging code. Join me at the ADCES presentation (and together we can rule the galaxy) for the full demo.

Also, I intend to add something to the demo if I have the time and that is unit testing, showing the power of the scheduler paradigm in Reactive Extensions. Wish me luck!

Today I published a raw version of a program that solves Pixelo puzzles, a Flash version of the game generally known as Nonogram, Picross, Hanjie, etc.. I was absolutely fascinated by the game, not only the concept, but also the attention to details that Tamaii lent to the game. The program is called Pixelo Solver and you can find it at Github, complete with source code.


I liked working on this because it covers several concepts that I found interesting:
  • Responding to global key combinations
  • Getting a snapshot of the screen and finding an object in it
  • Parsing a visual image for digits in a certain format
  • The algorithm for solving the puzzle in a reasonable amount of time and memory (it was not trivial)

Quick how-to: get all the files from here and copy them in a folder, then run PixeloTools.GameSolver.exe and press Ctrl-Shift-P on your puzzle in the browser.

Usage:
  1. Start PixeloTools.GameSolver.exe
  2. Open the browser to the Pixelo game
  3. Start a puzzle
  4. Press Ctrl-Shift-P

However, if the list of numbers per row or column is too long, the automated parsing will not work. In that case, you may use it offline, with a parameter that defines a file in the format:
5 1 10, 3 3 7, 2 5 4, 2 5 2, 2 1 1 1, 1 1 1 1 1, 1 1 3 1 1, 1 1 1 1 1, 1 1 1, 1 1, 1 1, 2 2 2 4, 2 1 1 1 2 4, 2 1 2 1, 7 4, 2 2 1 2 2 2, 2 1 1 1 1 1 1, 2 1 1 4 2, 1 3 4 2 1, 1 1
8 1 1, 5 2 2 1, 2 1 3, 1 1, 1 7 4 1, 3 5 1, 3 1 1 3, 4 3 4, 3 1 1 3, 3 5 1, 1 7 4 1, 1 2, 1 1 1, 2 2 2, 2 1 1 2, 2 1 2 2, 3 2 1, 3 1 1, 4 1 2 2, 9 2 3
where the first line is the horizontal lines and the second line the vertical lines. When the parsing fails, you still get something like this in the output of the program. You can just copy paste the two lines in a file, edit it so that it matches the puzzle, then run:
start "" PixeloTools.GameSolver.exe myFile.txt

The file can also be in XML format, same as in the file the game loads. That's for Tamaii's benefit, mostly.

Let me know what you think in the comments below.


Update 23 Oct 2023: Here are the latest files to directly download and use. Do read the rest of the article, as these files might not be what you are looking for:
user.action
user.filter

Update 12 Feb 2016: As an alternative, if you have access to your hosts file, you can use a generated list of domains to immediately block any access to those IPs, courtesy of Steven Black: StevenBlack/hosts, and you don't have to install anything and works on most operating systems.

Now for the rest of the article:

I discovered today a new tool called Privoxy. It is a proxy software that has extra features, like ad blocking and extra privacy. What that means is that you can install the proxy, point your browser to that proxy and have an almost ad free untracked by marketing firms or FaceBook experience. The only problem, though, is that the default filters are not so comprehensive. Would it be great if one could take the most used list for ad blocking (Adblock Plus' Easylist) and convert it to Privoxy? Well it would, only that no one seems to want to do it for Windows. You get a few folks that have created Linux scripts to do the conversion, but they won't work for Windows. Nor do they deem it necessary to make an online tool or a web service or at least publish the resulting files so that we, Windows people, can also use the list!

Well, I intend to do a small script that will allow for this, preferably embedded in this blog post, but until then, I had no script, no files, only Privoxy installed. Luckily, I also have Cygwin installed, which allows me to run a ridiculous flavour of Linux inside Windows. I had to hack the script in order for it to work on Cygwin, but in the end, at last, I managed to make it work. For now, I will publish the resulting files here and give you instructions to install them. When they become obsolete, send me a comment and I will refresh them.

So, the instructions:

  • Install Privoxy
  • Go to the installation folder of Privoxy and look for files named 'user.action' and 'user.filter'
  • Download the user.action file from here and replace the default one.
  • Download the user.filter file from here and replace the default one.
  • Restart Privoxy
  • Of course, then you have to go to your browser settings and set the proxy to Privoxy (usually localhost, port 8118)


Warning! The filter file is quite big and it will cause some performance issues. You might want to use only the action file with the filter actions removed.

Update: If you can't download the files, let me know. I am using Github pages and it seems sometimes it doesn't work as I expected.

Also, I have lost faith that AdBlockPlus rules can be completely and correctly translated to Privoxy and I lack the time, so I am publishing my crappy program as it is and if you want to use it or fix it, be my guest. You can find the program here: AdblockPlus to Privoxy. I would ask that you share with me those modifications, though, so that everybody can benefit from them.

Update October 2023: Other people have contributed by making their own translation software. Here are the links for the binary and source code of adblock2privoxy made by Zubr, in Haskell mind you, which is pretty cool:

Binary: https://www.dropbox.com/s/69u1iqbubzft1yl/adblock2privoxy-1.2.4.rar?dl=0
Source code: https://projects.zubr.me/wiki/adblock2privoxy

The original software is not available anymore, but here is a GitHub fork for the same: https://github.com/essandess/adblock2privoxy

The latest sources are now on Github: C# 4.0 library to generate INotifyPropertyChanged proxy from POCO type. The source from the post, designed as a proof of concept, is not the same as the one from Github.

It all started from a Sacha Barber post on CodeProject, enumerating ways in which one can use Aspect Oriented Programming to mark simple automatic properties so that they get compiled into fully fledged INotifyPropertyChanged properties, thus saving us the grief of repeating the same code over and over again in each property setter. The implementations there were good, but too complex, relying on third party libraries, some of them not even free.
He completely ignored template generators like T4, but then again, that particular approach has a lot of issues associated with it, like having to either parse source files or somehow tap into the compiled assembly... before you compile it.
However, this brought forth the idea that I could do this, maybe in some other way.

Enter Felice Pollano, with his article on CodeProject detailing a method of using CodeDom generation to create at runtime the INotifyPropertyChanged object from an already existing type. This is pretty slow, but only when first creating the type, so with a cache system it would be totally usable. I liked this approach better, but I noticed there were some errors in the generated code and when I tried changing the generating code I had to look at it for half an hour just to understand where to change it. Wouldn't it be better to use some sort of template that would be easy to edit and use it to generate the proxy type?

So this is my take on generating INotifyPropertyChanged classes dynamically, avoiding the repetitive plumbing in property setters. The library contains a template for the class and a separate template for the properties. The proxy type is being generated in memory from a string that is generated from the source type and the two templates. All in all, one class, two templates, three public methods and four static methods. As easy as 1,2,3,4 :) Here is the code:

Click to expand/collapse
public static class TypeFactory
{
private static readonly Dictionary<Type, Type> sCachedTypes = new Dictionary<Type, Type>();

public static T GetINotifyPropertyChangedInstance<T>(params object[] arguments)
{
Type type = GetINotifyPropertyChangedType<T>();
return (T) Activator.CreateInstance(type, arguments);
}

public static Type GetINotifyPropertyChangedType<T>()
{
return GetINotifyPropertyChangedType(typeof (T));
}

public static Type GetINotifyPropertyChangedType(Type type)
{
Type result;
lock (((ICollection) sCachedTypes).SyncRoot)
{
if (!sCachedTypes.TryGetValue(type, out result))
{
result = createINotifyPropertyChangedProxyType(type);
sCachedTypes[type] = result;
}
}
return result;
}

public static bool IsVirtual(this PropertyInfo info)
{
return (info.CanRead == false || info.GetGetMethod().IsVirtual)
&&
(info.CanWrite == false || info.GetSetMethod().IsVirtual);
}


private static Type createINotifyPropertyChangedProxyType(Type type)
{
var className = "@autonotify_" + type.Name;
var properties = type.GetProperties().Where(p => p.IsVirtual());
var sourceCode = getINotifyPropertyChangedSourceCode(className, type, properties);
var assembly = generateAssemblyFromCode(sourceCode);
return assembly.GetTypes().First();
}

private static string getINotifyPropertyChangedSourceCode(string className, Type baseType,
IEnumerable<PropertyInfo> properties)
{
var classTemplate = getTemplate("INotifyPropertyChangedClassTemplate.txt");
var propertyTemplate = getTemplate("INotifyPropertyChangedPropertyTemplate.txt");
var usingsBuilder = new StringBuilder();
var propertiesBuilder = new StringBuilder();
usingsBuilder.AppendLine("using System.ComponentModel;");
usingsBuilder.AppendFormat("using {0};\r\n", baseType.Namespace);
foreach (PropertyInfo propertyInfo in properties)
{
usingsBuilder.AppendFormat("using {0};\r\n", propertyInfo.PropertyType.Namespace);

string propertyString = propertyTemplate
.Replace("{propertyType}", propertyInfo.PropertyType.FullName)
.Replace("{propertyName}", propertyInfo.Name);
propertiesBuilder.AppendLine(propertyString);
}
string sourceCode = classTemplate
.Replace("{usings}", usingsBuilder.ToString())
.Replace("{className}", className)
.Replace("{baseClassName}", baseType.Name)
.Replace("{properties}", propertiesBuilder.ToString());
#if DEBUG
Debug.WriteLine(sourceCode);
#endif
return sourceCode;
}

private static string getTemplate(string resourceName)
{
var templateAssembly = Assembly.GetAssembly(typeof (TypeFactory));
resourceName = templateAssembly.GetManifestResourceNames()
.First(name => name.EndsWith(resourceName));
using (Stream stream = templateAssembly.GetManifestResourceStream(resourceName))
{
using (var streamReader = new StreamReader(stream))
{
return streamReader.ReadToEnd();
}
}
}

private static Assembly generateAssemblyFromCode(string sourceCode)
{
var codeProvider = CodeDomProvider.CreateProvider("CSharp");
var parameters = new CompilerParameters
{
GenerateExecutable = false,
GenerateInMemory = true
};
var locations = AppDomain.CurrentDomain.GetAssemblies()
.Where(v => !v.IsDynamic).Select(a => a.Location).ToArray();
parameters.ReferencedAssemblies.AddRange(locations);
CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, sourceCode);
#if DEBUG
foreach (CompilerError error in results.Errors)
{
Debug.WriteLine("Error: " + error.ErrorText);
}
#endif
return results.Errors.Count > 0
? null
: results.CompiledAssembly;
}
}


As you can see, the code needs only a type that has public virtual properties in it and it will create a proxy that will inherit that class, implement INotifyPropertyChange and override each virtual property with a notifying one. The templates are so basic that I feel slightly embarrassed; I keep thinking if I should have created template entities that would stay in the same file. :) Here are the templates:

{usings}

namespace __generatedINotifyPropertyChanged
{
  public class {className} : {baseClassName},INotifyPropertyChanged
  {
    public event PropertyChangedEventHandler PropertyChanged;

    {properties}

    private void OnPropertyChanged(string propertyName)
    {
      var handler=PropertyChanged;
      if (handler != null)
      {
        handler(this, new PropertyChangedEventArgs(propertyName));
      }
    }
  }
}

public override {propertyType} {propertyName}
{
  get { return base.{propertyName}; }
  set {
    if (!Equals(value,base.{propertyName})) {
      base.{propertyName}=value;
      OnPropertyChanged("{propertyName}");
    }
  }
}


Don't forget to save the templates as Embedded Resource in the assembly.

Update: At Sacha Barber's advice I took a look at the DynamicObject solution for the INotifyPropertyChanged code smell. The link he provided is OlliFromTor's CodeProject article Using DynamicObject to Implement General Proxy Classes. While this works a lot easier than with compiling generated code, it also has a major drawback: the proxy class does not inherit from the original object and so it can only be used as such, but only in dynamic scenarios. Otherwise, it seems to be a perfect solution for proxy scenarios, if you are willing to discard the type safety.

I've heard about LESS yesterday so I thought about how I would use it in my projects. Using a .NET http handler is just fine, but I was thinking of a simpler approach, so I created jQuery.cssLess, a jQuery plugin that reads the css and interprets it. You can find it at Github.

Current version supports variables, mixins and nested rules. I am wondering if it is even worth it to implement operations. It may bloat the plugin too much. What do you think?

Little did I know, someone else was trying a js centric approach to this. The project is called less.js and it's made by cloudhead. You can find it at GitHub.

If you are using LESS and decide to use jQuery.cssLess, please leave me a message about it and whatever your opinions are.

Yay! New Github project: EasyReplace.

What it does is replace all files in a folder hierarchy with the files you drag&drop on the app info box. It is very helpful when you want to replace old library files or some other versions of your files with newer ones without having to manually navigate through solution folders.

I've stumbled upon this Windows port of a Linux application called HotBabe. What it does is show a transparent image of a girl over your applications that looks more naked as the CPU is used more. I wanted to use my own pictures and explore some of the concepts of desktop programming that are still a bit new to me, so I rewrote it from scratch.

The project is now up on Github and is functional. Please report any bugs or write any feature requests here or on the project page in order to make this even cooler.

Features:
  • Custom images responding to custom measurements
  • Custom measures (included are Cpu, Memory and Random, but an abstract class for custom monitor classes is included)
  • AutoRun, ClickThrough, Opacity control
  • Interface for custom images and custom monitors
  • XML config file


Update: After adding a lot of new features, I've also written a blog entry about the highlights from HotBabe.NET's development, a "making of", if you will. You can find it here: Things I've learned from HotBabe.NET.

Enjoy!

Ever wanted to bind something to the layout rendering phase of an element in Javascript? This helps, by checking at a fixed interval if the size or position of an element have changed and, if so, firing the 'refresh' custom event. All one has to do is then bind to it.

Github page: https://github.com/Siderite/jGenerateRefresh
JQuery plugins page: http://plugins.jquery.com/node/9030

Example:
$(function() { 
$('#target').bind('refresh',{},someRefreshFunction);
$('#target').generateRefreshEvent(100); // every 100 milliseconds
});

Update: two more days of work and a huge text file of regular expressions and I know a lot more about the syntax of .Net Regex than even MSDN :)
The third (Apr11) release of the library has a huge load of bug fixes and new features and it is now... [Tadaaaaa]... a stable version. At least I think of it that way :) Go download it.!

I've been working for two days on an idea. What can I do to make those long regular expressions that I always leave in my code more readable and easy to understand without having to compile automatons in your head?

I have first researched on Google regular expression converters. Nothing was even close to what I wanted. Also, on the more scientific side, people were talking a lot about BNFs, as a superset of regular expression syntax. I looked at BNF. Yes, it describes anything in a human readable form, it is used in RFCs but I hate it even more than XML! So XML it is. Most of the inspiration for the code came from this link: Regular expressions and regular grammars

I give you, RegexConverter. It is a library+demo that transforms a Regex into an XML and then back again. The demo application demonstrates (duh!) this by having two panes, one in which to write regex and the other in which to write XML. Changing one, also changes the other. It warns you of errors in both Regex, RegexConverter and then checks if what it got can be safely converted into your changed string!

Please tell me what you think. I believe it can be a real help in understanding regular expressions, some specific ones or regular expression syntax in general, whether one is a pro or a complete noob.

I've worked hard to design the library source in a way that is understandable, I also added comments everywhere. I tried to implement all the specifications of .NET regular expressions from the MSDN site so if you have a regex that is valid but can't be turned into XML or the conversion is not perfect, let me know.

The link is: RegexConverter on Github.

I will update this post with more science and links to my places of inspiration for this, so stay tuned.

Update: Ok, so I haven't updated this post much. Shame on me. I was reminded of this project when I got an email from the FamousWhy site which said RegexConverter "has been granted the Famous Software Award". I know it's probably an automatically generated message and went to many or all of the Codeplex people, but still: automated attention is still attention :)

A while ago I wrote a post detailing a fix for Very slow UpdatePanel refresh when containing big ListBoxes of DropDownLists. I have restructured the fix into a ControlAdapter and placed it on Github.

Enjoy!