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."); //} //} } }
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 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(); }
/// <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 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(); }
/// <summary> /// Renders a partial view to a string in the specified context. /// </summary> /// <param name="partialViewContext">The partial view context.</param> /// <param name="viewModel">The view model.</param> /// <param name="cookies">Any cookies that were captures as part of the response.</param> /// <returns>The view rendered as a string.</returns> public static string ToString(PartialViewContext partialViewContext, object viewModel, out HttpCookieCollection cookies) { string viewName = partialViewContext.ViewName; using (var writer = new StringWriter()) { var httpRequest = new HttpRequest("", "http://www.example.com", ""); var httpResponse = new HttpResponse(writer); // There are still dependencies on HttpContext.Currrent in the ASP.NET (MVC) framework, eg., AntiForgeryRequestToken (as of ASP.NET MVC 4). var httpContext = new HttpContext(httpRequest, httpResponse) { User = partialViewContext.User }; System.Web.HttpContext.Current = httpContext; var controllerContext = CreateControllerContext(httpContext); var viewEngineResult = ViewEngines.Engines.FindPartialView(controllerContext, viewName); if (viewEngineResult == null) { string message = "The partial view was not found."; throw new ArgumentException(message, viewName); } var view = viewEngineResult.View; if (view == null) { var locations = new StringBuilder(); foreach (string searchedLocation in viewEngineResult.SearchedLocations) { locations.AppendLine(); locations.Append(searchedLocation); } throw new ArgumentException("The partial view was not found. The following locations were searched: " + locations, viewName); } try { var viewData = new ViewDataDictionary(viewModel); var tempData = new TempDataDictionary(); var viewContext = new ViewContextStub(controllerContext, view, viewData, tempData, writer) { ClientValidationEnabled = partialViewContext.ClientValidationEnabled, UnobtrusiveJavaScriptEnabled = partialViewContext.UnobtrusiveJavaScriptEnabled }; view.Render(viewContext, httpResponse.Output); cookies = controllerContext.HttpContext.Response.Cookies; httpResponse.Flush(); } finally { viewEngineResult.ViewEngine.ReleaseView(controllerContext, view); } return writer.ToString(); } }
static void RedirectPermanent(HttpResponse response, string destination) { response.Clear(); response.Status = "301 Moved Permanently"; response.AddHeader("Location", destination); response.Flush(); 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(); }
private static void RenderToResponseStream(HttpResponse response, XmlBaseController baseController) { // save script timeout var scriptTimeOut = HttpContext.Current.Server.ScriptTimeout; // temporarily set script timeout to large value ( this value is only applicable when application is not running in Debug mode ) HttpContext.Current.Server.ScriptTimeout = int.MaxValue; response.ContentType = baseController.ContentType; response.AppendHeader("content-disposition", "inline; filename=" + baseController.FileName); baseController.Render(response.OutputStream); response.Flush(); // reset script timeout HttpContext.Current.Server.ScriptTimeout = scriptTimeOut; }
/// <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(); }
/// <summary> /// Renders a partial view to a string in the specified context. /// </summary> /// <param name="crowbarViewContext">The view context.</param> /// <param name="viewModel">The view model.</param> /// <param name="cookies">Any cookies that were captures as part of the response.</param> /// <returns>The view rendered as a string.</returns> public static string ToString(CrowbarViewContext crowbarViewContext, object viewModel, out HttpCookieCollection cookies) { string viewName = crowbarViewContext.ViewName; using (var writer = new StringWriter()) { var httpRequest = new HttpRequest("", "http://www.example.com", ""); var httpResponse = new HttpResponse(writer); var controllerContext = CreateControllerContext(httpRequest, httpResponse, crowbarViewContext); var viewEngineResult = crowbarViewContext.FindViewEngineResult(controllerContext); var view = viewEngineResult.View; if (view == null) { var locations = new StringBuilder(); foreach (string searchedLocation in viewEngineResult.SearchedLocations) { locations.AppendLine(); locations.Append(searchedLocation); } throw new ArgumentException("The view was not found. The following locations were searched: " + locations, viewName); } try { var viewData = new ViewDataDictionary(viewModel); var tempData = new TempDataDictionary(); var viewContext = new ViewContextStub(controllerContext, view, viewData, tempData, writer) { ClientValidationEnabled = crowbarViewContext.ClientValidationEnabled, UnobtrusiveJavaScriptEnabled = crowbarViewContext.UnobtrusiveJavaScriptEnabled }; view.Render(viewContext, httpResponse.Output); cookies = controllerContext.HttpContext.Response.Cookies; httpResponse.Flush(); } finally { viewEngineResult.ViewEngine.ReleaseView(controllerContext, view); } return writer.ToString(); } }
public Stream GenerateOutput(dynamic shape) { var controller = new DummyController(_hca.Current().Request.RequestContext); using (var stream = new MemoryStream()) using (var streamWriter = new StreamWriter(stream)) { var originalContext = controller.ControllerContext.HttpContext; try { // Get the Request and User objects from the current, unchanged context var currentRequest = HttpContext.Current.ApplicationInstance.Context.Request; var currentUser = HttpContext.Current.ApplicationInstance.Context.User; // Create our new HttpResponse object containing our HtmlTextWriter var newResponse = new HttpResponse(streamWriter); // Create a new HttpContext object using our new Response object and the existing Request and User objects var newContext = new HttpContextWrapper( new HttpContext(currentRequest, newResponse) { User = currentUser }); // Swap in our new HttpContext object - output from this controller is now going to our HtmlTextWriter object controller.ControllerContext.HttpContext = newContext; new ShapePartialResult(controller, shape).ExecuteResult(controller.ControllerContext); newResponse.Flush(); streamWriter.Flush(); stream.Flush(); // New stream so everything else here can be disposed var responseStream = new MemoryStream(); stream.Position = 0; stream.CopyTo(responseStream); responseStream.Position = 0; return responseStream; } finally { // Setting context back to original so nothing gets messed up controller.ControllerContext.HttpContext = originalContext; } } }
protected override Gizmox.WebGUI.Common.Interfaces.IGatewayHandler ProcessGatewayRequest(System.Web.HttpContext objHttpContext, String strAction) { if ((strAction != null) && (strAction == "LoadPDF")) { // Variables Warning[] warnings; String[] streamIds; String mimeType = String.Empty, encoding = String.Empty, extension = String.Empty; // Setup the report viewer object and get the array of bytes ReportDataSource ds = new ReportDataSource(DATASOURCE_XSD_NAME, _DataSource); ReportViewer viewer = new ReportViewer(); viewer.LocalReport.SubreportProcessing += new SubreportProcessingEventHandler(RptSubreportProcessingEventHandler); viewer.ProcessingMode = ProcessingMode.Local; //Dictionary<string, DataTable> subSource = new Dictionary<string, DataTable>(); //subSource.Add(DATASOURCE_XSD_NAME, BindDataCurrent()); //subSource.Add("DataSource_vwStockInOutHistory2", BindDataCurrent()); //subSource.Add("DataSource_vwStockInOutHistory3", BindDataHistory()); //subSource.Add("DataSource_vwStockInOutHistory4", BindDataHistory()); //viewer.LocalReport.ReportPath = "RT2008.Web.Reports.Rdlc.StockQtyStatusRdl.rdlc"; viewer.LocalReport.EnableExternalImages = true; viewer.LocalReport.EnableHyperlinks = true; viewer.LocalReport.ReportEmbeddedResource = REPORT_RDLC_NAME; viewer.LocalReport.DataSources.Add(ds); viewer.LocalReport.SetParameters(GetSelParams()); byte[] bytes = viewer.LocalReport.Render("PDF", 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. System.Web.HttpResponse response = objHttpContext.Response; response.Buffer = true; response.Clear(); response.ContentType = mimeType; response.AddHeader("content-disposition", "inline; filename=" + REPORT_FILENAME + "." + extension); response.BinaryWrite(bytes); // create the file response.Flush(); // send it to the client to download return(null); } else { return(this.ProcessGatewayRequest(objHttpContext, strAction)); } }
public static string CaptureViewOutput(Controller controller, ViewResult view) { var builder = new StringBuilder(); using (var stringWriter = new StringWriter(builder)) { using (var htmlTextWriter = new HtmlTextWriter(stringWriter)) { var currentContext = controller.ControllerContext.HttpContext; try { // get the Request and User objects from the current, unchanged context var currentRequest = HttpContext.Current.ApplicationInstance.Context.Request; var currentUser = HttpContext.Current.ApplicationInstance.Context.User; // create our new HttpResponse object containing our HtmlTextWriter var newResponse = new HttpResponse(htmlTextWriter); // create a new HttpContext object using our new Response object and the existing Request and User objects var newContext = new HttpContextWrapper( new HttpContext(currentRequest, newResponse) { User = currentUser }); // swap in our new HttpContext object - output from this controller is now going to our HtmlTextWriter object controller.ControllerContext.HttpContext = newContext; // Run the ViewResult view.ExecuteResult(controller.ControllerContext); // flush the output newResponse.Flush(); htmlTextWriter.Flush(); stringWriter.Flush(); } finally { // and no matter what happens, set the context back! controller.ControllerContext.HttpContext = currentContext; } } } // our StringBuilder object now contains the output of the ViewResult object return builder.ToString(); }
public static void Download(MemoryStream MyStream, string fileName) { System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "text/plain"; //string fileExtension = "txt"; response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", fileName)); MyStream.WriteTo(response.OutputStream); response.Flush(); response.End(); }
protected void btnDownload_Click(object sender, EventArgs e) { if (gvMain.SelectedRow != null) { System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); string[] FileName = gvMain.SelectedRow.Cells[2].Text.ToString().Split('/'); response.ContentType = "text/plain"; response.AddHeader("Content-Disposition", "attachment; filename=" + FileName[3] + ";"); response.TransmitFile(Server.MapPath(gvMain.SelectedRow.Cells[2].Text)); response.Flush(); response.End(); } }
//HELPER FUNCTIONS// //User save dialog method public void dialog(string conType, string path, string name) { //Open dialog so that the user can save their file System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = conType; response.AddHeader("Content-Disposition", "attachment; filename=" + name + ";"); response.TransmitFile(path + name); response.Flush(); message = null; File.Delete(path + name); return; }
public void ProcessRequest(HttpContext context) { System.Web.HttpRequest request = System.Web.HttpContext.Current.Request; string fileName = request.QueryString["fileName"]; string fileDest = request.QueryString["fileDest"]; 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(fileDest); response.Flush(); response.End(); }
public static void ExportExcel(System.Web.HttpResponse response, string excelLocation) { byte[] bytes = File.ReadAllBytes(excelLocation); response.Clear(); response.ClearHeaders(); response.ClearContent(); response.ContentType = "application/vnd.ms-excel"; response.AddHeader("Content-Length", bytes.Length.ToString()); response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(Path.GetFileName(excelLocation), System.Text.Encoding.UTF8).Replace("+", "%20")); response.BinaryWrite(bytes); if (response.IsClientConnected) { response.Flush(); } }
protected void lnk_Click(object sender, EventArgs e) { string strFileName = "CalendarManual.pdf"; string strSourceFile = string.Empty; strSourceFile = Server.MapPath("~/Manual/CalendarManual.pdf"); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "text/plain"; response.AddHeader("Content-Disposition", "attachment; filename=" + strFileName + ";"); response.TransmitFile(strSourceFile); response.Flush(); response.End(); }
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 + "\\Downloadables\\Trial\\SimpleSqlite.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=SimpleSqlite.zip;"); response.TransmitFile(trialDownloadPath); TrialUser trialUser = new SqlDatabaseManager.SimpleSqlite.TrialUser(); trialUser.Email = "*****@*****.**"; trialUser.Name = "test name"; trialUser.Version = ConfigurationManager.AppSettings["Version"]; ConnectionStringSettings connectionStringSettings = ConfigurationManager.ConnectionStrings["SimpleSqliteDatabaseConnString"]; if (connectionStringSettings == null || string.IsNullOrEmpty(connectionStringSettings.ConnectionString)) { //throw error and return return; } Database.TrialDatabase.AddTrialUser(trialUser, connectionStringSettings.ConnectionString); response.Flush(); response.End(); } catch (Exception ex) { //Pop up dialog to let user know an error occurred } }
public async Task <System.Web.HttpResponse> DownloadBlobZip(string containerName, string folderpath, string configXml) { try { var container = GetBlobContainer(containerName); System.Web.HttpResponse Response = HttpContext.Current.Response; using (var zipOutputStream = new ZipOutputStream(Response.OutputStream)) { var blobs = container.ListBlobs(useFlatBlobListing: true); var blobNames = blobs.OfType <CloudBlockBlob>().Select(b => b.Name).ToList(); foreach (var blobName in blobNames) { var blobPathNameSplit = blobName.Split('/'); if (blobPathNameSplit.First().Equals(folderpath)) { zipOutputStream.SetLevel(0); var blob = container.GetBlockBlobReference(blobName); var entry = new ZipEntry(blobPathNameSplit.Last()); zipOutputStream.PutNextEntry(entry); blob.DownloadToStream(zipOutputStream); } } // add config file for simulator if (configXml != null) { var configEntry = new ZipEntry("Config.xml"); zipOutputStream.PutNextEntry(configEntry); byte[] toBytes = Encoding.ASCII.GetBytes(configXml); zipOutputStream.Write(toBytes, 0, toBytes.Length); } zipOutputStream.Finish(); zipOutputStream.Close(); } Response.BufferOutput = false; Response.AddHeader("Content-Disposition", "attachment; filename=" + folderpath + ".zip"); Response.ContentType = "application/octet-stream"; Response.Flush(); Response.End(); return(Response); } catch (Exception e) { throw e; } }
public void ExportGridViewToExcel(GridView grid, string fileName, HttpResponse Hresponse) { Hresponse.Clear(); Hresponse.Buffer = true; Hresponse.AddHeader("content-disposition", "attachment;fileName=" + fileName + ".xls"); Hresponse.Charset = ""; Hresponse.ContentType = "application/vnd.ms-excel"; StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); grid.RenderControl(hw); Hresponse.Output.Write(sw.ToString()); Hresponse.Flush(); Hresponse.Close(); //Hresponse.End(); Hresponse.OutputStream.Close(); }
private void dtManageThemes_ItemCommand(object sender, System.Web.UI.WebControls.DataListCommandEventArgs e) { if (e.Item.ItemType == System.Web.UI.WebControls.ListItemType.Item || e.Item.ItemType == System.Web.UI.WebControls.ListItemType.AlternatingItem) { string text = this.dtManageThemes.DataKeys[e.Item.ItemIndex].ToString(); string directoryName = this.Page.Request.MapPath(Globals.ApplicationPath + "/Templates/master/") + text; string text2 = this.Page.Request.MapPath(Globals.ApplicationPath + "/Templates/master/") + text; if (e.CommandName == "btnUse") { this.UserThems(text); this.ShowMsg("成功修改了商城模板", true); } if (e.CommandName == "download") { try { new System.IO.DirectoryInfo(text2); System.Text.Encoding uTF = System.Text.Encoding.UTF8; using (ZipFile zipFile = new ZipFile()) { zipFile.CompressionLevel = CompressionLevel.Default; if (System.IO.Directory.Exists(text2)) { zipFile.AddDirectory(text2); } else { zipFile.AddDirectory(directoryName); } System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ContentType = "application/zip"; response.ContentEncoding = uTF; response.AddHeader("Content-Disposition", "attachment;filename=" + text + ".zip"); response.Clear(); zipFile.Save(response.OutputStream); response.Flush(); response.Close(); } } catch (System.Exception ex) { throw ex; } } } }
public void ProcessRequest(HttpContext context) { string sPath = string.Empty; string sNomArchivo = oWeb.GetData("sNomArchivo"); string sNumContrato = oWeb.GetData("sNumContrato"); System.Web.HttpResponse oResponse = System.Web.HttpContext.Current.Response; sPath = HttpContext.Current.Server.MapPath("..\\rps_licenciatariosmattel") + "\\" + sNomArchivo; oResponse.ContentType = "application/octet-stream"; oResponse.AppendHeader("Content-Disposition", "attachment; filename=" + sNomArchivo); // Write the file to the Response const int bufferLength = 10000; byte[] buffer = new Byte[bufferLength]; int length = 0; Stream download = null; try { download = new FileStream(sPath, FileMode.Open, FileAccess.Read); do { if (oResponse.IsClientConnected) { length = download.Read(buffer, 0, bufferLength); oResponse.OutputStream.Write(buffer, 0, length); buffer = new Byte[bufferLength]; } else { length = -1; } }while (length > 0); oResponse.Flush(); oResponse.End(); } finally { if (download != null) { download.Close(); } } }
public static void ResponseExcel <T>(System.Web.HttpResponse response, List <T> items) { try { string attachment = "attachment; filename=vauExcel.xls"; response.ClearContent(); response.AddHeader("content-disposition", attachment); response.ContentType = "application/vnd.ms-excel"; string tab = string.Empty; // Get all the properties PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo prop in props) { response.Write(tab + prop.Name); tab = "\t"; } response.Write("\n"); foreach (T item in items) { var values = new object[props.Length]; for (int i = 0; i < props.Length; i++) { values[i] = props[i].GetValue(item, null); if (values[i] != null) { response.Write(values[i].ToString().Trim() + "\t"); } else { response.Write("\t"); } } response.Write("\n"); } response.Flush(); response.Close(); } catch (Exception ex) { throw ex; } }
/// <summary> /// 安全的Response.End() /// </summary> public static void SafeResponseEnd(HttpResponse response, String title) { try { response.Flush(); response.End(); Thread.Sleep(2000); } catch (ThreadAbortException tae) { //Logger.LogInfo("PublicMethodBLL", "SafeResponseEnd", 0, // "\"" + title + "\"页面在Response.End()时发生异常,只做为记录,不影响程序正常运行。", // tae.StackTrace + tae.Source); } }
public void ProcessRequest(HttpContext context) { System.Web.HttpRequest request = System.Web.HttpContext.Current.Request; string fileCode = request.QueryString["fileCode"]; Dictionary <string, string> FileInfoDict = Find_File_Info(context, fileCode); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "text/plain"; response.AddHeader("Content-Disposition", "attachment; filename=" + FileInfoDict["fileName"] + ";"); response.TransmitFile(context.Server.MapPath(FileInfoDict["filePath"])); response.Flush(); 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); ResponseWrite("Threads:", lThreads.Text.Replace("<br />", Environment.NewLine.ToString()), response); // Last and least... ResponseWrite("Server Variables:", "", response); foreach (string key in Request.ServerVariables) { bool isCookieOrPassword = key.Equals("HTTP_COOKIE", StringComparison.OrdinalIgnoreCase) || key.Equals("AUTH_PASSWORD", StringComparison.OrdinalIgnoreCase); // Skip cookies if (isCookieOrPassword) { continue; } bool isSensitiveData = key.IndexOf("ALL_HTTP", StringComparison.OrdinalIgnoreCase) >= 0 || key.IndexOf("ALL_RAW", StringComparison.OrdinalIgnoreCase) >= 0; if (isSensitiveData) { // strip out any sensitive data ResponseWrite(key, Regex.Replace(Request.ServerVariables[key], @"ASP.NET_SessionId=\S*;|\.ROCK=\S*;", string.Empty, RegexOptions.Multiline), response); } else { ResponseWrite(key, Request.ServerVariables[key], response); } } response.Flush(); response.End(); }
private void Download(string path, Employee emp) { string filename = path; FileInfo fileInfo = new FileInfo(filename); if (fileInfo.Exists) { System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response; Response.Clear(); Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name); Response.AddHeader("Content-Length", fileInfo.Length.ToString()); Response.ContentType = "application/octet-stream"; Response.Flush(); Response.TransmitFile(fileInfo.FullName); Response.End(); } }
/// <summary> /// 保存报表文件为文件 /// </summary> /// <param name="rpvObject">Reportview控件实例</param> /// <param name="rptType">打印的文件类型</param> /// <param name="filePath">文件存放路径</param> /// <param name="fileName">文件名</param> public static void Dowload(HttpResponse response, string filePath, string fileName, string extension) { if (response == null || string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(filePath) || string.IsNullOrEmpty(extension)) return; FileStream stream = new FileStream(filePath + fileName + "." + extension, FileMode.Open); byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); // 设置当前流的位置为流的开始 stream.Seek(0, SeekOrigin.Begin); stream.Close(); //Download response.Buffer = true; response.Clear(); response.ContentType = "application/" + extension; response.AddHeader("content-disposition", "attachment; filename=" + fileName + "." + extension); response.BinaryWrite(bytes); response.Flush(); response.End(); }
public void ProcessRequest(HttpContext context) { System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; System.Web.HttpRequest request = System.Web.HttpContext.Current.Request; string filePath = request.QueryString["filePath"]; string fileExtension = Path.GetExtension(filePath); string fileName = Guid.NewGuid().ToString("N"); string fullName = fileName + fileExtension; response.ClearContent(); response.Clear(); response.ContentType = "text/plain"; response.AddHeader("Content-Disposition", "attachment; filename=" + fullName + ";"); response.TransmitFile(HttpContext.Current.Server.MapPath("/Uploads/" + filePath)); response.Flush(); response.End(); }
/* * private Dictionary<string, string> _contentType = new Dictionary<string, string>() * { * { "pdf", "application/pdf"}, * {"doc", "application/msword"}, * {"exe", "application/x-msdownload"} * }; */ public void ProcessRequest(HttpContext context) { try { if ((System.Web.HttpContext.Current.User != null) && System.Web.HttpContext.Current.User.Identity.IsAuthenticated) { string path = "~/App_Data"; System.Web.HttpRequest request = System.Web.HttpContext.Current.Request; string fileType = request.QueryString["fileType"]; string fileName = request.QueryString["fileName"]; string extension = System.IO.Path.GetExtension(fileName); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "application/" + extension; response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ";"); response.TransmitFile( HttpContext.Current.Server.MapPath( string.Format("{0}/{1}/{2}", path, fileType, fileName))); response.Flush(); response.End(); } else { context.Response.Redirect("../errors/unauthorized.aspx"); } } catch (NullReferenceException) { context.Response.Redirect("../errors/unauthorized.aspx"); } catch (System.IO.DirectoryNotFoundException) { context.Response.Redirect("../errors/notfound.aspx"); } catch (System.IO.FileNotFoundException) { context.Response.Redirect("../errors/notfound.aspx"); } }
protected void GrdQuestionPaper_RowCommand(object sender, GridViewCommandEventArgs e) { int index = Convert.ToInt32(e.CommandArgument); GridViewRow gvRow = GrdQuestionPaper.Rows[index]; int questionpaper_id = Convert.ToInt32(gvRow.Cells[0].Text); if (e.CommandName == "Upload") { SqlConnection conn = new SqlConnection(@"Data Source=LAPTOP-8444MQAL\MSSQLSERVER01;Initial Catalog=StudentModule;Integrated Security=True"); conn.Open(); string checkuser = "******" + fileuploadQuestionPaper.FileName + "' where qp_id =" + questionpaper_id; SqlCommand cmd = new SqlCommand(checkuser, conn); cmd.ExecuteNonQuery(); if (fileuploadQuestionPaper.FileName != "") { fileuploadQuestionPaper.SaveAs(Server.MapPath("QuestionPaper") + "//" + fileuploadQuestionPaper.FileName); Label1.Text = "Notes Updated Successfully Uploaded"; } else { Label1.Text = "Please Select The File"; } } else if (e.CommandName == "Download") { SqlConnection conn = new SqlConnection(@"Data Source=LAPTOP-8444MQAL\MSSQLSERVER01;Initial Catalog=StudentModule;Integrated Security=True"); conn.Open(); string checkuser = "******" + questionpaper_id; SqlCommand cmd = new SqlCommand(checkuser, conn); string filename = cmd.ExecuteScalar().ToString(); 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("QuestionPaper") + "//" + filename); response.Flush(); response.End(); } LoadGrid(); }
public void ProcessRequest(HttpContext context) { System.Web.HttpResponse oResponse = System.Web.HttpContext.Current.Response; string sPath = string.Empty; sPath = sPath + "\\\\srvdebt03\\Comun\\Mattel Europa\\Base.bak"; oResponse.ContentType = "application/pdf"; oResponse.AppendHeader("Content-Disposition", "attachment; filename=Base.bak"); // Write the file to the Response const int bufferLength = 10000; byte[] buffer = new Byte[bufferLength]; int length = 0; Stream download = null; try { download = new FileStream(sPath, FileMode.Open, FileAccess.Read); do { if (oResponse.IsClientConnected) { length = download.Read(buffer, 0, bufferLength); oResponse.OutputStream.Write(buffer, 0, length); buffer = new Byte[bufferLength]; } else { length = -1; } }while (length > 0); oResponse.Flush(); oResponse.End(); } finally { if (download != null) { download.Close(); } } }
protected void ClientBigfileOk_Click(object sender, EventArgs e) { try { string fileName = "FileUpLoadSetup.exe"; System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.Clear(); response.ClearHeaders(); response.ClearContent(); response.AddHeader("Content-Disposition", "attachment; filename=" + fileName); response.ContentType = "text/plain"; response.TransmitFile(System.Web.HttpContext.Current.Server.MapPath(fileName)); response.Flush(); response.End(); } catch (Exception ex) { } }
protected void exportButton_Click(object sender, EventArgs e) { SqlConnection conn = new SqlConnection(); conn.ConnectionString = ConfigurationManager.ConnectionStrings["PracticeConnectionString"].ConnectionString; String strDelimiter = ","; String cs = ConfigurationManager.ConnectionStrings["PracticeConnectionString"].ConnectionString; StringBuilder sb = new StringBuilder(); if (emp != null) { emp = Session["employees"] as List <Employee>; foreach (Employee epl in emp) { sb.Append(epl.getfn() + strDelimiter); sb.Append(epl.getln() + strDelimiter); sb.Append(epl.getad() + strDelimiter); sb.Append(epl.getpo() + strDelimiter); sb.Append("\r\n"); } Console.Clear(); StreamWriter file = new StreamWriter(@"C:\Users\Owner\Desktop\Data.csv"); file.WriteLine(sb.ToString()); file.Close(); String FileName = "Data.csv"; String FilePath = "C:/Users/Owner/Desktop/Data.csv"; 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(); System.IO.File.Delete(@"C:\Users\Owner\Desktop\Data.csv"); } }
private static void ShowSource(HttpResponse response, int moduleId, int portalId, Hashtable settings) { if (response == null) throw new ArgumentNullException("response"); var scriptTimeOut = HttpContext.Current.Server.ScriptTimeout; // temporarily set script timeout to large value ( this value is only applicable when application is not running in Debug mode ) HttpContext.Current.Server.ScriptTimeout = int.MaxValue; response.ContentType = "xml|text/xml"; response.AppendHeader("content-disposition", "inline; filename=" + "datasource.xml"); using (var writer = XmlWriter.Create(response.OutputStream)) { var providerName = settings[Setting.SourceProvider].DefaultIfNullOrEmpty(); if (providerName != string.Empty) writer.WriteNode(XmlDataProvider.Instance(providerName).Load(moduleId, portalId, settings), false); writer.Flush(); } response.Flush(); // reset script timeout HttpContext.Current.Server.ScriptTimeout = scriptTimeOut; }
public ActionResult DownloadProject() { int projectid = int.Parse(Request.QueryString["pid"]); List <project> project = objadminmodel.DownloadProject(projectid); foreach (var item in project) { System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = item.filetype; response.AddHeader("Content-Disposition", "attachment; filename=" + item.filename + ";"); response.TransmitFile(Server.MapPath(@"~/Uploads/" + item.filename)); response.Flush(); response.End(); } ViewBag.projects = objadminmodel.GetProjects(); return(View("~/Views/Admin/ProjectsList.cshtml")); }
public void ExportWord(System.Web.UI.WebControls.GridView exportGV, System.Web.HttpResponse Response, System.Web.UI.HtmlControls.HtmlForm htmlForm) { Response.Clear(); Response.Buffer = true; Response.AddHeader("content-disposition", "attachment;filename=Export.doc"); Response.Charset = ""; Response.ContentType = "application/vnd.ms-word "; StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); exportGV.Parent.Controls.Add(htmlForm); htmlForm.Attributes["runat"] = "server"; htmlForm.Controls.Add(exportGV); htmlForm.RenderControl(hw); Response.Output.Write(sw.ToString()); Response.Flush(); Response.End(); }
protected void DownloadButton_Click(object sender, EventArgs e) { System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; string[] extArray = ProfilePic.ImageUrl.Split('.'); string ext = extArray[extArray.Length - 1]; response.Clear(); response.AddHeader("Content-Disposition", "attachment; filename= " + Session["User"].ToString() + "ProfilePicture." + ext + ";"); response.TransmitFile(Server.MapPath(ProfilePic.ImageUrl)); response.Flush(); response.End(); List <string> values = new List <string>(); values.Add("IMG_DWL"); values.Add(UpdaterId()); values.Add(Session["User"].ToString()); int status = DataConsumer.executeProcedure("audit_proc", values); }
protected void Page_Load(object sender, EventArgs e) { this.Page.Response.Clear(); if (base.Request.Files["uploadfile"] != null) { this.Upload(); } else if (base.Request.QueryString["download"] != null) { string filename = base.Server.MapPath("~/congvan.pdf"); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "application/pdf"; response.AddHeader("Content-Disposition", "attachment; filename=" + "testfilename.pdf" + ";"); response.TransmitFile(filename); response.Flush(); } this.Page.Response.End(); }
public void ProcessRequest(HttpContext context) { System.Web.HttpRequest request = System.Web.HttpContext.Current.Request; int ID_Files = Convert.ToInt32(request.QueryString["yourVariable"]); // string yourVariableValue = request.QueryString["yourVariable"]; // string yourVariableValue2 = request.QueryString["yourVariable2"]; string yourVariableFileName = FINANCIAL_MANAGEMENT.App_Code.xrisi.Fetch_File_Path_ABE(ID_Files); string yourVariableType = FINANCIAL_MANAGEMENT.App_Code.xrisi.Fetch_File_Type_ABE(ID_Files); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = yourVariableType; response.AddHeader("Content-Disposition", "attachment; filename=" + yourVariableFileName + ";"); response.TransmitFile("~\\FilesUp\\" + yourVariableFileName); response.Flush(); response.End(); }
//2018-1-12修正正確寫法,才能在Client端儲存檔案 private void Save_csv_toClient(DataTable dt, string svPath) { System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "text/plain"; response.AddHeader("Content-Disposition", "attachment; filename=" + svPath + ";"); StringBuilder sb = new StringBuilder(); string data = ""; foreach (DataRow row in dt.Rows) { foreach (DataColumn column in dt.Columns) { if (!string.IsNullOrEmpty(row[column].ToString().Trim())) { if (column.ColumnName == "birth" | column.ColumnName == "date") { data += Convert.ToDateTime(row[column].ToString().Trim()).ToString("yyyy-MM-dd 00:00:00.000") + ","; } else { data += row[column].ToString().Trim() + ","; } } else { data += "NULL,"; } } data += ""; sb.AppendLine(data.Substring(0, (data.Length - 1))); data = ""; } response.Write(sb.ToString()); response.Flush(); response.End(); }
public void WriteFile(string strFileName) { System.Web.HttpResponse objResponse = System.Web.HttpContext.Current.Response; System.IO.Stream objStream = null; byte[] bytBuffer = new byte[10000]; int intLength; long lngDataToRead; try { objStream = new System.IO.FileStream(strFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); lngDataToRead = objStream.Length; objResponse.ContentType = "application/octet-stream"; while (lngDataToRead > 0) { if (objResponse.IsClientConnected) { intLength = objStream.Read(bytBuffer, 0, 10000); objResponse.OutputStream.Write(bytBuffer, 0, intLength); objResponse.Flush(); bytBuffer = new byte[10000]; lngDataToRead = lngDataToRead - intLength; } else { lngDataToRead = -1; } } } catch (Exception ex) { objResponse.Write("Error : " + ex.Message); } finally { if (objStream != null) { objStream.Close(); } } }
/// <summary> /// pjy /// 2013-05-07 /// 把内存流(文件)发送到客户端 /// </summary> /// <param name="fileName">文件名称</param> /// <param name="ms">文件流</param> /// <param name="response">响应客户端对象</param> public static void SendFile(string fileName, MemoryStream ms, Encoding encoding = null) { encoding = encoding ?? Encoding.UTF8; if (ms != null && !string.IsNullOrEmpty(fileName)) { System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.Clear(); response.AddHeader("Content-Type", "application/octet-stream"); 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); response.BinaryWrite(ms.GetBuffer()); ms.Close(); ms = null; response.Flush(); response.End(); } }
public void Flush(System.Web.HttpResponse resp) { byte[] data1 = output.ToArray(); if (!useGZip_ || data1.Length < 200) { finalOutLength = data1.Length; resp.BinaryWrite(data1); return; } // compress MemoryStream ms = new MemoryStream(); GZipStream GZip = new GZipStream(ms, CompressionMode.Compress); GZip.Write(data1, 0, data1.Length); GZip.Close(); // get compressed bytes byte[] data2 = ms.ToArray(); ms.Close(); // if compression failed (more data) if (data2.Length >= data1.Length) { finalOutLength = data1.Length; resp.BinaryWrite(data1); return; } resp.BufferOutput = true; resp.ContentType = "application/octet-stream"; resp.Write("$1"); //resp.Write(string.Format("SIZE: {0} vs {1}<br>", data1.Length, data2.Length)); finalOutLength = data2.Length; resp.BinaryWrite(data2); resp.Flush(); }
//public void DownLoad(HttpRequest request, HttpResponse response, string name, string path, long speed) //{ // try // { // if (string.IsNullOrEmpty(path)) // { // path = System.Web.HttpContext.Current.Server.MapPath(name); // } // //BinaryReader br // #region response // response.Clear(); // response.AddHeader("Accept-Ranges", "bytes"); // response.AddHeader("Content-Length", ""); // response.AddHeader("Content-Range", ""); // response.AddHeader("Connection", "Keep-Alive"); // response.AddHeader("Content-Type", "application/octet-stream"); // response.AddHeader("Content-Disposition", "attachment;filename=" + path); // //response.TransmitFile(); // //response.BinaryWrite(); // response.End(); // #endregion // } // catch { } //} private void DownLoad(HttpResponse response, string name, string path) { try { if (string.IsNullOrEmpty(path)) { path = System.Web.HttpContext.Current.Server.MapPath(name); } //以字符流的形式下载文件 FileStream fs = new FileStream(path, FileMode.Open); byte[] bytes = new byte[(int)fs.Length]; fs.Read(bytes, 0, bytes.Length); fs.Close(); response.ContentType = "application/octet-stream"; //通知浏览器下载文件而不是打开 response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8)); response.BinaryWrite(bytes); response.Flush(); response.End(); } catch { } }
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 }
protected void StreamChunk(byte[] bytes, HttpResponse response) { if (bytes != null && bytes.Length > 0) { byte[] chunkLength = System.Text.Encoding.ASCII.GetBytes(System.Convert.ToString(bytes.Length, 0x10)); response.BinaryWrite(chunkLength); response.BinaryWrite(CRLF_BYTES); response.BinaryWrite(bytes); response.Flush(); } else { //response.OutputStream.WriteByte(48); //response.BinaryWrite(CRLF_BYTES); response.Flush(); } }
/// ----------------------------------------------------------------------------- /// <summary> /// Writes a Stream to the appropriate File Storage /// </summary> /// <param name="objResponse">The Id of the File</param> /// <param name="objStream">The Input Stream</param> /// <remarks> /// </remarks> /// <history> /// [cnurse] 04/27/2006 Created /// </history> /// ----------------------------------------------------------------------------- private static void WriteStream(HttpResponse objResponse, Stream objStream) { //Buffer to read 10K bytes in chunk: var bytBuffer = new byte[10000]; //Length of the file: int intLength; //Total bytes to read: long lngDataToRead; try { //Total bytes to read: lngDataToRead = objStream.Length; //Read the bytes. while (lngDataToRead > 0) { //Verify that the client is connected. if (objResponse.IsClientConnected) { //Read the data in buffer intLength = objStream.Read(bytBuffer, 0, 10000); //Write the data to the current output stream. objResponse.OutputStream.Write(bytBuffer, 0, intLength); //Flush the data to the HTML output. objResponse.Flush(); lngDataToRead = lngDataToRead - intLength; } else { lngDataToRead = -1; } } } catch (Exception ex) { DnnLog.Error(ex); objResponse.Write("Error : " + ex.Message); } finally { if (objStream != null) { objStream.Close(); objStream.Dispose(); } } }
private void HandleFlexClientStreamingOpenRequest(HttpRequest request, HttpResponse response, IClient flexClient) { Session session = FluorineContext.Current.Session as Session; if (session == null) { string msg = string.Format("Cannot grant streaming connection when ASP.NET session state is disabled", this.Id); if (log.IsWarnEnabled) log.Warn(msg); try { HandleBadRequest(msg, HttpContext.Current.Response); } catch (HttpException) { } return; } if (!_canStream || !session.CanStream) { string msg = string.Format("Cannot grant streaming connection, limit has been reached", this.Id); try { HandleBadRequest(msg, HttpContext.Current.Response); } catch (HttpException) { } return; } bool canStream = false; lock (this.SyncRoot) { _streamingClientsCount.Increment(); if (_streamingClientsCount.Value == this.MaxStreamingClients) { canStream = true; // This thread got the last spot. _canStream = false; } else if (_streamingClientsCount.Value > this.MaxStreamingClients) { canStream = false; // This thread lost the last spot. _streamingClientsCount.Decrement();// We're not going to grant the streaming right to the client. } else { // Allow this thread to stream. canStream = true; } } if (!canStream) { string msg = string.Format("Cannot service streaming request, max-streaming-clients reached in endpoint {0}", this.Id); try { HandleBadRequest(msg, HttpContext.Current.Response); } catch (HttpException) { } return; } UserAgent userAgent = this.ChannelDefinition.Properties.UserAgentSettings[request.Browser.Browser]; if (userAgent != null) { lock (session.SyncRoot) { session.MaxConnectionsPerSession = userAgent.MaxStreamingConnectionsPerSession; } } lock (session.SyncRoot) { session.StreamingConnectionsCount++; if (session.StreamingConnectionsCount == session.MaxConnectionsPerSession) { canStream = true; // This thread got the last spot in the session. session.CanStream = false; } else if (session.StreamingConnectionsCount > session.MaxConnectionsPerSession) { canStream = false; session.StreamingConnectionsCount--; _streamingClientsCount.Decrement(); } else { canStream = true; } } if (!canStream) { string msg = string.Format("Cannot grant streaming connection, limit has been reached", this.Id); try { HandleBadRequest(msg, HttpContext.Current.Response); } catch (HttpException) { } return; } EndpointPushNotifier notifier = null; try { response.ContentType = ContentType.AMF; response.AppendHeader("Cache-Control", "no-cache"); response.AppendHeader("Pragma", "no-cache"); response.AppendHeader("Connection", "close"); //response.AppendHeader("Transfer-Encoding", "chunked"); response.Flush(); // Setup for specific user agents. byte[] kickStartBytesToStream = null; int kickStartBytes = userAgent != null ? userAgent.KickstartBytes : 0; if (kickStartBytes > 0) { // The minimum number of actual bytes that need to be sent to kickstart, taking into account transfer-encoding overhead. try { int chunkLengthHeaderSize = System.Text.Encoding.ASCII.GetBytes(System.Convert.ToString(kickStartBytes, 0x10)).Length; //System.Text.ASCIIEncoding.ASCII.GetBytes(kickStartBytes.ToString("X")).Length; int chunkOverhead = chunkLengthHeaderSize + 4; // 4 for the 2 wrapping CRLF tokens. int minimumKickstartBytes = kickStartBytes - chunkOverhead; kickStartBytesToStream = new byte[(minimumKickstartBytes > 0) ? minimumKickstartBytes : kickStartBytes]; } catch { kickStartBytesToStream = new byte[kickStartBytes]; } } if (kickStartBytesToStream != null) { StreamChunk(kickStartBytesToStream, response); } try { notifier = new EndpointPushNotifier(this, flexClient); lock (_currentStreamingRequests.SyncRoot) { _currentStreamingRequests.Add(notifier.Id, notifier); } // Push down an acknowledgement for the 'connect' request containing the unique id for this specific stream. AcknowledgeMessage connectAck = new AcknowledgeMessage(); connectAck.body = notifier.Id; connectAck.correlationId = OpenCommand; StreamMessage(connectAck, response); } catch (MessageException) { } if (log.IsDebugEnabled) { string msg = string.Format("Start streaming for endpoint with id {0} and client with id {1}", this.Id, flexClient.Id); log.Debug(msg); } int serverToClientHeartbeatMillis = this.ChannelDefinition.Properties.ServerToClientHeartbeatMillis >= 0 ? this.ChannelDefinition.Properties.ServerToClientHeartbeatMillis : 0; serverToClientHeartbeatMillis = 100; while (!notifier.IsClosed) { IList messages = notifier.GetPendingMessages(); StreamMessages(messages, response); lock (notifier.SyncRoot) { Monitor.Wait(notifier.SyncRoot, serverToClientHeartbeatMillis); messages = notifier.GetPendingMessages(); // If there are no messages to send to the client, send a 0 // byte as a heartbeat to make sure the client is still valid. if ((messages == null || messages.Count == 0) && serverToClientHeartbeatMillis > 0) { try { StreamChunk(Heartbeat, response); response.Flush(); } catch (HttpException) { break; } catch (IOException) { break; } } else { StreamMessages(messages, response); } } } // Terminate the response. StreamChunk(null, response); if (log.IsDebugEnabled) { string msg = string.Format("Releasing streaming connection for endpoint with id {0} and and client with id {1}", this.Id, flexClient.Id); log.Debug(msg); } } catch (IOException ex)//HttpException? { if (log.IsWarnEnabled) log.Warn("Streaming thread for endpoint with id " + this.Id + " is closing connection due to an IO error.", ex); } catch (Exception ex) { if (log.IsErrorEnabled) log.Error("Streaming thread for endpoint with id " + this.Id + " is closing connection due to an error.", ex); } finally { if (notifier != null && _currentStreamingRequests != null) { if (_currentStreamingRequests != null) { lock (_currentStreamingRequests.SyncRoot) { _currentStreamingRequests.Remove(notifier.Id); } } notifier.Close(); } _streamingClientsCount.Decrement(); lock (session.SyncRoot) { session.StreamingConnectionsCount--; session.CanStream = session.StreamingConnectionsCount < session.MaxConnectionsPerSession; } } }
/// <summary> /// 下载报表文件 /// </summary> /// <param name="s_rptType">打印的文件类型("Excel,PDF,Image")</param> public static void DowloadReportFile(HttpResponse response, ReportViewer rpvObject, ReportPrintType rptType, string fileName) { if (string.IsNullOrEmpty(fileName) || response == null || rpvObject == null) return; Warning[] warnings; string[] streamids; string mimeType; string encoding; string extension; byte[] bytes = rpvObject.LocalReport.Render( rptType.ToString(), null, out mimeType, out encoding, out extension, out streamids, out warnings); //Download response.Buffer = true; response.Clear(); response.ContentType = "application/" + extension; response.AddHeader("content-disposition", "attachment; filename=" + fileName + "." + extension); response.BinaryWrite(bytes); response.Flush(); response.End(); }
public static void DownloadFile(int fileId, HttpResponse response, bool AddContentDispositionHeader) { string fileName; string contentType; int size; GetInfo(fileId, out fileName, out contentType, out size); response.ContentType = contentType; string susag = HttpContext.Current.Request.UserAgent.ToString(); if(susag.IndexOf("MSIE")>0) { string sextension = ""; string _fileName = fileName; int lastDot = fileName.LastIndexOf("."); if(lastDot >= 0) { sextension = fileName.Substring(lastDot); _fileName = fileName.Substring(0, lastDot); } bool MoreThan127 = false; for(int i=0; i<_fileName.Length; i++) { char ch = _fileName[i]; int j = (int)ch; if(j>127) { MoreThan127 = true; break; } } if(MoreThan127 && _fileName.Length>25) _fileName = _fileName.Substring(0,25); fileName = HttpContext.Current.Server.UrlPathEncode(_fileName+sextension); } if (AddContentDispositionHeader) response.AddHeader("content-disposition", String.Format("attachment; filename=\"{0}\"", fileName)); const int iBufferSize = 65536; // 64 KB byte[] outbyte = new byte[iBufferSize]; using(IDataReader reader = DBFile.GetBinaryData(fileId)) { if(reader != null) { if(reader.Read()) { long read = 0, startIndex = 0; do { if(response.IsClientConnected) { read = reader.GetBytes(0, startIndex, outbyte, 0, iBufferSize); response.OutputStream.Write(outbyte, 0, System.Convert.ToInt32(read)); response.Flush(); startIndex += read; } else read = 0; } while(read == iBufferSize); } } } }
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 } }
//@Override public bool preHandle(HttpRequest request, HttpResponse response, Object o) { // we only care about post because that's the only instance where we can get anything useful besides IP address. if (!"POST".Equals(request.HttpMethod)) { return true; } if (this.exceedsThreshold(request)) { this.recordThrottle(request); response.StatusCode = 403;// response.StatusDescription = ("Access Denied for user [" + request.getParameter(this.usernameParameter) + " from IP Address [" + ".." + "]"); response.Flush(); return false; } return true; }
/// <summary> /// 下载文件 /// </summary> /// <param name="Response"></param> /// <param name="filepath"></param> /// <param name="filename"></param> public static void DownloadFile(HttpResponse Response, string filepath, string filename) { System.IO.Stream iStream = null; // Buffer to read 10K bytes in chunk: byte[] buffer = new Byte[10000]; // Length of the file: int length; // Total bytes to read: long dataToRead; // Identify the file to download including its path. //string filepath = "strFilePath"; // Identify the file name. //string filename = System.IO.Path.GetFileName(filepath); //filename = HttpUtility.UrlEncode(filename);//加密 try { // Open the file. iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); // Total bytes to read: dataToRead = iStream.Length; //Response.Charset = "utf-8"; Response.Charset = "utf-8"; Response.ContentEncoding = System.Text.Encoding.UTF8; Response.ContentType = "application/octet-stream"; // 添加头信息,为"文件下载/另存为"对话框指定默认文件名 Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8)); // 添加头信息,指定文件大小,让浏览器能够显示下载进度 Response.AddHeader("Content-Length", dataToRead.ToString()); // Read the bytes. while (dataToRead > 0) { // Verify that the client is connected. if (Response.IsClientConnected) { // Read the data in buffer. length = iStream.Read(buffer, 0, 10000); // Write the data to the current output stream. Response.OutputStream.Write(buffer, 0, length); // Flush the data to the HTML output. Response.Flush(); buffer = new Byte[10000]; dataToRead = dataToRead - length; } else { //prevent infinite loop if user disconnects dataToRead = -1; } } } catch (Exception ex) { // Trap the error, if any. Response.Write("系统消息:服务器中的附件(" + filename + ")已被删除!"); } finally { if (iStream != null) { //Close the file. iStream.Close(); } } }
private void ReturnMessage(RtmptConnection connection, ByteBuffer data, HttpResponse response) { response.StatusCode = 200; response.ClearHeaders(); response.AppendHeader("Connection", "Keep-Alive"); int contentLength = data.Limit + 1; response.AppendHeader("Content-Length", contentLength.ToString()); response.Cache.SetCacheability(HttpCacheability.NoCache); response.ContentType = ContentType.RTMPT; response.Write((char)connection.PollingDelay); byte[] buffer = data.ToArray(); response.OutputStream.Write(buffer, 0, buffer.Length); response.Flush(); }
private void ReturnMessage(byte message, HttpResponse response) { response.StatusCode = 200; response.ClearHeaders(); response.AppendHeader("Connection", "Keep-Alive"); response.AppendHeader("Content-Length", "1"); response.Cache.SetCacheability(HttpCacheability.NoCache); response.ContentType = ContentType.RTMPT; response.Write((char)message); response.Flush(); }
private void HandleBadRequest(string message, HttpResponse response) { response.StatusCode = 400; response.ContentType = "text/plain"; response.AppendHeader("Content-Length", message.Length.ToString()); response.Write(message); response.Flush(); }