public void DefaultGroupLogFileNameTest() { string Expected = $"{Environment.MachineName}.Group.20201107.log"; string Actual = FileNameGenerator.GenerateFileName("AppName", s_Nov7Local, "Group", FileLoggerOptions.DefaultGroupLogFileNamePattern); Assert.AreEqual(Expected, Actual); }
public void Confirm() { var format = SelectedDownloadOption.Format; // Prompt user for output file path var filter = $"{format.ToUpperInvariant()} file|*.{format}"; var defaultFileName = FileNameGenerator.GenerateFileName(_settingsService.FileNameTemplate, Video, format); var filePath = _dialogManager.PromptSaveFilePath(filter, defaultFileName); // If canceled - return if (string.IsNullOrWhiteSpace(filePath)) { return; } // Save last used format _settingsService.LastFormat = format; // Save last used subtitle language if selected if (!string.IsNullOrWhiteSpace(SelectedSubtitleOption.Language.Code)) { _settingsService.LastSubtitleLanguageCode = SelectedSubtitleOption.Language.Code; } // Create download view model var download = _viewModelFactory.CreateDownloadViewModel(Video, filePath, format, SelectedDownloadOption, SelectedSubtitleOption); // Create empty file to "lock in" the file path PathEx.CreateDirectoryForFile(filePath); PathEx.CreateEmptyFile(filePath); // Close dialog Close(download); }
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { EditorGUI.BeginProperty(position, label, property); position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label); var indent = EditorGUI.indentLevel; EditorGUI.indentLevel = 0; float tagWidth = 50; float txtWidth = position.width - tagWidth - 5; Rect txtRect = new Rect(position.x, position.y, txtWidth, position.height); Rect tagRect = new Rect(position.x + txtWidth + 5, position.y, tagWidth, position.height); EditorGUI.PropertyField(txtRect, property.FindPropertyRelative("m_Pattern"), GUIContent.none); int value = EditorGUI.Popup(tagRect, 0, m_FileNameTags); if (value != 0) { var pattern = property.FindPropertyRelative("m_Pattern"); pattern.stringValue = FileNameGenerator.AddTag(pattern.stringValue, (FileNameGenerator.ETags)(value - 1)); } EditorGUI.indentLevel = indent; EditorGUI.EndProperty(); }
private void RenameFile(DirectoryInfo dir, FileInfo file, FileNameGenerator p) { Tag tag = ID3.TagUtils.ReadTag(file); if (!p.CanBuildName(tag)) { Logger.WriteLine(Tokens.Warning, "Can not build name for file \"" + file.Name + "\" with pattern \"" + p.ToString() + "\""); return; } string pathString = dir.FullName + Path.DirectorySeparatorChar; string newName = p.Name(tag); string dst = pathString + newName; string src = file.FullName; int maxLength = 240; if (dst.Length >= maxLength) { newName = p.NameLimited(tag, maxLength - pathString.Length); dst = pathString + newName; } renamer.ProcessMessage(new FileOperationProcessor.Message( newName, FileOperationProcessor.FileOperation.Move)); renamer.Process(file); }
public void Save() { var directoryInfo = new DirectoryInfo(WorkingDirectory); if (!directoryInfo.Exists) { directoryInfo.Create(); } var fileName = FileNameGenerator.GenerateUniqueName(directoryInfo, "BrightnessDistribution"); var imgFileName = Path.Combine(WorkingDirectory, $"{fileName}.bin"); using (var stream = File.OpenWrite(imgFileName)) { foreach (var snapshot in snapshots) { stream.Write(snapshot.Image, 0, snapshot.Image.Length); } } var snapshotsData = snapshots.Select(x => new { x.DateTime, x.ExposureTime, x.Energy, x.PixelFormat, }).ToArray(); var json = JsonConvert.SerializeObject(snapshotsData); var jsonFileName = Path.Combine(WorkingDirectory, $"{fileName}.json"); File.WriteAllText(jsonFileName, json); snapshots.Clear(); }
public void ContinuosGenerateTest() { // Arrange object parameter = null; int seed = 1337; FileNameGenerator fng = new FileNameGenerator(); // Act var shouldBeValidResult = fng.Init(parameter, seed); var generated1 = fng.Generate(parameter); var generated2 = fng.Generate(parameter); // Same step should provide same result fng.NextStep(); // Step increase should alter the result for next generate var generated3 = fng.Generate(parameter); // Assert Assert.IsTrue(shouldBeValidResult.success); Assert.IsTrue(generated1.success); Assert.IsTrue(generated2.success); Assert.IsTrue(generated3.success); Assert.AreEqual(generated1.result, generated2.result); Assert.AreNotEqual(generated1.result, generated3.result); }
public HttpResponseMessage Print() { HttpResponseMessage response = new HttpResponseMessage(); try { String outputFolderPath = _environment.ContentRootPath + "\\Outputs\\"; String outputFilePath = outputFolderPath + FileNameGenerator.getName(6) + _config.GetValue <String>("IoFileType"); var newsString = Request.Form["newspaper"]; var newspaper = JsonConvert.DeserializeObject <Newspaper>(newsString); if (!Directory.Exists(outputFolderPath)) { Directory.CreateDirectory(outputFolderPath); } _streamWriter.setPath(outputFilePath); newspaper.printNewspaper(_streamWriter); response.StatusCode = HttpStatusCode.OK; } catch (Exception e) { response.StatusCode = HttpStatusCode.InternalServerError; } return(response); }
public void ApplicationNameTokenLogFileNameTest() { string Expected = $"AppName.log"; string Actual = FileNameGenerator.GenerateFileName("AppName", s_Jan19Utc, "Group", "{ApplicationName}.log"); Assert.AreEqual(Expected, Actual); }
private void Snapshot() { try { var start = DateTime.Now; byte[] snapshotImageBuffer = null; bool snapshot = simpleCamera.Snapshot(out snapshotImageBuffer); if (snapshot) { this.SnapshotImage.Image = new Bitmap(new MemoryStream(snapshotImageBuffer)); } SimpleConsole.WriteLine("Snapshot."); //byte[] encryptBuffer = AES.AESEncrypt(snapshotImageBuffer, "yuanfeng"); snapshotImageBuffer.Writer(FileNameGenerator.Generator()); var end = DateTime.Now; SimpleConsole.WriteLine("Use Time:" + (end - start).TotalSeconds); } catch (Exception exception) { SimpleConsole.WriteLine(exception.Message); } }
public void SeedTest() { // Arrange int seed1 = 1337; int seed2 = 13370; int rounds = 100; string parameter = "random"; FileNameGenerator fng1 = new FileNameGenerator(); FileNameGenerator fng2 = new FileNameGenerator(); List <object> gene1Objects = new List <object>(capacity: rounds); List <object> gene2Objects = new List <object>(capacity: rounds); // Act var shouldBeValidInitResult1 = fng1.Init(parameter, seed1); var shouldBeValidInitResult2 = fng2.Init(parameter, seed2); for (int i = 0; i < rounds; i++) { var genResult1 = fng1.Generate(); var genResult2 = fng2.Generate(); gene1Objects.Add(genResult1.result); gene2Objects.Add(genResult2.result); fng1.NextStep(); fng2.NextStep(); } CollectionAssert.AreNotEqual(gene1Objects, gene2Objects); }
public void LocalTimeLogFileNameTest() { string Expected = $"{Environment.MachineName}.20201107.log"; string Actual = FileNameGenerator.GenerateFileName("AppName", s_Nov7Local, "Group", "{MachineName}.{DateTime:yyyyMMdd}.log"); Assert.AreEqual(Expected, Actual); }
public void WildcardTokenMatchLogFileNameTest() { string Expected = $"{Environment.MachineName}.AppName.*.*.{{NonMatch}}.*.*log"; string Actual = FileNameGenerator.GenerateWildcardFileName("AppName", "{MachineName}.{ApplicationName}.{GroupName}.{DateTimeUtc:yyyyMMdd}.{NonMatch}.{DateTime}.log"); Assert.AreEqual(Expected, Actual); }
public void Confirm() { // Prompt for output directory path var dirPath = _dialogManager.PromptDirectoryPath(); if (string.IsNullOrWhiteSpace(dirPath)) { return; } _settingsService.LastFormat = SelectedFormat; _settingsService.LastVideoQualityPreference = SelectedVideoQualityPreference; // Make sure selected videos are ordered in the same way as available videos var orderedSelectedVideos = AvailableVideos.Where(v => SelectedVideos.Contains(v)).ToArray(); var downloads = new List <DownloadViewModel>(); for (var i = 0; i < orderedSelectedVideos.Length; i++) { var video = orderedSelectedVideos[i]; var fileName = FileNameGenerator.GenerateFileName( _settingsService.FileNameTemplate, video, SelectedFormat !, (i + 1).ToString().PadLeft(orderedSelectedVideos.Length.ToString().Length, '0') ); var filePath = Path.Combine(dirPath, fileName); // If file exists - either skip it or generate a unique file path, depending on user settings if (File.Exists(filePath)) { if (_settingsService.ShouldSkipExistingFiles) { continue; } filePath = PathEx.MakeUniqueFilePath(filePath); } // Create empty file to "lock in" the file path. // This is necessary as there may be other downloads with the same file name // which would otherwise overwrite the file. PathEx.CreateDirectoryForFile(filePath); PathEx.CreateEmptyFile(filePath); var download = _viewModelFactory.CreateDownloadViewModel( video, filePath, SelectedFormat !, SelectedVideoQualityPreference ); downloads.Add(download); } Close(downloads); }
/// <summary> /// Generates api templates in the desired folder /// </summary> /// <param name="singleApiName">name of API to load api from</param> /// <param name="multipleApiNames">multiple API names to load api from</param> /// <param name="baseFilesGenerationDirectory">name of base folder where to save output files</param> /// <returns>generated api template</returns> public async Task <Template <ApiTemplateResources> > GenerateApiTemplateAsync( string singleApiName, List <string> multipleApiNames, string baseFilesGenerationDirectory) { this.logger.LogInformation("Started generation of api template..."); var apiTemplate = await this.apiExtractor.GenerateApiTemplateAsync( singleApiName, multipleApiNames, baseFilesGenerationDirectory, this.extractorParameters); if (apiTemplate?.HasResources() == true) { apiTemplate.TypedResources.FileName = FileNameGenerator.GenerateExtractorAPIFileName(singleApiName, this.extractorParameters.FileNames.BaseFileName); await FileWriter.SaveAsJsonAsync( apiTemplate, directory : baseFilesGenerationDirectory, fileName : apiTemplate.TypedResources.FileName); } this.logger.LogInformation("Finished generation of api template..."); return(apiTemplate); }
private void DelDayFile(int dayint) { lock (_object) { if (_timesheetdictionary.ContainsKey(dayint)) { _timesheetdictionary[dayint].Close(); _timesheetdictionary.Remove(dayint); System.IO.File.Delete(FileNameGenerator.GetTimeFullFileName(dayint, this)); } if (_itemsdictionary.ContainsKey(dayint)) { _itemsdictionary[dayint].Close(); _itemsdictionary.Remove(dayint); System.IO.File.Delete(FileNameGenerator.GetItemFullFileName(dayint, this)); } if (_contentdictionary.ContainsKey(dayint)) { _contentdictionary[dayint].Close(); _contentdictionary.Remove(dayint); System.IO.File.Delete(FileNameGenerator.GetContentFullFileName(dayint, this)); } } }
public AsyncFileDownloader(IEnumerable <string> urls, FileNameGenerator fileNameForUrl, string directoryPath) { if (fileNameForUrl == null) { throw new InvalidOperationException("FileNameForUrl can not be null"); } if (directoryPath == null) { throw new InvalidOperationException("directoryPath can not be null"); } _directoryPath = directoryPath; FileNameForUrl = fileNameForUrl; if (urls == null) { throw new ArgumentNullException(); } foreach (var i in urls) { _urls.AddLast(i); } _enumerator = _urls.GetEnumerator(); _webClient.DownloadFileCompleted += (o, e) => DownloadNext(); }
public void DateTimeUtcNoFormatLogFileNameTest() { string Expected = $"{Environment.MachineName}.20200119.log"; string Actual = FileNameGenerator.GenerateFileName("AppName", s_Jan19Utc, "Group", "{MachineName}.{DateTimeUtc}.log"); Assert.AreEqual(Expected, Actual); }
public void DateTimeCustomFormatLogFileNameTest() { string Expected = $"{Environment.MachineName}.20.11.7.log"; string Actual = FileNameGenerator.GenerateFileName("AppName", s_Nov7Local, "Group", "{MachineName}.{DateTime:yy.M.d}.log"); Assert.AreEqual(Expected, Actual); }
public void UnknownTokenLogFileNameTest() { string Expected = $"{Environment.MachineName}.{{UnknownToken}}.log"; string Actual = FileNameGenerator.GenerateFileName("AppName", s_Jan19Utc, "Group", "{MachineName}.{UnknownToken}.log"); Assert.AreEqual(Expected, Actual); }
static void EnableAllSinks(string assemblyName, string platform) { var now = DateTime.UtcNow; // if multinode.output-directory wasn't specified, the results files will be written // to the same directory as the test assembly. var outputDirectory = OutputDirectory; MessageSink CreateJsonFileSink() { var fileName = FileNameGenerator.GenerateFileName(outputDirectory, assemblyName, platform, ".json", now); var jsonStoreProps = Props.Create(() => new FileSystemMessageSinkActor(new JsonPersistentTestRunStore(), fileName, !TeamCityFormattingOn, true)); return(new FileSystemMessageSink(jsonStoreProps)); } MessageSink CreateVisualizerFileSink() { var fileName = FileNameGenerator.GenerateFileName(outputDirectory, assemblyName, platform, ".html", now); var visualizerProps = Props.Create(() => new FileSystemMessageSinkActor(new VisualizerPersistentTestRunStore(), fileName, !TeamCityFormattingOn, true)); return(new FileSystemMessageSink(visualizerProps)); } var fileSystemSink = CommandLine.GetProperty("multinode.enable-filesink"); if (!string.IsNullOrEmpty(fileSystemSink)) { SinkCoordinator.Tell(new SinkCoordinator.EnableSink(CreateJsonFileSink())); SinkCoordinator.Tell(new SinkCoordinator.EnableSink(CreateVisualizerFileSink())); } }
public void ShouldCreateCorrectNumberOfDeploymentResources() { // arrange CreatorConfig creatorConfig = new CreatorConfig() { apimServiceName = "apimService", linked = true }; MasterTemplateCreator masterTemplateCreator = new MasterTemplateCreator(); Template apiVersionSetsTemplate = new Template(); Template globalServicePolicyTemplate = new Template(); Template productsTemplate = new Template(); Template tagTemplate = new Template(); Template loggersTemplate = new Template(); List <LinkedMasterTemplateAPIInformation> apiInfoList = new List <LinkedMasterTemplateAPIInformation>() { new LinkedMasterTemplateAPIInformation() { name = "api", isSplit = true } }; FileNameGenerator fileNameGenerator = new FileNameGenerator(); FileNames creatorFileNames = fileNameGenerator.GenerateFileNames(creatorConfig.apimServiceName); // should create 7 resources (globalServicePolicy, apiVersionSet, product, tag, logger, both api templates) int count = 7; // act Template masterTemplate = masterTemplateCreator.CreateLinkedMasterTemplate(creatorConfig, globalServicePolicyTemplate, apiVersionSetsTemplate, productsTemplate, loggersTemplate, null, null, tagTemplate, apiInfoList, creatorFileNames, creatorConfig.apimServiceName, fileNameGenerator); // assert Assert.Equal(count, masterTemplate.resources.Length); }
// this function will generate master template for each API within this version set and an extra master template to link these apis public static async Task GenerateAPIVersionSetTemplates(ExtractorConfig exc, FileNameGenerator fileNameGenerator, FileNames fileNames, FileWriter fileWriter) { // get api dictionary and check api version set var apiDictionary = await GetAllAPIsDictionary(exc.sourceApimName, exc.resourceGroup, fileWriter); if (!apiDictionary.ContainsKey(exc.apiVersionSetName)) { throw new Exception("API Version Set with this name doesn't exist"); } else { Console.WriteLine("Start extracting the API version set {0}", exc.apiVersionSetName); foreach (string apiName in apiDictionary[exc.apiVersionSetName]) { // generate seperate folder for each API string apiFileFolder = String.Concat(@exc.fileFolder, $@"/{apiName}"); System.IO.Directory.CreateDirectory(apiFileFolder); await GenerateTemplates(new Extractor(exc, apiFileFolder), apiName, null, fileNameGenerator, fileNames, fileWriter, null); } // create master templates for this apiVersionSet string versionSetFolder = String.Concat(@exc.fileFolder, fileNames.versionSetMasterFolder); System.IO.Directory.CreateDirectory(versionSetFolder); await GenerateTemplates(new Extractor(exc, versionSetFolder), null, apiDictionary[exc.apiVersionSetName], fileNameGenerator, fileNames, fileWriter, null); Console.WriteLine($@"Finish extracting APIVersionSet {exc.apiVersionSetName}"); } }
// this function will generate templates for multiple specified APIs public static async Task GenerateMultipleAPIsTemplates(ExtractorConfig exc, FileNameGenerator fileNameGenerator, FileWriter fileWriter, FileNames fileNames) { if (exc.mutipleAPIs == null && exc.mutipleAPIs.Equals("")) { throw new Exception("mutipleAPIs parameter doesn't have any data"); } string[] apis = exc.mutipleAPIs.Split(','); for (int i = 0; i < apis.Length; i++) { apis[i] = apis[i].Trim(); } Console.WriteLine("Start extracting these {0} APIs", apis.Length); foreach (string apiName in apis) { // generate seperate folder for each API string apiFileFolder = String.Concat(@exc.fileFolder, $@"/{apiName}"); System.IO.Directory.CreateDirectory(apiFileFolder); await GenerateTemplates(new Extractor(exc, apiFileFolder), apiName, null, fileNameGenerator, fileNames, fileWriter, null); } // create master templates for these apis string groupApiFolder = String.Concat(@exc.fileFolder, fileNames.groupAPIsMasterFolder); System.IO.Directory.CreateDirectory(groupApiFolder); await GenerateTemplates(new Extractor(exc, groupApiFolder), null, apis.ToList(), fileNameGenerator, fileNames, fileWriter, null); Console.WriteLine($@"Finish extracting mutiple APIs"); }
public void ShouldCreateCorrectNumberOfDeploymentResources() { // arrange MasterTemplateCreator masterTemplateCreator = new MasterTemplateCreator(); Template apiVersionSetsTemplate = new Template(); Template productsTemplate = new Template(); Template loggersTemplate = new Template(); List <LinkedMasterTemplateAPIInformation> apiInfoList = new List <LinkedMasterTemplateAPIInformation>() { new LinkedMasterTemplateAPIInformation() { name = "api", isSplit = true } }; FileNameGenerator fileNameGenerator = new FileNameGenerator(); CreatorFileNames creatorFileNames = fileNameGenerator.GenerateCreatorLinkedFileNames(); // should create 5 resources (apiVersionSet, product, logger, both api templates) int count = 5; // act Template masterTemplate = masterTemplateCreator.CreateLinkedMasterTemplate(apiVersionSetsTemplate, productsTemplate, loggersTemplate, null, null, apiInfoList, creatorFileNames, fileNameGenerator); // assert Assert.Equal(count, masterTemplate.resources.Length); }
public void CaseInsensitiveTokenMatchLogFileNameTest() { string Expected = $"{Environment.MachineName}.log"; string Actual = FileNameGenerator.GenerateFileName("AppName", s_Jan19Utc, "Group", "{machinename}.log"); Assert.AreEqual(Expected, Actual); }
public void Confirm() { var format = SelectedDownloadOption.Format; var filter = $"{format.ToUpperInvariant()} file|*.{format}"; var defaultFileName = FileNameGenerator.GenerateFileName(_settingsService.FileNameTemplate, Video, format); var filePath = _dialogManager.PromptSaveFilePath(filter, defaultFileName); if (string.IsNullOrWhiteSpace(filePath)) { return; } _settingsService.LastFormat = format; var download = _viewModelFactory.CreateDownloadViewModel(Video, filePath, format, SelectedDownloadOption); FileEx.CreateDirectoriesForFile(filePath); FileEx.CreateEmptyFile(filePath); Close(download); }
public void ShouldGenerateFileNameWithGivenDate(DateTime date, string fileName) { var fileNameGenerator = new FileNameGenerator(); var newFileName = fileNameGenerator.Generate(date); newFileName.Should().Be(fileName); }
public FileSystemMessageSink(string assemblyName) : this( Props.Create( () => new FileSystemMessageSinkActor(new JsonPersistentTestRunStore(), FileNameGenerator.GenerateFileName(assemblyName, ".json"), true))) { }
public void ShouldGenerateNonEmptyFileName() { var fileNameGenerator = new FileNameGenerator(); var newFileName = fileNameGenerator.Generate(Arg.Any <DateTime>()); newFileName.Should().NotBeEmpty(); }
public FileRepository() { _appSettingService = new AppSettingService(); _fileNameGenerator = new FileNameGenerator(); FilteredMetadataItems = new List <MetadataItem>(); EveryMetadataItemInRepository = new List <MetadataItem>(); LoadMetadataFiles(); }
public List<Record> GenerateRecords(int numberOfRecords) { #region Generator's Parameters Initialization _uniqueIpList = _kernel.Get<UniqueIpListGenerator>(); _uniqueIpListGeneratorParameters = new UniqueIpListGeneratorParameters { NumberOfUniqueIp = NumberOfUniqueIp }; UniqueIpList = _uniqueIpList.Generate(_uniqueIpListGeneratorParameters).UniqueIpList; _ipGeneratorParameters = new IpGeneratorParameters { UniqueIpList = UniqueIpList }; _queryTimeGeneratorParameters = new QueryTimeGeneratorParameters { MinInterval = MinIntervalInMilliseconds, MaxInterval = MaxIntervalInMilliseconds, StartTime = DateTime.Now }; _queryMethodGeneratorParameters = new QueryMethodGeneratorParameters { Values = Methods, ValuesWithWeights = Settings }; _fileNameGeneratorParameters = new FileNameGeneratorParameters { MinNumberOfCharacters = MinNumberOfCharacters, MaxNumberOfCharacters = MaxNumberOfCharacters, MinNumberOfFolders = MinNumberOfFolders, MaxNumberOfFolders = MaxNumberOfFolders }; _extensionGeneratorParameters = new ExtensionGeneratorParameters { Values = Extensions, ValuesWithWeights = Settings }; _protocolGeneratorParameters = new ProtocolGeneratorParameters { Values = Protocols }; _serverResponseCodeGeneratorParameters = new ServerResponseCodeGeneratorParameters { Values = ServerResponseCodes, ValuesWithWeights = Settings }; _sizeOfResponseGeneratorParameters = new SizeOfResponseGeneratorParameters { MinSize = MinSizeOfResponse, MaxSize = MaxSizeOfResponse }; #endregion #region Creation of generators _ip = _kernel.Get<IpGenerator>(); _queryTime = _kernel.Get<QueryTimeGenerator>(); _queryMethod = _kernel.Get< QueryMethodGenerator>(); _fileName = _kernel.Get<FileNameGenerator>(); _extension = _kernel.Get<ExtensionGenerator>(); _protocol = _kernel.Get<ProtocolGenerator>(); _serverResponseCode = _kernel.Get<ServerResponseCodeGenerator>(); _sizeOfTheResponse = _kernel.Get<SizeOfResponseGenerator>(); #endregion var listOfRecords = new List<Record>(); for (var i = 0; i < numberOfRecords; i++) listOfRecords.Add(GenerateRecord()); return listOfRecords; }