//-------------------------------------------------------------------------
        /// <summary>
        /// Returns a full-text search-ready string with most punctuation and
        /// the words and phrases listed in the module settings removed.
        /// </summary>
        internal static string RemoveNameSearchNoiseTerms(
            string facilityNameSearchTerms,
            IEnumerable <string> nameSearchNoiseTerms)
        {
            Precondition.IsNotNull <string>(
                facilityNameSearchTerms, "facilityNameSearchTerms");

            List <string> noiseWords =
                new List <string>(nameSearchNoiseTerms);

            List <string> cleanTerms = new List <string>();

            string[] terms = StringX.SplitOnWhitespace(
                facilityNameSearchTerms.ToLower());

            foreach (string term in terms)
            {
                string cleanTerm =
                    InvalidSearchTermPattern.Replace(term, String.Empty);

                if ((cleanTerm.Length > 0) &&
                    !cleanTerms.Contains(cleanTerm) &&
                    !noiseWords.Contains(cleanTerm))
                {
                    cleanTerms.Add(cleanTerm);
                }
            }

            return(String.Join(" ", cleanTerms.ToArray()));
        }
        //-------------------------------------------------------------------------
        private static IntSet <PartyId> SearchByName(
            Timer t,
            AddressParserResult apr,
            IEnumerable <string> noiseWords)
        {
            Precondition.IsNotNull(apr, "apr");

            // this is not used becasue now name search can happen even with SearchType=postcode,city,zip etc.

            //if (Snap.Data.Controller.SearchType.PartyName != apr.Type) {
            //    throw new ArgumentException("apr.Type must be PartyName");
            //}

            string searchTerms =
                Snap.Util.StringX.CollapseWhitespace(
                    RemoveNameSearchNoiseTerms(apr.PartyName, noiseWords));

            IntSet <PartyId> partiesByName = null;

            t.Measure("Search by Name", delegate() {
                //partiesByName = Snap.Cache.Cache.PartyName(searchTerms);
                partiesByName = new Snap.Data.LuceneController().LuceneSearchIds(searchTerms, Snap.ForSeniors.Constants.SnapPartyLuceneTableName, Snap.ForSeniors.Constants.SnapPartyLuceneSearchField, Snap.ForSeniors.Constants.SnapPartyLuceneResultField);
            });
            if (partiesByName.Count == 0)
            {
                throw new InvalidPartyNameException(apr.PartyName);
            }

            return(partiesByName);
        }
예제 #3
0
        /// <summary>
        /// Indicates whether the instance is greater as the reference value.
        /// </summary>
        /// <param name="value">The instance to test.</param>
        /// <param name="referenceValue">The reference value to test.</param>
        /// <returns><strong>true</strong> if the instance is greater as the reference value;
        /// otherwise, <strong>false</strong>.</returns>
        /// <exception cref="ArgumentNullException"><em>value</em> or <em>referenceValue</em> is
        /// <strong>null</strong>.</exception>
        public static bool IsGreater(this IComparable value, IComparable referenceValue)
        {
            Precondition.IsNotNull(value, nameof(value));
            Precondition.IsNotNull(referenceValue, nameof(referenceValue));

            return(value.CompareTo(referenceValue) > 0);
        }
예제 #4
0
파일: Room.cs 프로젝트: v-karpov/Parquet
        /// <summary>
        /// Initializes a new instance of the <see cref="Room"/> class.
        /// </summary>
        /// <param name="in_walkableArea">
        /// The <see cref="Space"/>s on which a <see cref="Characters.Being"/>
        /// may walk within this <see cref="Room"/>.
        /// </param>
        /// <param name="in_perimeter">
        /// The <see cref="Space"/>s whose <see cref="Block"/>s and <see cref="Furnishing"/>s
        /// define the limits of this <see cref="Room"/>.
        /// </param>
        public Room(HashSet <Space> in_walkableArea, HashSet <Space> in_perimeter)
        {
            Precondition.IsNotNull(in_walkableArea, nameof(in_walkableArea));
            Precondition.IsNotNull(in_perimeter, nameof(in_perimeter));

            if (in_walkableArea.Count < All.Recipes.Rooms.MinWalkableSpaces ||
                in_walkableArea.Count > All.Recipes.Rooms.MaxWalkableSpaces)
            {
                throw new IndexOutOfRangeException(nameof(in_walkableArea));
            }

            var minimumPossiblePerimeterLength = 2 * in_walkableArea.Count + 2;

            if (in_perimeter.Count < minimumPossiblePerimeterLength)
            {
                throw new IndexOutOfRangeException($"{nameof(in_perimeter)} is too small to surround {nameof(in_walkableArea)}.");
            }

            if (!in_walkableArea.Concat(in_perimeter).Any(space
                                                          => All.Parquets.Get <Furnishing>(space.Content.Furnishing)?.IsEntry ?? false))
            {
                throw new ArgumentException($"No entry/exit found in {nameof(in_walkableArea)} or {nameof(in_perimeter)}.");
            }

            WalkableArea = in_walkableArea;
            Perimeter    = in_perimeter;
        }
예제 #5
0
        /// <summary>
        /// Indicates whether the string is an base-64 encoded string.
        /// </summary>
        /// <param name="str">A string to test.</param>
        /// <returns><strong>true</strong> if the <em>str</em> parameter is an base-64 encoded
        /// string; otherwise, <strong>false</strong>.</returns>
        /// <exception cref="ArgumentNullException"><em>str</em> is <strong>null</strong>.</exception>
        /// <remarks>This method is based on an example from
        /// <a href="http://stackoverflow.com/questions/6309379/how-to-check-for-a-valid-base-64-encoded-string-in-c-sharp" target="_blank">StackOverflow</a>.</remarks>
        public static bool IsBase64(this string str)
        {
            Precondition.IsNotNull(str, nameof(str));

            str = str.Trim();
            return((str.Length % 4 == 0) && Regex.IsMatch(str, @"^[a-zA-Z0-9\+/]*={0,3}$", RegexOptions.None));
        }
예제 #6
0
        /// <summary>
        /// Converts the string representation of a logical value to its Boolean equivalent.
        /// </summary>
        /// <param name="str">A string containing a boolean to convert.</param>
        /// <returns><strong>true</strong> if <em>str</em> is a representation of a <em>true</em>
        /// Boolean value,
        /// or <strong>false</strong> if <em>str</em> is a representation of a <em>false</em>
        /// Boolean value.</returns>
        /// <exception cref="ArgumentNullException"><em>str</em> is
        /// <strong>null</strong>.</exception>
        /// <exception cref="FormatException"><em>str</em> is not a representation of a Boolean
        /// value.</exception>
        public static bool ToBoolean(this string str)
        {
            Precondition.IsNotNull(str, nameof(str));

            bool result;

            switch (str.ToLower())
            {
            case "0":
            case "no":
            case "false":
                result = false;
                break;

            case "1":
            case "yes":
            case "true":
                result = true;
                break;

            default:
                result = Convert.ToBoolean(str);
                break;
            }

            return(result);
        }
예제 #7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GameObjectCollection{T}"/> class.
        /// </summary>
        /// <param name="in_bounds">The bounds within which the collected <see cref="GameObjectID"/>s are defined.</param>
        /// <param name="in_entities">The <see cref="GameObject"/>s to collect.  Cannot be null.</param>
        public GameObjectCollection(List <Range <GameObjectID> > in_bounds, IEnumerable <GameObject> in_entities)
        {
            Precondition.IsNotNull(in_entities, nameof(in_entities));

            var baseDictionary = new Dictionary <GameObjectID, GameObject> {
                { GameObjectID.None, null }
            };

            foreach (var entity in in_entities)
            {
                Precondition.IsInRange(entity.ID, in_bounds, nameof(in_entities));

                if (!baseDictionary.ContainsKey(entity.ID))
                {
                    baseDictionary[entity.ID] = entity;
                }
                else
                {
                    throw new InvalidOperationException($"Tried to duplicate entity ID {entity.ID}.");
                }
            }

            Bounds   = in_bounds;
            Entities = baseDictionary;
        }
예제 #8
0
        /// <summary>
        /// Indicates whether the instance is less or equal to the reference value.
        /// </summary>
        /// <param name="value">The instance to test.</param>
        /// <param name="referenceValue">The reference value to test.</param>
        /// <returns><strong>true</strong> if the instance is less or equal to the reference
        /// value; otherwise, <strong>false</strong>.</returns>
        /// <exception cref="ArgumentNullException"><em>value</em> or <em>referenceValue</em> is
        /// <strong>null</strong>.</exception>
        public static bool IsLessOrEqual(this IComparable value, IComparable referenceValue)
        {
            Precondition.IsNotNull(value, nameof(value));
            Precondition.IsNotNull(referenceValue, nameof(referenceValue));

            return(value.IsLess(referenceValue) || value.IsEqual(referenceValue));
        }
예제 #9
0
        /// <summary>
        /// Indicates whether the instance is between a minimum and maximum value.
        /// </summary>
        /// <param name="value">The instance to test.</param>
        /// <param name="min">The minimum value to test.</param>
        /// <param name="max">The maximum value to test.</param>
        /// <returns><strong>true</strong> if the instance is between the minimum and maximum
        /// value; otherwise, <strong>false</strong>.</returns>
        /// <exception cref="ArgumentNullException"><em>value</em>, <em>min</em> or <em>max</em> is
        /// <strong>null</strong>.</exception>
        public static bool IsBetween(this IComparable value, IComparable min, IComparable max)
        {
            Precondition.IsNotNull(value, nameof(value));
            Precondition.IsNotNull(min, nameof(min));
            Precondition.IsNotNull(max, nameof(max));

            return(value.IsGreaterOrEqual(min) && value.IsLessOrEqual(max));
        }
예제 #10
0
        /// <summary>
        /// Converts an string to its equivalent string representation that is encoded with base-64
        /// digits.
        /// </summary>
        /// <param name="str">A string to convert.</param>
        /// <param name="encoding">Represents the string character encoding.</param>
        /// <returns>The string representation, in base 64, of the contents of
        /// <em>str</em>.</returns>
        /// <exception cref="ArgumentNullException"><em>str</em> or <em>encoding</em> is
        /// <strong>null</strong>.</exception>
        public static string Base64Encode(this string str, Encoding encoding)
        {
            Precondition.IsNotNull(str, nameof(str));
            Precondition.IsNotNull(encoding, nameof(encoding));

            byte[] bytes = encoding.GetBytes(str);
            return(Convert.ToBase64String(bytes));
        }
예제 #11
0
        /// <summary>
        /// Creates an instance of a list designated by the specified type parameter, using the
        /// parameterless constructor.
        /// </summary>
        /// <param name="type">The type of list object to create.</param>
        /// <returns>A reference to the newly created list.</returns>
        public static IList CreateListInstance(Type type)
        {
            Precondition.IsNotNull(type, nameof(type));

            Type listType = typeof(List <>).MakeGenericType(type);

            return((IList)Activator.CreateInstance(listType));
        }
예제 #12
0
        public void IsNullTest()
        {
            var testValue = "will pass";

            var exception = Record.Exception(() => Precondition.IsNotNull(testValue));

            Assert.Null(exception);
        }
예제 #13
0
        /// <summary>
        /// Creates an instance of a dictionary designated by the specified key and value type
        /// parameters, using the parameterless constructor.
        /// </summary>
        /// <param name="keyType">The type of dictionary key to create.</param>
        /// <param name="valueType">The type of dictionary value to create.</param>
        /// <returns>A reference to the newly created dictionary.</returns>
        public static IDictionary CreateDictionaryInstance(Type keyType, Type valueType)
        {
            Precondition.IsNotNull(keyType, nameof(keyType));
            Precondition.IsNotNull(valueType, nameof(valueType));

            Type dictionaryType = typeof(Dictionary <,>).MakeGenericType(keyType, valueType);

            return((IDictionary)Activator.CreateInstance(dictionaryType));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="CompressionBase"/> class.
        /// </summary>
        /// <param name="fileSystem">The file system.</param>
        /// <param name="environment">The environment.</param>
        /// <param name="log">The log.</param>
        protected CompressionBase(IFileSystem fileSystem, ICakeEnvironment environment, ICakeLog log)
        {
            Precondition.IsNotNull(fileSystem, nameof(fileSystem));
            Precondition.IsNotNull(environment, nameof(environment));
            Precondition.IsNotNull(log, nameof(log));

            this.fileSystem  = fileSystem;
            this.environment = environment;
            this.log         = log;
            this.comparison  = environment.Platform.IsUnix() ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase;
        }
예제 #15
0
        /// <summary>
        /// Assign an ordering to over the set of search results (e.g.,
        /// alphabetic, distance).
        /// </summary>
        public void OrderBy(Comparison <Result> comparison)
        {
            Precondition.IsNotNull(comparison, "comparison");

            if (null == mOrdering)
            {
                mOrdering = new Result[mPartyIdToResult.Count];
                mPartyIdToResult.Values.CopyTo(mOrdering, 0);
            }

            Array.Sort(mOrdering, comparison);
        }
예제 #16
0
        /// <summary>
        /// Create a Zip archive of the specified files.
        /// </summary>
        /// <param name="rootPath">The root path.</param>
        /// <param name="outputPath">The output path.</param>
        /// <param name="filePaths">The file paths.</param>
        /// <param name="level">The compression level (1-9).</param>
        public override void Compress(DirectoryPath rootPath, FilePath outputPath, IEnumerable <FilePath> filePaths, int level)
        {
            Precondition.IsNotNull(rootPath, nameof(rootPath));
            Precondition.IsNotNull(outputPath, nameof(outputPath));
            Precondition.IsNotNull(filePaths, nameof(filePaths));
            Precondition.IsBetween(level, 1, 9, nameof(level));

            // Make root path and output file path absolute.
            rootPath   = rootPath.MakeAbsolute(environment);
            outputPath = outputPath.MakeAbsolute(environment);

            // Get the output file.
            var outputFile = fileSystem.GetFile(outputPath);

            // Open up a stream to the output file.
            log.Verbose("Creating Zip file: {0}", outputPath.FullPath);

            using (var outputStream = outputFile.Open(FileMode.Create, FileAccess.Write, FileShare.None))
                using (var zipOutputStream = new ZipOutputStream(outputStream))
                {
                    zipOutputStream.SetLevel(level);

                    foreach (var inputPath in filePaths)
                    {
                        var absoluteInputPath = inputPath.MakeAbsolute(environment);
                        var file = fileSystem.GetFile(absoluteInputPath);

                        using (var inputStream = file.Open(FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            // Get the relative filename to the rootPath.
                            var relativeFilePath = GetRelativeFilePath(rootPath, absoluteInputPath);
                            log.Verbose("Compressing file {0}", absoluteInputPath);

                            string entryName = relativeFilePath.FullPath;
                            entryName = ZipEntry.CleanName(entryName);

                            // Create the tar archive entry.
                            ZipEntry entry = new ZipEntry(entryName)
                            {
                                DateTime = File.GetLastWriteTime(absoluteInputPath.FullPath),
                                Size     = inputStream.Length
                            };

                            zipOutputStream.PutNextEntry(entry);
                            inputStream.CopyTo(zipOutputStream);
                            zipOutputStream.CloseEntry();
                        }
                    }
                }

            log.Verbose("Zip file successfully created: {0}", outputPath.FullPath);
        }
예제 #17
0
        // Called from single-threaded context
        public void AssignWork(ThreadedWork workToDo)
        {
            Precondition.IsNotNull(workToDo);

            if (!mIsWorking)
            {
                mIsWorking      = true;
                mActiveWorkItem = workToDo;

                // Start work processing
                mSignal.Set();
            }
        }
예제 #18
0
파일: All.cs 프로젝트: v-karpov/Parquet
        /// <summary>
        /// Initializes the <see cref="GameObjectCollection{T}s"/> from the given collections.
        /// </summary>
        /// <param name="in_parquets">All parquets to be used in the game.</param>
        /// <remarks>This initialization routine may be called only once per library execution.</remarks>
        /// <exception cref="InvalidOperationException">When called more than once.</exception>
        // TODO Make an version that takes serialized strings instead of ienumerables.
        public static void InitializeCollections(IEnumerable <ParquetParent> in_parquets)
        {
            if (_collectionsHaveBeenInitialized)
            {
                throw new InvalidOperationException($"Attempted to reinitialize {typeof(All)}.");
            }
            Precondition.IsNotNull(in_parquets, nameof(in_parquets));

            // TODO Uncomment these once we have CSV import implemented for non-parquets.
            //Beings = new EntityCollection<Being>(BeingIDs);
            //CraftingRecipes = new EntityCollection(CraftingRecipeIDs);
            //Items = new EntityCollection(ItemIDs);
            Parquets = new GameObjectCollection <ParquetParent>(ParquetIDs, in_parquets);
            //RoomRecipes = new EntityCollection(RoomRecipeIDs);

            _collectionsHaveBeenInitialized = true;
        }
예제 #19
0
        public BeingStatus(Being in_beingDefinition, Behavior in_currentBehavior,
                           Location in_position, Location in_spawnAt,
                           int in_biomeTimeRemaining,
                           float in_buildingSpeed, float in_modificationSpeed,
                           float in_gatheringSpeed, float in_movementSpeed,
                           List <GameObjectID> in_knownCritters        = null, List <GameObjectID> in_knownNPCs        = null,
                           List <GameObjectID> in_knownParquets        = null, List <GameObjectID> in_knownRoomRecipes = null,
                           List <GameObjectID> in_knownCraftingRecipes = null, List <GameObjectID> in_quests           = null,
                           List <GameObjectID> in_inventory            = null)
        {
            Precondition.IsNotNull(in_beingDefinition, nameof(in_beingDefinition));
            var nonNullCritters        = in_knownCritters ?? Enumerable.Empty <GameObjectID>().ToList();
            var nonNullNPCs            = in_knownNPCs ?? Enumerable.Empty <GameObjectID>().ToList();
            var nonNullParquets        = in_knownParquets ?? Enumerable.Empty <GameObjectID>().ToList();
            var nonNullRoomRecipes     = in_knownRoomRecipes ?? Enumerable.Empty <GameObjectID>().ToList();
            var nonNullCraftingRecipes = in_knownCraftingRecipes ?? Enumerable.Empty <GameObjectID>().ToList();
            var nonNullQuests          = in_quests ?? Enumerable.Empty <GameObjectID>().ToList();
            var nonNullInventory       = in_inventory ?? Enumerable.Empty <GameObjectID>().ToList();

            Precondition.AreInRange(nonNullCritters, All.CritterIDs, nameof(in_knownCritters));
            Precondition.AreInRange(nonNullNPCs, All.NpcIDs, nameof(in_knownNPCs));
            Precondition.AreInRange(nonNullParquets, All.ParquetIDs, nameof(in_knownParquets));
            Precondition.AreInRange(nonNullRoomRecipes, All.RoomRecipeIDs, nameof(in_knownRoomRecipes));
            Precondition.AreInRange(nonNullCraftingRecipes, All.CraftingRecipeIDs, nameof(in_knownCraftingRecipes));
            Precondition.AreInRange(nonNullQuests, All.QuestIDs, nameof(in_quests));
            Precondition.AreInRange(nonNullInventory, All.ItemIDs, nameof(in_inventory));

            BeingDefinition      = in_beingDefinition;
            CurrentBehavior      = in_currentBehavior;
            Position             = in_position;
            SpawnAt              = in_spawnAt;
            BiomeTimeRemaining   = in_biomeTimeRemaining;
            BuildingSpeed        = in_buildingSpeed;
            ModificationSpeed    = in_modificationSpeed;
            GatheringSpeed       = in_gatheringSpeed;
            MovementSpeed        = in_movementSpeed;
            KnownCritters        = nonNullCritters;
            KnownNPCs            = nonNullNPCs;
            KnownParquets        = nonNullParquets;
            KnownRoomRecipes     = nonNullRoomRecipes;
            KnownCraftingRecipes = nonNullCraftingRecipes;
            Quests    = nonNullQuests;
            Inventory = nonNullInventory;
        }
예제 #20
0
        /// <summary>
        /// Uncompress the specified Zip file.
        /// </summary>
        /// <param name="filePath">Zip file to uncompress.</param>
        /// <param name="outputPath">Output path to uncompress into.</param>
        public override void Uncompress(FilePath filePath, DirectoryPath outputPath)
        {
            Precondition.IsNotNull(filePath, nameof(filePath));
            Precondition.IsNotNull(outputPath, nameof(outputPath));

            // Make root path and output file path absolute.
            filePath   = filePath.MakeAbsolute(environment);
            outputPath = outputPath.MakeAbsolute(environment);

            var file = fileSystem.GetFile(filePath);

            log.Verbose("Uncompress Zip file {0} to {1}", filePath.FullPath, outputPath.FullPath);

            using (Stream inputStream = file.Open(FileMode.Open, FileAccess.Read, FileShare.Read))
                using (ZipFile zipFile = new ZipFile(inputStream))
                {
                    foreach (ZipEntry zipEntry in zipFile)
                    {
                        if (!zipEntry.IsFile)
                        {
                            continue;                     // Ignore directories
                        }

                        string entryFileName = zipEntry.Name;

                        byte[] buffer    = new byte[4096];              // 4K is optimum
                        Stream zipStream = zipFile.GetInputStream(zipEntry);

                        string fullZipToPath = System.IO.Path.Combine(outputPath.FullPath, entryFileName);
                        string directoryName = System.IO.Path.GetDirectoryName(fullZipToPath);

                        if (directoryName.Length > 0)
                        {
                            Directory.CreateDirectory(directoryName);
                        }

                        using (FileStream streamWriter = File.Create(fullZipToPath))
                        {
                            StreamUtils.Copy(zipStream, streamWriter, buffer);
                        }
                    }
                }
        }
예제 #21
0
        /// <summary>
        /// Create a BZip2 Tar archive of the specified files.
        /// </summary>
        /// <param name="rootPath">The root path.</param>
        /// <param name="outputPath">The output path.</param>
        /// <param name="filePaths">The file paths.</param>
        /// <param name="level">The compression level (1-9).</param>
        public override void Compress(DirectoryPath rootPath, FilePath outputPath, IEnumerable <FilePath> filePaths, int level)
        {
            Precondition.IsNotNull(rootPath, nameof(rootPath));
            Precondition.IsNotNull(outputPath, nameof(outputPath));
            Precondition.IsNotNull(filePaths, nameof(filePaths));
            Precondition.IsBetween(level, 1, 9, nameof(level));

            // Make root path and output file path absolute.
            rootPath   = rootPath.MakeAbsolute(environment);
            outputPath = outputPath.MakeAbsolute(environment);

            // Get the output file.
            var outputFile = fileSystem.GetFile(outputPath);

            // Open up a stream to the output file.
            log.Verbose("Creating BZip2 file: {0}", outputPath.FullPath);

            using var outputStream      = outputFile.Open(FileMode.Create, FileAccess.Write, FileShare.None);
            using var bzip2OutputStream = new BZip2OutputStream(outputStream, level);
            using var tarOutputStream   = new TarOutputStream(bzip2OutputStream, Encoding.UTF8);

            foreach (var inputPath in filePaths)
            {
                var absoluteInputPath = inputPath.MakeAbsolute(environment);
                var file = fileSystem.GetFile(absoluteInputPath);

                using var inputStream = file.Open(FileMode.Open, FileAccess.Read, FileShare.Read);

                // Get the relative filename to the rootPath.
                var relativeFilePath = GetRelativeFilePath(rootPath, absoluteInputPath);
                log.Verbose("Compressing file {0}", absoluteInputPath);

                // Create the tar archive entry.
                TarEntry entry = TarEntry.CreateTarEntry(relativeFilePath.FullPath);
                entry.Size = inputStream.Length;

                tarOutputStream.PutNextEntry(entry);
                inputStream.CopyTo(tarOutputStream);
                tarOutputStream.CloseEntry();
            }

            log.Verbose("BZip2 file successfully created: {0}", outputPath.FullPath);
        }
예제 #22
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RoomRecipe"/> class.
        /// </summary>
        /// <param name="in_id">Unique identifier for the <see cref="RoomRecipe"/>.  Cannot be null.</param>
        /// <param name="in_name">Player-friendly name of the <see cref="RoomRecipe"/>.</param>
        /// <param name="in_description">Player-friendly description of the <see cref="RoomRecipe"/>.</param>
        /// <param name="in_comment">Comment of, on, or by the <see cref="RoomRecipe"/>.</param>
        /// <param name="in_requiredFurnishings">A list of furnishing categories this <see cref="RoomRecipe"/> requires.</param>
        /// <param name="in_MinimumWalkableSpaces">The minimum number of walkable <see cref="Space"/>s required by this <see cref="RoomRecipe"/>.</param>
        /// <param name="in_optionallyRequiredWalkableFloors">An optional list of floor categories this <see cref="RoomRecipe"/> requires.</param>
        /// <param name="in_optionallyRequiredPerimeterBlocks">An optional list of block categories this <see cref="RoomRecipe"/> requires as walls.</param>
        public RoomRecipe(GameObjectID in_id, string in_name, string in_description, string in_comment,
                          List <RecipeElement> in_requiredFurnishings,
                          int in_MinimumWalkableSpaces = All.Recipes.Rooms.MinWalkableSpaces,
                          List <RecipeElement> in_optionallyRequiredWalkableFloors  = null,
                          List <RecipeElement> in_optionallyRequiredPerimeterBlocks = null)
            : base(All.RoomRecipeIDs, in_id, in_name, in_description, in_comment)
        {
            Precondition.IsNotNull(in_requiredFurnishings, nameof(in_requiredFurnishings));
            Precondition.IsNotEmpty(in_requiredFurnishings, nameof(in_requiredFurnishings));
            if (in_MinimumWalkableSpaces < All.Recipes.Rooms.MinWalkableSpaces ||
                in_MinimumWalkableSpaces > All.Recipes.Rooms.MaxWalkableSpaces)
            {
                throw new ArgumentOutOfRangeException(nameof(in_MinimumWalkableSpaces));
            }

            MinimumWalkableSpaces   = in_MinimumWalkableSpaces;
            RequiredFloors          = in_optionallyRequiredWalkableFloors ?? Enumerable.Empty <RecipeElement>().ToList();
            RequiredPerimeterBlocks = in_optionallyRequiredPerimeterBlocks ?? Enumerable.Empty <RecipeElement>().ToList();
            RequiredFurnishings     = in_requiredFurnishings;
        }
예제 #23
0
        /// <summary>
        /// Uncompress the specified GZip Tar file.
        /// </summary>
        /// <param name="filePath">GZip file to uncompress.</param>
        /// <param name="outputPath">Output path to uncompress into.</param>
        public override void Uncompress(FilePath filePath, DirectoryPath outputPath)
        {
            Precondition.IsNotNull(filePath, nameof(filePath));
            Precondition.IsNotNull(outputPath, nameof(outputPath));

            // Make root path and output file path absolute.
            filePath   = filePath.MakeAbsolute(environment);
            outputPath = outputPath.MakeAbsolute(environment);

            var file = fileSystem.GetFile(filePath);

            log.Verbose("Uncompress GZip file {0} to {1}", filePath.FullPath, outputPath.FullPath);

            using (Stream inputStream = file.Open(FileMode.Open, FileAccess.Read, FileShare.Read))
                using (Stream gzipInputStream = new GZipInputStream(inputStream))
                {
                    TarArchive archive = TarArchive.CreateInputTarArchive(gzipInputStream);
                    archive.ExtractContents(outputPath.FullPath);
                    archive.Close();
                }
        }
예제 #24
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CraftingRecipe"/> class.
        /// </summary>
        /// <param name="in_id">Unique identifier for the <see cref="CraftingRecipe"/>.  Cannot be null.</param>
        /// <param name="in_name">Player-friendly name of the <see cref="CraftingRecipe"/>.  Cannot be null or empty.</param>
        /// <param name="in_description">Player-friendly description of the <see cref="CraftingRecipe"/>.</param>
        /// <param name="in_comment">Comment of, on, or by the <see cref="CraftingRecipe"/>.</param>
        /// <param name="in_products">The types and quantities of <see cref="Items.Item"/>s created by following this recipe once.</param>
        /// <param name="in_ingredients">All items needed to follow this <see cref="CraftingRecipe"/> once.</param>
        /// <param name="in_panelPattern">The arrangment of panels encompassed by this <see cref="CraftingRecipe"/>.</param>
        /// <exception cref="IndexOutOfRangeException">
        /// Thrown when <paramref name="in_panelPattern"/> has zero-dimensions or dimensions larger than those given by
        /// <see cref="All.Dimensions.PanelsPerPatternWidth"/> and <see cref="All.Dimensions.PanelsPerPatternHeight"/>.
        /// </exception>
        public CraftingRecipe(GameObjectID in_id, string in_name, string in_description, string in_comment,
                              IEnumerable <RecipeElement> in_products,
                              IEnumerable <RecipeElement> in_ingredients, StrikePanel[,] in_panelPattern)
            : base(All.CraftingRecipeIDs, in_id, in_name, in_description, in_comment)
        {
            Precondition.IsNotNull(in_products, nameof(in_products));
            Precondition.IsNotEmpty(in_products, nameof(in_products));
            Precondition.IsNotNull(in_ingredients, nameof(in_ingredients));
            Precondition.IsNotEmpty(in_ingredients, nameof(in_ingredients));
            Precondition.IsNotNull(in_panelPattern, nameof(in_panelPattern));
            if (in_panelPattern.GetLength(0) > All.Dimensions.PanelsPerPatternHeight ||
                in_panelPattern.GetLength(1) > All.Dimensions.PanelsPerPatternWidth ||
                in_panelPattern.GetLength(0) < 1 ||
                in_panelPattern.GetLength(1) < 1)
            {
                throw new IndexOutOfRangeException($"Dimension outside specification: {nameof(in_panelPattern)}");
            }

            Products     = in_products.ToList();
            Ingredients  = in_ingredients.ToList();
            PanelPattern = in_panelPattern;
        }
예제 #25
0
        /// <summary>
        /// Merge two results.  Clients should call Result.Merge(...) instead.
        /// </summary>
        private Result(Result lhs, Result rhs)
            : this()
        {
            Precondition.IsNotNull(lhs, "lhs");
            Precondition.IsNotNull(rhs, "rhs");

            Assert((null == lhs.mSummaryRow) || (null == rhs.mSummaryRow),
                   "Both 'lhs' and 'rhs' have non-null mSummaryRow fields.");
            if (null == lhs.mSummaryRow)
            {
                mSummaryRow = rhs.mSummaryRow;
            }
            else
            {
                mSummaryRow = lhs.mSummaryRow;
            }

            Assert(Double.IsNaN(lhs.DistanceMi) || Double.IsNaN(rhs.DistanceMi),
                   "Both 'lhs' and 'rhs' have non-NaN mDistanceMi fields.");
            if (Double.IsNaN(lhs.DistanceMi))
            {
                mDistanceMi = rhs.DistanceMi;
            }
            else
            {
                mDistanceMi = lhs.DistanceMi;
            }

            Assert((0 == lhs.MatchingProfiles.Count) || (0 == rhs.MatchingProfiles.Count),
                   "Both 'lhs' and 'rhs' have non-empty mMatchingProfiles fields.");
            if (0 == lhs.MatchingProfiles.Count)
            {
                mMatchingProfiles = rhs.mMatchingProfiles;
            }
            else
            {
                mMatchingProfiles = lhs.mMatchingProfiles;
            }
        }
예제 #26
0
        /// <param name="outputPath">Output path to uncompress into.</param>
        public override void UncompressToMultiple(FilePath filePath, IEnumerable <DirectoryPath> outputPath)
        {
            Precondition.IsNotNull(filePath, nameof(filePath));
            Precondition.IsNotNull(outputPath, nameof(outputPath));

            // Make root path and output file path absolute.
            filePath = filePath.MakeAbsolute(environment);

            var file = fileSystem.GetFile(filePath);


            using (Stream inputStream = file.Open(FileMode.Open, FileAccess.Read, FileShare.Read))
                using (Stream bzip2InputStream = new BZip2InputStream(inputStream))
                {
                    TarArchive archive = TarArchive.CreateInputTarArchive(bzip2InputStream);
                    foreach (var path in outputPath)
                    {
                        var p = path.MakeAbsolute(environment);
                        log.Verbose("Uncompress BZip2 file {0} to {1}", filePath.FullPath, p.FullPath);
                        archive.ExtractContents(p.FullPath);
                    }
                    archive.Close();
                }
        }
예제 #27
0
 public void IsNotNull_Throws_ArgumentNullException(Culture culture, object value, string parameter, string message, string expectedParameter, string expectedMessage)
 {
     AssertThrowsException <ArgumentNullException>(culture, () => Precondition.IsNotNull(value, parameter, message), expectedParameter, expectedMessage, null);
 }
예제 #28
0
 public void IsNotNull_Throws_Nothing(object value, string parameter, string message)
 {
     Assert.That(() => Precondition.IsNotNull(value, parameter, message), Throws.Nothing);
 }
예제 #29
0
 public void IsNotNull_Throws_Nothing(object value)
 {
     Assert.That(() => Precondition.IsNotNull(value), Throws.Nothing);
 }
예제 #30
0
        public ThreadedWork(Action finishedWorkCallback)
        {
            Precondition.IsNotNull(finishedWorkCallback);

            this.FinishedWorkCallback = finishedWorkCallback;
        }