public override IEnumerable <RazorProjectItem> EnumerateItems(string path)
        {
//            path = NormalizeAndEnsureValidPath( path );
            var directoryContents = _provider.GetDirectoryContents(path);

            return(EnumerateFiles(directoryContents, path, string.Empty));
        }
Example #2
0
        public IActionResult ShowImages()
        {
            ViewBag.ConnectionString = configuration.GetSection("MySQL").Value;
            var files = fileProvider.GetDirectoryContents("wwwroot/images").ToList().Select(x => x.Name);

            return(View(files));
        }
Example #3
0
        public Task Initialize()
        {
            if (_fileProvider.GetDirectoryContents(ELEVATION_CACHE).Any() == false)
            {
                _logger.LogError($"!!! The folder: {ELEVATION_CACHE} does not exists, please change the BinariesFolder key in the configuration file !!!");
                return(Task.CompletedTask);
            }
            var hgtZipFiles = _fileProvider.GetDirectoryContents(ELEVATION_CACHE);

            _logger.LogInformation("Found " + hgtZipFiles.Count() + " files in: " + _fileProvider.GetFileInfo(ELEVATION_CACHE).PhysicalPath);
            foreach (var hgtZipFile in hgtZipFiles)
            {
                var bottomLeftLat = int.Parse(hgtZipFile.Name.Substring(1, 2));
                var bottomLeftLng = int.Parse(hgtZipFile.Name.Substring(4, 3));
                var key           = new Coordinate(bottomLeftLng, bottomLeftLat);

                _initializationTaskPerLatLng[key] = Task.Run(() =>
                {
                    _logger.LogInformation("Reading file " + hgtZipFile.Name);
                    var byteArray      = GetByteArrayFromZip(hgtZipFile);
                    int samples        = (short)(Math.Sqrt(byteArray.Length / 2.0) + 0.5);
                    var elevationArray = new short[samples, samples];
                    for (int byteIndex = 0; byteIndex < byteArray.Length; byteIndex += 2)
                    {
                        short currentElevation = BitConverter.ToInt16(new[] { byteArray[byteIndex + 1], byteArray[byteIndex] }, 0);
                        elevationArray[(byteIndex / 2) / samples, (byteIndex / 2) % samples] = currentElevation;
                    }
                    _elevationData[key] = elevationArray;
                    _logger.LogInformation("Finished reading file " + hgtZipFile.Name);
                });
            }

            return(Task.WhenAll(_initializationTaskPerLatLng.Values));
        }
        public IActionResult OnGet(string id, string rev)
        {
            IDirectoryContents file;

            // get the appropriate markdown folder for the console and revision to interrogate if it exists
            if (rev != null)
            {
                file = _files.GetDirectoryContents("markdown/consoles/" + id + "/" + rev);
            }
            else
            {
                file = _files.GetDirectoryContents("markdown/consoles/" + id);
            }

            // if revision is invalid redirect to generic console
            if (rev != null && !file.Exists)
            {
                return(Redirect("/console/" + id));
            }

            // if generic console is invalid redirect to home page
            if (!file.Exists)
            {
                return(Redirect("/"));
            }

            console  = id;
            revision = rev;

            return(Page());
        }
        public IActionResult Logs([FromBody] dynamic value)
        {
            try
            {
                string svalue = Convert.ToString(value);

                dynamic partnerJsonEntity = JsonConvert.DeserializeObject(svalue);

                var username = partnerJsonEntity["un"].Value;
                var password = partnerJsonEntity["pw"].Value;

                //Auth
                var authResult = IsValidUserAndPasswordCombination(username, password);


                if (authResult.Result.result)
                {
                    var contents = _fileProvider.GetDirectoryContents("Logs");
                    return(Json(new
                    {
                        contents
                    }));
                }
                else
                {
                    return(Json("failed"));
                }
            }
            catch
            {
                return(Json("failed"));
            }
        }
        public void OnProvidersExecuting(ApplicationModelProviderContext context)
        {
            IEnumerable <string> files;
            bool standardHandling = true;

            _app.OnControllersCreation(out files, ref standardHandling);

            var sources = new List <IFileInfo>();

            if (files != null)
            {
                sources.AddRange(files.Select(x => new PhysicalFileInfo(new FileInfo(x))));
            }

            if (standardHandling)
            {
                // прямые контроллеры
                var filesystemSources = _scriptsProvider.GetDirectoryContents(CONTROLLERS_FOLDER).Where(x => !x.IsDirectory && x.PhysicalPath.EndsWith(".os"));
                sources.AddRange(filesystemSources);

                // контроллеры в папках
                filesystemSources = _scriptsProvider.GetDirectoryContents(CONTROLLERS_FOLDER)
                                    .Where(x => x.IsDirectory);

                sources.AddRange(filesystemSources);
            }

            FillContext(sources, context);
        }
        public IDirectoryContents GetDirectoryContents(string subpath)
        {
            var folder = NormalizePath(subpath);

            if (folder == "")
            {
                return(_fileProvider.GetDirectoryContents(subpath));
            }

            if (folder == Application.ModulesPath)
            {
                return(_fileProvider.GetDirectoryContents(subpath));
            }

            if (folder.StartsWith(Application.ModulesRoot, StringComparison.Ordinal))
            {
                if (folder.Substring(Application.ModulesRoot.Length).IndexOf('/') == -1)
                {
                    return(_fileProvider.GetDirectoryContents(subpath));
                }

                var tokenizer = new StringTokenizer(folder, new char[] { '/' });
                if (tokenizer.Any(s => s == "Pages" || s == "Components"))
                {
                    return(_fileProvider.GetDirectoryContents(subpath));
                }
            }

            return(new NotFoundDirectoryContents());
        }
Example #8
0
        public ActionResult <string> GetFile(string name)
        {
            try
            {
                var contents = _fileProvider.GetDirectoryContents("Uploads").ToList();
                var file     = contents.FirstOrDefault(x => x.Name == name);

                XmlDocument doc = new XmlDocument();
                doc.Load(file.PhysicalPath);
                RemoveAllNamespaces(doc.InnerXml);
                string measurementUnit    = doc.GetElementsByTagName("MeasurementUnit")[0].InnerText;
                string processingDateTime = doc.GetElementsByTagName("processingDateTime")[0].InnerText;
                string softwareCreator    = doc.GetElementsByTagName("softwareCreator")[0].InnerText;
                string softwareName       = doc.GetElementsByTagName("softwareCreator")[0].InnerText;
                string softwareVersion    = doc.GetElementsByTagName("softwareVersion")[0].InnerText;
                string text = name.ToLower().Replace(".xml", "") + ":::" + "<Description><MeasurementUnit> " + measurementUnit + " </MeasurementUnit><processingDateTime>" + processingDateTime + "</processingDateTime><softwareCreator>" + softwareCreator + "</softwareCreator><softwareName>" + softwareName + "</softwareName><softwareVersion>" + softwareVersion + "</softwareVersion></Description>";


                var config = new ConfigurationBuilder()
                             .AddJsonFile("appsettings.json")
                             .Build();
                IConfigurationSection section = config.GetSection("RabbitMqConnection");

                RabbitMQPublisher mq = new RabbitMQPublisher();
                mq.SendMessage(section, text);

                return(text);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #9
0
        public IDirectoryContents GetDirectoryContents(string subpath)
        {
            var folder = NormalizePath(subpath);

            if (folder == "")
            {
                return(_fileProvider.GetDirectoryContents(subpath));
            }

            foreach (var path in _paths)
            {
                if (folder.StartsWith(path, StringComparison.Ordinal))
                {
                    if (folder.Length == path.Length || folder.Contains("/Pages") ||
                        folder.Substring(path.Length + 1).IndexOf('/') == -1)
                    {
                        return(_fileProvider.GetDirectoryContents(subpath));
                    }

                    break;
                }
            }

            return(new NotFoundDirectoryContents());
        }
Example #10
0
        /// <summary>
        ///  Loads the suplimentary localaization files via the file provider.
        /// </summary>
        /// <remarks>
        ///  locates all *.xml files in the lang folder of any sub folder of the one provided.
        ///  e.g /app_plugins/plugin-name/lang/*.xml
        /// </remarks>
        private static IEnumerable <LocalizedTextServiceSupplementaryFileSource> GetPluginLanguageFileSources(
            IFileProvider fileProvider, string folder, bool overwriteCoreKeys)
        {
            IEnumerable <IFileInfo> pluginFolders = fileProvider
                                                    .GetDirectoryContents(folder)
                                                    .Where(x => x.IsDirectory);

            foreach (IFileInfo pluginFolder in pluginFolders)
            {
                // get the full virtual path for the plugin folder
                var pluginFolderPath = WebPath.Combine(folder, pluginFolder.Name);

                // loop through the lang folder(s)
                //  - there could be multiple on case sensitive file system
                foreach (var langFolder in GetLangFolderPaths(fileProvider, pluginFolderPath))
                {
                    // request all the files out of the path, these will have physicalPath set.
                    IEnumerable <FileInfo> localizationFiles = fileProvider
                                                               .GetDirectoryContents(langFolder)
                                                               .Where(x => !string.IsNullOrEmpty(x.PhysicalPath))
                                                               .Where(x => x.Name.InvariantEndsWith(".xml"))
                                                               .Select(x => new FileInfo(x.PhysicalPath));

                    foreach (FileInfo file in localizationFiles)
                    {
                        yield return(new LocalizedTextServiceSupplementaryFileSource(file, overwriteCoreKeys));
                    }
                }
            }
        }
        public IActionResult Index()
        {
            var images = _fileProvider.GetDirectoryContents("wwwroot/images")
                         .ToList()
                         .Select(x => x.Name);

            return(View(images));
        }
Example #12
0
        public async Task OnGetAsync()
        {
            DatabaseFiles = await _context.File.AsNoTracking().ToListAsync();

            PhysicalFiles = _fileProvider.GetDirectoryContents(string.Empty);
            ModelFiles    = _fileProvider.GetDirectoryContents("\\model\\");
            DataFiles     = _fileProvider.GetDirectoryContents("\\data\\");
        }
Example #13
0
        public IActionResult Index(string dd1)
        {
            string   device = "";
            string   selected = "";
            string   start = null;
            string   end = null;
            DateTime start_d, end_d;

            if (Request.Method == "POST")
            {
                device   = Request.Form["ddl"];
                selected = device;
                start    = Request.Form["start"];
                end      = Request.Form["end"];
                if (start.Length > 0 && end.Length > 0)
                {
                    start_d = FromString(start);
                    end_d   = FromString(end);
                }
            }

            start_d = FromString(start);
            end_d   = FromString(end);

            IndexModel content = new IndexModel();

            content.Files   = _fileProvider.GetDirectoryContents("/files/" + device + "/gzip");
            content.Devices = _fileProvider.GetDirectoryContents("/files/");

            IFileInfo[] files = _fileProvider.GetDirectoryContents("/files/" + device + "/gzip").OrderBy(p => p.LastModified).ToArray();

            content.filesSorted = files;

            string        pattern = @"^(device)[(0-9)]";
            List <string> df      = new List <string>();

            foreach (var item in content.Devices)
            {
                if (Regex.IsMatch(item.Name.ToString(), pattern, RegexOptions.IgnoreCase))
                {
                    df.Add(item.Name.ToString());
                }
            }

            content.deviceFolders = df;

            content.selected = selected;
            content.start    = start;
            content.end      = end;
            if (start_d != null && end_d != null)
            {
                content.start_d = start_d;
                content.end_d   = end_d;
            }


            return(View(content));
        }
Example #14
0
        protected void CreateDataDirectoryIfNotExists()
        {
            var directory = FileProvider.GetDirectoryContents(DataDirectory);

            if (directory.Exists == false)
            {
                var di = new DirectoryInfo(FileProvider.GetFileInfo(DataDirectory).PhysicalPath);
                di.Create();
            }
        }
Example #15
0
        public ActionResult CreatePhysical()
        {
            var contents = _fileProvider.GetDirectoryContents(string.Empty);
            StreamFileUploadDatabase model = new StreamFileUploadDatabase()
            {
                PhysicalFiles = contents
            };

            return(View(model));
        }
        public Task Initialize()
        {
            if (_fileProvider.GetDirectoryContents(ELEVATION_CACHE).Any() == false)
            {
                _logger.LogError($"!!! The folder: {ELEVATION_CACHE} does not exists, please change the BinariesFolder key in the configuration file !!!");
                return(Task.CompletedTask);
            }
            var hgtZipFiles = _fileProvider.GetDirectoryContents(ELEVATION_CACHE);

            _logger.LogInformation("Found " + hgtZipFiles.Count() + " files in: " + _fileProvider.GetFileInfo(ELEVATION_CACHE).PhysicalPath);
            foreach (var hgtZipFile in hgtZipFiles)
            {
                var match = HGT_NAME.Match(hgtZipFile.Name);
                if (!match.Success)
                {
                    _logger.LogWarning($"File {hgtZipFile.Name} in elevation cache does not match naming rules");
                    continue;
                }

                var latHem        = match.Groups["latHem"].Value == "N" ? 1 : -1;
                var bottomLeftLat = int.Parse(match.Groups["lat"].Value) * latHem;
                var lonHem        = match.Groups["lonHem"].Value == "E" ? 1 : -1;
                var bottomLeftLng = int.Parse(match.Groups["lon"].Value) * lonHem;
                var key           = new Coordinate(bottomLeftLng, bottomLeftLat);

                _initializationTaskPerLatLng[key] = Task.Run(() =>
                {
                    _logger.LogInformation("Reading file " + hgtZipFile.Name);
                    var byteArray = GetByteArrayFromZip(hgtZipFile);
                    if (byteArray == null)
                    {
                        _logger.LogError($"Unable to find hgt file in: {hgtZipFile.Name}");
                        return;
                    }

                    int samples        = (short)(Math.Sqrt(byteArray.Length / 2.0) + 0.5);
                    var elevationArray = new short[samples, samples];
                    for (int byteIndex = 0; byteIndex < byteArray.Length; byteIndex += 2)
                    {
                        short currentElevation = BitConverter.ToInt16(new[] { byteArray[byteIndex + 1], byteArray[byteIndex] }, 0);
                        // if hgt file contains -32768, use 0 instead
                        if (currentElevation == short.MinValue)
                        {
                            currentElevation = 0;
                        }

                        elevationArray[(byteIndex / 2) / samples, (byteIndex / 2) % samples] = currentElevation;
                    }
                    _elevationData[key] = elevationArray;
                    _logger.LogInformation("Finished reading file " + hgtZipFile.Name);
                });
            }

            return(Task.WhenAll(_initializationTaskPerLatLng.Values));
        }
        public void Test()
        {
            Assert.IsFalse(fp.GetDirectoryContents("/nonexisting").Exists);
            Assert.IsTrue(fp.GetDirectoryContents("/tmp").Exists);
            Assert.IsTrue(fp.GetDirectoryContents("/tmp/dir").Exists);
            Assert.IsTrue(fp.GetDirectoryContents("c:").Exists);
            Assert.IsFalse(fp.GetDirectoryContents("/tmp/helloworld.txt").Exists);
            Assert.IsTrue(fp.GetFileInfo("/tmp/helloworld.txt").Exists);
            Assert.IsFalse(fp.GetFileInfo("/tmp").Exists);

            // Read file
            using (Stream s = fp.GetFileInfo("/tmp/helloworld.txt").CreateReadStream())
            {
                byte[] data = new byte[100];
                int    c    = s.Read(data, 0, 100);
                Assert.AreEqual(c, HelloWorld.Length);
                for (int i = 0; i < c; i++)
                {
                    Assert.AreEqual(data[i], HelloWorld[i]);
                }
            }

            // Observe
            IChangeToken token      = fp.Watch("/tmp/**");
            Semaphore    semaphore  = new Semaphore(0, int.MaxValue);
            IDisposable  disposable = token.RegisterChangeCallback(o => semaphore.Release(), null);

            // Test, not activated
            Assert.IsFalse(semaphore.WaitOne(300));
            Assert.IsFalse(token.HasChanged);

            // Test, not activated
            ram.CreateFile("/not-monited-path.txt");
            Assert.IsFalse(semaphore.WaitOne(300));
            Assert.IsFalse(token.HasChanged);

            // Test, not activated
            disposable.Dispose();
            ram.CreateFile("/tmp/monited-path.txt");
            Assert.IsFalse(semaphore.WaitOne(300));
            Assert.IsTrue(token.HasChanged);

            // Observe again
            token      = fp.Watch("/tmp/**");
            semaphore  = new Semaphore(0, int.MaxValue);
            disposable = token.RegisterChangeCallback(o => semaphore.Release(), null);
            ram.CreateFile("/tmp/monited-path-again.txt");
            Assert.IsTrue(semaphore.WaitOne(300));
            Assert.IsTrue(token.HasChanged);

            // Shouldn't activate any more
            ram.CreateFile("/tmp/monited-path-again-one-more-time.txt");
            Assert.IsFalse(semaphore.WaitOne(300));
        }
Example #18
0
        public void Should_Define_And_Get_Embedded_Directory_Contents()
        {
            var contents = _virtualFileProvider.GetDirectoryContents("/Text");

            Assert.IsTrue(contents.Exists);

            var contentList = contents.ToList();

            Assert.Contains("Testfile_1.txt", contentList.Select(c => c.Name).ToList());
            Assert.Contains("Testfile_{2}.txt", contentList.Select(c => c.Name).ToList());
        }
Example #19
0
        public Task <IFileStoreEntry> GetDirectoryInfoAsync(string path)
        {
            var directoryInfo = _fileProvider.GetDirectoryContents(path);

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

            return(Task.FromResult <IFileStoreEntry>(null));
        }
 public IDirectoryContents GetDirectoryContents(string subPath)
 {
     if (FileCache.TryGetValue(subPath, out string value))
     {
         if (subPath != value)
         {
             return(_provider.GetDirectoryContents(value));
         }
     }
     return(_provider.GetDirectoryContents(subPath));
 }
        public virtual IEnumerable <string> ListDirectories(string path)
        {
            return(_webFileProvider.GetDirectoryContents(FileInfoExtension.RemoveRelativeSymbols(path))
                   .Where(f => f.IsDirectory)
                   .Select(t => t.ToAppRelative(_hostingEnvironment.ContentRootPath)));
//            return HostingEnvironment
//                .VirtualPathProvider
//                .GetDirectory(path)
//                .Directories
//                .OfType<VirtualDirectory>()
//                .Select(d => VirtualPathUtility.ToAppRelative(d.VirtualPath));
        }
Example #22
0
        public IEnumerable <IFileInfo> ListFiles(string path)
        {
            var directoryContents = _fileProvider.GetDirectoryContents(path);

            if (!directoryContents.Exists)
            {
                return(Enumerable.Empty <IFileInfo>());
            }

            return(directoryContents
                   .Where(x => !x.IsDirectory));
        }
Example #23
0
        public async Task <ActionResult <Media> > Index()
        {
            var Series = await _context.Series.ToListAsync();

            if (Series == null)
            {
                return(NotFound());
            }

            var contents = _fileProvider.GetDirectoryContents("/series");

            return(_mediaService.RemovedDuplicates(contents, Series));
        }
Example #24
0
        public ActionResult Details(int id)
        {
            var reservationsContext = _savingLogic.GetSavingReservations(id);

            ViewBag.Reservations = reservationsContext.Select(reserve => new ReservationViewModel(reserve));

            var savingContext = _savingLogic.GetSavingById(id);
            var model         = new SavingsViewModel(savingContext.UserId, id, savingContext.SavingName, savingContext.SavingCurrentAmount, savingContext.SavingsGoalAmount, savingContext.State, savingContext.IconId, savingContext.GoalDate);

            ViewBag.FileProvider = _fileProvider.GetDirectoryContents("wwwroot/Icons/Savings").ToList().Select(icon => icon.Name).ToList();
            ViewBag.Accounts     = _accountLogic.GetUserAccounts(HttpContext.Session.GetString("UserSession"));
            ViewBag.Savings      = _savingLogic.GetOngoingUserSavings((int)HttpContext.Session.GetInt32("UserId"));
            return(View("~/Views/Savings/SavingDetails.cshtml", model));
        }
Example #25
0
        public IActionResult Files()
        {
            var model = new FilesViewModel();

            var test = _fileProvider.GetDirectoryContents(path);

            foreach (var item in _fileProvider.GetDirectoryContents(path))
            {
                model.Files.Add(new FileDetails {
                    Name = item.Name, Path = item.PhysicalPath, Url = path + item.Name
                });
            }
            return(View(model));
        }
        public string Get(string fileName = "")
        {
            // Response.ContentType = "application/json; charset=utf-8";
            if (string.IsNullOrWhiteSpace(fileName))
            {
                fileName = "";
            }
            fileName = $"/{fileName.Trim('/')}";
            var rootFileInfo = _fileProvider.GetFileInfo(fileName);
            IDirectoryContents dirContents = _fileProvider.GetDirectoryContents(fileName);

            if (rootFileInfo != null && rootFileInfo.Exists && !rootFileInfo.IsDirectory)
            {
                strBuilder.Append("{");
                strBuilder.Append($"\"name\":\"{fileName.Trim('/').Split('/').LastOrDefault()}\",");
                strBuilder.Append($"\"path\":\"{fileName}\",");
                strBuilder.Append($"\"info\":");
                strBuilder.Append("{");
                strBuilder.Append($"\"lastModified\":\"{rootFileInfo.LastModified.LocalDateTime}\",");
                strBuilder.Append($"\"size\":\"{rootFileInfo.Length}\"");
                strBuilder.Append("}");
                strBuilder.Append("}");
            }
            else if (dirContents != null && dirContents.Exists)
            {
                strBuilder.Append("{");
                strBuilder.Append($"\"name\":\"{fileName.Trim('/').Split('/').LastOrDefault()}\",");
                strBuilder.Append($"\"path\":\"{fileName}\",");
                strBuilder.Append("\"children\":[");
                if (dirContents.Count() > 0)
                {
                    Render($"{fileName}");
                    strBuilder.Remove(strBuilder.Length - 1, 1);
                }
                strBuilder.Append("]");
                strBuilder.Append("}");
            }
            else
            {
                strBuilder.Append("{}");
            }

            // JObject o = JObject.Parse(strBuilder.ToString());
            //JArray categories = (JArray)o["children"][1]["children"];
            //JArray categories2 = (JArray)o.SelectToken("children[1].children");
            // Response.ContentType="application/json";
            return(strBuilder.ToString());
            // return Json(o);
        }
Example #27
0
 public override IEnumerable <FileSystemInfoBase> EnumerateFileSystemInfos()
 {
     foreach (var fileInfo in _fileProvider.GetDirectoryContents(RelativePath))
     {
         yield return(BuildFileResult(fileInfo));
     }
 }
Example #28
0
        private static void mapFile(string dirName, IFileProvider provider, IApplicationBuilder appBuilder)
        {
            var folder = provider.GetDirectoryContents(dirName);

            foreach (var item in folder)
            {
                if (item.IsDirectory)
                {
                    mapFile(dirName + "/" + item.Name, provider, appBuilder);
                    continue;
                }
                string map = (dirName + "/" + item.Name).Substring("blocklyFiles".Length);
                appBuilder.Map(map, app =>
                {
                    var f = item;

                    app.Run(async cnt =>
                    {
                        //TODO: find from extension
                        //cnt.Response.ContentType = "text/html";
                        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();
                        var m         = new Memory <byte>(result);
                        await cnt.Response.BodyWriter.WriteAsync(m);
                    });
                });
            }
        }
        /// <inheritdocs />
        public IEnumerable <IFileInfo> GetLocations(string cultureName)
        {
            var poFileName = cultureName + PoFileExtension;
            var extensions = _extensionsManager.GetExtensions();

            // Load .po files in each extension folder first, based on the extensions order
            foreach (var extension in extensions)
            {
                // From [Extension]/Localization
                yield return(_fileProvider.GetFileInfo(PathExtensions.Combine(extension.SubPath, _resourcesContainer, poFileName)));
            }

            // Load global .po files from /Localization
            yield return(_fileProvider.GetFileInfo(PathExtensions.Combine(_resourcesContainer, poFileName)));

            // Load tenant-specific .po file from /App_Data/Sites/[Tenant]/Localization
            yield return(new PhysicalFileInfo(new FileInfo(PathExtensions.Combine(_shellDataContainer, _resourcesContainer, poFileName))));

            // Load each modules .po file for extending localization when using Orchard Core as a NuGet package
            foreach (var extension in extensions)
            {
                // \src\OrchardCore.Cms.Web\Localization\OrchardCore.Cms.Web\fr-CA.po
                yield return(_fileProvider.GetFileInfo(PathExtensions.Combine(_resourcesContainer, extension.Id, poFileName)));

                // \src\OrchardCore.Cms.Web\Localization\OrchardCore.Cms.Web-fr-CA.po
                yield return(_fileProvider.GetFileInfo(PathExtensions.Combine(_resourcesContainer, extension.Id + CultureDelimiter + poFileName)));
            }

            // Load all .po files from a culture specific folder
            // e.g, \src\OrchardCore.Cms.Web\Localization\fr-CA\*.po
            foreach (var file in _fileProvider.GetDirectoryContents(PathExtensions.Combine(_resourcesContainer, cultureName)))
            {
                yield return(file);
            }
        }
Example #30
0
        /// <summary>
        /// This examines the request to see if it matches a configured directory, and if there are any files with the
        /// configured default names in that directory.  If so this will append the corresponding file name to the request
        /// path for a later middleware to handle.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task Invoke(HttpContext context)
        {
            if (context.GetEndpoint() == null &&
                Helpers.IsGetOrHeadMethod(context.Request.Method) &&
                Helpers.TryMatchPath(context, _matchUrl, forDirectory: true, subpath: out var subpath))
            {
                var dirContents = _fileProvider.GetDirectoryContents(subpath.Value);
                if (dirContents.Exists)
                {
                    // Check if any of our default files exist.
                    for (int matchIndex = 0; matchIndex < _options.DefaultFileNames.Count; matchIndex++)
                    {
                        string defaultFile = _options.DefaultFileNames[matchIndex];
                        var    file        = _fileProvider.GetFileInfo(subpath.Value + defaultFile);
                        // TryMatchPath will make sure subpath always ends with a "/" by adding it if needed.
                        if (file.Exists)
                        {
                            // If the path matches a directory but does not end in a slash, redirect to add the slash.
                            // This prevents relative links from breaking.
                            if (!Helpers.PathEndsInSlash(context.Request.Path) && _options.RedirectToAppendTrailingSlash)
                            {
                                Helpers.RedirectToPathWithSlash(context);
                                return(Task.CompletedTask);
                            }
                            // Match found, re-write the url. A later middleware will actually serve the file.
                            context.Request.Path = new PathString(Helpers.GetPathValueWithSlash(context.Request.Path) + defaultFile);
                            break;
                        }
                    }
                }
            }

            return(_next(context));
        }
 public DirectoryHandler(IFileProvider fileProvider, string path, DirectoryOptions options)
 {
     _fileProvider = fileProvider;
     _path = path;
     _extensionsOptionsRegex = new Regex(String.Join("|", options.DirectoryBrowsingStripExtensions.Select(i => String.Concat(i.FirstOrDefault() == '.' ? @"\" : "", i, @"$"))));
     _directoryOptions = options;
     CanHandleRequest = _fileProvider.GetDirectoryContents(_path).Exists;
 }