Ejemplo n.º 1
0
        public override void ExecuteResult(ControllerContext context)
        {
            var xmlSerializerNamespaces = new XmlSerializerNamespaces();

            xmlSerializerNamespaces.Add(string.Empty, string.Empty);

            var xmlWriterSettings = new XmlWriterSettings();

            xmlWriterSettings.Indent             = false;
            xmlWriterSettings.OmitXmlDeclaration = true;

            var xmlSerializer = new XmlSerializer(typeof(Projects));

            string xml;

            using (var textWriter = new StringWriter())
            {
                using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, xmlWriterSettings))
                {
                    xmlSerializer.Serialize(xmlWriter, _model, xmlSerializerNamespaces);
                }
                xml = textWriter.ToString();
            }
            var fileContentResult = new FileContentResult(Encoding.UTF8.GetBytes(xml), "text/xml");

            fileContentResult.FileDownloadName = "status.xml";
            fileContentResult.ExecuteResult(context);
        }
Ejemplo n.º 2
0
    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }

        // Set the model and data
        context.Controller.ViewData.Model = Model;
        ViewData = context.Controller.ViewData;
        TempData = context.Controller.TempData;


        // Get the view name
        if (string.IsNullOrEmpty(ViewName))
        {
            ViewName = context.RouteData.GetRequiredString("action");
        }

        // Get the view
        ViewEngineResult viewEngineResult = null;

        if (View == null)
        {
            viewEngineResult = FindView(context);
            View             = viewEngineResult.View;
        }

        // Render the view
        StringBuilder sb = new StringBuilder();

        using (TextWriter tr = new StringWriter(sb))
        {
            ViewContext viewContext = new ViewContext(context, View, ViewData, TempData, tr);
            View.Render(viewContext, tr);
        }
        if (viewEngineResult != null)
        {
            viewEngineResult.ViewEngine.ReleaseView(context, View);
        }

        // Create a PDF from the rendered view content
        Aspose.Pdf.Generator.Pdf pdf = new Aspose.Pdf.Generator.Pdf();
        using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(sb.ToString())))
        {
            pdf.BindXML(ms, null);
        }

        // Save the PDF to the response stream
        using (MemoryStream ms = new MemoryStream())
        {
            pdf.Save(ms);
            FileContentResult result = new FileContentResult(ms.ToArray(), "application/pdf")
            {
                FileDownloadName = FileDownloadName
            };
            result.ExecuteResult(context);
        }
    }
Ejemplo n.º 3
0
        public override void ExecuteResult(ControllerContext context)
        {
            var result = new FileContentResult(
                _chart.GetBytes(_imageType),
                "image/" + _imageType);

            result.ExecuteResult(context);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// 导出文件
        /// </summary>
        /// <param name="fileContents">字节数组</param>
        /// <param name="outputName">要输出的文件名称,含扩展名</param>
        public void OutPut(byte[] fileContents, string outputName)
        {
            var fileResult = new FileContentResult(fileContents, MimeMapping.GetMimeMapping(outputName))
            {
                FileDownloadName = outputName
            };

            fileResult.ExecuteResult(this.context);
        }
Ejemplo n.º 5
0
        public override void ExecuteResult(ControllerContext context)
        {
            byte[] data = new CsvFileCreator().AsBytes(ModelListing);

            var fileResult = new FileContentResult(data, "text/csv")
            {
                FileDownloadName = "CsvFile.csv"
            };

            fileResult.ExecuteResult(context);
        }
        public override void ExecuteResult(ControllerContext context)
        {
            var generator = new ExelReportGenarator.LoanHistoryExelReportGenerator();
            var loans     = _customer.Loans.Select(l => LoanModel.FromLoan(l, new LoanRepaymentScheduleCalculator(l, null, CurrentValues.Instance.AmountToChargeFrom))).ToList();
            var content   = generator.GenerateReport(loans, _customer.PersonalInfo.Fullname);
            var f         = new FileContentResult(content, "application/xls")
            {
                FileDownloadName = "LoanHistory(" + _customer.PersonalInfo.Fullname + ").xls"
            };

            f.ExecuteResult(context);
        }
Ejemplo n.º 7
0
        public override void ExecuteResult(ControllerContext context)
        {
            var medalCalculator = new MedalCalculators(_customer);
            var generator       = new MedalExcelReportGenerator();
            var content         = generator.GenerateReport(medalCalculator, _customer.PersonalInfo.Fullname);
            var f = new FileContentResult(content, "application/xls")
            {
                FileDownloadName = "Medal Calculations(" + _customer.PersonalInfo.Fullname + ").xls"
            };

            f.ExecuteResult(context);
        }
Ejemplo n.º 8
0
    public override void ExecuteResult(ControllerContext context) {
      if (context == null) {
        throw new ArgumentNullException("context");
      }

      // Set the model and data
      context.Controller.ViewData.Model = Model;
      ViewData = context.Controller.ViewData;
      TempData = context.Controller.TempData;


      // Get the view name
      if (string.IsNullOrEmpty(ViewName)) {
        ViewName = context.RouteData.GetRequiredString("action");
      }

      // Get the view
      ViewEngineResult viewEngineResult = null;
      if (View == null) {
        viewEngineResult = FindView(context);
        View = viewEngineResult.View;
      }

      // Render the view
      StringBuilder sb = new StringBuilder();
      using (TextWriter tr = new StringWriter(sb)) {
        ViewContext viewContext = new ViewContext(context, View, ViewData, TempData, tr);
        View.Render(viewContext, tr);
      }
      if (viewEngineResult != null) {
        viewEngineResult.ViewEngine.ReleaseView(context, View);
      }

      // Create a PDF from the rendered view content

      var workStream = new MemoryStream();
      var document = new Document();
      PdfWriter writer = PdfWriter.GetInstance(document, workStream);
      writer.CloseStream = false;
      document.Open();
      Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(sb.ToString()));

      XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, stream, Encoding.UTF8);
      document.Close();

      // Save the PDF to the response stream
      FileContentResult result = new FileContentResult(workStream.ToArray(), "application/pdf") {
        FileDownloadName = FileDownloadName
      };

      result.ExecuteResult(context);
    }
Ejemplo n.º 9
0
        public async Task GetImage(int id)
        {
            try
            {
                var image = await imageManager.GetImageAsync(id);

                var res = new FileContentResult(image.Content, MimeMapping.GetMimeMapping(image.ImageTypeExtenction));
                res.ExecuteResult(this.ControllerContext);
            }
            catch (Exception)
            {
                Redirect(this.Request.UrlReferrer?.AbsoluteUri ?? "/").ExecuteResult(this.ControllerContext);
            }
        }
Ejemplo n.º 10
0
        public override void ExecuteResult(ControllerContext context)
        {
            var fileFormat = _isExcel ? "xls" : "pdf";
            var generator  = new LoanOfferReportGenerator();
            var header     = string.Format("LoanOffer ({0}, {1}, {2})",
                                           (_customer.PersonalInfo.FirstName +
                                            ((_customer.PersonalInfo.MiddleInitial == null) ? " ": (" " + _customer.PersonalInfo.MiddleInitial) + " ") +
                                            _customer.PersonalInfo.Surname
                                           ),
                                           _customer.RefNumber, _loanOffer.Details.Date.ToString("dd_MM_yyyy"));
            var content  = generator.GenerateReport(_loanOffer, _isExcel, _isShowDetails, header);
            var fileName = header + "." + fileFormat;
            var f        = new FileContentResult(content, "application/" + fileFormat)
            {
                FileDownloadName = fileName
            };

            f.ExecuteResult(context);
        }
Ejemplo n.º 11
0
        public override void ExecuteResult(ControllerContext context)
        {
            var fileFormat = _isExcell ? "xls" : "pdf";
            var header     = string.Format("Payment Schedule ({0}, {1}, {2}, {3})",
                                           (_customer.PersonalInfo.FirstName +
                                            ((_customer.PersonalInfo.MiddleInitial == null) ? " " : (" " + _customer.PersonalInfo.MiddleInitial) + " ") +
                                            _customer.PersonalInfo.Surname),
                                           _customer.RefNumber,
                                           _loan.RefNumber,
                                           DateTime.Now.ToString("dd/MM/yyyy"));

            var generator = new LoanScheduleReportGenerator();
            var content   = generator.GenerateReport(_loanDetails, _isExcell, _withErrors, header);
            var fileName  = header + "." + fileFormat;
            var f         = new FileContentResult(content, "application/" + fileFormat)
            {
                FileDownloadName = fileName
            };

            f.ExecuteResult(context);
        }
Ejemplo n.º 12
0
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (string.IsNullOrEmpty(ViewName))
            {
                throw new ArgumentNullException("ViewName");
            }

            ViewData = context.Controller.ViewData;
            TempData = context.Controller.TempData;

            ViewEngineResult viewEngineResult = null;

            if (View == null)
            {
                viewEngineResult = FindView(context);
                View             = viewEngineResult.View;
            }

            if (viewEngineResult != null)
            {
                viewEngineResult.ViewEngine.ReleaseView(context, View);
            }

            var streamReader = new StreamReader(_htmlFileSource);
            var htmlString   = streamReader.ReadToEnd();

            var pdfSource = _converter.ConvertToPdfAsArray(_settings, htmlString);

            FileContentResult result = new FileContentResult(pdfSource, "application/pdf")
            {
                FileDownloadName = _settings.FileName
            };

            result.ExecuteResult(context);
        }
Ejemplo n.º 13
0
        public override void ExecuteResult(ControllerContext context)
        {
            using (var pck = new ExcelPackage())
            {
                var ws = pck.Workbook.Worksheets.Add(WorksheetName);

                if (ColumnDefinitions == null)
                {
                    ws.Cells["A1"].LoadFromCollection(_records, true, TableStyles.None);
                }
                else
                {
                    ws.Cells["A1"].LoadFromCollection(_records, true, TableStyles.None, BindingFlags.Default, ColumnDefinitions.Select(x => x.MemberInfo).ToArray());
                    Format(ws, ColumnDefinitions);
                }

                const string contentType       = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                var          fileContentResult = new FileContentResult(pck.GetAsByteArray(), contentType)
                {
                    FileDownloadName = FileDownloadName
                };
                fileContentResult.ExecuteResult(context);
            }
        }
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            // Set the model and data
            context.Controller.ViewData.Model = Model;
            ViewData = context.Controller.ViewData;
            TempData = context.Controller.TempData;

            // Get the view name
            if (string.IsNullOrEmpty(ViewName))
            {
                ViewName = context.RouteData.GetRequiredString("action");
            }

            // Get the view
            ViewEngineResult viewEngineResult = null;

            if (View == null)
            {
                viewEngineResult = FindView(context);
                View             = viewEngineResult.View;
            }

            // Render the view
            var sb = new StringBuilder();

            using (TextWriter tr = new StringWriter(sb))
            {
                var viewContext = new ViewContext(context, View, ViewData, TempData, tr);
                View.Render(viewContext, tr);
            }

            viewEngineResult?.ViewEngine.ReleaseView(context, View);
            var scheme = (context.RequestContext.HttpContext.Request.Url != null) ?
                         context.RequestContext.HttpContext.Request.Url.Scheme : "http";
            var baseUri =
                $"{scheme}://{context.RequestContext.HttpContext.Request.Url.Authority}{context.RequestContext.HttpContext.Request.ApplicationPath}/";

            // Load HTML file
            if (Options == null)
            {
                Options = new Aspose.Pdf.HtmlLoadOptions(baseUri);
            }


            var pdfDocument = new Document(new MemoryStream(Encoding.UTF8.GetBytes(sb.ToString())), Options);

            using (var streamOut = new MemoryStream())
            {
                pdfDocument.Save(streamOut);
                streamOut.Seek(0, SeekOrigin.Begin);
                var result = new FileContentResult(streamOut.ToArray(), "application/pdf")
                {
                    FileDownloadName = FileDownloadName
                };
                result.ExecuteResult(context);
            }
        }
Ejemplo n.º 15
0
        public override void ExecuteResult(ControllerContext context)
        {
            const int ROW_NUMBER_COL_HEADING = 2;

            using (var pkg = new ExcelPackage())
            {
                pkg.Workbook.Properties.Author   = context.HttpContext.User.Identity.Name ?? "Anonymous";
                pkg.Workbook.Properties.Comments = "This file was automatically generated by DCMS Connect - Inquiry";
                pkg.Workbook.Properties.Company  = "Eclipse Systems";
                var name = Assembly.GetExecutingAssembly().GetName();
                pkg.Workbook.Properties.Status = string.Format("{0} {1}", name.Name, name.Version);

                if (_sheets.Count == 0)
                {
                    throw new NotImplementedException("This should never happen. Did you forget to add sheets?");
                }

                foreach (var sheet in _sheets)
                {
                    var wks = pkg.Workbook.Worksheets.Add(sheet.TabName);
                    // 0 based Index of the last column in this sheet
                    int maxColIndex = -1;
                    foreach (var row in sheet.Rows.Cast <object>().Where(p => p != null).Select((p, i) => new
                    {
                        Index = i,
                        Value = p
                    }))
                    {
                        var columns = ModelMetadataProviders.Current.GetMetadataForType(() => row.Value, sheet.ElementType).Properties
                                      .Where(p => p.ShowForDisplay && !p.IsComplexType)
                                      .OrderBy(p => p.Order)
                                      .Select((p, i) =>
                        {
                            var dtype = GetDataType(p);
                            return(new
                            {
                                Index = i,
                                ShortDisplayName = p.ShortDisplayName ?? p.PropertyName,
                                ColumnDataType = dtype,
                                Model = p.Model,
                                DateValue = GetDateValue(p.ModelType, p.Model, dtype)
                            });
                        });

                        foreach (var col in columns)
                        {
                            maxColIndex = Math.Max(maxColIndex, col.Index);
                            if (row.Index == 0)
                            {
                                // First Row. Generate headings
                                wks.Cells[ROW_NUMBER_COL_HEADING, col.Index + 1].Value = col.ShortDisplayName;
                                var excelCol = wks.Column(col.Index + 1);
                                switch (col.ColumnDataType)
                                {
                                case DataType.Date:
                                    excelCol.Style.Numberformat.Format = "m/d/yyyy";
                                    break;

                                case DataType.DateTime:
                                    excelCol.Style.Numberformat.Format = "m/d/yyyy h:mm";
                                    break;

                                case DataType.Time:
                                    excelCol.Style.Numberformat.Format = "h:mm";
                                    break;

                                case DataType.Currency:
                                    excelCol.Style.Numberformat.Format = "#,##0";
                                    break;

                                case DataType.Text:
                                    excelCol.Style.Numberformat.Format = "@";
                                    break;

                                case DataType.MultilineText:
                                    excelCol.Style.Numberformat.Format         = "@";
                                    excelCol.Style.WrapText                    = true;
                                    wks.Cells[2, col.Index + 1].Style.WrapText = false;
                                    break;

                                default:
                                    throw new NotImplementedException();
                                }
                                //rowNumber = ROW_NUMBER_COL_HEADING + 1;
                            }

                            if (col.Model != null)
                            {
                                if (col.DateValue.HasValue)
                                {
                                    try
                                    {
                                        wks.Cells[row.Index + ROW_NUMBER_COL_HEADING + 1, col.Index + 1].Value = col.DateValue.Value.ToOADate();
                                    }
                                    catch (OverflowException)
                                    {
                                        // This happens when the date is too old to be represented as OLE date e.g. 2/1/0013
                                        // In this case, show the string representation
                                        wks.Cells[row.Index + ROW_NUMBER_COL_HEADING + 1, col.Index + 1].Value = col.DateValue.Value.ToString();
                                    }
                                }
                                else
                                {
                                    wks.Cells[row.Index + ROW_NUMBER_COL_HEADING + 1, col.Index + 1].Value = col.Model;
                                }
                            }
                        }
                    }

                    if (maxColIndex == -1)
                    {
                        // Empty worksheet. Row 1 is still the heading
                        wks.Cells[1, 1].Value                                  = sheet.Heading;
                        wks.Cells[1, 1].Style.Font.Bold                        = true;
                        wks.Cells[ROW_NUMBER_COL_HEADING, 1].Value             = "There are no rows in this list";
                        wks.Cells[ROW_NUMBER_COL_HEADING, 1].Style.Font.Italic = true;
                    }
                    else
                    {
                        // Row 2 Column headers must be bold. colNumber now represents the number of columns
                        var header = wks.Cells[2, 1, 2, maxColIndex + 1];
                        header.Style.Font.Bold = true;

                        // Row 1: Worksheet heading
                        header       = wks.Cells[1, 1, 1, maxColIndex + 1];
                        header.Merge = true;
                        header.Value = sheet.Heading;
                        header.Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                        header.Style.Font.Bold           = true;
                    }
                    wks.Cells.AutoFitColumns();
                }

                // Render XML file contents instead of the view
                var result = new FileContentResult(pkg.GetAsByteArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                {
                    FileDownloadName = string.Format("{0}.xlsx", _fileName)
                };
                result.ExecuteResult(context);
            }
        }