public void TestRemoveDesignFromDesignCache() { AddApplicationRouting(); var siteModel = DITAGFileAndSubGridRequestsWithIgniteFixture.NewEmptyModel(); var designUid = DITAGFileAndSubGridRequestsWithIgniteFixture.AddDesignToSiteModel(ref siteModel, TestHelper.CommonTestDataPath, TESTFILENAME, true); var localStorage = Path.Combine(FilePathHelper.GetTempFolderForProject(siteModel.ID), TESTFILENAME); var designFiles = DIContext.ObtainOptional <IDesignFiles>(); designFiles.NumDesignsInCache().Should().Be(0); designFiles.Lock(designUid, siteModel, SubGridTreeConsts.DefaultCellSize, out var loadResult); File.Exists(localStorage).Should().BeTrue(); designFiles.NumDesignsInCache().Should().Be(1); var design1 = loadResult.Should().Be(DesignLoadResult.Success); design1.Should().NotBeNull(); var message = new DesignChangedEvent() { SiteModelUid = siteModel.ID, DesignUid = designUid, DesignRemoved = true, FileType = ImportedFileType.DesignSurface }; var listener = new DesignChangedEventListener(TRexGrids.ImmutableGridName()); listener.Invoke(Guid.Empty, message).Should().BeTrue(); File.Exists(localStorage).Should().BeFalse(); designFiles.NumDesignsInCache().Should().Be(0); }
protected void Application_Startup(object sender, StartupEventArgs e) { // Set default culture for all threads for this application (affects date and string formats, e.g. periods instead of commas) CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture; CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture; FilePathHelper.CalculateGameAssetsFilePaths(); /* Content seeding - use with caution! * GameAssetsHelper.SeedContent<Artifact>(FilePathHelper.ArtifactsFilePath); * GameAssetsHelper.SeedContent<Artifact>(FilePathHelper.BlessingsFilePath); * GameAssetsHelper.SeedContent<Artifact>(FilePathHelper.BossesFilePath); * GameAssetsHelper.SeedContent<Artifact>(FilePathHelper.DungeonsFilePath); * GameAssetsHelper.SeedContent<Artifact>(FilePathHelper.DungeonGroupsFilePath); * GameAssetsHelper.SeedContent<Artifact>(FilePathHelper.MonstersFilePath); * GameAssetsHelper.SeedContent<Artifact>(FilePathHelper.RegionsFilePath); * GameAssetsHelper.SeedContent<Artifact>(FilePathHelper.QuestsFilePath); * GameAssetsHelper.SeedContent<Artifact>(FilePathHelper.RecipesFilePath); * GameAssetsHelper.SeedContent<Artifact>(FilePathHelper.PriestOfferFilePath); * GameAssetsHelper.SeedContent<Artifact>(FilePathHelper.ShopOfferFilePath); */ GameAssetsHelper.LoadAllContent(); }
protected override void Initialize() { Header = "Mail"; Icon = FilePathHelper.GetDXImageUri("Mail/Mail_32x32"); FillFolders(); CurrentFolder = GetFolderByFolderDescription(MessageFolderName.All, MessageType.Inbox, Folders); }
private async Task ProcessFiles( Dictionary <string, DocumentationNode> resultNodes, DocumentationNode parentNode, string[] allFilePaths, Dictionary <string, string> redirects) { foreach (var filePath in allFilePaths) { // slug path var fileExtension = Path.GetExtension(filePath); var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePath); var sluggedFileName = SlugFormatter.ToSlug(fileNameWithoutExtension); var sluggedFileNameWithExtension = Path.ChangeExtension(sluggedFileName, fileExtension); // skip the file if there's already a redirect if (redirects.Any(r => SlugFormatter.ToSlug(r.Key) == sluggedFileName)) { continue; } if (fileExtension == MARKDOWN_FILE_EXTENSION) { var destinationFilePath = FilePathHelper.CombineVirtualPath(parentNode.Url, sluggedFileNameWithExtension); var updateDate = File.GetLastWriteTimeUtc(filePath); // if we have a custom index file, map this to the container directory if (sluggedFileName == "index") { parentNode.DocumentFilePath = destinationFilePath; parentNode.UpdateDate = updateDate; } else { var node = new DocumentationNode() { Title = fileNameWithoutExtension, Url = FilePathHelper.CombineVirtualPath(parentNode.Url, sluggedFileName), DocumentFilePath = destinationFilePath, UpdateDate = updateDate }; resultNodes.Add(sluggedFileName, node); } await _fileWriterService.CopyFile(filePath, destinationFilePath); } else if (fileExtension != ".json") { // static files are served out of a separate directory var destinationDirectory = FilePathHelper.CombineVirtualPath(STATIC_FOLDER_NAME, parentNode.Url); var destinationPath = FilePathHelper.CombineVirtualPath(destinationDirectory, sluggedFileNameWithExtension); await _fileWriterService.EnsureDirectoryExistsAsync(destinationDirectory); await _fileWriterService.CopyFile(filePath, destinationPath); } // json files ignore, they are assumed to be config } }
public void RemoveDuplicateDirectories_Removes_Multiple_Duplicates() { var inputPath = Path.Combine("Dir1", "Dir2", "Dir2", "Dir2", "Dir2", "Dir3"); var expectedPath = Path.Combine("Dir1", "Dir2", "Dir3"); Assert.AreEqual(expectedPath, FilePathHelper.RemoveDuplicateDirectories(inputPath)); }
private void DeleteLocalFiles(Guid siteModelUid, string filename, ImportedFileType importedFileTypeEnum) { var localPath = FilePathHelper.GetTempFolderForProject(siteModelUid); var localPathAndFileName = Path.Combine(new[] { localPath, filename }); if (System.IO.File.Exists(localPathAndFileName)) { System.IO.File.Delete(localPathAndFileName); if (importedFileTypeEnum != ImportedFileType.Alignment) { var indexFilename = SubGridIndexFileName(localPathAndFileName); if (System.IO.File.Exists(indexFilename)) { System.IO.File.Delete(indexFilename); } indexFilename = SpatialIndexFileName(localPathAndFileName); if (System.IO.File.Exists(indexFilename)) { System.IO.File.Delete(indexFilename); } indexFilename = BoundaryFileName(localPathAndFileName); if (System.IO.File.Exists(indexFilename)) { System.IO.File.Delete(indexFilename); } } } }
public async Task ExecuteAsync(AddDocumentAssetCommand command, IExecutionContext executionContext) { var documentAsset = new DocumentAsset(); documentAsset.Title = command.Title; documentAsset.Description = command.Description ?? string.Empty; documentAsset.FileName = FilePathHelper.CleanFileName(command.Title); documentAsset.VerificationToken = _randomStringGenerator.Generate(6); if (string.IsNullOrWhiteSpace(documentAsset.FileName)) { throw ValidationErrorException.CreateWithProperties("Document title is empty or does not contain any safe file path characters.", nameof(command.Title)); } _entityTagHelper.UpdateTags(documentAsset.DocumentAssetTags, command.Tags, executionContext); _entityAuditHelper.SetCreated(documentAsset, executionContext); documentAsset.FileUpdateDate = executionContext.ExecutionDate; using (var scope = _transactionScopeFactory.Create(_dbContext)) { _dbContext.DocumentAssets.Add(documentAsset); await _documentAssetCommandHelper.SaveFile(command.File, documentAsset); command.OutputDocumentAssetId = documentAsset.DocumentAssetId; scope.QueueCompletionTask(() => OnTransactionComplete(documentAsset)); await scope.CompleteAsync(); } }
public void Test_Data_GetFilePathById() { // List <Property> _prop = new List <Property>(); DataResponse record = new DataResponse() { Id = "HelloData", Name = "Hello.csv", User = "", Created_on = DateTime.Now.ToString(), Edited_on = DateTime.Now.ToString(), Extension = ".csv", MimeType = "application/csv", Size = 111, Type = "CSV", Url = "http://localhost/uploads/Data/Hello.csv", FilePath = "/home/zmod/data/Hello.csv", Properties = _prop }; List <DataResponse> records = new List <DataResponse> { record }; string result = FilePathHelper.GetFilePathById("HelloData", records); // Assert.Equal("/home/zmod/data/Hello.csv", result); }
private IEnumerable <PageTemplateFile> SearchDirectoryForPageTemplateFiles(string directoryPath, string searchText) { var directoryContents = _resourceLocator.GetDirectory(directoryPath); foreach (var file in directoryContents.Where(f => !f.IsDirectory)) { // filename contains the search text and is located in a 'PageTemplates' folder, but not a 'partials' folder and has the extension .cshtml if (Contains(file.Name, searchText) && !Contains(file.Name, "_ViewStart") && !Contains(file.Name, "_ViewImports") && file.Name.EndsWith(VIEW_FILE_EXTENSION, StringComparison.OrdinalIgnoreCase)) { yield return(MapPageTemplateFile(directoryPath, file)); } } foreach (var childDirectoryName in directoryContents .Where(f => f.IsDirectory) .Select(f => f.Name) ) { var childDirectoryPath = FilePathHelper.CombineVirtualPath(directoryPath, childDirectoryName); foreach (var file in SearchDirectoryForPageTemplateFiles(childDirectoryPath, searchText)) { yield return(file); } } }
public void Execute_FailWithNonExistentDesignReference(SurveyedSurfacePatchType patchType) { AddApplicationGridRouting(); var asAtDate = DateTime.UtcNow; var siteModel = DITAGFileAndSubGridRequestsWithIgniteFixture.NewEmptyModel(); // Construct a surveyed surface from the design DITAGFileAndSubGridRequestsWithIgniteFixture.ConstructSingleFlatTriangleSurveyedSurfaceAboutOrigin(ref siteModel, 1.0f, asAtDate); // Delete the second surveyed surface TTM file from both it's original location and the project temporary folder string fileToDelete = siteModel.SurveyedSurfaces[0].DesignDescriptor.FullPath; File.Exists(fileToDelete).Should().BeTrue(); File.Delete(fileToDelete); File.Exists(fileToDelete).Should().BeFalse(); fileToDelete = Path.Combine(FilePathHelper.GetTempFolderForProject(siteModel.ID), siteModel.SurveyedSurfaces[0].DesignDescriptor.FileName); File.Exists(fileToDelete).Should().BeTrue(); File.Delete(fileToDelete); File.Exists(fileToDelete).Should().BeFalse(); var req = new SurfaceElevationPatchRequestViaLocalCompute(); var result = req.Execute(new SurfaceElevationPatchArgument(siteModel.ID, SubGridTreeConsts.DefaultIndexOriginOffset, SubGridTreeConsts.DefaultIndexOriginOffset, siteModel.CellSize, patchType, SubGridTreeBitmapSubGridBits.FullMask, siteModel.SurveyedSurfaces)); result.Should().BeNull(); }
private void CheckOneLightFile(string path, int op) { Scene scene = EditorSceneManager.OpenScene(path); string relativePath = path.Replace(FilePathHelper.GetProjectPath(), ""); LightObject lightObj = new LightObject(); lightObj.hasLight = false; GameObject[] goList = SceneManager.GetActiveScene().GetRootGameObjects(); foreach (GameObject go in goList) { if (go != null) { LookupAllLight(go.transform, lightObj, op); } } if (lightObj.hasLight) { lightObj.obj = AssetDatabase.LoadAssetAtPath(relativePath, typeof(Object)); lightObj.path = path; _lightObjects.Add(lightObj); } if (op == 2 && lightObj.hasLight) { EditorSceneManager.SaveScene(scene); } }
public void IsSubDirectory_Returns_True_If_OtherPath_Is_Multiple_Levels_Above_BasePath() { var basePath = Path.Combine("Dir1", "Dir2"); var otherPath = Path.Combine(basePath, "Dir3", "Dir4", "Dir5"); Assert.True(FilePathHelper.IsSubDirectory(basePath, otherPath)); }
public void IsSubDirectory_Returns_False_If_OtherPath_Is_One_Level_Below_BasePath() { var otherPath = Path.Combine("Dir1", "Dir2"); var basePath = Path.Combine(otherPath, "Dir3"); Assert.False(FilePathHelper.IsSubDirectory(basePath, otherPath)); }
public void Init() { FilePathHelper = new FilePathHelper(videoPath, catalogPath); ThumbCreator = new MediaToolkitExtractor(filePathHelper: FilePathHelper, silentMode: false); if (File.Exists(ThumbCreator.OutputImagePath)) File.Delete(ThumbCreator.OutputImagePath); }
protected override void ProcessFilesForReports(List <string> files, IUserConfiguration user) { if (files.Count == 0) { return; } _logger.Debug($"Crete Edesur report for user {user.Name}."); var ftpHelper = user.Ftp.GetFtpHelper(_logger); var filePathHelper = new FilePathHelper(_configuration, user.Name); var report = new EdesurReport(_logger, _reportTypeConfiguration); report.SourceFiles = files; report.Separator = _reportTypeConfiguration.FieldSeparator; report.ReportPath = filePathHelper.GetReportsFilesFolder(); report.ReportGMT = user.UserGMT; report.UserId = user.Credentials.AccountId; string reportFileName = report.Generate(); if (File.Exists(reportFileName)) { UploadFileToFtp(reportFileName, ((UserApiConfiguration)user).Reports.Folder, ftpHelper); } }
public override bool GenerateForcedReport(List <string> files, IUserConfiguration user) { List <string> filteredFiles = FilterFilesByTemplate(files, user); if (filteredFiles.Count == 0) { return(false); } _logger.Debug($"Crete Edesur report for user {user.Name}."); var ftpHelper = user.Ftp.GetFtpHelper(_logger); var filePathHelper = new FilePathHelper(_configuration, user.Name); var report = new EdesurReport(_logger, _reportTypeConfiguration) { SourceFiles = files, Separator = _reportTypeConfiguration.FieldSeparator, ReportPath = filePathHelper.GetForcedReportsFolder(), ReportGMT = user.UserGMT, UserId = user.Credentials.AccountId }; report.Generate(); return(true); }
/// <summary> /// Some shared validation to prevent image asset types from being added to documents. /// </summary> public static IEnumerable <ValidationResult> Validate(IUploadedFile file) { if (file != null && !string.IsNullOrWhiteSpace(file.FileName)) { // Validate extension & mime type var ext = Path.GetExtension(file.FileName)?.Trim(); if (string.IsNullOrWhiteSpace(ext)) { yield return(new ValidationResult("The file you're uploading has no file extension.", new string[] { "File" })); } else if (FilePathHelper.FileExtensionContainsInvalidChars(ext)) { yield return(new ValidationResult("The file you're uploading uses an extension containing invalid characters.", new string[] { "File" })); } else if ((ImageAssetConstants.PermittedImageTypes.ContainsKey(ext)) || (!string.IsNullOrEmpty(file.MimeType) && ImageAssetConstants.PermittedImageTypes.ContainsValue(file.MimeType))) { yield return(new ValidationResult("Image files shoud be uploaded in the image assets section.", new string[] { "File" })); } // Validate filename if (string.IsNullOrWhiteSpace(file.FileName)) { yield return(new ValidationResult("The file you're uploading has no file name.", new string[] { "File" })); } else if (string.IsNullOrWhiteSpace(FilePathHelper.CleanFileName(file.FileName))) { yield return(new ValidationResult("The file you're uploading has an invalid file name.", new string[] { "File" })); } } }
private async Task ProcessChildDirectories(Dictionary <string, DocumentationNode> resultNodes, DocumentationNode parentNode, string directoryPath) { foreach (var childDirectoryPath in Directory.GetDirectories(directoryPath)) { var directory = new DirectoryInfo(childDirectoryPath); var slug = SlugFormatter.ToSlug(directory.Name); var childNode = new DocumentationNode() { Title = directory.Name, Url = FilePathHelper.CombineVirtualPath(parentNode.Url, slug) }; childNode.UpdateDate = Directory.GetLastWriteTimeUtc(childDirectoryPath); await _fileWriterService.EnsureDirectoryExistsAsync(childNode.Url); await ProcessDirectory(childDirectoryPath, childNode); // Only add the node if it represents something in the document tree // i.e. skip static resource directories. if (childNode.Children.Any() || childNode.DocumentFilePath != null || childNode.RedirectTo != null) { resultNodes.Add(slug, childNode); } } }
private void CheckOneStaticFile(string path, int op) { Scene scene = EditorSceneManager.OpenScene(path); string relativePath = path.Replace(FilePathHelper.GetProjectPath(), ""); StaticObject staticObj = new StaticObject(); staticObj.hasStatic = false; GameObject[] goList = SceneManager.GetActiveScene().GetRootGameObjects(); foreach (GameObject go in goList) { if (go != null) { LookupAllStatic(go.transform, staticObj, op); //if (op == 2 && _addRuntimeCompList.IndexOf(go.name) > -1 && go.GetComponent<RuntimeBatch>() == null) { // go.AddComponent<RuntimeBatch>(); //} } } if (staticObj.hasStatic) { staticObj.obj = AssetDatabase.LoadAssetAtPath(relativePath, typeof(Object)); staticObj.path = path; _staticObjects.Add(staticObj); } if (op == 2 && staticObj.hasStatic) { EditorSceneManager.SaveScene(scene); } }
//复制文件夹 public static void Copy(this DirectoryInfo source, DirectoryInfo target, Action <FileInfo> callback = null) { if (source == null || !source.Exists) { return; } if (!target.Exists) { target.Create(); } DirectoryInfo subDirInfo; FileInfo subFileInfo; foreach (FileSystemInfo sysInfo in source.GetFileSystemInfos()) { if ((subDirInfo = sysInfo as DirectoryInfo) != null) { Copy(subDirInfo, new DirectoryInfo(FilePathHelper.GetAbsolutePath(subDirInfo.Name, target.FullName)), callback); } else if ((subFileInfo = sysInfo as FileInfo) != null) { try { subFileInfo.CopyTo(FilePathHelper.GetAbsolutePath(subFileInfo.Name, target.FullName), true); if (callback != null) { callback(subFileInfo); } } catch (Exception exp) { Console.WriteLine(exp.Message); } } } }
private void CheckOneDfMaterialFile(string path, int op) { Scene scene = EditorSceneManager.OpenScene(path); string relativePath = path.Replace(FilePathHelper.GetProjectPath(), ""); DfMaterialObject dfMaterialObj = new DfMaterialObject(); dfMaterialObj.hasDf = false; GameObject[] goList = SceneManager.GetActiveScene().GetRootGameObjects(); foreach (GameObject go in goList) { if (go != null) { LookupAllDfMaterial(go.transform, dfMaterialObj, op); } } if (dfMaterialObj.hasDf) { dfMaterialObj.obj = AssetDatabase.LoadAssetAtPath(relativePath, typeof(Object)); dfMaterialObj.path = path; _dfMaterialObjects.Add(dfMaterialObj); } if (op == 2 && dfMaterialObj.hasDf) { EditorSceneManager.SaveScene(scene); } }
private PageBlockTypeFileLocation CreateTemplateFile(string directoryPath, IFileInfo file) { var templateFile = new PageBlockTypeFileLocation(); templateFile.Path = FilePathHelper.CombineVirtualPath(directoryPath, file.Name); templateFile.FileName = Path.GetFileNameWithoutExtension(file.Name); var templatePath = FilePathHelper.CombineVirtualPath(directoryPath, TEMPLATES_FOLDER_NAME); var templateDirectory = _resourceLocator.GetDirectory(templatePath); if (templateDirectory != null) { templateFile.Templates = FilterViewFiles(templateDirectory) .GroupBy(t => t.Name, (k, v) => v.FirstOrDefault()) // De-dup .Select(t => new PageBlockTypeTemplateFileLocation() { FileName = Path.GetFileNameWithoutExtension(t.Name), Path = FilePathHelper.CombineVirtualPath(templatePath, t.Name) }) .ToDictionary(t => t.FileName); } else { templateFile.Templates = new Dictionary <string, PageBlockTypeTemplateFileLocation>(); } return(templateFile); }
public override Task <IEnumerable <FileInformation> > MigrateClassAsync() { LogStart(); _metricsContext.CollectActionMetrics(WebFormsActionType.ClassConversion, ActionName); // NOTE: We could just read the file from the disk and retrieve the bytes like // that but instead I opted to "rebuild" the type in case we wanted to add comments // or something else to these undefined code files, most likely though we may still // want to scan parts of these files and remove/alter/take note of certain lines/info var newRelativePath = FilePathHelper.RemoveDuplicateDirectories(FilePathHelper.AlterFileName(_relativePath, newFileName: _originalClassSymbol.Name)); // NOTE: Removed temporarily until usings can be better determined, at the moment, too // many are being removed //var sourceClassComponents = GetSourceClassComponents(); var namespaceNames = _sourceFileSemanticModel.GetOriginalUsingNamespaces().Append(Constants.BlazorComponentsNamespace); namespaceNames = CodeSyntaxHelper.RemoveFrameworkUsings(namespaceNames); var usingStatements = CodeSyntaxHelper.BuildUsingStatements(namespaceNames); var namespaceNode = CodeSyntaxHelper.BuildNamespace(_originalClassSymbol.ContainingNamespace?.ToDisplayString(), _originalDeclarationSyntax); var fileText = CodeSyntaxHelper.GetFileSyntaxAsString(namespaceNode, usingStatements); DoCleanUp(); LogEnd(); var result = new[] { new FileInformation(newRelativePath, Encoding.UTF8.GetBytes(fileText)) }; return(Task.FromResult((IEnumerable <FileInformation>)result)); }
public async Task <DocumentAssetFile> ExecuteAsync(GetDocumentAssetFileByIdQuery query, IExecutionContext executionContext) { var dbResult = await _dbContext .DocumentAssets .Where(f => f.DocumentAssetId == query.DocumentAssetId && !f.IsDeleted) .Select(f => new { Extension = f.FileExtension, ContentType = f.ContentType, FileName = f.Title }) .SingleOrDefaultAsync(); if (dbResult == null) { return(null); } var fileName = Path.ChangeExtension(query.DocumentAssetId.ToString(), dbResult.Extension); var result = new DocumentAssetFile(); result.DocumentAssetId = query.DocumentAssetId; result.ContentType = dbResult.ContentType; result.ContentStream = await _fileStoreService.GetAsync(DocumentAssetConstants.FileContainerName, fileName); result.FileName = FilePathHelper.CleanFileName(Path.ChangeExtension(dbResult.FileName, dbResult.Extension), fileName); if (result.ContentStream == null) { throw new FileNotFoundException("DocumentAsset file could not be found", fileName); } return(result); }
public void Test_Model_GetFilePathById() { // List <Property> _prop = new List <Property>(); ModelResponse record = new ModelResponse() { Id = "HelloModel", Name = "Hello.pmml", User = "", Created_on = DateTime.Now.ToString(), Edited_on = DateTime.Now.ToString(), Extension = "pmml", MimeType = "application/pmml", Size = 222, Type = "PMML", Url = "http://localhost/uploads/Model/HelloModel.pmml", FilePath = "/home/zmod/model/HelloModel.pmml", Loaded = false, Deployed = false, Properties = _prop }; List <ModelResponse> records = new List <ModelResponse> { record }; string result = FilePathHelper.GetFilePathById("HelloData", records); // Assert.Equal("/home/zmod/model/HelloModel.pmml", result); }
private void Initialize() { UserCredential credential; using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) { var credPath = FilePathHelper.GetSpecialFolder(); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; Debug.WriteLine("Credential file saved to: " + credPath); } // Create Calendar Service. var service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); GoogleCalendarProvider.GoogleCalendatService = service; }
private void DeleteLocalFiles(IUserConfiguration user) { string path = new FilePathHelper(_configuration, user.Name).GetUserFolder(); DateTime filterDate = DateTime.UtcNow.AddDays(-_configuration.CleanDays); var baseDirectory = new DirectoryInfo(path); if (baseDirectory.Exists) { DirectoryInfo[] directories = baseDirectory.GetDirectories(); foreach (DirectoryInfo directory in directories) { FileInfo[] files = directory.GetFiles().Where(f => f.CreationTimeUtc < filterDate).ToArray(); foreach (FileInfo file in files) { try { //_logger.Debug($"Delete local file {file.FullName}"); file.Delete(); } catch (Exception e) { _logger.Error($"Error trying to delete file {file.FullName} -- {e}"); } } } } }
public void Test_Code_GetFilePathById() { // List <Property> _prop = new List <Property>(); CodeResponse record = new CodeResponse() { Id = "HelloCode", Name = "Hello.py", User = "", Created_on = DateTime.Now.ToString(), Edited_on = DateTime.Now.ToString(), Extension = ".py", MimeType = "application/image", Size = 111, Type = "PY", Url = "http://localhost/uploads/Code/Hello.png", FilePath = "some Path", Properties = _prop }; List <CodeResponse> records = new List <CodeResponse> { record }; string result = FilePathHelper.GetFilePathById("HelloCode", records); // Assert.Equal("some Path", result); }
protected override void ProcessFilesForReports(List <string> files, IUserConfiguration user) { if (files.Count == 0) { return; } var ftpHelper = user.Ftp.GetFtpHelper(_logger); var filePathHelper = new FilePathHelper(_configuration, user.Name); foreach (string file in files) { _logger.Debug($"Create report file with {file} for user {user.Name}."); var report = new ExcelReport(_logger, _reportTypeConfiguration); report.SourceFile = file; report.Separator = _reportTypeConfiguration.FieldSeparator; report.ReportPath = filePathHelper.GetReportsFilesFolder(); report.ReportGMT = user.UserGMT; report.UserId = user.Credentials.AccountId; string reportFileName = report.Generate(); if (!string.IsNullOrEmpty(reportFileName) && File.Exists(reportFileName)) { string renameFile = file.Replace(".sent", ".report"); File.Move(file, renameFile); UploadFileToFtp(reportFileName, ((UserApiConfiguration)user).Reports.Folder, ftpHelper); } } }
public void IsSubDirectory_Returns_False_If_Paths_Do_Not_Share_A_Root() { var basePath = Path.Combine("Dir1Alt", "Dir2", "Dir3"); var otherPath = Path.Combine("Dir1", "Dir2"); Assert.False(FilePathHelper.IsSubDirectory(basePath, otherPath)); }
private DownloadInfo DoDownloadIfNeed(IndexShopContext context, XmlFileInfo xmlInfo) { var filePath = FilePathHelper.GetFilePath(_settings.DirectoryPath, xmlInfo); if (context.DownloadFresh || File.Exists(filePath) == false) { var downloadContext = new BackgroundBaseContext($"Download:{xmlInfo.Name}", "download"); downloadContext.Prepare(); downloadContext.Start(); context.Contexts.Add(downloadContext); var downloader = new FeedsDownloader(_settings.AttemptsToDownload, Db, downloadContext); var file = downloader.Download(_settings.DirectoryPath, xmlInfo); downloadContext.Content = "Все скачали"; downloadContext.Finish(); return(file); } return(new DownloadInfo(xmlInfo.ShopId, xmlInfo.NameLatin, xmlInfo.Weight) { ShopName = xmlInfo.NameLatin, FilePath = filePath }); }
public MediaToolkitExtractor(FilePathHelper filePathHelper, bool silentMode = true) { if (!Directory.Exists(string.Concat(filePathHelper.DirectoryStart, ConfigurationManager.AppSettings["ThumbnailssDirectoryName"]))) Directory.CreateDirectory(string.Concat(filePathHelper.DirectoryStart, ConfigurationManager.AppSettings["ThumbnailssDirectoryName"])); Timing = new TimeSpan(0, 0, 10); OutputFrameDimensions = new Size(200, 125); VideoPath = filePathHelper.FileFull; OutputImagePath = string.Concat( filePathHelper.DirectoryStart, ConfigurationManager.AppSettings["ThumbnailsDirectoryName"], filePathHelper.Name, ".png"); OutputSpriteFramePathTemplate = OutputImagePath.Replace(".png", ".{0}.png"); InputFile = new MediaFile { Filename = VideoPath }; }
public void UnescapeFileRelativePaths() { // escaped inputs, trailing \ on start path FilePathHelper = new FilePathHelper(_pathToFile, _rootPath); Assert.AreEqual(_correctRelativePathToDirectory, FilePathHelper.DirectoryRelative); Assert.AreEqual(_correctRelativePathToFile, FilePathHelper.FileRelative); }
public void FileName() { FilePathHelper = new FilePathHelper(_pathToFile); Assert.AreEqual(_correctFileName, FilePathHelper.Name); }
public void ParentFolder() { FilePathHelper = new FilePathHelper(_someSubDirectory, _rootPath); Assert.AreEqual(_correctParentSubDirectory, FilePathHelper.ParentDirectoryFull, "Parent Directory Full Path incorrect"); Assert.AreEqual(_correctRelativeParentSubDirectory, FilePathHelper.ParentDirectoryRelative, "Parent Directory Relative incorrect"); }
public void UnescapeDirectoryRelativePaths() { FilePathHelper = new FilePathHelper(_someSubDirectory, _rootPath); Assert.AreEqual(_correctRelativeSubDirectory, FilePathHelper.DirectoryRelative, "Directories input path must be handled correctly"); }
public void UnescapeFileFullPaths() { // From escaped input FilePathHelper = new FilePathHelper(_pathToFile); Assert.AreEqual(_correctPathToFile, FilePathHelper.FileFull); Assert.AreEqual(_correctPathToDirectory, FilePathHelper.DirectoryFull); }
public void DirectoryStart() { FilePathHelper = new FilePathHelper(_pathToFile, _rootPath); Assert.AreEqual(_correctRootPath, FilePathHelper.DirectoryStart); }