Showing posts with label extensions. Show all posts
Showing posts with label extensions. Show all posts

Monday, May 24, 2010

The coolest code

At [the appropriately-numbered] revision 42 in a certain source control repository lies, without a doubt, the biggest masterpiece of software ever written since the advent of the parentheses:
public static IEnumerable<T> PreOrder<T>(this T startingPoint, Func<T, IEnumerable<T>> children)
{
    yield return startingPoint;
    foreach (var child in children(startingPoint))
    {
        var preOrderedChildren = PreOrder(child, children);
        foreach (var preOrderedChild in preOrderedChildren)
        {
            yield return preOrderedChild;
        }
    }
}
"What is it?" you say? It's a generic, recursive generator, implemented as an extension method with a functor.

"Uhh, so... what does it do?" you counter? It traverses a tree of items (of type T) by yielding them, starting at the provided startingPoint and obtaining the children of a given instance of T using the provided children function object.

"I am from Missouri. You have got to show me." Sure thing! Suppose we have this Node class:
public class Node : IEnumerable<Node>
{
    private readonly IList<Node> _children = new List<Node>();
    public IEnumerable<Node> Children { get { return _children; } }

    private readonly string _name;
    public string Name { get { return _name; } }

    public Node(string name)
    {
        _name = name;
    }

    public Node Add(string nodeName)
    {
        return Add(new Node(nodeName));
    }

    public Node Add(Node node)
    {
        _children.Add(node);
        return node;
    }

    #region IEnumerable<Node> Members
    public IEnumerator<Node> GetEnumerator()
    {
        return Children.GetEnumerator();
    }
    #endregion

    #region IEnumerable Members
    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return Children.GetEnumerator();
    }
    #endregion
}
...we can then use the Node class to represent its own high-level parse tree:
var compilationUnit = new Node("Node.cs")
{
    new Node("namespace Test")
    {
        new Node("public class Node : IEnumerable<Node>")
        {
            new Node("public IEnumerable<Node> Children")
            {
                new Node("get;")
            },
            new Node("public string Name")
            {
                new Node("get;")
            },
            new Node("public Node(string name);"),
            new Node("public Node Add(string nodeName);"),
            new Node("public Node Add(Node node);"),
            new Node("#region IEnumerable<Node> Members")
            {
                new Node("public IEnumerator<Node> GetEnumerator();"),
            },
            new Node("#region IEnumerable Members")
            {
                new Node("System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator();"),
            },
        },
    },
};
Notice how the Node constructor accepts both regular arguments (in this case, a string representing the node's Name) as well as a list of Node instances? That feature -- collection initializers -- is made available to classes that implement IEnumerable as well as an Add method.

The PreOrder method can then be called on the compilationUnit instance, as follows, due to the extension method feature:
var sequenceOfNodes = compilationUnit.PreOrder(n => n.Children);
The second argument to the method is a lambda expression that, given an instance of Node, returns an IEnumerable<Node>. In other words, it explains to PreOrder how to get a sequence of Node instances given a single Node instance. In our case, it is rather simple, as the Node class has the Children property for that purpose (and it could have been even simpler than that, since Node implements IEnumerable and thus the second parameter could have been written as n => n).

Anyway, calling the PreOrder method looked like it did nothing and it almost did indeed do nothing, which is the point of a generator: until you start pulling on the IEnumerable, no work is performed and no items are generated. All that was done by calling PreOrder was setting up the generator instance in the sequenceOfNodes variable. Let's actually start generating (a.k.a. yielding):
foreach (var node in sequenceOfNodes)
{
    Console.WriteLine(node.Name);
}
...when that loop starts executing, the code in PreOrder kicks in and the first item yielded is the startingPoint, which was initialized in compilationUnit, so its Name is printed to the console. The children of startingPoint are obtained by calling the children functor on startingPoint itself. As you will remember, that's simply the Children property. The process repeats recursively behind the scenes, yielding a node, then its children, while our loop doesn't need to worry about all of that. The loop will end up printing a flat list version of the original tree.

Conclusion (a.k.a. Too long; didn't read)

In 12 lines of code, I made use of the following groovy C# 3.5 compiler features:
  1. Extension methods: extend a closed type with a static method that appears like an instance method
  2. Lambda expressions: inline, anonymous methods that replace private classes that implement an interface AND can operate on local variables
  3. Generators (a.k.a. Iterators): the yield return keyword in methods that return IEnumerable
  4. Implicitly-typed local variables: the var keyword, to avoid repeating yourself

Bonus

If this modest display of mad skillz hasn't convinced you to switch to .NET 3.5, well, you don't even need to! You can compile all this code with the C# 3.5 compiler but still target the .NET 2.0 runtime or even the JVM!

Targetting the .NET 2.0 runtime

Not only can you make use of the new compiler features, you can also make use of the new IDE features, such as call hierarchy and reference highlighting.
  1. Open Visual Studio (this should work in Visual Studio 2008 and 2010)
  2. File > New > Project...
  3. Select .NET Framework 2.0 from the drop-down list on the right:
  4. Create the ExtensionAttribute replacement by adding a file called ExtensionAttribute.cs in your project with the following contents:
    namespace System.Runtime.CompilerServices
    {
       public class ExtensionAttribute : Attribute { }
    }
    
  5. Create a Delegates.cs file that contains the missing Action and Func delegates from the System namespace (you probably only need up to 4 arguments)
  6. Start writing cool code!

Targetting the JVM

This one is more complicated, but the tool you need to download is Mainsoft Grasshopper. You'll need to perform similar additions of missing attribute and delegates as above, but then you should be fine.

Wednesday, April 22, 2009

On uninstalling Google Chrome

I finally gave up with Google Chrome on my laptop. Here's what popped up when I completed the uninstallation process, with my answers:

Google Chrome has been uninstalled.

Thanks for trying out Google Chrome. Please help us improve Google Chrome by telling us why you uninstalled it. Your feedback is much appreciated.

Which of the following best describes you?
I am uninstalling Google Chrome for now, but I may try it again in the future
I am permanently uninstalling Google Chrome
I am only uninstalling briefly. I am going to reinstall straight away (e.g. changing computer, upgrading operating system)

Why are you uninstalling Google Chrome? Please check all that apply
It doesn't load some web pages properly (please list any examples below)
It's missing some features that I use (please provide detail in the box below)
I'm concerned about privacy (please provide detail in the box below)
It seems to slow down my computer
It crashes too often
Other (please provide more details in the text box below)

Please provide any additional detail on your reason for uninstalling:

There are too many Firefox add-ons that I have come to rely on and using Chrome just leaves me "naked" in comparison. I blogged about this potential problem when Chrome initially came out: http://oliiscool.blogspot.com/2008/09/world-in-verdana.html

I first installed Chrome when I heard Gmail and Google Reader had exceptionally good performance in Chrome. This was true, but as soon as I clicked a 3rd-party link from within either, I felt I was abandoned and frequently would end up copy/pasting the URL into Firefox and continue from there.

I definitely appreciate the engineering skills and value of having a process-per-tab kind of browser, but that functionality alone is not sufficient for a heavy add-on user such as myself. In fact, I have checked the "slow down" checkbox since that model seems to in fact be a liability when viewing YouTube videos: I definitely notice much higher CPU usage from Chrome when visiting a site containing an embedded video than visiting the same page with Firefox.

Perhaps not all is lost: the process-per-tab model could still be applied to Firefox and a "Chromium Tab" Firefox add-on that worked similarly to the "IE Tab" add-on (in that it would enable the Webkit/Chromium engine on a per-tab basis) would be fantastic in my books.



So maybe I'll eventually re-install it. There's definitely value in the "application mode" as well, which hides the address bar and makes a "tab" its own window using the site/application's "favico" as the application window's icon, but that breaks quickly - as I described above - when you need to go outside that site/application. That "application mode" would also be a neat add-on/extension for Firefox. :)

Wednesday, September 03, 2008

The world in Verdana

OK, by now everybody and their cat has heard about Google Chrome. The general buzz on Slashdot and blogs seems to be "it's not Firefox" and, more specifically, a general lament of the chicken and egg problem surrounding the release of a new platform when there isn't any software (in this case "plug-ins" or "add-ons") to run on it. Well, OK, there are some Chrome plug-ins available, but Chrome extensions are currently NOT supported. On the other hand, the source code is out there and given that it has the "Google brand", it won't be hard to find motivated geeks hacking some neat software to [eventually] bring Chrome on par with Firefox, with said geeks' hidden agenda of being noticed by Google and be offered a nice googlejob where they get to sit on their googlechair, etc.

It's technically not such a bad chicken-and-egg situation, with the massive and thorough testing Google [claims to] have performed. Plus, the browser is more than a fine replacement for users of Internet Explorer or plain, out-of-the-box Firefox, thus making all us geeks appear crazy when non-techies ask us why we're not using Google Chrome, when we use everything else Google throws at us.

Anyway, I didn't set out to write yet another review, but to post solutions to problems I encountered:

Installing Chrome as a non-administrator


I hit issue 119 ( Install Fails on W2K8 with low-rights user ) when I tried to install on my computer as a non-administrator and got the following:



Thankfully, the work-around by stephen.oakman in comment 6 worked and I found the elusive chrome_installer.exe in a folder matching the pattern C:\Documents and Settings\[user]\Local Settings\Application Data\Google\Update\Download\[guid]\chrome_installer.exe and was able to install it successfully.


Setting the minimum font size


I also had the same accessibility lament about minimum font sizes and font family overrides. For example, here is the Getting Started page in Firefox 2, with Verdana @ 14pt bliss:



...and this is what Chrome gave me with the same page:



OK, yes, the Firefox version looks weird with the title text not lining up with the logo, etc. but all the content is perfectly legible, which is more important to me. Well, more legible than the fonts picked by the web developer.

Thankfully, I have solved the first half the problem with a few quick searches in the source code and now my C:\Documents and Settings\[user]\Local Settings\Application Data\Google\Chrome\User Data\Default\Preferences file contains this little gem:


"webkit": {
"webprefs": {
"cursive_font_family": "Verdana",
"default_fixed_font_size": 14,
"default_font_size": 14,
"fantasy_font_family": "Verdana",
"fixed_font_family": "Courier New",
"minimum_font_size": 14,
"minimum_logical_font_size": 14,
"sansserif_font_family": "Verdana",
"serif_font_family": "Verdana"
}
}



...which gives me a slight improvement in readability in Chrome:



You can find out what the names of the [other] supported hidden preferences are by peeking into chrome/common/pref_names.cc and cross-referencing with WebContents::GetWebkitPrefs() in chrome/browser/web_contents.cc. In particular, you'll find (as of this writing) that the other half of my problem is already identified in a comment:



// User CSS is currently disabled because it crashes chrome. See
// webkit/glue/webpreferences.h for more details.



...with the more details being:



// TODO(tc): User style sheets will not work in chrome because it tries to
// load the style sheet using a request without a frame.
bool user_style_sheet_enabled;
GURL user_style_sheet_location;



D'oh. Maybe this will inspire someone else to fix that part of the code or otherwise provide the elusive "let me choose my own damn fonts" setting that I rely on for keeping my sight and posture in good shape.