2014-09-24

More MVC and JSON.Net - Exceptions

In my last episode with MVC, I was trying to reconcile MVC 5.0 with WebAPI 5.1 and the fact that the former used a broken JSON library, while the latter used the better Newtonsoft JSON library. I implemented a model binder and a value provider factory to get the two projects in sync, and all was right with the world.

As the project has gone on, we've come across instances where we've needed to call MVC controllers and get JSON responses back. We have created WebAPI controllers in some cases, but the way the project is structured, we've needed to post MVC models as JSON via AJAX back to MVC methods where we cannot reference them in the WebAPI project (otherwise we'd have a circular reference).

There are probably a few ways to restructure this to work. Ripping the view models out to a library that can be referenced by both MVC and WebAPI was one idea, for instance. But that would've been a lot of work and caused bigger deployment headaches that I don't want to get into here. (A smaller project might've gotten away with it, though.)

Returning JSON to the client is almost as easy as having your MVC controller return a JsonResult — the MVC Controller class has its own built-in Json() method to do just that. Except, of course, it uses the JSON serializer we never want to see again. In this case, I created my own JsonNetResult class (based on a StackOverflow question, naturally), and my controller just calls this.JsonNetResult(resultObj); to do the magic.

The remaining issue, though, is when it came to exceptions. While WebAPI, on a JSON request, returns an error response formatted in JSON (that jQuery's ajax method parses easily), MVC gives you that nice, big, friendly "yellow screen of death" with the error formatted in HTML (or a generic message when you get to production). Not too useful when you want your JavaScript to report back some detail about what went wrong.

The solution, here, was to use an exception filter. The JsonNetExceptionFilter class checks to see if the incoming request was specified as JSON (using very similar code to the model binder), and if so, it handles the error on its own. We were throwing HTTP error messages using two different types of objects, depending on whether the code was copied from WebAPI or MVC (since they each have their own namespaces for this kind of thing). I check for these types so that I can set the response code to something besides the default 500 (400 Bad Request is used quite a bit), and I set the content to a JsonNetResult object with the data being a message formatted in something similar to the WebAPI format (and thus parsed by the same JavaScript code).

I considered leaving it here, so that we would have to decorate every JSON method with this handler as well as specifying it returned a JsonNetResult (unless there's a way to find out programmatically in the filter whether the current controller method returns a JsonNetResult, but I failed to find that); but ultimately, I decided to just override the default error handler site-wide (since it falls back to the base class for non-JSON requests, it shouldn't be an issue). That was done by editing the MVC app's RegisterGlobalFilters method to read:

filters.add(new JsonNetExceptionFilter());

Now, whenever we want to return an exception back to a JSON request, all we have to do is throw an exception:

throw new System.Web.HttpException((int)System.Net. HttpStatusCode.BadRequest, "Bad request data.");

Processing the return message in jQuery is left as an exercise to the reader (though if you use WebAPI, you probably already know). ;)

2014-08-11

How is escrow not a scam?

The concept of "escrow" already annoys me. As a requirement for my mortgage, I have to put aside money to pay for my homeowners insurance and property taxes, into a special account managed by the mortgage company, plus some extra depending on the mortgage company's demands. I can understand why they have a vested interest in making sure these things get paid, since technically they do own the house; but it seems it operates under the assumption that I would not take responsibility for these payments, and it gives me no opportunity to prove otherwise. Instead, the mortgage company gets to take the money and earn the interest, or dividends on the investments, and I have to just trust that they will make the tax and insurance payments (that I am responsible for) on time.

(To their credit, I have not yet had a mortgage company fail to pay either of these things on time.)

But recent events make me even more ticked off at the whole racket. I have a homeowners insurance claim in progress for storm damage (nothing too serious, mostly hail damage on the roof; we had the same thing five years ago). If the check is over a certain amount, the insurance company makes the check out to us and the mortgage company, requiring endorsement from all parties before the money can be used. I don't fully understand this. The insurance policy is a contract I have entered into with the insurance company. The mortgage company did not co-sign or endorse this contract, outside of requiring me to have a contract that meets whatever minimum requirements they had to allow me to get the mortgage. The mortgage company does not put any money into this contract — while they do make the payment of funds every year, they do so out of money they took from me. So why should they have a claim to the money on the insurance policy I paid for?

Still, before now, it was just a hurdle I had to jump before I could start repairing my home.

This time around, it's worse. Because the insurance payment was over a specific amount, my mortgage company demands I endorse the check and send it to them, and they will deposit it in a separate escrow account, and only give me money from it when I turn in receipts for repairs.

This is ridiculous. For one thing, it means I will be paying money out of pocket first. I don't have thousands of dollars sitting around that I can "float", paying for the repairs and waiting for the mortgage company to validate the receipts and give me my money back. That's the reason I have an insurance policy, so I don't have to pay out of pocket for catastrophes. For another, if my insurance company overestimated the damage amount, or if I am able to find a contractor willing to make the repairs for much less than the amount the insurance company gave me, how do I get that money when I don't have a big receipt to cover it? (The fact that the insurance company may have overpaid me is a discussion between me and them alone, since we are the ones that hold that contract.)

And this is just on top of my initial annoyance with escrow, that I'm not able to so much as put that money in an interest-bearing account to make a lousy 1‰ until I get the repairs done.

Of course, the answer is going to be so that they know that damage to their property is repaired, because otherwise the value of their property will be lessened by my negligence, while I could pocket the money and run. Still, this should be something I should prove first, let them sue me for negligence later. I get weary fast of having to pay for someone else's mistakes, and it seems like that's what is happing now: because irresponsible people exist, I cannot be trusted to do the right thing.

2014-07-27

Attraction doesn't always mean action

So here's a really interesting story. It's a hard one to read or listen to, because it involves something that, I'd wager, most of us would rather not think about. It's about a young man who discovered he was sexually attracted to children, and how he's been struggling with this attraction all his life. A big part of his struggle is that pedophilia is something for which it is very difficult to get help. As the article states: "…they have no way to talk about these urges or how to prevent them from taking control of their lives without being considered a threat. Talk to a shrink? You risk being reported to the authorities. The scientific community is so afraid of the stigma attached to even researching pedophilia that it's barely been studied it at all." Which is why this young man has risked tarring and feathering to set up support groups, to help people who need help taking control of their lives instead of letting their urges define and control them. It's actually a pretty inspirational story about taking control and standing up for what's right, even when the wrongness is coming from your own self.

Now, here's where I'm about to get very unpopular.

Take that same story, but replace all references to sexual attraction to children, with sexual attraction to members of the same sex.

Suddenly, it goes from a story of inspiration and self-control to one worthy of derision because of its support of self-denial and giving in to homophobia.

I've seen many arguments that saying "anti-gay" is wrong because people can't change who they are, and they should be free to act on their feelings. It's the whole crux of the argument for allowing same-sex marriage: preventing discrimination based on what a person is. Yet if we were to apply the same logic to other sexual attractions that are (still) considered bad — pedophilia, bestiality, necrophilia, take your pick — we would be immediately shot down for trying to support the "sick" or "depraved" (if we weren't immediately shot for merely insinuating any kind of relationship between homosexuality and pedophilia).

So what's the difference? Attraction to children is something that, as a society, we all seem to agree is wrong — so it's ok to have laws against it and to not even think about granting legal protections and rights to those forms of relationships. And yet, it wasn't until just the past few years that the same could be said for same-sex attraction. Debate or blame whomever you wish for the existence of California's famous Proposition 8, but the fact that it passed means there was a significant number of people who, less than a decade ago, supported the idea that condoning same-sex attraction was wrong.

So, why? Why is this form of sexual attraction ok, and others aren't? What makes same-sex attraction part of a person's being, but underage attraction something that a person can and should suppress and live their lives in denial of? And what form of sexual attraction that we think is wrong today, will we be forced to bake cakes in celebration of ten years from now?

2014-07-17

MVC, JSON, and DateTime (oh my)

It's been a while since I've had a programming issue that warrants a blog post, but here's an interesting one.
First, let me set up the situation. I have an MVC project (MVC version 5.0) that communicates to RESTful services using WebAPI (version 5.1). In one particular view, I write out an object in JSON with the intent that the client can make changes to it and POST it back to an MVC action to get an HTML table back. Here's the model:

public class PaymentScheduleRequestModel {
[JsonProperty(PropertyName = "effDt", NullValueHandling = NullValueHandling.Ignore)]
public DateTime EffectiveDate { get; set; }

[JsonProperty(PropertyName = "termId", NullValueHandling = NullValueHandling.Ignore)]
public Nullable<int> ContractTermId { get; set; }

[JsonProperty(PropertyName = "billDay", NullValueHandling = NullValueHandling.Ignore)]
public int BillingDayOfMonth { get; set; }

[JsonProperty(PropertyName = "freq", NullValueHandling = NullValueHandling.Ignore)]
public PaymentScheduleFrequencyId PaymentScheduleFrequencyId { get; set; }

[JsonProperty(PropertyName = "prem", NullValueHandling = NullValueHandling.Ignore)]
public decimal TotalPremium { get; set; }
}

(Note that the JsonProperty decorators exist because the same model is used to communicate to the WebAPI service -- we are using shorter property names to lighten the payload.)

And the MVC action that is set up to process it looks like this:

[HttpPost] public async Task<ActionResult> NewPaymentSchedule(PaymentScheduleRequestModel request) { … }

To put it in JavaScript, the view has this block of code:

window.ScriptModel = @Html.Raw(Json.Encode(new {
PaymentScheduleUrl = Url.Action("NewPaymentSchedule", "Contract"),
PaymentScheduleRequestModel = new PaymentScheduleRequestModel {
ContractTermId = Model.ContractTermId,
EffectiveDate = Model.StartDate ?? DateTime.Now,
TotalPremium = 200m
}
}));

Unfortunately, Json.Encode doesn't work well with dates. This is the output that the browser sees (with line breaks added for legibility):

window.ScriptModel={
"PaymentScheduleUrl":"/Contract/NewPaymentSchedule",
"PaymentScheduleRequestModel":{
"EffectiveDate":"\/Date(1078729200000)\/",
"ContractTermId":null,
"BillingDayOfMonth":0,
"PaymentScheduleFrequencyId":0,
"TotalPremium":200
}
};

Notice two things about System.Web.Helpers.Json.Encode's output:

  1. The property names are the .Net property names. The same code could not be used to post what should be the same model to MVC or to WebAPI.
  2. The EffectiveDate field has been converted to a Date function, enclosed in a string. Even if the Date function would reveal the correct value, the fact that it's in a string means JavaScript will not see it as a Date.

If I don't do anything with this object and just post it back to the MVC app, the resulting object does not have a valid date — all other values carry over, but the EffectiveDate property is 01/01/0001. So not only does it look odd, not only is it inconvenient in that JavaScript can't use it as-is (without picking apart the string), but it doesn't even work for round-tripping data to and from the client.

In doing some research on this topic, I came across Scott Hanselman's blog post describing the problem, and stating that the release of WebAPI won't have the issue since it will use JSON.Net (a.k.a. Newtonsoft.Json). Since I'm using the same model in an WebAPI call further downstream, I can verify that it does work as intended. It uses the JsonProperty decorators to rename the properties, and it serializes and deserializes like magic.

To solve this problem in MVC, you have to alter how it deals with JSON on the way out and on the way in.

On the way out is easy in my case, since I am manually spitting out JSON into the HTML. I just exchanged Json.Encode with Newtonsoft's serializer:

window.ScriptModel = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(new {
PaymentScheduleUrl = Url.Action("NewPaymentSchedule", "Contract"),
PaymentScheduleRequestModel = new PaymentScheduleRequestModel {
ContractTermId = Model.ContractTermId,
EffectiveDate = Model.StartDate ?? DateTime.Now,
TotalPremium = 200m
}
}));

And the browser sees:

window.ScriptModel={
"PaymentScheduleUrl":"/Contract/NewPaymentSchedule",
"PaymentScheduleRequestModel":{
"effDt":"2004-03-08T00:00:00",
"billDay":0,
"freq":0,
"prem":200
}
};

This is better. Of course, the controller action doesn't understand this. It's still looking for the .Net property names, and, since they don't exist on the incoming object, all values come back empty. (In this simple example, not only is EffectiveDate 01/01/0001, but TotalPremium is 0.0.)

The trick here is to override MVC's default model binder, so that it, too, uses the Newtonsoft.Json library. It is also consistent to have MVC use a value provider factory that also uses JSON.Net.

Fortunately, people smarter than I figured out these two steps. I found a value provider factory on this blog: http://www.dalsoft.co.uk/blog/index.php/2012/01/10/asp-net-mvc-3-improved-jsonvalueproviderfactory-using-json-net/
and the important piece, the model binder, that will translate the JSON property names to their real .Net names, is detailed here: http://stackoverflow.com/questions/4164114/posting-json-data-to-asp-net-mvc

My implementation looks like this:

And this code gets called from Application_Start (I actually added it to my WebApiConfig class (which, for some reason, exists in my MVC app even though it's obviously not the same as WebAPI), since other configuration-type things were being done here):

ValueProviderFactories.Factories.Remove(ValueProviderFactories.Factories.OfType<JsonValueProviderFactory>().FirstOrDefault());
ValueProviderFactories.Factories.Add(new JsonDotNetValueProviderFactory());

ModelBinders.Binders.DefaultBinder = new JsonDotNetDefaultModelBinder();

All this because, although Microsoft updated one of their web interfaces (WebAPI) to use the JSON.Net library that works, another one of their interfaces (MVC) uses their own, broken, JSON serialization library.

2014-04-30

Consequences of free speech

A lot has been made recently of Los Angeles Clippers' owner Donald Sterling, being caught on tape saying some pretty racist things, bad enough for the NBA to ban him for life, fine him $2½ million, and force him to sell his team. From what I've heard, this result seems like a net positive for society as a whole, but how this whole thing has come about makes me very worried for the direction this country is headed.

According to the reports I've been reading, Sterling is not a very nice guy. Some say he has a long history of being racist. By the sound of things, the NBA will be better off without him. And yet, the NAACP gave him an award back in 2009 because (at least in part) he gave away a lot of tickets. The more cynical reports suggest he was given this award, with his racism overlooked, because he gave money to the right people. He was, in fact, due to receive another award this year from the NAACP, before recent events made the organization reconsider.

But what were the "recent events"? Did he use his power as an owner in real estate to deny housing to blacks or hispanics? Did he make an employment decision based on race? No, that was years ago (before, during, and after the NAACP was giving him his first lifetime achievement award). It happened because his girlfriend recorded a private conversation, coaxed him to say what he did, and sold the tape to the online tabloid TMZ.

I've read conflicting comments as to whether or not Sterling knew he was being recorded, but those that care to mention the girlfriend seem to agree that she really worked on Sterling to get him to make his damaging statements, leading him to say what he did and really dragging it out of him. Of course that brings a lot of rumor and speculation about how much, and from whom, she was getting paid to do this, and whether or not it was illegal (most likely if Sterling didn't know the tape was rolling).

Kareem Abdul-Jabbar wrote an excellent opinion of the issue for Time, which echoes a lot of the comments I've heard that led me to my conclusion above. It also comes to pretty much the same end — Sterling's eviction from the NBA is a good thing and long overdue, but how it happened is very, very wrong.

The big question, of course, is, did Sterling deserve his NBA exile, fine, and loss of ownership of his team for what he said? Maybe his speech just served to bring about awareness of what he was actually doing, but because he only got punished when he expressed his views in the privacy of his own home, it certainly looks like that's his sin. He said something that was unpopular, and now he must pay.

It is true that "freedom of speech" does not make you free of consequences. If you say something that someone doesn't like, that person is just as entitled to use their own freedom of speech to speak out against you, exercise their freedom of association to refuse to do business with you, and even freely encourage others to avoid you as well. But why does it seem like it's only the speech — or even the perceived interpretation of speech — that deserves to be punished, when actions can go unnoticed or be forgiven?

We've been sliding down this slope for a while. Paula Deen was condemned for using a racial slur in the past (including in a description of someone who had a gun to her head), despite having apparently changed her ways since. Phil Robertson lost his place on the show Duck Dynasty for daring to honestly answer an interview question asking what he considered a sin (only to be reinstated after enough public support). Brendan Eich found he was unable to do his new job as Netscape CEO due to all the protests that, six years prior, he gave a paltry (for him) sum for California Proposition 8 — a view that, even though is becoming less so now, was the popular view at the time (Prop 8 passed) and, at the time, was even supported by presidential candidate Barack Obama. Cliven Bundy was supported by many in the (mostly right-wing) media, before he expressed his political opinion that came off as racist (though that might be less actual racism and more poor word choice and selective editing by the media, depending on your point of view).

So now, it's not just what you say in public. It's not even what you said in public in the past, whether or not you've recanted since. But what you say in private, behind closed doors, can and will be used against you in the court of public opinion; and if your opinion goes against the prevailing wisdom, whichever way it happens to be blowing at the time, then God help you.

2014-03-13

My New Year's Resolutions

I try to avoid making New Year's Resolutions. They tend to be some big life-changing or life-enhancing promises that start with really good intentions, and then fall flat within a month or two. Personally, I just can't see myself deciding to completely change my habits or lifestyle overnight. But this year, I decided there were a couple things I could do better. They aren't major issues, but at least it's something I can do and accomplish and feel like I've done something to improve.

The first is a bit of housekeeping. Our HVAC system has stainless steel air filters (rather than cheap cardboard-framed filters), and they are supposed to be cleaned out periodically. Historically, I've been very bad at cleaning those filters, going way back to when we first had the system installed. I remember cleaning them one day and then being very surprised that I actually saw curtains moving in the breeze from the air vents. Our house also tends to be very dusty, which I don't doubt is at least partially the fault of the HVAC's inability to move air through the completely clogged filters. So, I resolved this year to incorporate into my Sunday routine, cleaning out those air filters.

For the month of January, I did manage to clean the filters out every week. At least in those first couple weeks, it really needed it, as the filters were pretty well coated when I pulled them out. But by the time I got to February, the filters were still pretty clear when I went to clean them. So, I've backed off a bit on my initial resolution, instead cleaning the filters out every other week. Even then, they're not catching nearly as much dust as they were, so I feel that I'm reaching my ultimate goal of keeping them clear so the heater & A/C will work efficiently. I'm not certain it's cut down on the dust that gathers in the rest of the house, as that's pretty hard to quantify (especially when we just simply don't dust around here), but I like to think so. I was hoping to see my energy bill go down a bit as a result of the better air flow, but that, too, failed to come to pass. Still, I can at least pretend that I'm doing the right thing.

The second has to do with my church. I believe in the Law of Tithing, where I give 10% of everything I earn back to the Lord. The way I've kept track of what I should pay, on every increase, I enter a transaction in my financial software with a future date with the 10% amount. It's always there at the bottom of my register, so I always know how much I owe; and I can always make sure I don't spend too much such that there isn't enough for the tithing amount. If I forget to take a check to church one week, I just keep adding to that transaction in my register, until I get around to writing the check and giving it a real date.

I thought it was a pretty good system, but a couple things bothered me. One, I noticed in months where money was tight, I would find myself "borrowing" from that total to pay the bills. Oh, I wouldn't change the amount, but I would ignore the fact that the tithing transaction was actually making my balance negative, because it would be fine when the next paycheck showed up. But I found that it seemed to happen more frequently and with greater amounts the longer I left that transaction in there unpaid (not to mention the tithing amount was growing over time as well).

The other thing occurred to me as we discussed tithing in church one Sunday. While it's relatively easy for us to pay tithing now by just writing a check, in the past it involved real items — for example, agricultural farmers would bring food from their harvest, and livestock farmers would bring animals. They always referred to it as bringing the "firstfruits" of the harvest or the flock, because it was a sign of devotion and respect to God that we give Him the best portion of what He gave us. When I applied this to my system of reserving money in my register, I realized that what I was doing was closer to making sure everything else was paid first, and then giving God what was left over. In practice, I had it backwards.

My resolution for tithing is to pay as soon as possible. That means, on Saturday night, I check to see if I need to pay anything for tithing (since I don't really think about which weeks are the pay weeks and which aren't), and write out the check, so it's ready to turn in the very next day. It just feels like the right thing to do, and I feel better about doing it this way.

So yeah, that's it. Those are my New Year's resolutions. Nothing earth-shattering or anything, but I feel like they are realistic, attainable goals that I can actually keep. And now, here they are in writing, so I can hold myself accountable.

2013-11-21

A no good very bad end of the day

So I went to a karate class this evening. Usually, I just wear my uniform pants (fairly thin), a t-shirt, and flip-flops. Tonight, my wife was helping out with a Cub Scout activity, and since she had to leave before I would be home, she would have to take the kids with her, and I would come by and pick them up after my class. I figured I would at least bring a set of sweats with me, so I wouldn't show up to get the kids just in my sweaty karate gear.

On my way to the church after my class, I went to turn on the street. I wasn't going very fast, but the road was very icy, and my car just wouldn't stop. I slid right into the curb, there was a loud smack, and then my car refused to drive. I got out and checked the damage, and found the tire that hit the curb had been driven right into the wheel well, pretty much jammed in there.

I didn't think to take my phone with me to karate, so there I was in sweats and flip-flops, just under 20°F outside, with no way to call for help.

Fortunately, I was only about three blocks away from the church (blessing number 1, I suppose), so I set my hazard lights on, left the car, and started walking. I got to the church, found my wife, grabbed her phone, and left her to her business while I walked back to the car.

The company for whom I work happens to provide roadside assistance plans, and one of the perks of my employment is enrollment in that plan (blessing number 2), so I called for help. I'm not sure if I had a bad signal or not, but the agent on the phone seemed to have a very hard time understanding the road names I recited and spelled for him several times. Then he told me that a tow truck would be there in about an hour and a half.

So there I sat in the car at a very icy intersection, waiting for help. How it is that no other car hit me coming around that corner, I'll never know (blessing number 3). I was at least able to start the car periodically to run the heater so I didn't freeze. I also happened to find a pair of socks that my son had left in the car, and that I had asked him to take out more than once. They weren't clean, but it was better than just wearing flip-flops. Once I had the socks on, I realized I had a spare pair of boots in the car. They're not a perfect fit, but I keep them there for emergencies. (Looking back, I wish I had realized that earlier and put them on, even without socks, before walking three blocks back and forth.)

While I was waiting, the tow truck dispatcher called saying he couldn't find the streets on the map. No wonder, since the agent had gotten them very wrong. I was able to give him directions at least.

Help finally arrived. Somehow, the details of my problem got mixed up, as he was expecting to just winch me out of something, but fortunately he didn't have an issue giving me a tow. I just had him tow me back to my house (not even a quarter mile away; I could have just walked it, if it didn't mean leaving my car in the middle of an icy road where it would be likely to get hit). I had a shop in mind, but I figured it'd be easier to get all the details together and set up the appointment in the morning.

So at least I'm home. Though with money already tight, I'm not looking forward to trying to figure out how to pay for this repair.

A shame. I mean, it wasn't that bad of a day up until tonight.

2012-12-13

Animaniacs Volume 4 is coming!

If you know the origin of my nom de plume, you'll also understand why this news is very exciting to me.

The 3rd volume of the 1990s cartoon show Animaniacs was released back in 2007, but it did not complete the series. Fans (including myself) have been waiting for the fourth volume to be released with the remainder of the series, but Warner Bros. has been sitting on them for the past five years. My kids have developed an appreciation for the show (and Pinky and The Brain, whose full 3-volume collection has already been released, save for the forgettable Pinky, Elmira, and The Brain fiasco). There are some real gems in the missing 4th volume, like the excellent parodies The Sound of Warners, Cutie and the Beast, and Jokahontas, that I've only been able to relive via poor-quality uploads on YouTube. Now I'll finally get to see them and share them with my kids.

This news apparently came out two months ago. I don't know what prompted me to search for evidence of Volume 4, but I'm glad I did. And with a February release date, I know what's going on my birthday wish list!

2012-12-05

Switches Gone Wild

Had an interesting network error the other day. Very suddenly, while I was paying bills online and my kids were watching Doctor Who on Netflix, the network was completely non-responsive. My first thought was that I had lost my connection to the internet again. But as I tried to connect to my server to check, I was unable to connect to that machine, too. Even when my internet connection drops, I don't lose connection to machines on the internal network.

I went downstairs to check the server. It appeared to be running normally, and I was able to log in to the machine using the keyboard and ancient CRT monitor I keep plugged in for emergencies. I tried resetting the network stack. Curiously, it threw up an error message trying to bring up the network card for the internal network, something about an inability to allocate memory. But the external interface came up without error. I tried a second time, and again, the internal interface still couldn't connect to any other machine.

Thinking there shouldn't be anything wrong with the network adapter itself, I spent quite a bit of time checking my iptables rules. I assumed there must be something in there preventing packets from the internal network from getting processed. Perhaps I had set the wrong rule when I was trying to get a couple new devices to play nice with the email server. But why would it work fine for a while and only now, many days later, decide to drop internal traffic? And why couldn't I fix it? Even when I dropped all filtering rules, I couldn't get any traffic through my internal network to that network card.

Not long ago, my computer failed to get an IP address from my ISP, and for whatever reason, it wouldn't get one until I gave up and rebooted the server. Figuring this was another symptom of whatever the problem was before, I just rebooted the server. It came up again, with only errors I've seen before (fairly obscure warning messages that haven't before caused any noticeable issues). It acquired the ISP's network quickly enough, but still, the internal interface didn't appear to respond.

I finally decided to take a close look at the network switch. One light was flickering rapidly, which was on the port connected to the entertainment center. This seemed odd, since the only devices on at the time were the TV (which does have an Ethernet port, but its features have been pretty useless so far) and the Blu-ray player (which was streaming Netflix before the network crashed, had been powered off by the kids, and was currently displaying a screen complaining about a lack of network connectivity since I turned it on to check).

Just to check if it was a bad port, I pulled the cord for the entertainment center and plugged it into an empty port. The light on that port came on solid, then started to flicker rapidly as before. I then unplugged the switch's power cable, waited several seconds, and plugged it back in. Each of the lights cycled in sequence as the switch went through the startup sequence, then all lights on ports connected to live devices turned on solid. Some started to blink, and the one connected to the entertainment center started to flicker rapidly again.

I went up to the entertainment center to check on the switch there. The lights on ports connected to the TV and Blu-ray player were on solid. Only the light on the port connected to the wall (and back down to the entertainment center) was blinking, and it was flashing rapidly.

This was seriously odd. No lights connected to any computers or devices were blinking with any intensity — only the lights on the switches that connected to each other. Were the switches generating their own traffic, talking back and forth to each other? These are fairly inexpensive, unmanaged switches, with no network address of their own to speak of; what could they possibly be saying to each other, and how?

I unplugged the power cord on the switch behind the entertainment center, waited a few seconds, and plugged it back in. All its lights came on briefly as it powered up, and then finally, mercifully, the lights on all connected ports came on and stayed solid, including the light leading to the switch on the server. I checked the Blu-ray player and my laptop, and both were able to connect to the server and, by extension, the rest of the internet.

I still have no clue what was causing all that traffic. I did notice that, when the Blu-ray player started streaming Netflix again, the lights on both ports on the switch that connect to the wall and the Blu-ray player were flickering quickly, looking much like the flickering on the one port when things weren't working (although there's no way to tell by sight if the flickering was exactly the same). Near as I can figure, there was so much of this mysterious traffic that it jammed the main switch so thoroughly that no traffic could get through any other port. (Since they are both 1Gb switches, it certainly could do it. The only other gigabit network device on my home network is the network adapter on the server facing the internal network, but the light on the switch on that port wasn't showing anything but the most rudimentary activity.)

2012-11-28

MVC: Any object you want, but not a string

I often refer to MVC — the Model-View-Controller pattern for building websites — as "Magic, Voodoo, & Conjuring", because a lot of things just happen by what seems like magic. Moreover, when something goes wrong, it's very difficult to find exactly where it went wrong, because the process is happening without writing any code.

I had one such example of something going wrong today. It was only after I got another pair of eyes to confirm I wasn't crazy that I found a StackOverflow question that addressed my question.

We had a JavaScript method that took a method name, a key, and an object, and posted that to an AJAX handler on the server, more or less like so:

$.ajax({
    url: "/Home/" + methodName + "?key=" + keyId,
    contentType: 'application/json',
    data: $.toJSON(dataObject),
    success: function (result) { doSomething(); },
    type: "POST"
});

This JavaScript code block was part of a plug-in that we wrote to apply to many different forms on the site, that shared common functionality. Depending on the data being processed, the dataObject could be anything from a string to a full-blown object. The controller methods all had similar signatures:

public ActionResult ProcessStringData(string key, string newData);

public ActionResult ProcessDataEntity(string key, DataEntity newData);

When the AJAX call was made, the querystring parameter key was correctly mapped to the method parameter key, and the JSON object in the request payload was magically deserialized and mapped to the newData parameter.

The problem was (as you may have guessed from the StackOverflow question), while this worked great for the object, it was completely ineffective for the string — despite the fact that the data was in the request input stream, the value would always be "null".

This is why it was such a head-scratcher. If the data was a DataEntity object and we were calling the ProcessDataEntity method, the AJAX payload would simply be:

{ prop1: "value", prop2: "value2" }

Note that nowhere in that text is the name newData, and yet the MVC framework somehow managed to interpret it as a DataEntity object and pass it as the newData parameter.

Calling the ProcessStringData method with a string as data, however, resulted in this payload:

"data value"

So why wasn't it magically treating this as a string and assigning it to the correct parameter?

Maybe the JSON deserialization magic was throwing an unseen error. Using Fiddler, I tried submitting a payload of { "data value" }. This resulted in a very visible error response from the server about an invalid JSON object. Since "data value" did not return the error, the deserializer must've been relatively fine with it.

Curiously, if I changed the payload to:

{ newData: "data value" }

it did, in fact, work. However, I didn't want to have to wrap a simple string with a named parameter object to get it to work — it would be inconsistent with the object-processing methods that did not require this massaging. (Consistency makes for much more maintainable code. Try bringing up a new developer to speed and explaining that data is in a certain format, except in a list of "special cases" that you're lucky if you remember to mention, and you discover this truth quickly.)

Looking through StackOverflow, it seems that it is possible to remove the content type to process strings. Again, this would have required determining if I was calling a string-based or object-based method and setting the content type (because I actually did want the application/json type for objects). It just didn't "feel" right.

I ended up wrapping the payload in an array. For whatever reason, it is unable to take a string payload and map it to a string parameter, but it is perfectly fine mapping a payload of the form [ "value" ] to a parameter of type List<string>.

It's just one of those things that requires some coding around, but the hard part is trying to understand why. And because it's all handled by magic, voodoo, and conjuring (a.k.a. some method buried deep inside the framework), it's not in your working code, and therefore very difficult to track down.

2012-10-06

Microsoft Store fixing my preorder

This is a follow up to the previous post.

After yet another exchange of emails saying "You weren't charged, so it was canceled" and "I wanted to be charged, why was it canceled", I got an email from another "escalation specialist". He referenced my exchange with Aubrey, so I figured this new person was taking over for the previous one, and he offered to re-place the order and get all my preorder bonuses for me.

We had a couple emails back and forth to confirm everything, and he asked for my phone number and a time to call so he could get my credit card information (since it wasn't available to him, and email is way too insecure for sending that information). When I was on the phone with him, he placed the order and gave me the new order number. He commented that it had been flagged for review from the fraud department, so it might take a day to process, but he would put a note on it so the investigators would know what was going on. Sometime during the night, I got a confirmation email that the order had been processed.

He called a couple days later in regards to the 1600 Microsoft Points card that was one of the preorder bonuses, asking if I wanted a physical card or a code by email. I told him a code was fine, and he said he would get that processed. He also told me he would be upping my $10 next-purchase credit to $20 for my trouble. Interestingly enough, when he emailed later with the Points code, he commented that every order he is placing for me is getting flagged for review. In my thank-you reply for the code, I asked if there was a way to check into why this was so. Maybe it's just the oddity of the customer service person placing orders on my behalf, but if there is another underlying reason, it'll be good to know before I try to use my $20 credit on my next order.

The next day, I got a call from Aubrey, who wanted to check on my shipping details to get my order replaced. I guess the "takeover" wasn't fully communicated. I gave him the other guy's phone number, and he said he'd double-check everything to make sure it was getting taken care of; and he later emailed me to say it looks like everything is good.

So, it took a while, and a few frustrating emails to start off, but it does look like everything is finally getting taken care of.

2012-09-28

Microsoft Store canceled my pre-order [UPDATED]

See my update in the next post — it looks like it's all getting fixed.

The Microsoft Store online was having a special. For certain pre-ordered games, you could get a coupon code for $10 off on your next purchase, plus 1600 Microsoft Points ($20 worth). There was a game going for $30 that I thought might be a nice one for one of my boys, and with the bonuses for pre-ordering, that was like getting a free game! Seemed like a great deal to me. It was a Friday, and the game was to be released the following Monday, so I placed my order. The website told me my order was successful, and I put it to the back of my mind.

Towards the end of the next week, I realized the game had not arrived yet. They didn't say anything about "release day delivery", so I didn't expect it on Monday, but I thought for sure it would've arrived that week. I logged on to the Microsoft Store and checked the order. Oddly enough, it still said "In Process". So I decided to call their support line to find out what was up.

The very courteous person who took my call was just as confused as I was when he looked at my order status. He talked to his manager, and when neither of them had an answer, he told me he would escalate the problem, and someone should contact me within 48 hours. This was on a Saturday. The next Tuesday, I found this message in my email inbox:

Thank you for contacting Microsoft Office Electronic Software Delivery customer support.

My name is Aubrey and I will be looking into your case [case number] and will keep you updated.

Please confirm any issues you are having with your order.

The charge you have referenced is a pre-authorization only.

A pre-authorization is a temporary hold to verify that funds are available when you place an order. Pre-authorizations are typically removed from your credit card transaction history when the full charge processes and funds are withdrawn. However, in some cases, this process can take up to 2 business days. Rest assured, you were not charged for your purchase. If you feel this is an error, please provide a Proof of Purchase such as a Bank Statement.

Please note that debit cards may display both the pre-authorization and the completed payment as full charges for up to 5 to 7 business days from the date of purchase. If you need assistance removing a pre-authorization from your debit card transaction history, please contact your bank or financial

Thank you and if you have any questions, please reply to this email or you can find my contact information below.

Regards,

Aubrey Teeter | Escalation Specialist | Microsoft Store Support| 1-877-696-7786| a-auteet@microsoft.com | www.MicrosoftStore.com

So, naturally, I figure my order must've been stuck in some "pre-authorization" state. I replied,

Ok, but this order was placed on the 14th, a full 11 days (7 business days) ago. When is it going to go from "in process" to shipping and complete?

And the response:

I am contacting you to give you a quick update as to where we are with your case.

My apologies. I wasn't clear. Pre-authorization means you were never charged. There are many reasons for this but the order has been cancelled. You may reorder at anytime.

Again, thank you for contacting Office ESD. If we can be of further assistance, please reply to this message. When replying, please be sure to include this and any other relevant correspondence in your message.

Well, that doesn't make any sense. I am positive the card would not have declined the charge, considering I used that same card just a few days later to pay a medical bill (several times the balance of this video game order). So what was the specific reason?

Why was it cancelled??

Which received this less-than-helpful response:

Hello,

It was cancelled due to no monies exchanged hands and time lapse You may now re-order the product now to take atvantage of the bundle before it expires.

Again, thank you for contacting Office ESD. If we can be of further assistance, please reply to this message. When replying, please be sure to include this and any other relevant correspondence in your message.

To which I replied:

Ok, apparently I need to be more clear.

I placed the order and provided my credit card information on your website with the expectation that my card would be charged and my order would be shipped as promised. Instead, you didn’t charge my card and cancelled my order without notification. WHY?

I didn't even bother to bring to Aubrey's attention that the referenced bundle had already expired when the game released nine days prior to this point (yes, I did attempt to re-place the order to confirm this).

I posted my complaint to the Microsoft Store Twitter account, @MicrosoftStore, which invited me to email my issue to storesoc@microsoft.com. I forwarded my email conversation with Aubrey, with a summary of the issue.

I haven't heard anything back from either email at this point.

Not only does this make me not want to ever attempt to do business with their online store again, but it makes me very uncomfortable with regards to my Halo 4 preorder at their store where I'll be spending most of November 5th.

See my update in the next post — it looks like it's all getting fixed.

2012-09-13

Windows 8 Review

Windows 8 came out this month for MSDN subscribers. I had been looking forward to it for quite some time now — primarily for the quite mundane reason of wanting to finally rebuild my Asus K70AB laptop and not have to dual-boot between Windows 7 and Windows 8. (There are a few reasons for my dual-booting, but they're not worth going into here.)

I blogged about my thoughts on Windows 8 a few months ago when they released their "Consumer Preview". And the major concern I bring up there still applies: there is a disconcerting lack of visual cues for possible actions. Even when you know what you want to do and you know it's possible, it's not easy to discover how to do it. The other issue that is still disconcerting is the bipolar behavior of launching an app. Look at all the fancy tiles on the start screen. Click one. What's going to happen? Will it launch a full-screen Metro Modern-style app? Will it switch to the desktop and launch a windowed app? No telling until you see it happen.

Other issues I've had are a little more mundane. The default camera driver for the built-in camera generates an upside-down image. I did install the Windows 7 driver for my camera in the Release Preview, and while it did correct the image and programs like Skype saw it correctly, Windows 8's default camera app and the bit in the user profile where it offers to take your picture suddenly couldn't detect that I had a camera at all. So I've been hesitant to install that driver on my "official" install.

Windows 8 supports multi-touch trackpads to be able to use gestures that you usually can only do with a touch screen, like swiping in from the right side to bring up charms. Unfortunately, I am unable to find Windows 8 drivers for my notebook's Elantech touchpad (a beta Win8 driver for a different notebook model was unable to find my touchpad in the Release Preview), so I'm still unable to do gestures. (I guess I should consider myself lucky that the touchpad hardware itself understands some gestures and can send the right signals to Windows 8, even if Windows doesn't see it as anything but a "PS/2 Mouse".)

Modern apps are still a disruptive experience for the mouse and keyboard. For a desktop app, to interact with a windowed application, you only have to move your mouse as far as the bounds of the window. For a Modern app, you are forced to move your mouse across the whole screen. Want to close it? It's no longer as simple as moving the mouse to the upper right and clicking; you have to go to the top of the screen, click, and drag to the bottom of the screen — or move your hands to the keyboard to hit Alt-F4.

The graphics are much improved than I noted back in March, at least from a cursory glance. I installed the Game Room app, and the avatar on screen finally rendered without long triangular pieces of skin stretching grotesquely to the floor, and the virtual arcade environment was no longer obscured by large random fields of color. Good thing, too — the only possible workaround I could find was to install Windows 7 drivers, and that only caused more issues when I tried that in the Release Preview, like the screen randomly going blank when switching modes.

Your local user account is also your Windows Live account, if you so choose — but there are some nice bonuses to doing so. Your desktop settings and profile can be stored and migrated from PC to PC, along with other system preferences and your collection of apps purchased from the Marketplace. The one downside I found, though, is that it only lets you log in to your PC with that password. I have a relatively long and complex password for my Live account, but I tend to stick with simpler, easier-to-type passwords for my PCs. The only workaround is to use a "picture password" (mouse clicks on select places on the lock screen, very easy to snoop over the shoulder) or a PIN (a much less secure four-digit numeric password). Being able to set a custom local password would've been nice.

Given all of this, is there any reason to stick with Windows 8? Well, sure, there are lots of things to like.

The startup time is drastically improved. While I don't have empirical data to prove this, there are plenty of tech sites out there that have the evidence. Even time to resume from sleep or hibernate is so much faster. Time will prove out if the time I spent waiting on Win7 is due to the OS or all the applications I had installed and forgotten about over the years. It's likely that Win8 will slow down once I've done the same there, but if the tech analyses are true, it will still be relatively faster than Win7 was with the same load.

The Xbox Live integration is exciting. Available from the Marketplace already are Live-enabled versions of the standard Windows games Solitaire and Minesweeper, as well as Mahjong, Wordament, and Pinball FX, all for free (although Pinball FX tables are available for a price). And all of these games have achievements! Although they could still use a little work — the achievement notice does tell you that you've earned something, but it doesn't tell you how much Gamerscore you've earned; and a lot of the features, like online leaderboards, are blocked with a message asking you to download an update to the game that is not yet available. But still, older predictions that Microsoft would use the free Windows games, by adding achievements, to lure more people into the gaming world are starting to come true.

It's disappointing that, after a full year of generally available preview versions, that functional, compatible drivers for the camera and touchpad are still missing, but I'm relatively confident that they will come, especially once Windows 8 reaches general availability.

2012-08-14

The Lying Mainstream Media

I remember the first time I was truly angry at "mainstream media" for manipulating facts to provoke a certain response. I was in college in the mid-1990s, and there was a story widely reported about a schoolteacher who had written "Where are my glasses?" on a little girl's face. As I watched the story on the fraternity commons room TV, I said a few unkind words about the teacher in question. As luck would have it, in the room were two friends who were familiar with the teacher and knew the facts that the media was carefully leaving out.

For one thing, writing on kids' faces was not an uncommon occurrence for this teacher. She would often paint their faces with something they learned that day — the letter of the day, numbers, facts, etc. It was something the kids looked forward to, happy to show off that they learned something new.

Second, she used water-soluble paints that washed off easily. It was extremely unlikely that such markings would still be visible for "days", without some help from studio makeup artists anyway.

Third, the girl was visually impaired. The teacher was concerned that her coming to school without her glasses was affecting her ability to learn, and notes that she repeatedly sent home to her parents were apparently being ignored.

As my friends explained these points to me, my anger shifted from the "vengeful, irresponsible" teacher to the media outlets and the reporters breaking this story. I felt deceived, manipulated, and ultimately lied to.

Even as I went searching for this story, nearly two decades later, most articles still ignore these points. A Bing search for "teacher write face 'where are my glasses'" first returned two articles about the girl graduating high school, then one titled "White teacher suspended for allegedly writing on black student's face" (emphasis added). It's not until page 2 of results that I found a New York Times article that mentions how routine the teacher's face-painting was and the notes she sent home about the girl's missing glasses. (I was also struck by how many articles call out, either in the title or the first sentence, the race of the child and that of the teacher, although I don't recall the "race card" being played so heavily when I first heard the story.)

It didn't altogether surprise me, therefore, when I first heard of how the media was twisting the Zimmerman/Martin case. What did surprise me, though, was just how far they were going in lying to the public, actually to the point of manufacturing and manipulating evidence.

From the beginning, the incident was tainted to look like a "simple" case of white-on-black, racially motivated violence. Zimmerman was described by the media as a "white Hispanic", a phrase that, before this incident, was rarely used.

Then there's Zimmerman's 911 call. Transcripts that were reported were carefully edited to make it appear that Zimmerman was focused on Martin's race. And while initial reports of the audio of the 911 call proclaimed he used a racial slur, further analysis casts that "fact" into further doubt [video].

And why was Zimmerman's account that he was being beaten, with his head slammed on the concrete, so hard to believe? Probably in no small part to the video of Zimmerman's arrest and questioning being degraded and obscured so that his injuries were not visible to the general public — even if such injuries were verified.

Never mind that Zimmerman has a history of helping people, including the black community as a whole. Never mind that he might have even had good reason to keep an eye out for someone who is black.

I'm not sure why they chose to twist this story so completely. Maybe they were trying to support Obama's call for sympathy for the Martins with his "If I had a son..." comment. Maybe they saw an opportunity to tell a story and wanted to make it bigger by playing on people's preconceptions on racial intolerance. Maybe there was a more sinister "wag the dog" motivation, blowing this story up to divert attention from something else.

Whatever the reason, the media seems to be more intent on pursuing its own interests than the well-being of the population. Not only will Zimmerman have a devil of a time getting anything resembling a fair trial, but innocent people are being attacked in retaliation for the story the media has manufactured.

But don't hold your breath for them to offer any corrections. Even with more facts coming to light, they still hold on to their original narrative.

2012-07-23

@ComcastCares really does care

I was having issues with my Comcast internet service where it would randomly disconnect throughout the day. Usually, the disconnects lasted only a minute or two, as the cable modem re-acquired the signal (if I happened to get to the basement fast enough, I could see the modem go through its startup sequence of flashing lights), although sometimes it would be down for several minutes. This would usually happen three or four times a day.

One day, when it was especially flaky, I called Comcast customer service. After going through the standard troubleshooting tips (including resetting the modem and rebooting the computer), I finally got a service call scheduled. The technician didn't find anything wrong inside the house and promised to schedule a line technician to check the wires outside. He said to call back in a few days if things hadn't improved. When they hadn't a few days later, I tried calling back, only to get a customer service rep on the line who could only tell me that he didn't have access to the line tech's schedule, but to try waiting a week as it sometimes takes that long for a technician to be available.

During the week, on a particularly hot day, the internet service was being very unstable again. It did seem like, the hotter the day, the less stable my internet connection (although that could just be correlation, since really hot days are days I'd rather spend inside in the A/C). I decided to send a tweet to the @ComcastCares customer service account to ask if this was typical behavior, which resulted in an exchange of messages where the @ComcastCares representative was actually able to tell me that the line tech had not been out yet, and that he would see to it that it got done.

Already I was pretty impressed with their service (and more disappointed with the telephone customer service), but I was completely unprepared for the next step. That Sunday afternoon, I got a phone call from someone who monitors the @ComcastCares Twitter account to follow up with my service issues. After asking me some more detailed questions about my setup (like whether the cable line went through a whole-house amplifier before or after it hits the cable modem, and whether there were any splitters or traps on the line) and then trying some other troubleshooting steps (like removing the splitter and trap and just dedicating the cable line to the modem), he promised to follow up with another service call from another technician.

The next service call, the technician was able to determine that there was damage on the line from the house to the pedestal, and he replaced that and scheduled a time for another team to come back and bury the cable.

Unfortunately, the problems didn't stop there. Things did seem to get better for a time. (There was one peculiar instance of my cable modem doing a factory reset of itself. My network setup requires the cable modem be in "bridging" mode instead of the default "routing", so when this happened, I couldn't connect to the internet even though my connection was technically "good". Since I couldn't fix this myself, I used my phone to fire off a tweet to @ComcastCares, and it was fixed within minutes. No rep that I've spoken to about this can figure out why this happened, however.)

Again, I got a phone call from that same rep who's been watching my case. Although he had promised to have an area manager contact me, he realized there was some miscommunication along the way, and the area manager was sending him updates but not me; so he wanted to contact me and check on the status. I mentioned that things seemed a lot better, although things still weren't perfect. (This was right after the cable had been buried.) He had already left me his voice mail number on an earlier call, and he invited me to keep an eye on things and leave him a message if things hadn't improved. Well, not much later that day, there were a couple fairly long-term (i.e., several minutes) dropouts, so I did end up leaving him a voice mail.

I haven't heard back from him just yet, but there was a technician at our house today. He checked the line and was finding some errors, and he started tracing the line back along their network until he found a bad amplifier further upstream. He reported to us that he fixed that, and that the bad amplifier plus our damaged cable would be a likely cause to all our issues. He also said he was surprised no one else had reported any problems.

So, as of now, things are a whole lot better than they were. I have to say, I am really amazed at the level of service I've received through the @ComcastCares account. Sure, it would be nice if nothing ever went wrong in the first place, but the fact that the people I've been working with have actually taken an interest in fixing things up (especially reaching out and calling me to check up on things) is really impressive.

2012-05-24

I code with a catapult

I decided to try something this year. For my entire programming career, I have used a fixed-width font while coding. Of course, when I first started coding, fixed-width fonts were all a computer could do; and even these days, command line interfaces still predominately depend on a fixed-width font for display (especially if they try to draw boxes or other pseudo-graphical elements). Even as I type this blog post using Blogger's HTML editor, the edit window uses fixed-width characters; and if I wrap some text in <code> tags, chances are your browser will also render that text with a fixed-width font (even if Blogger didn't apply a custom style to it). But for a long time now, computers have been able to use proportional-width fonts on screen, and many development tools support picking your own font. Yet, whenever I get the inspiration to try a different typeface in my IDE, I always picked from the list of fixed-width fonts. Visual Studio seems to encourage this by making fixed-width fonts bold in the font dialog.

(Although, admittedly, it is convenient to know which fonts are fixed vs. proportional at a glance, and bolding one or the other is a simple way to show the difference.)

But I had read a handful of blog posts from developers claiming how it is easier to read code when they view it in a proportional-width font. The discussion often includes pros and cons of viewing code in a "literary" font vs. a "computer" font, and often includes a discussion of tabs vs. spaces (the reverse is also true: discussions about tabs vs. spaces often include someone commenting on the benefits of one vs. the other when using a proportional-width font instead of a fixed-width font). I decided that I wanted to try something new, and maybe I'd give this developing-in-a-proportional-width-font thing a try.

The major criterion I've found for picking a font is that it must have very distinct characters. Fonts where a number 1 looks like a capital I looks like a lower case l, where a number 0 looks like a capital O looks like a pair of (), and where (parentheses), [brackets], and {braces} are too similar (or just too "weird"), tend to cause more headaches and annoyances than their otherwise typographical good looks are worth. Also, the font should, obviously, be supported (Visual Studio only supports TrueType fonts in the IDE), and it should be legible (and similar characters distinguishable) at smallish sizes (I tend to view my code at 8 or 9 point). It's also helpful if it's one of the "standard" fonts that is available on nearly every machine (i.e., you don't have to try and find a legal, free download every time you want to use it on a new machine). One proportional-width font that fits these criteria fairly well (no font is perfect on all counts) is Trebuchet MS.

To make a long story short, I'm lovin' it. I've found it much easier on the eyes to read through code. It looks neater, cleaner, more professional, and more tidy (even if the actual code is a mess). And while I realize this "analysis" is all based on subjective, personal preferences, in my opinion a font choice when doing development is exactly that. The proportional font also helps view wider lines on the screen. Now, in an ideal world, you should never let your code lines get so wide that you need to change fonts to read them all, there are times where it is necessary to have a wide line (especially in HTML, where a browser — and I'm not just talking about IE here — behave oddly when you try to insert a line break).

Since commentary on font style is almost never complete without tabs vs. spaces, I'll add my 2¢ here. Personally, I prefer tabs, because they are more compact (one character vs. [number of spaces]), more customizable (most IDEs worth their salt let you specify the size of a "tab stop"), less prone to error (you can type three spaces instead of four, but you can't type half a tab), and easier to navigate (to back up an indent level, you only have to press the left arrow or delete key once, instead of four, six, or eight times). The arguments I've heard for spaces over tabs, I either don't agree with or I don't (personally) think matter: they are uniform across all IDEs (agreed, it is jarring to open a code file in another tool [e.g., a diff tool] and see it display tabs at a very different width), they display the code as written (arrogance; why is the way John Q. Developer aligned the code the "right" or "only" way to view that code?), and they allow for more precise aligning of things like variable declarations (irrelevant; you can tab to the proper indent and use spaces for fine alignment, if necessary). But these are just my opinions, as everyone has their own (and, as a quick scan of the internet shows, some hold to their own opinion with something approaching fanaticism or zealotry that makes it not worth arguing).

I've found that using a proportional-width font seems to work best with tabs, since it helps you keep the code consitently indented no matter which font you use. (Plus, if you prefer larger indents, you end up having to use even more spaces to get the same depth as with a fixed-width font.) However, there is one potential drawback to using a proportional-width font that neither tabs nor spaces can solve, and that's aligning of variable declarations (or other similarly-formatted code blocks). See this picture for an example:

In a proportional-width font, you can't use spaces to align the variable names with the first line. Not only would it vary depending on your choice of font, but there's no guarantee that the sum of the widths of the letters in the variable type is evenly divisible by the width of a space. (You can use tabs to align them with a tab stop, but again, that will depend on the size of your tab stop and whether the variable type name fits within one or two [or more] tab stops.) If that matters enough to you, this may be a deal-breaker; but it's one of the things I've found, in practice, doesn't matter that much when you can just indent the dependent lines like so:

If you haven't tried coding with a proportional-width font, I highly encourage you to give it a try. At best, you might like it. At worst, you can always change it back.

2012-03-18

Old hardware obsolete in Windows 8?

I've come across a minor concern in my trial of Windows 8. In particular, I have noticed some rather disappointing graphics issues with my two-year-old notebook's ATI Radeon HD 4570 chip.

At the right, you can see an image of the Games for Windows Live application Game Room. The only really odd thing about it is the fact that the avatar is a rather generic one, rather than my actual avatar (which the Xbox version of the game uses).

To the right, here, is the same application, running on the same hardware, booted from a Windows 8 partition. The same generic avatar appears here, but with obvious rendering issues. The issues occur also in the "arcade" virtual world, making the arcade impossible to navigate or use (large triangles would block out most of the viewing area).

This picture is of the recent game Microsoft Flight on the same Windows 8 partition. In addition to the wide zebra stripes in the skybox, there are rendering issues with one of the planes that comes free with the game (some invisible triangles, some other triangles that stretch through the cockpit). Oddly enough, the other plane doesn't seem to have that issue. (I would have a picture from Windows 7 picture for comparison, but it won't run on my Windows 7 setup for some reason — it may be time to rebuild the thing.)

I did some internet searching, and there were some suggestions about going to the video card manufacturers' websites to find updated Windows 8 drivers. I checked the AMD website for drivers for my notebook's ATI Radeon Mobility HD 4570. There were Windows 8 Preview drivers for the HD Radeon 5000 series and newer, but nothing for the 4000 series. Some of the websites I found earlier suggested downloading the Windows 7 drivers, just like Windows Vista drivers would work on Windows 7. However, AMD's download site didn't provide direct links to the drivers, just an automated installer application, which refused to install any drivers on my "undetected operating system".

Now, this is just a preview, so it is very possible that, by the time Windows 8 is released, drivers will be available for all of the ATI chips, or that the included drivers will be fully functional. It is just making it rather difficult to make a truly objective assessment of Windows 8 when the only video driver I can use has such obvious issues.

2012-03-11

Thoughts on Windows 8 Preview

On February 29th, Microsoft released the Windows 8 Consumer Preview to the wild, and it quickly scored over a million downloads. I downloaded it and installed it on a separate partition on my laptop. I did this a while back with the Developer Preview, but it was so buggy and didn't really offer me too much at the time that I killed the partition and kept on keepin' on with Windows 7. This time, I've decided to give it more of my time and form some real opinions about it, and — since we live in an age where any idiot with a blog can publish their opinions — I decided to publish this idiot's opinions.

Every day I use the operating system, I have the same thought: this would work great on a tablet. The machine boots up in a fraction of the time as my Windows 7 partition. The new start screen is so much like my Windows Phone, I want to reach out and touch the screen and swipe the tiles around with my fingertips. This would, of course, be futile, since my laptop does not have a touch screen, so there is more than a little awkwardness in using my mouse or touchpad to control the UI. The mouse I use is a Notebook Optical Mouse, which includes a scroll wheel. Using the wheel to pan the Start screen is easy enough, even if it is disconcerting at first to scroll the vertical wheel to move the screen horizontally. As an experiment, I tried disconnecting my mouse and using the laptop's integrated touchpad. The touchpad is multi-touch, so I found I was easily able to scroll the Start screen using two fingers instead of moving the pointer with one.

This does bring me to my first complaint, however: there is really no visual cue or instruction telling me how to get around. While touching the screen to swipe tiles around seems intuitive enough, using the mouse wheel or using two fingers on the touchpad isn't so much. I had to just experiment to see what worked.

This lack of visual cues is a perpetual problem with the OS. For instance, if you install a program, the main program appears on your Start screen. However, it is often the case that a program will, on installation, create a Start Menu folder that contains several shortcuts. It may be true that the most common user story is they will click on the program to run it, but there are often shortcuts to the program's other tools or modes that may be essential at some point (if not an everyday use of the program). Where do those go? It turns out, if you right-click on the Start screen (not on any tile, though; it has to be an empty location on the screen), it brings up a button at the bottom of the screen marked "all programs", and that can be used to see the entire program group. The only way I found this, though, was by random experimentation. If I was looking for these options, there is nothing on the screen that would help me find it except by randomly clicking. This is not efficient task-solving design.

The Start menu itself is also hidden. Once you get off of the Start screen, it's not obvious how to get back to it. You could use the Windows key, but that key no longer looks like the button on the screen it would activate (because that button doesn't exist). You can also throw your mouse into the lower left corner of the screen, where the Start button used to be; but there's nothing on the screen that suggests this is where you need to go to get there.

Another example is the Metro version of Internet Explorer. Its full-screen mode means you don't see so much as an address bar, and although it does support opening multiple web pages in "tabs", these, too, are hidden from view. Bringing these up requires right-clicking on the web page (but not on any real element of the page, otherwise the right-click will bring up an action menu specific to whatever happened to be under your mouse at the time), at which point you can see the URL and all the tabs you have open. Even the Windows Phone version of Internet Explorer doesn't force you to guess this badly; not only is the URL always on-screen (in portrait mode), but there is an ever-present ellipsis button in the lower right that, when tapped, shows you all of your possible actions, including viewing currently-opened tabs. There's really no reason why a laptop can't sacrifice a few pixels of screen real estate for these visual elements when a phone an eighth the size can do it.

One more thing is the side-by-side method of running apps. I know it exists, because I've seen the videos showing it off, but such videos are almost exclusively demonstrated using a touch interface. I do not remember how this is done, let alone how to do it with a mouse and keyboard, and there's nothing on the screen that even hints at what I need to do to activate it. (With these full-screen apps without chrome, there's no title bar to grab and drag to the side like there was with Windows 7.) When I went to find a link to use in this blog post, I had to use the old-fashioned alt-tab combination to switch to a new window and find it, then copy and paste it back here.

Why all this fuss about visual cues? I try to think about the non-computer-literate, specifically my mother and my mother-in-law, and how they would deal with this. Without seeing something on the screen, how would they know what to do? Going to the lower-left to access programs may seem like a second-nature gesture to most of us, but how would anyone expect them to see a blank screen and just know they need to go to this lower corner? How will they know they need to swipe in from the right to see the "charms" (the list of quick actions available to every app)? Even with a computer-literate son or daughter nearby to explain it to them, I would not expect them to have the actions memorized in any reasonable time frame, when computer activity is so little of their day. I have a hard enough time picking up a videogame I haven't played in a couple days and trying to remember all the controls specific to that game, and that's something I do nearly every day.

The whole idea of Metro-style apps on the computer is something I thought at first to be too restrictive. As I've worked with it more, though, I'm finding there aren't nearly as many drawbacks as I originally thought. I'm often only working on one thing at a time, or comparing data between two apps. Having the one full-screen helps me to focus on that window without being distracted by other windows or widgets. Being able to dock two apps side-by-side (if I could figure out how to do it) would probably take care of 95% of my use cases.

However, there are, indeed, drawbacks. I definitely miss not having a clock ever-present in the lower right, or a status tray of icons that I can see, at a glance, what's up with my PC. It's also not immediately apparent what is running on the system — there's a Metro-style Messaging program, which will pop up a notification when a message comes in, but it's not clear to me when it's running or how to start it to make sure those notifications come in. (Contrast that to Skype, which runs as a standard Desktop app, and which, when I'm on the Desktop, I know immediately that it is running.

It's still a little disconcerting having Metro apps and Desktop apps, and a Start screen that doesn't distinguish between the two. When I click on something, I don't know what will happen — will this just open full-screen, or will it take me to the Desktop and add a window there? Why is there a difference? Why do I have to open an app full-screen, or why are there some apps where I can't? It's almost like dual-booting, except there's really no planning ahead and no way to tell which UI is going to handle it.

I do think this would be a great tablet OS, and I would love to have a tablet myself capable of running it. Actually, it would be more correct to say I would love it if my laptop could be used as a tablet (much like the old tablet PCs that failed to take hold of the market a few years ago, pre-iPad). As far as installing the latest and greatest OS on my current machine, I just can't say I'm all that excited about it yet.

2011-12-17

Innocent by Law, Guilty by State Farm

Several months ago, I was involved in a traffic accident. The police officer who arrived on the scene took statements from three witnesses and the other driver before approaching me with a ticket in his hand charging me with "careless driving".

A few things annoyed me about the charge. For one thing, the term "careless driving" is really broad. It doesn't really tell you what you did wrong, just that you didn't do something right. For another, I believed I was following the laws and acting not only according to what I believe was correct (especially with reference to what the Colorado Driver's Handbook says to do at a malfunctioning traffic light), but with how other cars present at the intersection at the time were behaving. Also, the fact that the cop issued the ticket without getting my view, but only that of the other driver and some witnesses, made me feel like the decision was obnoxiously one-sided. Finally, the fact that the officer's report stated the other driver was being cautious didn't fit the facts that, I felt, were obvious.

I was determined to fight what I felt was an unfair assessment. And after finding out how much it would cost to obtain a lawyer (from the one firm that found it worthwhile to actually return my call), I decided I could only afford to fight it if I fought it on my own.

To make a very long story short, the judge agreed with me, that I did take into account the situation (the malfunctioning traffic light, the large number of cars stopped at this light in all directions). One of the witnesses was key in this decision, as she happened to be behind me at the time of the accident, and she testified that I did in fact stop for plenty of time to analyze the situation before entering the intersection. It also sounded like the was about to say the other driver was at fault for entering against a flashing yellow when there was a car already in the intersection (which I was able to prove I had first, by a large margin), before she interrupted herself and gave her ruling, that the prosecution failed to prove my guilt. So, against the odds of representing myself in court, I prevailed.

With that ruling, I thought it would be prudent to contact State Farm and let them know that not only was I found not at fault, but a competent lawyer could likely take this case and go after the other driver's insurance for the loss — hey, if an incompetent fool like myself could win the case, imagine what someone with appropriate skill could do. Boy, was I ever in for a surprise. When I was connected to the agent in charge of processing my claim, and I explained the situation, she told me she didn't think they had a case. And then this State Farm agent proceeded to tell me why: because the other driver had the right of way, she had no obligation to watch for traffic in the intersection because I should not have been there; basically all the arguments the prosecution made at my trial, that were ultimately rejected by the judge. When she mentioned details that were just wrong (like the other driver having a regular yellow light and I ran a red light) and I tried to correct her, she accused me of changing my story. (I don't know if, in the heat of the moment when I first reported the accident, I got some details wrong; but the condition of the traffic light was a fact clearly spelled out in the police report for crying out loud.) She even went so far as to claim that there was no difference between a flashing yellow light and a green light! I was in shock.

I suppose ultimately it's their decision to pursue the case or not, but to just dismiss the results of a trial and accuse me of guilt after I had been found not guilty, does not sit well with me. I believe it is time for me to find a new insurance agent, one that does not stubbornly hold to an assumption of my guilt even after being found not guilty in a court of law, like State Farm has done.

2011-11-21

Hitting the wall

Looks like it might actually happen. With my nephew staying with us while he goes to college, his additional gaming and Netflix bandwidth has pushed our internet usage up over 210MB this month, with still a third of a month to go.

To get comparable internet speeds from Comcast Business (which is not, reportedly, subject to bandwidth caps), I would have to pay triple my current monthly internet bill. I was unable to get comparable numbers from CenturyLink Business (the only other viable internet service provider in my area) without providing my home address and phone number.

My nephew is off spending the Thanksgiving holiday with his immediate family, and I've told my wife we need to use our shiny plastic (and completely unrestricted) discs for home entertainment, so we have a chance of making it through the month under the cap; but now, it's clear that the bandwidth cap is making a clear impact on our internet usage.

It's interesting to note that Microsoft has announced that they are going to be bringing even more streaming video content to the Xbox in the coming months, including (but not limited to) YouTube, UFC shows, and various cable providers' on-demand content (which would be delivered over capped internet, rather than the limitless pipe that carries regular cable content).

Internet use and services are going up (and Comcast even occasionally increases its speeds to deliver more of that content faster), but the cap doesn't move. How many people are going to find themselves over the cap soon? When will Comcast realize "generous" is becoming "too restrictive"? And, most importantly, when will I see a viable option that gives me reliable connection and speed, and the ability to actually use it to its potential?