State List in Dictionary Form

Tired of having to look this up from time to time, so I’m putting this here for my own use. If you get something out of it, good for you. In the end, I really don’t care.

    public Dictionary GetAllStates()
    {
      if(_stateList == null)
      {
        _stateList = new Dictionary();

        _stateList.Add("Alabama","AL");
        _stateList.Add("Alaska","AK");
        _stateList.Add("American Samoa","AS");
        _stateList.Add("Arizona","AZ");
        _stateList.Add("Arkanas","AR");
        _stateList.Add("California","CA");
        _stateList.Add("Colorado","CO");
        _stateList.Add("Connecticut","CT");
        _stateList.Add("Delaware","DE");
        _stateList.Add("District Of Colombia","DC");
        _stateList.Add("Federated States Of Micronesia","FM");
        _stateList.Add("Florida","FL");
        _stateList.Add("Georgia","GA");
        _stateList.Add("Guam","GU");
        _stateList.Add("Hawaii","HI");
        _stateList.Add("Idaho","ID");
        _stateList.Add("Illinois","IL");
        _stateList.Add("Indiana","IN");
        _stateList.Add("Iowa","IA");
        _stateList.Add("Kansas","KS");
        _stateList.Add("Kentucky","KY");
        _stateList.Add("Lousiana","LA");
        _stateList.Add("Maine","ME");
        _stateList.Add("Marshall Islands","MH");
        _stateList.Add("Maryland","MD");
        _stateList.Add("Massachusetts","MA");
        _stateList.Add("Michigan","MI");
        _stateList.Add("Minnesota","MN");
        _stateList.Add("Mississippi","MS");
        _stateList.Add("Missouri","MO");
        _stateList.Add("Montana","MT");
        _stateList.Add("Nebraska","NE");
        _stateList.Add("Nevada","NV");
        _stateList.Add("New Hampshire","NH");
        _stateList.Add("New Jersey","NJ");
        _stateList.Add("New Mexico","NM");
        _stateList.Add("New York","NY");
        _stateList.Add("North Carolina","NC");
        _stateList.Add("North Dakota","ND");
        _stateList.Add("Northern Mariana Islands","MP");
        _stateList.Add("Ohio","OH");
        _stateList.Add("Oklahoma","OK");
        _stateList.Add("Oregon","OR");
        _stateList.Add("Palau","PW");
        _stateList.Add("Pennsylvania","PA");
        _stateList.Add("Puerto Rico","PR");
        _stateList.Add("Rhode Island","RI");
        _stateList.Add("South Carolina","SC");
        _stateList.Add("South  Dakota","SD");
        _stateList.Add("Tennessee","TN");
        _stateList.Add("Texas","TX");
        _stateList.Add("Utah","UT");
        _stateList.Add("Varmont","VT");
        _stateList.Add("Virgin Islands","VI");
        _stateList.Add("Virginia","VA");
        _stateList.Add("Washington","WA");
        _stateList.Add("West Virginia","WV");
        _stateList.Add("Wisconsin","WI");
        _stateList.Add("Wyoming","WY");
      }

      return _stateList;
    }

So there. Hope you’re happy.

What I Hate About Programming

Lately I have been screwing around with creating a blog framework using MVC and jQuery, the former being more troublesome from a design stand point. For example, The use of controllers and actions can cause a great deal of second guessing. Do I put all the admin view attached actions, like one for viewing a list of posts to select and edit, on an Admin controller? Do I have a Post Admin Controller and a Comment Admin Controller? Should anything having to do with Posts be on one Post controller and just seperate the actions based on attributes? (As in MustBeAdminAttribute as opposed to MustBeLoggedIn) After all controllers are about grouping things, but how the h— should they be grouped? Of course, that’s a sort of gray area an subject to debate. The problem is I can’t help but think not matter what, I’m making the wrong choice. Why? Mostly because I know I’m not a super programmer.

Now this isn’t going to be an Atwood, back patting, I’m so good I know I’m bad kind of post but something has really occurred to me more and more lately. As I’ve gone deeper and deeper into things like Entity Framework, MVC, and jQuery I’ve only been left with the feeling that someone else, somewhere is doing this a lot better. Maybe it’s because my lack of experience with them, maybe it’s just a self depreciating nature thing, but it’s also having access to too many good programmers due to the plethora of them on the internets. Yeah right, that’s a bad thing? Well it kind of is. It’s tough doing anything anymore when you know there are people far better than you doing a far better job. And with the advancement of information sharing, you can’t help but find proof of that. With that comes a certain guilt that you aren’t the top of the food chain and in fact you just might be a programmer the other better people complain about. That’s right, you. Someone at this very moment is straight up banging his/her head against a desk because of something you wrote.

Some would suggest this is the sign of a good programmer. Someone who is never completely happy with his/her performance. F— that, it just plain sucks and makes what can be enjoyable an epic pain in the a–. No one wants to be that guy, you know the one that names every variable with numbers (v1 + v2 = v3) or has one gigantic method that does everything. Problem is, this is all relative. One person’s perfection is another guy’s multi purpose stored procedure that runs 10 different query using a switch and a passed in string. Code perfection is in the eye of the beholder. And by now we all know there are plenty of high end beholders.

What does that mean? You can never win at the game of programming. Read it again. You can never win at the game of programming. That is unless you are beyond a doubt the sharpest bulb in the bunch. For the rest of us chumps, it’s grin and bear it time.

That’s it. That’s the answer. Suck it up. Don’t like that answer? Refer back to the answer. Fact is, you’ll never be perfect and if you were, chances are you wouldn’t be reading this nonsense. You’d be out in the middle of the Gulf of Mexico kicking it back on some island you own. For the rest of us mortals (Or dumb immortals), it’s time to join the Tool Fiesta. Start dancing, drinking, and accepting. I’m not saying that you can’t better yourself. Hell maybe you’ll be one of the top people out there… and optimistically thinking, considering this site, maybe you are (What the hell are you doing here though?). But you aren’t going to be perfect and neither is your code. However, sitting around and worrying about producing perfect code is just sitting around. Have to figure some code is better than no code at all right? Just lie to me.

jQuery Whack-A-Mole… Timer, Hide, Slide, and Fun

So I’ll just straight up file this under “I really shouldn’t have” and not bother asking for forgiveness. For some reason I had it in my mind I wanted to see if I could take the stuff I learned from this guy and this guy and see if I could make a simple Whack A Mole game with just jquery and the three include files. (jquery, jquery UI, and jquery Timer) Not thinking of the massive consequences such a thing might bring, I pushed on in the name of science.

So with no further build up or stupidity (I used that all up in building this game) I give you jQuery WHACK A MOLE which oddly enough has somehow clawed it’s way into my hosting here. So if you’re foolish enough to actually want to know how it works, there are plenty of comments in the script files. Just don’t blame me for any loss of intelligence.

I might actually take this to the next horrifying level and make it an mvc application. Not sure I… no… THE WORLD can take it.

Programmer: Hero to All or Digital Masochist?

Ok so it hit me the other day when I was asking myself why I program. Basically I’ve hit that point in my career where I am starting to re-evaluate what the s— I’m doing and why I’m doing it. Actually it was more like me lamenting over my current path and I came to the conclusion that if I didn’t program for a living, I’d still do it as a hobby. To this the woman asked, “If you like it as a hobby, why do you hate programming?” This got me to thinking, do I hate this all the time? And the answer is no. I think this overworked bin of waste I call a blog is a testament to what I do love about programming. You know, the new stuff. The discovery. And yes (And you know it) the elation and self pleasing like act of “Yeah, I figured that out. I’m f—ing smart and stuff.” I even like the building and designing of systems (Well the non UI part since I have a restraining order that doesn’t allow me to be within 50 feet of UI design). Actually I really like that stuff.

Here’s the bad. When do I actually get a chance to do that? When do most of us ever get to do that? Problem is that most programming jobs don’t entail this. How do I know this? Well in my short 8 or so year career, I’ve had a lot of programming jobs. 9 to be exact. And about eh 50+ interviews with companies. So basically like a follower of “free love”, I’ve been around. In those jobs and interviews I’ve had 1 job and 3 possible ones where I wouldn’t have just been either:

  1. Maintenance Boy
  2. Legacy Avenger

Now you might think it’s because I suck. Well that could be a reason, but that would imply that the people I’ve worked with sucked since they were stuck doing the same thing, regardless of their experience. I can’t believe everyone I’ve worked with sucked, but I have no real proof. Then again, this isn’t being submitted to Fox New– eh The New York Ti– eh some scientific journal.

So with this I’m going out on a limb here and going to guess that the people not in the top 15% of the programming world are stuck doing tasks that involve:

  1. Updating old code
  2. Fixing old code
  3. Adding to old code
  4. Creating new things but under old standards and frameworks
  5. Spending time trying to figure out a web of stored procedures so complicated it would make Brian Greene spin. (His ENTIRE body)

And people do this everyday and a lot of them bitch about it but when pressed wouldn’t want to do anything else. Why? Because we hate ourselves! It’s simple f—ing psychology. When you hate yourself, you do things to keep that feeling of hate alive. You will be drawn to people who most likely cause us grief. You will be drawn to a job that causes pain. Think about it:

  1. In most companies, IT is the lowest rung on the ladder.
  2. People have no idea what we do which leads to horrible deadlines. Read: “It won’t take that long, it’s just HTML.”
  3. We work on systems that we didn’t build and the people who came before us didn’t have a lot of concern about someone else having to work on it.
  4. The stuff we work with can be really expensive and therefore most companies are years behind on IDEs, frameworks, ect
  5. In the high school we call the workplace, we’re basically the kid taped to the goal post.

And the best part is we’re described as problem solvers, which means right off the bat our job consists of cleaning up someone else’s f— ups or we’re expected to figure out the things that some committee of tool bags couldn’t get their collective head around.

I mean what sane person does this willingly? You know what the kicker is? We get some crazy high from when we actually do pull off some crazy impossible. Tell me how is that different than getting some kind of high after running a blade down your arm? We get pleasure from pain. That is our existence. We are sick puppies.

I’m hungry.

ConfigurationManager And AppSettings… A Wrapper Class Story

You can file this under “Do I really need this?” but for now I kind of like it. That, however, may change in the next hour.

The idea is simple, create a class that uses the ConfigurationManager AppSettings NameValueCollection (Triple Combo!) but only presents properties that represent the keys in the .config file. This way there is no guessing of how the key is spelled or that that type returned is converted to something it should be. (Say you have a numeric value in the .config file) Now this doesn’t seem like a big deal, but I’m not happy with something that is just simple like:

    public String SomeKey
    {
       get
       {
          return System.Configuration.ConfigurationManager.AppSettings["SomeKey"];
       }
    }

Oh no, that’s just not good enough. Call it divine intervention. Call it spontaneous brilliance. Call it whatever the guy that invented the corn dog had. But what I came up with is far better. (And by better I mean more complex)

Remember, the idea isn’t to have to grab just the value from System.Configuration.ConfigurationManager.AppSettings but also to have it be typed on the way back. Now we know this to be true: I am awesome. What we also know to be true is that the value held in the appSettings area of the .config file is going to correspond to a value type but is going to be read in as a string. If you’ve read some of my posts (Which I assume you haven’t), you might have stumbled upon this little gem and know that I already have something to convert from a string to pretty much any value type. (Those having a TryParse method) So the converting part is already done, but what about the getting?

    protected static T? GetValueFromConfiguration<T>(String key) where T : struct
    {
      T? returnValue = null;
      if (System.Configuration.ConfigurationManager.AppSettings[key] != null)
      {
        returnValue = System.Configuration.ConfigurationManager.AppSettings[key]
                           .ConvertTo<T>(); //MY AWSOME CONVERTTO METHOD!!11
      }

      return returnValue;
    }

Ok so you can see, this is really simple. I check to see if the key exists, get the value from the .config file, and convert to whatever I said it should. In use this would be:

    public static DateTime? TestDate
    {
       get
       {
          return GetValueFromConfiguration<DateTime>("TestDate");
        }
      }

Now you might have noticed something about this… yes besides the fact that it’s Mentos fresh. First, the method returns nullable versions. The reason for doing this is you really don’t know what the value will be in the .config file. Say this was an integer and you returned just a normal integer. (Non nullable) What would you set the value to? Sure you could do minimum value but COULD mean that there was a value in the .config file. This is more of a design choice though.

Second is that the method doesn’t cover strings. This is an ouch due to how nullables and strings work. You can’t return a nullable string since string doesn’t fit in the non nullable value category. This is a real pain but easily overcome with a non generic overload:

    protected static String GetValueFromConfiguration(String key)
    {
      String returnValue = null;

      if (System.Configuration.ConfigurationManager.AppSettings[key] != null)
      {
        returnValue = System.Configuration
                           .ConfigurationManager.AppSettings[key];
       }
       return returnValue;
    }

See? Easy way to side step the problem. There might be a better way to handle that, but not sure at this point. Something to revisit I suppose. Oh and here’s the whole class for the hell of it:

    public class BaseConfigurationManager
    {
       private const String SOME_KEY = "SomeKey";

       protected static T? GetValueFromConfiguration<T>(String key) where T : struct
       {
         T? returnValue = null;

         if (System.Configuration.ConfigurationManager.AppSettings[key] != null)
         {
           returnValue = System.Configuration.ConfigurationManager.AppSettings[key]
                         .ConvertTo<T>();
         }

         return returnValue;
       }

       protected static String GetValueFromConfiguration(String key)
       {
         String returnValue = null;

         if (System.Configuration.ConfigurationManager.AppSettings[key] != null)
         {
           returnValue = System.Configuration.ConfigurationManager.AppSettings[key];
         }

       return returnValue;
     }

     public static String SomeKey
     {
       get
       {
         return GetValueFromConfiguration(SOME_KEY);
       }
     }

    }

Oddly enough I spelled “spontaneous brilliance” correctly the first time around but thought “numeric” had a silent ‘b’. Go figure. Should have finished middle school.

By Reference in C# and How to Get Schooled By It

WARNING: If you understand The concept of By Reference, skip the first part of this post:

So you have an object, huh? Ok well what does that mean? Basically there is a stack and a heap. When you declare an object, space is made on the stack, basically it’s a placeholder saying that there will be something to point.

    User someUser;

Now when you instatiate:

    someUser = new User();

That user Object is put on the heap and that placeholder (reference) on the stack? Well it’s given a pointer which SURPRISE points to the object on the heap. Now when you pass the object into the method, you aren’t really passing what’s on the heap. You are actually copying and passing the pointer. Inside the method, a new entry is thrown on the stack that points to the same object on the heap. This way if you change anything on the object in the method, the changes are reflected outside the method. (Say if you added items to a list in the method) Now this all changes if the object inside the method is reinitialized or repointed:

    SomeMethod(User user)
    {
        user = new User();
        user.UserName = "Sean";
    }

Remember that user we passed in? It now has nothing to do with the one in the method now. There is now a new object on the heap and “user” in the method now points to it. Why did I tell you all of this?

END REFERENCE EXPLANATION:

Say you have this:

    ...

    UserList userList = new UserList();
    SomeList list = new SomeList();
    FillListFromUserList(list, userList);

    ...

    void FillListFromUser(SomeList listToCopyTo, UserList userList)
    {
       foreach(User currentUser in userList)
       {
          listToCopyTo.Add(userList);
       }
    }

Easy, and basically at this point list should have the same items as userList. Now say list needs what’s in userList but in order by UserID. Suppose you did it like this:

    void FillListFromUser(SomeList listToCopyTo, UserList userList)
    {
       foreach(User currentUser in userList)
       {
          listToCopyTo.Add(userList);
       }

       var sorted = from user in userList
                    orderby user.UserID
                    select user;

       listToCopy = sorted.ToList();
    }

Ok so a quick check to see if list now contains items will show it does. Now say you looked at this method and thought it was a little more than needed. You decide to do this:

    void FillListFromUser(SomeList listToCopyTo, UserList userList)
    {
        listToCopyTo = userList.OrderBy(user => user.ID);
    }

Now a quick check to see if list has something in it shows that it doesn’t. But wait, what the hell? The first one worked and the second is just short hand right? Eh well the problem is how objects are passed. By reference means that it doesn’t pass the original pointer from the stack but it copies it so that there are two references on the stack that point to the same object on the heap. What does this all mean? Well both

    listToCopy = sorted.ToList();
 And
    listToCopyTo = userList.OrderBy(user => user.ID);

Have now reset the pointer for the reference in the method (listToCopyTo) making it no longer have anything to do with the list outside of it (list). The reason why it gave a false positive on the first one was that I had added to the list within, and therefor to the object the list outside points to. So the changing of the pointer:

    listToCopy = sorted.ToList();

would no longer affect the list oustide. However, in the second example I never added to the object they both pointed to before I changed the pointer on the inner. Hense why the second example had nothing in the outer list. To make matters worse I would have noticed this before if the original userList hadn’t been sorted by ID already.

Another removing Lambda “trick”

And by trick, I mean I was too slow to realize that:

  someDictionary.Add("Hi", (Boolean doThis) => SomeMethod(doThis));

Can be done this way:

  someDictionary.Add("Hi", SomeMethod);

Where the dictionary is:

  Dictionary<String, Action<Bool>> someDictionary;
  someDictionary = new Dictionary<String, Action<Bool>>();

And SomeMethod is:

void SomeMethod(Boolean doSomething)
{
  //Something is to be done!
}

Which as far as I know, removes a step from the whole process. What does that mean? Well if you break the first one down into an anonymous method, it would look like this:

  someDictionary.Add("Hi", delegate(Boolean doThis){ SomeMethod(doThis); });

I am assuming this would create a reference to a completely new method as opposed to the second example which just uses the already existing method’s reference. Fun yah?

Static Abstract … should I bother?

So it came up recently that someone was bummed that you can’t create a static abstract method. Now conceptually, this is blocked by C# but I came up with this “work around”… And I have no idea if I would ever use it. This was more of a “Do it because I can” rather than “Do it because I should.”

  public abstract class Parent
  {
    public abstract String ReturnAValue(String returnThis);

    public static String ReturnAValue(String returnThis) where K : Parent
    {
        K classToCreate;

        classToCreate = Activator.CreateInstance();
        return classToCreate.ReturnAValue(returnThis);
    }
  }

So what I did here was create a parent class that causes any child to override the ReturnAValue method so that I could create a static method on the parent that basically would just instantiate the child class and call the overridden method. How’s that for a run on sentence?

  public class ChildA : Parent
  {
    public override String ReturnAValue(String returnThis)
    {
        return "ChildA " + returnThis;
    }
  }

And this in full use:

  String testReturn;
  testReturn = Parent.ReturnAValue("returned");

Can you guess what that returns? If you can, you’re special. You might wonder why I have to use generics in this. Well I mean you could do this:

    public static String ReturnAValue(Parent returnThis)
    {
        return returnThis.ReturnAValue(returnThis);
    }

But that assumes you have to instantiate the child and pass it in.

Now the main problem with this, beyond the fact that you’ll probably never use this, is Activator.CreateInstance() need a default public constructor to use. Kind of a catch.

Convert a String to a Number String With Linq… YAY

Really stupid little thing I came up with today… but I wanted to use Linq to strip any non number from a string and return the string with only numbers. I told you this was a stupid little thing.

public static String CreateNumberOnlyString(String textToCheck)
{
  String returnText;

  var queryForIntegers = from currentChar in textToCheck
                         where Char.IsNumber(currentChar)
                         select currentChar;

  returnText = new String(queryForIntegers.ToArray());

  return returnText;
}

I are tupid

This may be novel or really dumb, but I like it. Say you want to convert a Dictionary to a List of KeyValuePairs that are sorted by something within the dictionary Key or Value. Don’t ask why, just go with it. You could do this:

Where someDictionary is Dictionary<Type, string> :

List<KeyValuePair<Type, String>> dataSource = new List<KeyValuePair<Type, String>>(someDictionary);
dataSource.Sort(new SomeComparer<KeyValuePair<Type, String>>("Value", true));

To:

var query = from keyValuePair in someDictionary
          orderby keyValuePair.Value
          select new KeyValuePair<Type, String>(keyValuePair.Key, keyValuePair.Value);
SomeMethod(query.ToList());

If nothing else, you don’t have to create or implement a System.Collections.IComparer class to use the .Sort method. That seems worth it. That and I think it just plain looks better, but that just me. If I am completely wrong here, refer to the title of this post. Just a thought really.