public async Task Compile_Success()
        {
            var processor    = new Compiler();
            var context      = new Mock <IAssetContext>().SetupAllProperties();
            var asset        = new Mock <IAsset>().SetupAllProperties();
            var env          = new Mock <IWebHostEnvironment>();
            var fileProvider = new Mock <IFileProvider>();

            var inputFile = new PhysicalFileInfo(new FileInfo("foo.less"));

            context.Object.Content = new Dictionary <string, byte[]> {
                { "/file.less", "@foo: 1px; * {margin: @foo}".AsByteArray() },
            };

            context.Setup(s => s.HttpContext.RequestServices.GetService(typeof(IWebHostEnvironment)))
            .Returns(env.Object);

            context.SetupGet(s => s.Asset)
            .Returns(asset.Object);

            env.SetupGet(e => e.WebRootFileProvider)
            .Returns(fileProvider.Object);

            fileProvider.Setup(f => f.GetFileInfo(It.IsAny <string>()))
            .Returns(inputFile);

            await processor.ExecuteAsync(context.Object);

            var result = context.Object.Content.First().Value;

            Assert.Equal("* {\n  margin: 1px;\n}", result.AsString().Trim());
        }
Beispiel #2
0
        public async Task<IActionResult> GetFile(Guid fileId)
        {
            if (!ModelState.IsValid)
            {
                throw new BadRequestException("File Id has to  be specified");
            }

            var remoteFileId = (await _fileFacade.GetSafelyAsync(fileId)).LocationId;

            if (_fileStorage is FileSystemStorage)
            {
                IFileInfo fileInfo = new PhysicalFileInfo(new FileInfo(remoteFileId));

                HttpContext.Response.ContentType = GetContentType(fileInfo.Name);

                var service = HttpContext.Features.Get<IHttpSendFileFeature>();
                if (service != null)
                {
                    await service.SendFileAsync(remoteFileId, 0, fileInfo.Length, CancellationToken.None);
                }
                else
                {
                    await HttpContext.Response.SendFileAsync(fileInfo);
                }
            }
            else
            {
                var result = await _fileStorage.GetAsync(remoteFileId);

                return new FileStreamResult(result.Content, result.ContentType);
            }

            return new EmptyResult();
        }
Beispiel #3
0
        /// <summary>
        /// Locate a file at the given path by directly mapping path segments to physical directories.
        /// </summary>
        /// <param name="subpath">A path under the root directory</param>
        /// <param name="fileInfo">The discovered file, if any</param>
        /// <returns>True if a file was discovered at the given path</returns>
        public bool TryGetFileInfo(string subpath, out IFileInfo fileInfo)
        {
            try
            {
                if (subpath.StartsWith("/", StringComparison.Ordinal))
                {
                    subpath = subpath.Substring(1);
                }
                string fullPath = GetFullPath(subpath);
                if (fullPath != null)
                {
                    var info = new FileInfo(fullPath);
                    if (info.Exists && !IsRestricted(info))
                    {
                        fileInfo = new PhysicalFileInfo(info);
                        return(true);
                    }
                }
            }
            catch (ArgumentException)
            {
            }

            fileInfo = null;
            return(false);
        }
Beispiel #4
0
 public Task Invoke(HttpContext context)
 {
     if (IsGetMethod(context.Request.Method) && IsPluginMatchPath(context.Request.Path) && IsSupportContentType(context))
     {
         string filePath = GetAbsolutePath(context.Request.Path);
         if (File.Exists(filePath))
         {
             var file = new PhysicalFileInfo(new FileInfo(filePath));
             context.Response.ContentLength = file.Length;
             context.Response.StatusCode    = 200;
             var sendFileFeature = context.Features.Get <IHttpSendFileFeature>();
             if (sendFileFeature != null)
             {
                 return(sendFileFeature.SendFileAsync(filePath, 0, file.Length, CancellationToken.None));
             }
             using (var readStream = file.CreateReadStream())
             {
                 var task = StreamCopyOperation.CopyToAsync(readStream, context.Response.Body, file.Length, 64 * 1024, context.RequestAborted);
                 task.Wait();
                 return(task);
             }
         }
     }
     return(_next(context));
 }
        private static void mapStorage(IApplicationBuilder appBuilder)
        {
            var manifestEmbeddedProvider =
                new ManifestEmbeddedFileProvider(Assembly.GetExecutingAssembly());

            appBuilder.Map("/blocklyStorage", app =>
            {
                app.Run(async cnt =>
                {
                    string nameFile = "extensions/SaveToLocalStorage.js";
                    IFileInfo f     = new PhysicalFileInfo(new FileInfo("wwwroot/" + nameFile));

                    if (!f.Exists)
                    {
                        f = manifestEmbeddedProvider.GetFileInfo("blocklyFiles/" + nameFile);
                    }
                    //TODO: add corect mime type for js files
                    using var stream = new MemoryStream();
                    using var cs     = f.CreateReadStream();
                    byte[] buffer    = new byte[2048]; // read in chunks of 2KB
                    int bytesRead;
                    while ((bytesRead = cs.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        stream.Write(buffer, 0, bytesRead);
                    }
                    byte[] result = stream.ToArray();
                    // TODO: do something with the result
                    var m = new Memory <byte>(result);
                    await cnt.Response.BodyWriter.WriteAsync(m);
                });
            });
        }
        public async Task Compile_SuccessAsync()
        {
            var processor    = new Transformer("templates-main");
            var pipeline     = new Mock <IAssetPipeline>().SetupAllProperties();
            var context      = new Mock <IAssetContext>().SetupAllProperties();
            var asset        = new Mock <IAsset>().SetupAllProperties();
            var env          = new Mock <IHostingEnvironment>();
            var fileProvider = new Mock <IFileProvider>();

            context.Object.Content = new Dictionary <string, byte[]> {
                { "/other.html", @"<form ng-submit=ctrl.submitForm(ctrl.formData)>Name:<input type=text ng-model=ctrl.formData.name required><br> Last name:<input type=text ng-model=ctrl.formData.lastname required><br><input type=submit value=Submit></form><pre>{{ctrl.formData}}</pre>'}".AsByteArray() },
            };

            context.Setup(s => s.HttpContext.RequestServices.GetService(typeof(IHostingEnvironment)))
            .Returns(env.Object);

            string temp      = Path.GetTempPath();
            var    inputFile = new PhysicalFileInfo(new FileInfo("other.html"));

            context.SetupGet(s => s.Asset)
            .Returns(asset.Object);

            env.SetupGet(e => e.WebRootFileProvider)
            .Returns(fileProvider.Object);

            fileProvider.Setup(f => f.GetFileInfo(It.IsAny <string>()))
            .Returns(inputFile);

            await processor.ExecuteAsync(context.Object);

            var result = context.Object.Content.First().Value;

            Assert.Equal(@"angular.module('templates-main',[]).run(['$templateCache',function($templateCache){$templateCache.put('other.html','<form ng-submit=ctrl.submitForm(ctrl.formData)>Name:<input type=text ng-model=ctrl.formData.name required><br> Last name:<input type=text ng-model=ctrl.formData.lastname required><br><input type=submit value=Submit></form><pre>{{ctrl.formData}}</pre>\'}');}]);", result.AsString());
        }
        public async Task Compile_Success()
        {
            var processor    = new Compiler();
            var pipeline     = new Mock <IAssetPipeline>().SetupAllProperties();
            var context      = new Mock <IAssetContext>().SetupAllProperties();
            var asset        = new Mock <IAsset>().SetupAllProperties();
            var env          = new Mock <IWebHostEnvironment>();
            var fileProvider = new Mock <IFileProvider>();

            context.Object.Content = new Dictionary <string, byte[]> {
                { "/file.css", "$bg: blue; div {background: $bg}".AsByteArray() },
            };

            context.Setup(s => s.HttpContext.RequestServices.GetService(typeof(IWebHostEnvironment)))
            .Returns(env.Object);

            string temp      = Path.GetTempPath();
            var    inputFile = new PhysicalFileInfo(new FileInfo("site.css"));

            context.SetupGet(s => s.Asset)
            .Returns(asset.Object);

            env.SetupGet(e => e.WebRootFileProvider)
            .Returns(fileProvider.Object);

            fileProvider.Setup(f => f.GetFileInfo(It.IsAny <string>()))
            .Returns(inputFile);

            await processor.ExecuteAsync(context.Object);

            var result = context.Object.Content.First().Value;

            Assert.Equal("div {\n  background: blue; }\n", result.AsString());
        }
        public Task <IFileInfo> MoveTempFile(string tempFileName, string relativeFolderPath, string fileName, string extension, CancellationToken cancellationToken = default(CancellationToken))
        {
            ThrowIfContainsSlashes(tempFileName, nameof(tempFileName));

            var tempFilePath = Path.Combine(tempFolderPath, tempFileName);
            var tempFileInfo = new PhysicalFileInfo(new FileInfo(tempFilePath));

            return(MoveFile(tempFileInfo, relativeFolderPath, fileName, extension, cancellationToken));
        }
        public static IConfigurationBuilder AddCsv(this IConfigurationBuilder configurationBuilder,
                                                   string fileName)
        {
            var file = new PhysicalFileInfo(new FileInfo(fileName));

            configurationBuilder.Add(new CsvConfigurationSource {
                Stream = file.CreateReadStream()
            });
            return(configurationBuilder);
        }
        public async Task UploadFile_FromFileInfo_ExpectedSkylink()
        {
            // Arrange
            var file = new PhysicalFileInfo(new FileInfo("assets/test-file.json"));

            // Act
            var skylink = await _skynetWebPortal.UploadFile(file);

            // Assert
            Assert.That(skylink.ToString() == "AACcDsB0hiRosExg1JlERWIJP5MVYiAS2F5EkU8VLtlPrA");
        }
        public async Task CssImageInliner_Success(string url, string newUrl)
        {
            var processor    = new CssImageInliner(5120);
            var context      = new Mock <IAssetContext>().SetupAllProperties();
            var pipeline     = new Mock <IAssetPipeline>().SetupAllProperties();
            var asset        = new Mock <IAsset>().SetupAllProperties();
            var env          = new Mock <IWebHostEnvironment>();
            var fileProvider = new Mock <IFileProvider>();

            string temp = Path.GetTempPath();
            string path = Path.Combine(temp, "css", "img");

            Directory.CreateDirectory(path);
            string imagePath = Path.Combine(path, "test.png");

            File.WriteAllText(imagePath, "empty");
            File.SetLastWriteTime(imagePath, new DateTime(2017, 1, 1));

            var inputFile  = new PhysicalFileInfo(new FileInfo(Path.Combine(temp, "css", "site.css")));
            var outputFile = new PhysicalFileInfo(new FileInfo(Path.Combine(temp, "dist", "all.css")));

            context.SetupGet(s => s.Asset.Route)
            .Returns("/my/route.css");

            context.Setup(s => s.HttpContext.RequestServices.GetService(typeof(IAssetPipeline)))
            .Returns(pipeline.Object);

            context.Setup(s => s.HttpContext.RequestServices.GetService(typeof(IWebHostEnvironment)))
            .Returns(env.Object);

            context.SetupGet(s => s.Asset)
            .Returns(asset.Object);

            env.SetupGet(e => e.WebRootFileProvider)
            .Returns(fileProvider.Object);

            env.SetupGet(e => e.WebRootPath)
            .Returns(temp);

            fileProvider.SetupSequence(f => f.GetFileInfo(It.IsAny <string>()))
            .Returns(inputFile)
            .Returns(outputFile);

            context.Object.Content = new Dictionary <string, byte[]> {
                { "css/site.css", url.AsByteArray() }
            };


            await processor.ExecuteAsync(context.Object);

            string result = context.Object.Content.First().Value.AsString();

            Assert.Equal(newUrl, result);
        }
        public async Task <FileEntryInfo> GetFileInfoAsync(string path)
        {
            var physicalPath = GetPhysicalPath(path);
            var fileInfo     = new PhysicalFileInfo(new FileInfo(physicalPath));

            if (fileInfo.Exists)
            {
                return(await Task.FromResult(new FileEntryInfo(path, fileInfo)));
            }

            return(null);
        }
        public async Task UploadFile_FromUploadItemDifferentSkynetPath_ExpectedSkylink()
        {
            // Arrange
            var file = new PhysicalFileInfo(new FileInfo("assets/test-file.json"));
            var item = new UploadItem(file, skynetPath: "custom/directory/test-file.json");

            // Act
            var skylink = await _skynetWebPortal.UploadFile(item);

            // Assert
            Assert.That(skylink.ToString() == "AADoxsbpEVLgFTMco_fS3eiTAvtKx5WCfll5wqHEfyksrQ");
        }
        public async Task UploadFile_FromUploadItemDifferentContentType_ExpectedSkylink()
        {
            // Arrange
            var file = new PhysicalFileInfo(new FileInfo("assets/test-file.json"));
            var item = new UploadItem(file, contentType: new MediaTypeHeaderValue("text/xml"));

            // Act
            var skylink = await _skynetWebPortal.UploadFile(item);

            // Assert
            Assert.That(skylink.ToString() == "AABDI5UpS0B8tuxKBOiwwKEULV7V4Ln_aBdPPFLWpTlFhA");
        }
        private static IStyle parseTestStyle()
        {
            var fileInfo           = new PhysicalFileInfo(new System.IO.FileInfo(@"C:\Playground\AbsoluteGraphicsPlatform\tests\TestFiles\TestStyle1.dss"));
            var expressionExecutor = new ExpressionExecutor();
            var dssParser          = new DssParser();
            var dssCompiler        = new DssCompiler(expressionExecutor);

            var sourceInfo   = new SourceCodeInfo(fileInfo);
            var instructions = dssParser.Parse(sourceInfo);
            var style        = dssCompiler.Compile(instructions);

            return(style);
        }
Beispiel #16
0
        public static IFileInfo FindFile(string filePath)
        {
            var fileWithFullDirectoryPath = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filePath));

            IFileInfo fileInfo = null;

            if (fileWithFullDirectoryPath.Equals(appConstantsPath, StringComparison.OrdinalIgnoreCase) && File.Exists(fileWithFullDirectoryPath))
            {
                fileInfo = new PhysicalFileInfo(new FileInfo(fileWithFullDirectoryPath));
            }

            return(fileInfo);
        }
Beispiel #17
0
        public Task <IFileStoreEntry> GetFileInfoAsync(string path)
        {
            var physicalPath = GetPhysicalPath(path);

            var fileInfo = new PhysicalFileInfo(new FileInfo(physicalPath));

            if (fileInfo.Exists)
            {
                return(Task.FromResult <IFileStoreEntry>(new FileSystemStoreEntry(path, fileInfo)));
            }

            return(Task.FromResult <IFileStoreEntry>(null));
        }
        /// <summary>
        /// Enumerate a directory at the given path, if any.
        /// </summary>
        /// <param name="subpath">A path under the root directory</param>
        /// <param name="contents">The discovered directories, if any</param>
        /// <returns>True if a directory was discovered at the given path</returns>
        public bool TryGetDirectoryContents(string subpath, out IEnumerable <IFileInfo> contents)
        {
            //Console.WriteLine("[LOG.FILE] ====> " + subpath);

            try
            {
                if (subpath.StartsWith("/", StringComparison.Ordinal))
                {
                    subpath = subpath.Substring(1);
                }
                var fullPath = GetFullPath(subpath);
                if (fullPath != null)
                {
                    var directoryInfo = new DirectoryInfo(fullPath);
                    if (!directoryInfo.Exists)
                    {
                        contents = null;
                        return(false);
                    }

                    FileSystemInfo[] physicalInfos = directoryInfo.GetFileSystemInfos();
                    var virtualInfos = new IFileInfo[physicalInfos.Length];
                    for (int index = 0; index != physicalInfos.Length; ++index)
                    {
                        var fileInfo = physicalInfos[index] as FileInfo;
                        if (fileInfo != null)
                        {
                            virtualInfos[index] = new PhysicalFileInfo(fileInfo);
                        }
                        else
                        {
                            virtualInfos[index] = new PhysicalDirectoryInfo((DirectoryInfo)physicalInfos[index]);
                        }
                    }
                    contents = virtualInfos;
                    return(true);
                }
            }
            catch (ArgumentException)
            {
            }
            catch (DirectoryNotFoundException)
            {
            }
            catch (IOException)
            {
            }
            contents = null;
            return(false);
        }
Beispiel #19
0
        /// <summary>
        /// 取得文件信息
        /// </summary>
        /// <param name="relativePath">相对路径</param>
        /// <param name="rootPhysicalPath">物理根路径</param>
        /// <returns>文件信息</returns>
        public IFileEntity GetFileInfo(string relativePath, string rootPhysicalPath)
        {
            var path     = GetFilePhysicalPath(relativePath, rootPhysicalPath);
            var fileInfo = new PhysicalFileInfo(new FileInfo(path));

            return(fileInfo.Exists ? new FileManageEntity
            {
                FilePhysicalPath = path,
                IsDirectory = fileInfo.IsDirectory,
                LastModified = fileInfo.LastModified.UtcDateTime,
                Length = fileInfo.Length,
                RelativePath = relativePath,
                Name = fileInfo.Name
            } : null);
        }
        public void GetPlainTextTestEmail_WhenInvoke_ShouldReturnNotNullEmailMessage()
        {
            _webHostEnvMock.DefaultValue = DefaultValue.Mock;
            var provider     = _webHostEnvMock.Object.ContentRootFileProvider;
            var providerMock = Mock.Get(provider);
            var fileMock     = new PhysicalFileInfo
                                   (new FileInfo(_fileInfoPath));

            providerMock.Setup(x => x.GetFileInfo(It.IsAny <string>()))
            .Returns(fileMock);
            EmailTemplates.Initialize(_webHostEnvMock.Object);
            DateTime testDate = new DateTime(2020, 1, 1);

            string emailMessage = EmailTemplates.GetPlainTextTestEmail(testDate);

            Assert.IsNotNull(emailMessage);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="subpath">A path under the root directory</param>
        /// <param name="contents">The discovered directories, if any</param>
        /// <returns>True if a directory was discovered at the given path</returns>
        public bool TryGetDirectoryContents(string subpath, out IEnumerable <IFileInfo> contents)
        {
            try
            {
                var fullPath = GetFullPath(subpath);
                if (fullPath != null)
                {
                    var directoryInfo = new DirectoryInfo(fullPath);
                    if (!directoryInfo.Exists)
                    {
                        contents = null;
                        return(false);
                    }

                    FileSystemInfo[] physicalInfos = directoryInfo.GetFileSystemInfos();
                    var virtualInfos = new IFileInfo[physicalInfos.Length];
                    for (int index = 0; index != physicalInfos.Length; ++index)
                    {
                        var fileInfo = physicalInfos[index] as FileInfo;
                        if (fileInfo != null)
                        {
                            virtualInfos[index] = new PhysicalFileInfo(fileInfo);
                        }
                        else
                        {
                            virtualInfos[index] = new PhysicalDirectoryInfo((DirectoryInfo)physicalInfos[index]);
                        }
                    }
                    contents = virtualInfos;
                    return(true);
                }
            }
            catch (ArgumentException)
            {
            }
            catch (DirectoryNotFoundException)
            {
            }
            catch (IOException)
            {
            }
            contents = null;
            return(false);
        }
        public async Task UploadFiles_FromFileInfo_ExpectedSkylink()
        {
            // Arrange
            var files = new PhysicalFileInfo[]
            {
                new PhysicalFileInfo(new FileInfo("assets/test-file.json")),
                new PhysicalFileInfo(new FileInfo("assets/test-file.txt"))
            };

            var options = new MultiFileUploadOptions {
                FileName = "integration-tests"
            };

            // Act
            var skylink = await _skynetWebPortal.UploadFiles(files, options);

            // Assert
            Assert.That(skylink.ToString() == "AACVmVl_KyZTaaS2cdGANxedYtOGJu13urqfc_yQl5jL8w");
        }
        public IAsyncEnumerable <IFileStoreEntry> GetDirectoryContentAsync(string path = null, bool includeSubDirectories = false)
        {
            try
            {
                var physicalPath = GetPhysicalPath(path);
                var results      = new List <IFileStoreEntry>();

                if (!Directory.Exists(physicalPath))
                {
                    return(results.ToAsyncEnumerable());
                }

                // Add directories.
                results.AddRange(
                    Directory
                    .GetDirectories(physicalPath, "*", includeSubDirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly)
                    .Select(f =>
                {
                    var fileSystemInfo   = new PhysicalDirectoryInfo(new DirectoryInfo(f));
                    var fileRelativePath = f.Substring(_fileSystemPath.Length);
                    var filePath         = this.NormalizePath(fileRelativePath);
                    return(new FileSystemStoreEntry(filePath, fileSystemInfo));
                }));

                // Add files.
                results.AddRange(
                    Directory
                    .GetFiles(physicalPath, "*", includeSubDirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly)
                    .Select(f =>
                {
                    var fileSystemInfo   = new PhysicalFileInfo(new FileInfo(f));
                    var fileRelativePath = f.Substring(_fileSystemPath.Length);
                    var filePath         = this.NormalizePath(fileRelativePath);
                    return(new FileSystemStoreEntry(filePath, fileSystemInfo));
                }));

                return(results.ToAsyncEnumerable());
            }
            catch (Exception ex)
            {
                throw new FileStoreException($"Cannot get directory content with path '{path}'.", ex);
            }
        }
        /// <summary>
        /// Creates a file at the given path.
        /// </summary>
        /// <param name="subpath">A path under the root directory</param>
        /// <returns>
        /// The file information. Caller must check
        /// <see cref="IFileInfo.Exists"/> property.
        /// </returns>
        public IFileInfo CreateFile(string subpath)
        {
            PhysicalFileInfo?physicalFileInfo = null;
            var fileInfo = this.GetFileInfo(subpath);

            if (!(fileInfo is NotFoundFileInfo))
            {
                var fileSystemInfo = new FileInfo(fileInfo.PhysicalPath);
                if (!fileSystemInfo.Exists)
                {
                    fileSystemInfo.Create();
                    fileSystemInfo.Refresh();
                }

                physicalFileInfo = new PhysicalFileInfo(fileSystemInfo);
            }

            return(physicalFileInfo ?? fileInfo);
        }
Beispiel #25
0
        public IList <IFileStoreEntry> GetDirectoryContent(string path = null, bool includeSubDirectories = false, bool listDirectories = true, bool listFiles = true)
        {
            var physicalPath = GetPhysicalPath(path);
            var results      = new List <IFileStoreEntry>();

            if (!Directory.Exists(physicalPath))
            {
                return(results.ToList());
            }

            // Add directories.
            if (listDirectories)
            {
                results.AddRange(
                    Directory
                    .GetDirectories(physicalPath, "*", includeSubDirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly)
                    .Select(f =>
                {
                    var fileSystemInfo   = new PhysicalDirectoryInfo(new DirectoryInfo(f));
                    var fileRelativePath = f.Substring(_fileSystemPath.Length);
                    var filePath         = this.NormalizePath(fileRelativePath);
                    return(new FileSystemStoreEntry(filePath, fileSystemInfo));
                }));
            }

            // Add files.
            if (listFiles)
            {
                results.AddRange(
                    Directory
                    .GetFiles(physicalPath, "*", includeSubDirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly)
                    .Select(f =>
                {
                    var fileSystemInfo   = new PhysicalFileInfo(new FileInfo(f));
                    var fileRelativePath = f.Substring(_fileSystemPath.Length);
                    var filePath         = this.NormalizePath(fileRelativePath);
                    return(new FileSystemStoreEntry(filePath, fileSystemInfo));
                }));
            }

            return(results.ToList());
        }
Beispiel #26
0
        /// <summary>
        /// 创建文件
        /// </summary>
        /// <param name="relativePath">相对路径</param>
        /// <param name="rootPhysicalPath">物理根路径</param>
        /// <param name="fileStream">文件流</param>
        public async Task <IFileEntity> CreateFile(string relativePath, string rootPhysicalPath, Stream fileStream)
        {
            var path = GetFilePhysicalPath(relativePath, rootPhysicalPath);

            using (var stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
            {
                await fileStream.CopyToAsync(stream);
            }
            var fileInfo = new PhysicalFileInfo(new FileInfo(path));

            return(new FileManageEntity
            {
                FilePhysicalPath = path,
                IsDirectory = fileInfo.IsDirectory,
                LastModified = fileInfo.LastModified.UtcDateTime,
                Length = fileInfo.Length,
                RelativePath = relativePath,
                Name = fileInfo.Name
            });
        }
        public Task <IFileStoreEntry> GetFileInfoAsync(string path)
        {
            try
            {
                var physicalPath = GetPhysicalPath(path);

                var fileInfo = new PhysicalFileInfo(new FileInfo(physicalPath));

                if (fileInfo.Exists)
                {
                    return(Task.FromResult <IFileStoreEntry>(new FileSystemStoreEntry(path, fileInfo)));
                }

                return(Task.FromResult <IFileStoreEntry>(null));
            }
            catch (Exception ex)
            {
                throw new FileStoreException($"Cannot get file info with path '{path}'.", ex);
            }
        }
        public void GetTestEmail_ForTestDate_ShouldReplaceTestDate()
        {
            _webHostEnvMock.DefaultValue = DefaultValue.Mock;
            var provider     = _webHostEnvMock.Object.ContentRootFileProvider;
            var providerMock = Mock.Get(provider);
            var fileMock     = new PhysicalFileInfo
                                   (new FileInfo(_fileInfoPath));

            providerMock.Setup(x => x.GetFileInfo(It.IsAny <string>()))
            .Returns(fileMock);
            EmailTemplates.Initialize(_webHostEnvMock.Object);
            string   recipentName  = "TestRecipent";
            DateTime testDate      = new DateTime(2020, 1, 1);
            string   textToReplace = "{testDate}";

            string emailMessage = EmailTemplates.GetTestEmail(recipentName, testDate);

            bool result = emailMessage.Contains(textToReplace);

            Assert.IsFalse(result);
        }
 /// <summary>
 ///
 /// </summary>
 /// <param name="subpath">A path under the root directory</param>
 /// <param name="fileInfo">The discovered file, if any</param>
 /// <returns>True if a file was discovered at the given path</returns>
 public bool TryGetFileInfo(string subpath, out IFileInfo fileInfo)
 {
     try
     {
         var fullPath = GetFullPath(subpath);
         if (fullPath != null)
         {
             var info = new FileInfo(fullPath);
             if (info.Exists)
             {
                 fileInfo = new PhysicalFileInfo(info);
                 return(true);
             }
         }
     }
     catch (ArgumentException)
     {
     }
     fileInfo = null;
     return(false);
 }
Beispiel #30
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="subpath">A path under the root directory</param>
 /// <param name="fileInfo">The discovered file, if any</param>
 /// <returns>True if a file was discovered at the given path</returns>
 public bool TryGetFileInfo(string subpath, out IFileInfo fileInfo)
 {
     try
     {
         var fullPath = GetFullPath(subpath);
         if (fullPath != null)
         {
             var info = new FileInfo(fullPath);
             if (info.Exists)
             {
                 fileInfo = new PhysicalFileInfo(info);
                 return true;
             }
         }
     }
     catch (ArgumentException)
     {
     }
     fileInfo = null;
     return false;
 }
Beispiel #31
0
        public async Task AdjustRelativePaths_Success(string url, string newUrl)
        {
            var adjuster     = new RelativePathAdjuster();
            var context      = new Mock <IAssetContext>().SetupAllProperties();
            var pipeline     = new Mock <IAssetPipeline>().SetupAllProperties();
            var inputFile    = new PhysicalFileInfo(new FileInfo(@"c:\source\css\site.css"));
            var outputFile   = new PhysicalFileInfo(new FileInfo(@"c:\source\dist\all.css"));
            var asset        = new Mock <IAsset>().SetupAllProperties();
            var env          = new Mock <IWebHostEnvironment>();
            var fileProvider = new Mock <IFileProvider>();

            context.SetupGet(s => s.Asset.Route)
            .Returns("/my/route.css");

            context.Setup(s => s.HttpContext.RequestServices.GetService(typeof(IAssetPipeline)))
            .Returns(pipeline.Object);

            context.Setup(s => s.HttpContext.RequestServices.GetService(typeof(IWebHostEnvironment)))
            .Returns(env.Object);

            context.SetupGet(s => s.Asset)
            .Returns(asset.Object);

            env.SetupGet(e => e.WebRootFileProvider)
            .Returns(fileProvider.Object);

            fileProvider.SetupSequence(f => f.GetFileInfo(It.IsAny <string>()))
            .Returns(inputFile)
            .Returns(outputFile);

            context.Object.Content = new Dictionary <string, byte[]> {
                { "css/site.css", url.AsByteArray() }
            };

            await adjuster.ExecuteAsync(context.Object);

            Assert.Equal(newUrl, context.Object.Content.First().Value.AsString());
            Assert.Equal("", adjuster.CacheKey(new DefaultHttpContext()));
        }
        /// <summary>
        /// Enumerate a directory at the given path, if any.
        /// </summary>
        /// <param name="subpath">A path under the root directory</param>
        /// <param name="contents">The discovered directories, if any</param>
        /// <returns>True if a directory was discovered at the given path</returns>
        public bool TryGetDirectoryContents(string subpath, out IEnumerable<IFileInfo> contents)
        {
            try
            {
                if (subpath.StartsWith("/", StringComparison.Ordinal))
                {
                    subpath = subpath.Substring(1);
                }
                var fullPath = GetFullPath(subpath);
                if (fullPath != null)
                {
                    var directoryInfo = new DirectoryInfo(fullPath);
                    if (!directoryInfo.Exists)
                    {
                        contents = null;
                        return false;
                    }

                    FileSystemInfo[] physicalInfos = directoryInfo.GetFileSystemInfos();
                    var virtualInfos = new IFileInfo[physicalInfos.Length];
                    for (int index = 0; index != physicalInfos.Length; ++index)
                    {
                        var fileInfo = physicalInfos[index] as FileInfo;
                        if (fileInfo != null)
                        {
                            virtualInfos[index] = new PhysicalFileInfo(fileInfo);
                        }
                        else
                        {
                            virtualInfos[index] = new PhysicalDirectoryInfo((DirectoryInfo)physicalInfos[index]);
                        }
                    }
                    contents = virtualInfos;
                    return true;
                }
            }
            catch (ArgumentException)
            {
            }
            catch (DirectoryNotFoundException)
            {
            }
            catch (IOException)
            {
            }
            contents = null;
            return false;
        }
 /// <summary>
 /// Locate a file at the given path by directly mapping path segments to physical directories.
 /// </summary>
 /// <param name="subpath">A path under the root directory</param>
 /// <param name="fileInfo">The discovered file, if any</param>
 /// <returns>True if a file was discovered at the given path</returns>
 public bool TryGetFileInfo(string subpath, out IFileInfo fileInfo)
 {
     try
     {
         if (subpath.StartsWith("/", StringComparison.Ordinal))
         {
             subpath = subpath.Substring(1);
         }
         var fullPath = GetFullPath(subpath);
         if (fullPath != null)
         {
             var info = new FileInfo(fullPath);
             if (info.Exists && !IsRestricted(info))
             {
                 fileInfo = new PhysicalFileInfo(info);
                 return true;
             }
         }
     }
     catch (ArgumentException)
     {
     }
     fileInfo = null;
     return false;
 }