SessionItem class to deal with Session objects


What do you think of this code?  Essentially I can do things like this:

SessionItem<int> myId= new SessionItem<int>("myId");
            if (myId.Exists)
            {
                user = new User(myId.Value);
            }

and

            myId.Value = int.Parse(Grid.DataKeys[row.RowIndex].Value.ToString());

for session objects.  Code is:

using System;
using System.Web;

namespace Utils
{
    public class SessionItem<T>
    {
        private string key = string.Empty;

        public SessionItem (string key)
        {
            this.key = key;
        }

        public bool Exists
        {
            get
            {
                object value = HttpContext.Current.Session[key];
                return value != null;
            }
        }

        public T Value
        {
            get
            {
                try
                {
                    object value = HttpContext.Current.Session[key];
                    return (T)value;
                }
                catch
                {
                    throw new Exception(string.Format("No session value with a key \"{0}\" exists.", key));
                }
            }
            set
            {
                HttpContext.Current.Session[key] = value;
            }
        }
    }
}

author: Willie | posted @ Wednesday, November 19, 2008 10:59 AM | Feedback (0)

SQL and Code Completion


It seems that perhaps the SQL syntax people weren't thinking about code completion (or intellesense) when coming up with the language.

Typing in a SELECT will give you nothing, because you selecting from what?  Once you have the FROM tableName statement then you could go back to your select and specify column names but what a pain.  Maybe the SQL syntax should have looked like this:

FROM tableName

SELECT columnName, anotherOne

WHERE columnName = 'me'

Maybe the LINQ people saw this issue too so that's why they have it switched?  Makes more sense to me.  I wonder why no one has thought to switch it around, or have they?

author: Willie | posted @ Monday, November 17, 2008 12:35 PM | Feedback (1)

Is this missing in ASP.NET MVC or what?


The ability to send data to the server and then display the same view that you were on.  In ASP.NET it was extremely simple to do this, just have an event driven method that did some logic, with no redirect.  With the MVC flavor it seems that with each action I need a new view to go with it?  Is this just a change in my thinking or am I missing something?

For example, I have a list of comments on a thread (in a blog or forum or...).  Right now I'm viewing the thread with the comments and I have a box below that says reply.  I'll take in comments, the person's user name in a controller and then...I have to display a new view or...why can't I wrap my head around this?

Does the controller also have to take in the current view name and threadId that I was viewing so that I can show the correct view?  Seems kinda wierd...

author: Willie | posted @ Sunday, November 16, 2008 11:20 AM | Feedback (2)

Small Steps to Coding Better Part 2: Eliminate comments from your code


I remember back in college my coding teachers would tell me that coding was a good part of a balanced breakfast.  It would help those that happened to have to work on your code in the future.  Most likely, that particular coder would have been you, so...comment well!

After coding for years now, I have to say I disagree.  I've been over commenting the crap out of code in the past when I really thought I was being helpful (I used to swear by GhostDoc and nDoc stuff...).  The problem resides in that code is changeable, and so when a specific code portion is changed we break the DRY principle because we have to update our comments as well.  Instead of repeating ourselves, lets make our code cleaner by removing all comments that don't show a thought process, buuuuut also in the same stroke keeping the readability that makes those verbose like comments so helpful in there.

It's a fairly simple process, that just takes a few days in adjusting your thinking while coding.  For instance here's what my code used to look like:

 

   1:        else // Show list of all  things in widget
   2:        {
   3:          if (!Page.IsPostBack)
   4:          {
   5:            BindGrid(string.Empty, 0);
   6:          }
   7:   
   8:          ExistingMonitorFiles.Visible = true;
   9:          ProcessMonitorFile.Visible = false;
  10:        }

and after:

   1:  else
   2:              {
   3:                  ShowListOfAllThingsInWidget();
   4:              }

What I've done here is simply take the comment I had, and refactor it into a method that contains the prior code.  Simple enough?  Instead of a comment, now I have a viable piece of code. If I do modify it, I will have to update the method name, which will in turn update all of those areas that are calling it, in essence updating the "comment".

One more example that comes up a ton, and you might not agree with at first:

if (ResultID != null) // Show results

To remove this comment I'll need to add a new boolean type, like so:

bool showResults = ResultID != null;

if (showResults)

Now, I hate adding extra lines to my code as much as the next guy, but this effectively gives us a valid in code "comment" that we can update a lot easier, and you'll find that you won't be testing for this again down the road because now showResults has way more meaning than ResultID != null.

Try it out, it's a mild switch in thinking while you're coding but in the end I think well worth it.

author: Willie | posted @ Tuesday, November 04, 2008 4:00 PM | Feedback (1)

Small Steps to Coding Better Part 1: Region commands, and why you should avoid them


As I get farther along in my goal for better coding I've started to notice something.  When before I've utilized the pre-processor region command I notice bad design.  Before, I thought I was being tidy by at least visually grouping elements of a class into a certain section of the code.  Very rarely though, does this make sense (the one place I can think of is still in the code behind for WebForm aspx pages [I typically have something like Properties, Events, Private Methods]).

If you finding yourself wanting to put region commands around a section of code, start to ask yourself, could this be it's own class?   What it comes down to is the single responsibility principle and when you are adding region commands you aren't following it.

author: Willie | posted @ Thursday, October 30, 2008 11:15 AM | Feedback (0)

Silverlight ArrayOfXElement Error


Trying to use web services with Silverlight and getting this error?  Most likely your asmx web service is returning data using DataSets and guess what...Silverlight no likey the DataSet.  Either modify them to use DataTables or you going to be doing some hand editing of the service code the reference pooped out.

author: Willie | posted @ Wednesday, October 22, 2008 11:05 PM | Feedback (0)

Recent Projects not Populating


Chances are your recent documents are turned off.  For some reason these two are tied together.  Open up regedit:

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer

and change the NoRecentDocsHistory to 0, most likely right now it's a 1.

Fixes for both 2005 and 2008 IDEs.

author: Willie | posted @ Monday, October 20, 2008 5:25 PM | Feedback (0)

Combining a dll and an exe into one exe file


I had a console app that used an external dll to zip files up.  The app worked great.  For the program to work properly it required both the files.  I wanted to just have the one exe with no dll.  My first search gave me some pay for utility (yucky) and then Bill saved the day once again by suggesting ILMerge.

I used ILMerge in the "Post-build event command line" box in my project settings like so (notice that you do indeed need to keep the quotes because of spaces in the path):

"c:\Program Files\Microsoft\ILMerge\ILMerge.exe" /wildcards /log:ILMerge.log /out:"$(TargetDir)JabuC.exe" "$(TargetPath)" "$(TargetDir)Ionic.Utils.Zip.dll"

This outputs what I wanted, one JabuC.exe that has the Ionic.Utils.Zip.dll included in it.  Presto!

author: Willie | posted @ Friday, September 19, 2008 9:19 AM | Feedback (1)

Sorting a List


I came across a different requirement today, I need to sort some objects in a certain order that wasn't alphabetical or numerical.  I looked towards SQL for a few minutes and found zilch that could help me with ORDER BY shinanigans.  I could have done multiple queries and then merged the results, but that would be pretty messy.  I ended up using Sort(), which I used before, but never to do anything more than a simple sort.

Consider that I have the following Employee objects with a Name and Position property like:

Joe, President

Frank, Vice President

Bob, Developer

that need to be sorted in that order.  Obviously sorting alphabetically wouldn't work so what to do?

Sort to the rescue!

Employees.Sort(CompareEmployeesByPositionInCompany);

with CompareEmployeesByPositionInCompany looking like:

private static int CompareEmployeesByPositionInCompany(Employee x, Employee y) {
            int xSortValue = GetSortValue(x.PositionInCompany);
            int ySortValue = GetSortValue(y.PositionInCompany);
            const int before = -1;
            const int same = 0;
            const int after = 1;

            if (xSortValue == ySortValue) {
               return same;
            }
            if (xSortValue < ySortValue) {
               return before;
            }
            return after;
         }

private static int GetSortValue(string value) {
            if (value == "President")  return 1;
            if (value == "Vice President") return 2;
            if (value == "Developer") return 3;

}

author: Willie | posted @ Tuesday, August 12, 2008 2:08 PM | Feedback (0)

Update Table with column and default value


When updating a table with a new column first I'd do something like:

alter table myTable add isGreat bit null

then fill that column with a value like so:

update myTable set isGreat = 0 where IsConfirmed IS NULL

Turns out there's a shortcut to that sucker:

alter table myTable add isGreat bit null default 0 with values;

author: Willie | posted @ Thursday, August 07, 2008 12:11 PM | Feedback (1)