public void CompleteFileSync(string Message) { if (this.InvokeRequired) { Invoke((MethodInvoker)delegate { CompleteFileSync(Message); }); } else { string dir1 = Directory1.rootDirectory; string dir2 = Directory2.rootDirectory; Directory1 = new TargetDirectory(); Directory2 = new TargetDirectory(); cmdDirectory1.Enabled = false; cmdDirectory2.Enabled = false; pgbFileProgress.Visible = true; lblUpdateText.Text = "Searching directory for files"; cmdDirectory1.Text = dir1; cmdDirectory2.Text = dir2; trvDirectory1.Nodes.Clear(); trvDirectory2.Nodes.Clear(); Thread FileListPopulator1 = new Thread(() => PopulateFileList(1, dir1)); Thread FileListPopulator2 = new Thread(() => PopulateFileList(2, dir2)); FileListPopulator1.Start(); FileListPopulator2.Start(); cmdSyncDirectories.Text = "Sync Directories"; lblUpdateText.Text = Message; } }
public Task Run() { return(Task.Run(() => { if (!TargetDirectory.Exists) { TargetDirectory.Create(); } SemaphoreSlim semaphore = new SemaphoreSlim(ThreadCount); int filenameCount = 0; int finished = 0; var tasks = new List <Task>(); int max = ImageQueue.Count; while (!ImageQueue.IsEmpty) { semaphore.Wait(); if (!ImageQueue.TryDequeue(out var address)) { continue; } string extension = address.ToString().Split(".")[^ 1];
public void Make() { var fileSet = new FileSet(TargetDirectory, _imageProviderFactory); var expected = TargetDirectory.GetFiles().Select(f => new FileNode(f, fileSet, BrowserResources.Properties.Resources.Image_File, _imageProviderFactory)); CollectionAssert.AreEquivalent(expected, fileSet); }
public Boolean CopyInstallationFiles(String sourceFolder, String destinationFolder) { FileInfo[] sourceFiles = null; try { DirectoryInfo sourceDirectory = new DirectoryInfo(Path.Combine(sourceFolder, "Binaries")); sourceFiles = sourceDirectory.GetFiles("*.*", SearchOption.AllDirectories); } catch (Exception exc) { if (listener != null) { listener.NotifyObject(new Exception("Falha ao copiar arquivos! " + exc.Message)); } return(false); } TargetDirectory targetDirectory = new TargetDirectory(destinationFolder); if (!targetDirectory.CopyFilesFrom(sourceFiles)) { if (listener != null) { listener.NotifyObject(new Exception("Falha ao copiar arquivos! " + targetDirectory.GetLastError())); } return(false); } return(true); }
public static string CalculateTargetdirectory(TargetDirectory targetDirectory) { switch (targetDirectory) { case TargetDirectory.Root: return(string.Empty); case TargetDirectory.Reports: return("Reports"); case TargetDirectory.Results: return("Results"); case TargetDirectory.Charts: return("Charts"); case TargetDirectory.Debugging: return("Debugging"); case TargetDirectory.Temporary: return("Temporary Files"); default: throw new LPGException("Forgotten TargetDirectory"); } }
void ParseTargetDirectory() { if (TargetDirectory == null) { hostname = username = directory = null; return; } int indexOfAt = TargetDirectory.IndexOf('@'); int indexOfColon = TargetDirectory.IndexOf(':'); if (indexOfColon < 1) { LoggingService.LogWarning("Ignoring invalid SSHFS host path \"{0}\" in configuration.", TargetDirectory); return; } if (indexOfAt > 0 && indexOfColon > indexOfAt) { username = TargetDirectory.Substring(0, indexOfAt); hostname = TargetDirectory.Substring(indexOfAt + 1, indexOfColon - indexOfAt - 1); } else { hostname = TargetDirectory.Substring(0, indexOfColon); } directory = TargetDirectory.Substring(indexOfColon + 1); }
public void RegisterFile([NotNull] string fileName, [NotNull] string description, bool displayResultFileEntry, ResultFileID rfid1, [NotNull] HouseholdKey householdKey, TargetDirectory targetDirectory, CalcOption enablingOption, [CanBeNull] string additionalFileIndex = null) { if (!HouseholdRegistry.IsHouseholdRegistered(householdKey)) { throw new LPGException("Forgotten Household Key: " + householdKey); } if (fileName.Contains("..")) { throw new LPGException("Filename with two dots. This looks bad. Please fix: " + fileName); } if (fileName.Contains(" ")) { throw new LPGException("Filename with two spaces. This looks bad. Please fix: " + fileName); } string fullFileName = Path.Combine(GetFullPathForTargetdirectry(targetDirectory), fileName); FileInfo fi = new FileInfo(fullFileName); ResultFileEntry rfe = new ResultFileEntry(description, fi, displayResultFileEntry, rfid1, householdKey.Key, additionalFileIndex, enablingOption); _inputDataLogger.Save(rfe); ResultFileList.ResultFiles.Add(rfe.HashKey, rfe); }
public void AllChildrenEnumeratedOnlyAfterAllSubDirsAllChildrenEnumerated() { DirectoryInfo dir = TargetDirectory.GetDirectories().First(); MakeSubDirs(dir); var node = new DirectoryNode(TargetDirectory, null); Assert.IsFalse(node.AllChildrenEnumerated); node.PopulateSubDirs(); Assert.IsFalse(node.AllChildrenEnumerated); foreach (var subDir in node.SubDirs) { subDir.PopulateSubDirs(); } Assert.IsFalse(node.AllChildrenEnumerated); foreach (var subDir in node.SubDirs) { foreach (var subSubDir in subDir.SubDirs) { subSubDir.PopulateSubDirs(); } } Assert.IsTrue(node.AllChildrenEnumerated); }
private Boolean PrepareDirectory() { txtProcessInfo.Text += Environment.NewLine + "Preparando diretório de instalação..."; const String prepareFail = "O diretório de instalação apresentou alguns problemas. "; // Ajusta o formato do caminho de instalação txtTargetDirectory.Text = PathFormat.Adjust(txtTargetDirectory.Text); // Prepara o diretório de destino ( faz algumas verificações / cria o diretório ) // Caso existam arquivos no diretório aborta e exibe mensagem de erro TargetDirectory targetDir = new TargetDirectory(txtTargetDirectory.Text); if (!targetDir.Mount()) { txtProcessInfo.Text += Environment.NewLine + prepareFail + Environment.NewLine + targetDir.GetLastError(); return(false); } // Cria o subdiretório para gravação de log de cópias copyLogDirectory = @"C:\CopyLogs"; try { DirectoryInfo dirInfo = new DirectoryInfo(copyLogDirectory); dirInfo.Create(); } catch (Exception exc) { txtProcessInfo.Text += Environment.NewLine + prepareFail + Environment.NewLine + exc.Message; return(false); } return(true); }
protected override void ProcessRecord() { // Commandファイルから読み取り if ((this.Command == null || this.Command.Length == 0) && !string.IsNullOrEmpty(this.CommandFile) && File.Exists(this.CommandFile)) { string text = File.ReadAllText(this.CommandFile); this.Command = pattern_return.Split(text); } this.Session ??= new SshSession() { Server = this.Server, Port = this.Port, User = this.User, Password = this.Password, KeyboardInteractive = this.KeyboardInteractive, Effemeral = true, // コマンドパラメータでSession指定が無い場合、Effemeral。 }; var client = Session.CreateAndConnectSshClient(); if (client.IsConnected) { foreach (string line in Command) { SshCommand command = client.CreateCommand(line); command.Execute(); /* * List<string> splitResult = pattern_return.Split(command.Result).ToList(); * * if (splitResult.Count > 0 && string.IsNullOrEmpty(splitResult[0])) * { * splitResult.RemoveAt(0); * } * if (splitResult.Count > 0 && string.IsNullOrEmpty(splitResult[splitResult.Count - 1])) * { * splitResult.RemoveAt(splitResult.Count - 1); * } */ var splitResult = pattern_return.Split(command.Result).Trim(); if (string.IsNullOrEmpty(this.OutputFile)) { WriteObject(string.Join("\r\n", splitResult), true); } else { TargetDirectory.CreateParent(this.OutputFile); using (var sw = new StreamWriter(OutputFile, true, new UTF8Encoding(false))) { sw.Write(string.Join("\r\n", splitResult)); } } } } Session.CloseIfEffemeral(); }
public ImageDownloadProgress( ImageSourcesConfig imageSource, QualityGroupConfig qualityGroup, ImageDirConfig dir, FileSignature[] imagesOnline) { ImageSource = imageSource; QualityGroup = qualityGroup; Dir = dir; TargetDirectory = QualityGroup.TargetDirectory.ToAppRootedPath(); TargetSubdirectory = Dir.Subdir.Value == null ? TargetDirectory : TargetDirectory.Join(Dir.Subdir); MegaUrl = string.IsNullOrEmpty(Dir.MegaId) ? null : ImageSource.MegaPrefix + Dir.MegaId; var existingSignatures = readExistingSignatures() ?.ToDictionary(_ => _.Path); if (imagesOnline == null) { FilesDownloaded = existingSignatures; return; } FilesOnline = Dir.Subdir.Value == null ? imagesOnline.ToDictionary(_ => _.Path) : imagesOnline.Where(_ => Dir.Subdir.IsParentOf(_.Path)) .Select(_ => new FileSignature { Path = _.Path.RelativeTo(Dir.Subdir).Intern(true), Md5Hash = _.Md5Hash }) .ToDictionary(_ => _.Path); FilesDownloaded = new Dictionary <FsPath, FileSignature>(); FilesCorrupted = new Dictionary <FsPath, FileSignature>(); foreach (var onlineImage in FilesOnline.Values) { var existingSignature = existingSignatures?.TryGet(onlineImage.Path); if (existingSignature == null) { continue; } if (existingSignature.Md5Hash == onlineImage.Md5Hash) { FilesDownloaded.Add(existingSignature.Path, existingSignature); } else { FilesCorrupted.Add(existingSignature.Path, existingSignature); } } }
public void PopulateMatchingFiles() { const string filePattern = "*.txt"; var fileSet = new FileSet(TargetDirectory, _imageProviderFactory, filePattern); var expected = TargetDirectory.GetFiles(filePattern).Select(f => new FileNode(f, fileSet, BrowserResources.Properties.Resources.Image_File, _imageProviderFactory)); CollectionAssert.AreEquivalent(expected, fileSet); }
public void Init(string logDir, string logPreName) { _lock ??= new AsyncLock(); string today = DateTime.Now.ToString("yyyyMMdd"); _logFilePath = Path.Combine(logDir, $"{logPreName}_{today}.log"); TargetDirectory.CreateParent(_logFilePath); _writer = new StreamWriter(_logFilePath, _logAppend, new UTF8Encoding(false)); }
protected override void CalculateName() { if (TargetDirectory.Contains("bcl-test")) { Name = TestProject.Name; } else { base.CalculateName(); } }
/// <summary> /// Delete every child under this directory and leave the directory itself alone. /// </summary> public void Empty() { foreach (var file in TargetDirectory.GetFiles()) { file.Delete(); } foreach (var directory in TargetDirectory.GetDirectories()) { directory.Delete(true); } }
public ImageDownloadProgress( ImageSourcesConfig imageSource, QualityGroupConfig qualityGroup, ImageDirConfig dir, FileSignature[] imagesOnline) { ImageSource = imageSource; QualityGroup = qualityGroup; Dir = dir; TargetDirectory = QualityGroup.TargetDirectory.ToAppRootedPath(); TargetSubdirectory = TargetDirectory.AddPath(Dir.Subdirectory); MegaUrl = string.IsNullOrEmpty(Dir.MegaId) ? null : ImageSource.MegaPrefix + Dir.MegaId; GdriveUrl = string.IsNullOrEmpty(Dir.GdriveId) ? null: ImageSource.GdrivePrefix + Dir.GdriveId; var existingSignatures = readExistingSignatures() ?.ToDictionary(_ => _.Path, Str.Comparer); if (imagesOnline == null) { FilesDownloaded = existingSignatures; return; } FilesOnline = imagesOnline .Where(_ => _.IsRelativeTo(Dir.Subdirectory)) .Select(_ => _.AsRelativeTo(Dir.Subdirectory)) .ToDictionary(_ => _.Path, Str.Comparer); FilesDownloaded = new Dictionary <string, FileSignature>(Str.Comparer); FilesCorrupted = new Dictionary <string, FileSignature>(Str.Comparer); foreach (var onlineImage in FilesOnline.Values) { var existingSignature = existingSignatures?.TryGet(onlineImage.Path); if (existingSignature == null) { continue; } if (existingSignature.Md5Hash == onlineImage.Md5Hash) { FilesDownloaded.Add(existingSignature.Path, existingSignature); } else { FilesCorrupted.Add(existingSignature.Path, existingSignature); } } }
private void AcceptFolderToHistory(string folder) { if (folder.ValidateDirectory()) { TargetDirectory newDir = new TargetDirectory(folder); var historyExists = DirectoryHistory.Where(item => item.DirectoryName == newDir.DirectoryName).FirstOrDefault(); if (historyExists == null) { DirectoryHistory.Add(newDir); } } }
public void PopulateSubDirs() { var node = new DirectoryNode(TargetDirectory, null); Assert.IsFalse(node.IsExpanded); node.PopulateSubDirs(); var expected = TargetDirectory.GetDirectories().Select(d => new DirectoryNode(d, node)); CollectionAssert.AreEquivalent(expected, node.SubDirs); Assert.IsTrue(node.ThisLevelEnumerated); }
/// <summary> /// The actual functionality to download with optional hash verification /// subclasses that wish to return the contents of the downloaded file /// or do something else with it can override this instead of RunWithReturn. /// </summary> /// <param name="success"></param> /// <returns></returns> protected virtual NPath RunDownload(bool success) { Exception exception = null; var attempts = 0; bool result = false; var partialFile = TargetDirectory.Combine(Filename + ".partial"); TargetDirectory.EnsureDirectoryExists(); do { exception = null; if (Token.IsCancellationRequested) { break; } try { Logger.Trace($"Download of {Url} to {Destination} Attempt {attempts + 1} of {RetryCount + 1}"); using (var destinationStream = fileSystem.OpenWrite(partialFile, FileMode.Append)) { result = Downloader.Download(Logger, Url, destinationStream, (value, total) => { UpdateProgress(value, total); return(!Token.IsCancellationRequested); }); } if (result) { partialFile.Move(Destination); } } catch (Exception ex) { exception = ex; result = false; } } while (!result && attempts++ < RetryCount); if (!result) { Token.ThrowIfCancellationRequested(); throw new DownloadException("Error downloading file", exception); } return(Destination); }
private TargetDirectory _GetTargetDir(string entry, TargetDirectory default_target = TargetDirectory.Managed) { var target = default_target; if (InstallInSubdir != null && InstallInSubdir.Contains(entry)) { target = TargetDirectory.Subdir; } if (InstallInManaged != null && InstallInManaged.Contains(entry)) { target = TargetDirectory.Managed; } return(target); }
protected override void CalculateName() { if (TargetDirectory.Contains("bcl-test")) { Name = (TestProject.Name == "mscorlib")? "mscorlib" : TestProject.Name.Substring(TestProject.Name.IndexOf("BCL", StringComparison.Ordinal)); } else { base.CalculateName(); } if (MonoNativeInfo != null) { Name = Name + MonoNativeInfo.FlavorSuffix; } }
protected override void CalculateName() { if (TargetDirectory.Contains("bcl-test")) { Name = TestProject.Name; } else { base.CalculateName(); } if (MonoNativeInfo != null) { Name = Name + MonoNativeInfo.FlavorSuffix; } }
// If your activity returns a value, derive from CodeActivity<TResult> // and return the value from the Execute method. protected override void Execute(CodeActivityContext context) { if (!Directory.Exists(SourceDirectory.Get(context))) { throw new DirectoryNotFoundException(); } if (!Directory.Exists(TargetDirectory.Get(context))) { Directory.CreateDirectory(TargetDirectory.Get(context)); } foreach (var item in Directory.EnumerateFiles(SourceDirectory.Get(context))) { var filename = Path.GetFileName(item); var targetFile = Path.Combine(TargetDirectory.Get(context), filename); File.Copy(item, targetFile); } }
private Boolean CopyInstallationFiles() { txtProcessInfo.Text += Environment.NewLine + "Copiando arquivos de instalação..."; const String copyFail = "Falha ao copiar arquivos de instalação. "; TargetDirectory targetDir = new TargetDirectory(frontendInfo.installDirectory); // Prepara o diretório de destino ( faz algumas verificações / cria o diretório ) // Caso existam arquivos no diretório aborta e exibe mensagem de erro if (!targetDir.Mount()) { txtProcessInfo.Text += Environment.NewLine + copyFail + Environment.NewLine + targetDir.GetLastError(); return(false); } FileInfo[] sourceFiles = null; try // tenta obter os arquivos de origem (extraídos do instalador) { String tempFolder = PathFormat.Adjust(Path.GetTempPath()); String installationFilesDirectory = PathFormat.Adjust(tempFolder + "AccountingServerFiles"); File.Copy(installationFilesDirectory + "DataAccess.XML", installationFilesDirectory + @"WebFrontend\WebAccounting\App_Data\DataAccess.XML", true); File.Copy(installationFilesDirectory + "DataAccess.XML", installationFilesDirectory + @"WebFrontend\WebAdministrator\App_Data\DataAccess.XML", true); DirectoryInfo sourceDirectory = new DirectoryInfo(installationFilesDirectory + "WebFrontend"); sourceFiles = sourceDirectory.GetFiles("*.*", SearchOption.AllDirectories); } catch (Exception exc) { txtProcessInfo.Text += Environment.NewLine + copyFail + Environment.NewLine + exc.Message; return(false); } // Tenta copiar os arquivos para o diretório de instalação if (!targetDir.CopyFilesFrom(sourceFiles)) { txtProcessInfo.Text += Environment.NewLine + copyFail + Environment.NewLine + targetDir.GetLastError(); return(false); } // Se não houve nenhuma falha notifica sucesso return(true); }
public string svnUtil_Execute(string target) { var parameters = ""; if (target.valid()) { if (TargetDirectory.valid()) { parameters = " /directory:\"{0}\" {1}".format(TargetDirectory, parameters); } if (OutputTarget.valid()) { parameters = " /target:{0} {1}".format(OutputTarget, parameters); } parameters += "\"" + target + "\""; } "Executing .NET SDK's SvcUtil.exe tool with parameters: {0}".info(parameters); return(Processes.startProcessAsConsoleApplicationAndReturnConsoleOutput(SvnUtil_Exe, parameters)); }
protected override void CalculateName() { if (TargetDirectory.Contains("bcl-test")) { if (TestProject.Name.StartsWith("mscorlib", StringComparison.Ordinal)) { Name = TestProject.Name; } else { var bclIndex = TestProject.Name.IndexOf("BCL", StringComparison.Ordinal); // most of the BCL test are grouped, but there are a number that are not, in those cases remove the "{testype} Mono " prefix Name = (bclIndex == -1) ? TestProject.Name.Substring(TestProject.Name.IndexOf("Mono ", StringComparison.Ordinal) + "Mono ".Length) : TestProject.Name.Substring(bclIndex); } } else { base.CalculateName(); } }
public async Task <List <string> > GetExistingSongHashesAsync(bool hashExisting) { foreach (var songDir in TargetDirectory.GetDirectories()) { // Add missing directories to the Dictionary with an empty string for the hash value. if (!ExistingHashes.ContainsKey(songDir.FullName)) { ExistingHashes.Add(songDir.FullName, string.Empty); } } List <string> songsToHash; if (hashExisting) { songsToHash = ExistingHashes.Keys.ToList(); } else { songsToHash = ExistingHashes.Values.Where(hashData => string.IsNullOrEmpty(hashData)).ToList(); } await Task.Run(() => songsToHash.AsParallel().ForAll(h => { lock (_existingHashesLock) { if (ExistingHashes.ContainsKey(h)) { ExistingHashes[h] = GenerateHash(h); } else { ExistingHashes.Add(h, GenerateHash(h)); } } })).ConfigureAwait(false); return(ExistingHashes.Values.ToList()); }
public bool IsValidTarget(bool createIfMissing = true) { TargetDirectory.Refresh(); if (!TargetDirectory.Exists) { if (createIfMissing) { try { TargetDirectory.Create(); return(true); // If we were able to create the directory, it should be valid } #pragma warning disable CA1031 // Do not catch general exception types catch (IOException) { return(false); } #pragma warning restore CA1031 // Do not catch general exception types } else { return(false); } } try { var testDir = TargetDirectory.CreateSubdirectory("dirTest"); testDir.Refresh(); if (testDir.Exists) { testDir.Delete(); return(true); } } catch (IOException) { return(false); } return(false); }
public ExplorerAddressBarViewModel(IContainerExtension container, ImageViewParameter parameter) { var compositeDirectory = container.Resolve <ICompositeImageDirectory>(); var imageDirectory = compositeDirectory.ImageDirectries[parameter.ContentIndex]; // ディレクトリPATHをModelに通知するAction(子View用) _sendSerectedDirectoryPathAction = path => TargetDirectory.Value = path; VisibleTextBoxCommand = new DelegateCommand(() => IsVisibleDirectoryNode.TurnOff()); CollapsedTextBoxCommand = new DelegateCommand(() => IsVisibleDirectoryNode.TurnOn()); // directory from model imageDirectory .ObserveProperty(x => x.DirectoryPath) .Where(path => path != null) .Subscribe(path => UpdateViewsSource(path)) .AddTo(CompositeDisposable); // directory to model TargetDirectory .Subscribe(path => imageDirectory.SetSelectedDictionaryPath(DirectoryNode.EmendFullPathFromViewModel(path))) .AddTo(CompositeDisposable); // TextBox入力確定時のディレクトリ通知 TextEnterCommand = new DelegateCommand <string>(path => { if (Directory.Exists(path)) { TargetDirectory.Value = path; } IsVisibleDirectoryNode.TurnOn(); }); // キャンセル時は表示切替のみ(テキストボックスに入力中の文字は残している) TextCancelCommand = new DelegateCommand(() => IsVisibleDirectoryNode.TurnOn()); }
private async Task <IReadOnlyList <TargetDirectory> > ProcessFilesAsync(IReadOnlyList <FileRecord> records, CancellationToken cancellationToken) { var outputs = new Dictionary <string, TargetDirectory>(); foreach (var record in records) { var key = record.GetTargetKey(); if (!outputs.TryGetValue(key, out var targetDirectory)) { targetDirectory = await TargetDirectory.FromRecordAsync(_directories, record); outputs[key] = targetDirectory; } else { targetDirectory.SourceRecords.Add(record); } } return(outputs.Values.ToArray()); }
public Controller.Results Run(bool runDoseComparisons, bool runPDDComparisons, string SaveDirectory, object sender) { // Maximum number of CPU threads ParallelOptions cpuParallel = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }; //ParallelOptions cpuParallel = new ParallelOptions { MaxDegreeOfParallelism = 1 }; ParallelOptions parallel = cpuParallel; var resultsStrings = new ConcurrentBag <string>(); // Sets the system to use the correct resources without doubling down on GPU mathematics = new X86Mathematics(); parallel = cpuParallel; double progress = 0; #region safetyChecks try { _ = SourceDirectory.IsNormalized(); } catch (NullReferenceException) { throw new NullReferenceException("Source directory cannot be null"); } try { _ = TargetDirectory.IsNormalized(); } catch (NullReferenceException) { throw new NullReferenceException("Target directory cannot be null");; } if (SourceListStrings.Length <= 0) { throw new InvalidOperationException("There are no Dose files in the source directory Tree"); } if (TargetListStrings.Length <= 0) { throw new InvalidOperationException("There are no Dose files in the Target directory Tree"); } #endregion #region setup ((BackgroundWorker)sender).ReportProgress((int)progress, "Setup: Scanning Source Doses "); SourceDosesList = FileHandler.DoseFiles(SourceListStrings); ((BackgroundWorker)sender).ReportProgress((int)progress, "Setup: Scanning Source Plans "); SourcePlanList = FileHandler.PlanFiles(SourceListStrings); ((BackgroundWorker)sender).ReportProgress((int)progress, "Setup: Scanning Target Doses "); TargetDosesList = FileHandler.DoseFiles(TargetListStrings); ((BackgroundWorker)sender).ReportProgress((int)progress, "Setup: Scanning Target Plans "); TargetPlanList = FileHandler.PlanFiles(TargetListStrings); #endregion DosePairsList = new ConcurrentBag <MatchedDosePair>(); progress += 5; ((BackgroundWorker)sender).ReportProgress((int)progress, "Scanning Source Folder"); _ = Parallel.ForEach(SourceDosesList, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, doseFile => { doseFile.SetFieldName(SourcePlanList); }); progress += 5; ((BackgroundWorker)sender).ReportProgress((int)progress, "Scanning Target Folder"); _ = Parallel.ForEach(TargetDosesList, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, doseFile => { doseFile.SetFieldName(TargetPlanList); }); double ProgressIncrimentor = 10.0 / TargetDosesList.Count; ((BackgroundWorker)sender).ReportProgress((int)progress, "Matching"); // match each pair for analysis _ = Parallel.ForEach(TargetDosesList, cpuParallel, (dose) => { progress += ProgressIncrimentor; progress %= 100; ((BackgroundWorker)sender).ReportProgress((int)progress, "Matching"); var sourceDose = SourceDosesList.Find(x => x.MatchIdentifier == dose.MatchIdentifier); if (sourceDose != null) { Debug.WriteLine("matched " + dose.FileName + " and " + sourceDose.FileName); DosePairsList.Add(new MatchedDosePair(sourceDose, dose, Settings)); } }); if (DosePairsList.Count <= 0) { return(null); } progress = 39; ProgressIncrimentor = 30.0 / DosePairsList.Count; progress %= 100; ((BackgroundWorker)sender).ReportProgress((int)progress, "PDD Production"); //if (runPDDComparisons) if (true) { _ = Parallel.ForEach(DosePairsList, cpuParallel, pair => { progress += ProgressIncrimentor; progress %= 100; ((BackgroundWorker)sender).ReportProgress((int)progress, "PDD Production"); pair.GeneratePDD(); Debug.WriteLine("Saving " + pair.ChartTitle + " to " + SaveDirectory); try { SaveFile saveFile = new SaveFile(pair.ChartTitle, SaveDirectory); if (pair.IsReasonablyCentered()) { pair.PDDoutString = saveFile.Save(pair.SourcePDD, pair.TargetPDD, pair.ChartFileName, SaveDirectory, pair.ChartTitle, SourceAliasName, TargetAliasName); } else { pair.PDDoutString = "did not run"; } } catch (Exception) { Debug.WriteLine("Failed to save " + pair.ChartTitle); } }); progress = 69; } //fix for memory abuse is to limit the number of cores, Arbitrarily I have hard coded it to half the logical cores of the system. if (runDoseComparisons) { ProgressIncrimentor = 30.0 / DosePairsList.Count; _ = Parallel.ForEach(DosePairsList, parallel, pair => { progress += ProgressIncrimentor; progress %= 100; ((BackgroundWorker)sender).ReportProgress((int)progress, "Comparing " + progress); try { pair.Evaluate(mathematics); resultsStrings.Add(pair.ResultString); } // Will catch array misalignment problems catch (Exception e) { string temp = pair.Name + ",Was not Evaluated ,\n"; resultsStrings.Add(temp); Debug.WriteLine(temp); Debug.WriteLine(e.Message.ToString() ?? "\n"); Debug.Write(e.StackTrace.ToString() ?? "\n"); } }); } return(new Controller.Results(SourceAliasName, TargetAliasName, resultsStrings.ToArray(), MatchedDosePair.StaticResultHeader(Settings.Dtas))); }
//===================================================================== /// <summary> /// Add a new target directory to the collection /// </summary> /// <param name="targetDirectory">The target directory to add</param> public void Add(TargetDirectory targetDirectory) { targetDirectories.Add(targetDirectory); }
//===================================================================== /// <summary> /// Constructor /// </summary> /// <param name="assembler">A reference to the build assembler.</param> /// <param name="configuration">The configuration information</param> public ResolveConceptualLinksComponent(BuildAssembler assembler, XPathNavigator configuration) : base(assembler, configuration) { TargetDirectory targetDirectory; XPathExpression urlExp, textExp, linkTextExp; LinkType linkType = LinkType.None; string attribute, basePath; targetDirectories = new TargetDirectoryCollection(); cache = new Dictionary<string, TargetInfo>(cacheSize); attribute = configuration.GetAttribute("showBrokenLinkText", String.Empty); if(!String.IsNullOrEmpty(attribute)) showBrokenLinkText = Convert.ToBoolean(attribute, CultureInfo.InvariantCulture); foreach(XPathNavigator navigator in configuration.Select("targets")) { basePath = navigator.GetAttribute("base", String.Empty); if(String.IsNullOrEmpty(basePath)) base.WriteMessage(MessageLevel.Error, "Every targets " + "element must have a base attribute that specifies " + "the path to a directory of target metadata files."); basePath = Environment.ExpandEnvironmentVariables(basePath); if(!Directory.Exists(basePath)) base.WriteMessage(MessageLevel.Error, String.Format( CultureInfo.InvariantCulture, "The specified target " + "metadata directory '{0}' does not exist.", basePath)); attribute = navigator.GetAttribute("url", String.Empty); if(String.IsNullOrEmpty(attribute)) urlExp = XPathExpression.Compile("concat(/metadata/topic/@id,'.htm')"); else urlExp = this.CompileXPathExpression(attribute); attribute = navigator.GetAttribute("text", String.Empty); if(String.IsNullOrEmpty(attribute)) textExp = XPathExpression.Compile("string(/metadata/topic/title)"); else textExp = this.CompileXPathExpression(attribute); // EFW - Added support for linkText option attribute = navigator.GetAttribute("linkText", String.Empty); if(String.IsNullOrEmpty(attribute)) linkTextExp = XPathExpression.Compile("string(/metadata/topic/linkText)"); else linkTextExp = this.CompileXPathExpression(attribute); attribute = navigator.GetAttribute("type", String.Empty); if(String.IsNullOrEmpty(attribute)) base.WriteMessage(MessageLevel.Error, "Every targets " + "element must have a type attribute that specifies " + "what kind of link to create to targets found in " + "that directory."); try { linkType = (LinkType)Enum.Parse(typeof(LinkType), attribute, true); } catch(ArgumentException) { base.WriteMessage(MessageLevel.Error, String.Format(CultureInfo.InvariantCulture, "'{0}' is not a valid link type.", attribute)); } targetDirectory = new TargetDirectory(basePath, urlExp, textExp, linkTextExp, linkType); targetDirectories.Add(targetDirectory); } base.WriteMessage(MessageLevel.Info, String.Format(CultureInfo.InvariantCulture, "Collected {0} targets directories.", targetDirectories.Count)); }
//===================================================================== /// <inheritdoc /> public override void Initialize(XPathNavigator configuration) { TargetDirectory targetDirectory; XPathExpression urlExp, textExp, linkTextExp; ConceptualLinkType linkType = ConceptualLinkType.None; string attribute, basePath; targetDirectories = new TargetDirectoryCollection(); // This is a simple cache. If the cache size limit is reached, it clears the cache and starts over cache = new Dictionary<string, TargetInfo>(CacheSize); attribute = (string)configuration.Evaluate("string(showBrokenLinkText/@value)"); if(!String.IsNullOrWhiteSpace(attribute)) showBrokenLinkText = Convert.ToBoolean(attribute, CultureInfo.InvariantCulture); foreach(XPathNavigator navigator in configuration.Select("targets")) { basePath = navigator.GetAttribute("base", String.Empty); if(String.IsNullOrEmpty(basePath)) base.WriteMessage(MessageLevel.Error, "Every targets element must have a base attribute " + "that specifies the path to a directory of target metadata files."); basePath = Environment.ExpandEnvironmentVariables(basePath); if(!Directory.Exists(basePath)) base.WriteMessage(MessageLevel.Error, "The specified target metadata directory '{0}' " + "does not exist.", basePath); attribute = navigator.GetAttribute("url", String.Empty); if(String.IsNullOrEmpty(attribute)) urlExp = XPathExpression.Compile("concat(/metadata/topic/@id,'.htm')"); else urlExp = this.CompileXPathExpression(attribute); attribute = navigator.GetAttribute("text", String.Empty); if(String.IsNullOrEmpty(attribute)) textExp = XPathExpression.Compile("string(/metadata/topic/title)"); else textExp = this.CompileXPathExpression(attribute); // EFW - Added support for linkText option attribute = navigator.GetAttribute("linkText", String.Empty); if(String.IsNullOrEmpty(attribute)) linkTextExp = XPathExpression.Compile("string(/metadata/topic/linkText)"); else linkTextExp = this.CompileXPathExpression(attribute); attribute = navigator.GetAttribute("type", String.Empty); if(String.IsNullOrEmpty(attribute)) base.WriteMessage(MessageLevel.Error, "Every targets element must have a type attribute " + "that specifies what kind of link to create to targets found in that directory."); if(!Enum.TryParse<ConceptualLinkType>(attribute, true, out linkType)) base.WriteMessage(MessageLevel.Error, "'{0}' is not a valid link type.", attribute); targetDirectory = new TargetDirectory(basePath, urlExp, textExp, linkTextExp, linkType); targetDirectories.Add(targetDirectory); } base.WriteMessage(MessageLevel.Info, "Collected {0} targets directories.", targetDirectories.Count); }