Esempio n. 1
0
        // GET: /Report/DocView/n
        public IActionResult DocView(int?id)
        {
            string method = "Report/DocView";

            if (NullId(id, "PendingId", method))
            {
                return(RedirectToAction("Error", "Home"));
            }

            try
            {
                PendingReport report = null;
                if ((report = Read(id.Value, method)) == null)
                {
                    return(RedirectToAction("Error", "Home"));
                }

                string filename = report.eFileName;
                if (IsNull(filename, "eFileName", method))
                {
                    return(RedirectToAction("Error", "Home"));
                }

                _filesys.ChangeDirectory(Config.Get("UploadDirectory"));
                byte[] file = _filesys.FileDownload(filename);

                return(new FileContentResult(file, MIME.GetMimeType(Path.GetExtension(filename))));
            }
            catch (Exception ex)
            {
                Log.Me.Error("Exception in " + method + ": " + ex.Message);
                return(RedirectToAction("Error", "Home"));
            }
        }
Esempio n. 2
0
        [RequestSizeLimit(52428800)]        // Handle requests up to 50 MB
        public async Task <IActionResult> UploadPhysical()
        {
            string testDir = Config.Get("TestDirectory");

            _filesys.ChangeDirectory(testDir);
            string filename = Path.GetRandomFileName();

            try
            {
                int reason = await Uploader.Upload(Request, _filesys, testDir, filename, _fileSizeLimit, _permittedExtensions);

                if (reason > 0)
                {
                    string message = null;
                    if (reason == 415)
                    {
                        message = "Type of file not accepted";
                    }
                    if (reason == 413)
                    {
                        message = "File too large";
                    }
                    Log.Me.Warn(message);
                    return(StatusCode(reason, message));
                }
            }
            catch (Exception ex)
            {
                Log.Me.Error(ex.Message);
                ModelState.AddModelError("File", ex.Message);
                BadRequest(ModelState);
            }

            return(Created(nameof(StreamingController), null));
        }
        [RequestSizeLimit(52428800)]        // Handle requests up to 50 MB
        public async Task <IActionResult> UploadDocument(string pendingId)
        {
            // Generate Filename
            string filename = _context.PendingReportRepo.GenerateFilename(pendingId.ToInteger());

            Log.Me.Debug("DocumentController.UploadDocument: Filename is " + filename);

            string uploadDir = Config.Get("UploadDirectory");

            _fsys.ChangeDirectory(uploadDir);

            try
            {
                int reason = await Uploader.Upload(Request, _fsys, uploadDir, filename, _sizeLimit, _extensions);

                if (reason > 0)
                {
                    string message = null;
                    if (reason == 415)
                    {
                        message = "Type of file not accepted";
                    }
                    if (reason == 413)
                    {
                        message = "File too large";
                    }
                    Log.Me.Warn(message);
                    return(StatusCode(reason, message));
                }
                else
                {
                    // Save filename
                    PendingReport report = _context.PendingReportRepo.Read(pendingId.ToInteger());
                    report.eFileName = filename;
                    string check = _context.PendingReportRepo.CheckFileSize(_fsys, report, Config.Get("UploadDirectory"));
                    if (check != null)
                    {
                        report.eFilePath = "OVERSIZE";
                    }
                    _context.PendingReportRepo.Update(report);
                    Log.Me.Info(CheckIdentity().UserName + " uploaded file " + filename + " to report " + pendingId);
                }
            }
            catch (Exception ex)
            {
                Log.Me.Error(ex.Message);
                ModelState.AddModelError("File", ex.Message);
                BadRequest(ModelState);
            }

            return(Created(nameof(DocumentController), null));
        }
Esempio n. 4
0
        public string CheckFileSize(IFile filesys, PendingReport report, string upload)
        {
            long maxFileSize = 0L;

            if (!long.TryParse(Config.Get("AttachmentSizeLimit"), out maxFileSize))
            {
                throw new Exception("Unable to parse FileSizeLimit as a long");
            }

            filesys.ChangeDirectory(upload);
            if (filesys.FileLength(report.eFileName) > maxFileSize)
            {
                return("The Report's PDF File is too large to send as an email attachment. Please amend the circulation list and amend all recipients that have been marked for Full Electronic distribution. Full Electronic distribution is NOT available for this report.");
            }
            return(null);
        }
        private async Task <int> UploadFile(IFormFile source, IFile filesys, string filename, long sizeLimit)
        {
            byte[] file;
            int    progress = 0;

            try
            {
                long len = source.Length;
                // Check if the file is empty or exceeds the size limit.
                if (len == 0L || len > sizeLimit)
                {
                    return(progress);
                }

                string sourcename = ContentDispositionHeaderValue.Parse(source.ContentDisposition).FileName.ToString().Trim('"');

                progress = 1;
                using (Stream input = source.OpenReadStream())
                {
                    file = await UploadStream(input, source.Length);
                }

                /* Check the file contents */
                progress = 2;
                if (CheckFileContent(file, sourcename, _extensions) > 0)
                {
                    return(progress);
                }

                /* Upload the file */
                progress = 3;
                filesys.ChangeDirectory("Upload");
                filesys.FileUpload(WebUtility.HtmlEncode(filename), new MemoryStream(file));

                progress = 4;
            }
            catch (Exception ex)
            {
                Log.Me.Error("In UploadFile. Progress is " + progress.ToString() + ", exception: " + ex.Message);
            }

            return(progress);
        }
Esempio n. 6
0
 private void SendEmailBatches(List <EmailBatch> batches, IFile filesys)
 {
     try
     {
         //--------------------------------------------------------------------------------------
         // Kick off a Thread to send emails out to all electronic users
         //--------------------------------------------------------------------------------------
         Log.Me.Info("About to kick off the Emailing Thread");
         filesys.ChangeDirectory(Config.Get("UploadDirectory"));
         MailEngine engine = new MailEngine();
         engine.SendGridKey = EmailConfig.Me.SendGridKey;
         engine.FileSys     = filesys;
         string sepchar = Path.DirectorySeparatorChar.ToString();
         engine.LoadTemplates(Config.ContentRoot + sepchar + "Config" + sepchar, "EmailTemplates.txt");
         engine.Start(batches);
         Log.Me.Info("Email Thread started!");
     }
     catch (Exception ex)
     {
         Log.Me.Error("EXCEPTION - " + ex.Message);
     }
 }
Esempio n. 7
0
        public string CommitReport(IFile filesys, int pendingId)
        {
            if (filesys == null)
            {
                throw new Exception("Cannot Commit Report - no file system!");
            }
            if (pendingId <= 0)
            {
                throw new Exception("Cannot Commit Report - invalid report id!");
            }
            PendingReport report = this.Read(pendingId);

            if (report == null)
            {
                throw new Exception("Cannot Commit Report - Pending Report not found!");
            }
            if (report.RecipientID <= 0)
            {
                throw new Exception("Cannot Commit Report - Zero RecipientId!");
            }

            string upload = Config.Get("UploadDirectory");
            string outbox = Config.Get("OutboxDirectory");

            IQueryable <Circulation> circlist = _context.CirculationRepo.List(pendingId)
                                                .Where(c => c.ElecDeliveryCode == "EF");

            if (circlist.Count() > 0)
            {
                if (report.eFileName == null)
                {
                    return("Cannot Commit Report - no pdf for EF circulation");
                }

                //-------------------------------------------
                // We have some EF recipients (check the file size of the PDF file - if it's Too big - Tell the user)
                //-------------------------------------------
                string msg = CheckFileSize(filesys, report, upload);
                if (msg != null)
                {
                    return(msg);
                }
            }

            //--------------------------------------------------------------------------------
            // Create the xml metadata file and upload it to Outbox.
            //--------------------------------------------------------------------------------
            string         metadatafile = GenerateFilename(report, ".xml");
            TransferReport transfer     = new TransferReport(report);
            string         xmlout       = transfer.ToXML();

            if (xmlout == null)
            {
                throw new Exception("Cannot Commit Report - failed to create xml metadata");
            }
            filesys.ChangeDirectory(outbox);
            filesys.FileUpload(metadatafile, xmlout.ToStream());
            Log.Me.Info("Uploaded XML");

            //--------------------------------------------------------------------------------
            // Copy pdf to Outbox
            //--------------------------------------------------------------------------------
            filesys.ChangeDirectory(upload);
            if (report.eFileName != null)
            {
                filesys.FileCopy(report.eFileName, outbox);
            }

            //--------------------------------------------------------------------------------
            // Change State to Committed
            //--------------------------------------------------------------------------------
            report.State = 1;
            this.Update(report);

            return(null);
        }
Esempio n. 8
0
 public void OnGet()
 {
     _filesys.ChangeDirectory(testDir);
     Files = _filesys.FileList();
 }
Esempio n. 9
0
        /// Streamed Upload
        public async static Task <int> Upload(HttpRequest request, IFile filesys, string targetFolder,
                                              string filename, long fileSizeLimit, string[] permittedExtensions)
        {
            long _fileSizeLimit = fileSizeLimit;
            int  reason         = 0;

            if (!MultipartRequestHelper.IsMultipartContentType(request.ContentType))
            {
                throw new Exception("Failed on Request.ContentType = " + request.ContentType + " (Error 1)");
            }

            MediaTypeHeaderValue contentType = MediaTypeHeaderValue.Parse(request.ContentType);
            // Use the default form options to set the default limits for request body data.
            int              lengthLimit = (new FormOptions()).MultipartBoundaryLengthLimit;
            string           boundary    = MultipartRequestHelper.GetBoundary(contentType, lengthLimit);
            MultipartReader  reader      = new MultipartReader(boundary, request.Body);
            MultipartSection section     = await reader.ReadNextSectionAsync();

            while (section != null)
            {
                var hasContentDispositionHeader =
                    ContentDispositionHeaderValue.TryParse(
                        section.ContentDisposition, out var contentDisposition);

                if (hasContentDispositionHeader)
                {
                    // This check assumes that there's a file present without form data.
                    // If form data is present, this method immediately fails and returns the error.
                    if (!MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                    {
                        throw new Exception("Failed on Content Disposition (Error 2)");
                    }
                    else
                    {
                        // In the  following, the file is saved without scanning the file's contents.
                        // In most production scenarios, an anti-virus/anti-malware scanner API
                        // is used on the file before making the file available for download or
                        // for use by other systems.


                        using (var stream = new MemoryStream())
                        {
                            await section.Body.CopyToAsync(stream);

                            string sourceFilename = contentDisposition.FileName.Value;

                            reason = FileHelpers.CheckStreamSize(stream, _fileSizeLimit);
                            if (reason == 0)
                            {
                                reason = FileHelpers.CheckStreamContent(stream, sourceFilename, permittedExtensions);
                            }

                            if (reason == 0)
                            {
                                byte[] bytes   = stream.ToArray();
                                Stream stream2 = new MemoryStream(bytes);

                                filesys.ChangeDirectory(targetFolder);
                                string ext = Path.GetExtension(sourceFilename).ToLowerInvariant();
                                if (filename == null)
                                {
                                    filename = WebUtility.HtmlEncode(sourceFilename);
                                }
                                filename = Path.ChangeExtension(filename, ext);
                                filesys.FileUpload(filename, stream2);

                                Log.Me.Info("Uploaded " + WebUtility.HtmlEncode(sourceFilename) + " as " + filename);
                            }
                        }
                    }
                }

                // Drain any remaining section body that hasn't been consumed and
                // read the headers for the next section.
                section = await reader.ReadNextSectionAsync();
            }

            return(reason);
        }
        static void Main(string[] args)
        {
            Config.Setup("appsettings.json", Directory.GetCurrentDirectory(), null, "MistwarePostmanTest");

            string connection = Config.Get("AzureConnectionString");
            string container  = Config.Get("AzureContainer");
            string logs       = Config.Get("Logs");
            IFile  filesys    = FileBootstrap.SetupFileSys(connection, container, null, logs);

            Log.Me.LogFile = "MistwarePostmanTest.log";

            EmailBatch batch = new EmailBatch();

            batch.Postmaster = new MailAddress("noreply@" + Config.Get("TestDomain"), "ACME Postmaster");
            batch.From       = new MailAddress(Config.Get("TestEmail"), Config.Get("TestPerson"));
            batch.Name       = "Test Batch";
            batch.Recipients = new List <EmailRecipient>();

            EmailRecipient r1 = new EmailRecipient();

            r1.To              = new MailAddress(Config.Get("TestEmail"), Config.Get("TestPerson"));
            r1.DeliveryType    = "Summary";
            r1.Attachment      = null;
            r1.MailMergeFields = new Dictionary <string, string>();
            r1.MailMergeFields.Add("FromName", "Fred Bloggs");
            r1.MailMergeFields.Add("FromEmail", "*****@*****.**");
            r1.MailMergeFields.Add("ISBN", "9780141198354");
            r1.MailMergeFields.Add("Title", "Bleak House");
            r1.MailMergeFields.Add("Authors", "Charles Dickens");
            r1.MailMergeFields.Add("Summary", "A satirical story about the British judiciary system. \nEsther Summerson is a lonely girl who was raised by her aunt and is taken in by John Jarndyce, a rich philanthropist. Parts of the story are told from her point of view.");
            r1.MailMergeFields.Add("Link", "https://en.wikipedia.org/wiki/Bleak_House");
            batch.Recipients.Add(r1);

            EmailRecipient r2 = new EmailRecipient();

            r2.To              = new MailAddress(Config.Get("TestEmail"), Config.Get("TestPerson"));
            r2.DeliveryType    = "Full";
            r2.Attachment      = "BleakHouse.pdf";
            r2.MailMergeFields = new Dictionary <string, string>();
            r2.MailMergeFields.Add("FromName", "Fred Bloggs");
            r2.MailMergeFields.Add("FromEmail", "*****@*****.**");
            r2.MailMergeFields.Add("ISBN", "9780141198354");
            r2.MailMergeFields.Add("Title", "Bleak House");
            r2.MailMergeFields.Add("Authors", "Charles Dickens");
            batch.Recipients.Add(r2);

            List <EmailBatch> batches = new List <EmailBatch>();

            batches.Add(batch);

            Log.Me.Info("About to kick off the Emailing Thread");
            MailEngine engine = new MailEngine();

            engine.SendGridKey = Config.Get("SendGridKey");
            engine.FileSys     = filesys;
            engine.LoadTemplates(Directory.GetCurrentDirectory() + "/", "EmailTemplates.txt");
            filesys.ChangeDirectory(Config.Get("UploadDirectory"));
            filesys.FileUpload(Directory.GetCurrentDirectory() + "/" + "BleakHouse.pdf");
            engine.Start(batches);

            Thread.Sleep(10000); // Wait 10 secs, so thread will finish before we kill the app.
            filesys.FileDelete("BleakHouse.pdf");
        }
Esempio n. 11
0
        public static void FileTest(IFile file, string name, string filename, string upload, string folder1,
                                    string folder2, string download, long fileLength, bool tidy)
        {
            string sFail = "";

            file.MakeDirectory(folder1);
            Directory.SetCurrentDirectory(upload); // Set the local directory to upload from
            file.FileUpload(filename);

            if (!file.FileExists(filename))
            {
                sFail += "FileExists ";
            }

            file.ChangeDirectory(folder1);
            if (!file.FileExists(filename))
            {
                sFail += "ChangeDirectory ";
            }

            if (file.FileLength(filename) != fileLength)
            {
                sFail += "FileLength ";
            }

            bool found = false;
            List <DirectoryEntry> files = file.FileList();

            foreach (DirectoryEntry de in files)
            {
                if (de.Name == filename)
                {
                    found = true;
                }
            }
            if (!found)
            {
                sFail += "FileList ";
            }

            file.MakeDirectory(folder2);
            file.ChangeDirectory(folder1);
            file.FileCopy(filename, folder2);
            file.ChangeDirectory(folder2);
            if (!file.FileExists(filename))
            {
                sFail += "FileCopy ";
            }

            file.FileDownload(filename, download);
            string dirsep = Path.DirectorySeparatorChar.ToString();

            if (!FileCompare(upload + dirsep + filename, download + dirsep + filename))
            {
                sFail += "FileDownload ";
            }

            // Clean Up remote folders
            if (tidy)
            {
                file.FileDelete(filename);
                if (file.FileExists(filename))
                {
                    sFail += "FileDelete ";
                }
                file.ChangeDirectory(folder1);
                file.FileDelete(filename);
                file.DeleteDirectory(folder1);
                file.DeleteDirectory(folder2);
            }

            if (sFail.Length == 0)
            {
                Console.WriteLine("************************");
                Console.WriteLine("** " + name + " Tests passed **");
                Console.WriteLine("************************");
            }
            else
            {
                Console.WriteLine("!!!!!!!!!!!!!!!!!!!");
                Console.WriteLine("!! " + name + " tests failed: " + sFail);
                Console.WriteLine("!!!!!!!!!!!!!!!!!!!");
            }
        }