/// <summary>
        /// Checks to ensure that the dataset is not null, has the specified number of tables
        /// and whether or not each table MUST have rows in it.
        /// </summary>
        /// <param name="requiredNumberOfTables">
        /// The number of tables that dataset must contain
        /// </param>
        /// <param name="tableMustHaveRowsFlags">
        /// A list of boolean flags denoting whether each table in the set MUST have some rows in it.
        /// e.g.
        ///
        /// DataSet ds = GetSomeDataSet();
        /// ds.IsPopulated(3, true, false, true);
        ///
        /// means that the dataset MUST have 3 tables. The first and third tables MUST have rows in them,
        /// the second table may or may not have rows in it.
        /// </param>
        /// <returns>
        /// True if the the tables required to be populated actually are, otherwise false.
        /// </returns>
        public static bool IsPopulated(this DataSet ds, int requiredNumberOfTables, params bool[] tableMustHaveRowsFlags)
        {
            _logger.DebugMethodCalled(ds, requiredNumberOfTables, tableMustHaveRowsFlags);

            #region Input validation

            Insist.IsAtLeast(requiredNumberOfTables, 1, "requiredNumberOfTables");
            Insist.IsNotNull(tableMustHaveRowsFlags, "tableMustHaveRowsFlags");
            Insist.Equality(tableMustHaveRowsFlags.Length, requiredNumberOfTables, "tableMustHaveRowsFlags", "The number of tableMustHaveRowsFlags must match the number of tables");

            #endregion

            if (ds == null ||
                ds.Tables == null ||
                ds.Tables.Count != requiredNumberOfTables)
            {
                return(false);
            }
            else
            {
                for (int i = 0; i < requiredNumberOfTables; i++)
                {
                    if (tableMustHaveRowsFlags[i] == true &&
                        (
                            ds.Tables[i].Rows == null ||
                            ds.Tables[i].Rows.Count == 0
                        ))
                    {
                        return(false);
                    }
                }

                return(true);
            }
        }
        public static IList <IList <T> > Chunk <T>(this IEnumerable <T> data, int chunkSize)
        {
            #region Input validation

            Insist.IsAtLeast(chunkSize, 1, "chunkSize");

            if (!data.Any())
            {
                return(new List <IList <T> >());
            }

            #endregion

            IList <IList <T> > chunks = new List <IList <T> >();
            int currentIndex          = 0;

            List <T> currentChunk = null;

            foreach (T element in data)
            {
                int offset = currentIndex % chunkSize;

                if (offset == 0)
                {
                    currentChunk = new List <T>();
                    chunks.Add(currentChunk);
                }

                currentChunk.Add(element);

                currentIndex++;
            }

            return(chunks);
        }
Ejemplo n.º 3
0
        /// <summary>
        ///  Pads the given string with the character specified to the given length.
        /// </summary>
        /// <param name="str">The string to be padded.</param>
        /// <param name="padCharacter">The character to be used as padding.</param>
        /// <param name="padToLength">The length of the new, padded string.</param>
        /// <param name="mode">The side the padding should be applied to.</param>
        /// <returns>The padded string.</returns>
        public static string Pad(this string str, char padCharacter, int padToLength, PaddingMode mode)
        {
            _logger.DebugMethodCalled(str, padCharacter, padToLength, mode);

            #region Input Validation

            Insist.IsAtLeast(padToLength, 1, "padToLength");

            #endregion

            bool createPadding = false;

            if (str != null)
            {
                if (str.Length > padToLength)
                //No need to do any padding if the string is already long enough
                {
                    createPadding = false;
                }
                else
                //String is too short so padding required.
                {
                    createPadding = true;
                }
            }
            else
            //The string is null so we'll set the output string to just the
            //padded string
            {
                createPadding = true;
            }

            string paddedStr;

            if (createPadding)
            {
                int    requiredPadding = padToLength - (str == null ? 0 : str.Length);
                string padding         = new string(padCharacter, requiredPadding);

                switch (mode)
                {
                case PaddingMode.Left:
                    paddedStr = padding + (str == null ? string.Empty : str);
                    break;

                case PaddingMode.Right:
                    paddedStr = (str == null ? string.Empty : str) + padding;
                    break;

                default:
                    throw new NotSupportedException(String.Format("The padding mode {0} is not supported.", mode));
                }
            }
            else
            {
                paddedStr = str;
            }

            return(paddedStr);
        }
        /// <summary>
        /// Generates a random string that is as long as length
        /// </summary>
        /// <param name="random">
        /// The random number generator to use
        /// </param>
        /// <param name="length">
        /// The length of the string to be generated. Returns an empty string if length
        /// is zero.
        /// </param>
        /// <param name="allowNumbers">
        /// Whether or not to allow numbers in the generated string
        /// </param>
        /// <param name="allowSymbols">
        /// Whether or not to allow symbols in the string
        /// </param>
        /// <returns>
        /// A random string of the specified length
        /// </returns>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when random is null
        /// </exception>
        /// <exception cref="System.ArgumentException">
        /// Throw when length is less than 0.
        /// </exception>
        public static string NextString(this Random random, int length, bool allowNumbers, bool allowSymbols)
        {
            #region Input Validation

            Insist.IsNotNull(random, "random");
            Insist.IsAtLeast(length, 0, "length");

            #endregion

            if (length == 0)
            {
                return(string.Empty);
            }

            StringBuilder builder = new StringBuilder();
            while (builder.Length < length)
            {
                //+1 because MaxValue is exclusive but minValue is inclusive
                int  i        = random.Next(STARTING_ASCII_CODE, ENDING_ASCII_CODE + 1);
                bool isNumber = false;
                bool isSymbol = false;
                bool canAdd   = true;

                if ((i >= UPPERCASE_ALPHABET_STARTING_CODE && i <= UPPERCASE_ALPHABET_ENDING_CODE) ||
                    (i >= LOWERCASE_ALPHABET_STARTING_CODE && i <= LOWERCASE_ALPHABET_ENDING_CODE))
                {
                    canAdd = true;
                }
                else if (i >= NUMBER_STARTING_CODE && i <= NUMBER_ENDING_CODE)
                {
                    isNumber = true;
                }
                else
                {
                    isSymbol = true;
                }

                if (isNumber == true &&
                    allowNumbers == false)
                {
                    canAdd = false;
                }

                if (isSymbol == true &&
                    allowSymbols == false)
                {
                    canAdd = false;
                }

                if (canAdd)
                {
                    builder.Append((char)i);
                }
            }

            return(builder.ToString());
        }
Ejemplo n.º 5
0
 public void IsAtLeast_Thrown_Exception_Has_Correct_Argument_Name()
 {
     try {
         Insist.IsAtLeast(1, 5, ARGUMENT_NAME);
     }
     catch (ArgumentOutOfRangeException e)
     {
         Assert.AreEqual(ARGUMENT_NAME, e.ParamName);
     }
 }
Ejemplo n.º 6
0
 public void IsAtLeast_Thrown_Exception_Has_Correct_Message()
 {
     try
     {
         Insist.IsAtLeast(1, 5, ARGUMENT_NAME, MESSAGE);
     }
     catch (ArgumentException e)
     {
         Assert.IsTrue(e.Message.Contains(MESSAGE));
     }
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Copies the contents of this Trie to the supplied array at the specified index
        /// </summary>
        public void CopyTo(KeyValuePair <TKey, TValue>[] array, int arrayIndex)
        {
            #region Input validation

            Insist.IsNotNull(array, "array");
            Insist.IsAtLeast(arrayIndex, 0, "arrayIndex");
            Insist.IsAtLeast((array.Length - arrayIndex), this.Count, "array", "The number of elements in the collection is greater than the size of the destination array");

            #endregion

            int currentIndex = 0;
            foreach (KeyValuePair <TKey, TValue> kvp in this)
            {
                array[arrayIndex + currentIndex] = kvp;
                currentIndex++;
            }
        }
        /// <summary>
        /// Generates a new one time password from the supplied data.
        /// </summary>
        /// <param name="secretKey">The secret key to use in the HMAC</param>
        /// <param name="hmac">The hmac algorithm to use</param>
        /// <param name="dt">The date and time to generate a code for</param>
        /// <param name="offset">Any offsets that should be applied to the supplie date time</param>
        /// <param name="timeStep">The timestep value to use to calculate the current step</param>
        /// <param name="otpLength">The required legnth of the returned passcode</param>
        /// <returns>A one time password code</returns>
        /// <exception cref="System.ArgumentNullException">Thrown if hmac or secret key is null</exception>
        /// <exception cref="System.ArgumentException">Thrown if secret key is empty, optLength is
        /// not defined value or timeStep is less than 1 second.</exception>
        public static string Generate(byte[] secretKey, HMAC hmac, DateTime dt, TimeSpan offset, TimeSpan timeStep, OneTimePasswordLength otpLength)
        {
            #region Input validation

            Insist.IsNotNull(hmac, "hmac");
            Insist.IsNotNull(secretKey, "secretKey");
            Insist.IsNotEmpty(secretKey, "secretKey");
            Insist.IsDefined <OneTimePasswordLength>(otpLength, "optLength");
            Insist.IsAtLeast(timeStep.TotalSeconds, 1, "timeStep");

            #endregion

            dt = dt + offset;

            ulong stepNumber = (ulong)Math.Floor((double)dt.ToUnixTime() / (double)timeStep.TotalSeconds);

            return(HmacOneTimePassword.Generate(secretKey, stepNumber, hmac, otpLength));
        }
Ejemplo n.º 9
0
        /// <summary>
        ///  Returns the substring of the StringBuilder.
        /// </summary>
        /// <param name="str">The StringBuilder to get the substring of.</param>
        /// <param name="startIndex">The starting index of the substring.</param>
        /// <param name="length">The (optional) length of the sub string.</param>
        /// <returns>The characters making up the given sub string.</returns>
        public static string SubString(this StringBuilder str, int startIndex, int?length)
        {
            _logger.DebugMethodCalled(str, startIndex, length);

            #region Input Validation

            Insist.IsNotNull(str, "str");
            Insist.IsAtLeast(str.Length, 1, "str", "The substring operation is not valid on a zero length string.");
            Insist.IsAtLeast(startIndex, 0, "startIndex");

            //Calculate the end index
            int endIndex;

            if (length.HasValue)
            {
                endIndex = startIndex + length.Value - 1;
            }
            else
            {
                endIndex = (str.Length - 1);
            }

            if (length.HasValue && endIndex > (str.Length - 1))
            {
                throw new IndexOutOfRangeException("The end index must be a value less than or equal to the final index of the string builder.");
            }

            if (length.HasValue && endIndex < startIndex)
            {
                throw new ArgumentException("The end index must be greater than or equal to the start index.", "length");
            }

            #endregion

            //Get the sub string
            char[] chars = new char[(endIndex - startIndex) + 1];

            for (int index = startIndex; index <= endIndex; index++)
            {
                chars[index - startIndex] = str[index];
            }

            return(new String(chars));
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Construct a new bloom filter that tracks the specified number of
        /// elements with the desired error rate.
        /// </summary>
        /// <param name="expectedNumberOfElements">
        /// The number of items that this bloom filter is expected to track
        /// </param>
        /// <param name="errorRate">
        /// The desired error rate for generating false positives.
        /// </param>
        /// <exception cref="System.ArgumentException">
        /// Thrown if expectedNumberOfElements is less than 0, errorRate is less than 0 or
        /// errorRate is greater than 1.
        /// </exception>
        public BaseBloomFilter(int expectedNumberOfElements, double errorRate)
        {
            #region Input validation

            Insist.IsAtLeast(expectedNumberOfElements, 0, "expectedNumberOfElements");
            Insist.IsAtLeast(errorRate, 0, "errorRate");
            Insist.IsAtMost(errorRate, 1.0d, "errorRate");

            #endregion

            _expectedNumberOfElements = expectedNumberOfElements;
            _errorRate     = errorRate;
            _hashAlgorithm = new MurmurHash2();

            _numberOfBuckets = (int)Math.Ceiling(1.1d * Math.Abs((((double)_expectedNumberOfElements) * Math.Log(errorRate)) / (Math.Pow(Math.Log(2), 2))));
            _numberOfHashes  = (int)(Math.Ceiling(0.7d * Math.Abs((double)(_numberOfBuckets / _expectedNumberOfElements))));

            _bucketStorage = GetBucketStorage(_numberOfBuckets);
            _lock          = new ReaderWriterLockSlim();
        }
Ejemplo n.º 11
0
 public void IsAtLeast_Value_Within_Bounds_Does_Not_Throw_Exception()
 {
     Insist.IsAtLeast(10, 5, ARGUMENT_NAME);
 }
Ejemplo n.º 12
0
 public void IsAtLeast_Value_Out_Of_Bounds_Throws_Exception()
 {
     Insist.IsAtLeast(1, 5, ARGUMENT_NAME);
 }
Ejemplo n.º 13
0
        /// <summary>
        /// Wraps a string onto multiple lines using the supplied argument as the line length.
        /// Optionally respects any words so that a line is wrapped on any preceding whitespace for a word
        /// that would get split over multiple lines.
        /// </summary>
        /// <param name="str">
        /// The string to split
        /// </param>
        /// <param name="respectWords">
        /// Whether or not to respect words during wrapping. If true then a word will only be split
        /// if there is no preceding whitespace. If false then words will be split in half if they
        /// span a line boundary.
        /// </param>
        /// <param name="lineLength">
        /// The maximum length each line should be after wrapping
        /// </param>
        /// <returns>
        /// A string that has been wrapped to the supplied line length
        /// </returns>
        /// <exception cref="System.ArgumentException">
        /// Thrown if lineLength is less than or equal to 0
        /// </exception>
        public static string Wrap(this string str, int lineLength, bool respectWords)
        {
            _logger.DebugMethodCalled(str, lineLength, respectWords);

            #region Input validation

            Insist.IsAtLeast(lineLength, 1, "lineLength");

            #endregion

            #region Shortcuts

            if (string.IsNullOrEmpty(str))
            {
                return(str);
            }

            if (str.Length <= lineLength)
            {
                return(str);
            }

            #endregion

            StringBuilder builder       = new StringBuilder();
            int           startingIndex = 0;
            int           charsLeft     = str.Length;

            while (charsLeft > 0)
            {
                //Watch for the end of the string
                if (charsLeft <= lineLength)
                {
                    builder.Append(str.Substring(startingIndex));
                    charsLeft = 0;
                }
                else
                {
                    int adjustedWrapLength = lineLength;
                    if (respectWords)
                    {
                        while (adjustedWrapLength > 0)
                        {
                            if (str[startingIndex + adjustedWrapLength] == '\t' ||
                                str[startingIndex + adjustedWrapLength] == ' ')
                            {
                                //Readjust index so that when we do a substring
                                //further down we'll also grab the whitespace
                                //character.
                                adjustedWrapLength++;
                                break;
                            }
                            adjustedWrapLength--;
                        }

                        if (adjustedWrapLength == 0)
                        //Didnt find any whitespace, just split the
                        //line at the wrapLength position
                        {
                            adjustedWrapLength = lineLength;
                        }
                    }

                    builder.AppendLine(str.Substring(startingIndex, adjustedWrapLength));
                    startingIndex += adjustedWrapLength;
                    charsLeft      = str.Length - startingIndex;
                }
            }

            return(builder.ToString());
        }