The Daily WTF

Curious Perversions in Information Technology
Error'd: The WTF Experience
Friday Oct 11, 2019 6:30 AM

"As it turns out, they've actually been singing Purple Haze before the start of all of those sportsball games," Adam writes.

 

Andrew C. writes, "When you buy from 'Best Pool Supplies', make no mistake...you're going to pay for that level of quality."

 

Jared wrote, "Pulling invalid data is forgiveable, but using a loop is not."

 

"VMware ESXi seems a little confused about how power state transitions work," writes Paul N.

 

"At first I was annoyed I didn't get the job, but now I really want to go in for free and fix their systems for them!" Mark wrote.

 

Peter M. writes, "Oh yes, Verizon! I am very excited! ...I'm just having a difficult time defining why."

 

[Advertisement] ProGet supports your applications, Docker containers, and third-party packages, allowing you to enforce quality standards across all components. Download and see how!


CodeSOD: Parse, Parse Again

Sometimes, a block of terrible code exists for a good reason. Usually, it exists because someone was lazy or incompetent, which while not a good reason, at least makes sense. Sometimes, it exists for a stupid reason.

Janet’s company recently bought another company, and now the new company had to be integrated into their IT operations. One of the little, tiny, minuscule known-issues in the new company’s system was that their logging was mis-configured. Instead of putting a new-line after each logging message, it put only a single space.

That tiny problem was a little bit larger, as each log message was a JSON object. The whole point of logging out a single JSON document per line was that it would be easy to parse/understand the log messages, but since they were all on a single line, it was impossible to just do that.

The developers at the acquired company were left with a choice: they could fix the glitch in the logging system so that it output a newline after each message, or they could just live with this. For some reason, they decided to live with it, and they came up with this solution for parsing the log files:

def parse(string):
  obs = []
  j = ""
  for c in string.split():
    j += c
    try:
      obs.append(json.loads(j))
      j = ""
    except ValueError:
      pass
 
  return obs

This splits the string on spaces. Then, for each substring, it tries to parse it as a JSON object. If it succeeds, great. If it throws an exception, append the next substring to this one, and then try parsing again. Repeat until we’ve built a valid JSON document, than clear out the accumulator and repeat the process for all the rest of the messages. Eventually, return all the log messages parsed as JSON.

As a fun side effect, .split is going to throw the spaces away, so when they j += c, if your log message looked like:

{"type": "Error", "message": "Unable to parse JSON document"}

After parsing that into JSON, the message becomes UnabletoparseJSONdocument.

But at least they didn’t have to solve than newline bug.

[Advertisement] Forget logs. Next time you're struggling to replicate error, crash and performance issues in your apps - Think Raygun! Installs in minutes. Learn more.


Coded Smorgasbord: Driven to Substraction
Wednesday Oct 9, 2019 6:30 AM

Deon (previously) has some good news. His contract at Initrode is over, and he’s on his way out the door. But before he goes, he wants to share more of his pain with us.

You may remember that the StringManager class had a bunch of data type conversions to numbers and dates. Well guess what, there’s also a DateManager class, which is another 1600 lines of methods to handle dates.

As you might expect, there are a pile of re-invented conversion and parsing methods which do the same thing as the built-in methods. But there’s also utility methods to help us handle date-related operations.

		public static int subStractFromCurrentDate(System.DateTime dateTimeParm) 
		{
			//get now
			System.DateTime now = System.DateTime.Now;
			//now compare days
			int daysDifference  = now.Day - dateTimeParm.Day;
			return daysDifference ;
		}

Fun fact: the Day property returns the day of the month. So this method might “subStract”, but if these two dates fall in different months, we’re going to get unexpected results.

One of the smaller string formatters included is this one:

		public static string formatEnglishDate (System.DateTime inputDateTime) 
		{
			Hashtable _monthsInEnglishByMonthNumber = new Hashtable();
			_monthsInEnglishByMonthNumber[1] = "January";
			_monthsInEnglishByMonthNumber[2] = "February";
			_monthsInEnglishByMonthNumber[3] = "March";
			_monthsInEnglishByMonthNumber[4] = "April";
			_monthsInEnglishByMonthNumber[5] = "May";
			_monthsInEnglishByMonthNumber[6] = "June";
			_monthsInEnglishByMonthNumber[7] = "July";
			_monthsInEnglishByMonthNumber[8] = "August";
			_monthsInEnglishByMonthNumber[9] = "September";
			_monthsInEnglishByMonthNumber[10] = "October";
			_monthsInEnglishByMonthNumber[11] = "November";
			_monthsInEnglishByMonthNumber[12] = "December";

			StringBuilder _dateBldr = new StringBuilder();
			_dateBldr.Append(_monthsInEnglishByMonthNumber[inputDateTime.Month].ToString());
			_dateBldr.Append(" ");
			_dateBldr.Append(inputDateTime.Day.ToString());
			_dateBldr.Append(", ");
			_dateBldr.Append(inputDateTime.Year.ToString());

			return _dateBldr.ToString();
		}

Among all the bad things implied here, I really like that they used a Hashtable as an array.

        public static bool  currentDateIsFirstBusinessDateOfTheMonth 
                            (
                                Hashtable inputHolidayHash
                            )
        {
            /*
             * If current date is not a business date, then it cannot
             * be the first business date of the month.
             */
            DateTime _currentDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
            _currentDate =
                new DateTime(2010, 5, 6);
            if (
                    _currentDate.DayOfWeek == DayOfWeek.Saturday
                    ||
                    _currentDate.DayOfWeek == DayOfWeek.Sunday
                    ||
                    inputHolidayHash[_currentDate] != null
                )
                return false;

            /*
             * If current date is a business date, and if it is also
             * the first calendar date of the month, then the
             * current date is the first business date of the month.
             */

            DateTime _firstDayOfTheMonth =
                _currentDate.AddDays(1 - _currentDate.Day);
            if (_firstDayOfTheMonth == _currentDate)
                return true;

            /*
             * If current date is a business date, but is not the 1st calendar
             * date of the month, and, if, in stepping back day by day 
             * from the current date,  we encounter a business day before 
             * encountering the last calendar day of the preceding month, then the 
             * current date is NOT the first business date of the month.
            */
            DateTime _tempDate = _currentDate.AddDays(-1);
            while (_tempDate >= _firstDayOfTheMonth)
            {
                if (
                        _tempDate.DayOfWeek != DayOfWeek.Saturday
                        &&
                        _tempDate.DayOfWeek != DayOfWeek.Sunday
                        &&
                        inputHolidayHash[_tempDate] == null
                    )
                    return false;
                _tempDate = _tempDate.AddDays(-1);
            }
            /*
             * * If current date is a business date, but is not the 1st calendar
             * date,and, if, in stepping back day by day from the current date, 
             * we encounter no business day before encountering the 
             * 1st calendar day of the month, then the current date 
             * IS the first business date of the month.
            */
            return true;
        }

This one has loads of comments, and honestly, I still have no idea what it’s doing. If it’s checking the current day, why does it need to cycle through other days? Why even ask that question, because clearly while debugging they hard-coded a testing date (new DateTime(2010, 5, 6)) and just left that in there.

I’m not the only one getting confused. Check out this comment:


        //@??
        public static DateTime givenPeriodEndDateFindLastBusinessDateInPeriod
                                (
                                    DateTime inputPeriodEndDate
                                    , Hashtable inputHolidayHash
                                )
        {
          ...
        }

And if you’re missing good old StringManager, don’t worry, we use it here:

    /**
		 * @description format date
		 * */
		public static string formatYYYYMMDD (System.DateTime inputDateTime) 
		{
			StringBuilder _bldr = new StringBuilder();
			_bldr.Append(inputDateTime.Year.ToString());
			_bldr.Append(initrode.utilities.StringManager.Fill(inputDateTime.Month.ToString(),
															"0",       // Zero-Fill
															true,	   // Fill from left
															2));        // String length

			_bldr.Append(initrode.utilities.StringManager.Fill(inputDateTime.Day.ToString(),
															"0",       // Zero-Fill
															true,	   // Fill from left
															2));       // String length
			return _bldr.ToString();
		}

And all of this is from just about the first third of the code. I’m trying to keep to shorter methods before posting the whole blob of ugly. So with that in mind, what if you wanted to compare dates?

		public static DateComparison date1ComparedToDate2(DateTime inputDate1, 
															DateTime inputDate2)
		{
			if (inputDate1.Year > inputDate2.Year) return DateComparison.gt;
			if (inputDate1.Year < inputDate2.Year) return DateComparison.lt;
			if (inputDate1.DayOfYear > inputDate2.DayOfYear) return DateComparison.gt;
			if (inputDate1.DayOfYear < inputDate2.DayOfYear) return DateComparison.lt;
			return DateComparison.eq;
		
		}

Oh yeah, not only do we break the dates up into parts to compare them, we also have a custom enumerated type to represent the result of the comparison. And it’s not just dates, we do it with times, too.

		public static DateComparison timestamp1ComparedToTimestamp2(DateTime inputTimestamp1, 
																	DateTime inputTimestamp2)
		{
			if (inputTimestamp1.Year > inputTimestamp2.Year) return DateComparison.gt;
			if (inputTimestamp1.Year < inputTimestamp2.Year) return DateComparison.lt;
			if (inputTimestamp1.DayOfYear > inputTimestamp2.DayOfYear) return DateComparison.gt;
			if (inputTimestamp1.DayOfYear < inputTimestamp2.DayOfYear) return DateComparison.lt;
			if (inputTimestamp1.Hour > inputTimestamp2.Hour) return DateComparison.gt;
			if (inputTimestamp1.Hour < inputTimestamp2.Hour) return DateComparison.lt;
			if (inputTimestamp1.Minute > inputTimestamp2.Minute) return DateComparison.gt;
			if (inputTimestamp1.Minute < inputTimestamp2.Minute) return DateComparison.lt;
			if (inputTimestamp1.Second > inputTimestamp2.Second) return DateComparison.gt;
			if (inputTimestamp1.Second < inputTimestamp2.Second) return DateComparison.lt;
			if (inputTimestamp1.Millisecond > inputTimestamp2.Millisecond) return DateComparison.gt;
			if (inputTimestamp1.Millisecond < inputTimestamp2.Millisecond) return DateComparison.lt;
			return DateComparison.eq;
		
		}

Initrode has a bright future with this product. Deon adds:

The contractor who is replacing me has rolled his own piece of software to try and replace Entity Framework because his version is “better” despite being written around a decade ago, so I’m sure he’ll fit right in.

The future’s so bright I’ve gotta wear shades.

Here’s the full block, if you want to suffer through that:

/*
  Changes Log:

  @01 - 01/23/2009 - {some initials were here} - Improve performance of approval screens.
*/
using System;
using System.Collections;
using System.Globalization; 
using System.Text;

namespace initrode.utilities
{
	/// <summary>
	/// Summary description for DateManager.
	/// </summary>
	public class DateManager
	{
		public enum	DateComparison {gt = 1, eq = 0, lt = -1}
        public enum DateTimeParts
        {
            dateOnly
            , dateAndTime
            , dateTimeAndAMOrPM
        }
						
		/*
			* @description return the days difference from today date
			* @parm int amount of days in the past
			* @return int the amount of days difference
			* 
			**/
		public static int subStractFromCurrentDate(System.DateTime dateTimeParm) 
		{
			//get now
			System.DateTime now = System.DateTime.Now;
			//now compare days
			int daysDifference  = now.Day - dateTimeParm.Day;
			return daysDifference ;
		}
		/**
		 * @description format date
		 * */
		public static string format (System.DateTime dateTime, string format) 
		{
			string dateFormat;
			dateFormat = dateTime.ToString(format,DateTimeFormatInfo.InvariantInfo);
			return dateFormat;
		}
        public static DateTime  convertDateStringInSlashedFormatToDateTime
                                (
                                    string inputDateStringInSlashedFormat
                                )
        {
            inputDateStringInSlashedFormat =
                initrode.utilities.StringManager.StripWhitespace
                (
                    inputDateStringInSlashedFormat
                );
            ArrayList _dateParts =
                initrode.utilities.StringManager.splitIntoArrayList
                (
                    inputDateStringInSlashedFormat
                    ,@"/"
                );
            if (_dateParts.Count != 3) return new DateTime(1900, 1, 1);

            string _monthString =
                initrode.utilities.StringManager.StripWhitespace
                (
                    _dateParts[0].ToString()
                );
            if (
                    initrode.utilities.StringManager.IsValidNumber
                    (
                        _monthString
                    ) == false
                )
                new DateTime(1900, 1, 1);

            string _dayString =
                initrode.utilities.StringManager.StripWhitespace
                (
                    _dateParts[1].ToString()
                );
            if (
                    initrode.utilities.StringManager.IsValidNumber
                    (
                        _dayString
                    ) == false
                )
                new DateTime(1900, 1, 1);

            string _yearString =
                initrode.utilities.StringManager.StripWhitespace
                (
                    _dateParts[2].ToString()
                );
            if (
                    initrode.utilities.StringManager.IsValidNumber
                    (
                        _yearString
                    ) == false
                )
                new DateTime(1900, 1, 1);
            return new DateTime
                        (
                            Convert.ToInt32
                            (
                                _yearString
                            )
                            , Convert.ToInt32
                            (
                                _monthString
                            )
                            , Convert.ToInt32
                            (
                                _dayString
                            )
                        );
        }            
		/**
		 * @description format date
		 * */
		public static string formatEnglishDate (System.DateTime inputDateTime) 
		{
			Hashtable _monthsInEnglishByMonthNumber = new Hashtable();
			_monthsInEnglishByMonthNumber[1] = "January";
			_monthsInEnglishByMonthNumber[2] = "February";
			_monthsInEnglishByMonthNumber[3] = "March";
			_monthsInEnglishByMonthNumber[4] = "April";
			_monthsInEnglishByMonthNumber[5] = "May";
			_monthsInEnglishByMonthNumber[6] = "June";
			_monthsInEnglishByMonthNumber[7] = "July";
			_monthsInEnglishByMonthNumber[8] = "August";
			_monthsInEnglishByMonthNumber[9] = "September";
			_monthsInEnglishByMonthNumber[10] = "October";
			_monthsInEnglishByMonthNumber[11] = "November";
			_monthsInEnglishByMonthNumber[12] = "December";

			StringBuilder _dateBldr = new StringBuilder();
			_dateBldr.Append(_monthsInEnglishByMonthNumber[inputDateTime.Month].ToString());
			_dateBldr.Append(" ");
			_dateBldr.Append(inputDateTime.Day.ToString());
			_dateBldr.Append(", ");
			_dateBldr.Append(inputDateTime.Year.ToString());

			return _dateBldr.ToString();
		}
        public static bool currentDateIsFirstSaturdayOfTheMonth()
        {
            /*
             * If current date is not a business date, then it cannot
             * be the first business date of the month.
             */
            DateTime _currentDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
            if (
                    _currentDate.DayOfWeek == DayOfWeek.Saturday
                    &&
                    _currentDate.Day <= 7
                )
                return true;

            return false;
        }

        public static bool  currentDateIsFirstBusinessDateOfTheMonth 
                            (
                                Hashtable inputHolidayHash
                            )
        {
            /*
             * If current date is not a business date, then it cannot
             * be the first business date of the month.
             */
            DateTime _currentDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
            _currentDate =
                new DateTime(2010, 5, 6);
            if (
                    _currentDate.DayOfWeek == DayOfWeek.Saturday
                    ||
                    _currentDate.DayOfWeek == DayOfWeek.Sunday
                    ||
                    inputHolidayHash[_currentDate] != null
                )
                return false;

            /*
             * If current date is a business date, and if it is also
             * the first calendar date of the month, then the
             * current date is the first business date of the month.
             */

            DateTime _firstDayOfTheMonth =
                _currentDate.AddDays(1 - _currentDate.Day);
            if (_firstDayOfTheMonth == _currentDate)
                return true;

            /*
             * If current date is a business date, but is not the 1st calendar
             * date of the month, and, if, in stepping back day by day 
             * from the current date,  we encounter a business day before 
             * encountering the last calendar day of the preceding month, then the 
             * current date is NOT the first business date of the month.
            */
            DateTime _tempDate = _currentDate.AddDays(-1);
            while (_tempDate >= _firstDayOfTheMonth)
            {
                if (
                        _tempDate.DayOfWeek != DayOfWeek.Saturday
                        &&
                        _tempDate.DayOfWeek != DayOfWeek.Sunday
                        &&
                        inputHolidayHash[_tempDate] == null
                    )
                    return false;
                _tempDate = _tempDate.AddDays(-1);
            }
            /*
             * * If current date is a business date, but is not the 1st calendar
             * date,and, if, in stepping back day by day from the current date, 
             * we encounter no business day before encountering the 
             * 1st calendar day of the month, then the current date 
             * IS the first business date of the month.
            */
            return true;
        }
        //@??
        public static DateTime givenPeriodEndDateFindLastBusinessDateInPeriod
                                (
                                    DateTime inputPeriodEndDate
                                    , Hashtable inputHolidayHash
                                )
        {
            if (inputHolidayHash[inputPeriodEndDate] == null)
                return inputPeriodEndDate;
            DateTime _tempDate = inputPeriodEndDate.AddDays(-1);

            while (
                        (
                            _tempDate.DayOfWeek == DayOfWeek.Saturday
                            ||
                            _tempDate.DayOfWeek == DayOfWeek.Sunday
                        )
                        ||
                        inputHolidayHash[_tempDate] != null
                    )
            {
                _tempDate = _tempDate.AddDays(-1);
            }
            return _tempDate;
        }

		/**
		 * @description format date
		 * */
        public static string convertDateTimeToSQLDate
                                (
                                    DateTime inputDateTime
                                )
        {
            StringBuilder _sqlDateBldr =
                new StringBuilder();
            _sqlDateBldr.AppendFormat
            (
                "{0}/{1}/{2}"
                ,inputDateTime.Month.ToString()
                ,inputDateTime.Day.ToString()
                ,inputDateTime.Year.ToString()
            );
            return _sqlDateBldr.ToString();
        }
        /**
         * @description format date
         * */
        public static string convertDateTimeToDB2Timestamp
                                (
                                    DateTime inputDateTime
                                )
        {
            StringBuilder _sqlDateBldr =
                new StringBuilder();
            _sqlDateBldr.AppendFormat
            (
                "{0}-{1}-{2}.{3}:{4}:{5}.{6}"
                , inputDateTime.Year.ToString()
                ,   initrode.utilities.StringManager.Fill
                    (
                        inputDateTime.Month.ToString()
                        ,"0"
                        ,true  //boolFromLeft
                        ,2
                    )
                ,   initrode.utilities.StringManager.Fill
                    (
                        inputDateTime.Day.ToString()
                        ,"0"
                        ,true  //boolFromLeft
                        ,2
                    )
                , initrode.utilities.StringManager.Fill
                    (
                        inputDateTime.Hour.ToString()
                        ,"0"
                        ,true  //boolFromLeft
                        ,2
                    )
                , initrode.utilities.StringManager.Fill
                    (
                        inputDateTime.Minute.ToString()
                        ,"0"
                        ,true  //boolFromLeft
                        ,2
                    )
                ,   initrode.utilities.StringManager.Fill
                    (
                        inputDateTime.Second.ToString()
                        , "0"
                        , true  //boolFromLeft
                        , 2
                    )
                ,   initrode.utilities.StringManager.Fill
                    (
                        inputDateTime.Millisecond.ToString()
                        , "0"
                        , true  //boolFromLeft
                        , 2
                    )
            );
            return _sqlDateBldr.ToString();
        }

		/**
		 * @description format date
		 * */
		public static string formatYYYYMMDD (System.DateTime inputDateTime) 
		{
			StringBuilder _bldr = new StringBuilder();
			_bldr.Append(inputDateTime.Year.ToString());
			_bldr.Append(initrode.utilities.StringManager.Fill(inputDateTime.Month.ToString(),
															"0",       // Zero-Fill
															true,	   // Fill from left
															2));        // String length

			_bldr.Append(initrode.utilities.StringManager.Fill(inputDateTime.Day.ToString(),
															"0",       // Zero-Fill
															true,	   // Fill from left
															2));       // String length
			return _bldr.ToString();
		}
		//@01
		public static DateTime givenDateGetPeriodStartDate(DateTime inputDate1)
		{
			if (inputDate1.Day > 15) return new DateTime(inputDate1.Year,inputDate1.Month,16);
			return new DateTime(inputDate1.Year,inputDate1.Month,1);
		}
		//@01
		public static DateTime givenDateGetPeriodEndDate(DateTime inputDate1)
		{
			if (inputDate1.Day < 16) return new DateTime(inputDate1.Year,inputDate1.Month,15);
			inputDate1 = inputDate1.AddMonths(1);
			inputDate1 = new DateTime(inputDate1.Year,inputDate1.Month,1).AddDays(-1);
			return inputDate1;
		}

		/**
		 * @description add days to a date
		 * */
		public static DateTime addDays (DateTime dateTime, int days) 
		{
			DateTime newDate = dateTime.AddDays(days);
			return newDate;
		}
		/** 
		 * @description get first day of the  month from mm-dd-yyyy formatted string
		 * **/
		public static DateTime getFirstDayofTheMonthFromMM_DD_YYYYFormattedString(
									string inputDateTimeInMM_DD_YYYYFormatString) 
		{
			if (initrode.utilities.StringManager.IsValidDateInMM_DD_YYYYFormat(inputDateTimeInMM_DD_YYYYFormatString) == false)
			{
				return initrode.utilities.DateManager.getFirstDayofTheCurrentMonth();
			}
			return initrode.utilities.DateManager.getFirstDayofTheMonth(Convert.ToDateTime(inputDateTimeInMM_DD_YYYYFormatString));
		}


		/** 
		 * @description get first day of the  month
		 * **/
		public static DateTime getFirstDayofTheMonth(System.DateTime inputDateTime) 
		{
			return new DateTime(inputDateTime.Year,
								inputDateTime.Month,
								1);
		}

        public static DateTime  convertTimestampOrDateInAnyStringFormatToDateTime
                                (
                                    string inputTimestampOrDateInAnyStringFormat
                                )
        {
            DateTime _returnDateTime = 
                new DateTime(1900, 1, 1);
            ArrayList _splitDateTimeParts = new ArrayList();
            inputTimestampOrDateInAnyStringFormat =
                initrode.utilities.StringManager.StripWhitespaceFromEnds
                (
                    inputTimestampOrDateInAnyStringFormat
                );
            DateTimeParts _myDateTimeParts = DateTimeParts.dateOnly;
            string _timeParts = "";
            string _amOrPMParts = "";
            if (inputTimestampOrDateInAnyStringFormat.Contains(" "))
            {
                _splitDateTimeParts =
                    initrode.utilities.StringManager.splitIntoArrayList
                    (
                        inputTimestampOrDateInAnyStringFormat
                        , " "
                    );
            }
            else
            {
                _splitDateTimeParts.Add
                (
                    inputTimestampOrDateInAnyStringFormat
                );
            }
            DateTime _dateOnly = new DateTime(1900, 1, 1);
            switch (_splitDateTimeParts.Count)
            {
                case 1:
                    _myDateTimeParts = DateTimeParts.dateOnly;
                    _dateOnly =
                        initrode.utilities.DateManager.convertDateInAnyStringFormatIntoDateTime
                        (
                            inputTimestampOrDateInAnyStringFormat
                        );
                    break;
                case 2:
                    _myDateTimeParts = DateTimeParts.dateAndTime;
                    _dateOnly =
                        initrode.utilities.DateManager.convertDateInAnyStringFormatIntoDateTime
                        (
                            _splitDateTimeParts[0].ToString()
                        );
                    _timeParts =
                        initrode.utilities.StringManager.StripWhitespace
                        (
                            _splitDateTimeParts[1].ToString()
                        );
                    break;
                case 3:
                    _myDateTimeParts = DateTimeParts.dateTimeAndAMOrPM;
                    _dateOnly =
                        initrode.utilities.DateManager.convertDateInAnyStringFormatIntoDateTime
                        (
                            _splitDateTimeParts[0].ToString()
                        );
                    _timeParts =
                        initrode.utilities.StringManager.StripWhitespace
                        (
                            _splitDateTimeParts[1].ToString()
                        );
                    _amOrPMParts =
                        initrode.utilities.StringManager.StripWhitespace
                        (
                            _splitDateTimeParts[2].ToString()
                        ).ToUpper();

                    break;
                default:
                    return _returnDateTime;
            }
            if (_myDateTimeParts == DateTimeParts.dateOnly) return _dateOnly;
            if (_dateOnly == new DateTime(1900, 1, 1)) return _returnDateTime;

            if (
                    _myDateTimeParts == DateTimeParts.dateTimeAndAMOrPM
                    &&
                    _amOrPMParts.CompareTo("AM") != 0
                    &&
                    _amOrPMParts.CompareTo("PM") != 0
                ) return _returnDateTime;
                
            switch (_myDateTimeParts)
            {
                case DateTimeParts.dateAndTime:
                return  initrode.utilities.DateManager.convertTimeInStringFormatAlongWithDateOnlyDateTimeIntoDateTime
                        (
                            _timeParts //string inputStrTime
                            , false //bool inputAMOrPMFormat
                            , "" //string inputAMOrPM
                            , _dateOnly //DateTime inputDateOnlyDateTime
                        );
                case DateTimeParts.dateTimeAndAMOrPM:
                return initrode.utilities.DateManager.convertTimeInStringFormatAlongWithDateOnlyDateTimeIntoDateTime
                        (
                            _timeParts //string inputStrTime
                            , true //bool inputAMOrPMFormat
                            , _amOrPMParts //string inputAMOrPM
                            , _dateOnly //DateTime inputDateOnlyDateTime
                        );
            }
            return _returnDateTime;
        }
        public static DateTime convertTimeInStringFormatAlongWithDateOnlyDateTimeIntoDateTime
                                (
                                    string inputStrTime
                                    ,bool inputAMOrPMFormat
                                    ,string inputAMOrPM
                                    ,DateTime inputDateOnlyDateTime
                                )
        {
            DateTime _returnDateTime = inputDateOnlyDateTime;
            if (inputStrTime.Contains(":") == false) return _returnDateTime;

            int _intMillisecondsPart = 0;
            if (inputStrTime.Contains(".") == true)
            {
                ArrayList _millisecondsAndTimeParts =
                    initrode.utilities.StringManager.splitIntoArrayList
                    (
                        inputStrTime
                        ,@"."
                    );
                if (_millisecondsAndTimeParts.Count != 2) return _returnDateTime;
                string _strMillisecondsPart =
                    initrode.utilities.StringManager.StripWhitespace
                    (
                        _millisecondsAndTimeParts[1].ToString()
                    );
                if (initrode.utilities.StringManager.IsValidNumber(_strMillisecondsPart) == true)
                    _intMillisecondsPart =
                        Convert.ToInt32
                        (
                            _strMillisecondsPart
                        );
                inputStrTime =
                    initrode.utilities.StringManager.StripWhitespace
                    (
                        _millisecondsAndTimeParts[0].ToString()
                    );
            }
            ArrayList _timeParts =
                initrode.utilities.StringManager.splitIntoArrayList
                (
                    inputStrTime
                    ,":"
                );
            if (_timeParts.Count != 3) return _returnDateTime;


            string _strHoursPart =
                initrode.utilities.StringManager.StripWhitespace
                (
                    _timeParts[0].ToString()
                );
            string _strMinutesPart =
                initrode.utilities.StringManager.StripWhitespace
                (
                    _timeParts[1].ToString()
                );
            string _strSecondsPart =
                initrode.utilities.StringManager.StripWhitespace
                (
                    _timeParts[2].ToString()
                );
            if (
                    initrode.utilities.StringManager.IsValidNumber
                    (
                        _strHoursPart
                    ) == false
                    ||
                    initrode.utilities.StringManager.IsValidNumber
                    (
                        _strMinutesPart
                    ) == false
                    ||
                    initrode.utilities.StringManager.IsValidNumber
                    (
                        _strSecondsPart
                    ) == false
                ) return _returnDateTime;

            int _intHoursPart =
                Convert.ToInt32
                (
                    _strHoursPart
                );
            int _intMinutesPart =
                Convert.ToInt32
                (
                    _strMinutesPart
                );
            int _intSecondsPart =
                Convert.ToInt32
                (
                    _strSecondsPart
                );

            if (_intHoursPart > 23) return _returnDateTime;
            if (inputAMOrPMFormat == true)
            {
                if (_intHoursPart > 12) return _returnDateTime;
            }
            if (_intMinutesPart > 59) return _returnDateTime;
            if (_intSecondsPart > 59) return _returnDateTime;

            if (inputAMOrPMFormat == true)
            {
                if (inputAMOrPM.CompareTo("PM") == 0)
                {
                    _intHoursPart += 12;
                }
                else if (
                            inputAMOrPM.CompareTo("AM") == 0
                            &&
                            _intHoursPart == 12
                            &&
                            _intMinutesPart == 0
                            &&
                            _intSecondsPart == 0
                            &&
                            _intMillisecondsPart == 0
                        )
                {
                    return new DateTime
                                (
                                    inputDateOnlyDateTime.Year
                                    , inputDateOnlyDateTime.Month
                                    , inputDateOnlyDateTime.Day
                                );
                }
            }
            _returnDateTime =
                new DateTime
                    (
                        inputDateOnlyDateTime.Year
                        , inputDateOnlyDateTime.Month
                        , inputDateOnlyDateTime.Day
                        , _intHoursPart
                        , _intMinutesPart
                        , _intSecondsPart
                        , _intMillisecondsPart
                    );
            return _returnDateTime;
        }
        public static DateTime convertDateInAnyStringFormatIntoDateTime
                                (
                                    string inputDateInAnyStringFormat   
                                )
        {
            DateTime _returnDateTime = new DateTime(1900, 1, 1);
            inputDateInAnyStringFormat =
                initrode.utilities.StringManager.StripWhitespace
                (
                    inputDateInAnyStringFormat
                );
            ArrayList _dateParts = new ArrayList();
            string _strMonth = "";
            string _strDay = "";
            string _strYear = "";
            if (inputDateInAnyStringFormat.Contains("/") == true)
            {
                _dateParts =
                    initrode.utilities.StringManager.splitIntoArrayList
                    (
                        inputDateInAnyStringFormat
                        ,@"/"
                    );
                if (_dateParts.Count != 3) return _returnDateTime;
                _strMonth =
                        initrode.utilities.StringManager.StripWhitespace
                        (
                            _dateParts[0].ToString()
                        );
                _strDay =
                        initrode.utilities.StringManager.StripWhitespace
                        (
                            _dateParts[1].ToString()
                        );
                _strYear =
                        initrode.utilities.StringManager.StripWhitespace
                        (
                            _dateParts[2].ToString()
                        );
                return initrode.utilities.DateManager.convertDateTimeStringPartsIntoDateTime
                        (
                            _strMonth
                            ,_strDay
                            ,_strYear
                        );
            }
            if (inputDateInAnyStringFormat.Contains("-") == true)
            {
                _dateParts =
                    initrode.utilities.StringManager.splitIntoArrayList
                    (
                        inputDateInAnyStringFormat
                        , @"-"
                    );
                if (_dateParts.Count != 3) return _returnDateTime;
                _strYear =
                        initrode.utilities.StringManager.StripWhitespace
                        (
                            _dateParts[0].ToString()
                        );
                _strMonth =
                        initrode.utilities.StringManager.StripWhitespace
                        (
                            _dateParts[1].ToString()
                        );
                _strDay =
                        initrode.utilities.StringManager.StripWhitespace
                        (
                            _dateParts[2].ToString()
                        );
                return initrode.utilities.DateManager.convertDateTimeStringPartsIntoDateTime
                        (
                            _strMonth
                            , _strDay
                            , _strYear
                        );
            }
            if (inputDateInAnyStringFormat.Length == 8)
            {
                _strYear =
                    inputDateInAnyStringFormat.Substring(0, 4);
                _strMonth =
                    inputDateInAnyStringFormat.Substring(4, 2);
                _strDay =
                    inputDateInAnyStringFormat.Substring(6, 2);
                return initrode.utilities.DateManager.convertDateTimeStringPartsIntoDateTime
                        (
                            _strMonth
                            , _strDay
                            , _strYear
                        );
            }
            if (inputDateInAnyStringFormat.Length == 6)
            {
                _strYear =
                    inputDateInAnyStringFormat.Substring(0, 2);
                _strMonth =
                    inputDateInAnyStringFormat.Substring(2, 2);
                _strDay =
                    inputDateInAnyStringFormat.Substring(4, 2);
                return initrode.utilities.DateManager.convertDateTimeStringPartsIntoDateTime
                        (
                            _strMonth
                            , _strDay
                            , _strYear
                        );
            }
            return _returnDateTime;
        }
        public static DateTime convertDateTimeStringPartsIntoDateTime
                                (
                                    string inputStrMonth
                                    , string inputStrDay
                                    , string inputStrYear
                                )
        {
            DateTime _returnDateTime = new DateTime(1900, 1, 1);
            if (
                    initrode.utilities.StringManager.IsValidNumber
                    (
                        inputStrMonth
                    ) == false
                    ||
                    initrode.utilities.StringManager.IsValidNumber
                    (
                        inputStrDay
                    ) == false
                    ||
                    initrode.utilities.StringManager.IsValidNumber
                    (
                        inputStrYear
                    ) == false
                ) return _returnDateTime;

            int _intYear =
                Convert.ToInt32
                (
                    inputStrYear
                );
            if (_intYear <= 100)
            {
                if (_intYear >= 90)
                {
                    _intYear += 1900;
                }
                else
                {
                    _intYear += 2000;
                }
            }
            inputStrYear = _intYear.ToString();

            inputStrMonth = 
                initrode.utilities.StringManager.Fill
                (
                    inputStrMonth
                    ,"0"
                    ,true //fromLeft
                    ,2
                );

            inputStrDay = 
                initrode.utilities.StringManager.Fill
                (
                    inputStrDay
                    ,"0"
                    ,true //fromLeft
                    ,2
                );

            if (
                    initrode.utilities.StringManager.IsValidDate
                    (
                        inputStrMonth
                        ,inputStrDay
                        ,inputStrYear
                    ) == false
                ) return _returnDateTime;

            _returnDateTime =
                new DateTime
                    (
                        Convert.ToInt32
                        (
                            inputStrYear
                        )
                        ,   Convert.ToInt32
                            (
                                inputStrMonth
                            )
                        , Convert.ToInt32
                            (
                                inputStrDay
                            )
                    );
            return _returnDateTime;
        }
        public static DateTime convertDateIn_MM_Slash_DD_Slash_YYYY_FormatToDateTime
                                (
                                    string inputDateIn_MM_Slash_DD_Slash_YYYY_Format
                                )
        {
            if (initrode.utilities.StringManager.IsValidDateInMM_DD_YYYYFormat(inputDateIn_MM_Slash_DD_Slash_YYYY_Format) == false)
                return Convert.ToDateTime("1/1/1900");
            ArrayList _dateParts =
                initrode.utilities.StringManager.splitIntoArrayList
                (
                    inputDateIn_MM_Slash_DD_Slash_YYYY_Format
                    ,"/"
                );
            string _mm = _dateParts[0].ToString();
            if (_mm.Substring(0, 1).CompareTo("0") == 0)
                _mm = _mm.Substring(1, 1);
            string _dd = _dateParts[1].ToString();
            if (_dd.Substring(0, 1).CompareTo("0") == 0)
                _dd = _dd.Substring(1, 1);
            string _yyyy = _dateParts[2].ToString();

            return new DateTime
                        (
                                Convert.ToInt32
                                (
                                    _yyyy
                                )
                            ,   Convert.ToInt32
                                (
                                    _mm
                                )
                            ,   Convert.ToInt32
                                (
                                    _dd
                                )
                        );
        }
        public static bool  isInputtedDateTheLastBusinessDateOfTheMonth
                            (
                                DateTime inputDateTime
                                , Hashtable inputHolidayHash
                            )
        {
            inputDateTime =
                new DateTime
                    (
                        inputDateTime.Year
                        , inputDateTime.Month
                        , inputDateTime.Day
                    );

            DateTime _lastBusinessDate =
                initrode.utilities.DateManager.getLastBusinessDateOfMonthForInputtedDate
                (
                    inputDateTime
                    ,inputHolidayHash
                );
            if (
                    inputDateTime.Year == _lastBusinessDate.Year
                    && inputDateTime.Month == _lastBusinessDate.Month
                    && inputDateTime.Day == _lastBusinessDate.Day
                )
                return true;
            return false;
        }

        public static DateTime  getLastBusinessDateOfMonthForInputtedDate
                                (
                                    DateTime inputDateTime
                                    , Hashtable inputHolidayHash
                                )
        {
            inputDateTime = 
                new DateTime
                    (
                        inputDateTime.Year
                        ,inputDateTime.Month
                        ,inputDateTime.Day
                    );
            DateTime _lastBusinessDate;
            if (
                    initrode.utilities.DateManager.isInputtedDateABusinessDate
                    (
                        inputDateTime
                        , inputHolidayHash
                    ) == true
                )
                _lastBusinessDate =
                    inputDateTime;
            else
                _lastBusinessDate =
                    initrode.utilities.DateManager.getNextBusinessDateFromInputtedDate
                    (
                        inputDateTime
                        , inputHolidayHash
                    );
            if (_lastBusinessDate.Month != inputDateTime.Month)
            {
                if (
                        initrode.utilities.DateManager.isInputtedDateABusinessDate
                        (
                            inputDateTime
                            , inputHolidayHash
                        ) == true
                    )
                    return inputDateTime;
                else
                    return
                        initrode.utilities.DateManager.getPreviousBusinessDateFromInputtedDate
                        (
                            inputDateTime
                            , inputHolidayHash
                        );
            } 
            DateTime _nextBusinessDate =
                initrode.utilities.DateManager.getNextBusinessDateFromInputtedDate
                (
                    _lastBusinessDate
                    , inputHolidayHash
                );
            while (_nextBusinessDate.Month == inputDateTime.Month)
            {
                _lastBusinessDate =
                    _nextBusinessDate;

                _nextBusinessDate =
                    initrode.utilities.DateManager.getNextBusinessDateFromInputtedDate
                    (
                        _lastBusinessDate
                        , inputHolidayHash
                    );
            }
            return _lastBusinessDate;
        }
        public static DateTime  getPreviousBusinessDateFromInputtedDate
                                (
                                    DateTime inputDateTime
                                    , Hashtable inputHolidayHash
                                )
        {
            DateTime _dateWithTimeOmitted =
                new DateTime
                    (
                        inputDateTime.Year
                        , inputDateTime.Month
                        , inputDateTime.Day
                    );
            _dateWithTimeOmitted =
                _dateWithTimeOmitted.AddDays(-1);
            while (
                        initrode.utilities.DateManager.isInputtedDateABusinessDate
                        (
                            _dateWithTimeOmitted
                            , inputHolidayHash
                        ) == false
                    )
            {
                _dateWithTimeOmitted =
                    _dateWithTimeOmitted.AddDays(-1);
            }
            return _dateWithTimeOmitted;
        }

        public static DateTime  getNextBusinessDateFromInputtedDate
                                (
                                    DateTime inputDateTime
                                    , Hashtable inputHolidayHash
                                )
        {
            DateTime _dateWithTimeOmitted =
                new DateTime
                    (
                        inputDateTime.Year
                        , inputDateTime.Month
                        , inputDateTime.Day
                    );
            _dateWithTimeOmitted.AddDays(1);
            while   (
                        initrode.utilities.DateManager.isInputtedDateABusinessDate
                        (
                            _dateWithTimeOmitted
                            ,inputHolidayHash
                        ) == false
                    )
            {
                _dateWithTimeOmitted.AddDays(1);
            }
            return _dateWithTimeOmitted;
        }

        public static bool      isInputtedDateABusinessDate
                                (
                                    DateTime inputDateTime
                                    ,Hashtable inputHolidayHash
                                )
        {
            DateTime _dateWithTimeOmitted =
                new DateTime
                    (
                        inputDateTime.Year
                        ,inputDateTime.Month
                        ,inputDateTime.Day
                    );
            if (_dateWithTimeOmitted.DayOfWeek == DayOfWeek.Saturday
                || _dateWithTimeOmitted.DayOfWeek == DayOfWeek.Sunday)
                return false;
            foreach (DateTime _holidayDate in inputHolidayHash.Keys)
            {
                if (
                        _holidayDate.Year == inputDateTime.Year
                        && _holidayDate.Month == inputDateTime.Month
                        && _holidayDate.Day == inputDateTime.Day
                    )
                {
                    return false;
                }
            }
            return true;
        }
        public static string    convertDateTimeToMMDDYYYY_WithoutSlashesOrDashes
                                (
                                    DateTime inputDateTime
                                )
        {
            StringBuilder _dateBldr =
                new StringBuilder();
            _dateBldr.AppendFormat
            (
                "{0}{1}{2}"
                , initrode.utilities.StringManager.Fill
                (
                    inputDateTime.Month.ToString()
                    , "0"
                    , true //from left
                    , 2
                )
                ,initrode.utilities.StringManager.Fill
                (
                    inputDateTime.Day.ToString()
                    , "0"
                    , true //from left
                    , 2
                )
                ,inputDateTime.Year.ToString()
            );
            return _dateBldr.ToString();
        }
        public static DateTime  convertMMDDYYYY_WithoutSlashesOrDashesToDateTime
                                (
                                    string inputMMDDYYYY
                                )
        {
            inputMMDDYYYY = 
                initrode.utilities.StringManager.StripWhitespace
                (
                    inputMMDDYYYY
                );
            StringBuilder _mmSlashddSlashyyyyBldr =
                new StringBuilder();
            _mmSlashddSlashyyyyBldr.AppendFormat
            (
                "{0}/{1}/{2}"
                ,inputMMDDYYYY.Substring(0,2)
                ,inputMMDDYYYY.Substring(2,2)
                ,inputMMDDYYYY.Substring(4,4)
            );
            if (
                    initrode.utilities.StringManager.IsValidDateInMM_DD_YYYYFormat
                    (
                        _mmSlashddSlashyyyyBldr.ToString()
                    ) == false
                )
                return new DateTime(1900, 1, 1);
            DateTime _returnDateTime =
                new DateTime
                    (
                        Convert.ToInt32
                        (
                            inputMMDDYYYY.Substring(4, 4)
                        )
                        , Convert.ToInt32
                        (
                            inputMMDDYYYY.Substring(0, 2)
                        )
                        , Convert.ToInt32
                        (
                            inputMMDDYYYY.Substring(2, 2)
                        )
                    );
            return _returnDateTime;
        }

		public static DateTime	convertDateInYYYYMMDDFormatToDateTime
								(
									string inputDateInYYYYMMDDFormat
								)
		{
			if (initrode.utilities.StringManager.IsValidDateInYYYYMMDDFormat(inputDateInYYYYMMDDFormat) == false) 
                return Convert.ToDateTime("1/1/1900");
			return new	DateTime
						(
							Convert.ToInt32(inputDateInYYYYMMDDFormat.Substring(0,4))
							,Convert.ToInt32(inputDateInYYYYMMDDFormat.Substring(4,2))
							,Convert.ToInt32(inputDateInYYYYMMDDFormat.Substring(6,2))
						);
		}
		public static DateTime	getNextPeriodStartDateFromGivenDate
								(
									DateTime inputDate
								)
		{
			if (inputDate.Day == 1) return inputDate;
			if (inputDate.Day == 16) return inputDate;
			if (inputDate.Day <= 15) return inputDate.AddDays(16 - inputDate.Day);
			return inputDate.AddMonths(1).AddDays(1 - inputDate.Day);
		}
		public static DateTime	getNextPeriodEndDateFromGivenPeriodStartDate
								(
									DateTime inputPeriodStartDate
								)
		{
			if (inputPeriodStartDate.Day == 1) return inputPeriodStartDate.AddDays(15 - inputPeriodStartDate.Day);
			return inputPeriodStartDate.AddMonths(1).AddDays(0 - inputPeriodStartDate.Day);
		}

		public static DateTime	convertDateInYYYYMMDDFormatAndTimeInHHColonMIColonSSFormatToDateTime
								(
									string inputDateInYYYYMMDDFormat,
									string inputTimeInHHColonMIColonSSFormat
								)
		{
			inputDateInYYYYMMDDFormat = initrode.utilities.StringManager.StripWhitespaceFromEnds(inputDateInYYYYMMDDFormat);
			inputTimeInHHColonMIColonSSFormat = initrode.utilities.StringManager.StripWhitespaceFromEnds(inputTimeInHHColonMIColonSSFormat);
			if (inputDateInYYYYMMDDFormat.Length != 8 ||
				initrode.utilities.StringManager.IsValidDateInYYYYMMDDFormat(inputDateInYYYYMMDDFormat) == false) return new DateTime(1900,1,1);
		
			if (inputTimeInHHColonMIColonSSFormat.Length != 8 ||
				initrode.utilities.StringManager.IsValidTimeInHHColonMIColonSSFormat(inputTimeInHHColonMIColonSSFormat) == false)
					return new	DateTime 
								(
									Convert.ToInt32(inputDateInYYYYMMDDFormat.Substring(0,4)),
									Convert.ToInt32(inputDateInYYYYMMDDFormat.Substring(4,2)),
									Convert.ToInt32(inputDateInYYYYMMDDFormat.Substring(6,2))
								);

			return new	DateTime 
						( 
							Convert.ToInt32(inputDateInYYYYMMDDFormat.Substring(0,4)),
							Convert.ToInt32(inputDateInYYYYMMDDFormat.Substring(4,2)),
							Convert.ToInt32(inputDateInYYYYMMDDFormat.Substring(6,2)),
							Convert.ToInt32(inputTimeInHHColonMIColonSSFormat.Substring(0,2)),
							Convert.ToInt32(inputTimeInHHColonMIColonSSFormat.Substring(3,2)),
							Convert.ToInt32(inputTimeInHHColonMIColonSSFormat.Substring(6,2))
						);
		
		}
        public static bool validateTimestampInODBCCanonicalFormat
                           (
                              string inputTimestampInODBCCanonicalFormat
                           )
        {
            if (inputTimestampInODBCCanonicalFormat.Length != 23)
                return false;

            if (initrode.utilities.StringManager.IsValidNumber(inputTimestampInODBCCanonicalFormat.Substring(0, 4)) == false
                || initrode.utilities.StringManager.IsValidNumber(inputTimestampInODBCCanonicalFormat.Substring(5, 2)) == false
                || initrode.utilities.StringManager.IsValidNumber(inputTimestampInODBCCanonicalFormat.Substring(8, 2)) == false
                || initrode.utilities.StringManager.IsValidNumber(inputTimestampInODBCCanonicalFormat.Substring(11, 2)) == false
                || initrode.utilities.StringManager.IsValidNumber(inputTimestampInODBCCanonicalFormat.Substring(14, 2)) == false
                || initrode.utilities.StringManager.IsValidNumber(inputTimestampInODBCCanonicalFormat.Substring(17, 2)) == false
                || initrode.utilities.StringManager.IsValidNumber(inputTimestampInODBCCanonicalFormat.Substring(20, 3)) == false)
                return false;

            string _yyyy =
                inputTimestampInODBCCanonicalFormat.Substring(0, 4);
            string _mm =
                inputTimestampInODBCCanonicalFormat.Substring(5, 2);
            string _dd =
                inputTimestampInODBCCanonicalFormat.Substring(8, 2);
            if (initrode.utilities.StringManager.IsValidDate
                (
                    _mm
                    ,_dd
                    ,_yyyy
                ) == false)
                return false;

            StringBuilder _timeBldr =
                new StringBuilder();
            _timeBldr.Append
            (
                inputTimestampInODBCCanonicalFormat.Substring(11, 2)
            );
            _timeBldr.Append
            (
                ":"
            );
            _timeBldr.Append
            (
                inputTimestampInODBCCanonicalFormat.Substring(14, 2)
            );
            _timeBldr.Append
            (
                ":"
            );
            _timeBldr.Append
            (
                inputTimestampInODBCCanonicalFormat.Substring(17, 2)
            );
            if (initrode.utilities.StringManager.IsValidTimeInHHColonMIColonSSFormat
                (
                    _timeBldr.ToString()
                ) == false)
                return false;
            return true;
        }
        public static DateTime  convertTimestampInODBCCanonicalFormatToDateTime
                                (
                                    string inputTimestampInODBCCanonicalFormat
                                )
        {
            if (validateTimestampInODBCCanonicalFormat
                    (
                        inputTimestampInODBCCanonicalFormat
                     ) == false)
                return new DateTime(1900, 1, 1);

            int _yyyy = 
                Convert.ToInt32(inputTimestampInODBCCanonicalFormat.Substring(0,4));
            int _mm = 
                Convert.ToInt32(inputTimestampInODBCCanonicalFormat.Substring(5,2));
            int _dd = 
                Convert.ToInt32(inputTimestampInODBCCanonicalFormat.Substring(8,2));

            int _hh =
                Convert.ToInt32(inputTimestampInODBCCanonicalFormat.Substring(11, 2));
            int _mi =
                Convert.ToInt32(inputTimestampInODBCCanonicalFormat.Substring(14, 2));
            int _ss =
                Convert.ToInt32(inputTimestampInODBCCanonicalFormat.Substring(17, 2));
            int _ms =
                Convert.ToInt32(inputTimestampInODBCCanonicalFormat.Substring(20, 3));
            return new DateTime
                        (
                            _yyyy
                            , _mm
                            , _dd
                            , _hh
                            , _mi
                            , _ss
                            , _ms
                         );   
        }

		/** 
		 * 
		 * @description get first day of the current month
		 * **/
		public static DateTime getFirstDayofTheCurrentMonth() 
		{
			return initrode.utilities.DateManager.getFirstDayofTheMonth(System.DateTime.Now);
		}

        public static DateTime convertDateTimeToDate
                                (
                                    DateTime inputTimestamp
                                )
        {
            DateTime _returnDate =
                new DateTime
                    (
                        inputTimestamp.Year
                        ,inputTimestamp.Month
                        ,inputTimestamp.Day
                    );
            return _returnDate;
        }
		/**
		 * @description get the last day of the month
		 * */
							   	
		public static DateTime getLastDayOfTheMonth( System.DateTime inputDateTime) 
		{
			return initrode.utilities.DateManager.getFirstDayofNextMonth(inputDateTime).AddDays(-1);
		}
		/** 
		 * @description get last day of the current month
		 * **/
		public static DateTime getLastDayofTheCurrentMonth() 
		{
			return initrode.utilities.DateManager.getLastDayOfTheMonth(DateTime.Now);
		}

		/** 
		 * Convert the DateTime value to YYYYMMDD format
		 * **/
		public static string convertDateTimeToYYYYMMDDFormat(DateTime inputDateTime)
		{
			StringBuilder _dateBldr = new StringBuilder();
			_dateBldr.Append(inputDateTime.Year.ToString());
			_dateBldr.Append(initrode.utilities.StringManager.Fill(inputDateTime.Month.ToString(),"0",true,2));
			_dateBldr.Append(initrode.utilities.StringManager.Fill(inputDateTime.Day.ToString(),"0",true,2));
			return _dateBldr.ToString();
		}
		/** 
		 * Convert the DateTime value to MM, DD, YYYY character parts
		 * **/
		public static void convertDateTimeToMM_DD_YYYYStringParts(DateTime inputDateTime,
																	out string outputMM,
																	out string outputDD,
																	out string outputYYYY)
		{
			string _date_in_MM_DD_YYYY_Format = 
				convertDateTimeToMM_DD_YYYYFormat(inputDateTime);
			outputMM = "";
			outputDD = "";
			outputYYYY = "";

			outputMM = _date_in_MM_DD_YYYY_Format.Substring(0,2);
			outputDD = _date_in_MM_DD_YYYY_Format.Substring(3,2);
			outputYYYY = _date_in_MM_DD_YYYY_Format.Substring(6,4);
		}
		/** 
		 * Convert the DateTime value to MM_DD_YYYY format.
		 * **/
		public static DateTime convertMM_DD_YYYYFormatToDateTime(string inputDateInMM_DD_YYYYFormat)
		{
			inputDateInMM_DD_YYYYFormat = initrode.utilities.StringManager.StripWhitespaceFromEnds(inputDateInMM_DD_YYYYFormat);
			if (initrode.utilities.StringManager.IsValidDateInMM_DD_YYYYFormat(inputDateInMM_DD_YYYYFormat) == false) return new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
			int _intMM = Convert.ToInt32(inputDateInMM_DD_YYYYFormat.Substring(0,2));
			int _intDD = Convert.ToInt32(inputDateInMM_DD_YYYYFormat.Substring(3,2));
			int _intYYYY = Convert.ToInt32(inputDateInMM_DD_YYYYFormat.Substring(6,4));
			return new DateTime(_intYYYY,_intMM, _intDD);
		}
        public static int calculateMonthsDifferenceBetweenTwoDates
                            (
                                DateTime inputOlderDate
                                , DateTime inputNewerDate
                            )
        {
            DateTime _tempDate = inputOlderDate;
            int _numberOfMonthsDifference = 0;
            while (_tempDate < inputNewerDate)
            {
                _tempDate = _tempDate.AddMonths(1);
                if (_tempDate < inputNewerDate)
                    _numberOfMonthsDifference++;
            }
            return _numberOfMonthsDifference;
        }

		/** 
		 * Convert the DateTime value to MM_DD_YYYY format.
		 * **/
		public static string convertTimestampToStringFormat(DateTime inputDateTime)
		{
			StringBuilder _bldr = new StringBuilder();
			_bldr.Append(initrode.utilities.StringManager.Fill(	
												inputDateTime.Month.ToString(),
												"0",
												true,           //Fill from left
												2));
			_bldr.Append("/");
			_bldr.Append(initrode.utilities.StringManager.Fill(	
												inputDateTime.Day.ToString(),
												"0",
												true,           //Fill from left
												2));
			_bldr.Append("/");
			_bldr.Append(inputDateTime.Year.ToString());
			_bldr.Append(" ");
			_bldr.Append(initrode.utilities.StringManager.Fill(	
												inputDateTime.Hour.ToString(),
												"0",
												true,           //Fill from left
												2));
			_bldr.Append(":");
			_bldr.Append(initrode.utilities.StringManager.Fill(	
												inputDateTime.Minute.ToString(),
												"0",
												true,           //Fill from left
												2));
			_bldr.Append(":");
			_bldr.Append(initrode.utilities.StringManager.Fill(	
												inputDateTime.Second.ToString(),
												"0",
												true,           //Fill from left
												2));
			_bldr.Append(".");
			_bldr.Append(initrode.utilities.StringManager.Fill(	
												inputDateTime.Millisecond.ToString(),
												"0",
												true,           //Fill from left
												3));

			return _bldr.ToString();
		}

		/** 
		 * Convert the DateTime value to MM_DD_YYYY format.
		 * **/
		public static string convertDateTimeToMM_DD_YYYYFormat(DateTime inputDateTime)
		{
			StringBuilder _bldr = new StringBuilder();
			_bldr.Append(initrode.utilities.StringManager.Fill(	
												inputDateTime.Month.ToString(),
												"0",
												true,           //Fill from left
												2));
			_bldr.Append("/");
			_bldr.Append(initrode.utilities.StringManager.Fill(	
												inputDateTime.Day.ToString(),
												"0",
												true,           //Fill from left
												2));
			_bldr.Append("/");
			_bldr.Append(inputDateTime.Year.ToString());
			return _bldr.ToString();
		}

		/** 
		 * @description get first day of the next  month
		 * **/
		public static DateTime getFirstDayofNextMonth(DateTime inputDateTime) 
		{
			return  initrode.utilities.DateManager.getFirstDayofTheMonth(inputDateTime).AddMonths(1);
		}


		/** 
		 * @description get first day of the next  month
		 * **/
		public static DateTime getFirstDayofNextMonth() 
		{
			return  getFirstDayofNextMonth(DateTime.Now); 
		}

		/** 
		 * @description add days to a date
		 * **/
		public static DateTime daysFromTheFirst(int days, System.DateTime date)
		{
			DateTime nextDate = date.AddDays(days); //calculate  1 day of next month
			return nextDate;
		}
		/** 
		 * 
		 * @description get first day of the current year
		 * **/
		public static DateTime getFirstDayofTheCurrentYear() 
		{
			return initrode.utilities.DateManager.getFirstDayofTheInputtedDatesYear(System.DateTime.Now);
		}
		/** 
		 * 
		 * @description get last day of the current year
		 * **/
		public static DateTime getLastDayofTheCurrentYear() 
		{
			return initrode.utilities.DateManager.getFirstDayofTheCurrentYear().AddYears(1).AddDays(-1);
		}

		/** 
		 * 
		 * @description get first day of the inputted year
		 * **/
		public static DateTime getFirstDayofTheInputtedDatesYear(System.DateTime inputDateTime) 
		{
			return new DateTime(inputDateTime.Year,1,1);
		}
		/** 
		 * 
		 * @description get last day of the inputted year
		 * **/
		public static DateTime getLastDayofTheInputtedDatesYear(System.DateTime inputDateTime) 
		{
			return new DateTime(inputDateTime.Year,12,31);
		}

		public static DateComparison timestamp1ComparedToTimestamp2(DateTime inputTimestamp1, 
																	DateTime inputTimestamp2)
		{
			if (inputTimestamp1.Year > inputTimestamp2.Year) return DateComparison.gt;
			if (inputTimestamp1.Year < inputTimestamp2.Year) return DateComparison.lt;
			if (inputTimestamp1.DayOfYear > inputTimestamp2.DayOfYear) return DateComparison.gt;
			if (inputTimestamp1.DayOfYear < inputTimestamp2.DayOfYear) return DateComparison.lt;
			if (inputTimestamp1.Hour > inputTimestamp2.Hour) return DateComparison.gt;
			if (inputTimestamp1.Hour < inputTimestamp2.Hour) return DateComparison.lt;
			if (inputTimestamp1.Minute > inputTimestamp2.Minute) return DateComparison.gt;
			if (inputTimestamp1.Minute < inputTimestamp2.Minute) return DateComparison.lt;
			if (inputTimestamp1.Second > inputTimestamp2.Second) return DateComparison.gt;
			if (inputTimestamp1.Second < inputTimestamp2.Second) return DateComparison.lt;
			if (inputTimestamp1.Millisecond > inputTimestamp2.Millisecond) return DateComparison.gt;
			if (inputTimestamp1.Millisecond < inputTimestamp2.Millisecond) return DateComparison.lt;
			return DateComparison.eq;
		
		}

		public static DateComparison date1ComparedToDate2(DateTime inputDate1, 
															DateTime inputDate2)
		{
			if (inputDate1.Year > inputDate2.Year) return DateComparison.gt;
			if (inputDate1.Year < inputDate2.Year) return DateComparison.lt;
			if (inputDate1.DayOfYear > inputDate2.DayOfYear) return DateComparison.gt;
			if (inputDate1.DayOfYear < inputDate2.DayOfYear) return DateComparison.lt;
			return DateComparison.eq;
		
		}

		/** 
		 * 
		 * @description get first day of the first Future Period
		 * **/
		public static DateTime getTheDateBeforeTheFirstFuturePeriod() 
		{
			// If date is less than the 16th, the 15th is the date.

			DateTime _date = DateTime.Now;
			if (_date.Day < 16)
			{
				return _date.AddDays(15 - _date.Day);
			}

			// If date is greater than the 16th, the 1st of the following month is
			// the first date of the first future period.

			return _date.AddDays(1 - _date.Day).AddMonths(1).AddDays(-1);
		}
	}
}
[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!


CodeSOD: Compiled Correctly

Properly used, version history can easily help you track down and identify the source of a bug. Improperly used, it still can. As previously established, the chief architect Dana works with has some issues with source control.

Dana works on a large, complex embedded system. “Suddenly”, her team started to spot huge piles of memory corruption problems. Something was misbehaving, but it was hard to see exactly what.

They ported Valgrind to their platform, just so they could try and figure out what was going wrong. Eventually, they tracked the problem down to a pair of objects.

In the flow of the code, the correct path was that object A, which we’ll call Monster would be allocated. Then a second object would be allocated. Somehow, Monster instances were corrupting the memory of the second object.

How does an object allocated earlier corrupt the memory of an object allocated later? Well, “before” and “after” have different meaning when your code is multi-threaded, which this was. Worse, the Monster class was katamari of functionality rolled up across thousands of lines of code. Obviously, there had to be a race condition- but a quick glance at all the Monster methods showed that they were using a mutex to avoid the race condition.

Or were they? Dana looked more closely. One of the methods called during the initialization process, doSomething, was marked const. In C++, that should mean that the method doesn’t change any property values. But if it doesn’t change any property values, how can it lock the mutex?

This is where walking through the commit history tells a story. “Fortunately” this was before Jerry learned you could amend a commit, so each step of his attempts to get the code to compile are recorded for posterity.

The chain of commits started with one labeled “Add Feature $X”, and our doSomething method looked like this.

  void doSomething() const {
      Mutex::ScopedLock lock(mutex);
      // Dozens of lines of code
  }

Now, the intent here was to create a ScopedLock object based off a mutex property. But that required the mutex property to change, which violated const, which meant this didn’t even compile.

Which brings up our next commit, labeled “Fix compile failure”:

  void doSomething() const {
      Mutex::ScopedLock lock(mutex) const;
      // Dozens of lines of code
  }

Surprisingly, just slapping the const declaration on the variable initialization didn’t do anything. The next commit, also helpfully labeled “Fix compile failure”:

  void doSomething() const {
      Mutex::ScopedLock lock(const mutex);
      // Dozens of lines of code
  }

Again, this didn’t work. Which brings us to the last “Fix compile failure” commit in this chain:

  void doSomething() const {
      Mutex::ScopedLock lock(const Mutex mutex);
      // Dozens of lines of code
  }

By randomly adding and subtracting symbols, Jerry was able to finally write a function which compiles. Unfortunately, it also doesn’t work, because this time, the line of code is a function declaration for a function with no implementation. It takes a mutex as a parameter, and returns a lock on that mutex. Since the declaration has no implementation, if we ever tried to call this in doSomething, we’d get an error, but we don’t, because this was always meant to be a constructor.

The end result is that nothing gets locked. Thus, the race condition means that sometimes, two threads contend with each other and corrupt memory. Dana was able to fix this method, but the root cause was only fixed when Jerry left Initech to be a CTO elsewhere.

[Advertisement] ProGet can centralize your organization's software applications and components to provide uniform access to developers and servers. Check it out!


CodeSOD: Generically Bad
Monday Oct 7, 2019 6:30 AM

The first two major releases of the .NET Framework, 1.0 and 1.1 were… not good. It's so long ago now that they're easily forgotten, but it's important to remember that a lot of core language features weren't in the framework until .NET 2.0.

Like generics. Generics haven't always been part of the language, but they've been in the language since 2006. The hope would be that, in the course of 13 years, developers would learn to use this feature.

Russell F (recently) has a co-worker who is still working on it.

public static DataTable ClassRegionDToDatatable<POSInvoiceRegionD>(string tableName) where POSInvoiceRegionD : class { Type classType = typeof(POSInvoiceRegionD); DataTable result = new DataTable(tableName); foreach (PropertyInfo property in classType.GetProperties()) { DataColumn column = new DataColumn(); column.ColumnName = property.Name; column.DataType = property.PropertyType; result.Columns.Add(column); } return result; } public static DataTable ClassRegionFToDatatable<POSInvoiceRegionF>(string tableName) where POSInvoiceRegionF : class { Type classType = typeof(POSInvoiceRegionF); DataTable result = new DataTable(tableName); foreach (PropertyInfo property in classType.GetProperties()) { DataColumn column = new DataColumn(); column.ColumnName = property.Name; column.DataType = property.PropertyType; result.Columns.Add(column); } return result; } public static DataTable ClassRegionGToDatatable<POSInvoiceRegionG>(string tableName) where POSInvoiceRegionG : class { Type classType = typeof(POSInvoiceRegionG); DataTable result = new DataTable(tableName); foreach (PropertyInfo property in classType.GetProperties()) { DataColumn column = new DataColumn(); column.ColumnName = property.Name; column.DataType = property.PropertyType; result.Columns.Add(column); } return result; } public static DataTable ClassRegionKToDatatable<POSInvoiceRegionK>(string tableName) where POSInvoiceRegionK : class { Type classType = typeof(POSInvoiceRegionK); DataTable result = new DataTable(tableName); foreach (PropertyInfo property in classType.GetProperties()) { DataColumn column = new DataColumn(); column.ColumnName = property.Name; column.DataType = property.PropertyType; result.Columns.Add(column); } return result; }

Now, the core idea behind generics is that code which is generic doesn't particularly care about what data-type it's working on. A generic list handles inserts and other list operations without thinking about what it's actually touching.

So, right off the bat, the fact that we have a pile of generic methods which all contain the same code is a simple hint that something's gone terribly wrong.

In this case, each of these methods takes a type parameter (which happens, in this case, to be named just like one of the actual classes we use), and then generates an empty DataTable with the columns configured to match the class. So, for example, you might do:

DataTable d = POSInvoiceRegionUtils.ClassRegionDToDatatable<POSInvoiceRegionD>("the_d");

Of course, because these methods are all generic and accept type parameters, you could just as easily…

DataTable d = POSInvoiceRegionUtils.ClassRegionKToDatatable<POSInvoiceRegionD>("the_d");

Not that such a counterintuitive thing ever happens. By the way, did you notice how these regions are named with letters? And you know how the alphabet has 26 of them? Well, while they're not using all 26 letters, there are a lot more regions than illustrated here, and they all get the same ClassRegion{x}ToDatatable implementation.

So yes, we could boil all of these implementations down into one. Then again, should we? GetProperties is one of .NET's reflection methods, which lets us examine the definition of class objects. Using it isn't wrong, but it's always suspicious. Perhaps we don't need any of this code? Without more information, it's hard to say, but Russell adds:

I'm going to leave aside the question of whether this is something that should be done at all to focus on the fact that it's being done in a really bizarre way.

I'm not sure about "bizarre", but wrong? Definitely. Definitely wrong.

[Advertisement] Ensure your software is built only once and then deployed consistently across environments, by packaging your applications and components. Learn how today!


Error'd: An Error Storm of Monstrous Proportions
Friday Oct 4, 2019 6:30 AM

"Move over NOAA, Google News shows us, unfortunately after the fact that The Daily Beast is the TRUEST hurricane prognosticator," Alejandro D. writes.

 

"Um...So, these are so my car can listen to music, wirelessly, because its mirrors are its...er...ears??" Paul writes.

 

Jyri B. wrote, "You know, it's really nice to see that the Eurovision people are embracing all the European languages."

 

"Wow! Maltese looks like a tough language to learn. Glad I don't have to know it. Thank YOU Google Translate!" Peter K. writes.

 

"At Gamestop, you can pre-order figurines of all your favoirte characters from MSI!" wrote Chris A.

 

Mikkel H. writes, "I don't want to hear about timezone issues. The only thing possible that happened here was that my FedEx package was teleported from Beijing to Anchorage and back again."

 

[Advertisement] Otter - Provision your servers automatically without ever needing to log-in to a command prompt. Get started today!


The Windows Update

Every change breaks someones workflow.

A few years ago, Ian started at one of the many investment banks based out of London. This particular bank was quite proud of how they integrated “the latest technology” into all their processes, “favoring the bleeding edge,” and “are always focusing on Agile methods, and cross-functional collaboration.”

That last bit is why every software developer was on a tech support rotation. Every two weeks, they’d have to spend a day sitting with the end users, watching them work. Ostensibly, by seeing how the software was actually used, the developers would have a better sense of the users’ needs. In practice, they mostly showed people how to delete emails or recover files from the recycling bin.

Unfortunately, these end users also directly or indirectly controlled the bank’s budgeting process, so keeping them happy was a big part of ensuring continued employment. Not just service, but service with a smile- or else.

Ian’s problem customer was Jacob. Jacob had been with the bank at least thirty years, and still longed for the days of lunchtime brandy and casual sexual harassment. He did not like computers. He did not like the people who serviced his computer. He did not like it when a web page displayed incorrectly, and he especially did not like it when you explained that you couldn’t edit the web page you didn’t own, and couldn’t tell Microsoft to change Internet Explorer to work with that particular website.

“I understand you smart technical kids are just a cost of doing business,” Jacob would often say, “but your budget is out of control. Something must be done!”

Various IT projects proceeded apace. Jacob continued to try and cut their budget. And then the Windows 7 rollout happened.

This was a massive effort. They had been on Windows XP. A variety of intranet and proprietary applications didn’t work on Windows 7, and needed to be upgraded. Even with those upgrades, everyone knew that there would be more problems. These big changes never came without unexpected side effects.

The day Jacob got Windows 7 imaged onto his computer also happened to be the day Ian was on helldesk duty. Ian got a frantic email:

My screen is broken! Everything is wrong! COME TO MY DESK RIGHT NOW, YOUNG MAN

Ian had already prepared, and went right ahead and changed Jacob’s desktop settings so that they as closely mimicked Windows XP as possible.

“That’s all fine and good,” Jacob said, “but it’s still broken.”

Ian looked at the computer. Nothing was broken. “What… what exactly is the problem?”

“Internet Explorer is broken!”

Ian double clicked the IE icon. The browser launched just fine, and pulled up the company home page.

“No! Close that window, and look at the desktop!”

Ian did so, waiting for Jacob to explain the problem. Jacob waited for Ian to see the problem. They both sat there, waiting, no one willing to move until the other had gone.

Jacob broke first. “The icon is wrong!”

Ah, yes, the big-blue-E of Windows XP had been replaced by the big-blue-E of Windows 7.

“This is unacceptable!” Jacob said.

Ian had already been here for most of the morning, so a few more minutes made no difference. He fired up image search, grabbed the first image which was an XP era IE icon, and then set that as the icon on the desktop.

Jacob squinted. “Nope. No, I don't like that. It’s too smooth.”

Of course. Ian had grabbed the first image, which was much higher resolution than the original icon file. “I… see. Give me a minute.”

Ian went back to his desk, resized the image, threw it on a network share, went back to Jacob’s desk, and changed the icon.

“There we are,” Jacob said. “At least someone on your team knows how to support their users. It’s not just about making changes willy-nilly, you know. Good work!”

That was the first and only honest compliment Jacob ever gave Ian. Two years later, Ian moved on to a new job, leaving Jacob with his old IE icon, sitting at the same desk he’d been since before the Internet was even a “thing”.

[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!


CodeSOD: An Updated Version
Wednesday Oct 2, 2019 6:30 AM

Some folks were perplexed by the fact that Microsoft skipped Windows 9 and went straight to Windows 10. The urban legend is that so many old applications checked which version of Windows was running by doing something like version.startsWith("Windows 9") to see if they were on 95 or 98, that Microsoft risked breaking otherwise working code if they released Windows 9.

But gone are those days of doing string munging to check which version of an OS we’re running on. We’ve got much better ways to check what features and functionality are available without having to parse strings out, right?

John D found some TypeScript code in a Ionic app that needs to adapt to different versions of iOS:

private iOS13Device(): boolean {
		// fix for ios 13 pan end issue
		if (
			this.isIOS13Device === undefined &&
			this.deviceService.isiOS &&
			this.deviceInfoService.deviceInfo &&
			this.deviceInfoService.deviceInfo.osVersion &&
			this.deviceInfoService.deviceInfo.osVersion.indexOf('_') &&
			this.deviceInfoService.deviceInfo.osVersion.split('_') &&
			this.deviceInfoService.deviceInfo.osVersion.split('_')[0] &&
			this.deviceInfoService.deviceInfo.osVersion.split('_')[0] === '11'
		) {
			this.isIOS13Device = true;
			return this.isIOS13Device;
		} else {
			this.isIOS13Device = false;
			return this.isIOS13Device;
		}
	}

Well, at least they’re caching the result.

Also, I’m no expert on iOS device strings, but this seems to imply that an iOS13Device (an OS which just came out recently) reports its OS version number as a string starting with 11. Maybe that’s correct, but in either case, that seems like a bonus WTF.

[Advertisement] ProGet can centralize your organization's software applications and components to provide uniform access to developers and servers. Check it out!


When Unique Isn't Unique

Palm III 24

Gather 'round, young'uns, for a tale from the Dark Ages of mobile programming: the days before the iPhone launched. Despite what Apple might have you believe, the iPhone wasn't the first portable computing device. Today's submitter, Jack, was working for a company that streamed music to these non-iPhone devices, such as the Palm Treo or the Samsung Blackjack. As launch day approached for the new client for Windows Mobile 6, our submitter realized that he'd yet to try the client on a non-phone device (called a PDA, for those of you too young to recall). So he tracked down an HP iPaq on eBay just so he could verify that it worked on a device without the phone API.

The device arrived a few days out from launch, after QA had already approved the build on other devices. It should've been a quick test: sideload the app, stream a few tracks, log in, log out. But when Jack opened the app for the first time on the new device, it was already logged into someone's account! He closed it and relaunched, only to find himself in a different, also inappropriate account. What on earth?!

The only thing Jack could find in common between the users he was logged in as was that they were running the same model of PDA. That was the crucial key to resolving the issue. To distinguish which device was making the calls to the streaming service, Jack used a call in Windows Mobile that would return a unique ID for each mobile device. In most devices, it would base this identifier on the IMEI, ensuring uniqueness—but not on the HP iPaq. All HP devices could automatically log into the account of the most recently used iPaq, providing the user logged out and back in, as it would generate a recent-user record with the device ID.

Jack had read the documentation many times, and it always stated that the ID was guaranteed to be unique. Either HP had a different definition of "unique" than anyone else, or they had a major security bug!

Jack emailed HP, but they had no plans to fix the issue, so he had to whip up an alternate method of generating a UUID in the case that the user was on this device. The launch had to be pushed back to accommodate it, but the hole was plugged, and life went on as usual.

[Advertisement] ProGet can centralize your organization's software applications and components to provide uniform access to developers and servers. Check it out!


CodeSOD: Butting In
Monday Sep 30, 2019 6:30 AM

Initech is a large, international corporation. Any time you're doing business at a global scale, you're going to need to contend with a language barrier sooner or later. This makes employees who are multilingual valuable.

Dana recently joined Initech, and in the first week, was warned about Jerry. Jerry was the "chief" "architect" and team "lead", and was one of those special, valuable employees who spoke three languages. Correction, "spoke" needs scare quotes too, because Jerry was incomprehensible in every language he spoke, including his native tongue.

Jerry's emails were stuff of legend around the office. Punctuation was included, not to structure sentences, but as a kind of decoration, just to spice up his communiques. Capitalization was applied at random. Sentences weren't there to communicate a single thought or idea, but to express fragments of half considered dreams.

Despite being the "chief architect", Jerry's code was about as clear as his emails. His class definitions were rambling stretches of unrelated functionality, piled together into a ball of mud. Splattered through it all were blocks of commented out functionality. And 99.9% of his commits to master had syntax errors.

Why did his commits always have syntax errors? Jerry had never seen fit to install a C++ compiler on his machine, and instead pushed to master and let their CI system compile and find all his syntax errors. He'd then amend the commit to fix the errors, and woe betide anyone else working in the repo, because he'd next git push --force the amended commit. Then he'd fix the new round of syntax errors.

Their organization did have an official code review standard, but since no one understood any of Jerry's code, and Jerry was the "chief", Jerry reviewed his own code.

So, let's talk about enumerated types. A common practice in C++ enums is to include an extra value in the enum, just to make it easy to discover the size of the enum, like so:

enum Color { COLOR_RED, COLOR_BLACK, COLOR_BLUE, COLOR_SIZE }

COLOR_SIZE isn't actually a color value, but it tells you how many color values there are. This can be useful when working with a large team, as it's a sort of form of documentation. It also allows patterns like, `for (int i = 0; i < COLOR_SIZE; i++)…`. Of course, it only works when everyone follows the same convention.

Jerry couldn't remember the convention. So, in his native language, he invented a new one: he'd end all his enums with a _END instead of _SIZE. But Jerry also couldn't remember what the English word for "end" was. So he went off to Google Translate, and got an English translation.

Then he wrote code. Lots of code. No one got to review this code. Jerry touched everything, without worrying about what any other developer was doing.

This meant that before long, every enum in the system looked like this:

enum Color { COLOR_RED, COLOR_BLACK, COLOR_BLUE, COLOR_BUTT }

Eventually, Jerry left Initech. He'd found a position where he could be a CTO of a well-funded startup. The very same day, Dana submitted her largest pull request ever, where she removed every single one of Jerry's butts.

[Advertisement] Forget logs. Next time you're struggling to replicate error, crash and performance issues in your apps - Think Raygun! Installs in minutes. Learn more.