The Daily WTF

Curious Perversions in Information Technology
Coded Smorgasbord: Unstrung Manager
Wednesday Aug 21, 2019 6:30 AM

Deon was on a contract-to-hire job. In the beginning, it sounded like a good job. Then he looked at the C# codebase. It didn’t take him long to decide that this wasn’t going to be a job he’d work at full time. Still, he’d be happy to continue contracting, because it was quite obvious that it would be a lot of billable hours.

How many is “a lot”? Well, let’s talk about their StringManager class. A common WTF is a “god” class that does a thousand different things. Here’s a class made up of nothing but static functions which is 1800 lines long. This wasn’t assembled by a junior developer or an intern, but their senior technical lead, who was adamant that this was the right way to program, and god damn anybody who said otherwise.

		public static DateTime ConvertCharacterDateToDateTime(string inputMM,
			string inputDD,
			string inputYYYY)
		{
			inputMM = initrode.utilities.StringManager.Fill(inputMM,
				"0",    /* Zero-fill */
				true,   /* From Left */
				2);
			inputDD = initrode.utilities.StringManager.Fill(inputDD,
				"0",    /* Zero-fill */
				true,   /* From Left */
				2);

			int _MM = initrode.utilities.StringManager.ConvertCharacterStringToInt(inputMM);
			int _DD = initrode.utilities.StringManager.ConvertCharacterStringToInt(inputDD);
			int _YYYY = initrode.utilities.StringManager.ConvertCharacterStringToInt(inputYYYY);
			return new DateTime(_YYYY,
				_DD,
				_MM);
		}

This is just a little taste, a small aperitif. Convert three strings into a datetime object. For some reason, this requires padding to be added to the strings. For some reason, all the calls to StringManager methods are fully prefixed with their namespace, which is utterly unnecessary from inside that namespace.

But, I mean, dates are “easy mode”. How about FormatDecimalAsString?

        public static string FormatDecimalAsString
                            (
                                decimal inputDecimal
                                , int inputNumberOfDecimalPlaces
                            )
        {
            StringBuilder _decimalStringBldr =
                new StringBuilder();
            string _tempDecimalString = inputDecimal.ToString();
            //No decimal point
            if (_tempDecimalString.IndexOf(".") < 0)
            {
                _decimalStringBldr.AppendFormat
                (
                    "{0}.{1}"
                    , _tempDecimalString
                    , initrode.utilities.StringManager.Fill
                        (
                            ""    //string input
                            , "0"  //string fillChars
                            , true //bool boolFromLet
                            , inputNumberOfDecimalPlaces    // int maxLength
                        )
                );
            }
            //"." exists
            else
            {
                //If "." at start of string.
                if (_tempDecimalString.IndexOf(".") == 0)
                {
                    _decimalStringBldr.AppendFormat
                    (
                        "0.{0}"
                        ,   initrode.utilities.StringManager.Fill
                            (
                                _tempDecimalString.Substring(1)    //string input
                                , "0"  //string fillChars
                                , false //bool boolFromLeft
                                , inputNumberOfDecimalPlaces    // int maxLength
                            )
                    );
                }
                // "." not at start.
                else
                {
                    //  "." at very end.
                    if (_tempDecimalString.IndexOf(".") == (_tempDecimalString.Length - 1))
                    {
                        _decimalStringBldr.AppendFormat
                        (
                            "{0}.{1}"
                            , _tempDecimalString.Substring(0, (_tempDecimalString.Length - 1))
                            , initrode.utilities.StringManager.Fill
                                (
                                    _tempDecimalString.Substring(1)    //string input
                                    , "0"  //string fillChars
                                    , false //bool boolFromLeft
                                    , inputNumberOfDecimalPlaces    // int maxLength
                                )
                        );
                    }
                    // "." in middle.
                    else
                    {
                        ArrayList _parts =
                            initrode.utilities.StringManager.splitIntoArrayList
                            (
                               _tempDecimalString
                               ,"."
                            );
                        if (_parts.Count == 2)
                        {
                            _decimalStringBldr.AppendFormat
                            (
                                "{0}.{1}"
                                , initrode.utilities.StringManager.StripWhitespace
                                    (
                                        _parts[0].ToString()
                                    )
                                , initrode.utilities.StringManager.Fill
                                    (
                                        initrode.utilities.StringManager.StripWhitespace
                                        (
                                            _parts[1].ToString()
                                        )
                                        ,"0"  //string fillChars
                                        ,false //bool boolFromLeft
                                        , inputNumberOfDecimalPlaces //int maxLength
                                    )
                            );
                        }
                    }
                }
            }
            return _decimalStringBldr.ToString();
        }

Well, I’m noticing a trend, anyway, in that the developer really likes to break things across lines, so our “1800” line initial estimate is probably overblown. Of course, with the number of indented levels in here, combined with using fully qualified names on every line, you sort of have to.

I’m noticing a lot of calls to StripWhitespace. I wonder how that’s implemented…

		public static string StripWhitespace(string input)
		{
			string whitespaceCharacters = " \n\t\r";
			string tempString = input;
			StringBuilder bldr = new StringBuilder();
			for(int i=0; i < tempString.Length; i++)
			{
                if (i >= tempString.Length)
                    return bldr.ToString();
				string loopChar = tempString.Substring(i,1);
				if (whitespaceCharacters.IndexOf(loopChar) < 0)
				{
					bldr.Append(loopChar);
				}
			}
			return bldr.ToString();
		}

Sure, just iterate across every character. But hey, while I was CTRL+Fing for this, I saw StripWhitespaceFromEnds. I wonder what that does.

        public static string StripWhitespaceFromEnds(string input)  
        {
            string whitespaceCharacters = " \n\t\r";  
            string tempString = input;  
            if (initrode.utilities.StringManager.IsEmptyString(tempString) == true) return "";  
            tempString = input;
            
            for(int i=0; i < tempString.Length; i++)  
            {
                string loopChar = tempString.Substring(i,1);  
                if (whitespaceCharacters.IndexOf(loopChar) < 0)  
                {
                    tempString = tempString.Substring(i);  
                    break;  
                }
            }  
            for(int i=(tempString.Length - 1); i >= 0; i--)  
            {
                string loopChar = tempString.Substring(i,1);  
                if (whitespaceCharacters.IndexOf(loopChar) < 0)  
                {
                    tempString = tempString.Substring(0,i+1);  
                    break;  
                }
            }  
            return tempString;  
        }

Oh yeah, two for loops from either side. What else would I expect. Hey, what does IsEmptyString do? Is it just a wrapper around the built-in, IsNullOrEmpty? Of course not!

    public static bool IsEmptyString(string input)
  {
    if (input == null) return true;
    input = StripWhitespace(input);
    if (input.Length == 0) return true;
    return false;
  }

Oh, of course, we have to check if it contains whitespace before we remove the whitespace it contains. What was I thinking?

Y’know, at the very top of the class, I noticed:

  public const string CHARACTERS_IN_EMAIL_ADDRESS_PART = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-";

They must use that when validating an email address.

  public static bool IsValidEMailAddress(string inputEMailAddress)
  {
    if (initrode.utilities.StringManager.IsEmptyString(inputEMailAddress) == true) return false;
    if (inputEMailAddress.IndexOf("@") < 0) return false;
    
    ArrayList _parts = initrode.utilities.StringManager.splitIntoArrayList(inputEMailAddress,"@");
    for (int _partCtr = 0; _partCtr < _parts.Count; _partCtr++)
    {
      string _part = _parts[_partCtr].ToString();
      if (initrode.utilities.StringManager.IsEmptyString(_part) == true) return false;
      if (_part.IndexOf(@".") >= 0)
      {
        ArrayList _periodDelimitedParts = initrode.utilities.StringManager.splitIntoArrayList(_part,@".");
        for (int _periodDelimitedPartCtr = 0; _periodDelimitedPartCtr < _periodDelimitedParts.Count; _periodDelimitedPartCtr++)
        {
          string _periodDelimitedPart = _periodDelimitedParts[_periodDelimitedPartCtr].ToString();
          if (initrode.utilities.StringManager.IsEmptyString(_periodDelimitedPart) == true) return false;
          if (initrode.utilities.StringManager.IsValidEMailAddressPart(_periodDelimitedPart) == false) return false;
        }
      }
      else
      {
        if (initrode.utilities.StringManager.IsValidEMailAddressPart(_part) == false) return false;
      }
    }
    return true;
  }

Oh, not here. What about in that IsValidEMailAddressPart?

  public static bool IsValidEMailAddressPart(string inputPart)
  {
    if (initrode.utilities.StringManager.IsEmptyString(inputPart) == true) return false;
    inputPart = initrode.utilities.StringManager.StripWhitespace(inputPart);
    for (int i = 0; i < inputPart.Length; i++)
    {
      string _character = inputPart.Substring(i,1);
      if (initrode.utilities.StringManager.CHARACTERS_IN_EMAIL_ADDRESS_PART.IndexOf(_character) < 0) return false;
    }
    return true;
  }

Ah, there it is. Hey, notice how it calls IsEmptyString and StripWhitespace, but also remember how IsEmptyString also calls StripWhitespace? Here’s a fun exercise for the readers: how many times do we access every character in the string?

I think nearly every method in this class could be an article in itself. And this is just a slice out of a large codebase where everything is done this way. There are NumberManager classes. DatabaseManager classes. Static methods everywhere.

If you need more proof, here is the entirety of the StringManager.cs class, all 1,800 lines of it:

using System;
using System.Collections;
using System.Text.RegularExpressions;
using System.Text;

namespace initrode.utilities
{
	/** Class:  StringManager
	 *	Contains static string handling routines. 
	 */
	public class StringManager
	{
		public const string CHARACTERS_IN_EMAIL_ADDRESS_PART = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-";


		public static double ConvertCharacterPartsToDecimal(string inputWhole,
			string inputDecimal)
		{
			inputWhole = initrode.utilities.StringManager.Fill(inputWhole,
				"0",    /* Zero-fill */
				true,   /* From Left */
				8);
			inputDecimal = initrode.utilities.StringManager.Fill(inputDecimal,
				"0",    /* Zero-fill */
				false,   /* From Right */
				2);

			int _whole = initrode.utilities.StringManager.ConvertCharacterStringToInt(inputWhole);
			double _decimal = initrode.utilities.StringManager.ConvertCharacterStringToInt(inputDecimal);
			_decimal = _decimal/100;
			double _returnDecimal = (double) _whole + _decimal;
			return _returnDecimal;
		}
        public static void  ParseCommaDelimitedNameToLastNameAndFirstWordOfFirstName
                            (
                                string inputCommaDelimitedName
                                , bool inputAllCaps
                                , out string outputLastName
                                , out string outputFirstWordOfFirstName
                            )
        {
            inputCommaDelimitedName = inputCommaDelimitedName.Replace("'", string.Empty);

            outputLastName = "";
            outputFirstWordOfFirstName = "";

            if (inputCommaDelimitedName.IndexOf(",") < 1)
                return;
            ArrayList _nameParts =
                initrode.utilities.StringManager.splitIntoArrayList
                (
                    inputCommaDelimitedName
                    ,","
                );
            if (_nameParts.Count == 1) return;

            outputLastName =
                initrode.utilities.StringManager.StripWhitespaceFromEnds
                (
                    _nameParts[0].ToString()
                );
            string _firstAndMiddleName =
                initrode.utilities.StringManager.StripWhitespaceFromEnds
                (
                    _nameParts[1].ToString()
                );
            if (_firstAndMiddleName.IndexOf(" ") >= 0)
            {
                ArrayList _firstAndMiddleNameParts =
                    initrode.utilities.StringManager.splitIntoArrayList
                    (
                        _firstAndMiddleName
                        , " "
                    );
                outputFirstWordOfFirstName =
                    initrode.utilities.StringManager.StripWhitespaceFromEnds
                    (
                        _firstAndMiddleNameParts[0].ToString()
                    );
            }
            else
            {
                outputFirstWordOfFirstName =
                    initrode.utilities.StringManager.StripWhitespaceFromEnds
                    (
                        _firstAndMiddleName
                    );
            }
            if (inputAllCaps == true)
            {
                outputFirstWordOfFirstName = outputFirstWordOfFirstName.ToUpper();
                outputLastName = outputLastName.ToUpper();
            }
        }
		public static DateTime ConvertCharacterDateToDateTime(string inputMM,
			string inputDD,
			string inputYYYY)
		{
			inputMM = initrode.utilities.StringManager.Fill(inputMM,
				"0",    /* Zero-fill */
				true,   /* From Left */
				2);
			inputDD = initrode.utilities.StringManager.Fill(inputDD,
				"0",    /* Zero-fill */
				true,   /* From Left */
				2);

			int _MM = initrode.utilities.StringManager.ConvertCharacterStringToInt(inputMM);
			int _DD = initrode.utilities.StringManager.ConvertCharacterStringToInt(inputDD);
			int _YYYY = initrode.utilities.StringManager.ConvertCharacterStringToInt(inputYYYY);
			return new DateTime(_YYYY,
				_DD,
				_MM);
		}
        public static string FormatDecimalAsString
                            (
                                decimal inputDecimal
                                , int inputNumberOfDecimalPlaces
                            )
        {
            StringBuilder _decimalStringBldr =
                new StringBuilder();
            string _tempDecimalString = inputDecimal.ToString();
            //No decimal point
            if (_tempDecimalString.IndexOf(".") < 0)
            {
                _decimalStringBldr.AppendFormat
                (
                    "{0}.{1}"
                    , _tempDecimalString
                    , initrode.utilities.StringManager.Fill
                        (
                            ""    //string input
                            , "0"  //string fillChars
                            , true //bool boolFromLet
                            , inputNumberOfDecimalPlaces    // int maxLength
                        )
                );
            }
            //"." exists
            else
            {
                //If "." at start of string.
                if (_tempDecimalString.IndexOf(".") == 0)
                {
                    _decimalStringBldr.AppendFormat
                    (
                        "0.{0}"
                        ,   initrode.utilities.StringManager.Fill
                            (
                                _tempDecimalString.Substring(1)    //string input
                                , "0"  //string fillChars
                                , false //bool boolFromLeft
                                , inputNumberOfDecimalPlaces    // int maxLength
                            )
                    );
                }
                // "." not at start.
                else
                {
                    //  "." at very end.
                    if (_tempDecimalString.IndexOf(".") == (_tempDecimalString.Length - 1))
                    {
                        _decimalStringBldr.AppendFormat
                        (
                            "{0}.{1}"
                            , _tempDecimalString.Substring(0, (_tempDecimalString.Length - 1))
                            , initrode.utilities.StringManager.Fill
                                (
                                    _tempDecimalString.Substring(1)    //string input
                                    , "0"  //string fillChars
                                    , false //bool boolFromLeft
                                    , inputNumberOfDecimalPlaces    // int maxLength
                                )
                        );
                    }
                    // "." in middle.
                    else
                    {
                        ArrayList _parts =
                            initrode.utilities.StringManager.splitIntoArrayList
                            (
                               _tempDecimalString
                               ,"."
                            );
                        if (_parts.Count == 2)
                        {
                            _decimalStringBldr.AppendFormat
                            (
                                "{0}.{1}"
                                , initrode.utilities.StringManager.StripWhitespace
                                    (
                                        _parts[0].ToString()
                                    )
                                , initrode.utilities.StringManager.Fill
                                    (
                                        initrode.utilities.StringManager.StripWhitespace
                                        (
                                            _parts[1].ToString()
                                        )
                                        ,"0"  //string fillChars
                                        ,false //bool boolFromLeft
                                        , inputNumberOfDecimalPlaces //int maxLength
                                    )
                            );
                        }
                    }
                }
            }
            return _decimalStringBldr.ToString();
        }
		public static DateTime ConvertTimestampStringToDateTime(string inputTimestampInStringFormat)
		{
			ArrayList _parts = initrode.utilities.StringManager.splitIntoArrayList(inputTimestampInStringFormat," ");
			if (_parts.Count != 2) return new DateTime(1900,1,1);
			string _date = initrode.utilities.StringManager.StripWhitespace(_parts[0].ToString());
			string _timeAndMilliseconds = initrode.utilities.StringManager.StripWhitespace(_parts[1].ToString());

            bool _boolValidDateInMM_DD_YYYY = false;
            bool _boolValidDateInYYYY_MM_DD = false;
            _boolValidDateInMM_DD_YYYY = 
                initrode.utilities.StringManager.IsValidDateInMM_DD_YYYYFormat(_date);
            _boolValidDateInYYYY_MM_DD =
                initrode.utilities.StringManager.IsValidDateInYYYYDashMMDashDDFormat(_date);

			if (
                    _boolValidDateInMM_DD_YYYY == false
                    &&
                    _boolValidDateInYYYY_MM_DD == false
                )
				return new DateTime(1900,1,1);
			string _dateYYYY = "";
			string _dateMM = "";
			string _dateDD = "";
			
			ArrayList _dateParts;
            if (_boolValidDateInMM_DD_YYYY == true)
            {
                _dateParts
                    = initrode.utilities.StringManager.splitIntoArrayList
                        (
                            _date
                            , "/"
                        );
                if (_dateParts.Count != 3) return new DateTime(1900, 1, 1);
                _dateYYYY = initrode.utilities.StringManager.StripWhitespace(_dateParts[2].ToString());
                _dateMM = initrode.utilities.StringManager.StripWhitespace(_dateParts[0].ToString());
                _dateDD = initrode.utilities.StringManager.StripWhitespace(_dateParts[1].ToString());

            }
            if (_boolValidDateInYYYY_MM_DD == true)
            {
                _dateParts
                    = initrode.utilities.StringManager.splitIntoArrayList
                        (
                            _date
                            , "-"
                        );
                if (_dateParts.Count != 3) return new DateTime(1900, 1, 1);
                _dateYYYY = initrode.utilities.StringManager.StripWhitespace(_dateParts[0].ToString());
                _dateMM = initrode.utilities.StringManager.StripWhitespace(_dateParts[1].ToString());
                _dateDD = initrode.utilities.StringManager.StripWhitespace(_dateParts[2].ToString());
            }
			ArrayList _timeAndMillisecondParts =	initrode.utilities.StringManager.splitIntoArrayList
													(
														_timeAndMilliseconds
														,"."
													);
			if (_timeAndMillisecondParts.Count != 2) return new DateTime(1900,1,1);
			string _timeMilliseconds = initrode.utilities.StringManager.StripWhitespace(_timeAndMillisecondParts[1].ToString());
			if (initrode.utilities.StringManager.IsValidNumber(_timeMilliseconds) == false) return new DateTime(1900,1,1);
			if (Convert.ToInt32(_timeMilliseconds) > 999) return new DateTime(1900,1,1);
			
			string _time = initrode.utilities.StringManager.StripWhitespace(_timeAndMillisecondParts[0].ToString());
			ArrayList _timeParts =	initrode.utilities.StringManager.splitIntoArrayList
													(
														_time
														,":"
													);
			if (_timeParts.Count != 3) return new DateTime(1900,1,1);
			string _timeHours = initrode.utilities.StringManager.StripWhitespace(_timeParts[0].ToString());
			string _timeMinutes = initrode.utilities.StringManager.StripWhitespace(_timeParts[1].ToString());
			string _timeSeconds = initrode.utilities.StringManager.StripWhitespace(_timeParts[2].ToString());
			StringBuilder _timeBldr = new StringBuilder();
			_timeBldr.Append(	initrode.utilities.StringManager.Fill
								(
									_timeHours
									,"0"
									,true        // from left
									,2
								)
							);
			_timeBldr.Append(":");
			_timeBldr.Append(	initrode.utilities.StringManager.Fill
								(
									_timeMinutes
									,"0"
									,true        // from left
									,2
								)
							);
			_timeBldr.Append(":");
			_timeBldr.Append(	initrode.utilities.StringManager.Fill
								(
									_timeSeconds
									,"0"
									,true        // from left
									,2
								)
							);
			if (initrode.utilities.StringManager.IsValidTimeInHHColonMIColonSSFormat(_timeBldr.ToString()) == false) 
				return new DateTime(1900,1,1);

			return new	DateTime	
						(
							Convert.ToInt32(_dateYYYY)
							,Convert.ToInt32(_dateMM)
							,Convert.ToInt32(_dateDD)
							,Convert.ToInt32(_timeHours)
							,Convert.ToInt32(_timeMinutes)
							,Convert.ToInt32(_timeSeconds)
							,Convert.ToInt32(_timeMilliseconds)
						);
		}
        public static bool stringHas3DecimalsWithThousandsCommasInRow
                            (
                                string inputString
                                , out decimal outputDecimal1
                                , out decimal outputDecimal2
                                , out decimal outputDecimal3
                            )
        {
            outputDecimal1 = (decimal) 0;
            outputDecimal2 = (decimal) 0;
            outputDecimal3 = (decimal) 0;
            ArrayList _oldParts =
                initrode.utilities.StringManager.splitIntoArrayList
                (
                    inputString
                    , @" "
                );
            ArrayList _parts;
            initrode.utilities.StringManager.eliminateEmptyStringsFromArrayListOfString
            (
                _oldParts
                ,out _parts
            );
            for (int _partCtr = 0;
                    _partCtr < (_parts.Count - 2);
                    _partCtr++)
            {
                if (
                        initrode.utilities.StringManager.IsValidDecimal
                        (
                            initrode.utilities.StringManager.StripWhitespace
                            (
                                _parts[_partCtr].ToString()
                            ).Replace(",", "")
                        ) == true
                        && initrode.utilities.StringManager.IsValidDecimal
                            (
                                initrode.utilities.StringManager.StripWhitespace
                                (
                                    _parts[(_partCtr + 1)].ToString()
                                ).Replace(",","")
                                    
                            ) == true
                        && initrode.utilities.StringManager.IsValidDecimal
                            (
                                initrode.utilities.StringManager.StripWhitespace
                                (
                                    _parts[(_partCtr + 2)].ToString()
                                ).Replace(",","")
                            ) == true
                   )
                {
                    outputDecimal1 = 
                        Convert.ToDecimal
                        (
                            initrode.utilities.StringManager.StripWhitespace
                            (
                                _parts[_partCtr].ToString()
                            ).Replace(",","")
                        );
                    outputDecimal2 =
                        Convert.ToDecimal
                        (
                            initrode.utilities.StringManager.StripWhitespace
                            (
                                _parts[(_partCtr + 1)].ToString()
                            ).Replace(",", "")
                        );
                    outputDecimal3 =
                        Convert.ToDecimal
                        (
                            initrode.utilities.StringManager.StripWhitespace
                            (
                                _parts[(_partCtr + 2)].ToString()
                            ).Replace(",", "")
                        );
                    return true;
                }
            }
            return false;
        }

        public static bool stringHas3CommaDelimitedNumbersInRow
                            (
                                string inputCommaDelimitedString
                                , out string outputNumericString1
                                , out string outputNumericString2
                                , out string outputNumericString3
                            )
        {
            outputNumericString1 = "";
            outputNumericString2 = "";
            outputNumericString3 = "";
            ArrayList _parts =
                initrode.utilities.StringManager.splitIntoArrayList
                (
                    inputCommaDelimitedString
                    , ","
                );
            for (int _partCtr = 0;
                    _partCtr < (_parts.Count - 2);
                    _partCtr++)
            {
                if (
                        initrode.utilities.StringManager.IsValidNumber
                        (
                            _parts[_partCtr].ToString()
                        ) == true
                        && initrode.utilities.StringManager.IsValidNumber
                            (
                                _parts[(_partCtr + 1)].ToString()
                            ) == true
                        && initrode.utilities.StringManager.IsValidNumber
                            (
                                _parts[(_partCtr + 2)].ToString()
                            ) == true
                   )
                {
                    outputNumericString1 = _parts[_partCtr].ToString();
                    outputNumericString2 = _parts[(_partCtr + 1)].ToString();
                    outputNumericString3 = _parts[(_partCtr + 2)].ToString();
                    return true;
                }
            }
            return false;
        }
        public static string getBasePathGivenPhysicalPath
                                (
                                    string inputPhysicalPath
                                )
        {
            inputPhysicalPath = inputPhysicalPath.ToUpper();
            string _endOfPath =
                initrode.utilities.StringManager.CaptureFirstOccurrenceOfParenthesesedPattern
                (	    
                    @"^C:\\INETPUB\\WWWROOT\\(.+)$"
                    ,inputPhysicalPath
                );
            ArrayList _pathParts =
                initrode.utilities.StringManager.splitIntoArrayList
                (
                    _endOfPath
                    , @"\\"
                );


            if (_pathParts.Count > 0)
            {
                StringBuilder _basePathBldr = new StringBuilder();
                _basePathBldr.Append("/");
                _basePathBldr.Append(_pathParts[0].ToString());
                return _basePathBldr.ToString();
            }
            return _endOfPath;
        }
        public static bool IsValidEMailAddressPart(string inputPart)
		{
			if (initrode.utilities.StringManager.IsEmptyString(inputPart) == true) return false;
			inputPart = initrode.utilities.StringManager.StripWhitespace(inputPart);
			for (int i = 0; i < inputPart.Length; i++)
			{
				string _character = inputPart.Substring(i,1);
				if (initrode.utilities.StringManager.CHARACTERS_IN_EMAIL_ADDRESS_PART.IndexOf(_character) < 0) return false;
			}
			return true;
		}
		public static bool IsValidEMailAddressList(string inputEMailAddressList)
		{
			if (inputEMailAddressList.IndexOf(";") >= 0) 
			{
				ArrayList _emailAddresses = initrode.utilities.StringManager.splitIntoArrayList(inputEMailAddressList,";");
				for (int _emailAddressCtr = 0; _emailAddressCtr < _emailAddresses.Count; _emailAddressCtr++)
				{
					string _emailAddress = _emailAddresses[_emailAddressCtr].ToString();
					if (initrode.utilities.StringManager.IsValidEMailAddress(_emailAddress) == false) return false;
				}
			}
			else
			{
				if (inputEMailAddressList.IndexOf(",") >= 0) 
				{
					ArrayList _emailAddresses = initrode.utilities.StringManager.splitIntoArrayList(inputEMailAddressList,";");
					for (int _emailAddressCtr = 0; _emailAddressCtr < _emailAddresses.Count; _emailAddressCtr++)
					{
						string _emailAddress = _emailAddresses[_emailAddressCtr].ToString();
						if (initrode.utilities.StringManager.IsValidEMailAddress(_emailAddress) == false) return false;
					}
				}
				else
				{
					if (initrode.utilities.StringManager.IsValidEMailAddress(inputEMailAddressList) == false) return false;
				}
			}
        
			return true;
		}

		public static bool IsEmptyString(string input)
		{
			if (input == null) return true;
			input = StripWhitespace(input);
			if (input.Length == 0) return true;
			return false;
		}
		public static string convertDateTimeInSQLFormatIntoMM_DD_YYYYFormat(string inputDateInSQLFormat)
		{
			if (initrode.utilities.StringManager.IsEmptyString(inputDateInSQLFormat) == true)
				return "";
			inputDateInSQLFormat = initrode.utilities.StringManager.StripWhitespaceFromEnds(inputDateInSQLFormat);
			ArrayList _dateAndTimeParts = initrode.utilities.StringManager.splitIntoArrayList(inputDateInSQLFormat," ");
			if (_dateAndTimeParts.Count != 3) return "";
			string _datePart = initrode.utilities.StringManager.StripWhitespaceFromEnds(_dateAndTimeParts[0].ToString());
            ArrayList _dateParts =
                initrode.utilities.StringManager.splitIntoArrayList(_datePart, "/");
            if (_dateParts.Count != 3) return "";

            StringBuilder _dateBldr =
                new StringBuilder();
            _dateBldr.AppendFormat
            (
                "{0}/{1}/{2}"
                ,   initrode.utilities.StringManager.Fill
                    (
                        initrode.utilities.StringManager.StripWhitespaceFromEnds
                        (
                            _dateParts[0].ToString()
                        )
                        , "0"
                        , true //from left
                        , 2
                    )
                ,   initrode.utilities.StringManager.Fill
                    (
                        initrode.utilities.StringManager.StripWhitespaceFromEnds
                        (
                            _dateParts[1].ToString()
                        )
                        , "0"
                        , true //from left
                        , 2
                    )
                ,   initrode.utilities.StringManager.StripWhitespaceFromEnds
                    (
                        _dateParts[2].ToString()
                    )
            );

            return _dateBldr.ToString();
		}
        public static string   ConvertDateInBESFormatToDB2Format
                                (
                                   string inputDateInBESFormat
                                )
        {
            ArrayList _dateParts =
                initrode.utilities.StringManager.splitIntoArrayList
                (
                    inputDateInBESFormat
                    , " "
                );
            string _month_string = 
                initrode.utilities.StringManager.StripWhitespace
                (
                    _dateParts[0].ToString()
                ).ToUpper();
            int _month_int = 0;
            switch (_month_string)
            {
                case "JAN":
                    _month_int = 1;
                    break;
                case "FEB":
                    _month_int = 2;
                    break;
                case "MAR":
                    _month_int = 3;
                    break;
                case "APR":
                    _month_int = 4;
                    break;
                case "MAY":
                    _month_int = 5;
                    break;
                case "JUN":
                    _month_int = 6;
                    break;
                case "JUL":
                    _month_int = 7;
                    break;
                case "AUG":
                    _month_int = 8;
                    break;
                case "SEP":
                    _month_int = 9;
                    break;
                case "OCT":
                    _month_int = 10;
                    break;
                case "NOV":
                    _month_int = 11;
                    break;
                case "DEC":
                    _month_int = 12;
                    break;
            }
            string _day_string =
                initrode.utilities.StringManager.StripWhitespace
                (
                    _dateParts[1].ToString()
                ).Replace(",", "");
            int _day_int =
                Convert.ToInt32
                (
                    _day_string
                );
            string _year_string =
               initrode.utilities.StringManager.StripWhitespace
               (
                   _dateParts[2].ToString()
               );
            int _year_int =
                Convert.ToInt32
                (
                    _year_string
                );

            string _time_string =
               initrode.utilities.StringManager.StripWhitespace
               (
                   _dateParts[3].ToString()
               );

            ArrayList _timeParts =
                initrode.utilities.StringManager.splitIntoArrayList
                (
                    _time_string
                    , ":"
                );
            string _hours_string =
                initrode.utilities.StringManager.StripWhitespace
                (
                    _timeParts[0].ToString()
                );
            int _hours_int =
                Convert.ToInt32
                (
                    _hours_string
                );
            string _minutes_string =
                initrode.utilities.StringManager.StripWhitespace
                (
                    _timeParts[1].ToString()
                );
            int _minutes_int =
                Convert.ToInt32
                (
                    _minutes_string
                );
            string _seconds_string =
                initrode.utilities.StringManager.StripWhitespace
                (
                    _timeParts[2].ToString()
                );
            int _seconds_int =
                Convert.ToInt32
                (
                    _seconds_string
                );
            string _am_or_pm_string =
                initrode.utilities.StringManager.StripWhitespace
                (
                    _dateParts[4].ToString()
                );
            if (_am_or_pm_string.CompareTo("PM") == 0)
                _hours_int += 12;
            string _microSeconds_string =
                initrode.utilities.StringManager.StripWhitespace
                (
                    _dateParts[5].ToString()
                );
            int _microSeconds_int =
                Convert.ToInt32
                (
                    _microSeconds_string
                );
            StringBuilder _outputDB2DateStringBuilder =
                new StringBuilder();
            _outputDB2DateStringBuilder.AppendFormat
            (
                "{0}-{1}-{2}-{3}.{4}.{5}.{6}"
                , _year_int.ToString()
                , initrode.utilities.StringManager.Fill
                    (
                        _month_int.ToString()
                        , "0"
                        , true //fromLeft
                        , 2
                    )
                , initrode.utilities.StringManager.Fill
                    (
                        _day_int.ToString()
                        , "0"
                        , true //fromLeft
                        , 2
                    )
                , initrode.utilities.StringManager.Fill
                    (
                        _hours_int.ToString()
                        , "0"
                        , true //fromLeft
                        , 2
                    )
                , initrode.utilities.StringManager.Fill
                    (
                        _minutes_int.ToString()
                        , "0"
                        , true //fromLeft
                        , 2
                    )
                , initrode.utilities.StringManager.Fill
                    (
                        _seconds_int.ToString()
                        , "0"
                        , true //fromLeft
                        , 2
                    )
                , initrode.utilities.StringManager.Fill
                    (
                        _microSeconds_int.ToString()
                        , "0"
                        , true //fromLeft
                        , 6
                    )
            );
            return _outputDB2DateStringBuilder.ToString();
        }
		public static bool HasCharactersMatchingRegexString(string inputRegexString, 
															string input)
		{
			input = initrode.utilities.StringManager.StripWhitespaceFromEnds(input);
			Regex pattern = new Regex(inputRegexString);
            bool _patternMatches = false;
            _patternMatches = pattern.IsMatch(input);

            return _patternMatches;
		}

		public static bool IsValidAlphanumeric(string input)
		{
			if (initrode.utilities.StringManager.IsEmptyString(input) == true) return false;
			return initrode.utilities.StringManager.HasCharactersMatchingRegexString("[^a-zA-Z0-9$]", 
																			input);
		}

        public static bool IsValidAlphanumericPlusBlanks(string input)
        {
            if (initrode.utilities.StringManager.IsEmptyString(input) == true) return false;
            return initrode.utilities.StringManager.HasCharactersMatchingRegexString("^[a-zA-Z0-9 ]+$",
                                                                            input);
        }

		public static bool IsValidName(string input)
		{
			if (initrode.utilities.StringManager.IsEmptyString(input) == true) return false;
			return initrode.utilities.StringManager.HasCharactersMatchingRegexString("^[a-zA-Z ]+$", 
																					input);
		}
		public static bool IsValidDecimal(string input)
		{
            input =
                initrode.utilities.StringManager.StripWhitespace
                (
                    input
                );
			if (initrode.utilities.StringManager.IsEmptyString(input) == true) return false;
            if (input.IndexOf("-") == 0
                || input.IndexOf("-") == (input.Length - 1))
            {
                input = input.Replace("-", "");
            }
			return initrode.utilities.StringManager.HasCharactersMatchingRegexString(@"^\d*\.?\d+$", 
																				 input);
		}

		public static bool IsValidNumber(string input)
		{
			if (initrode.utilities.StringManager.IsEmptyString(input) == true) return false;
            input = initrode.utilities.StringManager.StripWhitespace
                    (
                        input
                    );
            if (input.Substring(0, 1).CompareTo("-") == 0)
            {
                input = input.Substring(1);
            }
			return initrode.utilities.StringManager.HasCharactersMatchingRegexString(@"^\d+$", 
																				 input);
		}
		public static string ConvertDateInYYYYMMDDToMMSlashDDSlashYYYY(string inputDateInYYYYMMDDFormat)
		{
			string _strDate =  initrode.utilities.StringManager.StripWhitespace(inputDateInYYYYMMDDFormat);
			if (_strDate.Length != 8) return "";

			StringBuilder _bldr = new StringBuilder();
			_bldr.Append(inputDateInYYYYMMDDFormat.Substring(4,2));
			_bldr.Append("/");
			_bldr.Append(inputDateInYYYYMMDDFormat.Substring(6,2));
			_bldr.Append("/");
			_bldr.Append(inputDateInYYYYMMDDFormat.Substring(0,4));
			return _bldr.ToString();
		}
		public static string	splicePathAndFileNameInfo
								(	
									string inputPath,
									string inputFileName
								)
		{
			StringBuilder _bldr = new StringBuilder();
			_bldr.Append(inputPath);
			_bldr.Append("\\");
			_bldr.Append(inputFileName);
			return _bldr.ToString();
		}
														
		public static void ConvertLastNameCommaFirstNameToLastNameAndFirstName(
								string inputName,
								out string outputLastName,
								out string outputFirstName)
		{
			outputLastName = "";
			outputFirstName = "";
			ArrayList _parts = initrode.utilities.StringManager.splitIntoArrayList(
										inputName,
										",");
			if (_parts.Count != 2) return;
			outputLastName = initrode.utilities.StringManager.StripWhitespaceFromEnds(_parts[0].ToString());
			outputFirstName = initrode.utilities.StringManager.StripWhitespaceFromEnds(_parts[1].ToString());
		}
		public static void ConvertDashedCodeAndLastNameCommaFirstNameIntoCodeLastNameAndFirstName(
								string inputCodeLastNameFirstName,
								out string outputCode,
								out string outputLastName,
								out string outputFirstName)
		{
			outputCode = "";
			outputLastName = "";
			outputFirstName = "";

			if (inputCodeLastNameFirstName.IndexOf("-") < 0 
				|| inputCodeLastNameFirstName.IndexOf(",") < 0) return;
			string _lastNameCommaFirstName = "";
			initrode.utilities.StringManager.ConvertDashedCodeAndDescriptionToCodeAndDescription(
								inputCodeLastNameFirstName,
								out outputCode,
								out _lastNameCommaFirstName);
			ConvertLastNameCommaFirstNameToLastNameAndFirstName(
								 _lastNameCommaFirstName,
								out outputLastName,
								out outputFirstName);

		}
		public static void ConvertDashedCodeAndDescriptionToCodeAndDescription(
								string inputCodeAndDescription,
								out string outputCode,
								out string outputDescription)
		{
			outputCode = "";
			outputDescription = "";

			if (inputCodeAndDescription == null 
				|| initrode.utilities.StringManager.StripWhitespaceFromEnds(inputCodeAndDescription).Length < 3) return;	
			inputCodeAndDescription = initrode.utilities.StringManager.StripWhitespaceFromEnds(inputCodeAndDescription);

			outputCode = initrode.utilities.StringManager.StripWhitespaceFromEnds(
							initrode.utilities.StringManager.CaptureFirstOccurrenceOfParenthesesedPattern(	
									@"^(.*)-.*$",
									inputCodeAndDescription));

			outputDescription = initrode.utilities.StringManager.StripWhitespaceFromEnds(
									initrode.utilities.StringManager.CaptureFirstOccurrenceOfParenthesesedPattern(	
										@"^.*-(.*)$",
										inputCodeAndDescription));
		}

		public static void ConvertPhoneNumberInParenthesesedAreaCodeAndDashedPrefixAndSuffixIntoParts(
								string inputPhoneNumber,
								out string outputAreaCode,
								out string outputPrefix,
								out string outputSuffix)
		{
			outputAreaCode = "";
			outputPrefix = "";
			outputSuffix = "";

			if (inputPhoneNumber == null 
				|| initrode.utilities.StringManager.StripWhitespaceFromEnds(inputPhoneNumber).Length < 13) return;	

			outputAreaCode = initrode.utilities.StringManager.StripWhitespaceFromEnds(
								initrode.utilities.StringManager.CaptureFirstOccurrenceOfParenthesesedPattern(	
									@"^.*\(([0-9][0-9][0-9])\).+$",
									inputPhoneNumber));

			outputPrefix = initrode.utilities.StringManager.StripWhitespaceFromEnds(
								initrode.utilities.StringManager.CaptureFirstOccurrenceOfParenthesesedPattern(	
									@"^.*([0-9][0-9][0-9])\w*-.*$",
									inputPhoneNumber));

			outputSuffix = initrode.utilities.StringManager.StripWhitespaceFromEnds(
							initrode.utilities.StringManager.CaptureFirstOccurrenceOfParenthesesedPattern(	
									@"^.*-([0-9][0-9][0-9][0-9]).*$",
									inputPhoneNumber));

		}

		public static double ConvertStringWithNoPeriodIntoDoubleWithTwoDecimalPlaces(string inputNumber)
		{
			inputNumber =  initrode.utilities.StringManager.StripWhitespace(inputNumber);
			if (initrode.utilities.StringManager.IsValidNumber(inputNumber) == false) return 0;

			return (Convert.ToDouble(inputNumber)/100);
		}

		public static string ConvertDateInMMSlashDDSlashYYYYToYYYYMMDD(string inputDateInMMSlashDDSlashYYYYFormat)
		{
			string _strDate =  initrode.utilities.StringManager.StripWhitespace(inputDateInMMSlashDDSlashYYYYFormat);
			if (_strDate.Length != 10 
				|| _strDate.IndexOf("/") == -1) return "";

			StringBuilder _bldr = new StringBuilder();
			_bldr.Append(inputDateInMMSlashDDSlashYYYYFormat.Substring(6,4));
			_bldr.Append(inputDateInMMSlashDDSlashYYYYFormat.Substring(0,2));
			_bldr.Append(inputDateInMMSlashDDSlashYYYYFormat.Substring(3,2));
			return _bldr.ToString();
		}

		public static string ConvertDateInMMSlashDDSlashYYYYToYYYYDashMMDashDD(string inputDateInMMSlashDDSlashYYYYFormat)
		{
			string _strDate =  initrode.utilities.StringManager.StripWhitespace(inputDateInMMSlashDDSlashYYYYFormat);
			if (_strDate.Length != 10 
				|| _strDate.IndexOf("/") == -1) return "";

			StringBuilder _bldr = new StringBuilder();
			_bldr.Append(inputDateInMMSlashDDSlashYYYYFormat.Substring(6,4));
			_bldr.Append("-");
			_bldr.Append(inputDateInMMSlashDDSlashYYYYFormat.Substring(0,2));
			_bldr.Append("-");
			_bldr.Append(inputDateInMMSlashDDSlashYYYYFormat.Substring(3,2));
			return _bldr.ToString();
		}

		public static void GetDateTimeIfValidDateInYYYYMMDDFormat(string inputDateInYYYYMMDDFormat,
																	out bool outputValid,
																	out DateTime outputDateTime)
		{
			outputValid = false;
			outputDateTime = new DateTime();
			string _strippedInputDate = initrode.utilities.StringManager.StripWhitespace(inputDateInYYYYMMDDFormat);
			if (_strippedInputDate.Length != 8) return;

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

			// We have a valid date - convert it to DateTime
			outputValid = true;
			outputDateTime = new DateTime(	Convert.ToInt16(_yyyy),
											Convert.ToInt16(_mm),
											Convert.ToInt16(_dd));	
	
		}
		public static bool IsValidDateInYYYYMMDDFormat(string inputDateInYYYYMMDDFormat)
		{
			inputDateInYYYYMMDDFormat = initrode.utilities.StringManager.StripWhitespaceFromEnds(inputDateInYYYYMMDDFormat);
			if (inputDateInYYYYMMDDFormat.Length != 8) return false;
			
			string _strYYYY = inputDateInYYYYMMDDFormat.Substring(0,4);
			string _strMM = inputDateInYYYYMMDDFormat.Substring(4,2);
			string _strDD = inputDateInYYYYMMDDFormat.Substring(6,2);

			if (initrode.utilities.StringManager.IsValidDate(	_strMM,
															_strDD,
															_strYYYY) == false) return false;
			return true;
			
		}
		public static bool	IsValidTimeInHHColonMIColonSSFormat
							(
								string inputTimeInHHColonMIColonSSFormat
							)
		{
			inputTimeInHHColonMIColonSSFormat = initrode.utilities.StringManager.StripWhitespaceFromEnds(inputTimeInHHColonMIColonSSFormat);
			if (inputTimeInHHColonMIColonSSFormat.Length != 8) return false;

			string _strHH =	inputTimeInHHColonMIColonSSFormat.Substring(0,2); 
			string _strMI =	inputTimeInHHColonMIColonSSFormat.Substring(3,2); 
			string _strSS =	inputTimeInHHColonMIColonSSFormat.Substring(6,2); 
			if (initrode.utilities.StringManager.IsValidNumber(_strHH) == false ||
				initrode.utilities.StringManager.IsValidNumber(_strMI) == false ||
				initrode.utilities.StringManager.IsValidNumber(_strSS) == false) return false;
			
			int _intHH = Convert.ToInt32(_strHH);
			int _intMI = Convert.ToInt32(_strMI);
			int _intSS = Convert.ToInt32(_strSS);
		
			if (_intHH < 0 || _intHH > 23) return false;
			if (_intMI < 0 || _intMI > 59) return false;
			if (_intSS < 0 || _intSS > 59) return false;

			return true;
		}

		public static string getCurrentDateInMMSlashDDSlashYYYYFormat()
		{
			DateTime _currentDate = DateTime.Now;
			StringBuilder _currentDateBldr = new StringBuilder();
			_currentDateBldr.Append(initrode.utilities.StringManager.Fill(
											_currentDate.Month.ToString(),
											"0",
											true,
											2));
			_currentDateBldr.Append("/");
			_currentDateBldr.Append(initrode.utilities.StringManager.Fill(
											_currentDate.Day.ToString(),
											"0",
											true,
											2));
			_currentDateBldr.Append("/");
			_currentDateBldr.Append(_currentDate.Year.ToString());
			return _currentDateBldr.ToString();
		}

		public static string getCurrentDateInYYYYMMDDFormat()
		{
			DateTime _currentDate = DateTime.Now;
			StringBuilder _currentDateBldr = new StringBuilder();
			_currentDateBldr.Append(_currentDate.Year.ToString());
			_currentDateBldr.Append(initrode.utilities.StringManager.Fill(
											_currentDate.Month.ToString(),
											"0",
											true,
											2));
			_currentDateBldr.Append(initrode.utilities.StringManager.Fill(
											_currentDate.Day.ToString(),
											"0",
											true,
											2));
			return _currentDateBldr.ToString();
		}

		public static bool IsValidTimestamp(string inputTimestamp)
		{
			if (	initrode.utilities.StringManager.IsEmptyString(inputTimestamp) == true) return false;
			if (	initrode.utilities.DateManager.date1ComparedToDate2
					(
						initrode.utilities.StringManager.ConvertTimestampStringToDateTime(inputTimestamp)
						,new DateTime(1900,1,1)
					) == 0) return false;
			return true;
		}
		public static void ValidateAndConvertDateInMM_DD_YYYYFormatWithPossibleOneDigitMonthOrDayToMM_DD_YYYYFormat(
								string inputDateInMM_DD_YYYYFormat,
								out bool outputIsValid,
								out string outputDateInMM_DD_YYYYFormat)
		{
			outputDateInMM_DD_YYYYFormat = "01/01/1900";
			outputIsValid = false;
			if (initrode.utilities.StringManager.IsEmptyString(inputDateInMM_DD_YYYYFormat) == true) return;
			ArrayList _parts = initrode.utilities.StringManager.splitIntoArrayList(
										inputDateInMM_DD_YYYYFormat,
										"/");
			if (_parts.Count != 3) return;
			string strMM = initrode.utilities.StringManager.Fill(
							initrode.utilities.StringManager.StripWhitespaceFromEnds(_parts[0].ToString()),
							"0",
							true,
							2);
			string strDD = initrode.utilities.StringManager.Fill(
							initrode.utilities.StringManager.StripWhitespaceFromEnds(_parts[1].ToString()),
							"0",
							true,
							2);
			string strYYYY = initrode.utilities.StringManager.StripWhitespaceFromEnds(_parts[2].ToString());
			if (initrode.utilities.StringManager.IsValidDate(
											strMM,
											strDD,
											strYYYY) == false) return;

			outputIsValid = true;

			StringBuilder _bldr = new StringBuilder();
			_bldr.Append(strMM);
			_bldr.Append("/");
			_bldr.Append(strDD);
			_bldr.Append("/");
			_bldr.Append(strYYYY);

			outputDateInMM_DD_YYYYFormat = _bldr.ToString();
		}

		public static bool IsValidEMailAddress(string inputEMailAddress)
		{
			if (initrode.utilities.StringManager.IsEmptyString(inputEMailAddress) == true) return false;
			if (inputEMailAddress.IndexOf("@") < 0) return false;
			
			ArrayList _parts = initrode.utilities.StringManager.splitIntoArrayList(inputEMailAddress,"@");
			for (int _partCtr = 0; _partCtr < _parts.Count; _partCtr++)
			{
				string _part = _parts[_partCtr].ToString();
				if (initrode.utilities.StringManager.IsEmptyString(_part) == true) return false;
				if (_part.IndexOf(@".") >= 0)
				{
					ArrayList _periodDelimitedParts = initrode.utilities.StringManager.splitIntoArrayList(_part,@".");
					for (int _periodDelimitedPartCtr = 0; _periodDelimitedPartCtr < _periodDelimitedParts.Count; _periodDelimitedPartCtr++)
					{
						string _periodDelimitedPart = _periodDelimitedParts[_periodDelimitedPartCtr].ToString();
						if (initrode.utilities.StringManager.IsEmptyString(_periodDelimitedPart) == true) return false;
						if (initrode.utilities.StringManager.IsValidEMailAddressPart(_periodDelimitedPart) == false) return false;
					}
				}
				else
				{
					if (initrode.utilities.StringManager.IsValidEMailAddressPart(_part) == false) return false;
				}
			}
			return true;
		}

		public static bool IsValidDateInMM_DD_YYYYFormat(string inputDateInMM_DD_YYYYFormat)
		{
			if (initrode.utilities.StringManager.IsEmptyString(inputDateInMM_DD_YYYYFormat) == true) return false;

			if (initrode.utilities.StringManager.StripWhitespace(inputDateInMM_DD_YYYYFormat).Length != 10) return false;
			return initrode.utilities.StringManager.IsValidDate(inputDateInMM_DD_YYYYFormat.Substring(0,2),
															inputDateInMM_DD_YYYYFormat.Substring(3,2),
															inputDateInMM_DD_YYYYFormat.Substring(6,4));
			

		}
		public static bool IsValidDateInYYYYDashMMDashDDFormat(string inputDateInYYYYDashMMDashDDFormat)
		{
			if (initrode.utilities.StringManager.IsEmptyString(inputDateInYYYYDashMMDashDDFormat) == true) return false;
			inputDateInYYYYDashMMDashDDFormat = initrode.utilities.StringManager.StripWhitespaceFromEnds(inputDateInYYYYDashMMDashDDFormat);
			if (inputDateInYYYYDashMMDashDDFormat.Length != 10) return false;

			string _strTestDateYYYY = inputDateInYYYYDashMMDashDDFormat.Substring(0,4);
			string _strTestDateMM = inputDateInYYYYDashMMDashDDFormat.Substring(5,2);
			string _strTestDateDD = inputDateInYYYYDashMMDashDDFormat.Substring(8,2);
			if (initrode.utilities.StringManager.IsValidDate(
						_strTestDateMM,
						_strTestDateDD,
						_strTestDateYYYY) == true) return true;
			return false;
		}
		public static DateTime convertDateInYYYYDashMMDashDDToDateTime(string inputDateInYYYYDashMMDashDDFormat)
		{
			inputDateInYYYYDashMMDashDDFormat = initrode.utilities.StringManager.StripWhitespaceFromEnds(inputDateInYYYYDashMMDashDDFormat);
			if (initrode.utilities.StringManager.IsValidDateInYYYYDashMMDashDDFormat(inputDateInYYYYDashMMDashDDFormat) == true)
			{
				string _strTestDateYYYY = inputDateInYYYYDashMMDashDDFormat.Substring(0,4);
				string _strTestDateMM = inputDateInYYYYDashMMDashDDFormat.Substring(5,2);
				string _strTestDateDD = inputDateInYYYYDashMMDashDDFormat.Substring(8,2);
				int _intTestDateYYYY = Convert.ToInt32(_strTestDateYYYY);
				int _intTestDateMM = Convert.ToInt32(_strTestDateMM);
				int _intTestDateDD = Convert.ToInt32(_strTestDateDD);
				return new DateTime(_intTestDateYYYY,_intTestDateMM,_intTestDateDD);
			}
			return new DateTime(DateTime.Now.Year,
								DateTime.Now.Month,
								DateTime.Now.Day);
		}
		public static bool IsValidDate(string inputMM,
			string inputDD,
			string inputYYYY)
		{
			if (initrode.utilities.StringManager.IsValidNumber(inputMM) == false ||
				initrode.utilities.StringManager.IsValidNumber(inputDD) == false ||
				initrode.utilities.StringManager.IsValidNumber(inputYYYY) == false) return false;

			int _MM = initrode.utilities.StringManager.ConvertCharacterStringToInt(inputMM);
			int _DD = initrode.utilities.StringManager.ConvertCharacterStringToInt(inputDD);
			int _YYYY = initrode.utilities.StringManager.ConvertCharacterStringToInt(inputYYYY);

			if (_MM < 1 || _MM > 12) return false;

			if (_MM == 1 || 
				_MM == 3 || 
				_MM == 5 || 
				_MM == 7 || 
				_MM == 8 || 
				_MM == 10 || 
				_MM == 12)
			{
				if (_DD < 1 || _DD > 31) return false;
			}
				
			if (_MM == 4 || 
				_MM == 6 || 
				_MM == 9 ||
				_MM == 11)
			{
				if (_DD < 1 || _DD > 30) return false;
			}

			if (_MM == 2)
			{
				bool doesFebruaryHave29Days = false;
				if (_YYYY % 4 == 0)
				{
					if (_YYYY % 100 == 0)
					{
						if (_YYYY % 400 == 0)
						{
							doesFebruaryHave29Days = true;
						}
					}
					else
					{
						doesFebruaryHave29Days = true;
					}
				}
				if (doesFebruaryHave29Days == true)
				{
					if (_DD < 1 || _DD > 29) return false;
				}
				else
				{
					if (_DD < 1 || _DD > 28) return false;
				}
			}
			return true;
		}
		public static ArrayList splitIntoArrayListAfterRemovingCharacterSequence(
											string inputString,
                                            string inputSplitAt,
											string inputCharacterSequenceToBeRemoved)
		{
			inputString = inputString.Replace(inputCharacterSequenceToBeRemoved,"");
			return splitIntoArrayList(inputString,
                                      inputSplitAt);
		}
		public static string	getCurrentDateStringInYYYYMMDDFormat()
		{
			StringBuilder _dateStringbldr = new StringBuilder();
			DateTime _currentDateTime = DateTime.Now;

			_dateStringbldr.Append	(_currentDateTime.Year.ToString());
			_dateStringbldr.Append	(	initrode.utilities.StringManager.Fill
										(
											_currentDateTime.Month.ToString(),
											"0",
											true,
											2
										)
									);								
			_dateStringbldr.Append	(	initrode.utilities.StringManager.Fill
										(
											_currentDateTime.Day.ToString(),
											"0",
											true,
											2
										)
									);					
			return _dateStringbldr.ToString();			
		}
		public static string buildPathAndFileNameFromPathAndFileName
							(
								string inputPath,
								string inputFileNameAndExtension
							)
		{
			StringBuilder _bldr = new StringBuilder();
			_bldr.Append(inputPath);
			_bldr.Append("\\");
			_bldr.Append(inputFileNameAndExtension);
			return _bldr.ToString();
		}
		public static string extractFileNameFromFileNameAndExtension(string inputFileNameAndExtension)
		{
			if (initrode.utilities.StringManager.IsEmptyString(inputFileNameAndExtension) == true) return "";
			ArrayList _fileNameParts = initrode.utilities.StringManager.splitIntoArrayList(inputFileNameAndExtension,@".");
			StringBuilder returnFileNameBldr = new StringBuilder();
			for (int _partCtr = 0; _partCtr < (_fileNameParts.Count - 1); _partCtr++)
			{
				if (returnFileNameBldr.Length > 0) returnFileNameBldr.Append(".");
				returnFileNameBldr.Append(_fileNameParts[_partCtr].ToString());
			}
			return returnFileNameBldr.ToString();
			
		}
		public static string extractPathFromPathAndFileName(string inputPathAndFileName)
		{
			if (initrode.utilities.StringManager.IsEmptyString(inputPathAndFileName) == true) return "";
			ArrayList _fileNameAndPathParts = initrode.utilities.StringManager.splitIntoArrayList(inputPathAndFileName,@"\\");
			StringBuilder returnPathBldr = new StringBuilder();
			for (int _partCtr = 0; _partCtr < (_fileNameAndPathParts.Count - 1); _partCtr++)
			{
				if (returnPathBldr.Length > 0) returnPathBldr.Append("\\");
				returnPathBldr.Append(_fileNameAndPathParts[_partCtr].ToString());
			}
			return returnPathBldr.ToString();
		}

		public static string extractFileNameFromPathAndFileName(string inputPathAndFileName)
		{
			if (initrode.utilities.StringManager.IsEmptyString(inputPathAndFileName) == true) return "";
			ArrayList _fileNameAndPathParts = initrode.utilities.StringManager.splitIntoArrayList(inputPathAndFileName,@"\\");
			return _fileNameAndPathParts[(_fileNameAndPathParts.Count - 1)].ToString();
		}
        public static void eliminateEmptyStringsFromArrayListOfString
                            (
                                ArrayList inputArrayListOfStrings
                                , out ArrayList outputArrayListOfStrings
                            )
        {
            outputArrayListOfStrings = new ArrayList();
            for (int _entryCtr = 0;
                    _entryCtr < inputArrayListOfStrings.Count;
                    _entryCtr++)
            {
                if (
                        initrode.utilities.StringManager.IsEmptyString
                        (
                            inputArrayListOfStrings[_entryCtr].ToString()
                        ) == false
                    )
                    outputArrayListOfStrings.Add
                    (
                        initrode.utilities.StringManager.StripWhitespaceFromEnds
                        (
                            inputArrayListOfStrings[_entryCtr].ToString()
                        )
                    );
            }
        }
        public static ArrayList splitIntoArrayList(string inputString,
                                                   string inputSplitAt)
		{
			ArrayList _returnParts = new ArrayList();
			Regex _r;

			string[] _strParts;
			if (inputSplitAt.CompareTo(@".") == 0) _r = new Regex(@"(\.)");
			else
			{
				if (inputSplitAt.CompareTo(@"\\") == 0) _r = new Regex(@"(\\)");
				else
				{
				
					StringBuilder _bldrPattern = new StringBuilder();
					_bldrPattern.Append("(");
					_bldrPattern.Append(inputSplitAt);
					_bldrPattern.Append(")");
					_r = new Regex(_bldrPattern.ToString()); // Split on inputSplitAt.
				}
			}


			_strParts = _r.Split(inputString);
			for(int i = 0; i < _strParts.Length; i++)
			{
				string _loopPart = _strParts[i].ToString();
				if (_loopPart.CompareTo(inputSplitAt) == 0
					|| (inputSplitAt.CompareTo(@"\\") == 0
						&& _loopPart.CompareTo(@"\") == 0)) continue;
				_returnParts.Add(_strParts[i].ToString());
			}
			return _returnParts;
		}
        public static ArrayList splitIntoArrayListOfNonBlankStrings
                                (
                                    string inputString
                                    ,string inputSplitAt
                                )
        {
            ArrayList _returnParts = new ArrayList();
            Regex _r;

            string[] _strParts;
            if (inputSplitAt.CompareTo(@".") == 0) _r = new Regex(@"(\.)");
            else
            {
                if (inputSplitAt.CompareTo(@"\\") == 0) _r = new Regex(@"(\\)");
                else
                {

                    StringBuilder _bldrPattern = new StringBuilder();
                    _bldrPattern.Append("(");
                    _bldrPattern.Append(inputSplitAt);
                    _bldrPattern.Append(")");
                    _r = new Regex(_bldrPattern.ToString()); // Split on inputSplitAt.
                }
            }


            _strParts = _r.Split(inputString);
            for (int i = 0; i < _strParts.Length; i++)
            {
                string _loopPart = 
                    initrode.utilities.StringManager.StripWhitespaceFromEnds
                    (
                        _strParts[i].ToString()
                    );

                if (initrode.utilities.StringManager.IsEmptyString
                    (
                        _loopPart
                    ) == true
                    || _loopPart.CompareTo(inputSplitAt) == 0
                    || (inputSplitAt.CompareTo(@"\\") == 0
                        && _loopPart.CompareTo(@"\") == 0)) continue;
                _returnParts.Add(_strParts[i].ToString());
            }
            return _returnParts;
        }

		public static string	stripGivenCharactersFromLeftEnd
								(
									string inputStringToStrip,
									string inputStripCharacters
								)
		{
			string tempString = inputStringToStrip;
			for(int i=0; i < tempString.Length; i++)
			{
				string loopChar = tempString.Substring(i,1);
				if (inputStripCharacters.IndexOf(loopChar) < 0)
				{
					return tempString.Substring(i);
				}
			}
			return "";
		}

		public static string suppressLeadingZeroesFromScaleTwoDecimalInStringFormat(string inputDecimalInStringFormat)
		{
			string _strDecimal = initrode.utilities.StringManager.StripWhitespace(inputDecimalInStringFormat);
			string _strSign = "";

			if (_strDecimal.Substring(0,1).CompareTo("-") == 0)
			{
				_strSign = "-";	
				_strDecimal = _strDecimal.Substring(1);
			}

			ArrayList _strDecimalParts = new ArrayList();
			if (_strDecimal.IndexOf(".") >= 0)
				_strDecimalParts = initrode.utilities.StringManager.splitIntoArrayList(_strDecimal, ".");
			else
			{
				_strDecimalParts.Add(_strDecimal);	
				_strDecimalParts.Add("00");
			}
			string _strWholePart = initrode.utilities.StringManager.StripWhitespace(_strDecimalParts[0].ToString());
			string _strDecimalPart = initrode.utilities.StringManager.StripWhitespace(_strDecimalParts[1].ToString());

			// Suppress leading zeroes in whole part.			
			_strWholePart = initrode.utilities.StringManager.stripGivenCharactersFromLeftEnd
							(
								_strWholePart,
								"0"                // Characters to strip
							);
			if (_strWholePart.Length == 0)
				_strWholePart = "0";
			StringBuilder _bldr = new StringBuilder();
			_bldr.Append(_strSign);
			_bldr.Append(_strWholePart);
			_bldr.Append(".");
			_bldr.Append(_strDecimalPart);
			return _bldr.ToString();
		}

		public static string FormatSystemDateToDateString(string input)
		{
			StringBuilder bldr = new StringBuilder();
			if (initrode.utilities.StringManager.IsEmptyString(input) == true)
			{
				return "";
			}
			string[] _dateTimeParts;
			Regex _r = new Regex("( )"); // Split on spaces.
			_dateTimeParts = _r.Split(input);

			if (_dateTimeParts.Length != 5)
			{
				return "";
			}

			string[] _dateParts;
			Regex _r2 = new Regex("(/)"); // Split on spaces.
			_dateParts = _r2.Split(_dateTimeParts[0].ToString());

			if (_dateParts.Length != 5)
			{
				return "";
			}
			bldr.Append(initrode.utilities.StringManager.Fill(_dateParts[0].ToString(),
															"0",
															true,
															2));
			bldr.Append("/");
			bldr.Append(initrode.utilities.StringManager.Fill(_dateParts[2].ToString(),
															"0",
															true,
															2));
			bldr.Append("/");
			bldr.Append(_dateParts[4].ToString());

			return bldr.ToString();
		}

		public static string Fill(string input,
			string fillChars,
			bool boolFromLeft,
			int maxLength)
		{
			input = initrode.utilities.StringManager.StripWhitespaceFromEnds(input);
			StringBuilder bldr = new StringBuilder("",200);
			switch(boolFromLeft)
			{
				case true:
					while((input.Length + bldr.Length + fillChars.Length) <= maxLength)
					{
						bldr.Append(fillChars);
					}
					bldr.Append(input);
					break;
				case false:
					bldr.Append(input);
					while((bldr.Length + fillChars.Length) <= maxLength)
					{
						bldr.Append(fillChars);
					}
					break;
			}
			return bldr.ToString();
		}


		public static int ConvertCharacterStringToInt(string input)
		{
			string numericCharacters = "0123456789";
			input = initrode.utilities.StringManager.StripWhitespace(input);
			StringBuilder bldr = new StringBuilder("",10);
			for(int i=0; i < input.Length; i++)
			{
				string loopChar = input.Substring(i,1);
				if (numericCharacters.IndexOf(loopChar) >= 0)
				{
					bldr.Append(loopChar);
				}
			}
			if (bldr.Length == 0) return 0;
			return Convert.ToInt32(bldr.ToString());
		}

		public static string UpperCaseFirstCharactersInName(string input)
		{
			input = initrode.utilities.StringManager.StripWhitespaceFromEnds(input);
			char[] _splitChars = new char[1];
			_splitChars[0] = ' ';
			string[] _parts = input.Split(_splitChars);
			StringBuilder _bldr = new StringBuilder();
			for(int _partCtr = 0; _partCtr < _parts.Length; _partCtr++)
			{
				string _part = initrode.utilities.StringManager.StripWhitespaceFromEnds(_parts[_partCtr].ToString().ToLower());
				if (initrode.utilities.StringManager.IsEmptyString(_part) == true) continue;

				_bldr.Append(_part.Substring(0,1).ToUpper());
				if (_part.Length > 1)
				{
					_bldr.Append(_part.Substring(1));
				}
				if (_partCtr < (_parts.Length - 1))
				{
					_bldr.Append(" ");
				}
			}
			return _bldr.ToString();
		}
		public static string GetCurrentDateInYYYY_MM_DD_FORMAT()
		{
			StringBuilder _bldr = new StringBuilder();
			DateTime _currentDate = DateTime.Now;
			_bldr.Append(_currentDate.Year.ToString());
			_bldr.Append("-");
			_bldr.Append(initrode.utilities.StringManager.Fill(
							_currentDate.Month.ToString(),
							"0",    /* Zero-fill */
							true,   /* From Left */
							2));
			_bldr.Append("-");
			_bldr.Append(initrode.utilities.StringManager.Fill(
							_currentDate.Day.ToString(),
							"0",    /* Zero-fill */
							true,   /* From Left */
							2));
			return _bldr.ToString();
		}
		public static string StripWhitespaceFromEnds(string input)
		{
			string whitespaceCharacters = " \n\t\r";
			string tempString = input;
			if (initrode.utilities.StringManager.IsEmptyString(tempString) == true) return "";
			tempString = input;
			
			for(int i=0; i < tempString.Length; i++)
			{
				string loopChar = tempString.Substring(i,1);
				if (whitespaceCharacters.IndexOf(loopChar) < 0)
				{
					tempString = tempString.Substring(i);
					break;
				}
			}
			for(int i=(tempString.Length - 1); i >= 0; i--)
			{
				string loopChar = tempString.Substring(i,1);
				if (whitespaceCharacters.IndexOf(loopChar) < 0)
				{
					tempString = tempString.Substring(0,i+1);
					break;
				}
			}
			return tempString;
		}
		public static string StripWhitespace(string input)
		{
			string whitespaceCharacters = " \n\t\r";
			string tempString = input;
			StringBuilder bldr = new StringBuilder();
			for(int i=0; i < tempString.Length; i++)
			{
                if (i >= tempString.Length)
                    return bldr.ToString();
				string loopChar = tempString.Substring(i,1);
				if (whitespaceCharacters.IndexOf(loopChar) < 0)
				{
					bldr.Append(loopChar);
				}
			}
			return bldr.ToString();
		}
		public static string CaptureFirstOccurrenceOfParenthesesedPattern(	string inputPattern,
																			string inputStringToSearch)
		{
			string _returnString = "";				
			// Compile the regular expression.
			Regex _r = new Regex(inputPattern, RegexOptions.IgnoreCase);
			// Match the regular expression pattern against a text string.
			Match _m = _r.Match(inputStringToSearch);
			if (_m.Success) 
			{
				// 1 refers to the first parentheses'd match found.
				Group _g = _m.Groups[1];
				CaptureCollection _cc = _g.Captures;
				_returnString = initrode.utilities.StringManager.StripWhitespaceFromEnds(_cc[0].ToString().ToUpper());
			}
			return _returnString;
		}

		public static string GetDisplayFormatFor10DigitPhoneNumber(string inputPhoneNumber)
		{
			string _phoneNumber = initrode.utilities.StringManager.StripWhitespace(inputPhoneNumber);
			if (_phoneNumber.Length != 10)
			{
				return string.Empty;
			}
			StringBuilder _returnPhoneNumberBldr = new StringBuilder();
			_returnPhoneNumberBldr.Append("(");
			_returnPhoneNumberBldr.Append(_phoneNumber.Substring(0,3));
			_returnPhoneNumberBldr.Append(") ");
			_returnPhoneNumberBldr.Append(_phoneNumber.Substring(3,3));
			_returnPhoneNumberBldr.Append(" - ");
			_returnPhoneNumberBldr.Append(_phoneNumber.Substring(6,4));
			return _returnPhoneNumberBldr.ToString();
		}
        public static string convertIntegerToStringWithThousandsDelimiters
                                (
                                      int inputDecimal
                                )
        {
            StringBuilder _integerBldr = new StringBuilder();
            string _rest = inputDecimal.ToString();
            while (_rest.Length >= 4)
            {
                _integerBldr.AppendFormat
                (
                    ",{0}"
                    , _rest.Substring((_rest.Length - 3), 3)
                );
                _rest = _rest.Substring(0, (_rest.Length - 3));
            }
            _integerBldr.Insert
            (
                0
                , _rest
            );
            return _integerBldr.ToString();
        }
        public static string    convertDecimalToStringWithThousandsDelimiters
                                (
                                    decimal inputDecimal
                                    , int inputNumberOfDecimalPlaces
                                )
        {
            string _workString = inputDecimal.ToString();
            ArrayList _workStringParts =
                initrode.utilities.StringManager.splitIntoArrayList
                (
                    _workString
                    ,@"."
                );
            string _wholePart = "";
            string _decimalPart = "";
            if (_workStringParts.Count > 2) return "";
            if (_workStringParts.Count == 1)
            {
                _wholePart = _workStringParts[0].ToString();
                _decimalPart = "00";
            }
            else
            {
                _wholePart = _workStringParts[0].ToString();
                _decimalPart = _workStringParts[1].ToString();
            }


            _decimalPart =
                initrode.utilities.StringManager.Fill
                (
                    _decimalPart
                    , "0"
                    , true  //Fill from left
                    , inputNumberOfDecimalPlaces
                );
            StringBuilder _decimalBldr = new StringBuilder();
            string _rest = _wholePart;
            while (_rest.Length >= 4)
            {
                _decimalBldr.AppendFormat
                (
                    ",{0}"
                    , _rest.Substring((_rest.Length - 3), 3)
                );
                _rest = _rest.Substring(0, (_rest.Length - 3));
            }
            _decimalBldr.Insert
            (
                0
                ,_rest
            );
            _decimalBldr.AppendFormat
            (
                ".{0}"
                ,_decimalPart
            );
            return _decimalBldr.ToString();			
        }
		public static string	ConvertDecimalToMainframeStringOfDigitsWithoutDecimalPoint
								(
									decimal inputDecimal
									, int inputNumberOfMainframeDigitsUsed
								)
		{
			string _workString = inputDecimal.ToString();
			_workString.Replace(".","");
			_workString = 
				initrode.utilities.StringManager.Fill
				(
					_workString
					,"0" 
					,true  //Fill from left
					,inputNumberOfMainframeDigitsUsed
				);		
			return _workString;			
		}
	}
}


CodeSOD: I'm Sooooooo Random, LOL

There are some blocks of code that require a preamble, and an explanation of the code and its flow. Often you need to provide some broader context.

Sometimes, you get some code like Wolf found, which needs no explanation:

export function generateRandomId(): string { counter++; return 'id' + counter; }

I mean, I guess that's a slightly better than this solution. Wolf found this because some code downstream was expecting random, unique IDs, and wasn't getting them.

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


Lowest Bidder Squared
Monday Aug 19, 2019 6:30 AM

Stack of coins 0214

Initech was in dire straits. The website was dog slow, and the budget had been exceeded by a factor of five already trying to fix it. Korbin, today's submitter, was brought in to help in exchange for decent pay and an office in their facility.

He showed up only to find a boxed-up computer and a brand new flat-packed desk, also still in the box. The majority of the space was a video-recording studio that saw maybe 4-6 hours of use a week. After setting up his office, Korbin spent the next day and a half finding his way around the completely undocumented C# code. The third day, there was a carpenter in the studio area. Inexplicably, said carpenter decided he needed to contact-glue carpet to a set of huge risers ... indoors. At least a gallon of contact cement was involved. In minutes, Korbin got a raging headache, and he was essentially gassed out of the building for the rest of the day. Things were not off to a good start.

Upon asking around, Korbin quickly determined that the contractors originally responsible for coding the website had underbid the project by half, then subcontracted the whole thing out to a team in India to do the work on the cheap. The India team had then done the very same thing, subcontracting it out to the most cut-rate individuals they could find. Everything had been written in triplicate for some reason, making it impossible to determine what was actually powering the website and what was dead code. Furthermore, while this was a database-oriented site, there were no stored procedures, and none of the (sub)subcontractors seemed to understand how to use a JOIN command.

In an effort to tease apart what code was actually needed, Korbin turned on profiling. Only ... it was already on in the test version of the site. With a sudden ominous hunch, he checked the live site—and sure enough, profiling was running in production as well. He shut it off, and instantly, the whole site became more responsive.

The next fix was also pretty simple. The site had a bad habit of asking for information it already had, over and over, without any JOINs. Reducing the frequency of database hits improved performance again, bringing it to within an order of magnitude of what one might expect from a website.

While all this was going on, the leaderboard page had begun timing out. Sure enough, it was an N-squared solution: open database, fetch record, close database, repeat, then compare the two records, putting them in order and beginning again. With 500 members, it was doing 250,000 passes each time someone hit the page. Korbin scrapped the whole thing in favor of the site's first stored procedure, then cached it to call only once a day.

The weeks went on, and the site began to take shape, finally getting something like back on track. Thanks to the botched rollout, however, many of the company's endorsements had vanished, and backers were pulling out. The president got on the phone with some VIP about Facebook—because as we all know, the solution to any company's problem is the solution to every company's problems.

"Facebook was written in PHP. He told me it was the best thing out there. So we're going to completely redo the website in PHP," the president confidently announced at the next all-hands meeting. "I want to hear how long everyone thinks this will take to get done."

The only developers left at that point were Korbin and a junior kid just out of college, with one contractor with some experience on the project.

"Two weeks. Maybe three," the kid replied.

They went around the table, and all the non-programmers chimed in with the 2-3 week assessment. Next to last came the experienced contractor. Korbin's jaw nearly dropped when he weighed in at 3-4 weeks.

"None of that is realistic!" Korbin proclaimed. "Even with the existing code as a road map, it's going to take 4-6 months to rewrite. And with the inevitable feature-creep and fixes for things found in testing, it is likely to take even longer."

Korbin was told the next day he could pick up his final check. Seven months later, he ran into the junior kid again, and asked how the rewrite went.

"It's still ongoing," he admitted.

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


Error'd: What About the Fish?
Friday Aug 16, 2019 6:30 AM

"On the one hand, I don't want to know what the fish has to do with Boris Johnson's love life...but on the other hand I have to know!" Mark R. writes.

 

"Not sure if that's a new GDPR rule or the Slack Mailbot's weekend was just that much better then mine," Adam G. writes.

 

Connor W. wrote, "You know what, I think I'll just stay inside."

 

"It's great to see that an attempt at personalization was made, but whatever happened to 'trust but verify'?" writes Rob H.

 

"For a while, I thought that, maybe, I didn't actually know how to use my iPhone's alarm. Instead, I found that it just wasn't working right. So, I contacted Apple Support, and while they were initially skeptical that it was an iOS issue, this morning, I actually have proof!" Markus G. wrote.

 

Tim G. writes, "I guess that's better than an angry error message."

 

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


CodeSOD: A Devil With a Date

Jim was adding a feature to the backend. This feature updated a few fields on an object, and then handed the object off as JSON to the front-end.

Adding the feature seemed pretty simple, but when Jim went to check out its behavior in the front-end, he got validation errors. Something in the data getting passed back by his web service was fighting with the front end.

On its surface, that seemed like a reasonable problem, but when looking into it, Jim discovered that it was the record_update_date field which was causing validation issues. The front-end displayed this as a read only field, so there was no reason to do any client-side validation in the first place, and that field was never sent to the backend, so there was even less than no reason to do validation.

Worse, the field had, at least to the eye, a valid date: 2019-07-29T00:00:00.000Z. Even weirder, if Jim changed the backend to just return 2019-07-29, everything worked. He dug into the validation code to see what might be wrong about it:

/**
 * Custom validation
 *
 * This is a callback function for ajv custom keywords
 *
 * @param  {object} wsFormat aiFormat property content
 * @param  {object} data Data (of element type) from document where validation is required
 * @param  {object} itemSchema Schema part from wsValidation keyword
 * @param  {string} dataPath Path to document element
 * @param  {object} parentData Data of parent object
 * @param  {string} key Property name
 * @param  {object} rootData Document data
 */
function wsFormatFunction(wsFormat, data, itemSchema, dataPath, parentData, key, rootData) {

    let valid;
    switch (aiFormat) {
        case 'date': {
            let regex = /^\d\d\d\d-[0-1]\d-[0-3](T00:00:00.000Z)?\d$/;
            valid = regex.test(data);
            break;
        }
        case 'date-time': {
            let regex = /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d:\d\d)$/i;
            valid = regex.test(data);
            break;
        }
        case 'time': {
            let regex = /^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/;
            valid = regex.test(data);
            break;
        }
        default: throw 'Unknown wsFormat: ' + wsFormat;
    }

    if (!valid) {
        wsFormatFunction['errors'] = wsFormatFunction['errors'] || [];

        wsFormatFunction['errors'].push({
            keyword: 'wsFormat',
            dataPath: dataPath,
            message: 'should match format "' + wsFormat + '"',
            schema: itemSchema,
            data: data
        });
    }

    return valid;
}

When it starts with “Custom validation” and it involves dates, you know you’re in for a bad time. Worse, it’s custom validation, dates, and regular expressions written by someone who clearly didn’t understand regular expressions.

Let’s take a peek at the branch which was causing Jim’s error, and examine the regex:

/^\d\d\d\d-[0-1]\d-[0-3](T00:00:00.000Z)?\d$/

It should start with four digits, followed by a dash, followed by a value between 0 and 1. Then another digit, then a dash, then a number between 0 and 3, then the time (optionally), then a final digit.

It’s obvious why Jim’s perfectly reasonable date wasn’t working: it needed to be 2019-07-2T00:00:00.000Z9. Or, if Jim just didn’t include the timestamp, not only would 2019-07-29 be a valid date, but so would 2019-19-39, which just so happens to be my birthday. Mark your calendars for the 39th of Undevigintiber.

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


CodeSOD: A Loop in the String
Wednesday Aug 14, 2019 6:30 AM

Robert was browsing through a little JavaScript used at his organization, and found this gem of type conversion.

//use only for small numbers
function StringToInteger (str) {
    var int = -1;
    for (var i=0; i<=100; i++) {
        if (i+"" == str) {
            int = i;
            break;
        }
    }
    return int;
}

So, this takes our input str, which is presumably a string, and it starts counting from 0 to 100. i+"" coerces the integer value to a string, which we compare against our string. If it’s a match, we’ll store that value and break out of the loop.

Obviously, this has a glaring flaw: the 100 is hardcoded. So what we really need to do is add a search_low and search_high parameter, so we can write the for loop as i = search_low; i <= search_high; i++ instead. Because that’s the only glaring flaw in this code. I can’t think of any possible better way of converting strings to integers. Not a one.

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


CodeSOD: Nullable Knowledge

You’ve got a decimal value- maybe. It could be nothing at all, and you need to handle that null gracefully. Fortunately for you, C# has “nullable types”, which make this task easy.

Ian P’s co-worker made this straightforward application of nullable types.

public static decimal ValidateDecimal(decimal? value)
{
if (value == null) return 0;
decimal returnValue = 0;
Decimal.TryParse(value.ToString(), out returnValue);
return returnValue;
}

The lack of indentation was in the original.

The obvious facepalm is the Decimal.TryParse call. If our decimal has a value, we could just return it, but no, instead, we convert it to a string then convert that string back into a Decimal.

But the real problem here is someone who doesn’t understand what .NET’s nullable types offer. For starters, one could make the argument that value.HasValue() is more readable than value == null, though that’s clearly debatable. That’s not really the problem though.

The purpose of ValidateDecimal is to return the input value, unless the input value was null, in which case we want to return 0. Nullable types have a lovely GetValueOrDefault() method, which returns the value, or a reasonable default. What is the default for any built in numeric type?

0.

This method doesn’t need to exist, it’s already built in to the decimal? type. Of course, the built-in method almost certainly doesn’t do a string conversion to get its value, so the one with a string is better, is it knot?

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


Internship of Things
Monday Aug 12, 2019 6:30 AM

Mindy was pretty excited to start her internship with Initech's Internet-of-Things division. She'd been hearing at every job fair how IoT was still going to be blowing up in a few years, and how important it would be for her career to have some background in it.

It was a pretty standard internship. Mindy went to meetings, shadowed developers, did some light-but-heavily-supervised changes to the website for controlling your thermostat/camera/refrigerator all in one device.

As part of testing, Mindy created a customer account on the QA environment for the site. She chucked a junk password at it, only to get a message: "Your password must be at least 8 characters long, contain at least three digits, not in sequence, four symbols, at least one space, and end with a letter, and not be more than 10 characters."

"Um, that's quite the password rule," Mindy said to her mentor, Bob.

"Well, you know how it is, most people use one password for every site, and we don't want them to do that here. That way, when our database leaks again, it minimizes the harm."

"Right, but it's not like you're storing the passwords anyway, right?" Mindy said. She knew that even leaked hashes could be dangerous, but good salting/hashing would go a long way.

"Of course we are," Bob said. "We're selling web connected thermostats to what can be charitably called 'twelve-o-clock flashers'. You know what those are, right? Every clock in their house is flashing twelve?" Bob sneered. "They can't figure out the site, so we often have to log into their account to fix the things they break."

A few days later, Initech was ready to push a firmware update to all of the Model Q baby monitor cameras. Mindy was invited to watch the process so she could understand their workflow. It started off pretty reasonable: their CI/CD system had a verified build, signed off, ready to deploy.

"So, we've got a deployment farm running in the cloud," Bob explained. "There are thousands of these devices, right? So we start by putting the binary up in an S3 bucket." Bob typed a few commands to upload the binary. "What's really important for our process is that it follows this naming convention. Because the next thing we're going to do is spin up a half dozen EC2 instances- virtual servers in the cloud."

A few more commands later, and then Bob had six sessions open to cloud servers in tmux. "Now, these servers are 'clean instances', so the very first thing I have to do is upload our SSH keys." Bob ran an ssh-copy-id command to copy the SSH key from his computer up to the six cloud VMs.

"Wait, you're using your personal SSH keys?"

"No, that'd be crazy!" Bob said. "There's one global key for every one of our Model Q cameras. We've all got a copy of it on our laptops."

"All… the developers?"

"Everybody on the team," Bob said. "Developers to management."

"On their laptops?"

"Well, we were worried about storing something so sensitive on the network."

Bob continued the process, which involved launching a script that would query a webservice to see which Model Q cameras were online, then sshing into them, having them curl down the latest firmware, and then self-update. "For the first few days, we leave all six VMs running, but once most of them have gotten the update, we'll just leave one cloud service running," Bob explained. "Helps us manage costs."

It's safe to say Mindy learned a lot during her internship. Mostly, she learned, "don't buy anything from Initech."

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


Error'd: Intentionally Obtuse
Friday Aug 9, 2019 6:30 AM

"Normally I do pretty well on the Super Quiz, but then they decided to do it in Latin," writes Mike S.

 

"Uh oh, this month's AWS costs are going to be so much higher than last month's!" Ben H. writes.

 

Amanda C. wrote, "Oh, neat, Azure has some recommendations...wait...no...'just kidding' I guess?"

 

"Here I never thought that SQL Server log space could go negative, and yet, here we are," Michael writes.

 

"I love the form factor on this motherboard, but I'm not sure what case to buy with it," Todd C. writes, "Perhaps, if it isn't working, I can just give it a little kick?"

 

Maarten C. writes, "Next time, I'll name my spreadsheets with dog puns...maybe that'll make things less ruff."

 

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


CodeSOD: Swimming Downstream

When Java added their streams API, they brought the power and richness of functional programming styles to the JVM, if we ignore all the other non-Java JVM languages that already did this. Snark aside, streams were a great addition to the language, especially if we want to use them absolutely wrong.

Like this code Miles found.

See, every object in the application needs to have a unique identifier. So, for every object, there’s a method much like this one:

/**
     * Get next priceId
     *
     * @return next priceId
     */
    public String createPriceId() {
        List<String> ids = this.prices.stream().map(m -> m.getOfferPriceId()).collect(Collectors.toList());
        for (Integer i = 0; i < ids.size(); i++) {
            ids.set(i, ids.get(i).split("PR")[1]);
        }
        try {
            List<Integer> intIds = ids.stream().map(id -> Integer.parseInt(id)).collect(Collectors.toList());
            Integer max = intIds.stream().mapToInt(id -> id).max().orElse(0);
            return "PR" + (max + 1);
        } catch (Exception e) {
            return "PR" + 1;
        }
    }

The point of a stream is that you can build a processing pipeline: starting with a list, you can perform a series of operations but only touch each item in the stream once. That, of course, isn’t what we do here.

First, we map the prices to extract the offerPriceId and convert it into a list. Now, this list is a set of strings, so we iterate across that list of IDs, to break the "PR" prefix off. Then, we’ll map that list of IDs again, to parse the strings into integers. Then, we’ll cycle across that new list one more time, to find the max value. Then we can return a new ID.

And if anything goes wrong in this process, we won’t complain. We just return an ID that’s likely incorrect- "PR1". That’ll probably cause an error later, right? They can deal with it then.

Everything here is just wrong. This is the wrong way to use streams- the whole point is this could have been a single chain of function calls that only needed to iterate across the input data once. It’s also the wrong way to handle exceptions. And it’s also the wrong way to generate IDs.

Worse, a largely copy/pasted version of this code, with the names and prefixes changed, exists in nearly every model class. And these are database model classes, according to Miles, so one has to wonder if there might be a better way to generate IDs…

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