private async Task<CompilationResult> CompileCore(IFileInfo file)
        {
            var host = new MvcRazorHost();
            var engine = new RazorTemplateEngine(host);
            GeneratorResults results;
            using (TextReader rdr = new StreamReader(file.CreateReadStream()))
            {
                results = engine.GenerateCode(rdr, '_' + Path.GetFileNameWithoutExtension(file.Name), "Asp", file.PhysicalPath ?? file.Name);
            }

            string generatedCode;

            using (var writer = new StringWriter())
            using (var codeProvider = new CSharpCodeProvider())
            {
                codeProvider.GenerateCodeFromCompileUnit(results.GeneratedCode, writer, new CodeGeneratorOptions());
                generatedCode = writer.ToString();
            }

            if (!results.Success) 
            {
                return CompilationResult.Failed(generatedCode, results.ParserErrors.Select(e => new CompilationMessage(e.Message)));
            }

            Directory.CreateDirectory(_tempPath);
            string tempFile = Path.Combine(_tempPath, Path.GetRandomFileName() + ".cs");

            File.WriteAllText(tempFile, generatedCode);

            _tempFileSystem.TryGetFileInfo(tempFile, out file);
            return await _baseCompilationService.Compile(file);
        }
 private string GetHashForFile(IFileInfo fileInfo)
 {
     using (var sha256 = SHA256.Create())
     {
         using (var readStream = fileInfo.CreateReadStream())
         {
             var hash = sha256.ComputeHash(readStream);
             return WebEncoders.Base64UrlEncode(hash);
         }
     }
 }
        public PlacementFile Parse(IFileInfo fileInfo)
        {
            if (!fileInfo.Exists)
            {
                return null;
            }

            var element = XElement.Load(fileInfo.CreateReadStream());
            return new PlacementFile
            {
                Nodes = Accept(element).ToList()
            };
        }
Exemple #4
0
        // TODO: Make this internal
        public CompilationResult CompileCore(IFileInfo file)
        {
            GeneratorResults results;
            using (var inputStream = file.CreateReadStream())
            {
                Contract.Assert(file.PhysicalPath.StartsWith(_appRoot, StringComparison.OrdinalIgnoreCase));
                var rootRelativePath = file.PhysicalPath.Substring(_appRoot.Length);
                results = _razorHost.GenerateCode(rootRelativePath, inputStream);
            }

            if (!results.Success)
            {
                var messages = results.ParserErrors.Select(e => new CompilationMessage(e.Message));
                throw new CompilationFailedException(messages, results.GeneratedCode);
            }

            return _baseCompilationService.Compile(results.GeneratedCode);
        }
        public Task<CompilationResult> Compile(IFileInfo file)
        {
            string className = MakeClassName(file.Name);
            var engine = new RazorTemplateEngine(new RazorEngineHost(new CSharpRazorCodeLanguage())
            {
                DefaultBaseClass = "Microsoft.AspNet.Razor.Owin.PageBase",
                GeneratedClassContext = new GeneratedClassContext(
                    executeMethodName: "Execute",
                    writeMethodName: "Write",
                    writeLiteralMethodName: "WriteLiteral",
                    writeToMethodName: "WriteTo",
                    writeLiteralToMethodName: "WriteLiteralTo",
                    templateTypeName: "Template",
                    defineSectionMethodName: "DefineSection")
                {
                    ResolveUrlMethodName = "Href"
                }
            });
            engine.Host.NamespaceImports.Add("System");
            engine.Host.NamespaceImports.Add("System.Linq");
            engine.Host.NamespaceImports.Add("System.Collections.Generic");

            GeneratorResults results;
            using (TextReader rdr = new StreamReader(file.CreateReadStream()))
            {
                results = engine.GenerateCode(rdr, className, "RazorCompiled", file.PhysicalPath ?? file.Name);
            }

            var messages = new List<CompilationMessage>();
            if (!results.Success)
            {
                foreach (var error in results.ParserErrors)
                {
                    messages.Add(new CompilationMessage(
                        MessageLevel.Error,
                        error.Message,
                        new FileLocation(file.PhysicalPath ?? file.Name, error.Location.LineIndex, error.Location.CharacterIndex)));
                }
            }

            // Regardless of success or failure, we're going to try and compile
            return Task.FromResult(CompileCSharp("RazorCompiled." + className, file, results.Success, messages, results.GeneratedCode));
        }
        /// <summary>
        /// Create a stream that decrypts the encrypted file.
        /// </summary>
        /// <returns>An unencrypted stream.</returns>
        Stream IFileInfo.CreateReadStream()
        {
            if (!((IFileInfo)this).Exists)
            {
                throw new FileNotFoundException(innerFileInfo.Name);
            }
            DecryptResponse response;

            // Read the encrypted bytes from the file.
            using (var stream = innerFileInfo.CreateReadStream())
            {
                // Call kms to Decrypt them.
                response = kms.Decrypt(cryptoKeyName.Value,
                                       ByteString.FromStream(stream));
            }
            // Dump the unencrypted bytes to a memory stream.
            MemoryStream memStream = new MemoryStream();

            response.Plaintext.WriteTo(memStream);
            memStream.Seek(0, SeekOrigin.Begin);
            return(memStream);
        }
Exemple #7
0
        private static void InitializeAzureStorage(TestServer server)
        {
            try
            {
                // Upload an image to the Azure Test Storage;
                var                storageAccount = CloudStorageAccount.Parse(AzureConnectionString);
                CloudBlobClient    client         = storageAccount.CreateCloudBlobClient();
                CloudBlobContainer container      = client.GetContainerReference(AzureContainerName);

                if (!container.Exists())
                {
                    container.Create();
                    container.SetPermissions(new BlobContainerPermissions {
                        PublicAccess = BlobContainerPublicAccessType.Blob
                    });
                }

                IHostingEnvironment environment = server.Host.Services.GetRequiredService <IHostingEnvironment>();
                CloudBlockBlob      blob        = container.GetBlockBlobReference(ImagePath);
                if (!blob.Exists())
                {
                    IFileInfo file = environment.WebRootFileProvider.GetFileInfo(ImagePath);
                    using (System.IO.Stream stream = file.CreateReadStream())
                    {
                        blob.UploadFromStream(stream);
                    }
                }
            }
            catch (StorageException storageException)
            {
                // https://github.com/Azure/azure-sdk-for-net/issues/109
                // We do not fire exception if container exists - there is no need in such actions
                if (storageException.RequestInformation.HttpStatusCode != (int)HttpStatusCode.Conflict &&
                    storageException.RequestInformation.ExtendedErrorInformation.ErrorCode != StorageErrorCodeStrings.ContainerAlreadyExists)
                {
                    throw;
                }
            }
        }
        private void AddResizedImage(IFileInfo originalFileInfo, IFileInfo variantFileInfo)
        {
            DirectoryInfo variantDirectory = new FileInfo(variantFileInfo.PhysicalPath).Directory;

            if (!variantDirectory.Exists)
            {
                variantDirectory.Create();

                logger.LogInformation(
                    MainCfg.LogEventId,
                    "The variant directory '{0}' was successfully created!",
                    variantDirectory.FullName);
            }

            using (var outputImageStream = new FileStream(variantFileInfo.PhysicalPath, FileMode.Create))
            {
                using (Stream inputImageStream = originalFileInfo.CreateReadStream())
                {
                    imageResizer.Resize(inputImageStream, imageSizeInfo, outputImageStream);
                }
            }
        }
Exemple #9
0
        public Task <RecipeDescriptor> GetRecipeDescriptor(string recipeBasePath, IFileInfo recipeFileInfo, IFileProvider recipeFileProvider)
        {
            // TODO: Try to optimize by only reading the required metadata instead of the whole file

            using (var stream = recipeFileInfo.CreateReadStream())
            {
                using (var reader = new StreamReader(stream))
                {
                    using (var jsonReader = new JsonTextReader(reader))
                    {
                        var serializer       = new JsonSerializer();
                        var recipeDescriptor = serializer.Deserialize <RecipeDescriptor>(jsonReader);

                        recipeDescriptor.FileProvider   = recipeFileProvider;
                        recipeDescriptor.BasePath       = recipeBasePath;
                        recipeDescriptor.RecipeFileInfo = recipeFileInfo;

                        return(Task.FromResult(recipeDescriptor));
                    }
                }
            }
        }
Exemple #10
0
        /// <summary>
        ///     Asynchronously reads the file. This is called on start of the background service (to enable reading the
        ///     initial contents of the file) and whenever the file changes (to enable reading the changed contents of
        ///     the file).
        /// </summary>
        /// <param name="file">The file.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>A task that represents the asynchronous operation.</returns>
        private async Task ReadAsync(IFileInfo file, CancellationToken cancellationToken)
        {
            var    filePhysicalPath = file.PhysicalPath;
            string content;

            if (filePhysicalPath == null)
            {
                using (var stream = file.CreateReadStream())
                    using (var streamReader = new StreamReader(stream, Encoding.ASCII))
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        content = await streamReader.ReadToEndAsync().ConfigureAwait(false);
                    }
            }
            else
            {
                content = await File.ReadAllTextAsync(filePhysicalPath, Encoding.ASCII, cancellationToken).ConfigureAwait(false);
            }

            cancellationToken.ThrowIfCancellationRequested();
            this.OnRead(content);
        }
Exemple #11
0
        public void CanDeserializeJson()
        {
            var         serializer = new JsonSerializer();
            AirportFeed feed;

            using (var dataStream = jsonfile.CreateReadStream())
                using (var textReader = new StreamReader(dataStream))
                    using (var jsonReader = new JsonTextReader(textReader))
                    {
                        feed = serializer.Deserialize <AirportFeed>(jsonReader);
                    }

            Assert.NotNull(feed);
            Assert.Equal(xmlfileAirportIata, feed.AirportIata);
            Assert.NotNull(feed.Content);
            Assert.NotNull(feed.Content.Flights);
            Assert.NotEmpty(feed.Content.Flights);
            var flightIds = new HashSet <uint>();

            Assert.All(feed.Content.Flights, f => Assert.True(flightIds.Add(f.UniqueId)));
            Assert.All(feed.Content.Flights, AssertAirportFeedFlight);
        }
        public string GetSecretOrEnvVar(string key)
        {
            const string DOCKER_SECRET_PATH = "/run/secrets/";

            if (Directory.Exists(DOCKER_SECRET_PATH))
            {
                IFileProvider provider = new PhysicalFileProvider(DOCKER_SECRET_PATH);
                IFileInfo     fileInfo = provider.GetFileInfo(key);
                if (fileInfo.Exists)
                {
                    using (var stream = fileInfo.CreateReadStream())
                        using (var streamReader = new StreamReader(stream))
                        {
                            return(streamReader.ReadToEnd());
                        }
                }
            }

            var hmm = Configuration.GetValue <string>(key) ?? "MISSING";

            return(hmm);
        }
        private static string ReadPhysicalFile(string path)
        {
            if (_hostingEnvironment == null)
            {
                throw new InvalidOperationException($"{nameof(EmailTemplates)} is not initialized");
            }

            IFileInfo fileInfo = _hostingEnvironment.ContentRootFileProvider.GetFileInfo(path);

            if (!fileInfo.Exists)
            {
                throw new FileNotFoundException($"Template file located at \"{path}\" was not found");
            }

            using (var fs = fileInfo.CreateReadStream())
            {
                using (var sr = new StreamReader(fs))
                {
                    return(sr.ReadToEnd());
                }
            }
        }
        public static string GetHash([NotNull] IFileInfo file, int hashAlgorithmVersion)
        {
            if (hashAlgorithmVersion != HashAlgorithmVersion1)
            {
                throw new ArgumentException(Resources.RazorHash_UnsupportedHashAlgorithm,
                                            nameof(hashAlgorithmVersion));
            }

            try
            {
                using (var stream = file.CreateReadStream())
                {
                    return(Crc32.Calculate(stream).ToString(CultureInfo.InvariantCulture));
                }
            }
            catch (IOException)
            {
                // Don't throw if reading the file fails.
            }

            return(string.Empty);
        }
Exemple #15
0
        private void InitKeyIDTeamIDFromFile(string path)
        {
            var provider = new PhysicalFileProvider(path);

            IFileInfo fileInfo = provider.GetFileInfo("p8.txt");

            if (!fileInfo.Exists)
            {
                throw new FileNotFoundException("p8.txt not found");
            }

            Stream sr = fileInfo.CreateReadStream();

            if (sr == null)
            {
                return;
            }

            try
            {
                using (var reader = new StreamReader(sr))
                {
                    string[] content;
                    string   line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        content = line.Split(":");
                        if (content.Length == 2 && p8[content[0]] == null)
                        {
                            p8[content[0]] = content[1];
                        }
                    }
                }
            }
            catch (IOException e)
            {
                Debug.WriteLine(e.Message);
            }
        }
        public IActionResult Get(string fileName)
        {
            try
            {
                var downloadPath = Path.Combine(_environment.WebRootPath, "uploads");
                var dir          = new DirectoryInfo(downloadPath);
                if (!dir.Exists)
                {
                    dir.Create();
                }

                var       provider   = new PhysicalFileProvider(downloadPath);
                IFileInfo fileInfo   = provider.GetFileInfo(fileName);
                var       readStream = fileInfo.CreateReadStream();

                return(File(readStream, "text/plain"));
            }
            catch (Exception ex)
            {
                return(BadRequest($"Error: {ex.Message}"));
            }
        }
Exemple #17
0
        internal static byte[] GetSecretOrEnvVarAsByte(string key)
        {
            var bytes = default(byte[]);

            string configPath = GetConfigPath();

            try
            {
                IFileProvider provider = new PhysicalFileProvider(configPath);
                IFileInfo     fileInfo = provider.GetFileInfo(key);
                if (fileInfo.Exists)
                {
                    using (var stream = fileInfo.CreateReadStream())
                    {
                        using (var memstream = new MemoryStream())
                        {
                            var buffer    = new byte[512];
                            var bytesRead = default(int);
                            while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                memstream.Write(buffer, 0, bytesRead);
                            }
                            bytes = memstream.ToArray();
                        }
                    }
                }
                else
                {
                    throw new InvalidOperationException("Environment variable not found: " + key);
                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("Exception loading: " + key + " (" + ex.Message + ")");
            }

            return(bytes);
        }
Exemple #18
0
        public void Seed(StoreContext db, IFileInfo seedFile)
        {
            if (!seedFile.Exists)
            {
                log.LogInformation($"{seedFile.Name} does not exist. Skipping seed database.");
                return;
            }

            if (db.Organizations.Any() || db.Jurisdictions.Any())
            {
                log.LogInformation($"Database contains data. Skipping seed database.");
                return;
            }

            log.LogInformation("Seeding database ...");

            JObject data;

            using (var fileStream = seedFile.CreateReadStream())
            {
                using (var textReader = new StreamReader(fileStream))
                {
                    using (var jsonReader = new JsonTextReader(textReader))
                    {
                        data = JObject.Load(jsonReader);
                    }
                }
            }

            LoadTable(db.Jurisdictions, data);
            LoadTable(db.Organizations, data);

            FixLinks(db.Jurisdictions, data);
            FixLinks(db.Organizations, data);
            db.SaveChanges();

            log.LogInformation("Finished database seed.");
        }
Exemple #19
0
        /// <inheritdoc/>
        public async Task <byte[]> ResolveImageAsync(HttpContext context, ILogger logger)
        {
            // Path has already been correctly parsed before here.
            IFileProvider fileProvider = this.environment.WebRootFileProvider;
            IFileInfo     fileInfo     = fileProvider.GetFileInfo(context.Request.Path);

            byte[] buffer;

            // Check to see if the file exists.
            if (!fileInfo.Exists)
            {
                return(null);
            }

            using (Stream stream = fileInfo.CreateReadStream())
            {
                // Buffer is returned to the pool in the middleware
                buffer = BufferDataPool.Rent((int)stream.Length);
                await stream.ReadAsync(buffer, 0, (int)stream.Length);
            }

            return(buffer);
        }
Exemple #20
0
        public string ConvertMarkdownToHtml(string filename)
        {
            string markdownContent;

            IFileInfo file = _files.GetFileInfo(filename);

            using (var stream = file.CreateReadStream())
                using (var reader = new StreamReader(stream))
                {
                    markdownContent = reader.ReadToEnd();
                    //var output = await reader.ReadToEndAsync();
                    //await context.Response.WriteAsync(output.ToString());
                }

            var commonMarkSettings = CommonMarkSettings.Default.Clone();

            commonMarkSettings.OutputDelegate = (doc, output, settings) =>
                                                new CustomHtmlFormatter(output, settings).WriteDocument(doc);

            var htmlResult = CommonMarkConverter.Convert(markdownContent, commonMarkSettings);

            return(htmlResult);
        }
        private async Task <byte[]> renderContent(IFileInfo file)
        {
            long size = (header?.Length ?? 0) + file.Length + (footer?.Length ?? 0);

            using (var stream = new MemoryStream((int)size))
            {
                if (header != null)
                {
                    using (var headerStream = header.CreateReadStream())
                        await headerStream.CopyToAsync(stream);
                }
                using (var fileStream = file.CreateReadStream())
                    using (var reader = new StreamReader(fileStream))
                        using (var writer = new StreamWriter(stream, encoding: Encoding.UTF8, bufferSize: (int)file.Length, leaveOpen: true))
                            await writer.WriteAsync(Markdown.ToHtml(await reader.ReadToEndAsync(), pipeline: converter));
                if (footer != null)
                {
                    using (var footerStream = footer.CreateReadStream())
                        await footerStream.CopyToAsync(stream);
                }
                return(stream.ToArray());
            }
        }
Exemple #22
0
        private static string ReadOriginalFileContent(IFileInfo file)
        {
            if (!file.Exists || file.IsDirectory)
            {
                return(null);
            }
            Stream       stream  = null;
            StreamReader reader  = null;
            String       content = null;

            try
            {
                stream  = file.CreateReadStream();
                reader  = new StreamReader(stream);
                content = reader.ReadToEnd();
            }
            finally
            {
                stream?.Dispose();
                reader?.Dispose();
            }
            return(content);
        }
Exemple #23
0
        public async Task <string> LocalFile(string catchall)
        {
            logger.LogInformation($"request local file : {HttpContext.Request.Path}");
            logger.LogInformation($"controller: {RouteData.Values["controller"]}");
            logger.LogInformation($"action: {RouteData.Values["action"]}");
            logger.LogInformation($"catchall: {RouteData.Values["catchall"]}");
            logger.LogInformation($"catchall: {catchall}");
            string    path = catchall.TrimStart('/');
            IFileInfo file = _fileProvider.GetFileInfo(path);

            string res = "";

            using (var stream = file.CreateReadStream())
            {
                using (var reader = new StreamReader(stream))
                {
                    var output = await reader.ReadToEndAsync();

                    res = output;
                }
            }
            return(res);
        }
Exemple #24
0
        private static X509Certificate2 LoadCertificate()
        {
            Assembly             assembly             = typeof(Startup).GetTypeInfo().Assembly;
            EmbeddedFileProvider embeddedFileProvider = new EmbeddedFileProvider(assembly, "final");
            IFileInfo            certificateFileInfo  = embeddedFileProvider.GetFileInfo(Config["Ssl:Certificate:FileName"]);

            using (Stream certificateStream = certificateFileInfo.CreateReadStream())
            {
                byte[] certificatePayload;
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    certificateStream.CopyTo(memoryStream);
                    certificatePayload = memoryStream.ToArray();
                }

                return(new X509Certificate2(certificatePayload, Config["Ssl:Certificate:Password"]));
            }

            //string certFileName = Config["Ssl:Certificate:FileName"];
            //string certPassword = Config["Ssl:Certificate:Password"];

            //return new X509Certificate2(certFileName, certPassword);
        }
        public IActionResult Index3()
        {
            string content = "file not found";

            try
            {
                IFileInfo embeddedfileInfo = _fileProvider3.GetFileInfo("embeddedText.txt");

                if (embeddedfileInfo.Exists)
                {
                    using (Stream fileStream = embeddedfileInfo.CreateReadStream())
                    {
                        StreamReader streamReader = new StreamReader(fileStream);

                        content = streamReader.ReadToEnd();
                    }
                }

                IFileInfo physicalFileInfo = _fileProvider3.GetFileInfo("physicalText.txt");

                if (physicalFileInfo.Exists)
                {
                    using (Stream fileStream = physicalFileInfo.CreateReadStream())
                    {
                        StreamReader streamReader = new StreamReader(fileStream);

                        content += streamReader.ReadToEnd();
                    }
                }
            }
            catch (Exception)
            {
                content = "error reading file";
            }

            return(Content(content));
        }
        private static void InitializeAzureStorage(IServiceProvider services, AzureBlobStorageImageProviderOptions options)
        {
            // Upload an image to the Azure Test Storage;
            AzureBlobContainerClientOptions containerOptions = options.BlobContainers.First();
            var container = new BlobContainerClient(containerOptions.ConnectionString, containerOptions.ContainerName);

            container.CreateIfNotExists(PublicAccessType.Blob);

#if NETCOREAPP2_1
            IHostingEnvironment environment = services.GetRequiredService <IHostingEnvironment>();
#else
            IWebHostEnvironment environment = services.GetRequiredService <IWebHostEnvironment>();
#endif

            BlobClient blob = container.GetBlobClient(TestConstants.ImagePath);

            if (!blob.Exists())
            {
                IFileInfo file = environment.WebRootFileProvider.GetFileInfo(TestConstants.ImagePath);
                using Stream stream = file.CreateReadStream();

                // Set the max-age property so we get coverage for testing is in our Azure provider.
                var cacheControl = new CacheControlHeaderValue
                {
                    Public         = true,
                    MaxAge         = TimeSpan.FromDays(7),
                    MustRevalidate = true
                };

                var headers = new BlobHttpHeaders
                {
                    CacheControl = cacheControl.ToString(),
                };

                blob.Upload(stream, httpHeaders: headers);
            }
        }
        public async Task <IFileInfo> MoveFile(IFileInfo source, string relativeFolderPath, string fileName, string extension, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (source.IsDirectory)
            {
                throw new InvalidOperationException("You cannot move a folder.");
            }

            if (!source.Exists)
            {
                throw new InvalidOperationException("The source file does not exist.");
            }

            IFileInfo destination;

            using (var sourceStream = source.CreateReadStream()) {
                destination = await WriteFile(sourceStream, relativeFolderPath, fileName, extension, cancellationToken);
            }

            var sourceInfo = new FileInfo(source.PhysicalPath);

            sourceInfo.Delete();

            return(destination);
        }
        private void BuildHtml(BodyBuilder builder)
        {
            var entrants          = this.GetHtmlEntrants();
            var competitionValues = this.GetHtmlCompetitionValues();
            var contactValues     = this.GetHtmlContactValues();
            var entrantsHeader    = this.GetEntrantsHeader();

            var image1 = builder.LinkedResources.Add("logo.png", _logoFile.CreateReadStream());

            image1.ContentId = MimeUtils.GenerateMessageId();
            var image2 = builder.LinkedResources.Add("ok.gif", _okFile.CreateReadStream());

            image2.ContentId = MimeUtils.GenerateMessageId();

            var file = _registrationConfirmationTemplate.Replace("%%COMPETITION-VALUES%%", competitionValues.ToString());

            file             = file.Replace("%%CONTACT-VALUES%%", contactValues.ToString());
            file             = file.Replace("%%ENTRANTS%%", entrants.ToString());
            file             = file.Replace("LOGOIMAGEID", image1.ContentId);
            file             = file.Replace("OKIMAGEID", image2.ContentId);
            file             = file.Replace("%%ENTRANTS-HEADER%%", entrantsHeader.ToUpperInvariant());
            file             = file.Replace("%%COMPETITION-NAME%%", this._competition.Name);
            builder.HtmlBody = file;
        }
Exemple #29
0
        internal byte[] GetFileContent(string subpath)
        {
            byte[] content;
            if (!fileContentCache.TryGet(subpath, out content))
            {

                IFileInfo fileInfo = provider.GetFileInfo(subpath);
                using (Stream stream = fileInfo.CreateReadStream())
                {
                    long bytesToRead = fileInfo.Length;
                    content = new byte[bytesToRead];
                    long bytesRead = 0;
                    int readCount;

                    while ((readCount = stream.Read(content, (int)bytesRead, (int)bytesToRead)) > 0)
                    {
                        bytesRead += readCount;
                        bytesToRead -= readCount;
                    }
                }
                fileContentCache.Add(subpath, content);
            }
            return content;
        }
Exemple #30
0
 public IActionResult DownloadFile(string fileName)
 {
     try
     {
         //Get the file location
         FileInfo      file       = new FileInfo(Path.Combine(_newDownloadPath, fileName));
         IFileProvider provider   = new PhysicalFileProvider(_newDownloadPath);
         IFileInfo     fileInfo   = provider.GetFileInfo(fileName);
         var           readStream = fileInfo.CreateReadStream();
         string        mimeType   = "application/pdf";
         System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition
         {
             FileName = fileName,
             Inline   = false // false = prompt the user for downloading;  true = browser to try to show the file inline
         };
         Response.Headers.Add("Content-Disposition", cd.ToString());
         //Return the file
         return(File(readStream, mimeType, fileName));
     }
     catch (System.Exception ex)
     {
         return(Json("Download failed: " + ex.Message));
     }
 }
Exemple #31
0
        //________________________________________________________________________________


        public async Task <IActionResult> Download(int id)
        {
            if (id <= 0)
            {
                return(this.NotFound());
            }
            var UserId             = Tools.GetCurrentUserId(User);
            var applicationPublish = await _context.ApplicationPublishs
                                     .Include(a => a.Application)
                                     .FirstOrDefaultAsync(a => a.Id == id);

            if (applicationPublish == null)
            {
                return(this.NotFound());
            }

            var applicationDownload = await _context.DownloadApplications
                                      .FirstOrDefaultAsync(u => u.ApplicationStoreUserId == Tools.GetCurrentUserId(User) && u.ApplicationPublishId == id);

            if (applicationDownload == null)
            {
                applicationDownload.ApplicationStoreUserId = UserId;
                applicationDownload.RegisterDate           = DateTime.Now.Date;
                applicationDownload.ApplicationPublishId   = id;
                _context.DownloadApplications.Add(applicationDownload);
                await _context.SaveChangesAsync();
            }


            var           webRootPath = _hostingEnvironment.WebRootPath;
            var           uploadApp   = Path.Combine(webRootPath, "ApplicationFiles");
            IFileProvider provider    = new PhysicalFileProvider(uploadApp);
            IFileInfo     fileInfo    = provider.GetFileInfo(id + applicationPublish.Extension);

            return(File(fileInfo.CreateReadStream(), "application/andrew-inset", applicationPublish.Application.Title + applicationPublish.Extension));
        }
Exemple #32
0
        private static void InitializeAzureStorage(TestServer server)
        {
            // Upload an image to the Azure Test Storage;
            var container = new BlobContainerClient(AzureConnectionString, AzureContainerName);

            container.CreateIfNotExists(PublicAccessType.Blob);

#if NETCOREAPP3_1
            IWebHostEnvironment environment = server.Host.Services.GetRequiredService <IWebHostEnvironment>();
#else
            IHostingEnvironment environment = server.Host.Services.GetRequiredService <IHostingEnvironment>();
#endif

            BlobClient blob = container.GetBlobClient(ImagePath);

            if (!blob.Exists())
            {
                IFileInfo file = environment.WebRootFileProvider.GetFileInfo(ImagePath);
                using (Stream stream = file.CreateReadStream())
                {
                    blob.Upload(stream, true);
                }
            }
        }
Exemple #33
0
        public static string GetSecretOrEnvVarAsString(string key)
        {
            try
            {
                string configPath = GetConfigPath();

                IFileProvider provider = new PhysicalFileProvider(configPath);
                IFileInfo     fileInfo = provider.GetFileInfo(key);
                if (fileInfo.Exists)
                {
                    using (var stream = fileInfo.CreateReadStream())
                        using (var streamReader = new StreamReader(stream))
                        {
                            return(streamReader.ReadToEnd());
                        }
                }
            }
            catch (Exception ex)
            {
                return(string.Empty);
            }

            return(string.Empty);
        }
        public FileResult Download(string filePath)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                MyLogger.Log(messaggio: $"ERRORE: Richiesta POST: nessun filePath fornito", controller: "ReportController", metodo: "Download");
                return(null);
            }
            var dir       = Path.Combine(Globals.CartellaWEBMVA, "wwwroot", Path.GetDirectoryName(filePath));
            var fileName  = Path.GetFileName(filePath);
            var extension = Path.GetExtension(fileName).ToLower();

            if (!System.IO.File.Exists(Path.Combine(dir, fileName)))
            {
                MyLogger.Log(messaggio: $"ERRORE: Richiesta POST: il file {Path.Combine(dir, fileName)} non esiste", controller: "ReportController", metodo: "Download");
                return(null);
            }
            IFileProvider provider   = new PhysicalFileProvider(dir);
            IFileInfo     fileInfo   = provider.GetFileInfo(fileName);
            var           readStream = fileInfo.CreateReadStream();
            string        mimetype   = "text/plain";

            switch (extension)
            {
            case ".html":
                mimetype = "text/html";
                break;

            case ".xml":
                mimetype = "application/xml";
                break;

            default: break;
            }
            MyLogger.Log(messaggio: $"Richiesta POST: file {Path.Combine(dir, fileName)} scaricato", controller: "ReportController", metodo: "Download");
            return(File(readStream, mimetype, fileName));
        }
Exemple #35
0
 public MockStorageFile(IFileInfo file, string path) : this(path, file.LastModified.LocalDateTime, file.CreateReadStream())
 {
 }
        private IPublishedContent ReadContent(IFileInfo fileInfo)
        {
            using (var file = fileInfo.CreateReadStream())
            using (var reader = new StreamReader(file))
            {
                var serializer = new JsonSerializer
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                };

                var content = (IPublishedContent)serializer.Deserialize(reader, typeof(PublishedContent));
                return content;
            }
        }
        private static ChunkTree ParseViewFile(
            RazorTemplateEngine engine,
            IFileInfo fileInfo,
            string viewImportsPath)
        {
            using (var stream = fileInfo.CreateReadStream())
            {
                using (var streamReader = new StreamReader(stream))
                {
                    var parseResults = engine.ParseTemplate(streamReader, viewImportsPath);
                    var className = ParserHelpers.SanitizeClassName(fileInfo.Name);
                    var language = engine.Host.CodeLanguage;
                    var chunkGenerator = language.CreateChunkGenerator(
                        className,
                        engine.Host.DefaultNamespace,
                        viewImportsPath,
                        engine.Host);
                    chunkGenerator.Visit(parseResults);

                    // Rewrite the location of inherited chunks so they point to the global import file.
                    var chunkTree = chunkGenerator.Context.ChunkTreeBuilder.ChunkTree;
                    foreach (var chunk in chunkTree.Chunks)
                    {
                        chunk.Start = new SourceLocation(
                            viewImportsPath,
                            chunk.Start.AbsoluteIndex,
                            chunk.Start.LineIndex,
                            chunk.Start.CharacterIndex);
                    }

                    return chunkTree;
                }
            }
        }
        /// <summary>
        /// Returns <see cref="Stream"/> for the specified <paramref name="fileInfo"/>.
        /// </summary>
        /// <param name="fileInfo">The <see cref="IFileInfo"/> for which the stream is needed.</param>
        /// <returns><see cref="Stream"/> for the specified <paramref name="fileInfo"/>.</returns>
        protected virtual Stream GetFileStream(IFileInfo fileInfo)
        {
            if (fileInfo == null)
            {
                throw new ArgumentNullException(nameof(fileInfo));
            }

            return fileInfo.CreateReadStream();
        }
Exemple #39
0
		private string ReadAllText(IFileInfo fileInfo)
		{
			using (var stream = fileInfo.CreateReadStream())
			using (var reader = new StreamReader(stream))
			{
				return reader.ReadToEnd();
			}
		}
 protected virtual Stream GetFileStream(IFileInfo fileInfo)
 {
     return fileInfo.CreateReadStream();
 }
 private static string ReadFileContentsSafely(IFileInfo fileInfo)
 {
     try
     {
         using (var reader = new StreamReader(fileInfo.CreateReadStream()))
         {
             return reader.ReadToEnd();
         }
     }
     catch
     {
         // Ignore any failures
         return null;
     }
 }
 private static IEnumerable<string> ReadLines(IFileInfo fileInfo)
 {
     using (var reader = new StreamReader(fileInfo.CreateReadStream()))
     {
         string line;
         while ((line = reader.ReadLine()) != null)
         {
             yield return line;
         }
     }
 }
        private static IEnumerable<string> ReadLines(IFileInfo fileInfo)
        {
            var result = new List<string>();

            using (var reader = new StreamReader(fileInfo.CreateReadStream()))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    result.Add(line);
                }
            }

            return result;
        }
        private static CodeTree ParseViewFile(RazorTemplateEngine engine,
                                              IFileInfo fileInfo,
                                              string viewStartPath)
        {
            using (var stream = fileInfo.CreateReadStream())
            {
                using (var streamReader = new StreamReader(stream))
                {
                    var parseResults = engine.ParseTemplate(streamReader, viewStartPath);
                    var className = ParserHelpers.SanitizeClassName(fileInfo.Name);
                    var language = engine.Host.CodeLanguage;
                    var codeGenerator = language.CreateCodeGenerator(className,
                                                                     engine.Host.DefaultNamespace,
                                                                     viewStartPath,
                                                                     engine.Host);
                    codeGenerator.Visit(parseResults);

                    return codeGenerator.Context.CodeTreeBuilder.CodeTree;
                }
            }
        }