public void CopyWithExclusionFilemaskAndFilemask() { //Arrange var channelSettings = new FromSettings() { Path = _fromFolder.FullName, FileMask = "*.zip", ExclusionFileMasks = new string[] { "EE_*_*_*1-0_18.xml", "*.XML" }, Type = ConfigChannelType.Local }; LocalChannel channel = new LocalChannel(_workingDirectory, channelSettings); //Act var result = channel.Copy(); //Assert var sourceFiles = new DirectoryInfo(channelSettings.Path).GetFiles(); Assert.AreEqual(1, result.Count()); Assert.IsTrue(result.Any(d => d.Name == "GG_TR_529900G3SW56SHYNPR95_01_20180316_0014_01.zip")); Assert.AreEqual(5, sourceFiles.Count()); Assert.IsTrue(sourceFiles.Any(d => d.Name == "EE_FEETRA_TPY_000451-0_18.xml")); Assert.IsTrue(sourceFiles.Any(d => d.Name == "EE_FEETRA_TPY_000452-0_18.xml")); Assert.IsTrue(sourceFiles.Any(d => d.Name == $"GG_TR_529900G3SW56SHYNPR95_01_20180316_0014_01.zip{Constants.FileExtensions.FileOps}")); Assert.IsTrue(sourceFiles.Any(d => d.Name == "EE_FEETRA_TPY_000454-0_18.XML")); Assert.IsTrue(sourceFiles.Any(d => d.Name == "GG_TR_529900G3SW56SHYNPR95_01_20180316_0014_01.zip")); }
public void FilemaskSettedToDoNotFetchAnyFiles() { //Arrange var channelSettings = new FromSettings() { Path = _fromFolder.FullName, FileMask = "*.txt", ExclusionFileMasks = new string[] { "*.XML", "*.zip" }, Type = ConfigChannelType.Local, IgnoreCaseSensitive = true }; LocalChannel channel = new LocalChannel(_workingDirectory, channelSettings); //Act var result = channel.Copy(); //Assert var sourceFiles = new DirectoryInfo(channelSettings.Path).GetFiles(); Assert.AreEqual(0, result.Count()); Assert.AreEqual(4, sourceFiles.Count()); Assert.IsTrue(sourceFiles.Any(d => d.Name == "EE_FEETRA_TPY_000451-0_18.xml")); Assert.IsTrue(sourceFiles.Any(d => d.Name == "EE_FEETRA_TPY_000452-0_18.xml")); Assert.IsTrue(sourceFiles.Any(d => d.Name == "EE_FEETRA_TPY_000454-0_18.XML")); Assert.IsTrue(sourceFiles.Any(d => d.Name == "GG_TR_529900G3SW56SHYNPR95_01_20180316_0014_01.zip")); }
static void Main() { var currentPath = Directory.GetCurrentDirectory(); // Get the most recently accessed solution file or return null if none var slnfile = new DirectoryInfo(currentPath).GetFiles() .Where(x => x.Extension == ".sln") .OrderBy(x => x.LastAccessTimeUtc) .FirstOrDefault(); if (slnfile == null) { Console.WriteLine("No .sln file found"); return; } // Prefer VS2019 then downgrade to VS2017 if not there //var devenvpath = @"C:\Program Files (x86)\Microsoft Visual Studio\2017\"; var devenvpath = @"C:\Program Files (x86)\Microsoft Visual Studio\"; var vsDirectoryVersion = new DirectoryInfo(devenvpath).GetDirectories(); if (vsDirectoryVersion.Any(x => x.Name == "2019")) { devenvpath += @"2019\"; } else if (vsDirectoryVersion.Any(x => x.Name == "2017")) { devenvpath += @"2017\"; } else { Console.WriteLine($"Neither Visual Studio Community nor Enterprise can be found in {devenvpath}"); return; } var vsDirectory = new DirectoryInfo(devenvpath).GetDirectories(); // Where is VS - Community or Enterprise? if (vsDirectory.Any(x => x.Name == "Community")) { devenvpath += @"Community\Common7\IDE\"; } else if (vsDirectory.Any(x => x.Name == "Enterprise")) { devenvpath += @"Enterprise\Common7\IDE\"; } else { Console.WriteLine($"Neither Visual Studio Community nor Enterprise can be found in {devenvpath}"); return; } // Call VS in a new process and return to the shell Console.WriteLine($"{slnfile.Name,-20} : Opening this file! "); var proc = new Process(); proc.StartInfo.FileName = devenvpath + "devenv"; proc.StartInfo.Arguments = currentPath + @"\" + slnfile.Name; proc.Start(); }
/// <summary> /// Determines if the given file exists in the given folder /// </summary> /// <returns></returns> protected bool FolderNotEmpty(string relFolderPath, string fileTypes = "*.*", Anomalies anomalies = null) { var dirPath = Path.Combine(this.TargetDir, relFolderPath); var exists = Directory.Exists(dirPath); if (!exists) { if (anomalies != null) { anomalies.ExpectedFiles.Add(relFolderPath); } return(false); } else { var filesInFolder = new DirectoryInfo(dirPath).GetFiles(fileTypes); if (!filesInFolder.Any()) { if (anomalies != null) { anomalies.ExpectedFiles.Add(fileTypes); } } return(filesInFolder.Any()); } }
public void TryEmitTraces_should_output_the_artifact_of_the_test_to_the_specified_directory() { // Arrange var configuration = Configuration.Create().WithNumberOfIterations(200). WithMaxSchedulingSteps(200). WithParallelBugFindingTasks(5). WithRandomSchedulingSeed(); var testArtifact = configuration.CreateTestArtifact(MethodBase.GetCurrentMethod(), new DateTime(2017, 10, 10)); var engine = new CompositeBugFindingEngine(configuration, runtimeHost => { var m1 = runtimeHost.New(MachineInterface.Sender <M1.ISender>().Bundler <M1.IBundler>().Receiver <M1.BugReceiver>()); m1.Configure(new Notify()); }); engine.Run(); // Act engine.TryEmitTraces(testArtifact.Directory, testArtifact.TraceNameBase); // Assert Assert.GreaterOrEqual(engine.TestReport.NumOfFoundBugs, 1); var traceFileInfos = new DirectoryInfo(testArtifact.Directory).EnumerateFiles(); Assert.IsTrue(traceFileInfos.Any(_ => Regex.IsMatch(_.Name, $@"{ testArtifact.TraceNameBase }_\d+_\d+\.pstrace"))); Assert.IsTrue(traceFileInfos.Any(_ => Regex.IsMatch(_.Name, $@"{ testArtifact.TraceNameBase }_\d+_\d+\.schedule"))); Assert.IsTrue(traceFileInfos.Any(_ => Regex.IsMatch(_.Name, $@"{ testArtifact.TraceNameBase }_\d+_\d+\.txt"))); }
public void TestReportAndPackageIsCreatedRunningN5Archive() { // Establish/clear needed paths: string workingDirectoryPath = AppDomain.CurrentDomain.BaseDirectory; string testDataDirectoryPath = Path.Combine(workingDirectoryPath, "TestData"); string metadataFilePath = Path.Combine(testDataDirectoryPath, "metadata.txt"); string archiveDirectoryPath = Path.Combine(testDataDirectoryPath, "N5-archive"); string outputDirectoryPath = Path.Combine(testDataDirectoryPath, "output"); // Clear needed paths: File.Delete(metadataFilePath); if (Directory.Exists(outputDirectoryPath)) { Directory.Delete(outputDirectoryPath, true); } Directory.CreateDirectory(outputDirectoryPath); // Run commands and store results: Program.Main(new[] { "-g", metadataFilePath, "-p", testDataDirectoryPath }); bool metadataWasGenerated = File.Exists(metadataFilePath); Program.Main(new[] { "-a", archiveDirectoryPath, "-t", "noark5", "-m", metadataFilePath, "-p", testDataDirectoryPath, "-o", outputDirectoryPath }); FileSystemInfo[] outputDirectoryItems = new DirectoryInfo(outputDirectoryPath).GetFileSystemInfos(); bool testReportWasCreated = outputDirectoryItems.Any(item => item.Name.StartsWith("Arkaderapport")); bool packageWasCreated = outputDirectoryItems.Any(item => item.Name.StartsWith("Arkadepakke")); // Clean up: File.Delete(metadataFilePath); Directory.Delete(outputDirectoryPath, true); ArkadeProcessingArea.Destroy(); // Control results: metadataWasGenerated.Should().BeTrue(); testReportWasCreated.Should().BeTrue(); packageWasCreated.Should().BeTrue(); }
private static void CopyFiles(string sourceFolder, string targetFolder) { var targetFiles = new DirectoryInfo(targetFolder).GetFiles(); foreach (var fileInfo in targetFiles) { var sourceFile = new FileInfo(Path.Combine(sourceFolder, fileInfo.Name)); if (sourceFile.Exists) { Console.WriteLine($"{sourceFile.Name} -> {fileInfo.FullName}"); sourceFile.CopyTo(fileInfo.FullName, true); } } foreach (var dllFile in targetFiles.Where(x => x.Extension == ".dll")) { var pdbName = Path.GetFileNameWithoutExtension(dllFile.Name) + ".pdb"; if (targetFiles.Any(x => x.Name == pdbName)) { continue; } var sourcePdbFile = new FileInfo(Path.Combine(sourceFolder, pdbName)); if (sourcePdbFile.Exists) { var targetFile = Path.Combine(targetFolder, pdbName); Console.WriteLine($"{sourcePdbFile.Name} -> {targetFile}"); sourcePdbFile.CopyTo(targetFile, true); } } }
private void ValidateTables(IEnumerable <SqlTableViewModel> sqlTables) { FileInfo[] restRepositories = null; FileInfo[] repositories = null; FileInfo[] linqRepositories = null; var models = new DirectoryInfo(!string.IsNullOrEmpty(_solution.ModelProjectConfiguration.GeneratedCodeFolder) ? Path.Combine(_solution.ModelProjectConfiguration.ProjectFolder, _solution.ModelProjectConfiguration.GeneratedCodeFolder) : _solution.ModelProjectConfiguration.ProjectFolder).GetFiles(); if (_solution.DataProjectConfiguration != null && !string.IsNullOrEmpty(_solution.DataProjectConfiguration.ProjectPath)) { repositories = new DirectoryInfo(!string.IsNullOrEmpty(_solution.DataProjectConfiguration.GeneratedCodeFolder) ? Path.Combine(_solution.DataProjectConfiguration.ProjectFolder, _solution.DataProjectConfiguration.GeneratedCodeFolder) : _solution.DataProjectConfiguration.ProjectFolder).GetFiles(); } if (_solution.LinqProjectConfiguration != null && !string.IsNullOrEmpty(_solution.LinqProjectConfiguration.ProjectPath)) { linqRepositories = new DirectoryInfo(!string.IsNullOrEmpty(_solution.LinqProjectConfiguration.GeneratedCodeFolder) ? Path.Combine(_solution.LinqProjectConfiguration.ProjectFolder, _solution.LinqProjectConfiguration.GeneratedCodeFolder) : _solution.DataProjectConfiguration.ProjectFolder).GetFiles(); } if (_solution.RestProjectConfiguration != null && !string.IsNullOrEmpty(_solution.RestProjectConfiguration.ProjectPath)) { restRepositories = new DirectoryInfo(!string.IsNullOrEmpty(_solution.RestProjectConfiguration.GeneratedCodeFolder) ? Path.Combine(_solution.RestProjectConfiguration.ProjectFolder, _solution.RestProjectConfiguration.GeneratedCodeFolder) : _solution.RestProjectConfiguration.ProjectFolder).GetFiles(); } foreach (var table in sqlTables) { table.SingularName = _pluralizationServices.Singularize(table.TableName); table.IsModelValid = models.Any(e => e.Name == table.GetModelFileName()); table.IsRepositoryInterfaceValid = repositories?.Any(e => e.Name == table.GetRepsotioryInterfaceFileName()) ?? false; table.IsLinqRepositoryValid = linqRepositories?.Any(e => e.Name == table.GetRepsotioryFileName()) ?? false; table.IsRestRepositoryValid = restRepositories?.Any(e => e.Name == table.GetRepsotioryFileName()) ?? false; } }
private static StandaloneAzureBlobResultSegment FindFilesFlattened( string containerDirectory, string searchDirectory, string prefix, int?maxResults, int numberToSkip) { var files = new DirectoryInfo(searchDirectory ?? containerDirectory).EnumerateFiles((prefix ?? "") + "*", SearchOption.AllDirectories) .Where(f => !(f.DirectoryName ?? "").EndsWith(".meta")) .Skip(numberToSkip) .Take(maxResults.HasValue ? maxResults.Value : Int32.MaxValue) .Select(f => new StandaloneAzureBlockBlob( containerDirectory, f.FullName.Substring(containerDirectory.Length + 1))) .ToList(); var resultSegment = new StandaloneAzureBlobResultSegment( files, files.Any() ? new BlobContinuationToken { NextMarker = DetermineNextMarker(numberToSkip, files.Count) } : null); return(resultSegment); }
public static UserConfigOptionsModel LoadConfigData() { var response = new UserConfigOptionsModel(); var configFilename = ConfigurationManager.AppSettings["UserConfigFileName"]; var currentDir = Directory.GetCurrentDirectory(); var di = new DirectoryInfo(currentDir).GetFiles().Where(x => x.Name == configFilename).ToList(); if (!di.Any()) { response = GetDefaultUserOptions(currentDir); using (var fileStream = new FileStream(String.Format("{0}\\{1}", currentDir, configFilename), FileMode.Create)) using (var fileWriter = new StreamWriter(fileStream)) { fileWriter.Write(response.ToXML()); } } else { using (var fileStream = new FileStream(String.Format("{0}\\{1}", currentDir, configFilename), FileMode.Open)) using (var fileReader = new StreamReader(fileStream)) { var xmlData = fileReader.ReadToEnd(); response = UserConfigOptionsModel.LoadFromXMLString(xmlData); } } return(response); }
private TestResults RunTests(string directory) { var files = new DirectoryInfo(directory).GetFiles("*_tests.ei"); if (!files.Any()) { throw new InvalidOperationException("No tests found!"); } var failed = new List <FailedTest>(); var passed = new List <string>(); foreach (var file in files) { try { RunScript(file.FullName); passed.Add(file.Name); } catch (Exception e) { failed.Add(new FailedTest(file.Name, e)); } } return(new TestResults(passed, failed)); }
/// <summary> /// 获取已安装.NET Framework 版本 /// </summary> /// <returns></returns> public static string GetDotNetVersions() { DirectoryInfo[] directories = new DirectoryInfo(Environment.SystemDirectory + @"\..\Microsoft.NET\Framework").GetDirectories("v?.?.*"); string list = directories.Any() ? directories.Aggregate("", (current, info2) => current + (info2.Name.Substring(1) + "、")) : "暂无"; return(list.Substring(0, list.Length - 1)); }
private List <FileInfo> GetShpFiles(string directory) { var files = new DirectoryInfo(directory).GetFiles(); var list = new List <FileInfo>(); _fileGroups = new Dictionary <string, IList <string> >(); if (files != null && files.Any()) { foreach (var file in files) { var ext = file.Extension.ToLower(); if (ext == ".shp" || ext == ".shx" || ext == ".dbf" || ext == ".prj") { list.Add(file); var key = file.Name.ToLower().Replace(ext, ""); if (!_fileGroups.ContainsKey(key)) { _fileGroups.Add(key, new List <string> { file.FullName }); } else { _fileGroups[key].Add(file.FullName); } } } } return(list); }
private void Initialize() { var rootDir = Path.Combine("..", "results"); if (!Directory.Exists(rootDir)) { return; } var detectors = new DirectoryInfo(rootDir).GetDirectories().Select(d => d.ToString()).ToList(); if (!detectors.Any()) { return; } foreach (var detector in detectors) { _detectors.Add(detector); _results.Add(detector, new Dictionary <string, Dictionary <DateTime, double> >()); var path = Path.Combine("..", "results", detector, detector + "_standard_scores.csv"); if (!File.Exists(path)) { continue; } using (var sr = new StreamReader(path)) { var head = sr.ReadLine().Split(',').ToList(); var thresholdColumnIndex = head.IndexOf("Threshold"); var threshold = double.Parse(sr.ReadLine().Split(',')[thresholdColumnIndex]); _thresholds.Add(detector, threshold); } } }
private static List <KeyValuePair <string, string> > FindAviableMsBuildsIn(string folder) { var result = new List <KeyValuePair <string, string> >(); folder = Path.Combine(folder, "MSBuild"); if (!Directory.Exists(folder)) { return(result); } var subDirs = new DirectoryInfo(folder).GetDirectories().OrderByDescending(x => x.Name); foreach (var subDir in subDirs) { var currentVersion = subDir.Name; if (!Helper.IsVisualStudioVersion(currentVersion)) { continue; } var bin = Path.Combine(subDir.FullName, "Bin"); if (!Directory.Exists(bin)) { continue; } var matches = new DirectoryInfo(bin).GetFiles("msbuild.exe").ToList(); if (matches.Any()) { result.Add(new KeyValuePair <string, string>(currentVersion, matches.Last().FullName)); } } return(result); }
public IEnumerable <string> GetReferencePaths() { if (Assembly.IsDynamic) { return(Enumerable.Empty <string>()); } if (Dependency.Count > 0) { List <string> dependencyFiles = new List <string>(); foreach (var libaray in Dependency) { foreach (var item in libaray.Assemblies) { var files = new DirectoryInfo(Path.GetDirectoryName(Assembly.Location)).GetFiles(Path.GetFileName(item)); if (files.Any()) { dependencyFiles.AddRange(files.Select(m => m.FullName)); } } } if (dependencyFiles.Any()) { dependencyFiles.Add(Assembly.Location); return(dependencyFiles); } return(Dependency.SelectMany(library => library.ResolveReferencePaths()).Concat(new[] { Assembly.Location })); } return(new[] { Assembly.Location }); }
// This is only used by build artifact. This isn't a officially supported artifact type in RM public async Task DownloadArtifactAsync(IExecutionContext executionContext, IHostContext hostContext, ArtifactDefinition artifactDefinition, string dropLocation, string localFolderPath) { ArgUtil.NotNull(artifactDefinition, nameof(artifactDefinition)); ArgUtil.NotNull(executionContext, nameof(executionContext)); ArgUtil.NotNullOrEmpty(localFolderPath, nameof(localFolderPath)); ArgUtil.NotNullOrEmpty(dropLocation, nameof(dropLocation)); var trimChars = new[] { '\\', '/' }; var relativePath = artifactDefinition.Details.RelativePath; // If user has specified a relative folder in the drop, change the drop location itself. dropLocation = Path.Combine(dropLocation.TrimEnd(trimChars), relativePath.Trim(trimChars)); var fileSystemManager = hostContext.CreateService <IReleaseFileSystemManager>(); List <string> filePaths = new DirectoryInfo(dropLocation).EnumerateFiles("*", SearchOption.AllDirectories) .Select(path => path.FullName) .ToList(); if (filePaths.Any()) { foreach (var filePath in filePaths) { var filePathRelativeToDrop = filePath.Replace(dropLocation, string.Empty).Trim(trimChars); using (var fileReader = fileSystemManager.GetFileReader(filePath)) { await fileSystemManager.WriteStreamToFile(fileReader.BaseStream, Path.Combine(localFolderPath, filePathRelativeToDrop)); } } } else { executionContext.Warning(StringUtil.Loc("RMNoArtifactsFound", relativePath)); } }
public static List <MyWidgetInfo> GetMy(string tenant, int userId, string scope) { var widgets = new List <MyWidgetInfo>(); string container = PathMapper.MapPath($"{WidgetLocation.Replace("{tenant}", tenant)}/{scope}/{userId}"); if (!Directory.Exists(container)) { return(widgets); } var files = new DirectoryInfo(container).GetFiles("*.json"); if (!files.Any()) { return(widgets); } foreach (var file in files) { string contents = File.ReadAllText(file.FullName, new UTF8Encoding(false)); var info = JsonConvert.DeserializeObject <MyWidgetInfo>(contents); widgets.Add(info); } return(widgets); }
private static bool HasDotGitSubDirectory(string directory) { var subDirectories = new DirectoryInfo(directory).GetDirectories() .Where(x => (x.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden).ToArray(); return(subDirectories.Any(subDir => subDir.Name.Equals(".git"))); }
public async Task WritesAStreamAsync() { const string testoutputfilename = "test"; string dir = Config.GetDefaultDownloadDirectory(); var files = new DirectoryInfo(dir).GetFiles().Where(n => n.Name == testoutputfilename + ".zip"); var fileInfos = files as IList <FileInfo> ?? files.ToList(); if (fileInfos.Any()) { foreach (var file in fileInfos) { File.Delete(file.FullName); } } FileInfo spyfile = new FileInfo(dir + @"\SPY_Companies.csv"); AllDataDownloader dl = new AllDataDownloader(spyfile, null) { ZipOutput = true }; await dl.WriteStreamAsync(DateTime.Now, "Test Data", dir, testoutputfilename); files = new DirectoryInfo(dir).GetFiles().Where(n => n.Name == testoutputfilename + ".zip"); Assert.IsTrue(files.Any()); }
private static IEnumerable <string> DownloadFiles(string localPath, IFtpClient client, string directoryFullPath, DateTime beginTime) { if (!Directory.Exists(localPath)) { Directory.CreateDirectory(localPath); } var localFiles = new DirectoryInfo(localPath).GetFiles("*.*"); var remoteFiles = client.GetListing(directoryFullPath).Where(p => p.Modified >= beginTime); var downloads = new List <string>(); var localFullPaths = new List <string>(); foreach (var remoteFile in remoteFiles) { if (remoteFile.Size <= 0) { continue; } if (localFiles.Any(p => p.Name == remoteFile.Name)) { var localFile = localFiles.Single(p => p.Name == remoteFile.Name); if (localFile.Length == remoteFile.Size) { continue; } } downloads.Add(remoteFile.FullName); localFullPaths.Add(Path.Combine(localPath, remoteFile.Name)); } client.DownloadFiles(localPath, downloads); Console.WriteLine($"Download {downloads.Count} records from {directoryFullPath}..."); return(localFullPaths); }
private void StartDirectoryWatch() { exportFolderWatcherTimer = new System.Threading.Timer(o => { lock (tempLockObject) { try { if (!ExchangeServiceProvider.CookieExist()) { return; } var newFiles = new DirectoryInfo(directoryPath).GetFiles("*").Where(p => !p.Extension.Contains(".tmp")).ToList(); if (newFiles.Any()) { var infos = newFiles.Select(p => new FileInformation() { FullName = p.FullName, Name = p.Name, Content = File.ReadAllBytes(p.FullName), TempPath = Path.ChangeExtension(p.FullName, $"{p.Extension}.{Guid.NewGuid().ToString().Replace("-", string.Empty)}.tmp") }).ToList(); while (infos.Sum(p => p.Content.Length) > 25165824) { infos = infos.OrderByDescending(p => p.Content.Length).Skip(1).ToList(); } infos.ForEach(file => { try { File.Move(file.FullName, file.TempPath); } catch (Exception ex) { } }); ExportFilesOnCreated(infos); } } catch (Exception ex) { } } }, null, 0, 100); cookieTimer = new System.Threading.Timer(o => { if (!ExchangeServiceProvider.CookieExist() || ExchangeServiceProvider.IsInProgress()) { return; } ExchangeServiceProvider.ConnectionTest(); }, null, 0, 5 * 60 * 1000); }
internal static void CleanupSaves() { try { Log("Cleaning mod saves"); var modSaves = new DirectoryInfo(modSettings.SaveDirectory).GetFiles(); var slots = UnityGameInstance.BattleTechGame.SaveManager.GameInstanceSaves.GetAllSlots(); var gameSaves = new List <string>(); foreach (var slot in slots) { gameSaves.Add(slot.FileID.Substring(5)); } // if the scorch file has no match save file, delete it // legacy cleanup for 3.0 // 2nd save would be required to get rid of both 3.0 and 3.0.1 files for a missing save // this block would only be called once // TODO remove this eventually because how much do we care about legacy mod save data if (modSaves.Any(x => x.Name.EndsWith(".scorches.json"))) { // no point going through the footsteps separately so just assume they're in pairs foreach (var modSave in modSaves.Where(file => file.Name.EndsWith(".scorches.json"))) { // trim off .scorches.json (14 characters) var filename = modSave.Name.Substring(0, modSave.Name.Length - 14); if (!gameSaves.Contains(filename)) { Log($"{filename} is no longer present, deleting associated mod save data"); modSave.Delete(); var footstepsFilename = modSave.ToString().Replace(".scorches", ".footsteps"); new FileInfo(footstepsFilename).Delete(); } } } else { // cleanup for single file design 3.0.1 foreach (var modSave in modSaves) { // trim off .json (5 characters) var filename = modSave.Name.Substring(0, modSave.Name.Length - 5); if (!gameSaves.Contains(filename)) { Log($"{filename} is no longer present, deleting associated mod save data"); modSave.Delete(); } } } } catch (Exception ex) { Log(ex); } }
private void RenameAndSetImagesInDocument(LawSyncDocumentDetail lawDocument) { try { var lawDocumentId = lawDocument.DocumentControlNumber; var files = new DirectoryInfo(lawDocument.ImagesFolderPath).GetFiles( string.Format("{0}{1}*", lawDocumentId, Constants.RedactItPagingNameFormat)); if (!files.Any()) { return; } var convertedImages = new List <ConvertedImage>(); // hold the list of converted iamges. foreach (var file in files) { if (String.IsNullOrEmpty(file.Name)) { continue; } var fileExtenstion = Path.GetExtension(file.Name); var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file.Name); var currentPage = fileNameWithoutExtension.Replace(lawDocumentId, "").Replace(Constants.RedactItPagingNameFormat, ""); int pageNumber; if (!int.TryParse(currentPage, out pageNumber)) { continue; } var imageStartingNumber = (lawDocument.ImageStartingNumber + 1) + pageNumber; var newFileName = string.Format("{0:D3}", imageStartingNumber) + fileExtenstion; var image = Path.Combine(lawDocument.ImagesFolderPath, newFileName); File.Move(file.FullName, image); var evImageRelativePath = image.Replace(_imageArchiveDirectory, string.Empty); evImageRelativePath = evImageRelativePath.StartsWith(@"\") ? evImageRelativePath.Remove(0, 1) : evImageRelativePath; convertedImages.Add(new ConvertedImage { PageNo = pageNumber, RelativePath = evImageRelativePath }); } // DEVBug 169433: Page order mess up for LAW Sync reprocess. For example the first page in LAW is not the first page in EV NNV viewer, // e.g. the first page is 701.tif instead of 001.tif. // To solve this, we need to sort the image by page Number var imagePaths = convertedImages.OrderBy(o => o.PageNo).Select(o => o.RelativePath).ToList(); if (lawDocument.ProducedImages == null) { lawDocument.ProducedImages = new List <string>(); } lawDocument.ProducedImages.AddRange(imagePaths); } catch (Exception ex) { //continue the image process with out rename images ex.Trace().Swallow(); ReportToDirector(ex); } }
static void Main(params string[] args) { try { bool createNew; var m = new Mutex(true, Application.ProductName, out createNew); //设置应用程序处理异常方式:ThreadException处理 Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); //处理UI线程异常 Application.ThreadException += Application_ThreadException; //处理非UI线程异常 AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("zh-CN"); Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("zh-CN"); DirectoryInfo[] directories = new DirectoryInfo(Environment.SystemDirectory + @"\..\Microsoft.NET\Framework").GetDirectories("v?.?.*"); bool flag = directories.Any(info2 => Convert.ToDouble(info2.Name.Substring(1, 3)) >= 3.5); if (!flag) { XtraMessageBox.Show(@"请先安装Framework3.5或其更高版本!", @"提示:", MessageBoxButtons.OK, MessageBoxIcon.Warning); Application.Exit(); } else { if (createNew) { try { Application.AddMessageFilter(Filter); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FormLogin()); //Application.Run(new Main_Frm()); } catch { //WatchDog.Fatal("系统异常2:" + ex.StackTrace + "\r\n" + ex.InnerException, ex); } } else { XtraMessageBox.Show(@"您已经在运行<<YJL_ECG心电图系统>>", @"YJL_ECG心电图系统提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } } } catch { //WatchDog.Fatal("系统异常:" + ex.StackTrace + "\r\n" + ex.InnerException, ex); } }
private IEnumerable <string> DownloadDir(string dir) { var list = ListDirectory(dir + "//" + DateTime.Now.ToString("yyyyMMdd")); var remoteFiles = list as IList <string> ?? list.ToList(); if (!Directory.Exists(dir + "//" + DateTime.Now.ToString("yyyyMMdd"))) { Directory.CreateDirectory(dir + "//" + DateTime.Now.ToString("yyyyMMdd")); } var localFiles = new DirectoryInfo(dir + "//" + DateTime.Now.ToString("yyyyMMdd")).GetFiles("*.*"); return(remoteFiles.Select(remoteFile => { var remoteFileSize = GetFileSize(dir + "//" + remoteFile); if (remoteFileSize <= 0) { return null; } if (localFiles.Any(p => p.Name == remoteFile)) { var localFile = localFiles.Single(p => p.Name == remoteFile); if (localFile.Length == remoteFileSize) { return null; } localFile.Delete(); } DownloadFile(dir + "//" + remoteFile); return remoteFile; })); //foreach (var remoteFile in remoteFiles) //{ // var remoteFileSize = GetFileSize(dir + "//" + remoteFile); // if (remoteFileSize > 0) // { // if (localFiles.Any(p => p.Name == remoteFile)) // { // var localFile = localFiles.Single(p => p.Name == remoteFile); // if (localFile.Length == remoteFileSize) // continue; // localFile.Delete(); // } // DownloadFile(dir + "//" + remoteFile); // } // else // { // remoteFiles.Remove(remoteFile); // } //} //return remoteFiles; }
public static int ArchiveOldLogs(int logDays, int zipDays) { int numberOfZipped = 0; // Get list of archives. var lastArchiveList = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + "Logs\\").GetFiles() .Where(f => f.LastWriteTime > DateTime.Now.Subtract(TimeSpan.FromDays(logDays)) && f.Extension.ToLower() == ".zip") .OrderByDescending(f => f.LastWriteTime); // If there are no archives, or latest archive is older than the number of days for log archiving in settings, create archive. if (!lastArchiveList.Any() || (lastArchiveList.Any() && lastArchiveList.First().LastWriteTime <= DateTime.Now.Subtract(TimeSpan.FromDays(logDays)))) { var list = (from f in new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + "Logs\\").GetFiles() where f.LastWriteTime < DateTime.Now.Subtract(TimeSpan.FromDays(logDays)) && f.Extension.ToLower() == ".log" select f).ToList(); numberOfZipped = list.Count; if (numberOfZipped > 0) { var fromDate = list.First().Name.Split('.')[1].Substring(3); var toDate = list.Last().Name.Split('.')[1].Substring(3); using (FileStream zipToOpen = new FileStream(AppDomain.CurrentDomain.BaseDirectory + $"Logs\\Logs-{fromDate}-{toDate}.zip", FileMode.Create)) { using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)) { foreach (var file in list) { ZipArchiveEntry newEntry = archive.CreateEntry(file.Name); using (StreamWriter writer = new StreamWriter(newEntry.Open())) { writer.Write(file.OpenText().ReadToEnd()); } } } } } } DeleteOldArchives(lastArchiveList, zipDays); return(numberOfZipped); }
public static IEnumerable <string> CopyLatest(string from, string to) { var targets = new DirectoryInfo(to).GetFiles(); var filesToCopy = new DirectoryInfo(from) .GetFiles() .Where(f => targets.Any(t => t.Name == f.Name) && targets.First(t => t.Name == f.Name).LastWriteTime < f.LastWriteTime) .ToList(); filesToCopy .ForEach(f => File.Copy(f.FullName, Path.Combine(to, f.Name), true)); return(filesToCopy.Select(f => f.Name)); }
private static LastDownalodResult getImage(string dir) { var images = new DirectoryInfo(dir).GetFiles("*.jpg"); if (!images.Any()) { return(null); } FileInfo lastImage; var useRandomImages = ConfigSetGet.GetConfigData("UseRandomImages"); if (!string.IsNullOrWhiteSpace(useRandomImages) && useRandomImages.Equals("true", StringComparison.InvariantCultureIgnoreCase)) { var rnd = new Random(); lastImage = images[rnd.Next(0, images.Length - 1)]; } else { lastImage = images.OrderByDescending(fileInfo => fileInfo.LastWriteTime).FirstOrDefault(); if (lastImage == null) { return(null); } } var image = lastImage.FullName; var xmlFile = $"{image}.xml"; var copyright = ""; if (!File.Exists(xmlFile)) { xmlFile = $"{image.Split('_').First()}.xml"; } if (File.Exists(xmlFile)) { try { var info = XmlUtils.FromXmlFile <images>(xmlFile); copyright = info.image.copyright; } catch { } } return(new LastDownalodResult { ImageFileName = image, Copyright = copyright, XmlFileName = "" }); }
public void TestGenerateConfigurationFilesFromFolderAndMergeOutput() { var configFiles = _copyOfSchemasFolder.GetFiles("*.config", SearchOption.AllDirectories); Assert.IsFalse(configFiles.Any()); Assert.IsNotNull(_copyOfSchemasFolder); Assert.IsTrue(_copyOfSchemasFolder.Exists); var mergedConfigFilename = "merged.config"; var programResult = LinqToXsd.Program.Main(new[] { "config", _copyOfSchemasFolder.FullName, "-e", "-o", mergedConfigFilename }); Assert.IsTrue(programResult == 0); configFiles = new DirectoryInfo(Environment.CurrentDirectory) .GetFiles("*.config", SearchOption.AllDirectories); Assert.IsTrue(configFiles.Any()); Assert.IsTrue(configFiles.Length > 1); Assert.IsTrue(configFiles.Any(c => c.Name == mergedConfigFilename)); }