Exemplo n.º 1
0
        public void AddAll(List <T> items)
        {
            var added = false;

            Snapshot();
            for (var i = 0; i < items.Count; i++)
            {
                var item = items[i];
                Insist.IsNotNull(item, "item cannot be null");
                added = selected.AddIfNotPresent(item);
            }

            if (added)
            {
                if (programmaticChangeEvents && FireChangeEvent())
                {
                    Revert();
                }
                else
                {
                    lastSelected = items.LastOrDefault();
                    Changed();
                }
            }

            Cleanup();
        }
Exemplo n.º 2
0
        /// <summary>
        /// Sets the selection to only the specified item
        /// </summary>
        /// <param name="item">Item.</param>
        public Selection <T> Set(T item)
        {
            Insist.IsNotNull(item, "item cannot be null.");

            if (selected.Count == 1 && selected.First() == item)
            {
                return(this);
            }

            Snapshot();
            selected.Clear();
            selected.Add(item);

            if (programmaticChangeEvents && FireChangeEvent())
            {
                Revert();
            }
            else
            {
                lastSelected = item;
                Changed();
            }

            Cleanup();
            return(this);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Jon Skeet's excellent reimplementation of LINQ Count.
        /// </summary>
        /// <typeparam name="TSource">The source type.</typeparam>
        /// <param name="source">The source IEnumerable.</param>
        /// <returns>The number of items in the source.</returns>
        public static int Count <TSource>(this IEnumerable <TSource> source)
        {
            Insist.IsNotNull(source, "source cannot be null");

            // Optimization for ICollection<T>
            var genericCollection = source as ICollection <TSource>;

            if (genericCollection != null)
            {
                return(genericCollection.Count);
            }

            // Optimization for ICollection
            var nonGenericCollection = source as ICollection;

            if (nonGenericCollection != null)
            {
                return(nonGenericCollection.Count);
            }

            // Do it the slow way - and make sure we overflow appropriately
            checked
            {
                int count = 0;
                using (var iterator = source.GetEnumerator())
                {
                    while (iterator.MoveNext())
                    {
                        count++;
                    }
                }
                return(count);
            }
        }
Exemplo n.º 4
0
        public override TaskStatus Update(T context)
        {
            Insist.IsNotNull(Child, "child must not be null");

            // early out if we are done. we check here and after running just in case the count is 0
            if (!RepeatForever && _iterationCount == Count)
            {
                return(TaskStatus.Success);
            }

            var status = Child.Tick(context);

            _iterationCount++;

            if (EndOnFailure && status == TaskStatus.Failure)
            {
                return(TaskStatus.Success);
            }

            if (!RepeatForever && _iterationCount == Count)
            {
                return(TaskStatus.Success);
            }

            return(TaskStatus.Running);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Removes the specified data from the counting bloom filter.
        /// </summary>
        /// <param name="data">The data to remove from this counting bloom filter.</param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown if data is null.
        /// </exception>
        /// <exception cref="System.ArgumentException">
        /// Thrownf if data is empty.
        /// </exception>
        public void Remove(byte[] data)
        {
            #region Input validation

            Insist.IsNotNull(data, "data");
            Insist.IsNotEmpty(data, "data");

            #endregion

            int[] computedIndeces = GetIndeces(data);

            _lock.EnterWriteLock();
            try
            {
                foreach (int index in computedIndeces)
                {
                    if (_bucketStorage[index] > 0)
                    {
                        _bucketStorage[index]--;
                    }
                }
            }
            finally
            {
                _lock.ExitWriteLock();
            }
        }
Exemplo n.º 6
0
 public ListBox <T> SetStyle(ListBoxStyle style)
 {
     Insist.IsNotNull(style, "style cannot be null");
     _style = style;
     InvalidateHierarchy();
     return(this);
 }
Exemplo n.º 7
0
        /// <summary>
        /// Checks to see if the supplied data has been added to this filter.
        /// </summary>
        /// <param name="data">
        /// The data to check for presence in the filter.
        /// </param>
        /// <returns>
        /// True if the item *might* have been added to the filter. False if it
        /// definitely has not.
        /// </returns>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown if data is null.
        /// </exception>
        /// <exception cref="System.ArgumentException">
        /// Thrownf if data is empty.
        /// </exception>
        public bool IsPresent(byte[] data)
        {
            #region Input validation

            Insist.IsNotNull(data, "data");
            Insist.IsNotEmpty(data, "data");

            #endregion

            int[] computedIndeces = GetIndeces(data);

            _lock.EnterReadLock();
            try
            {
                foreach (int index in computedIndeces)
                {
                    if (IsBucketInUse(index) == false)
                    {
                        return(false);
                    }
                }
            }
            finally
            {
                _lock.ExitReadLock();
            }

            return(true);
        }
Exemplo n.º 8
0
        private static List <Move> GenerateMovesWithoutCheck(Cell cell)
        {
            Insist.IsNotNull(cell);
            Insist.IsNotNull(cell.piece);
            var moves = new List <Move>();                      // Rename

            // For each type of movement defined for the piece in this cell
            foreach (MoveDefinition moveDef in cell.piece.type.moveSet.moves)
            {
                if (GameBoard.Instance.Layout == BoardLayout.DefaultLayout || GameBoard.Instance.Layout == BoardLayout.FlippedDefaultLayout)
                {
                    moves.AddRange(GetCastlingMoves(cell));

                    if (cell.piece.type != PieceType.Pawn)
                    {
                        moves.AddRange(GetEnPassentMoves(cell));
                    }
                }

                if (moveDef is LeaperMoveDefinition)
                {
                    moves.AddRange(AddLeaperMoves(moveDef, cell, (moveDef as LeaperMoveDefinition).leapDistance, moves));
                    continue;
                }

                moves.AddRange(AddBasicMoves(cell, moveDef));
            }

            return(moves);
        }
Exemplo n.º 9
0
        public void RemoveAll(List <T> items)
        {
            var removed = false;

            Snapshot();
            for (var i = 0; i < items.Count; i++)
            {
                var item = items[i];
                Insist.IsNotNull(item, "item cannot be null");
                removed = selected.Remove(item);
            }

            if (removed)
            {
                if (programmaticChangeEvents && FireChangeEvent())
                {
                    Revert();
                }
                else
                {
                    lastSelected = null;
                    Changed();
                }
            }

            Cleanup();
        }
Exemplo n.º 10
0
        public Selection <T> SetAll(List <T> items)
        {
            var added = false;

            Snapshot();
            lastSelected = null;
            selected.Clear();
            for (var i = 0; i < items.Count; i++)
            {
                var item = items[i];
                Insist.IsNotNull(item, "item cannot be null");
                added = selected.AddIfNotPresent(item);
            }

            if (added)
            {
                if (programmaticChangeEvents && FireChangeEvent())
                {
                    Revert();
                }
                else if (items.Count > 0)
                {
                    lastSelected = items.Last();
                    Changed();
                }
            }

            Cleanup();
            return(this);
        }
        public static void Sort <TKey, TValue>(this IDictionary <TKey, TValue> collection, Comparison <KeyValuePair <TKey, TValue> > comparison)
        {
            _logger.DebugMethodCalled(collection, comparison);

            #region Input Validation

            Insist.IsNotNull(collection, "collection");

            #endregion

            List <KeyValuePair <TKey, TValue> > sortedItems = new List <KeyValuePair <TKey, TValue> >();

            foreach (KeyValuePair <TKey, TValue> pair in collection)
            {
                sortedItems.Add(pair);
            }

            sortedItems.Sort(comparison);

            collection.Clear();

            foreach (KeyValuePair <TKey, TValue> pair in sortedItems)
            {
                collection.Add(pair.Key, pair.Value);
            }
        }
        public static IList <T> FromIndexes <T>(this IList <T> list, IndexOutOfRangeBehaviour outOfRange, params int[] indexes)
        {
            #region Input validation

            Insist.IsNotNull(list, "list");
            Insist.IsNotNull(indexes, "indexes");
            Insist.IsDefined(outOfRange, "outOfRange");

            #endregion

            List <T> items = new List <T>();

            if (list.Count == 0)
            {
                return(items);
            }

            foreach (int index in indexes)
            {
                if (index >= list.Count)
                //Out of bounds
                {
                    if (outOfRange == IndexOutOfRangeBehaviour.Ignore)
                    {
                        continue;
                    }
                }

                items.Add(list[index]);
            }

            return(items);
        }
        /// <summary>
        /// Serilialize the supplied object to the supplied stream.
        /// </summary>
        /// <param name="obj">
        /// The object to serialize
        /// </param>
        /// <param name="stream">
        /// The stream to write the serialized object to. This stream will remain unaffected if the
        /// object is null.  The stream must be open and writable before calling this method.
        /// </param>
        public void Serialize(object obj, Stream stream)
        {
            _logger.DebugMethodCalled(obj, stream);

            #region Input Validation

            if (obj == null)
            //Just do nothing for null objects,  we don't want to throw
            //an exception because it will force more null checking in calling code.
            {
                return;
            }

            Insist.IsNotNull(stream, "stream");

            if (!stream.CanWrite)
            {
                throw new ArgumentException("Cannot write to stream", "stream");
            }

            #endregion

            //Delegate the actual serialization to a child class.
            OnSerialize(obj, stream);
        }
Exemplo n.º 14
0
        public bool Contains(T node)
        {
            Insist.IsNotNull(node, "node cannot be null");
            Insist.IsFalse(node.QueueIndex < 0 || node.QueueIndex >= _nodes.Length, "node.QueueIndex has been corrupted. Did you change it manually? Or add this node to another queue?");

            return(_nodes[node.QueueIndex] == node);
        }
        /// <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);
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// Selects or deselects the specified item based on how the selection is configured, whether ctrl is currently pressed, etc.
        /// This is typically invoked by user interaction.
        /// </summary>
        /// <param name="item">Item.</param>
        public virtual void Choose(T item)
        {
            Insist.IsNotNull(item, "item cannot be null");
            if (_isDisabled)
            {
                return;
            }

            Snapshot();

            try
            {
                if ((toggle || (!required && selected.Count == 1) || InputUtils.IsControlDown()) &&
                    selected.Contains(item))
                {
                    if (required && selected.Count == 1)
                    {
                        return;
                    }

                    selected.Remove(item);
                    lastSelected = null;
                }
                else
                {
                    bool modified = false;
                    if (!multiple || (!toggle && !InputUtils.IsControlDown()))
                    {
                        if (selected.Count == 1 && selected.Contains(item))
                        {
                            return;
                        }

                        modified = selected.Count > 0;
                        selected.Clear();
                    }

                    if (!selected.AddIfNotPresent(item) && !modified)
                    {
                        return;
                    }

                    lastSelected = item;
                }

                if (FireChangeEvent())
                {
                    Revert();
                }
                else
                {
                    Changed();
                }
            }
            finally
            {
                Cleanup();
            }
        }
Exemplo n.º 17
0
 public ScrollPane(Element widget, ScrollPaneStyle style)
 {
     Insist.IsNotNull(style, "style cannot be null");
     transform = true;
     _style    = style;
     SetWidget(widget);
     SetSize(150, 150);
 }
Exemplo n.º 18
0
        public ScrollPane SetStyle(ScrollPaneStyle style)
        {
            Insist.IsNotNull(style, "style cannot be null");
            _style = style;
            InvalidateHierarchy();

            return(this);
        }
Exemplo n.º 19
0
        public void UpdatePriority(T node, int priority)
        {
            Insist.IsNotNull(node, "node cannot be null");
            Insist.IsFalse(Contains(node), "Cannot call UpdatePriority() on a node which is not enqueued: " + node);

            node.Priority = priority;
            OnNodeUpdated(node);
        }
Exemplo n.º 20
0
 public void IsNotNull_2_Thrown_Exception_Has_Correct_Argument_Name()
 {
     try {
         Insist.IsNotNull(null, ARGUMENT_NAME);
     } catch (ArgumentNullException e) {
         Assert.AreEqual(ARGUMENT_NAME, e.ParamName);
     }
 }
        /// <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());
        }
        /// <summary>
        /// An extension method to raise an event that includes the null check.
        /// </summary>
        /// <typeparam name="T">
        /// The eventArgs type
        /// </typeparam>
        /// <param name="theEvent">
        /// The event handler to invoke
        /// </param>
        /// <param name="sender">
        /// The sender object
        /// </param>
        /// <param name="args">
        /// The event arguments
        /// </param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown if sender is null
        /// </exception>
        public static void Raise <T>(this EventHandler <T> theEvent, object sender, T args) where T : EventArgs
        {
            Insist.IsNotNull(sender, "sender");

            if (theEvent != null)
            {
                theEvent(sender, args);
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// Create new scope instace around the underlying value
        /// </summary>
        protected Scope(T value)
        {
            #region Input validation

            Insist.IsNotNull(value, "value");

            #endregion

            _value = value;
        }
Exemplo n.º 24
0
        /// <summary>
        /// Collates all Right values from a set of eithers
        /// </summary>
        /// <param name="eithers">
        /// The set of eithers from which to obtain the left values
        /// </param>
        /// <returns>
        /// All the left values from the supplied set of eithers
        /// </returns>
        public static IEnumerable <TRight> Rights <TLeft, TRight>(IEnumerable <Either <TLeft, TRight> > eithers)
        {
            #region Input validation

            Insist.IsNotNull(eithers, "eithers");

            #endregion

            return(eithers.Where(e => e.HasRight).Select(e => e.RightValue));
        }
        /// <summary>
        /// Creates a new instance
        /// </summary>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown if comparison is null.
        /// </exception>
        public GenericEqualityComparer(Func <T, T, bool> comparison)
        {
            #region Input Validation

            Insist.IsNotNull(comparison, "comparison");

            #endregion

            _comparison = comparison;
        }
Exemplo n.º 26
0
 public void IsNotNull_2_Thrown_Exception_Has_Correct_Message()
 {
     try
     {
         Insist.IsNotNull(null, ARGUMENT_NAME, MESSAGE);
     }
     catch (ArgumentNullException e)
     {
         Assert.IsTrue(e.Message.Contains(MESSAGE));
     }
 }
Exemplo n.º 27
0
        /// <summary>
        /// Create a disposer to provide onEnter and onExit functionality.
        /// </summary>
        /// <param name="onEnter"></param>
        /// <param name="onExit"></param>
        /// <returns></returns>
        protected Disposer <T> Create(Action <T> onEnter, Action <T> onExit)
        {
            #region Input validation

            Insist.IsNotNull(onEnter, "onEnter");
            Insist.IsNotNull(onExit, "onExit");

            #endregion

            return(Disposer <T> .Create(_value, onEnter, onExit));
        }
Exemplo n.º 28
0
        /// <summary>
        /// Hashes a string using the supplied encoding and the supplied hashing algorithm
        /// </summary>
        /// <param name="str">
        /// The string to compute the hash for
        /// </param>
        /// <param name="hashAlgorithm">
        /// The hashing algorithm to use to perform the hash.
        /// </param>
        /// <param name="encoding">
        /// The encoding used to encode the string into a byte[]
        /// </param>
        /// <returns>
        /// A string representing the hash of the original input string.
        /// </returns>
        /// <exception cref="ArgumentException">
        /// Thrown if str is null or empty.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        /// Thrown if hashAlgorithm is null or encoding is null.
        /// </exception>
        public static string Hash(this string str, HashAlgorithm hashAlgorithm, Encoding encoding)
        {
            _logger.DebugMethodCalled(str, hashAlgorithm, encoding);

            Insist.IsNotNullOrEmpty(str, "str");
            Insist.IsNotNull(hashAlgorithm, "hashAlgorithm");
            Insist.IsNotNull(encoding, "encoding");

            byte[] strBytes = encoding.GetBytes(str);
            byte[] hashed   = hashAlgorithm.ComputeHash(strBytes, 0, strBytes.Length);
            return(BitConverter.ToString(hashed).Replace("-", ""));
        }
Exemplo n.º 29
0
        /// <summary>
        /// Sets the minWidth, prefWidth, maxWidth, minHeight, prefHeight, and maxHeight to the specified value.
        /// </summary>
        /// <param name="size">Size.</param>
        public Cell Size(Value size)
        {
            Insist.IsNotNull(size, "size cannot be null.");

            minWidth   = size;
            minHeight  = size;
            prefWidth  = size;
            prefHeight = size;
            maxWidth   = size;
            maxHeight  = size;
            return(this);
        }
        /// <summary>
        ///  Returns a flag indicating whether the given item in a collection is of integral type.
        /// </summary>
        /// <param name="collection">The collection to look in.</param>
        /// <param name="key">The key to look at.</param>
        /// <returns>True if the value is integral; false otherwise.</returns>
        public static bool IsInteger <TKey>(this IDictionary <TKey, String> collection, TKey key)
        {
            _logger.DebugMethodCalled(collection, key);

            #region Input Validation

            Insist.IsNotNull(collection, "collection");

            #endregion

            return(RegexHelper.IsInteger(collection[key]));
        }