public void ConstructorSetsFileNameProperty()
        {
            // Act
            FilePathResult result = new FilePathResult("someFile", "contentType");

            // Assert
            Assert.Equal("someFile", result.FileName);
        }
Exemple #2
0
        public ActionResult DownloadPDF(string ev)
        {
            string path     = Server.MapPath("~/Download/");
            string logo     = Server.MapPath("~/Content/logo_bg1.png");
            string filename = Tools.PDFCreator.MakeTicket(User.Identity.Name, ev, path, logo);
            string fullPath = Path.Combine(path, filename);

            FilePathResult file = File(fullPath, "pdf");

            file.FileDownloadName = filename;
            return(file);
        }
        public FileResult DownloadArquivoOrtoFoto(string chave)
        {
            OrtofotoBus ortofotoBus = new OrtofotoBus();
            Ortofoto    ortofoto    = ortofotoBus.ValidarChaveOrtofoto(chave);

            string         diretorio  = Path.Combine(ConfigurationManager.AppSettings["diretorioOrtofotos"], ortofoto.ArquivoNome);
            FilePathResult fileResult = new FilePathResult(diretorio, "application/octet-stream");

            fileResult.FileDownloadName = ortofoto.ArquivoNome;

            return(fileResult);
        }
Exemple #4
0
        protected async Task WriteResponse(FilePathResult data)
        {
            if (!File.Exists(data.FileName))
            {
                throw new Exception($"File not found. Path: {data.FileName}");
            }

            SetResponseContentType("text/html");

            var reader = new StreamReader(data.FileName).ReadToEnd();
            await Context.Response.WriteAsync(reader);
        }
        public ActionResult DownloadXLS(string filename)
        {
            string path = Server.MapPath("~/Download/");

            Tools.XLSCreator.exportAsXLS(path, filename);
            string fullPath = Path.Combine(path, filename);

            FilePathResult file = File(fullPath, "xlsx");

            file.FileDownloadName = filename;
            return(file);
        }
        public void exportattachments_should_call_wikiexporter_exportattachments()
        {
            // Arrange
            var mockWikiExporter = new Mock <WikiExporter>(_applicationSettings, _pageService, _settingsRepository, _pageRepository, _userRepository, _pluginFactory);

            _toolsController._wikiExporter = mockWikiExporter.Object;

            // Act
            FilePathResult result = _toolsController.ExportAttachments() as FilePathResult;

            // Assert
            mockWikiExporter.Verify(x => x.ExportAttachments(result.FileDownloadName), Times.Once);
        }
        public ActionResult Reporte()
        {
            string archivoExcel = gestorArchivos.Reporte();

            FilePathResult download = new FilePathResult(
                archivoExcel,
                "application/vnd.ms-excel"
                );

            download.FileDownloadName = "Reporte_2016.xls";

            return(download);
        }
Exemple #8
0
        public void BookTest()
        {
            // Arrange
            ExampleController controller = new ExampleController();

            // Act
            FilePathResult result = controller.Book();

            // Assert
            Assert.AreEqual("application/pdf", result.ContentType);
            Assert.AreEqual("ASP.NET MVC3.pdf", result.FileDownloadName);
            //Assert.AreEqual(@"C:\Languages\C#\MVC3\Pro ASP.NET MVC 3 Framework (Apress).pdf", result.FileName);
        }
        public FilePathResult Get(string id)
        {
            DebugEx.Entry(id);

            string filename = Path.Combine(GameUiConfiguration.MapPath, id + ".xml");

            DebugEx.WriteLineF("Starsystem filename: {0}", Path.GetFullPath(filename));

            FilePathResult filePathResult = File(filename, "text/xml", id + ".xml");

            DebugEx.Exit(filePathResult);
            return(filePathResult);
        }
        public void ExportAsWikiFiles_Should_Call_WikiExporter_ExportAsWikiFiles()
        {
            // Arrange
            var mockWikiExporter = new Mock <WikiExporter>(_applicationSettings, _pageService, _repository, _pluginFactory);

            _toolsController._wikiExporter = mockWikiExporter.Object;

            // Act
            FilePathResult result = _toolsController.ExportAsWikiFiles() as FilePathResult;

            // Assert
            mockWikiExporter.Verify(x => x.ExportAsWikiFiles(result.FileDownloadName), Times.Once);
        }
        public ActionResult DownloadPDF(string filename)
        {
            string path = Server.MapPath("~/Download/");
            string logo = Server.MapPath("~/Content/logo_bg1.png");

            YakaTicket.Tools.PDFCreator.test(path, filename);
            string fullPath = Path.Combine(path, filename);

            FilePathResult file = File(fullPath, "pdf");

            file.FileDownloadName = filename;
            return(file);
        }
        public void ExportAsXml_Should_Call_WikiExporter_ExportAsXml()
        {
            // Arrange
            var mockWikiExporter = new Mock <WikiExporter>(_applicationSettings, _pageService, _repository, _pluginFactory);

            mockWikiExporter.Setup(x => x.ExportAsXml()).Returns(new MemoryStream());
            _toolsController._wikiExporter = mockWikiExporter.Object;

            // Act
            FilePathResult result = _toolsController.ExportAsXml() as FilePathResult;

            // Assert
            mockWikiExporter.Verify(x => x.ExportAsXml(), Times.Once);
        }
 public FilePathResult BaixarArquivoModelo()
 {
     try
     {
         FilePathResult file = new FilePathResult("~/Content/_zipModeloGeo/ModeloShape.zip", ContentType.ZIP);
         file.FileDownloadName = "ModeloShape.zip";
         return(file);
     }
     catch (Exception exc)
     {
         Validacao.AddErro(exc);
     }
     return(null);
 }
        public void exportassql_should_call_wikiexporter_exportassql()
        {
            // Arrange
            var mockWikiExporter = new Mock <WikiExporter>(_applicationSettings, _pageService, _settingsRepository, _pageRepository, _userRepository, _pluginFactory);

            _toolsController._wikiExporter = mockWikiExporter.Object;
            mockWikiExporter.Setup(x => x.ExportAsSql()).Returns(new MemoryStream());

            // Act
            FilePathResult result = _toolsController.ExportAsSql() as FilePathResult;

            // Assert
            mockWikiExporter.Verify(x => x.ExportAsSql(), Times.Once);
        }
        protected override void OnException(ExceptionContext filterContext)
        {
            HttpException httpException = (HttpException)filterContext.Exception;

            int _err = httpException.GetHttpCode();

            Exception exception = filterContext.Exception;

            filterContext.ExceptionHandled = true;

            ErrorModel _error = new ErrorModel();
            //Response.StatusCode = 500;
            var routeData = new RouteData();

            routeData.Values.Add("controller", "Error");

            if (httpException == null)
            {
                routeData.Values.Add("action", "Error500");
            }
            else
            {
                switch (httpException.GetHttpCode())
                {
                // This is a forced case where ASP.NET/MVC comes through here.
                // 503 is an IIS Error - Service not available :: neither Asp.Net nad neither Mvc AND neither IIS are available.
                // However, if we invoke through .Net/MVC a throw new HttpException(503)... it should end up here.
                // Else, in web.config, there's a redirect to that page .HTML.
                case 503:
                    var _result503 = new FilePathResult("~/Error/Pages/ServiceUnavailable.html", "text/html");
                    filterContext.Result = _result503;
                    break;

                case 500:
                    _error = AppErrorModule.ExceptionOccurred(exception, 500);
                    var _result500 = this.View("~/Views/Error/Error500.cshtml", _error);
                    //var Result = this.View("Index", new HandleErrorInfo(exception,
                    //		filterContext.RouteData.Values["controller"].ToString(),
                    //		filterContext.RouteData.Values["action"].ToString()));

                    //var Result = this.View("Index", new HandleErrorInfo(exception,
                    //		filterContext.RouteData.Values["controller"].ToString(),
                    //		filterContext.RouteData.Values["action"].ToString()));

                    filterContext.Result = _result500;
                    break;
                }
            }
        }
        public void ExportAttachments_Should_Set_Filename_And_ContentType()
        {
            // Arrange
            string fullPath = Path.Combine(_wikiExporter.ExportFolder, "attachments-");

            // Act
            FilePathResult result = _toolsController.ExportAttachments() as FilePathResult;

            // Assert
            Assert.That(result, Is.Not.Null, "FileStreamResult");
            Assert.That(result.FileName, Is.StringStarting(fullPath));
            Assert.That(result.FileDownloadName, Is.StringStarting("attachments-"));
            Assert.That(result.FileDownloadName, Is.StringEnding(".zip"));
            Assert.That(result.ContentType, Is.EqualTo("application/zip"));
        }
        public ActionResult Descarga(string id)
        {
            try {
                ArchivoDescarga archivo  = gestorArchivos.TraerArchivo(id);
                FilePathResult  download = new FilePathResult(archivo.Ruta, MimeMapping.GetMimeMapping(archivo.Nombre));
                download.FileDownloadName = archivo.Nombre;

                return(download);
            }

            catch (IndexOutOfRangeException ex)
            {
                return(new HttpNotFoundResult($"Tipo {id} no encontrado"));
            }
        }
Exemple #18
0
        public ActionResult Get(string fileName)
        {
            var filePath = FilesHelper.RelativePath + fileName;
            var result   = new FilePathResult(filePath, System.Web.MimeMapping.GetMimeMapping(fileName));

            result.FileDownloadName = fileName;
            if (System.IO.File.Exists(Server.MapPath(result.FileName)))
            {
                return(result);
            }
            else
            {
                return(Redirect(HttpContext.Request.UrlReferrer.AbsoluteUri));
            }
        }
        public ActionResult DownloadICS(string filename)
        {
            string       path = Server.MapPath("~/Download/");
            var          ics  = new Tools.ICSCreator();
            StreamWriter sw   = new StreamWriter(path + filename);

            sw.Write(ics.exportAsICS());
            sw.Close();

            string         fullPath = Path.Combine(path, filename);
            FilePathResult file     = File(fullPath, "text");

            file.FileDownloadName = filename;
            return(file);
        }
Exemple #20
0
        public FileResult DownloadImage(Photo photo, string location)
        {
            byte[] image = photo.RawData;

            FileContentResult contentResult = File(image, "img/png", photo.Name + ".png");

            if (!string.IsNullOrEmpty(location))
            {
                FilePathResult pathResult = File(location, "plain/text", "fileName");

                return(pathResult);
            }

            return(contentResult);
        }
Exemple #21
0
        public ActionResult Export(DateTime id)
        {
            string template = Server.MapPath("~/Content/templates/template-attendance.xlsx");
            string exported = Server.MapPath("~/Content/exported/" + "考勤记录-" + id.ToString("yyyy-MM-dd") + ".xlsx");
            var    ctx      = new TaskAssignmentModel();
            var    members  = ctx.Members.Where(m => m.IsInternal && m.Enable);
            var    record   = ctx.Attendances.Where(att => att.StartDate.Month == id.Month &&
                                                    att.StartDate.Year == id.Year &&
                                                    att.Member.Enable);
            var absType    = ctx.AttendanceTypes.Where(t => t.IsAbsent);
            var t_holidays = ctx.Holidays.SingleOrDefault(h => h.Year == id.Year);
            var thd        = t_holidays.Holidays.Split(';').Where(h => h.StartsWith(id.ToString("MM") + "-")).ToArray();
            var tex        = t_holidays.ExtraWorkdays.Split(';').Where(e => e.StartsWith(id.ToString("MM") + "-")).ToArray();

            int[] holidays      = new int[thd.Count()];
            int[] extraWorkdays = new int[tex.Count()];
            for (int i = 0; i < holidays.Length; i++)
            {
                holidays[i] = Convert.ToInt32(thd[i].Substring(3));
            }
            for (int i = 0; i < extraWorkdays.Length; i++)
            {
                extraWorkdays[i] = Convert.ToInt32(tex[i].Substring(3));
            }

            try {
                Global.Logger.AppendLog("Export");
                ExcelHelper.Export(id, members, record, absType, holidays, extraWorkdays, template, exported);
            }
            catch (Exception ex) {
                Global.Logger.AppendLog(ex);
            }
            //GC.Collect();

            FilePathResult r;

            if (System.IO.File.Exists(exported))
            {
                r = new FilePathResult(exported, ExcelHelper.XlsxContentType);
                r.FileDownloadName = "考勤记录-" + id.ToString("yyyy-MM-dd") + ".xlsx";
                return(r);
            }
            else
            {
                Global.Logger.AppendLog("Error occured!");
                return(RedirectToAction("Error"));
            }
        }
Exemple #22
0
        public ActionResult ExportExcel(int Month, int Year)
        {
            if (LoginProfile.BranchList == null)
            {
                LoginProfile.BranchList = EOfficeService.current.GetBranchForUser(LoginProfile.UserName, out ErrorResult);
            }

            List <eOfficeEmployee> listUser = new List <eOfficeEmployee>();

            foreach (var branchItem in LoginProfile.BranchList)
            {
                listUser.AddRange(EOfficeService.current.GetUserBranchTree(branchItem.BranchId, LoginProfile.UserName, out ErrorResult));
            }

            if (listUser.Count == 0)
            {
                return(Content("Anh/chị hiện không quản lý nhân viên nào!"));
            }

            System.IO.File.Copy(Server.MapPath("~/Content/Reports/BaoCaoChamCong.xlsx"), Server.MapPath("~/Content/Reports/BaoCaoChamCongTemp.xlsx"), true);
            var    wb    = new XLWorkbook(Server.MapPath("~/Content/Reports/BaoCaoChamCongTemp.xlsx"));
            string month = Month < 10 ? "0" + Month.ToString() : Month.ToString();
            string title = "BÁO CÁO CHẤM CÔNG " + LoginProfile.SpecializeBranch?.BranchName?.ToUpper();

            IXLWorksheet ws;

            wb.TryGetWorksheet("BC đi trễ", out ws);
            ws.Cell("A2").Value = "Đơn vị: " + LoginProfile.SpecializeBranch?.BranchName;
            ws.Cell("A3").Value = title;
            ws.Cell("A4").Value = "Tháng " + month + "/" + Year.ToString();

            IXLWorksheet wsBCDiTre;

            wb.TryGetWorksheet("BC lý do đi làm trễ", out wsBCDiTre);

            SetTableHeader(Month, Year, ws);
            SetValueToSheet1(Month, Year, ws, wsBCDiTre, listUser);

            string tempDir  = Server.MapPath("~/Temp");
            string fileName = Path.Combine(tempDir, title + " THÁNG " + month + " NĂM " + Year.ToString() + ".xlsx");

            wb.SaveAs(fileName);

            var result = new FilePathResult(fileName, "application/excel");

            result.FileDownloadName = title + " THÁNG " + month + " NĂM " + Year.ToString() + ".xlsx";
            return(result);
        }
Exemple #23
0
        public FilePathResult Download(string file)
        {
            var    decodedFile = HttpUtility.UrlDecode(file);
            string pathString  = WebConfigurationManager.AppSettings["directorypath"];

            string   fullPath    = pathString + decodedFile;
            FileInfo fileInfo    = new FileInfo(fullPath);
            string   contentType = ContentTypeUtility.GetMimeTypeFromFilename(fileInfo.Name);

            var result = new FilePathResult(fileInfo.FullName, contentType)
            {
                FileDownloadName = fileInfo.Name
            };

            return(result);
        }
Exemple #24
0
        public ActionResult DownloadExcel()
        {
            string fileName = Request["excel"] + ".xlsx";
            string filePath = "/Statis/" + fileName;

            if (!System.IO.File.Exists(filePath))
            {
                return(Content("无数据"));
            }

            FilePathResult file = new FilePathResult("~/Statis/" + fileName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

            file.FileDownloadName = fileName + ".xlsx";

            return(file);
        }
        public ActionResult Download(string p)
        {
            if (!Services.Authorizer.Authorize(Permissions.DownloadPackages, T("Not allowed to download packages")))
            {
                return(new HttpUnauthorizedResult());
            }

            string fileName = _packageService.CreatePackage(p, _tempPackageStoragePath.Value);

            if (!string.IsNullOrWhiteSpace(fileName) && System.IO.File.Exists(fileName))
            {
                var filePathResult = new FilePathResult(fileName, _mimeTypeProvider.GetMimeType(fileName));
                filePathResult.FileDownloadName = Path.GetFileName(fileName);
                return(filePathResult);
            }
            return(new HttpNotFoundResult());
        }
        public FilePathResult DownloadFile(string theme, string name)
        {
            if (theme.Contains(".") || theme.Contains("/") || theme.Contains("\\") ||
                name.Contains("..") || name.Contains("/") || name.Contains("\\"))
            {
                return(null);
            }

            name = name.Replace('|', '\\');

            var filePath = Path.Combine(Server.MapPath("~/Views"), theme, name);

            var result = new FilePathResult(filePath, "application/octet-stream");

            result.FileDownloadName = Path.GetFileName(filePath);
            return(result);
        }
        public ActionResult File(int id, string guid)
        {
            CFDataFile file = DataService.GetFile(id, guid);

            if (file == null)
            {
                return(HttpNotFound("File not found"));
            }

            string path_name = Path.Combine(file.Path, file.LocalFileName);

            FilePathResult result = new FilePathResult(path_name, file.ContentType);

            result.FileDownloadName = file.FileName;

            return(result);
        }
Exemple #28
0
        public FilePathResult View(string Url)
        {
            FilePathResult result = null;
            var            file   = CoreServices.File.Get(CoreServices.Portal.CurrentPortalId, Url);

            if (file != null)
            {
                var fileName = Portal.GetFile(CoreServices.Portal.CurrentPortalId, file.Id);
                result = File(fileName, file.MimeType);

                this.Response.AddFileDependency(fileName);
                this.Response.Cache.SetCacheability(System.Web.HttpCacheability.Public);
                this.Response.Cache.SetLastModifiedFromFileDependencies();
                this.Response.Cache.SetETagFromFileDependencies();
            }

            return(result);
        }
Exemple #29
0
        public ActionResult Email()
        {
            try
            {
                SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
                smtp.UseDefaultCredentials = false;
                smtp.Credentials           = new NetworkCredential("patientnowait", "kangaroo1234");
                smtp.EnableSsl             = true;
                smtp.Send("*****@*****.**", "*****@*****.**", "Subject - Pateint No Wait Mail", "Email Body - Pateint No WaitTest Mail");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            var result = new FilePathResult("~/Views/Home/Hospital.html", "text/html");

            return(result);
        }
        private ActionResult getFileResult(string path, Report report)
        {
            var contentType = MimeMapping.GetMimeMapping(path);
            var result      = new FilePathResult(path, contentType);

            if (contentType != "text/html")
            {
                if (report != null)
                {
                    result.FileDownloadName = Helper.CleanFileName(report.DisplayNameEx + Path.GetExtension(path));
                }
                else
                {
                    result.FileDownloadName = Path.GetFileName(path);
                }
            }

            return(result);
        }
Exemple #31
0
        public ActionResult ExternList()
        {
            if (!Request.IsAuthenticated)
            {
                return(new HttpStatusCodeResult(System.Net.HttpStatusCode.Forbidden));
            }
            if (!(Database.Database.database.RequestBoolean("f_is_moderator", User.Identity.GetUserName()) ||
                  Database.Database.database.RequestBoolean("f_is_administrator", User.Identity.GetUserName())))
            {
                return(new HttpStatusCodeResult(System.Net.HttpStatusCode.Forbidden));
            }
            string         path     = Server.MapPath("~/Download/");
            string         filename = Tools.XLSCreator.externAsXLS(path);
            string         fullPath = Path.Combine(path, filename);
            FilePathResult file     = File(fullPath, "xlsx");

            file.FileDownloadName = filename;
            return(file);
        }
Exemple #32
0
        private void ExecuteContentFile(IContext context)
        {
            string contentType;
            if (ContentType != null)
                contentType = ContentType;
            else
            {
                string extension = System.IO.Path.GetExtension(ContentFile);
                contentType = MimeTypes.FromExtension(extension);
            }

            if (System.IO.Path.IsPathRooted(ContentFile))
            {
                if (!System.IO.File.Exists(ContentFile))
                    throw new HttpException((int)HttpStatusCode.NotFound, string.Format("Resource '{0}' not found.", ContentFile));

                var result = new FilePathResult(ContentFile, contentType);
                if (!string.IsNullOrEmpty(FileDownloadName))
                    result.FileDownloadName = FileDownloadName;

                ExecuteFileResult(context, result);
            }
            else
            {
                string resourceLocation = context.Page.GetResourceLocation(ContentFile);
                if (!_resourceProvider.ResourceExists(resourceLocation))
                    throw new HttpException((int)HttpStatusCode.NotFound, string.Format("Resource '{0}' not found.", resourceLocation));

                using (var contentStream = _resourceProvider.OpenResource(resourceLocation))
                {
                    var result = new StreamResult(contentStream, contentType);
                    if (!string.IsNullOrEmpty(FileDownloadName))
                        result.FileDownloadName = FileDownloadName;

                    ExecuteFileResult(context, result);
                }
            }
        }