Devlico.Us
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @devlicious

Derik Whittaker

Thoughts on Software Development, .Net, OOP, Design Patterns and all things cool

January 2008 - Posts

  • NHibernate and Automatic Properties gotcha

    Just an FYI. 

    If you are using NHibernate and have objects that are using the new Automatic Properties feature of .Net 3.5 make sure that your NHibernate .hbm file does not have 'default-access="field.camelcase-underscore"' in the hibernate-mapping node.

    If you have this attribute set you will get a run-time error while using NHibernate.  The error is NHibernate.PropertyNotFoundException: Could not find field '_fieldNameHere' in class 'ClassNameHere'

    Hope this helps someone else. I know I spent about 10 minutes trying to figure out what I did wrong.

    Till next time,

  • Using System.ComponentModel Attributes to your advantage

    The System.ComponentModel namespace (more information here) in .Net contains an array of various attributes that every .Net developer should know about.  These attributes provide a way for the developer to implement design-time and run-time behavior on both controls and components.  In addition to attributes, this namespace also has base classes, interfaces, binding sources, etc.

    By using the various attributes in this namespace you can create better, more useable UI controls for your projects.  Below are a few that I tend to use often.

    BrowsableAttribute - (more info here)
    This is a boolean attribute and when set to false, the property on the control will not show up in the Properties panel in the IDE.  This is nice when you want to have a property but not expose it at design time to the developer.

    CategoryAttribute - (more info here)
    This is a simple attribute that will take a string and will allow you to create a custom category for your control.  If you do not use this, your control property will show up in the 'Misc' category in the Properties panel in the IDE.

    DefaultValueAttribute - (more info here)
    This attribute will all you to set the default value for the property in the control itself.  This will also show the default value in the Properties panel in the IDE. 

    NOTE - This WILL NOT work if you also are using the DesignOnly attribute.

    DescriptionAttribute - (more info here)
    This is another simple property that will allow the author of the control to provide description text about the meaning of the property.  This is similar to adding comments to the code, but it will be displayed in the Properties panel in the IDE.

    DesignOnlyAttribute - (more info here)
    This is a boolean attribute that is great.  You this and set it to true if you have a property that you DO NOT WANT to be set with any type of default value in the designer generated code.  Adding this can save you a ton of time and effort.

    NOTE - My experience has shown me that this will supercede the DefaultValue attribute is this is set to true.

    ReadOnlyAttribute - (more info here)
    This attribute is just a way to mark the property as read only.  This can also be accomplished by NOT putting a setter on the property.

    Till next time,

  • Whitebox vs Blackbox testing (location of unit tests)

    Over on the Alt.Net mailing list (here) the topic of where to put your unit tests was the hot topic a few days ago.  This is a topic that I have debated with various people over the past few years.  With all the debates I have had, it is clear to me that there really is no right or wrong way do to this, but it is just a matter of philosophical opinion.

    On this list there are various opinions (and supporting experiences to support those opinions) about which method is better or preferred.  As this is a topic that many developers chat about, I thought I would put a list of the various advantages/disadvantages into location.

    Whitebox Advantages

    • Location of tests to their corresponding class under test.
    • Very easy to test internal methods without the need of using the InternalVisibleTo attribute.
    • Reduces the number of projects you have in your solution because you will not need a test project for each assembly.

    Whitebox Disadvantages

    • Have to add compiler switches to ensure the tests are NOT compiled into the release code.  This is easily done, but is just something else that you have to setup and remember to do.
    • Addition of various test assemblies in the release of your project.  This includes stuff like the test framework assemblies, any mocking assemblies, etc.
    • Slower compilation time.

    Blackbox Advantages

    • You test your assembly exactly like a calling application would use the assembly.  This can be very beneficial as it can flush out implementation bugs very easily.
    • If following true TDD, should create a simpler interface as you can only test the calls that are public and this is the way the user will use the assembly.
    • No need to put any special compiler switches in the code in order to not release the tests.
    • No worries about deploying test code as it is in a separate assembly.

    Blackbox Disadvantages

    • Additional projects in your solution.
    • May need to add the InternalsVisibleTo to the various assemblies being tested if you need to tests internal methods (if this is the case, you may have a code smell on your hands).

    As you can see from the list of pros/cons above, both whitebox and blackbox testing have upsides and downsides.  At the end of the day this comes down to a personal/philosophical decision and both are better then the alternative....NO TESTS.

    Till next time,

    *** Note, some of the listed advantages/disadvantages above were taken from various postings on the Alt.Net mailing list.  Credit goes to the various authors in these cases ***

  • Defensive Coding best practice

    <disclaimer>
    This posting is purely my personal opinion.  I am sure many of you out there will disagree, if this is the case, let me know.
    </disclaimer>

    Today, during my bug hunting I stumbled across the dreaded 'Null reference' exception.  This was not the original target of my hunt, but it quickly became wanted bug number one.  After some digging and debugging I found the the varmint.  The offending code was the following a null ref because someone made the mistake of assuming that an object would always be non-null.

    listMain.Items.FindByText( listChild.SelectedItem.Text.Substring( 0, 1 ) ).Selected = true;
    
    

    Now let me explain the intent of this code.  There are 2 list boxes on the UI and when someone selects something in the second list box, the code is meant to filter down the code in the first list box.  However, the code above assumes that there will be a match for the 'FindByText' method and this is where we have problems.  The author of this code decided that there will NEVER be a situation where the filter will not find a result.  Oops.

    The defensive coder would not make that assumption and would have added a few extra lines of code.  Below may be an example:

    ListItem foundItem = listMain.Items.FindByText( listChild.SelectedItem.Text.Substring( 0, 1 ).ToUpper() );
    
    if ( foundItem != null )
    {
    	foundItem.Selected = true;
    
    	// Do something with the result	
    } 
    else 
    {
    	// Do something, either tell the user there was no data or anything else the business wants
    }
    
    

    By adding the defensive code we can avoid the 'Null Reference' exceptions that we all love.  We also make our code more robust by forcing the developer to thing about possible exception conditions.  

    For more information about Defensive Coding, check out this link here.

    Till next time,

  • Visual Studio 2008 Launch Event Announced

    Microsoft has announced the dates and locations for their next Launch Event.  They are launching VS 2008, SQL 2008 and Windows Server 2008 all here.

    One nice thing about attending these Launch Events is the FREE SOFTWARE.

    You can get more information about the event dates/locations here.

    I have already signed up for the Chicago event, should be a good time,

    Till next time,

  • Try-Catch in Sql 2005 is your friend.

    I know that SQL 2005 has been out for a while now, but I did not do ANY sql for over a year.  Anyway, anyone that has had to write anything more than trival procs knows that error handling can be a pain.

    In the past you have had to do something along the line of the following

    IF ( @@ERROR > 0 )
       -- Do Something

    A better way is to wrap your code in Try-Catch and with SQL 2005 you can do this pretty easily.

    BEGIN TRY
    
    	-- .... logic goes here
    
    END TRY
    BEGIN CATCH
    	-- handle here, or simply return
    	-- here I wanted to output the error, also showing what can be done
    	SELECT
    		ERROR_NUMBER() AS ErrorNumber,
    		ERROR_SEVERITY() AS ErrorSeverity,
    		ERROR_STATE() AS ErrorState,
    		ERROR_PROCEDURE() AS ErrorProcedure,
    		ERROR_LINE() AS ErrorLine,
    		ERROR_MESSAGE() AS ErrorMessage;
    END CATCH

    One really nice advantage to using the Try-Catch is that errors thrown in subsequent proc calls can be caught and handled.  No more needing to pass back return codes from procs.

    Check out the documentation for more information - found here

    Till next time,

  • Debugging .Net Framework Source from VS 2008

    As you may have heard, Microsoft has released the .Net framework source to the world.  No, you cannot make changes or additions, in fact it is being released under the Microsoft Reference License.  If you would like more information about the release of the source, check out Scott Guthrie's posting about it here.

    Well, yesterday a buddy of mine sent me this information on how to configure the VS 2008 IDE to enable easy debugging of the .Net Framework source.  You can find this information here.

    This should be pretty cool, and will hopefully reduce some pain in debugging.

    Till next time,

  • Overuse of #Regions

    Before I get started, I personally am a fan of using #regions in my code.  I think it cleans up everything, allowing me to only see what I want to see.  I also know that many of you disagree with me, and that is fine.

    Here are 2 posts that voice their disapproval for regions if you are interested.

    As much of a fan as i am of them, sometimes they are just waste.  Today i came across a code file that was had the following regions.  (I have changed the actual region tags to protect the innocent:)

    #region Custom Methods

    #region private bool MethodThatDoesSomething
    private bool MethodThatDoesSomething(){}
    #endregion

    #region private void AnotherMethodThatDoesSomething
    private void AnotherMethodThatDoesSomething(){}
    #endregion

    #endregion

    By putting the private methods inside it OWN region region the author has accomplished NOTHING, except making my hunt even further for the code i need to modify.  This was just total waste.

    If you are like me and like regions, my guess is that it is because you believe that it better organize your code.  But you must know when enough is enough.  Please don't put individual methods inside a region that is meant to ONLY hold that method.

    Till next time,

  • .Net 3.5 Framework Namespace posted updated

    Brad Abrams announced that there is an updated version of the poster available.

    You can get more information from Brad here.

    Till next time,

  • Object Properties, make them public ONLY when needed.

    Sorry we have interrupted your daily blog reading, but we have a special service announcement for all developers.

    <SpecialServiceAnnouncement>

    Only make properties public on an object when you KNOW they are needed.  Please make all properties private by default.

    If you need to access the property from outside your object, make the getter public and leave the setter private.

    Only open up the setter when you KNOW it is needed, this should be a last resort option.

    </SpecialServiceAnnouncement>

    Till next time,

  • On doing take home assignments before getting an interview

    <Disclaimer>
    Before I get into the meat of this, or before I start getting 'your an idiot' replay's I just want to state that I am NOT against asking potential employees to take tests.  I just think that there is an acceptable expected time frame that the test should take.
    </Disclaimer>

    I was chatting with a friend of mine today and he told me that he was thinking of taking an interview with a small .com shop in the Chicago land area.  But that they wanted him to do a 'small take home assignment' before hand.  I told him that sounded acceptable to me as it could be a decent way to judges someone's talent level.  He then forwarded me a copy of the requirements document' for the take home test.  After reading the doc, I quickly slapped an estimate of 4-6 hours of effort to finish the assignment.  When I told him this, he told me that they expect it to take him 10 hours (2 for planning, 8 for coding) or so to complete.  He also told me that they wanted this by Monday afternoon and AFTER they reviewed the code he would be scheduled for an interview.

    The take home assignment was to build a complete (i.e. functional) web site from the ground up.  This included the db model, all the domain/business object, the UI, etc.  And from the spec, it was not a simple few tables with a few objects.  The site needed to include user creation, user login, data assignment to a user, data retrieval, etc.  Nothing overly complicated, but would still take time and effort.  And lets face it, if this is for a job, you are going to spend a little more time on it then normal.

    When he told me that, I told him that I would pass on the interview.  I personally think that asking a developer to spend 10 hours of their free time in order to simply get an interview is a little extreme.

    Like I said above, I have no issues with testing developers, but there needs to be a limit on how much free time you are required to give up.  Do I really need to spend 10 hours of my life to write a fully functional web site in order to get an interview?

    There are much better ways of 'testing' ones skills then asking them to spend countless hours on a take home exam.  For example

    • Ask them standard .net questions.  This will weed out 50% of the people
    • Ask them to setup a simple db structure
    • Ask them to do a little object modeling
    • Ask them to refactor some 'smelly' code
    • etc.

    In today's job market, quality developers are few and far between.  I personally feel that employees have as much, if not more control then the employer. 

    Am I off base, am I being stupid?  I wanna know.

    Till next time,

  • NUnit, Class Assertions or Constraint Assertions

    I finally got around to upgrading to the most recent version of NUnit recently (Yea I know, bout time) and found out that there is a new way of doing assertions.  The new model is referred to as the 'constraint' model and follows a more fluent style interface.  Below are some examples in syntax between the 2 models.

    Classic Model examples

    Assert.IsNull( objectHere );
    Assert.AreEqual( value1, value2 ):
    Assert.IsTrue( boolValue );

    Constraint Model examples

    Assert.That( objectHere, Is.Not.Null );
    Assert.That( value1, Is.EqualTo( value2 ) );
    Assert.That( value1, Is.True );

    My initial reaction to the new style of assertions was that I did not like it.  I felt that Assert.IsNull() was cleaner than Assert.That (x, Is.Null ).  However, after I read up on the documentation for the new model ( here ), I started to like it more and more.  I have always been a fan of fluent interface style syntax because to me it reads more like English (insert your language of preference here).  Also, if you read the documentation, with the latest release (post 2.4 really) the classic model now just hides the constraint model, so why not just use the constraint model to begin with.

    Anyway, I was kind of excited to see the model and the possibilities it brings, but also a little 'put off' because now I have to learn something new....:(

    Till next time,

  • Sometimes I just feel dirty doing this job.....

    Many times during our development duties we have to read through code segments to figure out the desired intent of a feature.  Today I was doing just this.  There is a new feature that I need to implement and to do so, I needed to walk through a bunch of code to determine where my changes may need to go.

    Along the way looking though the code I found some less than efficient code (no, this is not a rant about WTF style code).  This code was doing stuff like checking the count of an array to ensure it was > 0 before it went into a for-each loop, along with some other useless stuff.

    I made note of the code, but did not change it and I continued on my marry way.  Once I figured out where I needed to make my changes I went back to that code.  My original intent was to fix the code in which I found to be less than efficient.  But then I stopped, I did NOT make the changes.  Why you may ask, here is why

    • My tasks was NOT to change/modify/refactor the code in this giving class
      Changing this code would be a waste, my task was to do something else.  If I feel this code needed to be changed, I need to add it to the list for future work.

    • There are NO tests for this project so I could not assume my trivial changes would not break everything.
      It sucks having no tests and with the absence of test, I would not have felt comfortable changing this code without putting it though its paces and like I said before my task was not to fix this code, but to add a new feature.

    • Why change code that works just fine and is not causing bugs, simply because I feel it was less then efficient?
      As much as I don't like inefficient code, I have a hard time making changes to it if there is no real business sense.  Sure if it was running too slow, or chewing up memory I would make the change, but these are not doing that.

    Anyway, I just always feel dirty when I come across code that needs to be fixed and I am not in the position to fix it.  Oh well, I am off to take a shower to get rid of that dirty feeling.

    Till next time,

  • Using lookup values in Stored Procedures

    Anyone who has written stored procedures has more then likely done the following (this is a very trivial, simple example):

    Select Column1,
               Column2,
               Column2,
               etc...
    FROM Table1
    WHERE SomeLookupType = 1

    What I am trying to show above is selecting some data based on hard coding a reference (lookup) value in the procedure.

    I have never really liked doing this for a few different reasons, but just accepted it as the way it was.  Here are a few of the reasons I have never really like it.

    • Hard codes business related logic in the procedure
      I know the procedure is meant to retrieve data by a given value, but if you need to change the value you will have to go to the procedure to do so.  I am not a big fan of putting business logic of any type in procedures.

    • Hard codes potentially dynamic data values in the proc
      If the values in the lookup table need to change for any reason, you will have to remember to go to the various procedures to make the appropriate changes.

    • Can make refactoring a little more challenging.
      If you are refactoring/changing business logic in your application you will have to remember to visit various procedures to make changes because maybe now you want to lookup the data by an other value.

    I really have never put too much thought into how to do it better, but at my current client they have a way that works, but I am still not sure I like it, but it is a step in the right direction.

    Select Column1,
               Column2,
               Column2,
               etc...
    FROM Table1
    WHERE SomeLookupType = @SomePassedInValueToTheProc

    The logic above is exactly the same, with one twist.  The magic (hard coded) value is now being passed into the procedure.  This resolves all my issues that I talk about above, but it does bring its own issues and they are.

    • Increases the parameter list
      I know this may seem like a petty thing, but I like to keep my procedure parameter list to a minimum, and if i have to pass in 'lookup' values it just muddies the water.

    • Can cause 'philosophical' dilemma's
      Let me explain.  I have a procedure that will return data based on its 'status'  The status is passed into the proc.  However, due to some lame business requirement there is one situation where i need to return the data based on 2 status's.  In this case I have 3 options.
      1) Change the proc to accept a new additional param. 
      2) Call the proc 2 times one for each status and combine the results
      3) 'Hack' the proc to use 2 values in special cases.

    Like I said above, I am not in love with either solution, but I do have to admit that passing in the lookup values appears to be a little cleaner in the long run.

    So, is there another way? 

    Till next time,

  • Things to think about if you want to be a consultant

    I was chatting a buddy recently and he was thinking about making the jump to the consulting world (not solo, through a consulting firm).  As he has never been a consultant I gave him my 2cents on questions to ask during the interview as well as things he has to accept before making the jump.

    Questions to ask the consulting firm

    • What percent of travel is the norm?
      This is very important to know up front.  Because if you don't want to travel much and they tell you they are 100% travel, then move on. 

      One thing you need to keep in mind, is that they can give you a number, that number is NOT in stone.  It can/will change from client to client.  In my 5 years of consulting, I never left the greater Chicago area.  And for 2+ years I worked out of our home office.

    • What is your bench policy?
      Ask what the policy is for being on the bench?  More importantly ask the billable % expectation is for a consultant.  This can be important because if they expect you to be billable 90% of the year then they may not be able to handle any rough patches.  However, if they expect you to be billable for only 80% then they should be better set for rough patches.

      I also found that if a company has higher expectations about billable %, they may not be willing to provide non-billable training as it eats into the bottom line.

      If you are on the bench, do they have something for you to do?  Can you go to training during that time?  Or can you simply stay home and collect a check (i wish)?

    • What is your training policy?
      Ask what type of training they budget for?  Do they pay for conferences, weekly training classes?  Do they EXPECT you to take some sort of training. 

      A good firm will have a defined budged that will allow for adequate training of all there consultants.  Actually, it is in their best interest to keep you trained as you become more marketable.

    • What is the 'standard' number of billable hours you expect?
      What is the standard number of hours do they expect you to bill for in a giving year?  Is it 1800, is it 2000?  This makes a difference because if they tell you 2000+ then are telling you they EXPECT you to work over time (more on that below).

      A full year with no time off is 2080 hours (52 weeks * 40 hours).  But if you get 2 weeks vacation and 10 paid holidays you are only at 1920 (48 weeks * 40 hours). 

      Again, now keep in mind that the 'standard' number is just a rule of thumb, but it is good to know.  The higher the number, the less room in the budget they may have for when times get tough. 

      Also, keep in mind that during my 5 years consulting, my average work week was about 45-50 hours.  So if you are looking for the 40 hours and go home, you may not want to do consulting.

    • How are bonuses/raises calculated?
      Do they give bonuses/raises?  Are they based on billable hours?  If they are based on billable hours, that can be good and bad. 

      Example.  My old firm would give a flat bonus, but if you worked 200 extra hours a year you got a bump, if you worked 300 you got an extra bump, etc.

      This is good because i knew that the more i billed, the larger my bonus. 
      This was bad because i only got a sliver of the extra billable hours and in the long run did not pay off in the end.

    • How does overtime work?
      Some firms don't do anything special for overtime (as is the case in most salary positions).  However, some will actually pay you extra for your overtime (these places typically don't give bonuses).  Other places bank your overtime and build that into your vacation (worked out well for my buddy).

      But i would say that most common is that nothing happens with your overtime, except the companies profits increase at your expense.

    Thing you have to accept as part of the job

    • The tech/environment will change with every new client
      With every new client/project your environment along with the technology will change.  For some people this is a show stopper, for others it is just another chance to learn.

      Keep in mind that if you work on site at the client you will be expected to follow ALL their rules.  So if they are business formal, you will be expected to dress in business formal.  If they say you cannot come in till 9 and must stay till 6, then that is what you must do.

      If you are not willing to accept this, then consulting may not be for you.

    • You may not always be working on 'cool/fun' tech
      Since each project may change technology you may not always be working on 'fun, cool' stuff.  You may go from doing cutting edge development on project to doing report writing on the next one. 

      If you are not willing to accept this, then consulting may not be for you.

    • You are the '***' of the client, at their mercy
      Since you are a 'hired gun' you are the mercy of the client.  Don't expect to have the same treatment as full timers (a lot of places today treat their consultants as part of the family, but not all).  Don't expect to get subsidized meals (if offered) or gym memberships, etc.

      Also, be ready to work in some of the worst spaces you can think of.  On place i worked the consultants all sat in a single 15-20 office.  They basically lined up desks along the wall and filled it with 6 people.  I felt bad for them :).


    • The people you will meet
      The coolest part is the people you will meet, the connections you will make.  This is great because networking is the best way to move ahead in this business.  I have meet some great people and have made some great contacts.

    This was my 2cents to him.

    Did I miss anything?  Am I wrong?  Let me know

    Till next time,

More Posts Next page »

Our Sponsors

Red-Gate!