Convert a Value to Nullable

on June 10th, 2010 by Matt

I’ve decided to start a new series-like set of articles on highly reusable code snippets. I write a lot of these types of snippets and figure it’s time to share. Kicking off will be the ConvertToNullable function.

Background

I despise boilerplate code in general, but I really hate writing the same code over and over to check if a variable equals some “default” value and acting on that case. That’s why I wrote SafeDataReader (article to come) years ago. SafeDataReader is constructed with a DbDataReader and adds a ton of new Get method that let you easily and safely access fields on the underlying data reader with strong typing.

One of the key benefits of SafeDataReader is that every Get method has an override for supplying a default value. If you use this version of a method, it will return your default value if the field is null (DBNull.Value).

Unfortunately, I wrote SafeDataReader before the much needed Nullable type was introduced to .NET. I also have not taken the time to go back and update it to support nullables. That leads us to the “dilemma” behind today’s code snippet.

The Problem

Have you ever written something like the following?

DateTime? someDate;
DateTime someTemporaryDate = GetSomeDate();
if (someTemporaryDate == DateTime.MinValue) {
  someDate = null;
} else {
  someDate = someTemporaryDate;
}

The GetSomeDate function may be legacy code, but it only returns DateTime (or another value type). However, you write code for the new millennium and want to use nullables for a clearer intent of the unknown value. Regardless, this type of code block is a PITA that bleeds unreadability.

Going back to my SafeDataReader example, here is some code that is nice and tidy until the DateTime value needs converting to a Nullable<DateTime>.

var setting = new Setting {
  Title = reader.GetString("Title"),
  Quantity = reader.GetInt32("Quantity", 1),
  BeginDate = reader.GetDateTime("BeginDate"),
  EndDate = (reader.IsDBNull("EndDate")
      ? (DateTime?)null
      : reader.GetDateTime("EndDate"))
};

Ugh! I hate that bit with the EndDate. Since Setting.EndDate is a nullable DateTime, I have to jump through ugly hoops to handle a null just because my GetDateTime method doesn’t yet support nullables.

The Reusable Solution

Nothing beats a generic reusable solution to such a problem. Let’s see it!

protected static T? ConvertToNullable<T>(T value, T defaultValue)
  where T : struct {
  if (value.Equals(defaultValue)) {
    return null;
  }
  return value;
}

protected static T? ConvertToNullable<T>(T value) where T : struct {
  return ConvertToNullable(value, default(T));
}

Now, we have something that will clean-up those previous examples.

DateTime? someDate = ConvertToNullable(GetSomeDate());
var setting = new Setting {
  Title = reader.GetString("Title"),
  Quantity = reader.GetInt32("Quantity", 1),
  BeginDate = reader.GetDateTime("BeginDate"),
  EndDate = ConvertToNullable((reader.IsDBNull("EndDate"))
};

That is much better! Enjoy!

SecuritySwitch Grows Up on Google Code

on February 5th, 2010 by Matt
Edit: Due to a trademark infringement, this open source project will now be named SecuritySwitch. What a huge PITA it was to migrate to a new project on Google Code! Since you cannot rename a project, I had to create a new one and move everything over to it. I so enjoyed blowing 2 hours of my day off on Good Friday.

I recently posted about an update to my WebPageSecurity module project to the newly named SecuritySwitch. One of the best ways to ramp up coding on the project again is to get it into a public code repository.

Get with Git?

I thought about using Git on GitHub, but I want to get moving on this and that would not be the case if I had to fumble through learning Git now. Although, I do really like the concept of a distributed version control system (DVCS). Instead, I will stick with Subversion (SVN) for now.

Google Code

That lands the project in the capable arms of Google Code, which I find to be a very nice new home for SecuritySwitch. I will likely have a dedicated page here on GeekFreeq for SecuritySwitch that refers visitors to the project on Google Code, and/or I will just pipe updates from the project site here via RSS.

Anyway, this is the first stage of a “grown-up” SecuritySwitch.

WebPageSecurity becomes SecuritySwitch

on January 29th, 2010 by Matt
Edit: Due to a trademark infringement, this open source project will now be named SecuritySwitch. Feel free to read the comment posted by the holder of the trademark on the name I originally planned to use. It was a polite enough message. I think there may be ground for me to stand on with the first name, but I don’t care to go to court over the name of a project that is free for anyone to download.

After a bit of a struggle supporting my WebPageSecurity module on Code Project, I’ve decided to put some quality effort into the project in the very near future. One of the first things that needed attention was the name.

What’s in a Name?

Could I have named it something more generic all those years ago? Perhaps, but not likely. After a few minutes of running through some of the key nouns and verbs that describe the project’s purpose, it will now be known as SecuritySwitch.

Educational Value vs. Quality Functionality

Another change to the project will be the maintenance of the dual source code languages. Since I originally started the module, a distinct project for C# and VB.NET have been maintained. While this was great for the educational aspect of the article and accompanying code, it is not ideal for a quality “product”.

After some consideration, I decided to drop the VB.NET version of the source code in favor of a single project written in C#. An immediate benefit to the community of this decision is faster releases.

What’s Next?

All of this change should be balanced with something to make it all worth while. I intend on stopping development on the 2.x version of the module for .NET 1.1 where it is now. Of course, I’ll fix any bugs, but no new features will likely be added. Version 3.x for .NET 2.0 will continue until version 4.0. That’s when I will add some of the new features in the queue and enable full support for ASP.NET MVC as well.

Keep checking back for more progress on this project.

How To: Send a Bulk E-mail Considerately

on October 22nd, 2009 by Matt

If you send bulk e-mails (i.e. messages to several contacts), you really should be considerate of your recipients. While you know (hopefully) all of the contacts in the “To” list of the message you are about to send, there’s a good chance that all of them do not know each other.

A considerate bulk mail sender (that’s you), should respect your contacts’ privacy. Listing all of your receiving contacts in the “To” field reveals their e-mail addresses to each other. That could be thought of as plain rude! In addition, some of your friends and/or family will likely have an e-mail program that collects any addresses from incoming messages. That means, when they forward that wonderful e-mail to their entire address book, demanding that it be forwarded on to 15 others, everyone that you sent your message to will get that person’s bulk messages now. Very uncool!

Luckily, there is an extremely easy way to be respectful of your list of e-mail buddies.

Read the rest »

ASP.NET “Remember Me” Option with Forms Authentication Not Working?

on October 19th, 2009 by Matt
ASP.NET Login Control

ASP.NET Login Control

So, you’ve set the timeout value for forms authentication to a fairly large value, yet checking the “remember me” check box on the Login control still does not persist your users’ authentication, even after a fairly short period of inactivity.

<system.web>
    ...
    <authentication mode="Forms">
        <forms timeout="10080"/>
    </authentication>
    ...
</system.web>

Don’t spend hours trying to figure out why this, seemingly, basic functionality doesn’t perform as it should. The solution to this problem is very simple, albeit somewhat obscure.

Read the rest »

SVN, the Way of the Tortoise

on October 13th, 2009 by Matt

Although, Subversion (SVN) is not new, it is still one of the most widely used version control systems (VCS) available. SVN is a tool that allows users to track the changes of files. Yes, it’s that simple.

Interfacing Your Demons

Like many version control systems, SVN utilizes a command-line interface (CLI) to interact with users. Some users frown upon the command-line; especially, Windows users. However, I want to point out how necessary it is that these tools use the command-line.

After you use a version control system for a good length of time, you should notice that there are routines you follow over and over again. Perhaps you lock certain files before editing them to prevent conflicts with other potential editors on your team. Maybe you always commit your changes when you build a project for release, or when you shut down your computer for the evening. The point is, these are things that can be automated with small scripts through build events or even Windows Task Scheduler. Having a command-line tool is essential to such automation.

On the other hand, there are many times you will want to issue commands to SVN on-demand. A nice graphical user interface can make things much easier and faster for those tasks. Enter TortoiseSVN.

Read the rest »

Google Teams with Verizon Wireless

on October 8th, 2009 by Matt

There was an announcement this week about a new alliance between Google and Verizon Wireless. The short of it is, Google and Verizon Wireless (VW) will be working together to deliver several Android-powered devices on the VW network.

Verizon? Open?

Android is an open source mobile operating system (OS). Yeah, open source. That means, you or I can go download the source code for the entire operating system and make changes to it if we please. Android is also an open architecture, in that applications developed for the OS have full-reign. Applications can change anything from the user interface (UI) to how a phone dials a number.

My confusion with this whole deal stems from Verizon Wireless’ past record with one huge issue: control. The company is notorious for locking devices to a mere fraction of their manufacturer’s default functionality. This is always done in order to control the things their customers can do on their network.

VW “customizes” the user interface of nearly all devices sold on their network. These changes are primarily made to prevent you, dear phone owner, from using the features that are built into your phone. That’s right! If you have a phone that was new within the past 3 years or so, it most likely has the capability to install custom ring tones. If you are a VW customer, I guarantee you cannot get custom ring tones on your phone without paying VW a monthly fee, or a per download fee, to get the simplest of tones you may have already downloaded to your computer. That last statement excludes only skilled geeks that hack around these limitations.

Another great “benefit” VW customers gain from the customized user interfaces is slow to unresponsive interfaces. The developers working for VW do not appear to be very talented programmers. The interface of nearly every device I have owned that has been ravaged by these folks is a horribly-performing, gaudy-looking, cluttered mess.

It’s just what Verizon Wireless does to its devices; that is cripple them.

So again, I am astonished at this deal. How in the world will Verizon Wireless maintain a stance of openness with these new Android devices? Will I be able to remove the inevitable garbage that the VW developers will come up with for these devices? Will I be able to browse the Adroid Market/Library and install any application I want to on my device?

What Google Will Not Stand For

Google will simply not stand for Verizon Wireless taking control over devices that make use of the Android OS. I am still concerned about VW’s track record though. I can only see them making every effort to control yet another class of devices. The public does not have access to the actual deal made between the two, but I certainly hope that Google stood by their morals on this one.

Bullies have never done well against Google. A case-and-point is the whole issue with Apple and getting Google Voice on the iPhone. Verizon Wireless is a well-known bully. How will this deal turn out? I guess, we can only wait and see.

The Future of the Mobile Market

If this deal plays out as announced, Verizon Wireless supporting an open device OS without governing it with their domination-nation, the mobile market will spike for the better. The new kid in town (Android) will finally have made enough friends to compete with the popular one (iPhone).

We need more of this kind of competition in order for true innovation to spark the necessary growth in this country (U.S.). We are well behind other countries in the mobile market. Most of Europe enjoys the next generation mobile infrastructure (currently, 4G) years before we begin to see it here. While there may be some provider issues abroad, generally mobile communication is much more affordable than here in the States. Our providers stifle the entire industry with their archaic practices and Band-aid methodologies.

My Final Take

I am actually excited about the deal between Google and Verizon Wireless. I know it seems surprising after reading all the above. The fact is, my family left VW last year for AT&T. I was so sick of the “device-crippling” that I just had to bail. One of the reasons Verizon Wireless has never been known for its cutting-edge devices is mostly due to their locking practices in order to make a buck on every single transaction you initiate from your VW device.

Now, I am unsatisfied with the coverage of AT&T. Granted, it was already second to VW, but it was acceptable for our needs a year ago. Since then, iPhone usage has snowballed and proven my point about our provider infrastructure problems. I feel certain that no matter which provider Apple teamed with, the iPhone would have totally discredited the network upon saturating it with streams of data requests. None of our providers can support that kind of traffic. AT&T is paying that price now.

I’ll switch back to VW for a truly open Android device on a network with the best overall coverage in the country. However, I still feel that all of the underlying infrastructure needs a total makeover. It won’t be long before VW suffers the same fate as AT&T, when an army of new Android users flood their network.

What is your take on this deal?

Kindle 2: An Introduction

on May 12th, 2009 by Matt
Kindle-2-Held

Kindle 2

Have you ever prepared for a trip and struggled when deciding which books to take with you? Do you have books that are too big to pack in the car or worry about lugging around? Do you get miles into the trip and wish you brought one of your other books instead?

I’m a software programmer and most of my books are at least 1,000 pages and weigh a couple of pounds. Seriously, these books are huge. Oftentimes, I have found myself in the car a few hours into a trip or even at my destination, and really wished that I had another book that was left home. Well, I finally found a solution.

Introducing the Kindle 2

Money

Image by TW Collins via Flickr

Amazon’s Kindle 2 is a wonderful product. It is an electronic wireless reading device. With it, you can potentially carry about 1,500 books around with you at a time. All those books on the new Kindle 2 would only weigh about 10 ounces! I read my Kindle in one hand and don’t have to worry about flipping pages, or maneuvering the book to see the words in the shadowed cleft where the pages attach to the spine. When I prepare to leave the house, I don’t have to debate with myself over which book deserves to be toted around with me; I just grab my Kindle. There are other benefits of the Kindle that are more than just convenient alternatives to physical books.

Who is it for?

Lisa Simpson

Image via Wikipedia

The Kindle 2 is ideal for any reading enthusiast. If you love books, but are not attached to the physical attributes of them, you will undoubtedly want a Kindle 2. I do have some specific recommendations for types of people that will most likely desire a Kindle the most.

  • bookworms that gobble up text like it’s candy (e.g. Aunt Mildred, Cousin Albert, that know-it-all kid next door; a.k.a. Lisa Simpson)
  • history, or reference, buffs that want that information at their fingertips (e.g. Professor Zimmer, spelling bee champions, Civil War reenactors, etc.)
  • technical devotees looking for a great way to consolidate all their manuals and guides (e.g. software developers, network analysts, electronic repairmen, etc.)
  • professionals with a need to constantly look-up codes or hard facts (e.g. building contractors, attorneys, engineers, etc.)
  • many more

This is a great gift for graduates heading off to college, people with low mobility, those with diminished eyesight, and friends or family with one hobby; reading.

Prince of Persia “Combo Specialist” Achievement/Trophy

on May 11th, 2009 by Matt

If you are like many Prince of Persia gamers out there, you have tried tons of different combinations of attack combos in the hopes of finding the right set that will award you that special achievement/trophy; the “Combo Specialist”. The good news is, you do not have to perform all 1,602 possible combos, like the task hint may lead you to believe. You only need to pull off 60 of them. Other guides will tell you 62, 63, or even more, but 60 is the magic number (remember, a combo is actually two or more attacks). I have tested this list at least 10 times with a new user profile each time. There are a few rules to keep in mind when trying to achieve this goal.

  1. A combo cannot kill the enemy. Even the last hit cannot kill your enemy.
  2. A combo cannot be blocked by the enemy. No part of the combo can be blocked for you to succeed.
  3. A combo cannot knock an enemy into a wall or off a ledge. If your combo chain is interrupted by an edge animation, it will not count.
  4. After you successfully complete all 60 combos, you must kill the enemy you are currently fighting before the achievement/trophy is awarded.
A = Acrobatic; G = Gauntlet; M = Magic; S = Sword
  • A,G
  • A,G,A,G
  • A,G,A,M,G
  • A,G,A,M,M
  • A,G,A,M,S
  • A,G,A,S
  • A,M,G
  • A,M,M,G
  • A,M,M,M
  • A,M,M,S
  • A,M,S,G
  • A,M,S,M,G
  • A,M,S,M,M
  • A,M,S,M,S
  • A,M,S,S
  • A,S,S,S
  • G,A
  • G,A,G
  • G,A,M,G
  • G,A,M,M
  • G,A,M,S
  • G,A,S
  • G,G
  • G,M,A
  • G,M,G
  • G,M,M,A
  • G,M,M,G
  • G,M,M,M
  • G,M,M,S
  • G,M,S,A
  • G,M,S,G
  • G,M,S,M,A
  • G,M,S,M,G
  • G,M,S,M,M
  • G,M,S,M,S
  • G,M,S,S
  • G,S
  • M,A
  • M,G
  • M,M,A
  • M,M,G
  • M,M,M
  • M,M,S
  • M,S,A
  • M,S,G
  • M,S,M,A
  • M,S,M,G
  • M,S,M,M
  • M,S,M,S
  • M,S,S
  • S,A
  • S,G
  • S,M
  • S,S,A
  • S,S,G
  • S,S,M
  • S,S,S,A
  • S,S,S,G
  • S,S,S,M
  • S,S,S,S

Want to Know How I Figured It Out?

How do I know that there are 1,602 total combos? How do I know that 60 of them are required for the “Combo Specialist” achievement/trophy? I wrote a software program to figure it out for me!

That’s right. I could not find a definitive list anywhere on the Net. The official game guide does not even list the exact combos necessary to get the award.

You can read about the program that I wrote on CodeProject.com. If you’re just interested in the code that calculates this award, look near the end of the Contents at the beginning of the article. You can see some very cool screenshots of the application too. Hey, while you’re there, vote me a 5 if you like it!

Save the Developers Lost to Microsoft?

on January 5th, 2009 by Matt

Save the Developers was a site dedicated to educating Web surfers about the tremendous failings of Microsoft’s Internet Explorer browsers. The site sported a free “badge” for Web developers and webmasters to include on websites to spread the word. “The word” being that Internet Explorer versions prior to 8 ignore all standards for HTML and CSS (the markup used by Web developers to create webpages). Ultimately, users were pleaded with to upgrade  to version 8 beta; at least leave version 6 behind and move on to version 7.

So, why all the past-tense in my explanation above? Well, the Save the Developers website (savethedevelopers.org) now redirects to Microsoft’s website for Internet Explorer 7 and 8 beta. At first, one might assume that Microsoft bought the domain for the website and issued the redirect themselves. However, I’m not so sure about that upon some digging.

A whois query for microsoft.com reveals that the owner of that domain is Microsoft Corporation; no surprise there. However, a whois for savethedevelopers.org (and .com) shows the owner to be Conveyor Group. There is only a month left before the domains expire, so who knows. Maybe they succumbed to the financial power of Microsoft.

The preceding is the opinion of the author(s) and is not intended to malign any religion, ethnic group, club, organization, company, or individual. The views of the writer are his own, and do not in any way reflect the views of the site they are posted on, other sites affiliated with this site, the staff involved with the site, or any other members of this site. For more information, review the full Terms of Use for this site.