示例#1
0
        public void ToExcel(HttpResponseBase Response, object clientsList)
        {
            var grid = new System.Web.UI.WebControls.GridView();

            grid.DataSource = clientsList;
            grid.DataBind();
            Response.ClearContent();

            //Response.AddHeader("content-disposition", "attachment; filename=Export.xls");
            //Response.ContentType = "application/excel";

            //Response.AddHeader("content-disposition", "attachment;filename=Lotes.xls");
            //Response.AddHeader("Content-Type", "application/vnd.ms-excel");

            //Response.AddHeader("content-disposition", "attachment; filename= LotesExcel.xlsx");
            //Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename= LotesTestes.xlsx");
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

            StringWriter   sw  = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            grid.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();
        }
        /// <summary>
        /// Executes the result.
        /// </summary>
        /// <param name="context">The context.</param>
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            HttpResponseBase response = context.HttpContext.Response;

            if (!String.IsNullOrEmpty(ContentType))
            {
                response.ContentType = ContentType;
            }

            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }

            response.Cache.SetCacheability(HttpCacheability.NoCache);
            response.Cache.AppendCacheExtension("no-cache=\"Set-Cookie\", proxy-revalidate");
            response.AppendHeader("X-Robots-Tag", "noindex, follow, noarchive, nosnippet");
            response.ClearContent();

            if (Data != null)
            {
                string content = GetContent();

                if (content != null)
                {
                    response.Write(content);
                }
            }
        }
        public static void ExportData(object data, HttpResponseBase Response, string fileName)
        {
            //List<object> pdoList = repoDemand.GetListByYearWeek(yearWeek, productionType).ToList();
            var gv = new GridView();

            gv.DataSource = data;// pdoList;
            gv.DataBind();
            Response.ClearContent();
            Response.Buffer = true;
            //Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");

            Response.Charset         = "UTF-8";
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            //Response.Write("ąęćżźń󳥌ŻŹĆŃŁÓĘ");
            Response.Write('\uFEFF');
            Response.AddHeader("content-disposition", string.Format("attachment; filename={0}.xls", fileName));
            Response.ContentType = "application/ms-excel";
            //Response.Charset = "";

            //Response.ContentType = "text/rtf; charset=UTF-8";

            StringWriter   objStringWriter   = new StringWriter();
            HtmlTextWriter objHtmlTextWriter = new HtmlTextWriter(objStringWriter);

            gv.RenderControl(objHtmlTextWriter);
            Response.Output.Write(objStringWriter.ToString());
            Response.Flush();
            Response.End();
        }
示例#4
0
        public override void ExecuteResult(ControllerContext context)
        {
            HttpResponseBase response = context.HttpContext.Response;

            try
            {
                response.ClearHeaders();
                response.ClearContent();
            }
            catch { }

            response.TrySkipIisCustomErrors = true;

            if (this.HttpStatus != default(HttpStatusCode))
            {
                response.StatusCode = (int)this.HttpStatus;
            }

            if (String.IsNullOrEmpty(this.ContentType))
            {
                response.ContentType = "text/plain";
            }
            else
            {
                response.ContentType = this.ContentType;
            }

            this.WriteMessage(response);
        }
示例#5
0
        public bool ToExcel(HttpResponseBase Response, DataTable listTable, string nomeArquivo = "ConsultaPedidos.xls", int columnsMerged = 0)
        {
            var grid = new System.Web.UI.WebControls.GridView();

            grid.DataSource = listTable;


            grid.DataBind();

            if (columnsMerged > 0)
            {
                MergeRows(grid, columnsMerged);
            }


            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=" + nomeArquivo);
            Response.ContentType = "application/excel";
            StringWriter   sw  = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            grid.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();

            return(true);
        }
示例#6
0
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            // get rendered HTML from view
            string html     = ViewRenderer.RenderViewToString(context, ViewName, Model);
            var    cssFiles = CssHelper.GetAllCssPaths(html);
            //html = ClearHtmlStrategy.Clear(html);
            // generate the PDF content from HTML
            var pageConfig = PageConfig != null ? PageConfig : PageSize.A4;

            byte[]           content            = HtmlToPdfRenderer.Render(html, cssFiles, pageConfig);
            var              contentDisposition = IsAttachment ? "attachement" : "inline";
            HttpResponseBase response           = context.HttpContext.Response;

            response.Clear();
            response.ClearContent();
            response.ClearHeaders();
            response.ContentType = "application/pdf";
            response.AppendHeader("Content-Disposition", $"{contentDisposition};filename={Filename}.pdf");
            response.AddHeader("Content-Length", content.Length.ToString());
            response.BinaryWrite(content);
            response.OutputStream.Flush();
            response.OutputStream.Close();
            response.End();
        }
示例#7
0
        public static void ToExcel(HttpResponseBase response, object clientsList, string fileName, GridOnRowCreated onRowCreated = null)
        {
            var grid = new GridView();

            if (onRowCreated != null)
            {
                grid.RowCreated += new GridViewRowEventHandler(onRowCreated);
            }

            grid.DataSource = clientsList;
            grid.DataBind();
            response.ClearContent();
            fileName = String.Format("{0}.xls", fileName);
            response.AddHeader("content-disposition", "attachment; filename=" + fileName);
            response.ContentType = "application/excel";
            using (var sw = new StringWriter())
            {
                using (var htw = new HtmlTextWriter(sw))
                {
                    grid.RenderControl(htw);
                    response.Write(sw.ToString());
                    response.End();
                }
            }
        }
示例#8
0
 private static void DownloadPdf(HttpResponseBase Response, MemoryStream mstream)
 {
     mstream.WriteTo(Response.OutputStream);
     Response.ClearContent();
     Response.Clear();
     Response.End();
 }
 /// <summary>
 /// Exports the chart to the specified HttpResponse object. This method
 /// is preferred over WriteToStream() because it handles clearing the
 /// output stream and setting the HTTP reponse headers.
 /// </summary>
 /// <param name="httpResponse"></param>
 public void WriteToHttpResponse(HttpResponseBase httpResponse)
 {
     httpResponse.ClearContent();
     httpResponse.ClearHeaders();
     httpResponse.ContentType = this.ContentType;
     httpResponse.AddHeader("Content-Disposition", this.ContentDisposition);
     WriteToStream(httpResponse.OutputStream);
 }
示例#10
0
 internal void CheckForAuthFailure(HttpRequestBase request, HttpResponseBase response, HttpContextBase context)
 {
     if (true.Equals(context.Items["RequestWasNotAuthorized"]) && request.IsAjaxRequest())
     {
         response.StatusCode = 401;
         response.ClearContent();
     }
 }
示例#11
0
 public void End()
 {
     this.IsClosed = true;
     try
     {
         response.ClearContent();
         response.End();
     }
     catch { }
 }
示例#12
0
 private void AddResponseHeader(HttpResponseBase Response)
 {
     Response.ClearContent();
     Response.Buffer = true;
     Response.AddHeader("content-disposition", "attachment; filename=" + GetExcelName());
     Response.ContentType     = "application/ms-excel";
     Response.Charset         = Encoding.UTF8.EncodingName;
     Response.ContentEncoding = Encoding.Unicode;
     Response.BinaryWrite(Encoding.Unicode.GetPreamble());
 }
示例#13
0
        /// <summary>
        /// 处理ajax请求
        /// </summary>
        /// <param name="filterContext">filterContext</param>
        /// <param name="message">message</param>
        private static void ProcessingAjax(ExceptionContext filterContext, string message)
        {
            filterContext.Result = new JsonResult();
            HttpResponseBase response = filterContext.HttpContext.Response;

            response.ClearContent();
            response.StatusCode = 300;
            response.Write(message);
            response.End();
        }
示例#14
0
        public override void ExecuteResult(ControllerContext context)
        {
            HttpResponseBase response = context.HttpContext.Response;

            try
            {
                response.ClearHeaders();
                response.ClearContent();
            }
            catch { }

            response.TrySkipIisCustomErrors = true;

            if (this.Resource == null)
            {
                response.ContentType = "text/plain";
                response.StatusCode  = (int)HttpStatusCode.NotFound;
                response.Write(response.Status);
                return;
            }

            HttpContext httpContext = HttpContext.Current;

            // check if client has cached copy
            ETag etag = new HashETag(this.Resource.Hash);

            if (etag.HandleETag(httpContext, HttpCacheability.ServerAndPrivate, this.IsDebug))
            {
                return;
            }

            if (String.IsNullOrEmpty(this.Resource.ContentType))
            {
                response.ContentType = "text/plain";
            }
            else
            {
                response.ContentType = this.Resource.ContentType;
            }

            // this helps IE determine the Content-Type
            // http://tools.ietf.org/html/rfc2183#section-2.3
            ContentDisposition disposition = new ContentDisposition
            {
                Inline   = !this.IsAttachment,
                FileName =
                    String.IsNullOrEmpty(this.Filename) ?
                    Path.GetFileNameWithoutExtension(this.ResourcePath) + '.' + this.Resource.FileExtension :
                    this.Filename
            };

            response.AddHeader("Content-Disposition", disposition.ToString());

            ResourceHandler.WriteResponse(httpContext, this.Resource, this.IsDebug);
        }
示例#15
0
        public static void Export(string type, HttpResponseBase Response, List <object> data, string filename)
        {
            Response.ClearContent();
            Response.Buffer = true;

            var grid = new GridView();

            grid.DataSource = data;
            grid.DataBind();

            Response.ClearContent();
            Response.Buffer  = true;
            Response.Charset = "";
            StringWriter   sw  = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            grid.RenderControl(htw);

            switch (type)
            {
            case "EXCEL":
                Response.AddHeader("content-disposition", "attachment; filename=Export.xls");
                Response.ContentType = "application/ms-excel";
                Response.Output.Write("<table><tr><td colspan='13' align='center' style='font-size:20px; color: black'><b>GOVERNMENT OF TELANGANA</b></td></tr><tr><td colspan='13' align='center' style='font-size:20px'><b>Growth Monitoring System</b></td></tr><tr><td colspan='13' align='center'><b>" + filename + "</b></td></tr><tr><td colspan='7'></td><td colspan='6' align='right'>Report Generated Time: " + System.DateTime.Now.Day + "-" + System.DateTime.Now.Month + "-" + System.DateTime.Now.Year + " " + System.DateTime.Now.Hour + ":" + System.DateTime.Now.Minute + "</td></tr></table>" + sw.ToString());
                //Response.Output.Write(sw.ToString());
                break;

            case "PDF":
                Response.ClearContent();
                Response.Buffer  = true;
                Response.Charset = "";
                Response.AddHeader("content-disposition", "attachment; filename=" + filename + ".pdf");
                Response.ContentType = "application/pdf";
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.BinaryWrite(FileExport.CreatePDF(data, filename));
                Response.Flush();
                Response.End();
                break;
            }
            Response.Flush();
            Response.End();
        }
示例#16
0
        public void End()
        {
            this.IsClosed = true;
            try
            {
                FlushBufferIfAny();

                response.ClearContent();
                response.End();
            }
            catch { }
        }
示例#17
0
        private void MakeExcel(System.Data.DataTable data)
        {
            string   FileName = "report" + DateTime.Today.ToShortDateString();
            FileInfo f        = new FileInfo(Server.MapPath("Downloads") + string.Format("\\{0}.xlsx", FileName));

            if (f.Exists)
            {
                f.Delete();
            }
            // delete the file if it already exist.

            HttpResponseBase response = HttpContext.Response;

            response.Clear();
            response.ClearHeaders();
            response.ClearContent();
            response.Charset = Encoding.UTF8.WebName;
            response.AddHeader("content-disposition", "attachment; filename=" + FileName + ".xls");
            response.AddHeader("Content-Type", "application/Excel");
            response.ContentType = "application/vnd.xlsx";
            //response.AddHeader("Content-Length", file.Length.ToString());
            //sets the table border, cell spacing, border color, font of the text, background, foreground, font height
            response.Write("<Table border='1' bgColor='#ffffff' " +
                           "borderColor='#000000' cellSpacing='0' cellPadding='0' " +
                           "style='font-size:10.0pt; font-family:Calibri; background:white;'> <TR>");


            // create a string writer
            using (StringWriter sw = new StringWriter())
            {
                using (HtmlTextWriter htw = new HtmlTextWriter(sw))
                {
                    // instantiate a datagrid
                    DataGrid dg = new DataGrid();
                    dg.DataSource = data;
                    dg.DataBind();
                    dg.RenderControl(htw);
                    response.Write(sw.ToString());
                    dg.Dispose();
                    data.Dispose();
                    response.SetCookie(new HttpCookie("fileDownload", "true")
                    {
                        Path = "/"
                    });
                    //response.Redirect("ReportPage");
                    response.End();
                }
            }
        }
示例#18
0
        public static Tuple <Stream, string, string> GetExportPdf <T>(List <T> result, HttpServerUtilityBase server, HttpResponseBase response)
        {
            ReportDocument rd   = new ReportDocument();
            string         name = typeof(T).Name;

            rd.Load(Path.Combine(server.MapPath("~/Reports"), name + "Report.rpt"));
            rd.SetDataSource(result);
            response.Buffer = false;
            response.ClearContent();
            response.ClearHeaders();
            Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);

            stream.Seek(0, SeekOrigin.Begin);
            return(new Tuple <Stream, string, string>(stream, "application/pdf", name + "Report.pdf"));
        }
示例#19
0
 private static void WriteCsvFile(HttpResponseBase Response, StringBuilder sb, string sExportedFileName)
 {
     Response.Clear();
     Response.ClearContent();
     Response.ClearHeaders();
     Response.Buffer      = true;
     Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
     Response.AddHeader("content-disposition",
                        "attachment;filename=" + sExportedFileName + ".csv");
     // Response.ContentType = "application/text";
     Response.ContentEncoding = Encoding.GetEncoding("windows-1256");
     Response.Output.Write(sb.ToString());
     Response.Flush();
     Response.End();
 }
示例#20
0
        /// <summary>
        /// 以文件形式响应
        /// </summary>
        /// <param name="resp"></param>
        /// <param name="localfile">需要下载的文件</param>
        public static void DoResponseFile(HttpResponseBase resp, string localfile)
        {
            try
            {
                using (FileStream fs = System.IO.File.OpenRead(localfile))
                {
                    resp.ClearContent();
                    resp.ContentType = "text/plain";
                    resp.Headers.Add("Transfer-Encoding", "chunked");
                    var bts = new byte[4096];
                    using (BinaryReader br = new BinaryReader(fs, Encoding.UTF8))
                    {
                        int n;
                        while ((n = br.Read(bts, 0, bts.Length)) > 0)
                        {
                            var bbss = Encoding.UTF8.GetBytes(n.ToString("x") + "\r\n");
                            resp.OutputStream.Write(bbss, 0, bbss.Length);
                            resp.OutputStream.Write(bts, 0, n);
                            resp.OutputStream.Write(new byte[] { 13, 10 }, 0, 2);
                            resp.Flush();

                            Thread.Sleep(100);
                        }

                        var bbss2 = Encoding.UTF8.GetBytes("0\r\n\r\n");
                        resp.OutputStream.Write(bbss2, 0, bbss2.Length);
                    }
                }
            }
            catch (Exception ex)
            {
                resp.ClearContent();
                resp.Write(ex);
            }
            resp.End();
        }
示例#21
0
            public void ToExcel(HttpResponseBase Response, object clientsList)
            {   //Hint: https://stackoverflow.com/questions/16346227/export-data-to-excel-file-with-asp-net-mvc-4-c-sharp-is-rendering-into-view
                var grid = new System.Web.UI.WebControls.GridView();

                grid.DataSource = clientsList;
                grid.DataBind();
                Response.ClearContent();
                Response.AddHeader("content-disposition", "attachment; filename=FileName.xls"); //seteamos las cabeceras como pieichpi
                Response.ContentType = "application/excel";
                StringWriter   sw  = new StringWriter();
                HtmlTextWriter htw = new HtmlTextWriter(sw);

                grid.RenderControl(htw);
                Response.Write(sw.ToString());
                Response.End();
            }
示例#22
0
        public void ToExcel(HttpResponseBase Response, object clientsList)
        {
            var grid = new System.Web.UI.WebControls.GridView();

            grid.DataSource = clientsList;
            grid.DataBind();
            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");
            Response.ContentType = "application/excel";
            StringWriter   sw  = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            grid.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();
        }
示例#23
0
 public static void BaixarArquivo(string nomeArquivo, byte[] arquivo, HttpResponseBase response, HttpServerUtilityBase server)
 {
     try
     {
         response.ClearContent();
         response.ContentType = DefinirContextDownloadArquivo(nomeArquivo);
         String Header = "attachment; filename=" + nomeArquivo;
         response.AppendHeader("Content-Disposition", Header);
         response.BinaryWrite(arquivo);
         response.Flush();
         response.End();
     }
     catch
     {
         throw new Exception("ERRO: 2200. </br>" + " NÃO FOI POSSÍVEL FAZER O DOWNLOAD DO ARQUIVO, TENTE NOVAMENTE MAIS TARDE.");
     }
 }
示例#24
0
        public void ToExcel(HttpResponseBase Response, List <IExportable> lista)
        {
            var       grid = new GridView();
            DataTable dt   = ToDataTable(lista);

            grid.DataSource = dt;
            grid.DataBind();
            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");
            Response.ContentType = "application/excel";
            StringWriter   sw  = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            grid.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();
        }
示例#25
0
        /// <summary>
        /// Stuffs current response from a HttpWebResponse object.
        /// </summary>
        /// <param name="web"></param>
        /// <param name="response"></param>
        public static void StuffFromHttpWebResponse(this HttpResponseBase web, HttpWebResponse response)
        {
            foreach (string name in response.Headers)
            {
                web.AppendHeader(name, response.Headers[name]);
            }

            web.ContentType = response.ContentType;
            web.Charset     = response.CharacterSet;
            if (!string.IsNullOrWhiteSpace(response.CharacterSet))
            {
                Encoding encoding = Encoding.GetEncoding(response.CharacterSet);
                web.ContentEncoding = encoding;
                web.HeaderEncoding  = encoding;
            }
            web.StatusCode        = (int)response.StatusCode;
            web.StatusDescription = response.StatusDescription;

            web.ClearContent();
            if (!string.IsNullOrWhiteSpace(response.Headers["Transfer-Encoding"]) || response.ContentLength < 0)
            {
                int    count  = 0;
                byte[] buffer = new byte[1024 * 1024];
                using (Stream reader = response.GetResponseStream()) {
                    using (Stream writer = web.OutputStream) {
                        while ((count = reader.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            writer.Write(buffer, 0, count);
                        }
                    }
                }
            }
            else
            {
                byte[] data = new byte[response.ContentLength];
                using (Stream reader = response.GetResponseStream()) {
                    reader.Read(data, 0, data.Length);
                }
                using (Stream writer = web.OutputStream) {
                    writer.Write(data, 0, data.Length);
                }
            }

            web.Flush();
        }
示例#26
0
    public static void RedirectToDownload(string filepath, string contentType, HttpResponseBase response)
    {
        FileInfo file = new FileInfo(filepath);

        if (file.Exists)
        {
            response.ClearContent();
            response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
            response.AddHeader("Content-Length", file.Length.ToString());
            response.ContentType = contentType;
            response.TransmitFile(file.FullName);
            response.End();
        }
        else
        {
            throw new FileNotFoundException();
        }
    }
示例#27
0
/// <summary>
/// 生成位图,输出到响应流
/// </summary>
/// <param name="Response"></param>
/// <param name="Code"></param>
        public static void GetCode(HttpResponseBase Response, out string Code)
        {
            Code = string.Empty;
            Bitmap bit = GetCode(out Code);

            ////清除该页输出缓存,设置该页无缓存
            //Response.Buffer = true;
            //Response.ExpiresAbsolute = DateTime.Now.AddMilliseconds(0);
            //Response.Expires = 0;
            //Response.CacheControl = "no-cache";
            //Response.AppendHeader("Pragma", "No-Cache");

            Response.ClearContent();
            bit.Save(Response.OutputStream, ImageFormat.Png);
            Response.ContentType = "image/png";

            //释放资源
            bit.Dispose();
        }
示例#28
0
    public static void WriteResponse(HttpResponseBase response, byte[] filearray, string type, string fileName)
    {
        response.ClearContent();
        response.Buffer = true;
        response.Cache.SetCacheability(HttpCacheability.Private);
        response.ContentType = "application/pdf";
        ContentDisposition contentDisposition = new ContentDisposition();

        contentDisposition.FileName        = fileName;
        contentDisposition.DispositionType = type;
        response.AddHeader("Content-Disposition", contentDisposition.ToString());
        response.BinaryWrite(filearray);
        HttpContext.Current.ApplicationInstance.CompleteRequest();
        try {
            response.End();
        }
        catch (System.Threading.ThreadAbortException) {
        }
    }
示例#29
0
    public static void SetConditionalGetHeaders(DateTime lastModified, HttpContextBase context)
    {
        HttpResponseBase response = context.Response;
        HttpRequestBase  request  = context.Request;

        lastModified = new DateTime(lastModified.Year, lastModified.Month, lastModified.Day, lastModified.Hour, lastModified.Minute, lastModified.Second);

        string incomingDate = request.Headers["If-Modified-Since"];

        response.Cache.SetLastModified(lastModified);

        DateTime testDate = DateTime.MinValue;

        if (DateTime.TryParse(incomingDate, out testDate) && testDate == lastModified)
        {
            response.ClearContent();
            response.StatusCode      = (int)System.Net.HttpStatusCode.NotModified;
            response.SuppressContent = true;
        }
    }
        /// <summary>
        /// 没有权限处理结果
        /// </summary>
        /// <param name="filterContext">当前上下文</param>
        public static void ProcessingResults(ActionExecutingContext filterContext)
        {
            var request = filterContext.HttpContext.Request;

            if (request != null && request.IsAjaxRequest())
            {
                HttpResponseBase response = filterContext.HttpContext.Response;
                response.ClearContent();
                response.StatusCode  = 300;
                filterContext.Result = new JsonResult {
                    Data = new { Type = "Unauthorized" }
                };
            }
            else
            {
                filterContext.Result = new ViewResult {
                    ViewName = "WithoutPermission", ViewData = new ViewDataDictionary("无菜单权限,无权访问")
                };
            }
        }