public static void ExportGridViewToExcel(string strFileName, DataTable dt, System.Web.HttpResponse response) { System.IO.StringWriter tw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw); System.Web.UI.WebControls.DataGrid dgGrid = new System.Web.UI.WebControls.DataGrid(); dgGrid.DataSource = dt; dgGrid.DataBind(); //Get the HTML for the control. dgGrid.RenderControl(hw); ////Write the HTML back to the browser. ////Response.ContentType = application/vnd.ms-excel; //response.ContentType = "application/vnd.ms-excel"; //response.AppendHeader("Content-Disposition", "attachment; filename=" + strFileName + ".xls"); //response.Write(tw.ToString()); //response.End(); byte[] bytes = System.Text.Encoding.Default.GetBytes(tw.ToString()); // Now that you have all the bytes representing the PDF report, buffer it and send it to the client. response.Buffer = true; response.Clear(); response.ClearContent(); response.ClearHeaders(); response.ContentType = "application/vnd.ms-excel"; response.ContentEncoding = System.Text.Encoding.Unicode; response.AddHeader("content-disposition", "attachment; filename=" + strFileName + ".xls"); response.BinaryWrite(bytes); // create the file response.End(); // send it to the client to download }
public ActionResult Download(ModelFile file) { try { if (ModelState.IsValid) { GenerateFile(file.MaxValue, file.FileAmount); var fileName = "GenerateFile.txt"; System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "text/plain"; response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ";"); response.TransmitFile(Server.MapPath("~/GenerateFile.txt")); response.Flush(); response.End(); } } catch { return(View("Download")); } return(View()); //return null; }
/// <summary> /// Create MS-Report /// </summary> /// <param name="reportPath">string path</param> /// <param name="reportType">PDF,Excel</param> /// <param name="reportName">name of report</param> /// <param name="reportDataSource">Data source report</param> /// <param name="response">HttpResponse</param> public static void ExportMSReport(string reportPath, string reportType, string reportName, ReportDataSource reportDataSource, System.Web.HttpResponse response) { // Variables Warning[] warnings; string[] streamIds; string mimeType = string.Empty; string encoding = string.Empty; string extension = string.Empty; // Setup the report viewer object and get the array of bytes ReportViewer viewer = new ReportViewer(); viewer.ProcessingMode = ProcessingMode.Local; viewer.LocalReport.DataSources.Add(reportDataSource); viewer.LocalReport.ReportPath = reportPath; byte[] bytes = viewer.LocalReport.Render(reportType, null, out mimeType, out encoding, out extension, out streamIds, out warnings); // Now that you have all the bytes representing the PDF report, buffer it and send it to the client. response.Buffer = true; response.Clear(); response.ClearContent(); response.ClearHeaders(); response.ContentType = mimeType; response.ContentEncoding = System.Text.Encoding.UTF8; response.AddHeader("content-disposition", "attachment; filename=" + reportName + "." + extension); response.BinaryWrite(bytes); // create the file response.End(); // send it to the client to download }
public bool ReturnXlsBytes(System.Web.HttpResponse resp, byte[] data, string fileName) { resp.ClearHeaders(); resp.ClearContent(); DialogUtils.SetCookieResponse(resp); resp.HeaderEncoding = System.Text.Encoding.Default; resp.AddHeader("Content-Disposition", "attachment; filename=" + fileName); resp.AddHeader("Content-Length", data.Length.ToString()); resp.ContentType = "application/octet-stream"; resp.Cache.SetCacheability(HttpCacheability.NoCache); /* * resp.BufferOutput = false; * resp.WriteFile(f.FullName); * resp.Flush(); * resp.End(); */ resp.BufferOutput = true; resp.BinaryWrite(data); //resp.End(); return(true); }
/// <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(); }
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(); } }
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 void prepareExcelFile(string name, System.Web.HttpResponse resp) { resp.ClearContent(); resp.ClearHeaders(); resp.AppendHeader("Content-Disposition", "attachment; filename=" + name + "_" + DateTime.Now.ToString("yyyyMMdd") + ".xls"); resp.ContentType = "application/vnd.ms-excel"; }
protected void btnDownloadPKCS12Certificate_Click(object sender, EventArgs e) { try { //***TESTIRANJE***Session["Preuzimanje-softverskog-sertifikata-pkcs12"] = @"\\ca-sajt.ca.posta.rs\c$\inetpub\wwwroot\Posta\Dokumentacija\P12_FOLDER\Sertifikat-PKCS12-4e624421b7dcb6dbdf-05112018.p12"; //String FileName = "Sertifikat-PKCS12-338151188815333c-20180605.p12"; string FileName = @"attachment; filename=""" + Path.GetFileName(Session["Preuzimanje-softverskog-sertifikata-pkcs12"].ToString()) + ""; //String FilePath = @"C:\inetpub\wwwroot\Posta\Dokumentacija\P12_FOLDER\Sertifikat-PKCS12-338151188815333c-20180605.p12"; string FilePath = Utils.ConvertToLocalPath(Session["Preuzimanje-softverskog-sertifikata-pkcs12"].ToString()); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.Buffer = true; response.ContentType = "text/plain"; response.AddHeader("Content-Disposition", FileName); //forse save as dialog in Mozzila an Explorer but no in Chrome response.TransmitFile(FilePath); response.Flush(); } catch (Exception ex) { log.Error("Error while saving .p12 file. " + ex.Message); ScriptManager.RegisterStartupScript(this, GetType(), "erroralertSendSOAP", "erroralertSendSOAP();", true); } finally { HttpContext.Current.Response.End(); } }
private void Descargar(ArrayList arrText) { string fic = Server.MapPath(@"TextFiles/polizavta.txt"); StreamWriter sw = new StreamWriter(fic, false, Encoding.UTF8); if (arrText.Count > 0) { for (int i = 0; i < arrText.Count; i++) { sw.WriteLine(arrText[i].ToString()); } } sw.Close(); //String FileName = "BulkAdd_Instructions.txt"; System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "text/plain"; response.AddHeader("Content-Disposition", "attachment; filename=polizavta.txt;"); response.TransmitFile(fic); response.Flush(); response.End(); }
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(); } }
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")); }
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 } }
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(); }
//defaultfile is under userpath public static void GetImageFromFile(string filename,string defaultfile,HttpResponse response) { if (!File.Exists(filename)) { string userdatapath = Functions.GetAppConfigString("UserDataPath", ""); filename = userdatapath + "\\"+defaultfile; } System.IO.FileStream fs = null; System.IO.MemoryStream ms = null; try { fs = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); fs.Close(); ms = new System.IO.MemoryStream(buffer); response.ClearContent(); response.BinaryWrite(ms.ToArray()); ms.Close(); } finally { fs.Dispose(); ms.Dispose(); } }
/// <summary> /// Create an Excel file, and write it out to a MemoryStream (rather than directly to a file) /// </summary> /// <param name="ds">DataSet containing the data to be written to the Excel.</param> /// <param name="filename">The filename (without a path) to call the new Excel file.</param> /// <param name="Response">HttpResponse of the current page.</param> /// <returns>Either a MemoryStream, or NULL if something goes wrong.</returns> public static bool CreateExcelDocumentAsStream(DataSet ds, string filename, System.Web.HttpResponse Response) { System.IO.MemoryStream stream = new System.IO.MemoryStream(); using (SpreadsheetDocument document = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook, true)) { WriteExcelFile(ds, document); } stream.Flush(); stream.Position = 0; Response.ClearContent(); Response.Clear(); Response.Buffer = true; Response.Charset = ""; // NOTE: If you get an "HttpCacheability does not exist" error on the following line, make sure you have // manually added System.Web to this project's References. Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache); Response.AddHeader("content-disposition", "attachment; filename=" + filename); Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; byte[] data1 = new byte[stream.Length]; stream.Read(data1, 0, data1.Length); stream.Close(); Response.BinaryWrite(data1); Response.Flush(); return(true); }
private int StreamFile(string FilePath, string DownloadAs) { DownloadAs = DownloadAs.Replace(" ", "_"); System.IO.FileInfo objFile = new System.IO.FileInfo(FilePath); if (!objFile.Exists) { return(0); } System.Web.HttpResponse objResponse = System.Web.HttpContext.Current.Response; objResponse.ClearContent(); objResponse.ClearHeaders(); objResponse.AppendHeader("Content-Disposition", "attachment; filename=" + DownloadAs); objResponse.AppendHeader("Content-Length", objFile.Length.ToString()); string strContentType; strContentType = "application/octet-stream"; objResponse.ContentType = strContentType; WriteFile(objFile.FullName); objResponse.Flush(); objResponse.Close(); return(1); }
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"); } }
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(); }
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) { } }
internal void WriteToHttpResponse(HttpResponse httpResponse) { httpResponse.ClearContent(); httpResponse.ClearHeaders(); httpResponse.ContentType = model.ContentType; httpResponse.AddHeader("Content-Disposition", ContentDisposition); WriteToStream(httpResponse.OutputStream); }
//protected void btnCancel_Click(object sender, EventArgs e) //{ // ChangePageMode(Helper.PageMode.New); // ClearPageData(); // EditBox.Visible = false; //} protected void gvYearEnd_RowCommand(object sender, GridViewCommandEventArgs e) { try { if (e.CommandName == "EditRow") { ClearPageData(); GridViewRow selectedRow = gvYearEnd.Rows[Convert.ToInt32(e.CommandArgument)]; selectedRow.Style["background-color"] = "skyblue"; int yearendid = Convert.ToInt32(gvYearEnd.DataKeys[selectedRow.RowIndex]["YearEndID"]); YearEnd objYearEnd = ((List <YearEnd>)Session["YearEndData"]).Where(x => x.YearEndID == yearendid).FirstOrDefault(); Session["SelectedYearEnd"] = objYearEnd; ddlBudgetType.SelectedIndex = -1; ddlBudgetType.Items.FindByText(objYearEnd.BudgetType.ToString()).Selected = true; ddlBudgetYear.SelectedIndex = -1; ddlBudgetYear.Items.FindByValue(objYearEnd.BudgetYear.ToString()).Selected = true; ddlStatus.SelectedIndex = -1; ddlStatus.Items.FindByValue(objYearEnd.Status).Selected = true; ddlStatus.Enabled = (objYearEnd.Status == "A"); ChangePageMode(Helper.PageMode.Edit); EditForm.Visible = true; } else if (e.CommandName == "Download") { GridViewRow selectedRow = gvYearEnd.Rows[Convert.ToInt32(e.CommandArgument)]; int yearendid = Convert.ToInt32(gvYearEnd.DataKeys[selectedRow.RowIndex]["YearEndID"]); YearEnd objYearEnd = ((List <YearEnd>)Session["YearEndData"]).Where(x => x.YearEndID == yearendid).FirstOrDefault(); string FolderPath = WebConfigurationManager.AppSettings["ArchiveFolderPath"]; string FileName = objYearEnd.BudgetYear + "_" + objYearEnd.BudgetType + ".xls"; if (File.Exists(FolderPath + FileName)) { System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "application/vnd.ms-excel"; response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";"); response.TransmitFile(FolderPath + FileName); response.Flush(); response.End(); } else { ((SiteMaster)this.Master).ShowMessage("Failure", "File not found : " + FolderPath + FileName); } } } catch (Exception ex) { ((SiteMaster)this.Master).ShowMessage("Error", "An error occurred", ex, true); } }
protected void btnDownloadFormat_Click(object sender, EventArgs e) { System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "application/excel"; response.AddHeader("Content-Disposition", "attachment; filename=ImportFormatColumn.xlsx"); response.TransmitFile(Server.MapPath("/Upload/ImportFormatColumn.xlsx")); response.Flush(); response.End(); }
public static bool ShowDownloadToolFile(HttpResponse httpResponse, NameValueCollection queryString, CommonUtils.AppSettingKey settingKey, out Exception message) { try { string fileName = queryString["DownloadToolFile"]; if (string.IsNullOrEmpty(fileName)) { message = new Exception("Query string 'DownloadToolFile' missing from url."); return false; } if (!File.Exists(fileName)) { message = new FileNotFoundException(string.Format(@"Failed to find file '{0}'. Please ask your administrator to check whether the folder exists.", fileName)); return false; } httpResponse.Clear(); httpResponse.ClearContent(); //Response.OutputStream.f httpResponse.BufferOutput = true; httpResponse.ContentType = "application/unknown"; httpResponse.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", Path.GetFileName(fileName))); byte[] fileContent = File.ReadAllBytes(fileName); BinaryWriter binaryWriter = new BinaryWriter(httpResponse.OutputStream); binaryWriter.Write(fileContent, 0, fileContent.Length); binaryWriter.Flush(); binaryWriter.Close(); var dirName = Path.GetDirectoryName(fileName); if (dirName != null) { //Delete any files that are older than 1 hour Directory.GetFiles(dirName) .Select(f => new FileInfo(f)) .Where(f => f.CreationTime < DateTime.Now.AddHours(-1)) .ToList() .ForEach(f => f.Delete()); } } catch (Exception ex) { message = ex; return false; } message = null; return true; }
protected void TransmitFile() { System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "text/plain"; response.AddHeader("Content-Disposition", "attachment; filename=" + _fileName + ";"); response.TransmitFile(_filePath); response.Flush(); response.End(); }
//modal ingreso pedidos protected void LinkPlantilla_Click(object sender, EventArgs e) { System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "text/plain"; response.AddHeader("Content-Disposition", "attachment; filename=Plantilla.xls"); response.TransmitFile(Server.MapPath("~/Cliente/Diccionario/Plantillas/Plantilla-DetalledePedido.xls")); response.Flush(); response.End(); }
public static void JsonResponse(HttpResponse response, Action<JsonWriter> writeAction) { response.ClearHeaders(); response.ClearContent(); JsonWriter writer = new JsonWriter(response.Output); writeAction(writer); writer.Flush(); }
public void GetAttachFile(byte[] dataFile, string fileName, System.Web.HttpResponse resPonsding) { resPonsding.ClearContent(); resPonsding.AddHeader("Content-Disposition", "attachment; filename=" + fileName); BinaryWriter bw = new BinaryWriter(resPonsding.OutputStream); bw.Write(dataFile); bw.Close(); resPonsding.ContentType = ReturnExtension(GetExtensionFile(fileName)); resPonsding.End(); }
protected void pdf_Click(object sender, ImageClickEventArgs e) { System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "text/plain"; response.AddHeader("Content-Disposition", "attachment; filename=Invoice " + txtNInvoice.Text + ".pdf;"); response.TransmitFile(Server.MapPath("" + Session["Link"] + "")); response.Flush(); response.End(); }
public void CodeGen() { //产生字符串 string VerifyStr = StrGen(_Length, _SystemType, _CustomTypes); Bitmap Objbitmap = new Bitmap(_ImgW, _ImgH); Graphics objgraphice = Graphics.FromImage(Objbitmap); objgraphice.Clear(_BgColor); //画图片的边框线 objgraphice.DrawRectangle(new Pen(Color.Gray), 0, 0, Objbitmap.Width - 1, Objbitmap.Height - 1); Random random = new Random(); //画图片的干扰线 int x1, x2, y1, y2; for (int i = 0; i < 10; i++) { x1 = random.Next(Objbitmap.Width); x2 = random.Next(Objbitmap.Width); y1 = random.Next(Objbitmap.Height); y2 = random.Next(Objbitmap.Height); objgraphice.DrawLine(new Pen(Color.LimeGreen), x1, y1, x2, y2); } //画图片的前景干扰点 for (int i = 0; i < 300; i++) { int x = random.Next(Objbitmap.Width); int y = random.Next(Objbitmap.Height); Objbitmap.SetPixel(x, y, Color.FromArgb(random.Next())); } //在矩形内绘制字串(字串,字体,画笔颜色,左上x.左上y) Font font = new Font("Courier New", 16, FontStyle.Bold); //字体颜色 SolidBrush fcolor = new SolidBrush(Color.Green); objgraphice.DrawString(VerifyStr, font, fcolor, 3, 3); //需要输出图象信息 要修改http头 Response.ClearContent(); Response.ContentType = "image/gif"; //Display Bitmap Objbitmap.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif); //写入Session Session[_SessionKey] = VerifyStr; }
public void ProcessRequest(HttpContext context) { System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "Application/msword"; response.AddHeader("Content-Disposition", "attachment; filename=" + context.Request.QueryString["FileName"] + ";"); response.TransmitFile(context.Server.MapPath("~/WorkGuides/rtfs/" + context.Request.QueryString["FileName"])); response.Flush(); response.End(); }
public static void XmlResponse(HttpResponse response, Action<XmlTextWriter> writeAction) { response.ClearHeaders(); response.ClearContent(); response.ContentType = "text/xml"; XmlTextWriter writer = new XmlTextWriter(response.Output); writeAction(writer); writer.Flush(); }
protected void btnTai_Click(object sender, EventArgs e) { string filePath = TrangChu.Format(ten); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.AddHeader("Content-Disposition", "attachment; filename=" + filePath + ";"); response.TransmitFile(Server.MapPath("~/Files/" + filePath)); response.Flush(); response.End(); }
/// <summary> /// Export CSV File /// </summary> /// <param name="fileName">Name of file</param> /// <param name="dataSource">Data source report</param> /// <param name="response">HttpResponse</param> public static void ExportCSVFile(string fileName, DataTable dataSource, System.Web.HttpResponse response) { byte[] bytes; if ((dataSource.Rows.Count == 0)) { string text = ""; if (dataSource.Columns.Count != 0) { text = dataSource.Columns[0].ColumnName; for (int i = 1; i < dataSource.Columns.Count; i++) { text = string.Format("{0},{1}", text, dataSource.Columns[i].ColumnName); } } text = string.Format("{0}\r\n", text); bytes = System.Text.Encoding.UTF8.GetBytes(text); } else { string text = dataSource.Columns[0].ColumnName; for (int i = 1; i < dataSource.Columns.Count; i++) { text = string.Format("{0},{1}", text, dataSource.Columns[i].ColumnName); } text = string.Format("{0}", text); for (int i = 0; i < dataSource.Rows.Count; i++) { string txtStr = StripCommaCharArray(dataSource.Rows[i][0].ToString()); for (int j = 1; j < dataSource.Columns.Count; j++) { txtStr = string.Format("{0},{1}", txtStr, ReportUtil.StripAllTagsCharArray(StripCommaCharArray(dataSource.Rows[i][j].ToString()))); } text = string.Format("{0}\r\n{1}", text, txtStr); txtStr = ""; } text = string.Format("{0}\r\n", text); bytes = System.Text.Encoding.UTF8.GetBytes(text); } // Now that you have all the bytes representing the PDF report, buffer it and send it to the client. response.Buffer = true; response.Clear(); response.ClearContent(); response.ClearHeaders(); response.ContentType = "text/csv"; response.ContentEncoding = System.Text.Encoding.UTF8; response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".csv"); response.BinaryWrite(bytes); // create the file response.End(); // send it to the client to download }
protected void DownloadFile(object sender, EventArgs e) { String FilePath = (sender as LinkButton).CommandArgument; //Replace this System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "application/octet-stream"; //response.ContentType = "text/plain"; response.AddHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(FilePath) + ";"); response.TransmitFile(FilePath); response.Flush(); response.End(); }
protected void PrepareContent(ref HttpResponse response) { List<HttpCookie> list = new List<HttpCookie>(response.Cookies.Count); for (int i = 0; i < response.Cookies.Count; i++) { list.Add(response.Cookies[i]); } //response.ClearHeaders(); response.ClearContent(); response.ContentType = "text/html"; for (int j = 0; j < list.Count; j++) { response.AppendCookie(list[j]); } response.Cache.SetCacheability(HttpCacheability.NoCache); }
public static void WriteResponse(HttpResponse response, byte[] filearray, string type) { response.ClearContent(); response.Buffer = true; response.Cache.SetCacheability(HttpCacheability.Private); response.ContentType = "application/pdf"; ContentDisposition contentDisposition = new ContentDisposition(); contentDisposition.FileName = "SaldoDotacao.pdf"; contentDisposition.DispositionType = type; response.AddHeader("Content-Disposition", contentDisposition.ToString()); response.BinaryWrite(filearray); HttpContext.Current.ApplicationInstance.CompleteRequest(); try { response.End(); } catch (System.Threading.ThreadAbortException) { } }
public static void Run() { // ExStart:SendingPdfToBrowser // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdfGenerator_AdvanceFeatures(); // Instantiate Pdf instance by calling its empty constructor Aspose.Pdf.Generator.Pdf pdf1 = new Aspose.Pdf.Generator.Pdf(); MemoryStream stream = new MemoryStream(); HttpResponse Response = new HttpResponse(null); pdf1.Save(stream); Response.Clear(); Response.ClearHeaders(); Response.ClearContent(); Response.Charset = "UTF-8"; Response.AddHeader("Content-Length", stream.Length.ToString()); Response.AddHeader("content-disposition", String.Format("attachment;filename={0}", dataDir + "SendingPdfToBrowser.pdf")); Response.ContentType = "application/pdf"; Response.BinaryWrite(stream.ToArray()); Response.Flush(); Response.End(); // ExEnd:SendingPdfToBrowser }
public void DownloadDocument(HttpResponse Response, int DocumentID, string FileName) { Response.Clear(); Response.ClearContent(); Response.ClearHeaders(); Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName); //Response.BinaryWrite(Global.DALCRM.GetPermitDocument(DocumentID)); }
/// <summary> /// Method to write an array of bytes in chunks to a http response /// </summary> /// <remarks> /// The code was adopted from http://support.microsoft.com/kb/812406/en-us /// </remarks> /// <param name="buffer">The array of bytes</param> /// <param name="response">The response</param> private static void WriteResponseInChunks(byte[] buffer, HttpResponse response) { try { response.ClearContent(); response.ContentType = "image/png"; using (var ms = new MemoryStream(buffer)) { var dataToRead = buffer.Length; while (dataToRead > 0) { if (response.IsClientConnected) { { var tmpBuffer = new byte[ChunkSize]; var length = ms.Read(tmpBuffer, 0, tmpBuffer.Length); response.OutputStream.Write(tmpBuffer, 0, length); response.Flush(); dataToRead -= length; } } else { dataToRead = -1; } } } } catch (Exception ex) { response.ClearContent(); response.ContentType = "text/plain"; response.Write(string.Format("Error : {0}", ex.Message)); response.Write(string.Format("Source : {0}", ex.Message)); response.Write(string.Format("StackTrace: {0}", ex.StackTrace)); } finally { response.End(); } }
public static void HandleUploadControl(HttpRequest Request, HttpResponse Response) { Guid userId = Guid.Empty; try { HttpCookie cookie = Request.Cookies.Get(FormsAuthentication.FormsCookieName); if(cookie != null && cookie.Value != null && cookie.Value.Length > 0) { FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value); if(ticket != null && ticket.Name != null && ticket.Name.Length > 0) userId = new Guid(ticket.Name); } if(userId == Guid.Empty) userId = Principal.MemberIdOrZero; } catch(Exception exc) { Log.LogDebug(exc); } string v = Request["v"]; int version = v!=null&&v.Length>0?int.Parse(v):0; string action = Request["action"]; try { Response.ClearContent(); if(action == "upload") HandleUploadControlUpload(Request, Response, userId); else if(action == "login") HandleUploadControlLogin(Request, Response); else if(action == "updatedetails") HandleDetailsUpdate(Request, Response, userId); else if(action == "userlookup") HandleUserLookup(Request, Response, userId); else if(action == "categorylookup") HandleCategoryLookup(Request, Response, userId); else if(action == "createcategory") HandleCreateCategory(Request, Response, userId); else { BinaryWriter w = new BinaryWriter(Response.OutputStream); w.Write(new byte[8]); } } finally { Response.Flush(); Response.Close(); Response.End(); } }
public static void HandleUserLookup(HttpRequest Request, HttpResponse Response, Guid userId) { try { ClientControlsReader r = new ClientControlsReader(Request.InputStream); Response.ClearContent(); ClientControlsWriter w = new ClientControlsWriter(Response.OutputStream); w.Write(1); string query = Request["userquery"]; //Write result code if(query == null || query.Length == 0) { w.Write(-1); return; } else w.Write(0); query = "%"+query+"%"; ArrayList data = new ArrayList(); using(Db db = new Db()) { db.CommandText = @" SELECT id, fullNameClean as fullName, username, email FROM tMember WHERE fullName LIKE @q OR email LIKE @q OR username LIKE @q ORDER BY fullNameClean ASC "; db.AddParameter("@q", query); while(db.Read()) { UserInfo user = new UserInfo(); user.username = (string)db["username"]; user.id = (Guid)db["id"]; user.email = db["email"] as string; user.name = (string)db["fullName"]; data.Add(user); } } w.Write((int)data.Count); foreach(object o in data) { if(o is UserInfo) { w.Write((byte)0); UserInfo user = (UserInfo)o; w.Write(user.id.ToByteArray()); w.WriteString(user.username); w.WriteString(user.email); w.WriteString(user.name); } } int a = 3; } finally { Response.Flush(); Response.Close(); Response.End(); } }
public static bool ShowFile(HttpResponse httpResponse, NameValueCollection queryString, CommonUtils.AppSettingKey settingKey, out Exception message) { try { string fileName = queryString["file"]; if (string.IsNullOrEmpty(fileName)) { message = new Exception("Query string 'file' missing from url."); return false; } string folderConfig = GetAppSettingValue(settingKey); string folderPath = Path.Combine(folderConfig, fileName); if (!Directory.Exists(folderPath)) { message = new DirectoryNotFoundException(string.Format(@"Failed to find file '{0}' from this location: ({1}). Please ask your administrator to check whether the folder exists.", fileName, folderPath)); return false; } var files = Directory.GetFiles(folderPath); if (files.Any()) { string filePath = files[0]; httpResponse.Clear(); httpResponse.ClearContent(); //Response.OutputStream.f httpResponse.BufferOutput = true; httpResponse.ContentType = "application/unknown"; httpResponse.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", Path.GetFileName(filePath))); byte[] fileContent = File.ReadAllBytes(filePath); BinaryWriter binaryWriter = new BinaryWriter(httpResponse.OutputStream); binaryWriter.Write(fileContent, 0, fileContent.Length); binaryWriter.Flush(); binaryWriter.Close(); //httpResponse.Flush(); } } catch (Exception ex) { message = ex; return false; } message = null; return true; }
public void Methods_Deny_Unrestricted () { HttpResponse response = new HttpResponse (writer); response.AddCacheItemDependencies (new ArrayList ()); response.AddCacheItemDependency (String.Empty); response.AddFileDependencies (new ArrayList ()); response.AddFileDependency (fname); response.AddCacheDependency (new CacheDependency[0]); response.AddCacheItemDependencies (new string [0]); response.AddFileDependencies (new string [0]); try { response.AppendCookie (new HttpCookie ("mono")); } catch (NullReferenceException) { // ms } try { Assert.IsNull (response.ApplyAppPathModifier (null), "ApplyAppPathModifier"); } catch (NullReferenceException) { // ms } try { response.Clear (); } catch (NullReferenceException) { // ms } try { response.ClearContent (); } catch (NullReferenceException) { // ms } try { response.ClearHeaders (); } catch (NullReferenceException) { // ms } try { response.Redirect ("http://www.mono-project.com"); } catch (NullReferenceException) { // ms } try { response.Redirect ("http://www.mono-project.com", false); } catch (NullReferenceException) { // ms } try { response.SetCookie (new HttpCookie ("mono")); } catch (NullReferenceException) { // ms } response.Write (String.Empty); response.Write (Char.MinValue); response.Write (new char[0], 0, 0); response.Write (this); response.WriteSubstitution (new HttpResponseSubstitutionCallback (Callback)); response.Flush (); response.Close (); try { response.End (); } catch (NullReferenceException) { // ms } }
protected virtual void PrepareContent(ref HttpResponse response) { List<HttpCookie> cookies = new List<HttpCookie>(response.Cookies.Count); for (int i = 0; i < response.Cookies.Count; i++) cookies.Add(response.Cookies[i]); response.ClearHeaders(); response.ClearContent(); response.ContentType = "text/html"; for (int i = 0; i < cookies.Count; i++) response.AppendCookie(cookies[i]); response.Cache.SetCacheability(HttpCacheability.NoCache); }
//private SvgDocument CreateSvgDocument() //{ // SvgDocument svgDoc; // XmlDocument xml = new XmlDocument(); // xml.LoadXml(this.Svg); // XmlNodeList nodeListAllg = xml.GetElementsByTagName("g"); // Dictionary<int, XmlNode[,]> dic = new Dictionary<int, XmlNode[,]>(); // int i = 0; // foreach (XmlNode xNod in nodeListAllg) // { // i++; // XmlNode xmlvisibility = xNod.Attributes.GetNamedItem("class"); // if (xmlvisibility != null && xmlvisibility.Value == "highcharts-series-group") // { // foreach (XmlNode xNod2 in xNod.ChildNodes) // { // i++; // XmlNode xmlvisibility1 = xNod2.Attributes.GetNamedItem("visibility"); // if (xmlvisibility1 != null && xmlvisibility1.Value == "hidden") // { // XmlNode[,] xmln = new XmlNode[1, 2]; // xmln[0, 0] = xNod; // xmln[0, 1] = xNod2; // dic.Add(i, xmln); // } // } // } // else if (xmlvisibility != null && xmlvisibility.Value == "highcharts-tooltip") // { // XmlNode[,] xmln = new XmlNode[1, 2]; // xmln[0, 0] = xml.FirstChild; // xmln[0, 1] = xNod; // dic.Add(i, xmln); // } // } // foreach (KeyValuePair<int, XmlNode[,]> a in dic) // { // a.Value[0, 0].RemoveChild(a.Value[0, 1]); // } // this.Svg = xml.OuterXml; // // Create a MemoryStream from SVG string. // using (MemoryStream streamSvg = new MemoryStream( // Encoding.UTF8.GetBytes(this.Svg))) // { // // Create and return SvgDocument from stream. // svgDoc = SvgDocument.Open(streamSvg); // } // // Scale SVG document to requested width. // svgDoc.Transforms = new SvgTransformCollection(); // float scalar = (float)this.Width / (float)svgDoc.Width; // svgDoc.Transforms.Add(new SvgScale(scalar, scalar)); // svgDoc.Width = new SvgUnit(svgDoc.Width.Type, svgDoc.Width * scalar); // svgDoc.Height = new SvgUnit(svgDoc.Height.Type, svgDoc.Height * scalar); // return svgDoc; //} /// <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(HttpResponse httpResponse) { httpResponse.ClearContent(); httpResponse.ClearHeaders(); httpResponse.ContentType = this.ContentType; httpResponse.AddHeader("Content-Disposition", this.ContentDisposition); WriteToStream(httpResponse.OutputStream); }
private void RenderAction(HttpResponse response, ActionResult result, bool isOther) { bool isSuccess = false; string message = "系统运行出现未知严重错误"; string responseData = string.Empty; if (result != null) { isSuccess = result.IsSuccess; responseData = (result.ResponseData ?? string.Empty).Trim(); if (!isSuccess) { string mess = (result.TipMessage ?? string.Empty).Trim(); message = string.IsNullOrEmpty(mess) ? message : mess; } } StringBuilder output = new StringBuilder(); output.Append(string.Format("{0} = {1};", (isOther) ? "Ssign" : "sign", (isSuccess) ? "true" : "false")); output.Append(responseData); if (!isSuccess) { if (!isOther) output.Append(string.Format("BadInfo = '{0}<br>请重新操作!';", message)); } response.ClearContent(); response.Write(Escape.JsEscape(output.ToString())); response.End(); }
/// <summary> /// Gives a permanent redirect to the browser. /// </summary> /// <param name="response">The response.</param> /// <param name="url">The URL to permanently redirect to.</param> public static void PermanentRedirect(HttpResponse response, string url) { response.ClearContent(); response.ClearHeaders(); response.StatusCode = 301; response.Status = "301 Moved Permanently"; response.RedirectLocation = url; response.End(); }
/// <summary> /// 产生验证图片信息 /// </summary> /// <param name="checkCode"></param> /// <param name="Response"></param> protected void ResponseImage2(string checkCode, HttpResponse Response) { int iwidth = 80;// (int)(checkCode.Length * 25); using (System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 30)) { System.Random rand = new Random(~unchecked((int)DateTime.Now.Ticks)); using (Graphics g = Graphics.FromImage(image)) { g.Clear(Color.White); //定义颜色 Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple, Color.SkyBlue }; //定义字体 string[] font = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体", "Comic Sans MS" }; Color nowColor = c[rand.Next(8)]; //Color.FromArgb(rand.Next()); /* //rand = new Random(~unchecked((int)DateTime.Now.Ticks)); //随机输出噪点 for (int i = 0; i < 50; i++) { int x = rand.Next(image.Width); int y = rand.Next(image.Height); //image.SetPixel(x, y, nowColor); g.DrawPie(new Pen(nowColor, 0), x, y, 2, 2, 1, 1); } */ //rand = new Random(~unchecked((int)DateTime.Now.Ticks)); //输出不同字体和颜色的验证码字符 for (int i = 0; i < checkCode.Length; i++) { int findex = rand.Next(6); Font _font = new System.Drawing.Font(font[findex], 16, System.Drawing.FontStyle.Bold); Brush b = new System.Drawing.SolidBrush(nowColor); g.DrawString(checkCode.Substring(i, 1), _font, b, rand.Next(1, 8) + (i * 14), rand.Next(6)); } /* //rand = new Random(~unchecked((int)DateTime.Now.Ticks)); //画图片的前景噪音点 for (int i = 0; i < 50; i++) { int x = rand.Next(image.Width); int y = rand.Next(image.Height); //image.SetPixel(x, y, Color.FromArgb(rand.Next())); //image.SetPixel(x, y, nowColor); g.DrawPie(new Pen(nowColor, 0), x, y, 2, 2, 1, 1); } */ //画一个边框 //g.DrawRectangle(new Pen(nowColor, 0), 0, 0, image.Width - 1, image.Height - 1); } rand = new Random(~unchecked((int)DateTime.Now.Ticks)); //using (var ximage = TwistImage(image, true, rand.Next(3, 8), rand.Next(1, 4))) //{ System.IO.MemoryStream ms = new System.IO.MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Png); Response.ClearContent(); Response.ContentType = "image/png"; Response.BinaryWrite(ms.ToArray()); //} } }
/// <summary> /// Writes file to response. /// </summary> public void DownloadFile(String path, String localFileName, String originalFileName, String contentType, HttpResponse response) { if (!System.IO.File.Exists(path + localFileName)) { return; } response.ClearContent(); response.ClearHeaders(); response.ContentType = contentType; response.AddHeader("content-disposition", "attachment; filename=" + originalFileName); response.WriteFile(path + localFileName); response.End(); }
private static void WriteError(HttpResponse response) { response.StatusCode = (int)HttpStatusCode.NotFound; response.ClearContent(); }
static void HandleCategoryLookup(HttpRequest Request, HttpResponse Response, Guid userId) { try { Response.ClearContent(); ClientControlsWriter w = new ClientControlsWriter(Response.OutputStream); //Version w.Write((int)1); //ResultCode if(userId == Guid.Empty) { w.Write((int)-1); return; } string categoryName = Request["categoryName"]; if(categoryName == null) categoryName = string.Empty; categoryName = categoryName.Trim(); if(!Validation.ValidateCategoryName(categoryName)) { w.Write((int)-2); return; } w.Write((int)0); // } result code. Database.MemberDetails details = Database.GetMemberDetails(null, userId); Guid existingId = Database.GetSubCategory(userId, details.HomeCategoryId, categoryName); Database.Category cat = null; if(existingId != Guid.Empty) cat = Database.GetCategoryInfo(userId, existingId); w.Write(existingId != Guid.Empty); w.Write(existingId.ToByteArray()); //canAddPermission w.Write(cat != null && cat.CurrentPermission >= Permission.Add); //securityPermission w.Write(cat != null && cat.CurrentPermission >= Permission.Owner); //TODO: shold be securitypermission. w.WriteString(cat != null?cat.Name:categoryName); //can't send email w.Write((byte)0x00); //can't share to friends w.Write((byte)0x00); //Write the permission entries on the category. if(existingId == Guid.Empty) w.Write(0); else { Guid groupId = Database.GetMemberGroup(userId, "$"+existingId); Database.GroupMember[] members = Database.EnumGroupMembers(userId, groupId); w.Write((uint)(members.Length-1)); //minus self foreach(Database.GroupMember member in members) { if(member.MemberId == userId) continue; Database.MemberDetails md = Database.GetMemberDetails(null, member.MemberId); w.Write((byte)0); w.Write(md.Id.ToByteArray()); w.WriteString(md.admin_username); w.WriteString(md.admin_email); w.WriteString(md.Name); w.Write((uint)0); w.Write((uint)0); w.Write((uint)0); w.Write((uint)0); } } } finally { Response.Flush(); Response.Close(); Response.End(); } }
public static void DownLoadFileByByteEX(byte[] buffers, HttpResponse response, string fileName, string filePath) { response.Clear(); response.ClearContent(); response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8)); response.AppendHeader("Content-Length ", buffers.Length.ToString()); response.ContentType = "application/pdf"; response.TransmitFile(filePath); //response.Flush(); //response.End(); }
public static bool DownloadFile(HttpResponse Response, HttpRequest Request, string filePath, string outputFileName, bool responseEnd,bool clearCache) { try { Response.ClearContent(); string fileExtension = Path.GetExtension(outputFileName).ToLower(); switch (fileExtension) { case ".gif": Response.ContentType = "image/gif"; break; case ".swf": case ".flv": Response.ContentType = "application/x-shockwave-flash"; break; case ".rmvb": case ".rm": Response.ContentType = "audio/x-pn-realaudio"; break; case ".mp3": case ".mpeg": case ".mpg": Response.ContentType = "audio/mpeg"; break; case ".wav": Response.ContentType = "audio/x-wav"; break; case ".ra": Response.ContentType = "audio/x-realaudio"; break; case ".avi": Response.ContentType = "video/x-msvideo"; break; case ".mov": Response.ContentType = "video/quicktime"; break; default: Response.ContentType = "application/octet-stream"; break; } // �ļ��� // if (!string.IsNullOrEmpty(outputFileName)) { Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(Encoding.GetEncoding(65001).GetBytes(outputFileName))); } Response.TransmitFile(filePath); if (clearCache) { Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Cache.SetNoStore(); } if (responseEnd) Response.End(); } catch { return false; } return true; }
protected virtual void ExecuteToResponse_ApplyResponseInfo(HttpResponse httpResponse) { // Clear the past content httpResponse.ClearContent(); // set content type httpResponse.ContentType = ResponseInfo.ContentType; if (ApplyContentFileName) ApplyContentFileNameToResponse(httpResponse); // Set response additional headers ApplyHeadersToResponse(httpResponse); // Add content type header httpResponse.AddHeader("Content-Type", ResponseInfo.ContentType); // ASProxy signature in request header if (Configurations.WebData.SendSignature) { httpResponse.AddHeader("X-Powered-By", Consts.BackEndConenction.ASProxyAgentVersion); httpResponse.AddHeader("X-Working-With", Consts.BackEndConenction.ASProxyAgentVersion); } // Set response content type if (ResponseInfo.ContentEncoding != null) { httpResponse.ContentEncoding = ResponseInfo.ContentEncoding; // BUG: This causes "illegal character" in browsers //httpResponse.Charset = ResponseInfo.ContentEncoding.BodyName; } // Write document text if (!string.IsNullOrEmpty(ResponseInfo.HtmlDocType)) httpResponse.Write(ResponseInfo.HtmlDocType); // Write document initialize code if (!string.IsNullOrEmpty(ResponseInfo.ExtraCodesForPage)) httpResponse.Write(ResponseInfo.ExtraCodesForPage); }
public static void HandleUpdate(HttpRequest Request, HttpResponse Response) { ClientControlsReader r = new ClientControlsReader(Request.InputStream); byte[] buffer; FileStream inFile = null; try { Response.ClearContent(); ClientControlsWriter w = new ClientControlsWriter(Response.OutputStream); int updateManagerVersion = int.Parse(Request["updateManagerVersion"]); int controlReleaseVersion = int.Parse(Request["controlReleaseVersion"]); int processorArchitecture = int.Parse(Request["processorArchitecture"]); bool win95 = Request["platform"] == "95"; int winMajor = int.Parse(Request["winmajor"]); int winMinor = int.Parse(Request["winminor"]); string winCsd = Request["winCsd"]; string gdiplusVerString = Request["gdiplusver"].Trim(); bool hasGdiplus = gdiplusVerString != "0.0"; bool adminInstall = bool.Parse(Request["admin"]); bool hasMfc71 = bool.Parse(Request["mfc71"]); string[] files; if(!hasGdiplus) files = new string[] { "gdiplus", "minakortcontrols" }; else files = new string[] { "minakortcontrols" }; //Write version w.Write(updateManagerVersion); //Write response code w.Write(1); //Write response message string message = ""; w.WriteString(message); //Write file count w.Write(files.Length); //Write total file size int totalSize=0; foreach(string file in files) { string filePath = HttpContext.Current.Server.MapPath(Configuration.RootPath+ "public/" + file + ".dll"); totalSize += (int)new FileInfo(filePath).Length; } w.Write(totalSize); //Write files foreach(string file in files) { string clientFileName; if(file == "minakortcontrols") { w.Write((byte)(1)); clientFileName = "minakortcontrols.2.dll"; } else { w.Write((byte)(0)); clientFileName = "gdiplus.dll"; } //Write client file name w.WriteString(clientFileName); string filePath = HttpContext.Current.Server.MapPath(Configuration.RootPath+ "public/" + file + ".dll"); inFile = new FileStream(filePath, FileMode.Open, FileAccess.Read); w.Write((int)inFile.Length); buffer = new byte[inFile.Length]; inFile.Read(buffer,0,buffer.Length); w.Write(buffer); inFile.Close(); inFile = null; } } finally { if(inFile != null) inFile.Close(); Response.Flush(); Response.Close(); Response.End(); } }
private static void HandlePublicBlobRequestWithCacheSupport(HttpContext context, CloudBlob blob, HttpResponse response) { // Set the cache request properties as IIS will include them regardless for now // even when we wouldn't want them on 304 response... response.Cache.SetMaxAge(TimeSpan.FromMinutes(0)); response.Cache.SetCacheability(HttpCacheability.Private); var request = context.Request; blob.FetchAttributes(); string ifNoneMatch = request.Headers["If-None-Match"]; string ifModifiedSince = request.Headers["If-Modified-Since"]; if (ifNoneMatch != null) { if (ifNoneMatch == blob.Properties.ETag) { response.ClearContent(); response.StatusCode = 304; return; } } else if (ifModifiedSince != null) { DateTime ifModifiedSinceValue; if (DateTime.TryParse(ifModifiedSince, out ifModifiedSinceValue)) { ifModifiedSinceValue = ifModifiedSinceValue.ToUniversalTime(); if (blob.Properties.LastModifiedUtc <= ifModifiedSinceValue) { response.ClearContent(); response.StatusCode = 304; return; } } } var fileName = blob.Name.Contains("/MediaContent/") ? request.Path : blob.Name; response.ContentType = StorageSupport.GetMimeType(fileName); //response.Cache.SetETag(blob.Properties.ETag); response.Headers.Add("ETag", blob.Properties.ETag); response.Cache.SetLastModified(blob.Properties.LastModifiedUtc); blob.DownloadToStream(response.OutputStream); }
/// <summary> /// 生成验证图片 /// </summary> /// <param name="response"></param> /// <param name="checkCode">验证字符</param> private static void CreateImages(HttpResponse response, string checkCode) { int iwidth = (int)(checkCode.Length * 16); Bitmap image = new Bitmap(iwidth, 32); Graphics g = Graphics.FromImage(image); g.Clear(Color.White); //定义颜色 Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple }; //定义字体 string[] font = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" }; Random rand = new Random(); //随机输出噪点 for (int i = 0; i < 50; i++) { int x = rand.Next(image.Width); int y = rand.Next(image.Height); g.DrawRectangle(new Pen(Color.LightGray, 0), x, y, 1, 1); } //输出不同字体和颜色的验证码字符 for (int i = 0; i < checkCode.Length; i++) { int cindex = rand.Next(7); int findex = rand.Next(5); Font f = new Font(font[findex], 12, FontStyle.Bold); Brush b = new SolidBrush(c[cindex]); int ii = 4; if ((i + 1) % 2 == 0) { ii = 2; } g.DrawString(checkCode.Substring(i, 1), f, b, 3 + (i * 12), ii); } //画一个边框 g.DrawRectangle(new Pen(Color.Black, 0), 0, 0, image.Width - 1, image.Height - 1); //输出到浏览器 MemoryStream ms = new MemoryStream(); image.Save(ms, ImageFormat.Jpeg); response.ClearContent(); response.ContentType = "image/Jpeg"; response.BinaryWrite(ms.ToArray()); g.Dispose(); image.Dispose(); }