/// <summary> /// Copies the full binary contents of the given blob to the given HTTP response. /// </summary> private static void CopyContents(CloudBlob blob, HttpResponseBase response, long offset = 0) { blob.FetchAttributes(); response.BufferOutput = false; response.AddHeader("Content-Length", blob.Attributes.Properties.Length.ToString()); response.Flush(); using (var reader = blob.OpenRead()) { reader.Seek(offset, System.IO.SeekOrigin.Begin); byte[] buffer = new byte[1024 * 4]; // 4KB buffer while (reader.CanRead) { int numBytes = reader.Read(buffer, 0, buffer.Length); if (numBytes <= 0) break; response.BinaryWrite(buffer); response.Flush(); } } }
private static void SaveSectionToDb(List<string> section, int section_id, HttpResponseBase response) { string url = String.Empty; int ch_count = 1; int current_ch = 1; XDocument xml = null; int chapter_id = 0; int book_id = 0; foreach (string abbrev in section) { response.Write("<br /><hr /><br />"); while(current_ch <= ch_count) { using(var db = new Entities()) { url = "http://piibel.net/.xml?q=" + abbrev + "%20" + current_ch; xml = XDocument.Load(url); if(current_ch == 1) { book_id = AddBook(section_id, xml); ch_count = Int32.Parse(xml.Descendants("bible").First().Attribute("pages").Value); } chapter_id = AddChapter(xml, book_id); AddVerses(xml, chapter_id); response.Write("Saved: " + abbrev + " " + current_ch + "<br />"); response.Flush(); current_ch++; } } current_ch = 1; ch_count = 1; } }
private void ResponseImg(HttpResponseBase response, string pic) { try { string FilePath = AppDomain.CurrentDomain.BaseDirectory; FilePath = Path.Combine(FilePath, "App_Data\\" + imgpath); string FileFullPath = Path.Combine(FilePath, pic); string FileExt = Path.GetExtension(FileFullPath); if (U.ExtValid(FileExt)) { if (File.Exists(FileFullPath)) { FileExt = FileExt.ToLower(); Image Img = Image.FromFile(FileFullPath); ImageFormat format = ImageFormat.Jpeg; switch (FileExt) { case ".gif": format = ImageFormat.Gif; break; case ".jpg": format = ImageFormat.Jpeg; break; case ".png": format = ImageFormat.Png; break; default: break; } response.ClearContent(); response.ContentType = "image/bmp"; Img.Save(response.OutputStream, format); Img.Dispose(); response.Flush(); } else { response.Write("file DO NOT Exists"); } } else { response.Write("file DO NOT Allow"); } } catch (Exception ex) { log.Warn(ex.Message); log.Warn("imgpath:{0},imgname:{1}", imgpath, imgname); } }
public static void DiplomProjectToWord(string fileName, DiplomProject work, HttpResponseBase response) { response.Clear(); response.Charset = "ru-ru"; response.HeaderEncoding = Encoding.UTF8; response.ContentEncoding = Encoding.UTF8; response.ContentType = "application/vnd.ms-word"; response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".doc"); CreateDoc(work, response); response.Flush(); response.End(); }
private void SetHttpResponse(HttpResponseBase httpResponse, string fileNameWithoutExtension, ExcelPackage package) { httpResponse.ClearContent(); httpResponse.Buffer = true; //Write it back to the client httpResponse.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; httpResponse.AddHeader("content-disposition", string.Format("attachment; filename={0}.xlsx", fileNameWithoutExtension)); httpResponse.BinaryWrite(package.GetAsByteArray()); httpResponse.Flush(); httpResponse.End(); }
/// <summary> /// Writes the file range to the response. /// </summary> /// <param name="response">The response from context within which the result is executed.</param> /// <param name="rangeStartIndex">Range start index</param> /// <param name="rangeEndIndex">Range end index</param> protected override void WriteEntityRange(HttpResponseBase response, long rangeStartIndex, long rangeEndIndex) { WriteMultipartEntityRange(response, rangeStartIndex, rangeEndIndex); try { response.Flush(); } // ReSharper disable EmptyGeneralCatchClause catch // ReSharper restore EmptyGeneralCatchClause { } }
protected override void WriteFile(HttpResponseBase response) { _isRssFeed = _feedType == FeedType.Rss; // Creates Xml file. string xmlFile = HttpContext.Current.Server.MapPath("~/feed.xml"); using (var fileStream = new FileStream(xmlFile, FileMode.Create)) { using (var streamWriter = new StreamWriter(fileStream, Encoding.UTF8)) { var xs = new XmlWriterSettings { Indent = true }; using (var xmlWriter = XmlWriter.Create(streamWriter, xs)) { xmlWriter.WriteStartDocument(); if (_isCssStyles) { const string strPi = "type='text/css' href='/Contents/Styles/feedStyle.css'"; // Write processor information xmlWriter.WriteProcessingInstruction("xml-stylesheet", strPi); } if (_isRssFeed) { // RSS 2.0 var rssFormatter = new Rss20FeedFormatter(_feed, true); rssFormatter.WriteTo(xmlWriter); } else { // Atom 1.0 var atomFormatter = new Atom10FeedFormatter(_feed); atomFormatter.WriteTo(xmlWriter); } } } } //Display Xml file in browser. response.Clear(); response.Buffer = true; response.Charset = ""; response.Cache.SetCacheability(HttpCacheability.NoCache); response.ContentType = "text/xml"; response.WriteFile(HttpContext.Current.Server.MapPath("~/feed.xml")); response.Flush(); response.End(); }
public void FileDownload(HttpResponseBase response,string filePah) { if(!IsExists(filePah)) { throw new Exception("�ļ�������"); } var fileInfo = new FileInfo(filePah); response.Clear(); response.ClearContent(); response.ClearHeaders(); response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileInfo.Name,System.Text.Encoding.UTF8)); response.AddHeader("Content-Length", fileInfo.Length.ToString()); //response.AddHeader("Content-Transfer-Encoding", "binary"); response.ContentType = "application/vnd.ms-excel;charset=UTF-8"; response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); response.WriteFile(fileInfo.FullName); response.Flush(); response.End(); }
protected override void WriteFile(HttpResponseBase response) { _isRssFeed = _feedType == FeedType.Rss; // Creates Xml file. string xmlFile = HttpContext.Current.Server.MapPath("~/feed.xml"); using (var fileStream = new FileStream(xmlFile, FileMode.Create)) { using (var streamWriter = new StreamWriter(fileStream, Encoding.UTF8)) { var xs = new XmlWriterSettings { Indent = true }; using (var xmlWriter = XmlWriter.Create(streamWriter, xs)) { xmlWriter.WriteStartDocument(); if (_isRssFeed) { // RSS 2.0 var rssFormatter = new Rss20FeedFormatter(_feed); rssFormatter.WriteTo(xmlWriter); } else { // Atom 1.0 var atomFormatter = new Atom10FeedFormatter(_feed); atomFormatter.WriteTo(xmlWriter); } } } } XslTransform myXslTransform = new XslTransform(); myXslTransform.Load(HttpContext.Current.Server.MapPath("~/feed.xslt")); myXslTransform.Transform(HttpContext.Current.Server.MapPath("~/feed.xml"), HttpContext.Current.Server.MapPath("~/newFeed.xml")); //Display Xml file in browser. response.Clear(); response.Buffer = true; response.Charset = ""; response.Cache.SetCacheability(HttpCacheability.NoCache); response.ContentType = "application/xml"; response.WriteFile(HttpContext.Current.Server.MapPath("~/newFeed.xml")); response.Flush(); response.End(); }
public static void DumpXls(HttpResponseBase response, DataTable table, string fileName) { var grid = new GridView(); grid.DataSource = table; grid.DataBind(); response.ClearContent(); response.Buffer = true; response.AddHeader("content-disposition", string.Format("attachment; filename={0}.xls", fileName)); response.ContentType = "application/ms-excel"; response.Charset = ""; var sw = new StringWriter(); var htw = new HtmlTextWriter(sw); grid.RenderControl(htw); response.Output.Write(sw.ToString()); response.Flush(); response.End(); }
/// <summary> /// Packages the response. <c>Flush()</c> would be called in this method. /// </summary> /// <param name="response">The response.</param> /// <param name="data">The data.</param> /// <param name="ex">The ex.</param> /// <param name="acceptEncoding">The accept encoding.</param> /// <param name="noBody">if set to <c>true</c> [no body].</param> /// <param name="settings">The settings.</param> public static void PackageResponse(HttpResponseBase response, object data, BaseException ex = null, string acceptEncoding = null, bool noBody = false, RestApiSettings settings = null) { if (response != null) { if (settings == null) { settings = defaultRestApiSettings; } var objectToReturn = ex != null ? (settings.EnableOutputFullExceptionInfo ? ex.ToExceptionInfo() : new SimpleExceptionInfo { Message = ex.Hint != null ? (ex.Hint.Message ?? ex.Hint.Cause) : ex.RootCause.Message, Data = data == null ? null : JObject.FromObject(data), Code = ex.Hint?.Code ?? ex.Code } as object) : data; response.Headers.Add(HttpConstants.HttpHeader.SERVERNAME, EnvironmentCore.ServerName); response.Headers.AddIfNotNull(HttpConstants.HttpHeader.TRACEID, ApiTraceContext.TraceId); response.StatusCode = (int)(ex == null ? (noBody ? HttpStatusCode.NoContent : HttpStatusCode.OK) : ex.Code.ToHttpStatusCode()); if (!noBody) { response.ContentType = "application/json"; if (settings.EnableContentCompression) { acceptEncoding = acceptEncoding.SafeToString().ToLower(); if (acceptEncoding.Contains("gzip")) { response.Filter = new System.IO.Compression.GZipStream(response.Filter, System.IO.Compression.CompressionMode.Compress); response.Headers.Remove(HttpConstants.HttpHeader.ContentEncoding); response.AppendHeader(HttpConstants.HttpHeader.ContentEncoding, "gzip"); } else if (acceptEncoding.Contains("deflate")) { response.Filter = new System.IO.Compression.DeflateStream(response.Filter, System.IO.Compression.CompressionMode.Compress); response.Headers.Remove(HttpConstants.HttpHeader.ContentEncoding); response.AppendHeader(HttpConstants.HttpHeader.ContentEncoding, "deflate"); } } response.Write(objectToReturn.ToJson(true, JsonConverters)); } response.Headers.Add(HttpConstants.HttpHeader.SERVEREXITTIME, DateTime.UtcNow.ToFullDateTimeTzString()); response.Flush(); } }
/// <summary> /// Exports the specified response. /// </summary> /// <param name="response">The response.</param> /// <param name="myPageName">Name of my page.</param> /// <param name="columns">The columns.</param> /// <param name="ds">The ds.</param> /// <Remarks> /// Created Time: 2008-8-4 10:59 /// Created By: jack_que /// Last Modified Time: /// Last Modified By: /// </Remarks> public static void Export(HttpResponseBase response, string myPageName, List<MESParameterInfo> columns, DataSet ds) { string path = AppDomain.CurrentDomain.BaseDirectory + @"\Excel\" + myPageName + ".xls"; response.Clear(); response.Buffer = true; response.Charset = "utf-8"; response.AppendHeader("Content-Disposition", "attachment;filename=" + myPageName + ".xls"); response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8"); response.ContentType = "application/ms-excel"; ExcelWriter excel = new ExcelWriter(path); try { excel.BeginWrite(); short row = 0; for (short k = 0; k < columns.Count; k++) { excel.WriteString(row, k, columns[k].ParamDisplayName); } DataTable dt = ds.Tables[0]; for (short i = 0; i < dt.Rows.Count; i++) { row++; for (short j = 0; j < columns.Count; j++) { MESParameterInfo column = columns[j]; string columnType = column.ParamType; string columnName = column.ParamName; object value = ds.Tables[0].Rows[i][columnName]; if (columnType != null && columnType.Equals("date")) { value = value.ToString().Split(new char[] { ' ' }, StringSplitOptions.None)[0]; } excel.WriteString(row, j, value.ToString()); } } } finally { excel.EndWrite(); } FileInfo file = new FileInfo(path); if (file.Exists) { response.WriteFile(path); response.Flush(); file.Delete(); } }
public static void Export(HttpResponseBase Response, string strStudentId) { HallTicketDataAccess dataaccess = new HallTicketDataAccess(); DataTable dt = dataaccess.GetHallTickets(strStudentId); Response.AddHeader("Content-Disposition", "attachment; filename=" + "PrintHalltickets.doc"); Response.Write("<html " + "xmlns:o='urn:schemas-microsoft-com:office:office' " + "xmlns:w='urn:schemas-microsoft-com:office:word'" + "xmlns='http://www.w3.org/TR/REC-html40'>" + "<head><title>Time</title>"); Response.Write("<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=UTF-8\">"); Response.Write("<meta name=ProgId content=Word.Document>"); Response.Write("<meta name=Generator content=\"Microsoft Word 9\">"); Response.Write("<meta name=Originator content=\"Microsoft Word 9\">"); Response.Write("<!--[if gte mso 9]>" + "<xml>" + "<w:WordDocument>" + "<w:View>Print</w:View>" + "<w:Zoom>90</w:Zoom>" + "<w:DoNotOptimizeForBrowser/>" + "</w:WordDocument>" + "</xml>" + "<![endif]-->"); Response.Write("<style> @page" + "{size:8.5in 11.0in; mso-first-footer:ff1; mso-footer: f1;" + " margin:0.2in 0.2in 0.2in 0.2in ; " + " mso-header-margin:.1in; " + " mso-footer-margin:.1in; mso-paper-source:0;}" + " div.Section1" + " {page:Section1;}" + "p.MsoFooter, li.MsoFooter, div.MsoFooter{margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; tab-stops:center 3.0in right 6.0in; font-size:12.0pt; font-family:'Verdana';}" + "p.MsoHeader, li.MsoHeader, div.MsoHeader {margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; tab-stops:center 3.0in right 6.0in; font-size:12.0pt; font-family:'Verdana';}" + "table#hrdftrtbl { margin:0in 0in 0in 0.1in; }" + "-->" + "</style>" + "</head>"); Response.Write("<body lang=EN-US style='tab-interval:.5in'>"); Response.Write("<table stle=\"width: 8.5in;\">"); foreach (DataRow dr in dt.Rows) { Response.Write("<tr>"); Response.Write("<td colspan=2 style=\"height: 0.25in;\">"); Response.Write("</td>"); Response.Write("</tr>"); Response.Write("<tr>"); Response.Write("<td colspan=2 align=\"center\">Exam Name</td>"); Response.Write("</tr>"); Response.Write("<tr>"); Response.Write("<td colspan=2 style=\"height: 0.25in;\">"); Response.Write("</td>"); Response.Write("</tr>"); Response.Write("<tr>"); Response.Write("<td>" + GetSideHeader("Hall Ticket Number")); Response.Write("</td>"); Response.Write("<td>" + dr["HallTicketNo"].ToString()); Response.Write("</td>"); Response.Write("</tr>"); Response.Write("<tr>"); Response.Write("<td>" + GetSideHeader("Student Name")); Response.Write("</td>"); Response.Write("<td>" + dr["Name"].ToString()); Response.Write("</td>"); Response.Write("</tr>"); Response.Write("<tr>"); Response.Write("<td>" + GetSideHeader("Father's Name")); Response.Write("</td>"); Response.Write("<td>" + dr["FatherName"].ToString()); Response.Write("</td>"); Response.Write("</tr>"); Response.Write("<tr>"); Response.Write("<td>" + GetSideHeader("School Name")); Response.Write("</td>"); Response.Write("<td>" + dr["SchoolName"].ToString()); Response.Write("</td>"); Response.Write("</tr>"); Response.Write("<tr>"); Response.Write("<td>" + GetSideHeader("Course Code")); Response.Write("</td>"); Response.Write("<td>" + dr["CourseCode"].ToString()); Response.Write("</td>"); Response.Write("</tr>"); Response.Write("<tr>"); Response.Write("<td>" + GetSideHeader("Exam Schedule")); Response.Write("</td>"); Response.Write("<td>" + dr["ExamSchedule"].ToString()); Response.Write("</td>"); Response.Write("</tr>"); Response.Write("<tr>"); Response.Write("<td>" + GetSideHeader("Exam Center Address")); Response.Write("</td>"); Response.Write("<td>" + dr["ExamCenterAddress"].ToString()); Response.Write("</td>"); Response.Write("</tr>"); } Response.Write("</table>"); Response.Write("</body></head>"); Response.Write("</html>"); Response.Flush(); }
public void TransmitComplete(HttpResponseBase response) { //TransmitFile is asynchronous make it syncronous //http://stackoverflow.com/questions/2275894/calling-response-transmitfile-from-static-method response.Flush(); }
protected override void WriteFile(HttpResponseBase response) { response.BufferOutput = false; response.Clear(); response.ClearContent(); response.ClearHeaders(); response.Cookies.Clear(); response.ContentType = ContentType; response.ContentEncoding = Encoding.Default; response.AddHeader("Content-Type", ContentType); response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", this.FileDownloadName)); byte[] buffer = new byte[4096]; using (ZipOutputStream zipOutputStream = new ZipOutputStream(response.OutputStream)) { foreach (string fileName in FilesToZip) { int folderOffset = fileName.LastIndexOf('\\'); Stream fs = System.IO.File.OpenRead(fileName); // or any suitable inputstream string entryName = fileName.Substring(folderOffset); ZipEntry entry = new ZipEntry(ZipEntry.CleanName(entryName)); entry.Size = fs.Length; // Setting the Size provides WinXP built-in extractor compatibility, // but if not available, you can set zipOutputStream.UseZip64 = UseZip64.Off instead. zipOutputStream.PutNextEntry(entry); //zipOutputStream.SetLevel(3); // 0-9 for compression level //zipOutputStream.Password(); // security int count = fs.Read(buffer, 0, buffer.Length); while (count > 0) { zipOutputStream.Write(buffer, 0, count); count = fs.Read(buffer, 0, buffer.Length); if (!response.IsClientConnected) { break; } response.Flush(); } fs.Close(); } zipOutputStream.Finish(); } //response.OutputStream.Flush(); response.End(); }
private static void RelayContent( string url, HttpRequestBase request, HttpResponseBase response, ILogger logger ) { var uri = new Uri(url); var serviceRequest = WebRequest.Create(uri); serviceRequest.Method = request.HttpMethod; serviceRequest.ContentType = request.ContentType; //pull in input if (serviceRequest.Method != "GET") { request.InputStream.Position = 0; var inStream = request.InputStream; Stream webStream = null; try { //copy incoming request body to outgoing request if (inStream != null && inStream.Length > 0) { serviceRequest.ContentLength = inStream.Length; webStream = serviceRequest.GetRequestStream(); inStream.CopyTo(webStream); } } finally { if (null != webStream) { webStream.Flush(); webStream.Close(); } } } //get and push output try { using (var resourceResponse = (HttpWebResponse)serviceRequest.GetResponse()) { using (var resourceStream = resourceResponse.GetResponseStream()) { resourceStream.CopyTo(response.OutputStream); } response.ContentType = uri.IsFile ? MimeTypeMap.GetMimeType(Path.GetExtension(uri.LocalPath)) : resourceResponse.ContentType; } } catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError) { var resourceResponse = ex.Response as HttpWebResponse; if (resourceResponse != null) { response.StatusCode = (int)resourceResponse.StatusCode; response.ContentType = resourceResponse.ContentType; } else { response.StatusCode = 500; response.ContentType = ex.Response.ContentType; logger.Error(ex, "Proxy module protocol error: {0}", ex.Message); } } else { response.StatusCode = 500; response.ContentType = ex.Response.ContentType; logger.Error(ex, "Proxy module error: {0}", ex.Message); } } finally { response.Flush(); response.End(); } }
private static void GenerarPdf7(DataTable dt, string titulo, string nombreDoc, EmpresaDTO objEmpresa, DateTime? FechaFin, HttpResponseBase Response) { GridView gv = new GridView(); gv.DataSource = dt; gv.AllowPaging = false; gv.DataBind(); if (dt.Rows.Count > 0) { PintarCabeceraTabla(gv); //PintarIntercaladoCategorias(gv); AddSuperHeader(gv, titulo + " - Empresa:" + objEmpresa.Nombre); //Cabecera principal AddWhiteHeader(gv, 1, ""); AddWhiteHeader(gv, 2, "FECHA LIMITE: " + FechaFin.GetValueOrDefault().ToShortDateString()); //PintarCategorias(gv); Response.ClearContent(); Response.Buffer = true; Response.AddHeader("content-disposition", "attachment; filename=" + nombreDoc + "_" + objEmpresa.Nombre + "_" + DateTime.Now.ToString("dd-MM-yyyy") + ".xls"); Response.ContentType = "application/ms-excel"; Response.Charset = ""; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); gv.RenderControl(htw); Response.Output.Write(sw.ToString()); Response.Flush(); Response.End(); htw.Close(); sw.Close(); } }