Archive for the ‘hackety hack’ Category

Intro to Android Hacking

The excellent Hack A Day is running a series of articles on programming for the Android OS. The first two sections (an intro to the series and a “Hello, World!” walk through) are up already, with more on the way. They are very easy to follow, and give you everything you need to get started with Android development.

It’s definitely shaping up to be a great resource.

Article 0 – Intro

Article 1 – Hello, World

Sugru for You!

Cross-posted from my non-code blog.

Hey, just wanted to post a quick follow up to my post on Sugru. Pete, in comments, points to the fact that it’s now on sale again. I will definitely be getting some. Hackers of all kinds and stripes should hie themselves to the Sugru site and do similarly.

Programmers, Flow, and Productivity

Giles Bowkett has a new video up over at his blog about programmers and flow. I first read Flow when I took a class on the Philosophy of Happiness. It’s interesting stuff and it basically reinforces the notion that people need some sort of challenge in order to be happy. (See also Viktor Frankl’s work on meaning.)

The video’s good, but it takes as given one thing that programmers all take for granted, but that many other people don’t understand: a 5-minute interruption costs us way more than 5-minutes worth of productivity. It’s not simply that talking to someone for 5-minutes is 5-minutes less that we’re working, it’s that (and Giles mentioned this in passing at one point), it completely wrecks our train of thought, our focus, our motivation, our strategy, and our tactic. They all get completely obliterated. Building these back up takes time; often hours of it.

One other thing that he might have done well to mention is the fact that many of our interruptions (or at least mine) are interruptions that I generate myself. I am habitually self-distracting, especially if the work that need to get done is boring.

The video is excellent, though, and highly recommended. It’s a much-watch for anyone who is a programmer, works with programmers, manages programmers, etc.

Sugru

Cross-posted from my non-code blog.

This stuff looks crazy awesome. It’s called Sugru and it’s a moldable, putty-like substance that dries into a high-strength silicone. I love the idea, and I love that it’s being marketed precisely to people who like to hack things. Alas, it’s sold out at the moment, or I’d be buying some right now. I can think of at least a half dozen projects for which this would be perfect. (E.g. custom-fitted, cushy silicone recoil pad!)

Can’t wait for them to get more in stock.

I love that this product explicitly combines two of the things that I think are poised to help revolutionize our culture and our world: the hacker ethos and material science. Now maybe (read: definitely) this is starry-eyed utopianism on my part, but the more people who internalize the idea that they can and should hack their stuff, their world, and themselves, the better. I think that being a hacker speaks to one of the primal elements that makes us human. I think that a far better descriptor for us than “man the wise” (homo sapiens) is “man the hacker” (homo textor? Homo abetor?)

So now combine that hacker spirit with the fact that our fundamental understanding of how materials really work is just starting bear some really cool fruit, and the future begins to look pretty damned awesome. See, we, as a species, moved from the stage of using ambient materials we found around us (flint), to reproducing materials that we first created by serendipity (bronze), to fine-tuning those serendipitous materials (high-carbon steel). But it’s only recently that we’ve gotten to the point where we can actually design materials to achieve the properties we want. Sugru is one such designed material.

So human-designed materials that are explicitly targeted to the hacker soul in each of us. How awesome is that? Rhetorical question. The answer is, of course, “insanely”. Better (non-rhetorical) question: when can I get my hands on some?

Fixing the Motorola Droid Battery Cover

Step 0: Own a Motorola Droid.
Step 1: Get kind of annoyed by the battery cover slipping off at inconvenient times. Be sure not to get so annoyed that you actually take steps to fix the issue.
Step 2: Go drinking with some friends at your local on an idle Thursday night.
Step 3: During a heated game of shuffleboard, accidentally slosh your beer on the pocket where you carry your phone.
Step 4: Swear.
Step 5: Wipe the phone off with a paper towel.
Step 6: Swear some more.
Step 7: Go back to playing shuffleboard.
Step 8: Wake up the next morning, carefully clean the Droid’s screen and keyboard.
Step 9: Notice after a few days that the battery cover is stuck shut with dried beer.

N.B.: I performed the above steps with (I believe) a porter. Not sure what kind. Not sure if the variety of beer matters.

Also, this post is just one man’s method. My phone weathered it fine, but yours might not. This will probably void your warranty. It might destroy your phone. Hell, it might give you scabies or an unhealthy obsession with the Beta Band.

Whatever happens, you undertake the above steps at your own risk. I make no promises, guarantees, avowals, or assertions as to the safety and efficacy of the above method. If you mess up your phone, it’s on your head.

I will, however, say that my battery cover still stays in place quite nicely.

Stupid C# Tricks: Ghetto Eval

Alternate Title: An Incredibly Simple Introduction to C# Metaprogramming

The eval method is a staple of scripting languages.  It takes a string and executes it as code.  This is useful when, e.g., you need to modify the value of one of several text fields on a page.  The name of the text field can be dynamically passed into the eval argument.

So C#, being a compiled language, doesn’t have an eval method. What it does have, however, is great support for programmatic compilation of code. This can be used to hack together something that’s kind of like an eval. Take, for instance, the following method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
        public static void FauxEval(string codeToEval)
        {
            //Create compiler objects
            CSharpCodeProvider Compiler = new CSharpCodeProvider();
            CompilerParameters Params = new CompilerParameters();
            CompilerResults Results;
 
            Params.GenerateExecutable = true;
            Params.OutputAssembly = "eval.exe";
 
            //We could check this Results object, but this is naught but an example
            Results = Compiler.CompileAssemblyFromSource(Params, codeToEval);
 
            //Execute the eval-ed code
            Process evalledExecutable = new Process();
            evalledExecutable.StartInfo.FileName = "eval.exe";
            evalledExecutable.Start();
            evalledExecutable.WaitForExit();
        }

This method takes the C# source of an executable as its argument. It compiles the source and executes it. Now this is kind of like an eval. It’s more structured than that found in a scripting language, since it can only eval code that compiles into a valid C# program. The heavy lifting is done by the CSharpCodeProvider class, which handles the compilation of the source. This class also contains a lot of handy methods to generate code from various CodeDOM objects, making it your one-stop shop for C# metaprogramming. (N.B. There’s a comparable class for Visual Basic called VBCodeProvider. This is exceptionally handy if, for whatever reason, you want to use C# to emit Visual Basic code.)

So the above FauxEval method can be used simply by assembling a string that will compile into an executable. The strength of eval-like methods, of course, is that this string can be constructed dynamically at run time. As a completely trivial example, here’s a program that uses the above eval to generate a Hello World-like program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
 
        static void Main(string[] args)
        {
            string programMessage = "Hello, world!";
            if (args.Length > 0)
            {
                programMessage = args[0];
            }
            string programCode = "";
            programCode += "using System;";
            programCode += "using System.Text;";
            programCode += "namespace GeneratedCode";
            programCode += "{";
            programCode += "class GeneratedProgram";
            programCode += "{";
            programCode += "static void Main(string[] args)";
            programCode += "{";
            programCode += "Console.WriteLine(\"" + programMessage + "\");";
            programCode += "Console.WriteLine(\"Press any key to continue...\");";
            programCode += "Console.ReadKey(true);";
            programCode += "}";
            programCode += "}";
            programCode += "}";
 
            FauxEval(programCode);
        }

The generated program will simply print the first command line argument to the console. If no argument is provided, the executable is built to be a default “Hello, World”.

The results:


(Click to embiggen)

So that’s a super-simple C# eval. This provides the ability to execute code that’s been dynamically created at run time, provided the code can be compiled into an executable. There’s a lot of room to expand on the method and make it more flexible and general, but there really is only so much you can do with this strategy of code evaluation, since the code always has to be able to be compiled into an assembly. Still, it’s a damn sight better than nothing.

Update 2010.3.30: I removed some random debugging code from the Eval method above. It was a classic case of YAGNI. I thought I might want to dump eval string contents to a file. I ended up not needing to, but then forgot to pull the debugging code.

Stupid C# Tricks – Sealed Classes

So as platform-driven languages go, C# isn’t a bad one.  We’ve had some good times together, and I’m rather fond of the bloated, lumbering behemoth.  But there are a few things about it which drive me absolutely insane.  One of these is sealed classes.

Now the conventional wisdom is that sealing classes improves performance and security.  First of all, if a sealed class increases performance (which it doesn’t in all cases), then those gains are absolutely negligible.  Relying on sealed classes to get your app to meet benchmark requirements is a little like entering a horse in the Kentucky Derby, and then relying on giving him a good shave to make him win.  Even if the minor weight loss DOES make him a bit faster, it’s not going to be enough to win.  Plus now you have an angry, naked horse on your hands.

Okay, so that analogy went kind of a weird place.  But I hope my point is clear: sealed classes don’t provide good enough performance boosts to really make a difference.  If the kind of operation-shaving that sealed classes sometimes result in is really your last resort for optimization, then you may have a bigger problem on your hands than you think.

As for the security argument, well, I just don’t buy it.  It seems that people think that a lack of inheritance is somehow a security feature, but I just don’t see how.  If not allowing your C# code to be overridden or reused by other people is really key to your “security” methodology, then you better hope that none of your customers are smart enough to use Reflector.  I mean, this security argument is really so stupid that I can’t help but think that I must be constructing a straw man.  Alas, a quick Google search seems to indicate that sealing classes is widely understood to be “good security.”

Of course, none of this would be that bad if it was just a smattering of C# developers who went around sealing their classes.  The problem is that a lot of very useful classes in the platform itself are sealed.  I recently found another such class when I tried to override the Console class.  Apparently the C# team at Microsoft has decided that no one will ever need, want, or get to override Console.  Which would be fine, except that I both needed and wanted to override Console.

Why, you ask?  Well, to be fair, it was for a gonzo code joke that probably would have amused only me.  But the fact of the matter is, I won’t get a chance to find out if it’s as funny as I thought it would be, because .NET won’t let me override the Console class.

So that’s the rant.  Sealing classes is both useless and annoying, doubly so when it’s done to basic platform classes.  What’s more, I’ve not seen a single good argument in defense of the practice.

Though just watch, a few weeks from now, we’ll see someone flogging sealed classes on the grounds that it protects the world from dubiously funny jokes by bored twenty-somethings.

Truth

Click for bigger. Source unknown; if anyone knows, please leave a comment.

Throw-Away Apps FTW!

So one of the greatest things about being a hacker is that one has a ready answer to idle thoughts of “I wish my computer did X…” You simply code up a way for it to do what you want. It’s especially nice when what you want it to do is actually rather simple, but just something that no one’s thought to implement yet. (This is all, of course, assuming that Google failed to turn up a good existing solution. Reinventing the wheel makes baby Edsger Dijkstra cry.)

Case in point: on a couple of recent occasions, I’ve thought it’d be nice if I had a way to quickly dump a timestamp to my windows clipboard so that I could drop it into documents. Well, after ten minutes of hacking and a little bit of thrashing at OS integration, I have exactly that.

Basically I wrote a lightweight C# console app that optionally takes a DateTime format string as an argument and does nothing but push a current timestamp to the clipboard. (It applies the format string if provided, otherwise it just uses default formatting.) I put the executable in an easy-to-remember path (C:\TimeToClipboard\). I then added keys to some of the shell registry entries to add the application (called with my preferred timestamp format) to filesystem context menus.

The application code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using System;
using System.Windows.Forms;
 
namespace TimeToClipboard
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                Clipboard.SetText(DateTime.Now.ToString(args[0]));
            }
            else
            {
                Clipboard.SetText(DateTime.Now.ToString());
            }
        }
    }
}

The registry entries:

Keys: HKey_Classes_Root/*/shell/Get Timestamp/command
HKey_Classes_Root/Drive/shell/Get Timestamp/command
HKey_Classes_Root/Folder/shell/Get Timestamp/command

Value: c:\TimeToClipboard\TimeToClipboard.exe “yyyy.M.d H:mm:ss”

This worked pretty well, but I couldn’t figure out a way to add the Get Timestamp context menu item to the desktop context menu. I was hoping that * really meant “add to all context menus”, but it in Microsoft world, it apparently means “add it to an unspecified subset of context menus.” Not very helpful.

So my next idea for easy access was a keyboard shortcut. I added a shortcut to the TimeToClipboard application to my desktop and bound it to the Ctrl+Alt+T keyboard combination. This works well, and works no matter what application has keyboard focus. So no matter what I’m doing, I’m never more than three keystrokes away from having a timestamp.

World changing? Hardly. But convenient. Plus the whole thing took me less than an hour to bash together and get setup, and most of that time was googling around for the names of registry keys.

CSS Hackery

Getting some CSS help from my friend Chris. This is just a test. Please ignore.

1
2
3
4
5
6
7
8
if(thisWorks)
{
    return "I'm impressed";
}
else
{
    return "OH SHIT GUYS, DIDN'T WORK!";
}

(Also, sorry for the weirdness of the code samples the past few days. I think we have the problems ironed out now. Just beating a new WP plugin into submission. Nothing to see here.)

Return top

Shut Up and Hack

This is a blog where I talk about hacking, code, software, and the philosophy of making things. It's basically just another craft blog. Whatever your project or passion is in life, it is more important than this. So thank you very much for reading, but please, when you're done here, go make something awesome.