public void Sys_UpdateApplication() { ConfigInfo entity = GetConfigByID(1); if (entity == null) { pub.Msg("error", "错误信息", "系统配置记录不存在", true, "/index.aspx"); Response.End(); } else { Application["Sys_Config_ID"] = entity.Sys_Config_ID; Application["Upload_Server_URL"] = entity.Upload_Server_URL; Application["Upload_Server_Return_WWW"] = entity.Upload_Server_Return_WWW; Application["Upload_Server_Return_Admin"] = entity.Upload_Server_Return_Admin; Application["Language_Define"] = entity.Language_Define; Application["Site_Name"] = entity.Site_Name; Application["Site_URL"] = entity.Site_URL; Application["Site_Logo"] = entity.Site_Logo; Application["Site_Tel"] = entity.Site_Tel; Application["Site_Fax"] = entity.Site_Fax; Application["Site_Email"] = entity.Site_Email; Application["Site_Keyword"] = entity.Site_Keyword; Application["Site_Description"] = entity.Site_Description; Application["Site_Title"] = entity.Site_Title; Application["Mail_Server"] = entity.Mail_Server; Application["Mail_ServerPort"] = entity.Mail_ServerPort; Application["Mail_EnableSsl"] = entity.Mail_EnableSsl; Application["Mail_ServerUserName"] = entity.Mail_ServerUserName; Application["Mail_ServerPassWord"] = entity.Mail_ServerPassWord; Application["Mail_FromName"] = entity.Mail_FromName; Application["Mail_From"] = entity.Mail_From; Application["Mail_Replyto"] = entity.Mail_Replyto; Application["Mail_Encode"] = entity.Mail_Encode; Application["Coin_Name"] = entity.Coin_Name; Application["Coin_Rate"] = entity.Coin_Rate; Application["Sys_Config_Site"] = entity.Sys_Config_Site; Application["Trade_Contract_IsActive"] = entity.Trade_Contract_IsActive; Application["Static_IsEnable"] = entity.Static_IsEnable; Application["Chinabank_Code"] = entity.Chinabank_Code; Application["Chinabank_Key"] = entity.Chinabank_Key; Application["Alipay_Email"] = entity.Alipay_Email; Application["Alipay_Code"] = entity.Alipay_Code; Application["Alipay_Key"] = entity.Alipay_Key; Application["Tenpay_Code"] = entity.Tenpay_Code; Application["Tenpay_Key"] = entity.Tenpay_Key; Application["CreditPayment_Code"] = entity.CreditPayment_Code; Application["RepidBuy_IsEnable"] = entity.RepidBuy_IsEnable; Application["Coupon_UsedAmount"] = entity.Coupon_UsedAmount; Application["Sys_Sensitive_Keyword"] = entity.Sys_Sensitive_Keyword; Application["Shop_Second_Domain"] = entity.Shop_Second_Domain; Application["Keyword_Adv_MinPrice"] = entity.Keyword_Adv_MinPrice; Application["Sys_Delivery_Code"] = entity.Sys_Delivery_Code; Application["Instant_GoldPrice"] = entity.Instant_GoldPrice; Application["Instant_SilverPrice"] = entity.Instant_SilverPrice; } }
public void Sys_UpdateApplication() { ConfigInfo entity = GetConfigByID(1); if (entity == null) { Public.Msg("error", "错误信息", "记录不存在", false, "{back}"); Response.End(); } else { Application["Sys_Config_ID"] = entity.Sys_Config_ID; Application["Upload_Server_URL"] = entity.Upload_Server_URL; Application["Upload_Server_Return_WWW"] = entity.Upload_Server_Return_WWW; Application["Upload_Server_Return_Admin"] = entity.Upload_Server_Return_Admin; Application["Upload_Server_Return_Supplier"] = entity.Upload_Server_Return_Supplier; Application["Language_Define"] = entity.Language_Define; Application["Site_DomainName"] = entity.Site_DomainName; Application["Site_Name"] = entity.Site_Name; Application["Site_URL"] = entity.Site_URL; Application["Site_Logo"] = entity.Site_Logo; Application["Site_Tel"] = entity.Site_Tel; Application["Site_Fax"] = entity.Site_Fax; Application["Site_Email"] = entity.Site_Email; Application["Site_Keyword"] = entity.Site_Keyword; Application["Site_Description"] = entity.Site_Description; Application["Site_Title"] = entity.Site_Title; Application["Mail_Server"] = entity.Mail_Server; Application["Mail_ServerPort"] = entity.Mail_ServerPort; Application["Mail_EnableSsl"] = entity.Mail_EnableSsl; Application["Mail_ServerUserName"] = entity.Mail_ServerUserName; Application["Mail_ServerPassWord"] = entity.Mail_ServerPassWord; Application["Mail_FromName"] = entity.Mail_FromName; Application["Mail_From"] = entity.Mail_From; Application["Mail_Replyto"] = entity.Mail_Replyto; Application["Mail_Encode"] = entity.Mail_Encode; Application["Coin_Name"] = entity.Coin_Name; Application["Coin_Rate"] = entity.Coin_Rate; Application["Trade_Contract_IsActive"] = entity.Trade_Contract_IsActive; Application["Sys_Config_Site"] = entity.Sys_Config_Site; Application["Alipay_Email"] = entity.Alipay_Email; Application["Alipay_Code"] = entity.Alipay_Code; Application["Alipay_Key"] = entity.Alipay_Key; Application["Tenpay_Code"] = entity.Tenpay_Code; Application["Tenpay_Key"] = entity.Tenpay_Key; Application["Sys_Sensitive_Keyword"] = entity.Sys_Sensitive_Keyword; Application["Shop_Second_Domain"] = entity.Shop_Second_Domain; Application["Keyword_Adv_MinPrice"] = entity.Keyword_Adv_MinPrice; Application["Instant_GoldPrice"] = entity.Instant_GoldPrice; Application["Instant_SilverPrice"] = entity.Instant_SilverPrice; } }
/// <summary>NoRight /// </summary> /// <param name="request"></param> /// <param name="respond"></param> public static void ResponseNoRight(HttpRequest request, HttpResponse respond) { if (IsAjax(request)) { respond.Write(ResponseCodeEntity.NoRight); respond.End(); } else { respond.Redirect(ResponseCodeEntity.NoRightURL);//需要改成非调转形式 respond.End(); } }
/// <summary>URL404 /// </summary> /// <param name="request"></param> /// <param name="respond"></param> public static void ResponseNotfound(HttpRequest request, HttpResponse respond) { if (IsAjax(request)) { respond.Write(ResponseCodeEntity.CODE404); respond.End(); } else { respond.Redirect(ResponseCodeEntity.ULR404); respond.End(); } }
protected void Page_Load(object sender, EventArgs e) { HtmlToPdf.Options.PageSize = PdfPageSizes.A4;// new SizeF(PdfPageSizes.A4.Height, PdfPageSizes.A4.Width); HtmlToPdf.Options.OutputArea = new RectangleF(0.05f, 0.07f, 8.17f, 12f); MemoryStream ms = new MemoryStream(); string fileName = "ANGLO-EASTERN SHIP MANAGEMENT"; var watch = System.Diagnostics.Stopwatch.StartNew(); HtmlToPdf.ConvertUrl("D:\\" + fileName + ".html", ms); watch.Stop(); //HtmlToPdf.ConvertUrl("D:\\HtmlContentForPdf.html", "D:\\result.pdf"); byte[] bPDFBytes = ms.ToArray(); var timeTakenToConvert = watch.ElapsedMilliseconds; System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.Clear(); response.AddHeader("Content-Type", "application/pdf"); response.AddHeader("Content-Disposition", "attachment; filename=Eo_" + fileName + "_" + timeTakenToConvert + ".pdf; size=" + bPDFBytes.Length.ToString()); response.Flush(); response.BinaryWrite(bPDFBytes); response.Flush(); response.End(); }
/// <summary> /// 导入数据,保存文档 /// </summary> /// <param name="tab"></param> /// <param name="fileName"></param> /// <param name="typeName"></param> /// <param name="styleText"></param> private void TableExport(System.Web.UI.HtmlControls.HtmlGenericControl tab, string fileName, string typeName, bool isFireFox) { System.Web.HttpResponse httpResponse = _InvokePage.Response; httpResponse.Clear(); httpResponse.Buffer = true; httpResponse.Charset = "gb2312";// "GB2312"; //Response.Charset = "UTF-8"; httpResponse.Write("<meta http-equiv=Content-Type content=text/html;charset=gb2312>"); if (isFireFox == true) { fileName = "\"" + fileName + "\""; httpResponse.AppendHeader("Content-Disposition", "attachment;filename=" + fileName); } else { httpResponse.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8).ToString()); } httpResponse.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); httpResponse.ContentType = typeName; _InvokePage.EnableViewState = false; StringWriter tw = new StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw); tab.RenderControl(hw); // httpResponse.Write(styleText); httpResponse.Write(tw.ToString()); httpResponse.End(); }
private void Real(HttpResponse response, HttpRequest request) { if (File.Exists(request.PhysicalPath)) { FileInfo file = new System.IO.FileInfo(request.PhysicalPath); response.Clear(); response.AddHeader("Content-Disposition", "filename=" + file.Name); response.AddHeader("Content-Length", file.Length.ToString()); string fileExtension = file.Extension.ToLower(); switch (fileExtension) { case ".mp3": response.ContentType = "audio/mpeg3"; break; case ".mpeg": response.ContentType = "video/mpeg"; break; case ".jpg": response.ContentType = "image/jpeg"; break; case ".bmp": response.ContentType = "image/bmp"; break; case ".gif": response.ContentType = "image/gif"; break; case ".doc": response.ContentType = "application/msword"; break; case ".css": response.ContentType = "text/css"; break; case ".html": response.ContentType = "text/html"; break; case ".htm": response.ContentType = "text/html"; break; case ".swf": response.ContentType = "application/x-shockwave-flash"; break; case ".exe": response.ContentType = "application/octet-stream"; break; case ".inf": response.ContentType = "application/x-texinfo"; break; default: response.ContentType = "application/octet-stream"; break; } response.WriteFile(file.FullName); response.End(); } else { response.Write("File Not Exists"); } }
private static void SendFileNotFound(HttpResponse response) { response.ClearHeaders(); response.StatusCode = 404; //not found response.StatusDescription = "Not Found"; response.End(); }
public void ExportDataGridToExcel(System.Web.UI.Control ctrl, System.Web.HttpResponse response) { response.Clear(); response.Buffer = true; response.Cache.SetCacheability(HttpCacheability.NoCache); response.ContentType = "application/vnd.ms-excel"; response.AddHeader("content-disposition", "attachment;filename=Flash Report.xls"); response.Charset = ""; this.EnableViewState = false; System.IO.StringWriter oStringWriter = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); //this.ClearControls(ctrl); ctrl.RenderControl(oHtmlTextWriter); // set content type and character set to cope with european chars like the umlaut. response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">" + Environment.NewLine); // add the style props to get the page orientation response.Write(AddExcelStyling()); response.Write("<span style='font-size: 11pt; font-family: Arial; font-weight:bold;'>" + "REPORTE EXCESO DE INVENTARIO" + indicadorTexto + "</span>"); response.Write("<br>"); response.Write("<span style='font-size: 10pt; font-family: Arial;'>" + lblLeyenda.Text + "</span>"); response.Write("<br>"); response.Write("<br>"); response.Write(oStringWriter.ToString()); response.Write("</body>"); response.Write("</html>"); response.End(); }
/// <summary> /// Creates a text version (mostly) of the Diagnostics data that is sent via the HttpResponse to the client. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void btnDumpDiagnostics_Click(object sender, EventArgs e) { System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearHeaders(); response.ClearContent(); response.Clear(); response.ContentType = "text/plain"; response.AddHeader("content-disposition", "attachment; filename=RockDiagnostics-" + System.Environment.MachineName + ".txt"); response.Charset = ""; ResponseWrite("Version:", lRockVersion.Text, response); ResponseWrite("Database:", lDatabase.Text.Replace("<br />", Environment.NewLine.ToString()), response); ResponseWrite("Execution Location:", lExecLocation.Text, response); ResponseWrite("Migrations:", GetLastMigrationData().Replace("<br />", Environment.NewLine.ToString()), response); ResponseWrite("Cache:", lCacheOverview.Text.Replace("<br />", Environment.NewLine.ToString()), response);; ResponseWrite("Routes:", lRoutes.Text.Replace("<br />", Environment.NewLine.ToString()), response); // Last and least... ResponseWrite("Server Variables:", "", response); foreach (string key in Request.ServerVariables) { ResponseWrite(key, Request.ServerVariables[key], response); } response.Flush(); response.End(); }
public string CreateExcelFile(System.Web.HttpResponse Response, DataTable dt, string FileName) { string ans = "Download Fail!!!"; try { GridView gv = new GridView(); gv.DataSource = dt; gv.DataBind(); Response.Clear(); Response.AddHeader("content-disposition", "attachment;filename=" + FileName + ".xls"); Response.ContentType = "application/vnd.ms-excel"; //For xls StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); gv.RenderControl(hw); Response.Output.Write(sw.ToString()); Response.Flush(); Response.End(); ans = "Download Successfully!!!"; } catch (Exception Ex) { ExceptionLogging.SendErrorToText(Ex); } return(ans); }
protected void Page_Load(object sender, EventArgs e) { try { List <EvaluacionEntidades.Empleados> list; if (!string.IsNullOrEmpty(Request.QueryString["idadmin"])) { DateTime?inicio = null; if (!string.IsNullOrEmpty(Request.QueryString["inicio"])) { inicio = DateTime.Parse(Request.QueryString["inicio"]); } DateTime?fin = null; if (!string.IsNullOrEmpty(Request.QueryString["fin"])) { fin = DateTime.Parse(Request.QueryString["fin"]); } int?idSuper = null; if (!string.IsNullOrEmpty(Request.QueryString["supervisorid"])) { idSuper = int.Parse(Request.QueryString["supervisorid"]); } list = EvaluacionBL.EmpleadosBL.GetEmpleadoAdmin(int.Parse(Request.QueryString["idadmin"]), Request.QueryString["pais"], inicio, fin, Request.QueryString["departamento"], Request.QueryString["estado"], idSuper); } else { list = EvaluacionBL.EmpleadosBL.GetEmpleadosSupervisados(int.Parse(Request.QueryString["idSupervisor"])); } if (list != null && list.Count > 0) { System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.Clear(); response.ClearContent(); response.ClearHeaders(); //Tipo de contenido para forzar la descarga response.ContentType = "application/octet-stream"; Response.HeaderEncoding = System.Text.Encoding.Default; response.AddHeader("Content-Disposition", "attachment; filename=" + "EmpleadosDesempeño.xlsx"); System.IO.MemoryStream grilla = Helpers.funcionesGenerales.ConvierteCSVEmpleados(list); // System.Text.Encoding encoding = new System.Text.UTF8Encoding(); // byte[] bufferAux = grilla.ToArray(); // byte[] buffer; //System.Text.Encoding utf8 = new System.Text.UTF8Encoding(); // System.Text.Encoding win1252 = System.Text.Encoding.GetEncoding(1252); // buffer = System.Text.Encoding.Convert(utf8,win1252,bufferAux); //while (mContador < grilla.Length) //{ // buffer[mContador] = Chr grilla.Substring(mContador,1) Strings.Asc(Strings.Mid(pCSV, mContador + 1, 1)); // mContador = mContador + 1; //} //Envia los bytes response.BinaryWrite(grilla.ToArray()); response.End(); } } catch (Exception ex) { } }
private void ExportDivContentToPDF() { System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response; try { // create an API client instance string userName = ConfigurationManager.AppSettings["pdfcrowdUsername"].ToString(); string APIKey = ConfigurationManager.AppSettings["pdfcrowdAPIKey"].ToString(); pdfcrowd.Client client = new pdfcrowd.Client(userName, APIKey); // convert a web page and write the generated PDF to a memory stream MemoryStream Stream = new MemoryStream(); //client.convertURI("http://www.google.com", Stream); // set HTTP response headers Response.Clear(); Response.AddHeader("Content-Type", "application/pdf"); Response.AddHeader("Cache-Control", "max-age=0"); Response.AddHeader("Accept-Ranges", "none"); Response.AddHeader("Content-Disposition", "attachment; filename=TigerReservePdfExport.pdf"); System.IO.StringWriter stringWrite1 = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite1 = new HtmlTextWriter(stringWrite1); MainContent.RenderControl(htmlWrite1); client.convertHtml(stringWrite1.ToString(), Stream); // send the generated PDF Stream.WriteTo(Response.OutputStream); Stream.Close(); Response.Flush(); Response.End(); } catch (pdfcrowd.Error why) { Response.Write(why.ToString()); } }
public void Genratepdf1(string str_Url, string filename) { try { string temp_path = ""; PdfConverter pdfConverter_Transcrpit = new PdfConverter(); string temp1 = ""; pdfConverter_Transcrpit.LicenseKey = "eVJIWUtLWUtZTFdJWUpIV0hLV0BAQEA="; PdfDocumentOptions docopt = new PdfDocumentOptions(); pdfConverter_Transcrpit.PageWidth = 1100; pdfConverter_Transcrpit.PageHeight = 500; byte[] downloadBytes = pdfConverter_Transcrpit.GetPdfFromUrlBytes(str_Url); pdfConverter_Transcrpit.SavePdfFromUrlToFile(str_Url, "D:\\LMS2.0Final\\LMS\\ABN\\pdfs\\test1.pdf"); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.Clear(); response.AddHeader("Content-Type", "binary/octet-stream"); response.AddHeader("Content-Disposition", "attachment; filename=" + filename + ".pdf" + "; size=" + downloadBytes.Length.ToString()); response.Flush(); response.BinaryWrite(downloadBytes); response.Flush(); response.End(); } catch (Exception EX) { //return ""; throw EX; } }
private void Real(HttpResponse response, HttpRequest request) { if (File.Exists(request.PhysicalPath)) { FileInfo file = new System.IO.FileInfo(request.PhysicalPath); response.Clear(); response.AddHeader("Content-Disposition", "filename=" + file.Name); response.AddHeader("Content-Length", file.Length.ToString()); string fileExtension = file.Extension.ToLower(); switch (fileExtension) { case ".jpg": response.ContentType = "image/jpeg"; break; case ".gif": response.ContentType = "image/gif"; break; case ".png": response.ContentType = "image/png"; break; default: response.ContentType = "application/octet-stream"; break; } response.WriteFile(file.FullName); response.End(); } else { response.Write("File Not Exists"); } }
public static void ToExcel(System.Web.UI.WebControls.DataGrid DataGrid2Excel, string FileName, string Title, string Head) { System.IO.StringWriter sw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw); FrontDecorator(hw); if (Title != "") { hw.Write(Title + "<br>"); } if (Head != "") { hw.Write(Head + "<br>"); } DataGrid2Excel.EnableViewState = false; DataGrid2Excel.RenderControl(hw); RearDecorator(hw); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.Clear(); response.Buffer = true; response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-7"); response.ContentType = "application/vnd.ms-excel"; response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls"); response.Charset = "gb2312"; response.Write(sw.ToString()); response.End(); }
public static void ExportToExcel(DataTable dt, string fileName) { System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response; Response.ContentType = "application/csv"; Response.Charset = ""; Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName); Response.ContentEncoding = Encoding.Unicode; Response.BinaryWrite(Encoding.Unicode.GetPreamble()); DataTable dtb = dt; try { StringBuilder sb = new StringBuilder(); //Tạo dòng tiêu để cho bảng tính for (int count = 0; count < dtb.Columns.Count; count++) { if (dtb.Columns[count].ColumnName != null) { sb.Append(dtb.Columns[count].ColumnName); } if (count < dtb.Columns.Count - 1) { sb.Append("\t"); } } Response.Write(sb.ToString() + "\n"); Response.Flush(); //Duyệt từng bản ghi int soDem = 0; while (dtb.Rows.Count >= soDem + 1) { sb = new StringBuilder(); for (int col = 0; col < dtb.Columns.Count - 1; col++) { if (dtb.Rows[soDem][col] != null) { sb.Append(dtb.Rows[soDem][col].ToString().Replace(",", " ")); } sb.Append("\t"); } if (dtb.Rows[soDem][dtb.Columns.Count - 1] != null) { sb.Append(dtb.Rows[soDem][dtb.Columns.Count - 1].ToString().Replace(",", " ")); } Response.Write(sb.ToString() + "\n"); Response.Flush(); soDem = soDem + 1; } } catch (Exception ex) { Response.Write(ex.Message); } dtb.Dispose(); Response.End(); }
public Document GetErrorDocument( Boolean openCloseConnection, Boolean addContentDisposition, String fileName, System.Web.HttpResponse webResponse, System.Web.HttpCookie cookie, DocTemplateVers.Domain.DTO.ServiceExport.DTO_Settings settings, IList <DocTemplateVers.Domain.DTO.ServiceExport.DTO_Signature> Signatures) { if (openCloseConnection) { webResponse.Clear(); } if (cookie != null) { webResponse.AppendCookie(cookie); } if (addContentDisposition || openCloseConnection) { webResponse.AddHeader("Content-Disposition", "attachment; filename=" + HtmlCheckFileName(fileName) + "." + ExportFileType.pdf.ToString()); webResponse.ContentType = "application/pdf"; } Document doc = ExportTo(settings, webResponse.OutputStream, true, Signatures, ""); if (doc != null && openCloseConnection) { webResponse.End(); } return(doc); }
public void ProcessRequest(HttpContext context) { try { //Save a trial user to the database string version = ConfigurationManager.AppSettings["Version"]; if (string.IsNullOrEmpty(version)) { //throw error and return return; } string trialDownloadPath = "~\\Releases\\" + version + "\\Utility\\Downloadables\\Trial\\SimpleSqliteUtility.zip"; //Transmit the files System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "text/plain"; response.AddHeader("Content-Disposition", "attachment; filename=SimpleSqliteUtility.zip;"); response.TransmitFile(trialDownloadPath); response.Flush(); response.End(); } catch (Exception ex) { //Report error in an email } }
protected void btnPDF_Click222(object sender, EventArgs e) { string downloadName = "Report"; byte[] downloadBytes = null; downloadName += ".pdf"; PdfConverter pdfConverter = new PdfConverter(); pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4; pdfConverter.PdfStandardSubset = PdfStandardSubset.Full; pdfConverter.PdfDocumentOptions.AutoSizePdfPage = true; pdfConverter.PdfDocumentOptions.EmbedFonts = true; pdfConverter.PdfDocumentOptions.BottomMargin = 80; pdfConverter.PdfDocumentOptions.TopMargin = 50; string url = string.Format("http://{0}/ExamOnline/ExamPaperStorage/ExamPaperView.aspx?epid=39&isPdf=1", Request.Url.Host); downloadBytes = pdfConverter.GetPdfBytesFromUrl(url); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.Clear(); response.AddHeader("Content-Type", "binary/octet-stream"); response.AddHeader("Content-Disposition", "attachment; filename=" + downloadName + "; size=" + downloadBytes.Length.ToString()); response.Flush(); response.BinaryWrite(downloadBytes); response.Flush(); response.End(); }
/// <summary> /// Datatable数据填充如excel /// </summary> /// <param name="filename">excel文件名</param> /// <param name="dt"> 数据源</param> /// <param name="Response"> response响应</param> /// <param name="headerStr"> 表头标题</param> public static void DataTableToExcel(string filename, DataTable dt, string sheetname, HttpResponse Response, string headerStr) { MemoryStream ms = StreamData(dt, sheetname, headerStr) as MemoryStream; //as MemoryStream as用作转换,此处可以省略 try { Response.Clear(); Response.ContentType = "application/vnd.ms-excel"; Response.ContentEncoding = Encoding.UTF8; Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(filename + ".xls")); Response.AddHeader("content-length", ms.Length.ToString()); Byte[] data = ms.ToArray(); //文件写入采用二进制流的方式。所以此处要转换为字节数组 Response.BinaryWrite(data); } catch { Response.Clear(); Response.ClearHeaders(); Response.Write("<script language=javascript>alert( '导出Excel错误'); </script>"); } Response.Flush(); Response.Close(); Response.End(); ms = null; }
public static void SendPosterToBrowser( PosterBuilder.Builder pb, HttpResponse resp, string posterFilename, PosterBuilder.ImgFormat.SupportedTypes outputFormat) { string filename = BuildFilename(posterFilename, outputFormat); resp.Clear(); // Ensure caching is off naturally resp.CacheControl = "no-cache"; resp.ContentType = PosterBuilder.ImgFormat.ToMimeType(outputFormat); resp.AddHeader("Content-Disposition", "attachment;filename=" + filename); // Call our image with our amendments and have it save to the response so we can send it back Bitmap bmp = pb.Render(); // Have the Poster build our new image and save the result to the outgoing response // ... have to do all this with MemoryStreams as PNG doesn't like being saved directly to HttpResponse.OutputStream // ... may as well do the same for all image types and be consistent using (Bitmap bitmap = pb.Render()) { using (MemoryStream ms = new MemoryStream()) { ImageFormat outFmt = PosterBuilder.ImgFormat.ToImageFormat(outputFormat); bmp.Save(ms, outFmt); ms.WriteTo(resp.OutputStream); } // using ms } // using pb // And of course, clear up after ourselves pb.Dispose(); resp.End(); }
private static void SendNotFoundResponse(string message, HttpResponse httpResponse) { httpResponse.StatusCode = (int) HttpStatusCode.NotFound; httpResponse.ContentType = "text/plain"; httpResponse.Write(message); httpResponse.End(); // This terminates the HTTP processing pipeline }
/// <summary> /// 将DataTable中的数据导出到指定的Excel文件中 /// </summary> /// <param name="page">Web页面对象</param> /// <param name="tab">包含被导出数据的DataTable对象</param> /// <param name="fileName">Excel文件的名称</param> public static bool Export(System.Web.UI.Page page, System.Data.DataTable tab, string fileName) { bool returnvalue = false; System.Web.HttpResponse httpResponse = page.Response; System.Web.UI.WebControls.DataGrid dataGrid = new System.Web.UI.WebControls.DataGrid(); dataGrid.DataSource = tab.DefaultView; dataGrid.AllowPaging = false; dataGrid.HeaderStyle.BackColor = System.Drawing.Color.BurlyWood; dataGrid.HeaderStyle.HorizontalAlign = HorizontalAlign.Center; dataGrid.HeaderStyle.Font.Bold = true; dataGrid.DataBind(); httpResponse.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)); //filename="*.xls"; httpResponse.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); httpResponse.ContentType = "application/ms-excel"; System.IO.StringWriter tw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw); dataGrid.RenderControl(hw); string filePath = System.Web.HttpContext.Current.Server.MapPath("/BasicInfo/temp/") + fileName; System.IO.StreamWriter sw = System.IO.File.CreateText(filePath); sw.Write(tw.ToString()); sw.Close(); sw.Dispose(); returnvalue = DownFile(httpResponse, fileName, filePath); httpResponse.End(); return(returnvalue); }
public void ExportToExcel(DataTable dataTable, HttpResponse response) { // Create a dummy GridView GridView GridView1 = new GridView(); GridView1.AllowPaging = false; GridView1.DataSource = dataTable; GridView1.DataBind(); response.Clear(); response.Buffer = true; response.AddHeader("content-disposition", "attachment;filename=DataTable.xls"); response.Charset = ""; response.ContentType = "application/vnd.ms-excel"; StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); for (int i = 0; (i <= (GridView1.Rows.Count - 1)); i++) { // Apply text style to each Row GridView1.Rows[i].Attributes.Add("class", "textmode"); } GridView1.RenderControl(hw); // style to format numbers to string string style = "<style> .textmode{mso-number-format:\\@;}</style>"; response.Write(style); response.Output.Write(sw.ToString()); response.Flush(); response.End(); }
public void ProcessRequest(HttpContext context) { DBConn oConn = new DBConn(); if (oConn.Open()) { Web oWeb = new Web(); //cProductosContrato oProductosContrato = new cProductosContrato(ref oConn); //oProductosContrato.NumContrato = oWeb.GetData("pCodContrato"); //DataTable dtProdCont = oProductosContrato.GetByExcel(); cRoyaltyContrato oRoyaltyContrato = new cRoyaltyContrato(ref oConn); oRoyaltyContrato.NumContrato = oWeb.GetData("pCodContrato"); DataTable dtProdCont = oRoyaltyContrato.GetByExcel(); oConn.Close(); System.Web.HttpResponse oResponse = System.Web.HttpContext.Current.Response; oResponse.Clear(); oResponse.AddHeader("content-disposition", "attachment;filename=FileName.csv"); oResponse.Charset = ""; oResponse.Cache.SetCacheability(HttpCacheability.NoCache); oResponse.ContentType = "application/vnd.ms-excel"; oResponse.Output.Write(ToCSV(dtProdCont)); oResponse.Flush(); oResponse.End(); } }
// Function : Export_with_XSLT_Web // Arguments : dsExport, sHeaders, sFileds, FormatType, FileName // Purpose : Exports dataset into CSV / Excel format private void Export_with_XSLT_Web(DataSet dsExport, string[] sHeaders, string[] sFileds, ExportFormat FormatType, string FileName) { try { // Appending Headers response.Clear(); response.Buffer = true; if (FormatType == ExportFormat.CSV) { response.ContentType = "text/csv"; response.AppendHeader("content-disposition", "attachment; filename=" + FileName); } else { response.ContentType = "application/vnd.ms-excel"; response.AppendHeader("content-disposition", "attachment; filename=" + FileName); } // XSLT to use for transforming this dataset. MemoryStream stream = new MemoryStream( ); XmlTextWriter writer = new XmlTextWriter(stream, Encoding.Default); CreateStylesheet(writer, sHeaders, sFileds, FormatType); writer.Flush( ); stream.Seek(0, SeekOrigin.Begin); XmlDocument xsl = new XmlDocument(); xsl.Load(stream); //XslTransform xslTran = new XslTransform(); //xslTran.Load(new XmlTextReader(stream), null, null); //System.IO.StringWriter sw = new System.IO.StringWriter(); //xslTran.Transform(xmlDoc, null, sw, null); XmlDataDocument xmlDoc = new XmlDataDocument(dsExport); StringWriter sw = new StringWriter(); XmlTextWriter xtw = new XmlTextWriter(sw); XslCompiledTransform t = new XslCompiledTransform(); t.Load((IXPathNavigable)xsl, null, null); t.Transform((IXPathNavigable)xmlDoc, xtw); //Writeout the Content response.Write(sw.ToString()); sw.Close(); xtw.Close(); writer.Close(); stream.Close(); response.End(); sw.Dispose(); stream.Dispose(); } catch (ThreadAbortException Ex) { string ErrMsg = Ex.Message; } catch (Exception Ex) { throw Ex; } }
/// <summary> /// Pushes the attachment to web response. /// </summary> /// <param name="response">The response.</param> /// <param name="EMailMessageId">The E mail message id.</param> /// <param name="AttachementIndex">The attachement id.</param> public static void PushAttachmentToWebResponse(System.Web.HttpResponse response, int EMailMessageId, int AttachementIndex) { EMailMessageRow row = new EMailMessageRow(EMailMessageId); MemoryStream memStream = new MemoryStream(row.EmlMessage.Length); memStream.Write(row.EmlMessage, 0, row.EmlMessage.Length); memStream.Position = 0; Pop3Message message = new Pop3Message(memStream); AttachmentData entry = GetAttachment(message.MimeEntries, ref AttachementIndex); response.ContentType = entry.ContentType; //response.AddHeader("content-disposition", String.Format("attachment; filename=\"{0}\"", GetFileName(entry))); if (Common.OpenInNewWindow(entry.ContentType)) { response.AddHeader("content-disposition", String.Format("inline; filename=\"{0}\"", entry.FileName)); } else { response.AddHeader("content-disposition", String.Format("attachment; filename=\"{0}\"", entry.FileName)); } response.OutputStream.Write(entry.Data, 0, entry.Data.Length); response.OutputStream.Flush(); response.End(); }
/// <summary> /// Exporta la información a Excel. /// </summary> /// <param name="response">HttpResponse actual.</param> /// <param name="data">Datos a exportar.</param> /// <param name="nombreArchivo">Nombre del archivo Excel</param> public static void ExportToExcelFile(HttpResponse response, DataView data, string nombreArchivo) { var dg = new DataGrid { DataSource = data }; dg.DataBind(); response.Clear(); response.Buffer = true; //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet response.AddHeader("Content-Disposition", "filename=" + nombreArchivo); response.ContentType = "application/vnd.ms-excel"; response.Charset = "UTF-8"; response.ContentEncoding = System.Text.Encoding.Default; var stringWriter = new StringWriter(); var htmlWriter = new HtmlTextWriter(stringWriter); dg.RenderControl(htmlWriter); response.Write(stringWriter.ToString()); //resp.Flush(); try { response.End(); } catch (Exception ex) { ISException.RegisterExcepcion(ex); throw ex; } }
public void ExportTableData(DataTable dt) { System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; string attach = "attachment;filename=" + formName + ".xls"; response.ClearContent(); response.AddHeader("content-disposition", attach); response.ContentType = "application/ms-excel"; response.ContentEncoding = System.Text.Encoding.Unicode; response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble()); if (dt != null) { string tab = ""; foreach (DataColumn dc in dt.Columns) { response.Write(tab + dc.ColumnName); tab = "\t"; } response.Write(System.Environment.NewLine); foreach (DataRow dr in dt.Rows) { tab = ""; for (int i = 0; i < dt.Columns.Count; i++) { response.Write(tab + dr[i].ToString().Replace("\n", " ")); tab = "\t"; } response.Write("\n"); } response.Flush(); response.End(); } }
protected void btnSaoLuuDuLieu_Click(object sender, EventArgs e) { dtSetting dt = new dtSetting(); DataTable db = dt.LayTenDatabase(); DataRow dr = db.Rows[0]; string Name = dr["DatabaseName"].ToString(); string CD = Server.MapPath("~/Uploads/"); string TenFile = DateTime.Now.ToString("ddMMyyyy") + "_" + Name + ".Bak"; data = new dtDuLieu(); //FileInfo newFile = new FileInfo(Server.MapPath("~/Uploads/" + TenFile)); //newFile.Delete(); string[] Files = Directory.GetFiles(Server.MapPath("~/Uploads/")); foreach (string file in Files) { File.Delete(file); } data.SaoLuuCSDL(CD, Name); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "text/plain"; response.AddHeader("Content-Disposition", "attachment; filename=" + TenFile + ";"); response.TransmitFile(Server.MapPath("~/Uploads/" + TenFile)); response.Flush(); response.End(); }
public static void Do302Redirect(HttpResponse response, string targetURL) { response.StatusCode = 0x12e; response.StatusDescription = "302 Moved Permanently"; response.RedirectLocation = targetURL; response.End(); }
public static void WriteJsonResponse(HttpResponse response, object model) { var serializer = new JavaScriptSerializer(); string json = serializer.Serialize(model); response.Write(json); response.End(); }
/// <summary> /// 导出EXCEL(HTML格式的) /// </summary> /// <param name="ds">要导出的DataSet</param> /// <param name="fileName"></param> public static void CreateEXCEL(DataSet ds, string fileName) { System.Web.UI.WebControls.DataGrid dg = new DataGrid(); dg.DataSource = ds; dg.DataBind(); for (int i = 0; i < dg.Items.Count; i++) { for (int j = 0; j < dg.Items[i].Cells.Count; j++) { dg.Items[i].Cells[j].Attributes.Add("style", "vnd.ms-excel.numberformat:@"); } } System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response; Response.Clear(); Response.Buffer = true; Response.Charset = "GB2312"; Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName + ".xls", System.Text.Encoding.UTF8) + ";charset=GB2312"); Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); //设置输出流为简体中文 Response.ContentType = "application/ms-excel"; //设置输出文件类型为excel文件。 System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true); System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad); System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); System.Web.UI.WebControls.DataGrid DG = dg; DG.RenderControl(oHtmlTextWriter); Response.Write(oStringWriter.ToString()); Response.End(); }
public void ProcessRequest(HttpContext context) { Int32 userid = SessionData.UserID; String uploadFileDir = ConfigurationManager.AppSettings["UploadFolderPath"]; System.Web.HttpRequest request = System.Web.HttpContext.Current.Request; string startDate = request.QueryString["startDate"]; string endDate = request.QueryString["endDate"]; string uploadfilepath = MppUtility.GetFilelocation(userid, uploadFileDir, "bulk"); string fileName = ConfigurationManager.AppSettings["filename"]; string fileName1 = fileName.PadRight(29) + MppUtility.DateFormat(Convert.ToDateTime(startDate), 2) + "-" + MppUtility.DateFormat(Convert.ToDateTime(endDate), 2) + ".csv"; string filePath = Path.Combine(uploadfilepath, fileName1); bool test = System.IO.File.Exists(filePath); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; if (System.IO.File.Exists(filePath)) { response.ClearContent(); response.Clear(); byte[] Content = System.IO.File.ReadAllBytes(filePath); response.ContentType = "text/csv"; response.AddHeader("content-disposition", "attachment; filename=" + fileName1 + ".csv"); response.BufferOutput = true; response.Cache.SetCacheability(HttpCacheability.NoCache); response.OutputStream.Write(Content, 0, Content.Length); response.Flush(); response.End(); } else { response.Redirect("ShowStatus.html"); } }
public void Genratepdftext(string text, string fname) { try { string temp_path = ""; PdfConverter pdfConverter_Transcrpit = new PdfConverter(); string temp1 = ""; pdfConverter_Transcrpit.LicenseKey = "eVJIWUtLWUtZTFdJWUpIV0hLV0BAQEA="; byte[] downloadBytes = pdfConverter_Transcrpit.GetPdfBytesFromHtmlString(text); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.Clear(); response.AddHeader("Content-Type", "binary/octet-stream"); response.AddHeader("Content-Disposition", "attachment; filename=" + fname + ".pdf" + "; size=" + downloadBytes.Length.ToString()); response.Flush(); response.BinaryWrite(downloadBytes); response.Flush(); response.End(); } catch (Exception EX) { //return ""; throw EX; } }
private static void DownloadFile(string FileLoc) { FileInfo objFile = new FileInfo(FileLoc); System.Web.HttpResponse objResponse = System.Web.HttpContext.Current.Response; string filename = objFile.Name; if (HttpContext.Current.Request.UserAgent.IndexOf("; MSIE ") > 0) { filename = HttpUtility.UrlEncode(filename); } if (objFile.Exists) { objResponse.ClearContent(); objResponse.ClearHeaders(); objResponse.AppendHeader("Content-Length", objFile.Length.ToString()); objResponse.ContentType = GetContentType(objFile.Extension.Replace(".", "")); if (objResponse.ContentType.Contains("x-shockwave-flash") || objResponse.ContentType.Contains("video")) { objResponse.AddHeader("Content-Disposition", "inline;filename=\"" + filename + "\""); } else { objResponse.AppendHeader("content-disposition", "attachment; filename=\"" + filename + "\""); } WriteFile(objFile.FullName); objResponse.Flush(); objResponse.End(); } }
/// <summary> /// 发送PDF文件回浏览器端 /// </summary> /// <param name="fileName"></param> /// <param name="ms"></param> /// <param name="encoding"></param> public static void SendFile(string fileName, MemoryStream ms, Encoding encoding = null) { fileName = (fileName + "").Replace(" ", ""); encoding = encoding ?? Encoding.UTF8; if (ms != null && !string.IsNullOrEmpty(fileName)) { System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.Clear(); response.Charset = encoding.BodyName;// "utf-8"; if (!HttpContext.Current.Request.UserAgent.Contains("Firefox") && !HttpContext.Current.Request.UserAgent.Contains("Chrome")) { fileName = HttpUtility.UrlEncode(fileName, encoding); } response.AddHeader("Content-Disposition", "attachment;filename=" + fileName); //为了解决打开,导出NPOI生成的xlsx文件时,提示发现不可读取内容。 if (!(fileName + "").ToLower().EndsWith(".xlsx")) { response.AddHeader("Content-Type", "application/octet-stream"); response.BinaryWrite(ms.GetBuffer()); } else { response.BinaryWrite(ms.ToArray()); } ms.Close(); ms = null; response.Flush(); response.End(); } }
public void ExportCSV(System.Web.UI.WebControls.GridView exportGV, System.Web.HttpResponse Response) { string strFileName = "Report" + System.DateTime.Now.Date.ToString("dd") + System.DateTime.Now.AddMonths(0).ToString("MM") + System.DateTime.Now.AddYears(0).ToString("yyyy") + System.DateTime.Now.Millisecond.ToString("0000"); StringBuilder sb = new StringBuilder(); System.Web.UI.WebControls.GridViewRow grHeader = exportGV.HeaderRow; int counter = 0; foreach (System.Web.UI.WebControls.TableCell tc in grHeader.Cells) { sb.Append("\"" + exportGV.Columns[counter].HeaderText.Trim() + "\","); counter++; } sb.AppendLine(); foreach (System.Web.UI.WebControls.GridViewRow gr in exportGV.Rows) { foreach (System.Web.UI.WebControls.TableCell tc in gr.Cells) { sb.Append("\"" + getGridCellText(tc) + "\","); } sb.AppendLine(); } Response.Clear(); Response.ClearHeaders(); Response.ClearContent(); Response.AddHeader("content-disposition", "attachment; filename=Export.csv"); Response.ContentType = "text/csv"; Response.AddHeader("Pragma", "public"); Response.Write(sb.ToString()); Response.End(); }
public void ExportPdf(System.Web.UI.WebControls.GridView exportGV, System.Web.HttpResponse Response, System.Web.UI.HtmlControls.HtmlForm htmlForm) { string strFileName = "PDFReport-" + System.DateTime.Now.Date.ToString("dd") + System.DateTime.Now.AddMonths(0).ToString("MM") + System.DateTime.Now.AddYears(0).ToString("yyyy"); Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "attachment;filename=" + strFileName + ".pdf"); Response.Cache.SetCacheability(HttpCacheability.NoCache); StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); HtmlForm frm = new HtmlForm(); exportGV.Parent.Controls.Add(frm); frm.Attributes["runat"] = "server"; frm.Controls.Add(exportGV); frm.RenderControl(hw); StringReader sr = new StringReader(Regex.Replace(sw.ToString(), "<script.*?</script>", "", RegexOptions.Singleline | RegexOptions.IgnoreCase)); Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f); HTMLWorker htmlparser = new HTMLWorker(pdfDoc); PdfWriter.GetInstance(pdfDoc, Response.OutputStream); pdfDoc.Open(); htmlparser.Parse(sr); pdfDoc.Close(); Response.Write(pdfDoc); Response.End(); }
public ActionResult ExportCSV(string emailList) { string FilePath = Server.MapPath("/App_Data/"); string FileName = "EmailList.csv"; System.IO.File.WriteAllText(FilePath + FileName, emailList); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "text/csv"; response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";"); response.TransmitFile(FilePath + FileName); response.Flush(); System.IO.File.Delete(FilePath + FileName); // Deletes the file on server response.End(); List <string> listOfEmails = emailList.Split(',').ToList(); foreach (var emailName in listOfEmails) { //Takes each email in list and searches for it on the JPStudents table and finds the associated ApplicationUserID. //Then calls the UpdateLatestContact method on each ApplicationUserID. var userId = db.JPStudents.Where(x => x.JPEmail == emailName).First().ApplicationUserId.ToString(); UpdateLatestContact(userId); } return(RedirectToAction("Index")); }
protected void Page_Load(object sender, EventArgs e) { String FileName = null; switch ((string)Session["filetype"]) { case ".txt": FileName = "CompressedText.cmx"; break; case ".JPG": case ".jpg": FileName = "CompressedImage.cmi"; break; case ".cmi": FileName = "ExtractedImage.jpg"; break; case ".cmx": FileName = "ExtractedText.txt"; break; } string fn = Server.MapPath("resources/" + FileName); System.Web.HttpResponse responses = System.Web.HttpContext.Current.Response; responses.ClearContent(); responses.Clear(); responses.ContentType = "text/plain"; responses.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";"); responses.TransmitFile(fn); responses.Flush(); responses.End(); }
public void ExportToCSV(DataTable dataTable, HttpResponse response) { response.Clear(); response.Buffer = true; response.AddHeader("content-disposition", "attachment;filename=DataTable.csv"); response.Charset = ""; response.ContentType = "application/text"; StringBuilder sb = new StringBuilder(); for (int k = 0; k < dataTable.Columns.Count; k++) { //add separator sb.Append(dataTable.Columns[k].ColumnName + ','); } //append new line sb.Append("\r\n"); for (int i = 0; i < dataTable.Rows.Count; i++) { for (int k = 0; k < dataTable.Columns.Count; k++) { //add separator sb.Append(dataTable.Rows[i][k].ToString().Replace(",", ";") + ','); } //append new line sb.Append("\r\n"); } response.Output.Write(sb.ToString()); response.Flush(); response.End(); }
public static void CloseIt(HttpResponse response) { response.Clear(); response.Write("<script type=\"text/javascript\">"); response.Write("window.close();"); response.Write("</script>"); response.End(); }
private static void PermanentRedirect(HttpResponse response, string location) { response.Clear(); response.StatusCode = (int)HttpStatusCode.MovedPermanently; response.StatusDescription = "Moved Permanently"; response.AddHeader("Location", location); response.End(); }
static void RedirectPermanent(HttpResponse response, string destination) { response.Clear(); response.Status = "301 Moved Permanently"; response.AddHeader("Location", destination); response.Flush(); response.End(); }
private static void SendNotModified(HttpResponse response) { response.ClearHeaders(); setCacheHeaders(response); response.StatusCode = 304; // not modified response.StatusDescription = "Not Modified"; response.End(); }
private void CancleFav(HttpRequest Request, HttpResponse Response) { BLL.Tao.Favorite favBll = new BLL.Tao.Favorite(); if (!string.IsNullOrEmpty(Request.Form["id"])) { int _ids = int.Parse(Request.Form["id"].ToString()); if (favBll.Delete(_ids)) { Response.Write("Succ"); Response.End(); } else { Response.Write("Faile"); Response.End(); } } }
/// <summary> /// This method will check for "directive=debug" in the querystring to indicate debugging mode. If we're /// in debugging mode, the error message and stack trace will be written to the page and the response will be ended. /// </summary> /// <param name="response"></param> /// <param name="request"></param> /// <param name="exception"></param> public static void WriteErrorInfo(HttpResponse response, HttpRequest request, Exception exception) { if (IsDebugMode(response, request)) { response.Write("<b>Message:</b> " + exception.Message + "<br /><br />"); response.Write("<b>Stack Trace:</b> " + exception.StackTrace.Replace("\n", "<br />")); response.End(); } }
public static void CheckSession2(System.Web.SessionState.HttpSessionState session, HttpRequest request, HttpResponse response) { if (session["corpadmin.id"] == null) { string templetbase = Functions.GetAppConfigString("TempletFileRootPath", ""); string norightfile = templetbase + "\\noright.png"; CommonBLL.GetStreamFromFile(norightfile, response); response.End(); } }
public static void ToExcel(DataSet dsInput, string filename, HttpResponse response) { var excelXml = GetExcelXml(dsInput, filename); response.Clear(); response.AppendHeader("Content-Type", "application/vnd.ms-excel"); response.AppendHeader("Content-Disposition", "attachment; filename=\"" + HttpContext.Current.Server.UrlEncode(filename) + "\""); response.Write(excelXml); response.Flush(); response.End(); }
public virtual void Export(ContentItem item, ExportOptions options, HttpResponse response) { response.ContentType = GetContentType(); response.AppendHeader("Content-Disposition", "attachment;filename=" + GetExportFilename(item)); using (var output = GetTextWriter(response)) { Export(item, options, output); output.Flush(); } response.End(); }
public void GetImage(HttpResponse reponse, int id) { using (SqlConnection connection = new SqlConnection("Data Source=DESKTOP-5A9RHHB;Initial Catalog=EcommerceSimplifie; Integrated Security=True")) { //try //{ SqlCommand command = new SqlCommand("select Picture.PictureBinary, Picture.MimeType from Picture inner join Product_Picture_Mapping on Picture.Id = Product_Picture_Mapping.PictureId where ProductId = @id and DisplayOrder = 1;"); command.Connection = connection; command.Parameters.Add(new SqlParameter("@id", id)); connection.Open(); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { //type de l'image string typeMime = reader.GetString(1); reponse.ContentType = (string.IsNullOrEmpty(typeMime)) ? "image/jpeg" : typeMime; //mise en cache reponse.Cache.SetCacheability(HttpCacheability.Public); int indexDepart = 0; int tailleBuffer = 1024; long nombreOctets = 0; Byte[] flux = new Byte[1024]; nombreOctets = reader.GetBytes(0, indexDepart, flux, 0, tailleBuffer); while (nombreOctets == tailleBuffer) { reponse.BinaryWrite(flux); reponse.Flush(); indexDepart += tailleBuffer; nombreOctets = reader.GetBytes(0, indexDepart, flux, 0, tailleBuffer); } if (nombreOctets > 0) { reponse.BinaryWrite(flux); reponse.Flush(); } reponse.End(); } //catch(Exception) //{ // throw new Exception("Pas d'image disponible."); //} //} } }
/// <summary> /// Sends the file to the response with content-length header. will check last-writetime for sending modified header /// </summary> /// <param name="Response"></param> /// <param name="file"></param> /// <param name="mimetype"></param> /// <remarks>Works with all types of files, not image specific</remarks> public void SendToResponse(HttpResponse Response, FileInfo file, string mimetype) { Response.ClearHeaders(); setCacheHeaders(Response); //Response.Cache.SetETag("\"999ed196eeb0cc1:9\""); Response.Cache.SetLastModified(file.LastWriteTime); Response.ContentType = mimetype; Response.AppendHeader("Content-Length", file.Length.ToString()); Response.WriteFile(file.FullName); Response.End(); }
public void Process(HttpResponse response) { response.Clear(); response.AppendHeader("Last-Modified", serverFingerprint.LastModifiedTime.ToString("r")); response.AppendHeader("ETag", serverFingerprint.ETag); response.AppendHeader("Cache-Control", "private, max-age=0"); response.ContentType = contentType; response.BinaryWrite(content); response.End(); }
public void SignOut(HttpResponse response, HttpSessionState sessionState) { var user = GetUser(false); Logger.Log.Error(string.Format("User {0} sing out.", user.UserName)); response.Cache.SetCacheability(HttpCacheability.NoCache); response.Cache.SetExpires(DateTime.Now); FormsAuthentication.SignOut(); sessionState.Abandon(); response.Redirect(@"~/Index.aspx"); response.End(); }
private void IsExistCourse(HttpRequest Request, HttpResponse Response) { if (!string.IsNullOrEmpty(Request.Form["courseId"])) { BLL.Tao.CourseModule manage = new BLL.Tao.CourseModule(); int cid = int.Parse(Request.Form["courseId"]); if (manage.Exists(cid)) { Response.Write("Succ"); Response.End(); } else { Response.Write("Faile"); Response.End(); } } else { Response.Write("Faile"); Response.End(); } }
/// <summary> /// Downloads the latex from estimate. /// </summary> /// <param name="projectId">The project id.</param> /// <param name="maxPriority">The max priority.</param> /// <param name="response">The response.</param> public void DownloadLatexFromEstimate(int? projectId , int? maxPriority , HttpResponse response) { response.Clear(); response.AddHeader ("Content-Disposition" , "attachment;filename=estimate.tex"); response.ContentType = "application/x-latex"; response.Write(GetLatexFromEstimate (projectId, maxPriority)); response.Flush(); response.End(); }
public static void ToExcel(HttpResponse Response,DataTable dt , string fileName) { Response.ContentType = "application/csv"; Response.Charset = ""; Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName); Response.ContentEncoding = Encoding.Unicode; Response.BinaryWrite(Encoding.Unicode.GetPreamble()); try { StringBuilder sb = new StringBuilder(); //Add Header for (int count = 0; count < dt.Columns.Count - 1; count++) { if (dt.Columns[count].ColumnName != null) sb.Append(dt.Columns[count].ColumnName); sb.Append("\t"); } Response.Write(sb.ToString() + "\n"); Response.Flush(); //Append Data int index = 0; while (dt.Rows.Count >= index + 1) { sb = new StringBuilder(); for (int col = 0; col < dt.Columns.Count -1; col++) { if (dt.Rows[index][col] != null) //sb.Append(dt.Rows[index][col].ToString().Replace(",", " ")); sb.Append(dt.Rows[index][col].ToString()); sb.Append("\t"); } Response.Write(sb.ToString() + "\n"); Response.Flush(); index = index + 1; } } catch (Exception ex) { Response.Write(ex.Message); } dt.Dispose(); Response.End(); }
public static void DataGridToExcel(HttpResponse myResponse, DataGrid dg, string fileName, int numRowLock) { myResponse.Clear(); myResponse.Buffer = true; myResponse.ContentType = "application/vnd.ms-excel"; myResponse.Charset = ""; myResponse.AddHeader("content-disposition", "attachment;filename=" + fileName + ".xls"); StringWriter writer = new StringWriter(); HtmlTextWriter writer2 = new HtmlTextWriter(writer); dg.HeaderStyle.Height = 30; dg.HeaderStyle.BackColor = Color.LightSlateGray; MassageData(dg); dg.RenderControl(writer2); myResponse.End(); }