-Поиск по дневнику

Поиск сообщений в rss_thedaily_wtf

 -Подписка по e-mail

 

 -Постоянные читатели

 -Статистика

Статистика LiveInternet.ru: показано количество хитов и посетителей
Создан: 06.04.2008
Записей:
Комментариев:
Написано: 0

The Daily WTF





Curious Perversions in Information Technology


Добавить любой RSS - источник (включая журнал LiveJournal) в свою ленту друзей вы можете на странице синдикации.

Исходная информация - http://thedailywtf.com/.
Данный дневник сформирован из открытого RSS-источника по адресу http://syndication.thedailywtf.com/thedailywtf, и дополняется в соответствии с дополнением данного источника. Он может не соответствовать содержимому оригинальной страницы. Трансляция создана автоматически по запросу читателей этой RSS ленты.
По всем вопросам о работе данного сервиса обращаться со страницы контактной информации.

[Обновить трансляцию]

Coded Smorgasbord: Driven to Substraction

Среда, 09 Октября 2019 г. 09:30 + в цитатник

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 description for DateManager.
	/// 
	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, 
																	
	        
	        
	        

Метки:  

CodeSOD: Compiled Correctly

Вторник, 08 Октября 2019 г. 09:30 + в цитатник

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!

https://thedailywtf.com/articles/compiled-correctly


Метки:  

CodeSOD: Generically Bad

Понедельник, 07 Октября 2019 г. 09:30 + в цитатник

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(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(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(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(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("the_d");

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

DataTable d = POSInvoiceRegionUtils.ClassRegionKToDatatable("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!

https://thedailywtf.com/articles/generically-bad


Метки:  

Error'd: An Error Storm of Monstrous Proportions

Пятница, 04 Октября 2019 г. 09:30 + в цитатник

"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!

https://thedailywtf.com/articles/an-error-storm-of-monstrous-proportions


Метки:  

The Windows Update

Четверг, 03 Октября 2019 г. 09:30 + в цитатник

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!

https://thedailywtf.com/articles/the-windows-update


Метки:  

CodeSOD: An Updated Version

Среда, 02 Октября 2019 г. 09:30 + в цитатник

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!

https://thedailywtf.com/articles/an-updated-version


Метки:  

When Unique Isn't Unique

Вторник, 01 Октября 2019 г. 09:30 + в цитатник

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!

https://thedailywtf.com/articles/when-unique-isn-t-unique


Метки:  

CodeSOD: Butting In

Понедельник, 30 Сентября 2019 г. 09:30 + в цитатник

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.

https://thedailywtf.com/articles/butting-in


Метки:  

Error'd: Modern Customer Support

Пятница, 27 Сентября 2019 г. 09:30 + в цитатник

"It's interesting to consider that First Great Western's train personnel track on-time but meanwhile, their seats measure uptime," writes Roger G.

 

Peter G. writes, "At $214.90 for two years I was perfectly happy, but this latest price increase? You've simply gone TOO FAR and I will be cancelling ASAP!"

 

"SharePoint does a lot of normal things, but in the case of this upgrade, it truly went above and beyond," Adam S. wrote.

 

"Sure, I guess you can email a question, but just don't get your hopes up for a reply," writes Samuel N.

 

Al H. writes, "When I signed up for a trial evaluation of Toad and got an e-mail with the activation license key, this was not quite what I was expecting."

 

"The cover story, in case anybody starts asking too many questions, is that Dustin is the name of the male squirrel outside the window. He and Sylvia the squirrel are married. Nobody was testing in Production," writes Sam P.

 

[Advertisement] Utilize BuildMaster to release your software with confidence, at the pace your business demands. Download today!

https://thedailywtf.com/articles/modern-customer-support


Метки:  

CodeSOD: Trim Off a Few Miles

Четверг, 26 Сентября 2019 г. 09:30 + в цитатник

I don’t know the length of Russell F’s commute. Presumably, the distance is measured in miles. Miles and miles. I say that, because of this block, which is written… with care.

  string Miles_w_Care = InvItem.MilesGuaranteeFlag == true && InvItem.Miles_w_Care.HasValue ? (((int)InvItem.Miles_w_Care / 1000).ToString().Length > 2 ? ((int)InvItem.Miles_w_Care / 1000).ToString().Trim().Substring(0, 2) : ((int)InvItem.Miles_w_Care / 1000).ToString().Trim()) : "  ";
  string Miles_wo_Care = InvItem.MilesGuaranteeFlag == true && InvItem.Miles_wo_Care.HasValue ? (((int)InvItem.Miles_wo_Care / 1000).ToString().Length > 2 ? ((int)InvItem.Miles_wo_Care / 1000).ToString().Trim().Substring(0, 2) : ((int)InvItem.Miles_wo_Care / 1000).ToString().Trim()) : "  ";

Two lines, so many nested ternaries. Need to round off to the nearest thousand? Just divide and then ToString the result, selecting the substring as needed. Be sure to Trim the string which couldn’t possibly contain whitespace, you never know.

Ironically, the only expression in this block which isn’t a WTF is InvItem.MilesGuaranteeFlag == true, because while we’re comparing against true, MilesGuaranteeFlag is a Nullable, so this confirms that it has a value and that the value is true.

So many miles.

And I would write five hundred lines
and I would write five hundred more
just to be the man who wrote a thousand lines
Uncaught Exception at line 24

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

https://thedailywtf.com/articles/trim-off-a-few-miles


Метки:  

CodeSOD: And it was Uphill Both Ways

Среда, 25 Сентября 2019 г. 09:30 + в цитатник

Today’s submission is a little bit different. Kevin sends us some code where the real WTF is simply that… it still is in use somewhere. By the standards of its era, I’d actually say that the code is almost good. This is more of a little trip down memory lane, about the way web development used to work.

Let’s start with the HTML snippet:


	

In 2019, if you want to have a sidebar full of links which allow users to click, and have a portion of the page update while not refreshing the whole page, you probably write a component in the UI framework of your choice. In 1999, you used frames. Honestly, by 1999, frames were already on the way out (he says, despite maintaining a number of frames-based applications well into the early 2010s), but for a brief period in web development history, they were absolutely all the rage.

In fact, shortly after I made my own personal home page, full of

tags, creative abuse of the tag, and a color scheme which was hot pink and neon green, I showed it to a friend, who condescendingly said, “What, you didn’t even use frames?” He made me mad enough that I almost deleted my Geocities account.

Frames are dead, but now we have which do the same thing, but are almost entirely used for embedding ads or YouTube videos. Some things will never truly die.

  IE4 = (document.all) ? true : false;
  NS4 = (document.layers) ? true : false;
  ver4 = (IE4||NS4);

  if (ver4!=true){  
    function MaximizeWindow(){
        alert('Please install a browser with support for Javascript 1.2. This website works for example with Microsofts Internet Explorer or Netscapes Navigator in versions 4.x or newer!')
        self.history.back();
        }
    }
  
  if (ver4==true){
    function MaximizeWindow(){
    window.focus();
	window.moveTo(0,0)
	window.resizeTo(screen.availWidth,screen.availHeight)
      }
}

Even today, in the era of web standards, we still constantly need to use shims and compatibility checks. The reasons are largely the same as they were back then: standards (or conventions) evolve quickly, vendors don’t care about standards, and browsers represent fiendishly complicated blocks of software. Today, we have better ways of doing those checks, but here we do our check with the first two lines of code.

And this, by the way, is why I said this code was “almost good”. In the era of “a browser with support for Javascript 1.2”, the standard way of checking browser versions was mining the user-agent string. And because of that we have situations where browsers report insanity like Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36.

Even in the late 90s though, the “right” way to check if your site was compatible with a given browser was to check for the features you planned to use. Which this code does- specifically, it’s looking for document.all or document.layers, which were two different approaches to exploring the DOM before we had actual tools for exploring the DOM. In this era, we’d call stuff like this “DHTML” (the D is for “dynamic”), and we traversed the DOM as a chain of properties, doing things like document.forms[0].inputs[0] to access fields on the form.

This is almost good, though, because it doesn’t gracefully degrade. If you don’t have a browser which reports these properties- document.all or document.layers, we just pop up an alert and forcibly hit the back button on your browser. Then again, if you do have a browser that supports those properties, it’s just going to go and forcibly hit the “Maximize” button on you, which is also not great, but I’m sure would make the site look quite impressive on an 800x600 resolution screen. I’m honestly kind of surprised that this doesn’t also check your resolution, and provide some warning about looking best at a certain resolution, which was also pretty standard stuff for this era.

Again, the real WTF is that this code still exists out in the wild somewhere. Kevin found it when he encountered a site that kept kicking him back to the previous page. But there’s a deeper WTF: web development is bad. It’s always been bad. It possibly always will be bad. It’s complicated, and hard, and for some reason we’ve decided that we need to build all our UIs using a platform where a paragraph is considered a first-class UI element comparable to a button. But the next time you struggle to “grok” the new hot JavaScript framework, just remember that you’re part of a long history of people who have wrestled with accomplishing basic tasks on the web, and that it’s always been a hack, whether it’s a hack in the UA-string, a hack of using frames to essentially embed browser windows inside of browser windows, or a hack to navigate the unending efforts of browser vendors to hamstring and befuddle the competition.

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

https://thedailywtf.com/articles/and-it-was-uphill-both-ways


Метки:  

CodeSOD: Do You Need this

Вторник, 24 Сентября 2019 г. 09:30 + в цитатник

I’ve written an unfortunate amount of “useless” code in my career. In my personal experience, that’s code where I write it for a good reason at the time- like it’s a user request for a feature- but it turns out nobody actually needed or wanted that feature. Or, perhaps, if I’m being naughty, it’s a feature I want to implement just for the sake of doing it, not because anybody asked for it.

The code’s useless because it never actually gets used.

Claude R found some code which got used a lot, but was useless from the moment it was coded. Scattered throughout the codebase were calls to getInstance(), as in, Task myTask = aTask.getInstance().

At first glance, Claude didn’t think much of it. At second glance, Claude worried that there was some weird case of deep indirection where aTask wasn’t actually a concrete Task object and instead was a wrapper around some factory-instantiated concrete class or something. It didn’t seem likely, but this was Java, and a lot of Java code will follow patterns like that.

So Claude took a third glance, and found some code that’s about as useful as a football bat.

public Task getInstance(){
    return this;
}

To invoke getInstance you need a variable that references the object, which means you have a variable referencing the same thing as this. That is to say, this is unnecessary.

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

https://thedailywtf.com/articles/do-you-need-this


Метки:  

Accounting for Changes

Понедельник, 23 Сентября 2019 г. 09:30 + в цитатник

Sara works as a product manager for a piece of accounting software for a large, international company. As a product manager, Sara interacts with their internal customers- the accounting team- and Bradley is the one she always bumps heads with.

Bradley's idea of a change request is to send a screenshot, with no context, and a short message, like "please fix", "please advise", or "this is wrong". It would take weeks of emails and, if they were lucky, a single phone call, for Sara's team to figure out what needs to be fixed, because Bradley is "too busy" to provide any more information.

One day, Bradley sent a screenshot of their value added taxation subsystem, saying, "This is wrong. Please fix." The email was much longer, of course, but the rest of the email was Bradley's signature block, which included a long list of titles, certifications, a few "inspirational" quotes, and his full name.

Sara replied. "Hi Brad," her email began- she had once called him "Bradley" which triggered his longest email to date, a screed about proper forms of address. "Thanks for notifying us about a possible issue. Can you help me figure out what's wrong? In your screen shot, I see SKU numbers, tax information, and shipping details."

Bradley's reply was brief. "Yes."

Sara sighed and picked up her phone. She called Bradley's firm, which landed her with an assistant, who tracked down another person, who asked another who got Bradley to confirm that the issue is that, in some cases, the Value Added Tax isn't using the right rate, as in some situations multiple rates have to be applied at the same time.

It was a big update to their VAT rules. Sara managed to talk to some SMEs at her company to refine the requirements, contacted development, and got the modifications built in the next sprint.

"Hi, Bradley," Sara started her next email. "Thank you for bringing the VAT issue to our attention. Based on your description, we have implemented an update. We've pushed it to the User Acceptance Testing environment. After you sign off that the changes are correct, we will deploy it into production. Let me know if there are any issues with the update." The email included links to the UAT process document, the UAT test plan template, and all the other details that they always provided to guide the UAT process.

A week later, Bradley sent an email. "It works." That was weird, as Bradley almost never signed off until he had pushed in a few unrelated changes. Still, she had the sign off. She attached the email to the ticket and once the changes were pushed to production, she closed the ticket.

A few days later, the entire accounting team goes into a meltdown and starts filing support request after support request. One user submitted ten by himself- and that user was the CFO. This turns into a tense meeting between the CFO, Bradley, Sara, and Sara's boss.

"How did this change get released to production?"

Sara pulled up the ticket. She showed the screenshots, referenced the specs, showed the development and QA test plans, and finally, the email from Bradley, declaring the software ready to go.

The CFO turned to Bradley.

"Oh," Bradley said, "we weren't able to actually test it. We didn't have access to our test environment at all last week."

"What?" Sara asked. "Why did you sign off on the change if you weren't able to test it!?"

"Well, we needed it to go live on Monday."

After that, a new round of requirements gathering happened, and Sara's team was able to implement them. Bradley wasn't involved, and while he still works at the same company, he's been shifting around from position to position, trying to find the best fit…

[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.

https://thedailywtf.com/articles/accounting-for-changes


Метки:  

Error'd: Full Stack Languages...and BEYOND!

Пятница, 20 Сентября 2019 г. 09:30 + в цитатник

"When travelling to outer space, don't forget your...Javascript code?" writes Rob S.

 

Pascal wrote, "If you ask me, I think Dr. Phil needs to hire a captioner that doens't have a stutter."

 

Tore F. writes, "If the Lenovo System Update tool was coded to expect an unexpected exception, does that mean that it was, in fact, actually expected?"

 

"Note to self: Never set the A/C to its lowest limit, or at least have a toilet and TP handy," writes Peter G.

 

"No matter how hard you try, Yodal, 82 - (-7) does not equal 22," Chris E. wrote.

 

Jiri G. writes, "100% service availability? Nah, you don't need that. Close enough is good enough."

 

[Advertisement] Continuously monitor your servers for configuration changes, and report when there's configuration drift. Get started with Otter today!

https://thedailywtf.com/articles/full-stack-languages-and-beyond


Метки:  

Redesign By Committee

Четверг, 19 Сентября 2019 г. 09:30 + в цитатник

Sample web form

Carl was excited to join his first "real" company and immerse himself in the World of Business. The fresh-faced IT Analyst was immediately assigned to a "cross-strata implementation team" tasked with redesigning the RMA form completed by customers when they returned goods. The current form had been flagged for various weaknesses and omissions.

The project's kickoff meeting ran for three hours, with twelve team members in attendance representing departments throughout the company. By the end of the meeting, the problem had been defined, and everyone had homework: to report to the next team meeting with their own interpretations of what the new form should look like.

Each team member dutifully came back with at least one version of the form each. The next meeting consisted of Norman, the QA Manager, critiquing each prospective form as it was presented to the group. Without fail, he'd shake his head with a furrowed brow, muttering "No, no ..."

This proceeded, form after form, until Terry, an Accounts Junior, presented his version. When Norman expressed displeasure, Terry dared to ask, "Well? What's wrong with it?"

Norman gestured to the list of required criteria in his hands. "You've missed this piece of information, and that's probably the most important item we need to capture."

Terry frowned. "But, Norman, your form doesn't have that information on it, either."

Upon looking down at his own form, Norman realized Terry was correct. He rallied to save his dignity. "Ah, yes, but, you see, I know that it's missing."

Stupefied, Terry backed down.

Carl cycled through bafflement, boredom, and agony of the soul as the meeting dragged on. At one point, Finance Manager Kevin picked up yet another version of the form and asked, "What about this one, then?"

Jason the Ops Manager skimmed through it, ticking off items against the list of criteria. "Yup, yup, yup, yup ... yes, this is it! I think we've cracked it!" he exclaimed.

Norman peered at the form in Jason's hands. "That's the form we're currently using." The very form they needed to replace.

Hours upon hours of combined effort had thus far resulted in no progress whatsoever. Carl glanced at the conference room's wall clock with its stubbornly slow hands, wondering if a camera hidden behind it were recording his reaction for a YouTube prank channel. But, no. He was simply immersed in the World of Business.

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

https://thedailywtf.com/articles/redesign-by-committee


Метки:  

CodeSOD: You Can Take Care

Среда, 18 Сентября 2019 г. 09:30 + в цитатник

Tiberrias sends us some code that, on its face, without any context, doesn’t look bad.

var conditionId = _monitorConditionManagement.GetActiveConditionCountByClient(clientIdentityNumber);

_monitorConditionManagement.StopCondition(conditionId);

The purpose of this code is to lookup a condition ID for a client, and then clear that condition from a client by StopConditioning that ID. Which, if you read the code closely, the problem becomes obvious: GetActiveConditionCountByClient. Count. This doesn’t return a condition ID, it returns the count of the number of active conditions. So, this is a stupid, simple mistake, an easy error to make, and an easy error to catch- this code simply doesn’t work, so what’s the WTF?

This code was written by a developer who either made a simple mistake or just didn’t care. But then it went through code review- and the code reviewer either missed it, or just didn’t care. It’s okay, though, because there are unit tests. There’s a rich, robust unit test suite. But in this case, the GetActiveConditionCountByClient and the StopCondition methods are just mocks, and the person who wrote the unit test didn’t check to see that the mocks were called as expected, because they just didn’t care.

Still, there’s an entire QA team between this code and production, and since this code definitely can’t work, they’re going to catch the bug, right? They might- if they cared. But this code passed QA, and got released into production.

The users might notice, but the StopCondition method is so nice that, if given an invalid ID, it just logs the error and trucks on. The users think their action worked. But hey, there’s a log file, right? There’s an operations team which monitors the logs and should notice a lot of errors suddenly appearing. They just would have to care, which guess what…

This bug only got discovered and fixed because Tiberrias noticed it while scrolling through the class to fix an entirely unrelated bug.

“You really shouldn’t fix two unrelated bugs in the same commit,” the code reviewer said when Tiberrias submitted it.

There was only one way to reply. “I don’t care.”

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

https://thedailywtf.com/articles/you-can-take-care


Метки:  

A Learning Experience

Вторник, 17 Сентября 2019 г. 09:30 + в цитатник

Jakob M. had the great pleasure of working as a System Administrator in a German school district. At times it was rewarding work. Most of the time it involved replacing keyboard keys mischievous children stole and scraping gum off of monitor screens. It wasn't always the students that gave him trouble though.

Frau Fritzenberger was a cranky old math teacher at a Hauptschule near Frankfurt. Jakob regularly had to answer support calls she made for completely frivolous things. Having been teaching since before computers were a thing, she put up a fight for every new technology or program Jakob's department wanted to implement.

Over the previous summer, a web-based grading system called NotenWertung was rolled out across the district's network. It would allow teachers to grade homework and post the scores online. They could work from anywhere, with any computer. There was even a limited mobile application. Students and parents could then get a notification and see them instantly. Frau Fritzenberger was predictably not impressed.

She threw a fit on the first day of school and Jakob was dispatched to defuse it. "Why do we need computers for grading?!" she screeched at Jakob. "Paper works just fine like it has for decades! How else can I use blood red pen to shame them for everything they get wrong!"

"I understand your concern, Frau Fritzenberger," Jakob replied while making a 'calm down' gesture with his arms. "But we can't have you submitting grades on paper when the entire rest of the district is using NotenWertung." He had her sit down at the computer and gave her a For Dummies-type walkthrough. "There, it's easier than you think. You can even do this at night from the comfort of your own home," he assured her before getting up to leave.

Just as he was exiting the classroom, he heard her shout, "If you were my student, I would smack you with my ruler!" Jakob brushed it off and left to answer a call about paper clips jammed in a PC fan.

The next morning, Jakob got a rare direct call on his desk phone. It was Frau and she was in a rage. All he could make out between strings of aged German cuss words was "computer is broken!" He hung up and prepared to head to Frau's Hauptschule.

Jakob expected to find that Frau didn't have a network connection, misplaced the shortcut to her browser, didn't realize the monitor was off, or something stupid like that. What he found was Frau's computer was literally broken. The LCD screen of her monitor was an elaborate spider web, her keyboard was cracked in half, and the PC tower looked like it had been run over on the Autobahn. Bits of the motherboard dangled outside the case, and the HDD swung from its cable. "Frau Fritzenberger... what in the name of God happened here?!"

"I told you the computer was broken!" Frau shouted while meanly pointing her crooked index finger at Jakob. "You told me I have to do grades on the computer. So I packed it up to take home on my scooter. It was too heavy for me to ride with it on back so I wiped out and it smashed all over the road! This is all your fault!"

Jakob stared on in disbelief at the mangled hunks of metal and plastic. Apparently you can teach an old teacher new tricks but you can't teach her that the same web application can be accessed from any computer.

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

https://thedailywtf.com/articles/a-learning-experience


Метки:  

CodeSOD: Should I Do this? Depends.

Понедельник, 16 Сентября 2019 г. 09:30 + в цитатник

One of the key differences between a true WTF and an ugly hack is a degree of self-awareness. It's not a WTF if you know it's a WTF. If you've been doing this job for a non-zero amount of time, you have had a moment where you have a solution, and you know it's wrong, you know you shouldn't do this, but by the gods, it works and you've got more important stuff to worry about right now, so you just do it.

An anonymous submitter committed a sin, and has reached out to us for absolution.

This is a case of "DevOps" hackery. They have one server with no Internet- one remote server with no Internet. Deploying software to a server you can't access physically or through the Internet is a challenge. They have a solution involving hopping through some other servers and bridging the network that lets them get the .deb package files within reach of the destination server.

But that introduces a new problem: these packages have complex dependency chains and unless they're installed in the right order, it won't work. The correct solution would be to install a local package repository on the destination server, and let apt worry about resolving those dependencies.

And in the long run, that's what our anonymous submitter promises to do. But they found themselves in a situation where they had more important things to worry about, and just needed to do it.

#!/bin/bash count=0 for f in ./*.deb do echo "Attempt $count" for file in ./*.deb do echo "Installing $file" sudo dpkg -i $file done (( count++ )) done

This is a solution to dependency management which operates on O(N^2): we install each package once for the total number of packages in the folder. It's the brutest of force solutions, and no matter what our dependency chain looks like, by sheer process of elimination, this will eventually get every package installed. Eventually.

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

https://thedailywtf.com/articles/should-i-do-this-depends


Метки:  

Error'd: Many Languages, One WTF

Пятница, 13 Сентября 2019 г. 09:30 + в цитатник

"It's as if IntelliJ IDEA just gave up trying to parse my code," writes John F.

Henry D. writes, "If you have a phone in English but have it configured to recognize two different languages, simple requests sometimes morph into the weirdest things."

 

 

Carl C. wrote, "Maybe Best Buy's page is referring to a store near Nulltown, Indiana, but really, I think their site is on drugs."

 

"Yeah, Thanks Cisco, but I'm not sure I really want to learn more," writes Matt P.

 

"Ebay is alerting me to something. No idea what it is, but I can tell you what they named their variables," Lincoln K. wrote.

 

"Not quite sure what secrets the Inner Circle holds, I guess knowing Latin?" writes Matt S.

 

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

https://thedailywtf.com/articles/many-languages-one-wtf


Метки:  

CodeSOD: Time to Wait

Четверг, 12 Сентября 2019 г. 10:00 + в цитатник

When dealing with customers- and here, we mean, “off the street” customers- they often want to know “how long am I going to have to wait?” Whether we’re talking about a restaurant, a mechanic, a doctor’s office, or a computer/phone repair shop, knowing (and sharing with our customers) reasonable expectations about how much time they’re about to spend waiting.

Russell F works on an application which facilitates this sort of customer-facing management. It does much more, too, obviously, but one of its lesser features is to estimate how long a customer is about to spend waiting.

This is how that’s calculated:

TimeSpan tsDifference = dtWorkTime - DateTime.Now;
string strEstWaitHM = ((tsDifference.Hours * 60) + tsDifference.Minutes).ToString();
if (Convert.ToInt32(strEstWaitHM) >= 60)
{
	decimal decWrkH = Math.Floor(Convert.ToDecimal(strEstWaitHM) / 60);
	int intH = Convert.ToInt32(decWrkH);
	txtEstWaitHours.Value = Convert.ToString(intH);
	int intM = Convert.ToInt32(strEstWaitHM) - (60 * intH);
	txtEstWaitMinutes.Value = Convert.ToString(intM);
}
else
{
	txtEstWaitHours.Value = "";
	txtEstWaitMinutes.Value = strEstWaitHM;
}

Hungarian Notation is always a great sign of bad code. It really is, and I think that’s because it’s easy to do, easy to enforce as a standard, and provides the most benefit when you have messy variable scoping and keeping track of what type a given variable is might actually be a challenge.

Or, as we see in this case, it’s useful when you’re passing the same data through a method with different types. We calculate the difference between the WorkTime and Now. That’s the last thing in this code which makes sense.

The key goal here is that, if we’re going to be waiting for more than an hour, we want to display both the hours and minutes, but if it’s just minutes, we want to display just that.

We have that TimeSpan object, which as you can see, has a convenient Hours and Minutes property. Instead of using that, though, we convert the hours to minutes, add it together, if the number is more than 60, we know we’ll be waiting for over an hour, so we want to populate the hours box, and the minutes box, so we have to convert back to hours and minutes.

In that context, the fact that we have to convert from strings to numbers and back almost seems logical. Almost. I especially like that they Convert.ToDecimal (to avoid rounding errors) and Math.floor the result (to round off). If only there were some numeric type that never rounded off, and always had an integer value. If only…

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

https://thedailywtf.com/articles/time-to-wait


Метки:  

Поиск сообщений в rss_thedaily_wtf
Страницы: 124 ... 83 82 [81] 80 79 ..
.. 1 Календарь