When to Add a Project to a Solution

To my knowledge there is not an official standard on when to add projects to a solution.

As a software consultant I’ve seen it done many ways. Below are the most common approaches to project structures.

By Namespace

One school of thought is each namespace gets a project. In most cases the projects don’t have any sub folders. This structure allows for simple project layouts. The downside is it can lead to solutions with 40, 50 or more projects.

By Separation of Concern (SOC)

Another school of thought is by SOC, for example a project for the UI layer, a project for the model (entities), a project the business logic and a project for the data layer. This allows for easy identification of the logical layers. The downside is SOC has nothing to do with assemblies. Just because the projects and the logic layers can be aligned does not mean they should.

Minimalist Approach

This school of thought keeps everything together until there is a reason to split it out. Reasons you’d want to split out code could be for testing or for using the code in another project.

In its extreme you’d have one project with the models and the data access together. The code would logically be broken up. SOP would be enforced by the architecture, not the project structure. The upside to this approach is the project structure is simple. You’ll have 2 to 4 projects in a solution. The downside is that it’s the responsibility of the developer to enforce SOP.

Which approach do I use?

I follow the Minimalist Approach.  Identifying SOC is hard. The Minimalist approach is not for the faint of heart. Those whom don’t have a concrete grasp on SOC will be better served aligning SOC and the project structure. This ensures there will be no cyclical references and SOC.

Clustered Index and Non-Clustered Index

Clustered Index
Clustered Indexes are primary keys and uniquely identify the data, they are called clustered index because the data is clustered together on the file-system. Clustering the data allows for quick retrieval and a table can only have one clustered index.

Non-Clustered Index
A non clustered index is an index that points to the clustered index. Ideally, the data has limited duplication. For example, take a create date. Rows created on a specific data has a limited scope of that day. Creating a non clustered index on CreateDate will allow quick retrieval of rows grouped by CreateDate. Thing of it as a grouping of all the same data with a reference(clustered index) to the physical row.

Nothing is free, the benefit of creating indexes is speed. Read speed greatly increases. The cost is insert, update and deletes slow down.

Fail Fast

For goodness sakes don’t swallow exceptions! It’ll kill you (not really)!!!

Don’t try to hobble along. If an exception is thrown, log it, present the user with a “Sorry, but we had a problem…” message and assure them you are on top of the issue and graceful close the application or restart it.

In business programming there is no reason to try to “Save” the context. It’s a disaster waiting to happen. By swallowing an exception the application is put into an unknown state. Badness can happen when your application is an unexpected state. Anything from data corruption to your application being compromised. One of the strategies of hackers is to test edge cases, looking for an in or an error to gain more information on compromising the application.

When your application throws an exception, logged it and close the application. The context may have been lost, but the application lives on.

The Three Tenets of Object Oriented Design

The three principles of Object Oriented Design.

P.I.E.

Polymorphism – Is the ability of an object to have more than one form.

Inheritance – Is the ability for an object to be sub classed from a base or parent class. Typically the child classes share some common functionality with the parent class.

Encapsulation – This is simply the hiding of implementation or data. “Don’t be concerned on how it’s done…”

Am I Due a Raise When I Graduate?

I’d like to give the company the benefit of the doubt, but in my experience they don’t deserve it. They probably hired you at lower rate to get a steal. Remember, all businesses are in the game to make a profit otherwise they die, which is bad for you. At the same time, if you leave the company, they also loose. They have hiring costs and training costs invested in you and you have part of the company mind-share. They do not want to loose their investment in you.

If I was hiring you, I would bring you in as low as possible. Let’s say at 50k. If this your first professional job, you are probably use to making 10 to 15 dollars an hour. That is roughly 30k a year. They offer you 50k a year. That seems like a lot of money to you and you accept.

You graduate with a degree, yes you are worth more, but we started you out at 50k. We’ll give you a 10 percent raise. They will give you some line of crap about how a 10 percent raise is almost unheard of in the industry and it’s tough times! You can tell them it’s not enough and explain to them the average wage is 65k for your position and that you’ll cut them a deal and accept 70k. Because that’s how good you are. Or you can do what most people do and accept the 10 percent wage and feel all warm and fuzzy inside.

Are you willing to find another job? Your bargaining chip is you leaving. I’ve seen people ask for a raise and not get it. They leave company and come back a year later taking a higher position and making double their old salary.

WordPress 3.5.1 MultiSites on Windows Azure

Out of the box the web.config included does not work with sub-directories.

The following web.config worked for me on Windows Azure:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="WordPress Rule 1" stopProcessing="true">
          <match url="^index.php$" ignoreCase="false" />
          <action type="None" />
        </rule>
        <rule name="WordPress Rule 2" stopProcessing="true">
          <match url="^([_0-9a-zA-Z-]+/)?files/(.+)" ignoreCase="false" />
          <action type="Rewrite" url="wp-includes/ms-files.php?file={R:2}" appendQueryString="false" />
        </rule>
        <rule name="WordPress Rule 3" stopProcessing="true">
          <match url="^([_0-9a-zA-Z-]+/)?wp-admin$" ignoreCase="false" />
          <action type="Redirect" url="{R:1}wp-admin/" redirectType="Permanent" />
        </rule>
        <rule name="WordPress Rule 4" stopProcessing="true">
          <match url="^" ignoreCase="false" />
          <conditions logicalGrouping="MatchAny">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" />
          </conditions>
          <action type="None" />
        </rule>
        <rule name="WordPress Rule 5" stopProcessing="true">
          <match url="^[_0-9a-zA-Z-]+/(wp-(content|admin|includes).*)" ignoreCase="false" />
          <action type="Rewrite" url="{R:1}" />
        </rule>
        <rule name="WordPress Rule 6" stopProcessing="true">
          <match url="^([_0-9a-zA-Z-]+/)?(.*.php)$" ignoreCase="false" />
          <action type="Rewrite" url="{R:2}" />
        </rule>
        <rule name="WordPress Rule 7" stopProcessing="true">
          <match url="." ignoreCase="false" />
          <action type="Rewrite" url="index.php" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

Comparing Enums With the Same Values

comparing_notes_popupRecently I came across some code where a switch statement was used to convert one Enum to another Enum. There were over 20 cases in the switch statement. The kicker was the values were the same. Why did they not use a single Enum? I’m still trying to figure that out.

I wrote some code that eliminated the massive switch statement:

        public TTo MapEnum(TFrom from)
            where TFrom : struct, IConvertible
            where TTo : struct, IConvertible
        {
            System.Diagnostics.Contracts.Contract.Requires(!typeof(TTo).IsEnum, "TTo must be an enumerated type");
            System.Diagnostics.Contracts.Contract.Requires(!typeof(TFrom).IsEnum, "TFrom must be an enumerated type");
          
            string fromValue = Convert.ToString(from);

            TTo toEnum;
            bool found = Enum.TryParse(fromValue, true, out toEnum);

            if (!found)
            {
                throw new Exception("Could not find value {0} for type {1} in enum {2} ");
            }

            return toEnum;
        }

Writing the SVN Reversion to a File in TeamCity

I spent hours trying to figure this one out. It turned out brain dead simple.

  1. Add a build step
  2. Select the command line runner type
  3. Set the working path to the path you’d like to save the version file too.
  4. In the Custom Script Text Field add the following text: ECHO %build.vcs.number% > version.txt

Considerations When Throwing Exceptions

A co-worker sent an email with some code he’s struggling with. He’s trying to avoid using try/catches to drive business logic.

The problem is not the try/catches it’s simply a symptom of the problem. Can you spot the problem? You’ll have to make some assumption, but I have faith you’ll come to the same conclusion I came too.

The code is below; I changed it to protect the innocent:

private Customer GetOrCreateCustomer(long customerTelephoneNumberOrCustomerId)
        {
           Customer customer;
            try
            {
                customer = this.DoMagic(customerMasterTelephoneNumberOrCustomerId);
            }
            catch (DataException)
            {
                try
                {
                    //TODO: I know this isn't ideal. Still thinking of a better way to do this. 
                    customer = this. GetCustomer(customerMasterTelephoneNumberOrCustomerId);
                }
                catch (DataException)
                {
                    customer = this.GetCustomerFromExternal(customerMasterTelephoneNumberOrCustomerId);
                    customer.CustomerId = this.CreateCustomer(customer);
                }
            }

            return customer;
        }

There is an underlining philosophy in this system that nulls are bad. In most cases where a null can be generated an exception is thrown. At first I did not see a problem with this. I saw it as an architecture decision, an aesthetic, but as I interface with the code, it’s apparent to me it’s an architectural mistake.

You might ask, why is throwing an exception in the case of nulls bad?

Below are some guidelines when considering throwing an exception:

  1. The fact that you have to check for the null to throw the exception should be a hint that it is not needed. It an expected outcome, thus not an exception.
  2. Throwing an exception is a resource intensive operation, one of the most resource intensive operations that can be done in .Net.
  3. An exception is just that, an exception. It’s an exception to the assumptions made in the code – when these assumptions are broken, the system must terminate, it cannot move on because the system is in an unknown state (i.e. the database is no longer available) this could also be an attack vector.
  4. Throwing an exception means you have to wrap the upstream call in a try/catch block to enforce business rules. A null value is a business opportunity to control the flow of the application. The action upon the null value should be done at the point in which a business decision must take place. For example, a customer variable is null, at the UI layer a message is shown to the user stating the customer with id ‘1234’ cannot be found.