Welcome

You have reached the blog of Keith Elder. Thank you for visiting! Feel free to click the twitter icon to the right and follow me on twitter.

Fried Bologna Sandwich

Posted by Keith Elder | Posted in Food | Posted on 15-12-2007

image I was reminded the other day about something I used to eat when I was growing up during a conversation with a friend.  It has been years, heck, a decade and then some since the last time I had a fried bologna sandwich. 

Growing up I considered it a delicacy.  The taste and satisfaction it brought was only equaled to that of a Hot Fudge Sundae (with no nuts).  How I forgot about this beloved treasure I have no idea.  Maybe age and the pursuit of other foods made me forget.  It is time to get back to the basics though.

Bologna Background

For those that find the thought of fried bologna a little weird we need to first understand what it really is made of and how it is made.  Bologna is actually a smoked sausage made of cured beef, pork, turkey or a combination thereof.  That’s right, it is considered a sausage.  At the factory it is made into a puree so it can be molded into different shapes and then sliced.  Everyone that eats sausage understands that sausage is fried before eaten.  Thus, since bologna is actually sausage, it should no longer come as a shock that bologna can be fried.

Bologna is also a great sandwich meat although many consider it the bottom dweller of meats because it isn’t a pure cut meat like ham, or turkey.  A lot of people refer to it as a “government” meat since the government provided it to those on welfare years ago. 

Best User Experience

imageThe best way to buy bologna is not to go to the store and buy a small pack.  To really experience a fine bologna it must be purchased in bulk.  Typically a Sam’s Club or Costco sales it by what is called the “stick”.  Normally a stick will weigh about 5lbs.  While it is a lot of meat, if kept refrigerated it will keep for a long time.  Bryan bologna has been around in the South for years and it is the first choice usually selected.  Another benefit of purchasing by the stick is it isn’t sliced.  This allows for varying degrees of thickness when sliced and allows it to serve different roles easier.

Ways To Eat Bologna

image

Fried Bologna Sandwich

The very first and best way to eat bologna is to fry it and eat it on a sandwich.  For the best flavor use a cast iron skillet.  Really for any meat that is going to be fried it should be cooked in a cast iron skillet.  If slicing your own bologna from a stick, do not make your cuts too thick.  When frying bologna it should be thin.  The perfect thickness when slicing your own is slightly less thick than a store bought pack of bologna.  Once cut to the proper thickness, slice bologna in the middle to make two halves. 

Unlike sausage, you must add a small amount of oil to the skillet.  This will keep it from sticking.  As the bologna cooks it will bubble up in the center.  If the skillet is hot, cooking time will be relatively quick so don’t put it in the skillet and walk away.  To get the perfect flavor of fried bologna I prefer it to be cooked to where there are charred markings on the bologna.  It shouldn’t be completely black when cooked, but it should have some black markings on it. 

Once the bologna is cooked, take two pieces of bread either toasted or plain and place several slices of bologna onto one side.  Then grab a jar of mustard and add several teaspoons.  That’s it, you are ready to eat!  I’ve had people ask me, why do you use mustard only?  The reason is it just tastes the best with the fried bologna.  Mayonnaise or other dressing do not work near as well with fried bologna, and neither does adding other things like tomatoes or pickles.  There is plenty of flavor in just the fried bologna so there is no need to dress it up anymore.

Traditional Bologna Sandwich

A traditional way to eat bologna is on a sandwich.  Bologna has such a strong flavor that it isn’t wise to mix it with other meats.  This is why delis do not offer turkey, ham, roast beef and bologna sandwiches.  The bologna is so rich and powerful it will overtake the flavor of the other meats.  This is why bologna should be eaten and served by itself. 

To fix a bologna sandwich it is simple.  Use one or two slices of bologna, miracle whip salad dressing or mayonnaise (depending on which one you prefer), and a slice or two of tomato.  While a slice of cheese can be added choose wisely.  About the only type of cheese that can take bologna head on is a sharp cheddar.  Anything else and it diminishes the flavor combination of the mayonnaise and the tomato and also gets in the way of the bologna.  Again the bologna provides plenty of flavor on its own.

Bologna, Cheese and Crackers

When I was a child growing up during the summer, one of the most anticipated days I looked forward to in the week was Tuesday.  Every summer I use to ride along with my Father and help him on his Pepsi Cola route.  It was hard work but I got to meet a lot of people and learned the art of salesman ship and the gift of gab from my Father.  Tuesday was the day we went to a country store outside of Ripley, MS called Curtis’s.  Curtis, the owner, had a store between Ripley and Booneville on HWY 4 that served the community.  It was a quaint country store with hardwood floors, a small meat counter where meats were sliced, and rows of candy.  Curtis was a supper nice guy and I enjoyed stopping into his store because that meant we got to eat.  We always got to Curtis’s store around lunch time. 

For lunch some days we’d have Curtis fix us a sandwich.  He’d slice a big piece of bologna from a stick and then other days we’d have him just slice a really thick slice of bologna, a thick slice of sharp cheddar cheese, and pick up a few packs of crackers.  When I mean thick slices, I mean thick.  Like a 1/4 lb slice of each. 

Hunters, fishermen, and explorers today are known to carry bologna, cheese and crackers because it stores easily, is quick to grab a quick bite, filling, easy, and requires no tools or utensils to eat.  The next time you go canoeing, camping, fishing, or hunting, give this a try, you’ll be glad you did.

How To Load an Embedded Resource From A DLL

Posted by Keith Elder | Posted in .Net | Posted on 14-12-2007

When developing class libraries in .Net there are times we utilize XML files to store static information or icons and bitmaps associated with components in our class libraries.  During the build process we have several build actions to choose from that allow us to handle different scenarios.  For icons used in components or static XML files it makes a lot of sense to package those files into the DLL so they can go along for the ride.  We call this an embedded resource. 

For those that are curious the .Net framework has a lot of embedded resources.  For example have you ever wondered where an icon came from after you dragged and dropped a component onto the designer?  Take the BindingNavigator that has icons for next, previous, delete, save, etc.  Those are all embedded within the DLL.  This is great because a developer just adds the one DLL to the project and it works.  No other files need to be added to the solution in order to make the component it work.

If you have a common or standard library that reads a lot of static information from XML files or text files, consider packaging those files as an embedded resource within the DLL.  This way when a user adds your DLL to their project they don’t have to even think about where it is getting its data.  It is already in the DLL.  Let’s look at an example of how this is done.

Embedding Our Data

I created a sample console application and I added an XML file into my solution which holds southern states.  Here is the file:

<?xml version="1.0" encoding="utf-8" ?>
<
SouthernStates>
<
State>
<
Name>Mississippi</Name>
<
Abbreviation>MS</Abbreviation>
</
State>
<
State>
<
Name>Tennesse</Name>
<
Abbreviation>TN</Abbreviation>
</
State>
<
State>
<
Name>Arkansas</Name>
<
Abbreviation>AR</Abbreviation>
</
State>
<
State>
<
Name>Louisiana</Name>
<
Abbreviation>LA</Abbreviation>
</
State>
<
State>
<
Name>Georiga</Name>
<
Abbreviation>GA</Abbreviation>
</
State>
<
State>
<
Name>Florida</Name>
<
Abbreviation>FL</Abbreviation>
</
State>
</
States>

Obviously this information isn’t going to change anytime soon so I can sleep at night knowing this information really doesn’t have to be dynamic and be read from a database.  Here is what my solution in Visual Studio looks like:

image

Right clicking on the SouthernStates.xml file within the project and selecting properties we see the file will be treated as standard content during the build process and will not be copied to the output directory (debug or release). 

image

To make this an Embedded Resource all we have to do is change the “Build Action” to “Embedded Resource”.

image

Now if we do a build on our project and look at the debug folder we only see our host executable along with the EmbeddedResource.Library.dll, and no SouthernStates.xml file.  To check if the XML file is in the DLL open a plain text editor and open the DLL the file was embedded in.  The file embedded should be able to be viewed in plain text with the editor.  Here’s a screen shot using Notepad++.

image

Accessing the Embedded Resource

Embedding the XML into the DLL is the easy part!  The question is how to get this data out so it can be accessed.  It isn’t that hard really.  About two lines of code using Reflection to get the data is all that is needed.   Since this example is using state related information I decided to build this example using a strong typed collection.  In my example I created two classes:  State and StatesCollection.   These classes will provide a strongly typed way of accessing the information in the XML file. 

The State object created has two properties:  Name and Abbreviation.  Basically the properties map to the data in the XML file.   Here is the State class:

    public class State
{
public string Name { get; set; }
public string Abbreviation { get; set; }
}

For the StatesCollection I chose to inherit from a generic list and use a lazy loading property called SouthernStates so the values from the XML file would only get read once.   Taking this approach allows access to all of the features of a generic list (Find(), Sort(), Skip<>, Take<>, etc).  Here is the initial stub of StatesCollection.

public class StatesCollection : System.Collections.Generic.List<State>
{
private StatesCollection()
{

}

private static StatesCollection _southernStates = null;
public static StatesCollection SouthernStates
{
get
{
if (_southernStates == null)
{
}
else
{
return _southernStates;
}
}
}
}

All that is left now is to fill in the code within the getter of our property to load the data from the embedded DLL.  The first thing needed is to get access to the assembly the code is executing within.  The second thing needed is to get the XML document into something we can work with.  Here are the two lines to perform this:

    System.Reflection.Assembly asm = Assembly.GetExecutingAssembly();
System.IO.Stream xmlStream = asm.GetManifestResourceStream("EmbeddedResource.Library.Data.SouthernStates.xml");

The main thing to note is the string passed into GetManifestResourceStream() is the full path including namespace to where the file lives within the project.  Normally if an exception is thrown  when you first try this, this is the cause of the problem.  If the path to the file is not clear then open the DLL with a plain text editor and search for the filename.  Use the path noted in the DLL.  Here’s a screen shot of what this may look like in the DLL:

image

Now that the XML data is in a stream there are several ways to access this data.  In this example I chose to load the stream into an XmlDocument and then process the nodes in the XmlDocument.  The following code fills in the getter property of the SouthernStates property in the StatesCollection class. 

                if (_southernStates == null)
{
StatesCollection states = new StatesCollection();
try
{
System.Reflection.Assembly asm = Assembly.GetExecutingAssembly();
System.IO.Stream xmlStream = asm.GetManifestResourceStream("EmbeddedResource.Library.Data.SouthernStates.xml");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlStream);
XmlNodeList nodes = xmlDoc.SelectNodes("/States/State");
StatesCollection coll = new StatesCollection();
foreach (XmlNode node in nodes)
{
State state = new State();
state.Abbreviation = node["Abbreviation"].InnerText;
state.Name = node["Name"].InnerText;
coll.Add(state);
}
return coll;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
else
{
return _southernStates;
}

Embedded Resource In Action

The hard part is now over.  In the above example notice after GetManifestResourceStream() is called the result is a stream.  Using the stream the XML data can be easily loaded into the XmlDocument using the Load() method.  After the data is loaded into the XmlDocument all that is left is to loop through the XmlDocument and build up a collection of State objects.  To test this example it becomes extremely trivial.  Here is a sample that prints the information in the XML file to the console.

            foreach (State state in StatesCollection.SouthernStates)
{
Console.WriteLine("Name: " + state.Name + " | Abbr: " + state.Abbreviation);
}
Console.ReadLine();

When executed would yield:

image

To take the example a step further LINQ could be used to sort the collection and return values easily.  This is the added benefit of using a strongly typed collection as eluded to earlier.  Here’s a sample using LINQ to sort the abbreviations and return them sorted. 

            var q = from state in StatesCollection.SouthernStates
orderby state.Name ascending
select state.Abbreviation;

List<string> sortedStates = q.ToList<string>();

for (int i = 0; i < sortedStates.Count; i++)
{
Console.WriteLine(sortedStates[i]);
}

When executed would yield:

image

While a little scary at first, embedded resource files aren’t that difficult to deal with and provide a lot of value if used correctly.  Obviously if the data in the XML changes constantly this is going to require a new build of the DLL.  A decision will have to be made on the part of the developer if this is acceptable.  Feel free to download the sample solution below and play around.

Technorati tags: ,

Announcing Home Highlighter Beta by Quicken Loans

Posted by Keith Elder | Posted in Internet | Posted on 11-12-2007

imageOne of the toughest things about owning a home is selling it.  Home owners are tasked with a mountain of things when preparing to sale their home.  Recently we launched a beta product to assist home owners with one of those task.  The product is called Home Highlighter and provides home owners the ability to build their feature sheets right from the web site complete with multiple templates and mortgage pricing information.  It is has become more main stream for home owners to create feature sheets that allow buyers to drive up to their home and grab detailed information.  Feature sheets can range from a single sheet to detailed books depending on the effort put in by the seller.  Home Highlighter helps home owners quickly and easily show case their home.

How to use Home Highlighter

Step 1 – Choose a Template

image

The first step getting started with Home Highlighter is to select a template.   Clicking step one will provide a screen whereby two different templates can be selected by pressing the left and right arrows.   Example:

image

Currently there are two templates to choose from.

image

image

To move forward click on the “Customized This Template” button to move to step two.

Step 2 – Fill In Your Details

image

Click each of the areas to upload images and set the features of your home.  The monthly payment is calculated automatically based on current interest rates and fixed pricing.  This is used to show prospective buyers how affordable the home can be.

Step 3 – Save and Print

Once all of your information is entered you can preview the information and save it.  Once saved you can then preview your generated PDF and print as many copies as you want.  I’ve attached the one I created if I was going to sale our home which you can download below. 

That’s it.  Three simple steps to creating a professional feature sheet the next time you sale your home.  If you have any feedback please use the feedback link located within the Home Highlighter web site.

Using Regular Expressions in C# vs PHP

Posted by Keith Elder | Posted in .Net, PHP | Posted on 05-12-2007

Recently at work I made a call out to all of the engineers to send me code they thought should be placed in the common library for .Net development.  In one of the responses I got an email from a PHP developer that shared a regular expression to check the format of money.  He stated he didn’t know how often we use them (referring to regular expressions) in C# but he thought he’d pass it along anyway.  That got me to thinking.  Do I use regular expressions as much in C# as I did in PHP? 

For those that are curious, the regular expression that was sent over works perfectly well in C#, no problems.  I think developers will find regular expressions will easily move from one to another.  If you happen to be porting PHP regular expressions to C# and vice versa you shouldn’t run into too many problems.  For example here is a quick test I threw together with the regular expression to make sure it worked.

using System;
using System.Text.RegularExpressions;

class Money
{
    public static void Main()
    {
        Regex exp = new Regex(@"^[1-9][0-9]{0,2}(,{0,1}[0-9]{3})*(\.[0-9]{0,2})$");
        Console.WriteLine(exp.IsMatch("123.23").ToString());
    }
}

When complied and ran it yielded the following result:

image

It worked.  When it comes to regular expressions within C# I have used them.  I find they are more like pepper sprinkled in a good stew rather than a main course meal.  That is how I would state the difference in use of them between the two languages.  If I had to give a percentage of how much less I use regular expressions I would definitely say more than half as much, and maybe go higher to 90% depending on the situation.  Why? 

I think it boils down to the reason that C# is strongly typed and PHP is loosely typed.  For example, the following code could never be written in C#. 

<?php
$x = 1;
$y = '2keith';

echo $x + $y;  // will print 3 (yes you can add strings and numbers in php)
// set $x to something completely different
$x = array('a', 'b', 'c', 'd');

echo $x[1]; // will print b
?>
Running the entire thing will result in:  3b

To some this example may be scary, others may look at it as a feature.  Whichever way you think, most developers when asked what the result will provide respond with all sorts of various answers.  When I taught PHP classes as a consultant I would use a similar example with the class.  To no exception, no one could ever predict the out come.  Answers given ranged from, it should throw an exception since you can’t add a string and a number.  Or it should throw an exception because the variable $x was reassigned to a different type.  

Do you see “why” PHP code relies on regular expressions more now?  Since $x can literally become any type at any time, a PHP developer can never rely on the fact that $x is an INT.  About the only way to check that value is the use of a regular expression.  In the PHP world it is called Type Juggling.  Conversely in C#, once the variable x is assigned a type, it cannot be changed and only valid numbers can be assigned to that type therefore eliminating the need to use a regular expression to check the value of the variable.

The question then becomes though, is this the C# way to test for the money value?  I would probably argue it isn’t the “best” way to handle money in C#.  While it certainly works there are other things to take into consideration when adding money.  For example two different types of money such as US Dollars and Euros cannot be added together.  It must first be exchanged and then added.  The same thing could be said of other operators performed against a variable of type money.  This is where it would be suitable to use a struct and create a new type called Money.

We can in C# declare a variable as the type of decimal and use it as money if we choose.  In this case we still don’t need a regular expression to validate the value of our variable.  Here’s a sample showing one way to handle a rogue value:

            decimal money;
            if (Decimal.TryParse("123.a234", out money))
            {
                Console.WriteLine("money is valid");
            }
            else
            {
                Console.WriteLine("money is invalid");
            }

I suspect a lot of programmers use this method but again a struct is more desirable.  Andre de Cavaignac has a great example of building a struct for a money type.  He provides these examples:

            Money eur10 = new Money(MoneyCurrency.Euro, 10);
            Money eurNeg10 = new Money(MoneyCurrency.USDollar, -10);
            Money usd10 = new Money(MoneyCurrency.USDollar, 10);
            Money usdZero = new Money(MoneyCurrency.USDollar, 0);

            bool result = (eur10 == usd10); // returns false;
            bool result = (eur10 > usd10); // throws InvalidOperationException (comparison not valid)
            bool result = (eur10 > Money.Zero); // returns true
            bool result = (eur10 > usd0); // returns true
            bool result = (usd10 > eurNeg10); // returns true (positive always greater than negative)

Obviously he’s put a lot of thought into how money should be handled and if you look at his library you’ll see he accounts for all different type of currencies. 

For those wondering the differences about regular expressions in PHP and C# I hope that gives you some insight into how the different languages respectively handle different situations.  It all boils down to strong typing vs loose typing and the ability to create new types based on structs.  Happy Holidays!

Programming Standards, Naming Conventions

Posted by Keith Elder | Posted in .Net, Programming | Posted on 30-11-2007

It never ceases to amaze me how different naming conventions are from language to language.  It seems each language has their own coding convention or style that gets adopted over time.  More times than not these naming conventions are established by authors in books, magazines, and Internet articles.  Developers that read those publications follow suite the majority of the time.  For example, I can remember years ago developers who wrote PHP named files they included in their programs with the extension of “.inc” yet other files ended in “.php”.  The huge downside to this was the .inc files would be passed directly through from an Apache server as plain text file instead of getting parsed as code.  This would allow want to be hackers to see the code to a web site.  The worse part is a lot of the time the database username and password was visible in plain text.  Why was this done?  It was done because Rasmus (the guy who wrote PHP) put it in his samples.  Once it was printed, it became a standard that took many years to correct.

After programming in a language for several years one tends to adopt a certain style and I am no exception to that.  It is funny how caught up we get in how things are named.  Our brains work on consistency though.  If I have to read code someone else wrote that doesn’t follow my naming conventions and style I am now out of my comfort zone and have to do double translation.  First translate their code into what I would have done to understand the problem better, and then read their code and translate that into what it is doing.  The worst examples of this are when you have to read code in a language written by a developer who is new to the language that brings in the previous style of the language they’ve used for years.  It is painful to read code that isn’t written in the “implied” standard the language is written in.  By implied I mean if you look at Intellisense for .Net objects, enumerations, namespaces, methods and so on you’ll quickly realize that everything starts with a capital letter.  A developer learning a programming language from scratch will pickup on this and more than likely follow this implied naming convention.  However, if a Java or PHP/Perl/Bash/Ruby programmer writes .Net code he or she will more than likely write code the same way they did in the Java world.  Example:

Typical .Net Version

        public int AddTwoNumbers(int x, int y)
        {
            return x + y;
        }

Typical Java Version

        public int addTwoNumbers(int x, int y)
        {
            return x + y;
        }

Typical Scripting Language Version

        public int add_two_numbers(int x, int y)
        {
            return x + y;
        }

Three distinct ways to name a method.  The difference in the first two is the upper / lower casing of the method but it is more obvious with the third example in how different platforms write their code.  I’ve had the pleasure, I mean pain of reading .Net code written or translated by developers who are new to .Net.  I can tell within a few lines the language the person translated the code from or the language they wrote in previously.  Assuming they don’t “change” how they write their code.  I suspect most others can as well.

When developers transition to .Net or learn .Net it amazes me how many of them deviate from the implied naming conventions.  For example, all namespaces in .Net are Pascal case with no underscores yet I see developers coming from a Java background creating namespaces like “com.something.foo” and breaking this convention instead of following what has been established before they got there.  I find the .Net framework very consistent in how it is written and coded.  If you are learning .Net the best rule you can follow is first follow the implied naming conventions.

I like standards, especially when moving developers in and out of development teams.  It amazes me when I look at a problem that isn’t formatted or named the way I prefer, how much longer it takes me to understand what the developer is doing.  This can be from how curly braces are structured, to variable naming conventions and much more.  I have had situations that before I could help the person I had to refactor their code before I could understand it.   More times than not while I am refactoring the person will find their own mistake because of how I refactored it (simplicity is genius).  Naming conventions are good because it helps others to quickly understand what is going on.  Again I go back to my point that if someone writes in a style you don’t follow you are doing double the work to understand it. 

Here’s an example of the subtlety in the naming of variables that can be confusing.  For example if I see a property of an object called “AddressCollection” I know immediately this is a generic list of Address objects.  Easy, Forrest Gump, no questions asked. Conversely, if I see “Addresses” as a property I have no idea what this is.  It could be a collection or just an object.  I’ve taught many a programming class and I’ve seen a lot of code written by complete newbie programmers.  It always amazed me at how I could write code they couldn’t understand just by changing my “style” or naming conventions.  Folks, this stuff does matter and especially in larger team environments.    If you don’t believe me, then write a program with variables named after Flintstone characters and then give it to a Senior Engineer and see how long it takes them to figure out what it does versus one that isn’t.

There are a lot of preferences when you talk to developers about how they code.  I personally like what makes sense and is as Gump as I can get it.  I also like to follow suit of how other things are named to provide consistency.  So what are my preferences?  Well, I won’t go into each and everyone but here are a few of my stronger opinions.

Variable Prefixes
A controversial topic no doubt but I prefix all private variables with an underscore.  I do this because it is easier to read.  It is also one character different which follows the rule of not making private variables and public variables different by case.  Example:

        private string _propertyName;
        public string PropertyName
        {
            get { return _propertyName; }
            set { _propertyName = value; }
        }

I’ve seen a lot of code written and published on the Internet that prefixes variables with “m_”.  Most of the time this is due to legacy habits.  For those that do this, please stop, you aren’t coding in VB6 anymore.   It boils down to simplicity.  I use one character, it avoids naming collisions and is easy on the eyes to read and less distracting. 

I also have seen code where developers will prefix a variable with a shortcut of a type.  For example if they are creating an array they’ll do arrMyVariable or if the variable is a string they will do strMyVariable.  Usually when I see this type of code it tells me the person came from a scripting language background whereby variables can literally be different types in the next statement.  For example this is something we used to do in Perl whereby this would help other developers to know what was in the variable or suppose to be in the variable so they wouldn’t try to change the type. 

Curly Braces
Another controversial topic is curly braces.  I line curly braces up on top of each other (each gets their own line).  Some may not agree with this but I find it extremely easy to debug sections since the braces line up and allow the eyes to see blocks of code quicker.  When you get into nested situations it is easier to see the “blocks”.  For those that don’t agree I have tested this in many programming classes I’ve taught and students who are “learning” a language from scratch will agree 100% of the time that lining them up is easier.  Here’s what I’m talking about with some random code that makes no sense and isn’t suppose to.  Two versions of it with a lot of nested blocks.

HARD TO READ

        private void MyFunction(int x) {
            if (x % 2 == 0) {
                for (int i = 0; i < x; i++) {
                    if (i % 2 == 0) {
                        // do something
                    }
                    else {
                        // do something
                        for (int i = 0; i < x*i; i++) {
                            // something else
                            if (DateTime.Today.DayOfWeek == DayOfWeek.Saturday) {
                                Console.WriteLine("Take the day off.");
                            }
                        }
                    }
                }
            }
        }

EASIER TO READ

   private void MyFunction(int x)
        {
            if (x % 2 == 0)
            {
                for (int i = 0; i < x; i++)
                {
                    if (i % 2 == 0)
                    {
                        // do something
                    }
                    else
                    {
                        // do something
                        for (int i = 0; i < x*i; i++)
                        {
                            // something else
                            if (DateTime.Today.DayOfWeek == DayOfWeek.Saturday)
                            {
                                Console.WriteLine("Take the day off.");
                            }
                        }
                    }
                }
            }
        }

While the second example is longer in terms of lines of code (this is why God created regions) one thing you can see easily is how nested it is and how the code breathes more.  The first approach looks like it is cramming the code together.  Like I’ve said, I have tested this in every programming class I’ve taught and the consensus is the second example is always preferred and easier to understand.  The nice thing is for those using Visual Studio this is the out of the box behavior. 

If Statements
A pet peeve of mine is when developers shortcut if blocks.  Here is what I mean.

If Block Shortcut

    public Foo(int x)
    {
        if (x % 2 == 0) Console.WriteLine(x.ToString() + " is even");
    }

If you have a single line for an If block you can shortcut it and leave off the curly braces.  It is a feature, yeah.  Some other languages support this and C# does as well.  Personally I can’t stand this because of several reasons.  One, debugging.  If I want to set a break point just when the Console.WriteLine is hit I can’t.  I have set it on the one line and check it each time.  Another reason this disturbs me is if the business logic changes where I have to print an else statement it has to be reformatted anyway.  Go ahead and add the curly braces up front instead of waiting.  The third reason is when looking at the code there may be things that occur after this and it is confusing to read to know what the intent of the person that originally wrote it was.   This also ties into the readability of the code as outlined in the curly braces section.   Bottom line, don’t shortcut just because you can.

Namespaces
I mentioned this earlier but I’ll mention it again. Namespaces should be Pascal Case.  A namespace should be something that is agreed on BEFORE you write code for a project.  The standard is to use the CompanyName[.Team][.SubTeam] + Project + [.Feature][.Design].  Example:  Microsoft.Practices.EnterpriseLibrary.Caching.  Of course you can leave off the team, subteam, feature or design if you choose depending on how global the project is.  Don’t worry if you do that.  ScottGu isn’t going to show up at your doorstep asking you to change it.  There aren’t any hard and fast rules these are just the “implied what Microsoft does” rules.  For more detailed information Microsoft has a reference page about namespaces available on MSDN.

Naming Preferences
This is a large topic, or can be.  So instead of re-hashing this on my own go read Peter Brown’s article on naming conventions.  It is fantastic. This is one of the few articles that I can say I agree with 96.78582762% or more of what it states.  I imagine if I read Peter’s code it would look exactly like mine in terms of naming preferences.  Beyond Peter’s article there is also naming guidelines already established on MSDN that outline how to name classes, enumerations, parameters, properties, events, and so on.  If you are wondering what I do, for the most part I follow that guideline.