public List <PathNode> GeneratePath(Vector3 startingPoint, Vector3 startingDirection, int lengthOfPath, Vector3 endingDirection = default(Vector3), GameObject endingRoom = null) { PathNode newNode = _SetupNode(startingPoint, startingDirection); PathNode previousNode = newNode; _oldDirections.Add(startingDirection); bool hasFinalDestination = endingDirection != Vector3.zero ? true : false; int loopAmount = hasFinalDestination ? lengthOfPath - 1 : lengthOfPath - 2; PathNode finalNode = _GeneratePath(loopAmount, previousNode, newNode); if (hasFinalDestination) { Vector3 newStartingDirection = endingDirection * -1f; finalNode.exitConnection = newStartingDirection; if (PathValidator.ValidDirection(_oldDirections, newStartingDirection)) { newNode = _SetupNode(finalNode.position, newStartingDirection); } else { newNode = _ForcePathForUniqueSpawn(finalNode, endingDirection); } newNode.enterConnection = finalNode.exitConnection; newNode.uniqueRoom = endingRoom; } return(_currentPath); }
private bool CheckPathValid(out string error) { error = string.Empty; var name = m_textBoxName.Text.Trim(); var folder = m_textBoxLocation.Text.Trim(); if (String.IsNullOrEmpty(name)) { return(false); } if (!PathValidator.IsFileNameValid(name)) { error = Messages.BUGTOOL_PAGE_DESTINATION_INVALID_NAME; return(false); } if (String.IsNullOrEmpty(folder)) { return(false); } string path = String.Format("{0}\\{1}", folder, name); if (!PathValidator.IsPathValid(path)) { error = Messages.BUGTOOL_PAGE_DESTINATION_INVALID_FOLDER; return(false); } return(true); }
private bool CheckPathValid(out string error) { error = string.Empty; if (String.IsNullOrEmpty(ApplianceFileName)) { return(false); } if (!PathValidator.IsFileNameValid(ApplianceFileName)) { error = Messages.EXPORT_APPLIANCE_PAGE_ERROR_INALID_APP; return(false); } if (String.IsNullOrEmpty(ApplianceDirectory)) { return(false); } string path = String.Format("{0}\\{1}", ApplianceDirectory, ApplianceFileName); if (!PathValidator.IsPathValid(path)) { error = Messages.EXPORT_APPLIANCE_PAGE_ERROR_INVALID_DIR; return(false); } return(true); }
public void Validate_CorrectFilePath_ValidateCorrectly() { var filePath = "c:\\SomeDirectory\\SomeFile.txt"; var pathValidator = new PathValidator(); Assert.IsTrue(pathValidator.Validate(filePath)); }
public void TryFormattingADiskAndInitializingFileSystemWithIt() { Stream stream = new MemoryStream(); // System.IO.File.Open(@"c:\bs.bin", FileMode.Create); var formatter = new VirtualDiskFormatter(); VirtualDisk disk = VirtualDisk.CreateFormattingTheStream(stream, 2048, 2048 * 5000); var diskStructuresManager = new FileSystemNodeStorage(disk); formatter.Format(disk, diskStructuresManager); FileSystemHeader header = diskStructuresManager.ReadFileSystemHeader(VirtualDiskFormatter.FileSystemHeaderBlockIndex); var nameValidator = new FileSystemArtifactNamesValidator(Constants.IllegalCharactersForNames, Constants.FileAndFolderMaximumNameLength); var pathValidator = new PathValidator(VirtualFileSystem.Root, Constants.IllegalCharactersForPaths, nameValidator, VirtualFileSystem.DirectorySeparatorChar); var pathBuilder = PathBuilder.Default; var nodeResolver = new NodeResolver(disk, diskStructuresManager, StringComparer.OrdinalIgnoreCase, header.RootBlockOffset, VirtualFileSystem.Root, VirtualFileSystem.DirectorySeparatorChar, pathValidator, pathBuilder); VirtualFileSystem fileSystem = VirtualFileSystem.CreateFromDisk(disk, StringComparer.OrdinalIgnoreCase, nodeResolver, pathBuilder, nameValidator, pathValidator); Assert.AreEqual(2048, fileSystem.FileSystemInfo.BlockSizeInBytes); Assert.AreEqual(new Version(1, 0, 0, 0), fileSystem.FileSystemInfo.Version); }
/// <summary> /// Make sure a feed url is valid. /// This doesn't check to make sure it has octgn games on it, it only /// checks to make sure it's a valid nuget feed, and sometimes it's even /// wrong when it check that, so don't 100% rely on this for validation. /// </summary> /// <param name="feed">Feed url</param> /// <returns>Returns true if it is, or false if it isn't</returns> public bool ValidateFeedUrl(string feed) { Log.InfoFormat("Validating feed url {0}", feed); if (PathValidator.IsValidUrl(feed) && PathValidator.IsValidSource(feed)) { Log.InfoFormat("Path Validator says feed {0} is valid", feed); try { Log.InfoFormat("Trying to query feed {0}", feed); var repo = PackageRepositoryFactory.Default.CreateRepository(feed); Log.InfoFormat("Loading feed to list {0}", feed); var list = repo.GetPackages().ToList(); // This happens so that enumerating the list isn't optimized away. foreach (var l in list) { System.Diagnostics.Trace.WriteLine(l.Id); } Log.InfoFormat("Queried feed {0}, feed is valid", feed); return(true); } catch (Exception e) { Log.WarnFormat("{0} is an invalid feed.", feed); } } Log.InfoFormat("Path validator failed for feed {0}", feed); return(false); }
private Vector3 _GetNewStartingDirection(Room oldRoom, Vector3 forcedDirection = default(Vector3)) { List <Transform> connections = oldRoom.Connections.AllConnections(); Vector3 direction = Vector3.zero; if (forcedDirection == Vector3.zero) { int index = Random.Range(0, connections.Count); direction = connections[index].position; } else { direction = forcedDirection; } if (PathValidator.ValidDirection(_oldDirections, direction)) { _oldDirections.Add(direction); } else { for (int i = 0; i < connections.Count; i++) { direction = connections[i].position; if (PathValidator.ValidDirection(_oldDirections, direction)) { _oldDirections.Add(direction); break; } } } return(direction); }
public static void Run(UpdateSourceArgs args, Func <ILogger> getLogger) { var settings = RunnerHelper.GetSettings(args.Configfile); var sourceProvider = RunnerHelper.GetSourceProvider(settings); var existingSource = sourceProvider.GetPackageSourceByName(args.Name); if (existingSource == null) { throw new CommandException(Strings.SourcesCommandNoMatchingSourcesFound, args.Name); } if (!string.IsNullOrEmpty(args.Source) && !existingSource.Source.Equals(args.Source, StringComparison.OrdinalIgnoreCase)) { if (!PathValidator.IsValidSource(args.Source)) { throw new CommandException(Strings.SourcesCommandInvalidSource); } // If the user is updating the source, verify we don't have a duplicate. var duplicateSource = sourceProvider.GetPackageSourceBySource(args.Source); if (duplicateSource != null) { throw new CommandException(Strings.SourcesCommandUniqueSource); } existingSource = new Configuration.PackageSource(args.Source, existingSource.Name); // If the existing source is not http, warn the user if (existingSource.IsHttp && !existingSource.IsHttps) { getLogger().LogWarning(string.Format(CultureInfo.CurrentCulture, Strings.Warning_HttpServerUsage, "update source", args.Source)); } } RunnerHelper.ValidateCredentials(args.Username, args.Password, args.ValidAuthenticationTypes); if (!string.IsNullOrEmpty(args.Username)) { var hasExistingAuthTypes = existingSource.Credentials?.ValidAuthenticationTypes.Any() ?? false; if (hasExistingAuthTypes && string.IsNullOrEmpty(args.ValidAuthenticationTypes)) { getLogger().LogMinimal(string.Format(CultureInfo.CurrentCulture, Strings.SourcesCommandClearingExistingAuthTypes, args.Name)); } var credentials = Configuration.PackageSourceCredential.FromUserInput( args.Name, args.Username, args.Password, args.StorePasswordInClearText, args.ValidAuthenticationTypes); existingSource.Credentials = credentials; } sourceProvider.UpdatePackageSource(existingSource, updateCredentials: existingSource.Credentials != null, updateEnabled: false); getLogger().LogMinimal(string.Format(CultureInfo.CurrentCulture, Strings.SourcesCommandUpdateSuccessful, args.Name)); }
public async Task RestorePartialParallelAsync(Regions regions, string TargetPath, string _user, LogOptions _logOptions, LogState _logstate, LogOperation _logoperation, CancellationToken token) { Logger.assignLogPath(TargetPath, _logstate, _logoperation); RestoreCopyHandler objrestorehandler = new RestoreCopyHandler(); objrestorehandler.OnAtomicCurrent += DataBackup_OnAtomicCurrent; var model = FileOperations.Read(TargetPath); if (model.CustomPaths != null) { regions.SetPaths(model.CustomPaths); } OnDataRestoreStart?.Invoke(this, new StringEventArgs("Data Restore Started")); var BackupDirectoriesInfo = (new DirectoryInfo(TargetPath)).GetDirectories(); foreach (var path in regions.GetPaths(_user)) { PathValidator validator = new PathValidator(); if (validator.Validate(path)) { var _path = new DirectoryInfo(path); foreach (var item in BackupDirectoriesInfo.Where(x => x.Name.Equals(_path.Name))) { if (!(new DirectoryInfo(path)).Name.Equals(item.Name)) { OnCalculationStart?.Invoke(this, true); //EnumData countModel = new EnumData(); //CountModel counts = await countModel.GetCountAsync(new DirectoryInfo(item.FullName)); //OnAtomicTotalCounts?.Invoke(this, (counts.FileCount + counts.DirCount)); int counts = await SafeNativeMethods.FilesAndDirectoryListCountAsync(item.FullName); OnAtomicTotalCounts?.Invoke(this, counts); new DirectoryInfo($@"{path}\{item.Name}").Create(); await objrestorehandler.CopyPartialParallelAsync(item, new DirectoryInfo($@"{path}\{item.Name}"), _logOptions, token); } else { OnCalculationStart?.Invoke(this, true); //EnumData countModel = new EnumData(); //CountModel counts = await countModel.GetCountAsync(new DirectoryInfo(item.FullName)); //OnAtomicTotalCounts?.Invoke(this, (counts.FileCount + counts.DirCount)); int counts = await SafeNativeMethods.FilesAndDirectoryListCountAsync(item.FullName); OnAtomicTotalCounts?.Invoke(this, counts); await objrestorehandler.CopyPartialParallelAsync(item, new DirectoryInfo(path), _logOptions, token); } } } else { Logger.log(path, "path not found", _logOptions); } } OnDataRestoreComplete?.Invoke(this, new StringEventArgs("Data Restore Completed")); }
private List <PluginFile> GetPluginFiles(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var filePaths = GetPluginFilePaths(); var files = new List <PluginFile>(); foreach (var filePath in filePaths) { cancellationToken.ThrowIfCancellationRequested(); if (PathValidator.IsValidLocalPath(filePath) || PathValidator.IsValidUncPath(filePath)) { if (File.Exists(filePath)) { var state = new Lazy <PluginFileState>(() => _verifier.IsValid(filePath) ? PluginFileState.Valid : PluginFileState.InvalidEmbeddedSignature); files.Add(new PluginFile(filePath, state)); } else { files.Add(new PluginFile(filePath, new Lazy <PluginFileState>(() => PluginFileState.NotFound))); } } else { files.Add(new PluginFile(filePath, new Lazy <PluginFileState>(() => PluginFileState.InvalidFilePath))); } } return(files); }
public string[] GetArgs() { string[] argsManual = new string[2]; Console.Write("Give filename or path to process: "); while (!PathValidator.PathTryParse(Console.ReadLine(), ref argsManual[1])) { Console.Write("Wrong path! Give right value: "); } if ((new FileInfo(argsManual[1]).Attributes & FileAttributes.Directory) == FileAttributes.Directory) { argsManual[0] = "-D"; //if path is folder stop collecting arguments } else { Array.Resize(ref argsManual, 3); argsManual[0] = "-F"; Console.Write("Give file process option :" + "\n1 to remove " + "\n2 for show each ten word" + "\n3 to show each third sentence\n> "); while (argsManual[2] == null) { switch (Console.ReadLine()) { case "1": argsManual[2] = "-R"; break; case "2": argsManual[2] = "-S"; break; case "3": argsManual[2] = "-T"; break; default: Console.WriteLine("Choose right number!"); break; } } if (argsManual[2].Equals("-R")) { Array.Resize(ref argsManual, 5); argsManual[3] = "-W"; Console.Write("Give word or char to remove : "); argsManual[4] = Console.ReadLine()?.ToLower(); } } return(argsManual); }
//////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Tests the validation of a directory. </summary> /// /// <exception cref="NotSupportedException"> /// Thrown when the requested operation is not supported. /// </exception> /// /// <param name="definitionFile"> The validator definition file. </param> /// <param name="path"> Full pathname of the directory to validate. </param> /// <param name="expectedResult"> The expected validation result. </param> /// /// <returns> true if the test passes, false if the test fails. </returns> private bool TestValidateDirectory(string definitionFile, string path, ExpectedResult expectedResult) { using (var xmlReader = XmlReader.Create(definitionFile)) { var definition = PathValidator.DeserializeDefinition(xmlReader); var validator = new PathValidator(); validator.Validate(definition, path); switch (expectedResult) { case ExpectedResult.Valid: return((validator.ErrorMessages.Count == 0) && (validator.WarningMessages.Count == 0)); case ExpectedResult.Warning: return((validator.ErrorMessages.Count == 0) && (validator.WarningMessages.Count > 0)); case ExpectedResult.Error: return((validator.ErrorMessages.Count > 0) && (validator.WarningMessages.Count == 0)); default: throw new NotSupportedException("Unknown result type"); } } }
private bool CheckPathValid(out string error) { error = String.Empty; string filepath = textBoxFile.Text; if (String.IsNullOrEmpty(filepath.TrimEnd())) { error = "模板路径不能为空"; return(false); } //if it's URI ignore if (IsUri()) { return(true); } if (!PathValidator.IsPathValid(filepath)) { error = "模板路径中包含无效的字符"; return(false); } return(true); }
public bool IsValidRootedPath(string path, bool checkExists = false, bool mayBeUnc = false) { if (string.IsNullOrWhiteSpace(path)) { return(false); } try { if (!path.IsValidAbsoluteDirectoryPath()) { return(false); } var absolutePath = path.ToAbsoluteDirectoryPath(); PathValidator.ValidateName(path); if (!mayBeUnc && (absolutePath.Kind == AbsolutePathKind.UNC)) { return(false); } return(!checkExists || absolutePath.Exists); } catch (ArgumentException) { return(false); } catch (PathTooLongException) { return(false); } catch (NotSupportedException) { return(false); } }
public void IsValidUncPathReturnsTrueForValidUncPath() { // Act var isValid = PathValidator.IsValidUncPath(@"\\server\share\Path\To\Source"); // Assert Assert.True(isValid); }
public void IsValidUrlReturnsFalseForInvalidUrlAsUncPath() { // Act var isValid = PathValidator.IsValidUrl(@"\\server\share"); // Assert Assert.False(isValid); }
public void IsValidUrlReturnsFalseForInvalidUrlAsLocalPath() { // Act var isValid = PathValidator.IsValidUrl(@"C:\Path\To\Source"); // Assert Assert.False(isValid); }
public void IsValidUrlReturnsFalseForInvalidUrl() { // Act var isValid = PathValidator.IsValidUrl(@"http::/\/go.microsoft.com/fw&link/?LinkID=199193"); // Assert Assert.False(isValid); }
public void IsValidUrlReturnsTrueForValidUrlUsingPorts() { // Act var isValid = PathValidator.IsValidUrl(@"http://127.0.0.1:8080/mysource"); // Assert Assert.True(isValid); }
public void IsValidFilePathReturnsFalseForAbsolutePathWithoutDriveLetter() { // Act var isValid = PathValidator.IsValidLocalPath(@"\Path\To\Source"); // Assert Assert.False(isValid); }
public void IsValidFilePathReturnsTrueForValidLocalPath() { // Act var isValid = PathValidator.IsValidLocalPath(@"C:\Path\To\Source"); // Assert Assert.True(isValid); }
public void IsValidFilePathReturnsFalseForInvalidLocalPathBadCharacters() { // Act var isValid = PathValidator.IsValidLocalPath(@"C:\Path\*\:\""\Source"); // Assert Assert.False(isValid); }
public void IsValidFilePathReturnsFalseForInvalidLocalPathFormat(string path) { // Act var isValid = PathValidator.IsValidLocalPath(path); // Assert Assert.False(isValid); }
public void IsValidFilePathReturnsFalseForRelativePathWithDriveLetter() { // Act var isValid = PathValidator.IsValidLocalPath(@"C:Path\To\Source"); // Assert Assert.False(isValid); }
public void IsValidUrlReturnsTrueForValidHttpsUrl() { // Act var isValid = PathValidator.IsValidUrl(@"https://go.microsoft.com/fwlink/?LinkID=199193"); // Assert Assert.True(isValid); }
public void IsValidUncPathReturnsFalseForInvalidUncPathMissingShare() { // Act var isValid = PathValidator.IsValidUncPath(@"\\server\"); // Assert Assert.False(isValid); }
public MessageProcessor(IGameReaderWriter gameReaderWriter) { _gameReaderWriter = gameReaderWriter; _wikipediaLinkExtractor = new WikipediaLinkExtractor(); _pageListExtractor = new PageListExtractor(); _leaderBoardGenerator = new LeaderBoardGenerator(_gameReaderWriter); _pathValidator = new PathValidator(); }
public void IsValidUncPathReturnsFalseForInvalidUncPathMissingDoubleBackslash() { // Act var isValid = PathValidator.IsValidUncPath(@"\server"); // Assert Assert.False(isValid); }
public void IsValidFilePathReturnsFalseForInvalidLocalPathFormat() { // Act var isValid = PathValidator.IsValidLocalPath(@"ABC:\Path\To\Source"); // Assert Assert.IsFalse(isValid); }
public void IsValidUncPathReturnsFalseForInvalidUncPathBadCharacters() { // Act var isValid = PathValidator.IsValidUncPath(@"\\server\share\*\:\""\Source"); // Assert Assert.False(isValid); }
//////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Tests the validation of a directory. </summary> /// /// <exception cref="NotSupportedException"> /// Thrown when the requested operation is not supported. /// </exception> /// /// <param name="definitionFile"> The validator definition file. </param> /// <param name="path"> Full pathname of the directory to validate. </param> /// <param name="expectedResult"> The expected validation result. </param> /// /// <returns> true if the test passes, false if the test fails. </returns> private bool TestValidateDirectory(string definitionFile, string path, ExpectedResult expectedResult) { using (var xmlReader = XmlReader.Create(definitionFile)) { var definition = PathValidator.DeserializeDefinition(xmlReader); var validator = new PathValidator(); validator.Validate(definition, path); switch (expectedResult) { case ExpectedResult.Valid: return (validator.ErrorMessages.Count == 0) && (validator.WarningMessages.Count == 0); case ExpectedResult.Warning: return (validator.ErrorMessages.Count == 0) && (validator.WarningMessages.Count > 0); case ExpectedResult.Error: return (validator.ErrorMessages.Count > 0) && (validator.WarningMessages.Count == 0); default: throw new NotSupportedException("Unknown result type"); } } }
//////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Validates an installation. </summary> /// /// <exception cref="ArgumentNullException"> /// Thrown when one or more required arguments are null. /// </exception> /// /// <param name="validatorDefinition"> The validator definition. </param> /// <param name="validatorPath"> The path to validate. </param> /// <param name="onLog"> The logging callback. </param> /// <param name="onMessageUser"> The message user callback. </param> /// <param name="onError"> The error callback. </param> /// /// <returns> true if it succeeds, false if it fails. </returns> public static bool InstallValidator(string validatorDefinition , string validatorPath , Action<string> onLog , Func<string, MessageType, bool> onMessageUser , Action<string, bool> onError) { if ((onLog == null) || (onMessageUser == null) || (onError == null)) { throw new ArgumentNullException("A required callback delegate was not supplied"); } onLog("Begin InstallValidator"); // Check the custom action arguments have been set if (String.IsNullOrEmpty(validatorDefinition) || String.IsNullOrEmpty(validatorPath)) { onError("InstallValidator: ERROR : Action data not set", false); return false; } // Log the properties for debugging if necessary onLog("LOG: INSTALLVALIDATORDEF : " + validatorDefinition); onLog("LOG: INSTALLVALIDATORPATH : " + validatorPath); // Validate the installation path var validator = new PathValidator(); validator.Validate(validatorDefinition, validatorPath); // Show warning messages if (validator.WarningMessages.Count != 0) { // Ask the user if they want to see the warnings that were raised var displayMessages = onMessageUser(String.Format("{0} warnings were raised when validating your installation.\n\nDo you want to view them (Recommended)?", validator.WarningMessages.Count) , MessageType.WarningYesNo); if (displayMessages) { // Display each warning in a separate dialog foreach (var message in validator.WarningMessages) { onLog(String.Format("InstallValidator: {0}", message)); onMessageUser(message, MessageType.WarningOK); } // See if the user still wants to continue the installation var continueInstallation = onMessageUser("Do you want to continue the installation?", MessageType.WarningYesNo); // If the user wants to cancel the installation return user exit if (!continueInstallation) { return false; } } } // Show error message if (validator.ErrorMessages.Count != 0) { onError(validator.ErrorMessages[0], true); return false; } return true; }