Wednesday, February 17, 2016

C# Argument Out of Range DateTime

Problem:

Had a customer contact about 3rd party solution running on our IIS server.  Customer support for software was expired and they were desperate for help.  I looked at the issue which was when the web page (asp.net) loaded user received an argument out of range error.  The page had been working previously.  The error listed the issue as no date time supported for hours, minutes, seconds constructor error.

Solution:

I took a look at the code behind and found the following constructor

var endTime = new DateTime(today.Year, today.Month, today.Day, 8 + course.LengthInHours, 0, 0).ToLocalTime(timeZone);

The declaration looks syntactically correct.  The error message made me key in on the last 3 fields, hours, minutes and seconds.  I typically don't go to that level of detail when using the DateTime namespace.  But this developer had done it so I took all a look at the MSDN site for the DateTime constructor (https://msdn.microsoft.com/en-us/library/272ba130%28v=vs.110%29.aspx)

It became pretty obvious where the issue was the hour declaration was a calculated time 8 plus some value stored in a database.  I ran the test and sure enough the error condition had an hour count of 32 (24+8).   This definitely was the issue as API says:

hour
Type: System.Int32 - The hours (0 through 23).
The error was due to the value in the object being larger than 24.  The developer had assumed that the value would always be a number under 24.  The new solution which fixes the error uses the AddHours method vice trying to initialize the DateTime in the constructor.

 var tempEndTime = DateTime.Today;
 //Default is 12 AM each day.  Add 8 hours to get to the start of the workday 8 AM.
 tempEndTime = tempEndTime.AddHours(8);
 //Now add the length of the class to estimate end time of class
 if(course.LengthInHours>0)
     tempEndTime = tempEndTime.AddHours(course.LengthInHours);
 var endTime = tempEndTime.ToLocalTime(timeZone);


No comments:

Post a Comment