DaedTech

Stories about Software

By

Dell Keyboard Failure

The Symptoms

This is yet another entry of the “hope this saves someone time and aggravation” variety. I’m adding a new category called “Lessons Learned” that I’ll be tagging these with going forward.

So, I was playing Civilization V and I stepped away for a few minutes to find the screensaver on when I came back. I moved the mouse and nothing. Enter key and nothing. Ctrl-Alt-Delete, nothing. Several minutes of angrily mashing my keyboard and, not surprisingly, nothing. Given the graphics-heavy nature of Civ V, I assumed that my machine had crashed (this happens sometimes with Civ V), so I rebooted.

When I did that, I was greeted by the image above. So, I figured my wireless keyboard had run out of batteries and I went all the way down to the basement, grumbling, got new triple As and slapped them in. Rebooted, and keyboard failure. Tried a different USB port and keyboard failure. Tried my keyboard in another machine and success! Uh, oh. To the interwebs!

After googling around, I didn’t find any definitive solution. There were some scorched Earth suggestions, my favorite of which was “replace the motherboard”. There were some shotgun suggestions involving running without a CMOS battery, bending USB pins, switching the wireless receiver around from port to port, and various other procedural mumbo-jumbo that had probably coincidentally worked for someone somehow.

The Solution

I got lucky, though. The first scattershot step I took seemed the simplest, and it worked, so I know exactly what worked. I powered down and disconnected from power, and then popped a two pin jumper off of a three pin block on the motherboard for a few seconds and replaced it. Viola!

Appropriate disclaimers about unplugging and discharging capacitors and all that other stuff that I never remember to do but wouldn’t want somehow to be liable for you not doing it. But, that did the trick. Back up and running with no new keyboard, and certainly no new motherboard. Excuse to buy a new machine averted… (d’oh!)

By

Compiling XML! (Not really)

So, here’s another one filed in the “hope this saves someone some grief” category. I was cruising along with my home automation ‘droid app, setting my layouts and wiring up my button click handlers, when all of a sudden, I was getting weird build errors about. I couldn’t run or even build. When I tried to build, I got messages about different things being redefined in my main XML layout file. This was strange, since I hadn’t edited it directly, but was using the graphical layout tool.

As I inspected the errors more closely, I began to understand that there was apparently some rogue XML somewhere. A bug in Eclipse? With the Android SDK plugin? Had I been hacked by someone with a very strange set of motives? I opened up my layout folder and this is what I saw:

Wat?

After some googling around and experimentation, I discovered that this file is generated if you run with the Play icon and the XML file open as your selected window in the editor. Perhaps that’s something that Eclipse users are used to, but coming from a pretty solid couple of years of Visual Studio, this had me mystified. So, lesson learned. Don’t run if you have XML open in Eclipse (or anything else you don’t want slapped with a .out between filename and extension and apparently included in compilation.

Cheers 🙂

By

Android: Let There Be Internet!

I’ve been a little lax in documenting my experience as a neophyte Android developer, and for that I apologize. Tonight, I have a quick entry that will hopefully save you some time.

I’m working on an open source home automation server. I’ve had a prototype functional for a couple of years now that runs as a web server in apache, Java-based, and controls the lights through a web interface front end and a low level backend that interfaces with the house’s electrical system. I control this through any computer/phone/ipod/wii/etc that’s hooked to my home wifi, using the browser.

Recently, I’ve wet my beak a little with Android development, out of curiosity, and so my mission tonight was to take the layout I’d been working on and get it to, you know, actually do something. So, the simplest thing for me to do was have the app reproduce the POST request sent by the browsers to get the desired result. Here is the code I slapped together for this:

final Button myButton = (Button) findViewById(R.id.breakfastNookButton);
        myButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	
            	HttpClient myClient = new DefaultHttpClient();
                HttpPost myPost = new HttpPost("you-get-the-idea");

                try {
                	myClient.execute(myPost);                  

                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

Not the prettiest thing I’ve ever written, but this is a throw-away prototype to prove the concept (though I’m going to refactor tomorrow – I can’t help myself, prototype or not).

So, I fired it up and nothing happened. I checked out the stack trace and was getting an UnknownHostExeption, which didn’t make sense to me, since I was using the home automation server’s IP address. I used the browser on my phone, and I could turn the light off. I googled around a bit and found a bunch of information about things that can go wrong with the emulator, but I’m debugging right on my phone since the Emulator is painfully slow.

Finally, I stumbled across a suggestion and got it right through some experimentation. I needed to give the app permission to use the internet! So, I updated my manifest to the following:



     
    
...

Important line is the “uses-permissions” node, and, viola, let there be dark! My light turned off. Hope that helps someone out there struggling to understand the UnknownHostException for a known host.

(Note, the node level in the XML file is important — it must be a child of manifest, NOT application).

By

Poor Man’s Code Contracts

What’s Wrong with Code Contracts?!?

Let me start out by saying that I really see nothing wrong with code contracts, and what I’m offering is not intended as any kind of replacement for them in the slightest. Rather, I’m offering a solution for a situation where contracts are not available to you. This might occur for any number of reasons:

  1. You don’t know how to use them and don’t have time to learn.
  2. You’re working on a legacy code base and aren’t able to retrofit wholesale or gradually.
  3. You don’t have approval to use them in a project to which you’re contributing.

Let’s just assume that one of these, or some other consideration I hadn’t thought of is true.

The Problem

If you’re coding defensively and diligent about enforcing preconditions, you probably have a lot of code like this:

public void DoSomething(Foo foo, Bar, bar)
{
  if(foo == null)
  {
    throw new ArgumentNullException("foo");
  }
  if(bar == null)
  {
    throw new ArgumentException("bar");
  }

  //Finally, get down to business...
}

With code contracts, you can compact that guard code and make things more readable:

public void DoSomething(Foo foo, Bar, bar)
{
  Contract.Requires(foo != null);
  Contract.Requires(bar != null);

  //Finally, get down to business...
}

I won’t go into much more detail here — I’ve blogged about code contracts in the past.

But, if you don’t have access to code contracts, you can achieve the same thing, with even more concise syntax.

public void DoSomething(Foo foo, Bar, bar)
{
  _Validator.VerifyParamsNonNull(foo, bar);

  //Finally, get down to business...
}

The Mechanism

This is actually pretty simple in concept, but it’s something that I’ve found myself using routinely. Here is an example of what the “Validator” class looks like in one of my code bases:

    public class InvariantValidator : IInvariantValidator
    {
        /// Verify a (reference) method parameter as non-null
        /// The parameter in question
        /// Optional message to go along with the thrown exception
        public virtual void VerifyNonNull(T argument, string message = "Invalid Argument") where T : class
        {
            if (argument == null)
            {
                throw new ArgumentNullException("argument", message);
            }
        }

        /// Verify a parameters list of objects
        /// 
        public virtual void VerifyParamsNonNull(params object[] arguments)
        {
            VerifyNonNull(arguments);

            foreach (object myParameter in arguments)
            {
                VerifyNonNull(myParameter);
            }
        }

        /// Verify that a string is not null or empty
        /// String to check
        /// Optional parameter for exception message
        public virtual void VerifyNotNullOrEmpty(string target, string message = "String cannot be null or empty.")
        {
            if (string.IsNullOrEmpty(target))
            {
                throw new InvalidOperationException(message);
            }
        }
    }

Pretty simple, huh? So simple that you might consider not bothering, except…

Except that for me, personally, anything that saves lines of code, repeat typing, and cyclomatic complexity is good. I’m very meticulous about that. Think of every place in your code base that you have an if(foo == null) throw paradigm, and add one to a cyclomatic complexity calculator. This is order O(n) on the number of methods in your code base. Contrast that to 1 in this code base. Not O(1), but actually 1.

I also find that this makes my methods substantially more readable at a glance, partitioning the method effectively into guard code and what you actually want to do. The vast majority of the time, you don’t care about the guard code, and don’t really have to think about it in this case. It doesn’t occupy your thought briefly as you figure out where the actual guts of the method are. You’re used to seeing a precondition/invariant one-liner at the start of a method, and you immediately skip it unless it’s the source of your issue, in which case you inspect it.

I find that streamlined contexting to be valuable. There’s a clear place for the guard code and a clear place for the business logic, and I’m used to seeing them separated.

Cross-Cutting Concerns

Everything I said above is true of Code Contracts as well as my knock off. Some time back, I did some research on Code Contracts and during the course of that project, we devised a way to have Code Contracts behave differently in debug mode (throwing exceptions) than in release mode (supplying sensible defaults). This was part of an experimental effort to wrap simple C# classes and create versions that the “no throw guarantee”.

But, Code Contracts work with explicit static method calls. With this interface validator, I can use an IoC container define run-time configurable, cross cutting behavior on precondition/invariant violations. That creates a powerful paradigm where, in some cases, I can throw exceptions, in other cases, I can log and throw, or in still other cases, I can do something crazy like pop up message boxes. The particulars don’t matter so much as the ability to plug in a behavior at configuration time and have it cross-cut throughout the application. (Note, this is only possible if you make your Validator an injectable dependency).

Final Thoughts

So, I thought that was worth sharing. It’s simple — perhaps so simple as to be obvious — but I’ve gotten a lot of mileage out of it in scenarios where I couldn’t use contracts, and sometimes I find myself even preferring it. There’s no learning curve, so other people don’t look at it and say things like “where do I download Code Contracts” or “what does this attribute mean?” And, it’s easy to fully customize. Of course, this does nothing about enforcing instance level invariants, and to get the rich experience of code contracts, you’d at the very least need to define some kind of method that accepted a delegate type for evaluation, but this is, again, not intended to replace contracts.

Just another tool for your arsenal, if you want it.

By

Scheduled Task Problems And Solutions in Windows 7

This is going here for my own sake as much as anything. I’ve been banging my head against a wall for a bit now, trying to figure out why I can’t get a scheduled task to run properly in Windows 7. Two things were going wrong. The first one was that I couldn’t get the start-in setting to work properly. This is neatly explained and addressed in this post.

Long story short, unlike everywhere else in Windows, the “start-in” text box randomly doesn’t demand or even support quotes around directory names with spaces in the paths. So, just remove the spaces.

Second issue I was having was that I was running a task to execute a program I had written that reads an XML config file to point it to files to use. One of these files was addressed by a mapped network drive. This worked fine when I ran the actual executable, but after a lot of bad noise and experimenting, I discovered that it wouldn’t work with the scheduled task. For the scheduled task, I had to use the UNC path to the file in my XML configuration file. I can only speculate that this has something to do with the scheduler not being tightly coupled enough to owning user to share network drives or something.

In the end, doesn’t matter. It’s kind of weird, but for anyone who finds themselves in that edge-case situation, try dealing with UNC exclusively.