public void RelativeRootInWebApp() { var request = new System.Web.HttpRequest("~/abc.html", "http://www.google.com/", "?123=123"); var response = new System.Web.HttpResponse(new StringWriter()); var context = new System.Web.HttpContext(request, response); System.Web.HttpContext.Current = context; GetMockCache("~/temp"); }
/// <summary> /// Create an Excel file, and write it out to a MemoryStream (rather than directly to a file) /// </summary> /// <param name="dt">DataTable 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>True if it was created succesfully, otherwise false.</returns> public static bool CreateExcelDocument(DataSet ds, string filename, System.Web.HttpResponse Response) { try { CreateExcelDocumentAsStream(ds, filename, Response); return(true); } catch (Exception ex) { Trace.WriteLine("Failed, exception thrown: " + ex.Message); return(false); } }
/// <summary> /// 把DataTable导出为Word文件 /// </summary> /// <param name="page">Page</param> /// <param name="fileName">Word文件名(不包括后缀*.doc)</param> /// <param name="dtbl">将要被导出的DataTable对象</param> /// <returns></returns> public static bool DataTableToWord(System.Web.HttpResponse response, string fileName, DataTable dtbl) { response.Clear(); response.Buffer = true; response.Charset = "UTF-8"; response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName + ".doc"); response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); response.ContentType = "application/ms-word"; //page.EnableViewState = false; response.Write(DataTableToHtmlTable(dtbl)); response.End(); return(true); }
public override void Response(System.Web.HttpResponse response) { #if NET40 JavaScriptSerializer serializer = new JavaScriptSerializer(); var output = new StringBuilder(); serializer.Serialize(_model, output); response.ContentType = "application/json"; response.Write(output.ToString()); #else throw new NotImplementedException("ToDo: use JSON.NET for <4.0"); #endif }
public Boolean ExportToRtf(String clientFileName, System.Web.HttpResponse webResponse, System.Web.HttpCookie cookie) { //lm.Comol.Core.DomainModel.DocTemplate.Helper.HelperExportRTF _Helper = new lm.Comol.Core.DomainModel.DocTemplate.Helper.HelperExportRTF(); //return false; //return _Helper.ExportToRtf(GetTemplate(), clientFileName, webResponse); //, View.GetSysHeader(), View.GetSysFooter()); Helpers.HelperExportRTF _Helper = new Helpers.HelperExportRTF(); //Helpers.HelperExportRTF _Helper = new Helpers.HelperExportRTF(); //lm.Comol.Core.DomainModel.DocTemplate.Helper.HelperExportPDF _Helper = new lm.Comol.Core.DomainModel.DocTemplate.Helper.HelperExportPDF(); return(_Helper.ExportToRtf(GetTemplate(), clientFileName, webResponse, cookie)); }
public static MerchantTribe.Commerce.RequestContext GetFakeRequestContext(string fileName, string url, string querystring) { var result = new MerchantTribe.Commerce.RequestContext(); var request = new System.Web.HttpRequest(fileName, url, querystring); var response = new System.Web.HttpResponse(new System.IO.StringWriter()); System.Web.HttpContext httpContext = new System.Web.HttpContext(request, response); System.Web.HttpContextWrapper httpWrapper = new System.Web.HttpContextWrapper(httpContext); result.RoutingContext = new System.Web.Routing.RequestContext(httpWrapper, new System.Web.Routing.RouteData()); return result; }
protected void Button1_Click(object sender, EventArgs e) { CreateBarcodePdf(); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "application/pdf"; response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";"); response.TransmitFile(AppPath + @"Files\Barcode\" + FileName); response.Flush(); //File.Delete(FilePath); //File.Delete(FilePath + ".gif"); response.End(); }
protected internal override void CustomPostRender(System.Web.HttpResponse response, bool isRefreshRequest) { base.CustomPostRender(response, isRefreshRequest); if (_needToActivate) { response.Write(GetReference() + ".activate();\n"); _needToActivate = false; } if (_needToFocus) { response.Write(GetReference() + ".focus();\n"); _needToFocus = false; } }
/// <summary> /// Resposne via OutputStream /// </summary> /// <param name="package"></param> /// <param name="Response"></param> public static void saveAs(rf.OfficeOpenXml.ExcelPackage package, System.Web.HttpResponse Response, string name = "temp.xlsx", string cookieKey = defaultDownloadedCookieKey, string cookieValue = defaultDownloadedCookieValue) { try { Response.Cookies.Add(new System.Web.HttpCookie(cookieKey, cookieValue)); Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("content-disposition", string.Format("attachment;filename={0}", name)); Response.Clear(); package.SaveAs(Response.OutputStream); } catch (Exception ex) { } }
public static MerchantTribe.Commerce.RequestContext GetFakeRequestContext(string fileName, string url, string querystring) { var result = new MerchantTribe.Commerce.RequestContext(); var request = new System.Web.HttpRequest(fileName, url, querystring); var response = new System.Web.HttpResponse(new System.IO.StringWriter()); System.Web.HttpContext httpContext = new System.Web.HttpContext(request, response); System.Web.HttpContextWrapper httpWrapper = new System.Web.HttpContextWrapper(httpContext); result.RoutingContext = new System.Web.Routing.RequestContext(httpWrapper, new System.Web.Routing.RouteData()); return(result); }
protected internal virtual void CustomPostRender(System.Web.HttpResponse response, bool isRefreshRequest) { if (isRefreshRequest) { foreach (var item in _appliedMethods.Get()) { response.Write(item.GetExpression(this)); } } foreach (var item in _newMethods.Get()) { response.Write(item.GetExpression(this)); } }
public static bool CreateExcelDocument <T>(List <T> list, string filename, System.Web.HttpResponse Response) { try { DataSet ds = new DataSet(); ds.Tables.Add(ListToDataTable(list)); CreateExcelDocumentAsStream(ds, filename, Response); return(true); } catch (Exception ex) { return(false); } }
/// <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) { try { 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"; Response.AppendHeader("content-length", stream.Length.ToString()); byte[] data1 = new byte[stream.Length]; stream.Read(data1, 0, data1.Length); stream.Close(); Response.BinaryWrite(data1); Response.Flush(); // Feb2015: Needed to replace "Response.End();" with the following 3 lines, to make sure the Excel was fully written to the Response System.Web.HttpContext.Current.Response.Flush(); System.Web.HttpContext.Current.Response.SuppressContent = true; System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest(); return(true); } catch (Exception ex) { Trace.WriteLine("Failed, exception thrown: " + ex.Message); // Display an error on the webpage. System.Web.UI.Page page = System.Web.HttpContext.Current.CurrentHandler as System.Web.UI.Page; page.ClientScript.RegisterStartupScript(page.GetType(), "log", "console.log('Failed, exception thrown: " + ex.Message + "')", true); return(false); } }
public override void Execute(System.Web.HttpResponse response) { var data = new byte[File.Length]; //TODO: very long files will blow up here File.Read(data, 0, (int)File.Length); string template = Encoding.UTF8.GetString(data); var presenter = RunPresenter(Path); var result = RazorEngine.Razor.Parse(template, new { name = presenter.GetType().Name }); response.Write(result); }
protected void btnDownload_Click(object sender, EventArgs e) { //string ten = ViewState["FileName"].ToString().Trim(); string filePath = Format(ViewState["FileName"].ToString().Trim()); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = ContentType; response.AddHeader("Content-Disposition", "attachment; filename=" + filePath + ";"); response.TransmitFile(Server.MapPath("~/Files/" + filePath)); response.Flush(); response.End(); }
public static bool CreateExcelDocument(DataTable dt, string filename, System.Web.HttpResponse Response) { try { DataSet ds = new DataSet(); ds.Tables.Add(dt); CreateExcelDocument(ds, filename, Response); ds.Tables.Remove(dt); return(true); } catch (Exception ex) { return(false); } }
/// <summary> /// Handles a fatal server exception. /// </summary> public static void HandleFatalServerException() { System.Web.HttpResponse resp = System.Web.HttpContext.Current.Response; resp.ClearContent(); resp.StatusCode = 400; resp.AddHeader("Status", "400 Bad Request"); // resp.StatusDescription = "Not Found"; // resp.Write("404 Not Found"); //resp.Flush(); resp.Write("<html><body><strong>The page that you requested caused a server error.</strong><p><em>Please try back later, or try visiting our <a href=\"" + CmsContext.ApplicationPath + "\">home page</a>.</em></p></body></html>"); resp.End(); return; }
public static bool CreateExcelDocument <T>(List <T> list, string filename, System.Web.HttpResponse Response) { try { DataSet ds = new DataSet(); ds.Tables.Add(ListToDataTable(list)); CreateExcelDocumentAsStream(ds, filename, Response); return(true); } catch (Exception ex) { System.IO.File.WriteAllText(@"D:\DSPBlackRock\errormessage.txt", "Failed, exception thrown: " + ex.Message); return(false); } }
public static void RedirectToErrorPage(ErrorTypes errorType, System.Web.HttpResponse response) { if (errorType == ErrorTypes.Generic) { response.Redirect("~/Error"); } else if (errorType == ErrorTypes.Product) { response.Redirect("~/Error?type=product"); } else if (errorType == ErrorTypes.Category) { response.Redirect("~/Error?type=category"); } }
public static bool CreateExcelDocument <T>(List <T> list, string filename, System.Web.HttpResponse Response) { try { DataSet ds = new DataSet(); ds.Tables.Add(ListToDataTable(list)); CreateExcelDocumentAsStream(ds, filename, Response); return(true); } catch (Exception ex) { Trace.WriteLine("Failed, exception thrown: " + ex.Message); return(false); } }
/// <summary> /// สำหรับ Zip ไฟล์และ Download /// </summary> /// <param name="httpResponse">Response ของ Page</param> /// <param name="reqDate">วันที่ต้องการ Download</param> /// <param name="tempFolder">Temp Folder</param> public void DownloadLicenseZip(System.Web.HttpResponse httpResponse, DateTime reqDate, string tempFolder) { //เตรียม Directory และ ไฟล์ที่ต้องการ Download string dir = InitRequestLicenseFileToDownload(tempFolder, reqDate); //สำหรับเก็บ Folder ที่ต้อง Zip เพื่อวนหาไฟล์ใน Folder List <string> list = new List <string>(); list.Add(dir); //วนหา Folder ที่ต้อง Zip และ SubFolder ที่อยู่ภายใน GetAllFiles(list, dir); string folderName = string.Empty; //สร้าง Instantce Zip using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile()) { //กำหนด Option Endcode zip.AlternateEncodingUsage = ZipOption.AsNecessary; //วนเ Folder และ SubFolder for (int i = 0; i < list.Count; i++) { //Folder ปัจจุบัน DirectoryInfo dInfo = new DirectoryInfo(list[i]); folderName += (i == 0 ? "" : "\\") + dInfo.Name; //สร้าง Folder ใน Zip zip.AddDirectoryByName(folderName); //วน Add File ใน Folder foreach (string f in Directory.GetFiles(list[i])) { zip.AddFile(f, folderName); } } httpResponse.Clear(); httpResponse.BufferOutput = false; string zipName = String.Format("{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss")); httpResponse.ContentType = "application/zip"; httpResponse.AddHeader("content-disposition", "attachment; filename=" + zipName); zip.Save(httpResponse.OutputStream); httpResponse.End(); } }
protected internal override void CustomPostRender(System.Web.HttpResponse response, bool isRefreshRequest) { base.CustomPostRender(response, isRefreshRequest); foreach (var rec in _openURL) { if (rec.isBlank) { response.Write("window.open('" + rec.path + "', '_blank');"); } else { response.Write("window.open('" + rec.path + "');"); } } _openURL.Clear(); }
// calls SetupResponse to set header and cache and saves Excel file to HttpResponse protected internal void SaveExcelBook(System.Web.HttpResponse response) { try { ISDExcelBook.Save(response.OutputStream, response); } catch (Exception ex) { throw ex; } // Need to call Response.End() so nothing will be attached to a file // System.Web.HttpResponse.End() function will throw System.Threading.ThreadAbortException // indicating that the current response ends prematurely - that's what we want response.End(); }
internal static void ThrowWmsException(WmsExceptionCode code, string Message) { System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response; Response.Clear(); Response.ContentType = "text/xml"; Response.Write("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n"); Response.Write("<ServiceExceptionReport version=\"1.3.0\" xmlns=\"http://www.opengis.net/ogc\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.opengis.net/ogc http://schemas.opengis.net/wms/1.3.0/exceptions_1_3_0.xsd\">\n"); Response.Write("<ServiceException"); if (code != WmsExceptionCode.NotApplicable) { Response.Write(" code=\"" + code.ToString() + "\""); } Response.Write(">" + Message + "</ServiceException>\n"); Response.Write("</ServiceExceptionReport>"); Response.End(); }
public void ProcessRequest(HttpContext context) { // retrieve your xbook System.IO.MemoryStream ms = new System.IO.MemoryStream(); xbook.Save(ms, C1.C1Excel.FileFormat.Biff8); xbook.Dispose(); ms.Position = 0; 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=CategoryReport.xls"); Response.BufferOutput = true; Response.OutputStream.Write(ms.ToArray(), 0, (int)ms.Length); response.Flush(); response.End(); }
internal static void CreatePDFDocument(DataTable dt, string excelFilename, System.Web.HttpResponse Response) { // // For PDF export we are using the free open-source iTextSharp library. // Document pdfDoc = new Document(); MemoryStream pdfStream = new MemoryStream(); PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, pdfStream); pdfDoc.Open();//Open Document to write pdfDoc.NewPage(); iTextSharp.text.Font font8 = FontFactory.GetFont("ARIAL", 7); PdfPTable PdfTable = new PdfPTable(dt.Columns.Count); PdfPCell PdfPCell = null; //Add Header of the pdf table for (int column = 0; column < dt.Columns.Count; column++) { PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Columns[column].Caption, font8))); PdfTable.AddCell(PdfPCell); } //How add the data from datatable to pdf table for (int rows = 0; rows < dt.Rows.Count; rows++) { for (int column = 0; column < dt.Columns.Count; column++) { PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), font8))); PdfTable.AddCell(PdfPCell); } } PdfTable.SpacingBefore = 15f; // Give some space after the text or it may overlap the table pdfDoc.Add(PdfTable); // add pdf table to the document pdfDoc.Close(); pdfWriter.Close(); Response.ClearContent(); Response.ClearHeaders(); Response.ContentType = "application/pdf"; Response.AppendHeader("Content-Disposition", "attachment; filename=" + excelFilename); Response.BinaryWrite(pdfStream.ToArray()); Response.End(); }
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> /// 读取一个多键cookie. 如果读取失败, 返回空 /// </summary> /// <param name="cookieName"></param> /// <param name="key">要读取的键名</param> /// <param name="request"></param> /// <param name="response"></param> /// <param name="server"></param> /// <returns>返回读到的值或空.</returns> public static string ReadCookie(string cookieName, string key, System.Web.HttpRequest request, System.Web.HttpResponse response, System.Web.HttpServerUtility server) { if (CheckCookie(cookieName, request) == false) { return(""); } System.Web.HttpCookie objCookie = request.Cookies[cookieName]; try { return(server.UrlDecode(objCookie.Values[key])); } catch (Exception ex) { return(""); } }
//download file public void saveFile(System.Web.HttpResponse Response, string PathfileName) { string filename = PathfileName; if (filename != "") { string path = filename; System.IO.FileInfo file = new System.IO.FileInfo(path); if (file.Exists) { Response.Clear(); Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name); Response.AddHeader("Content-Length", file.Length.ToString()); Response.ContentType = "application/octet-stream"; Response.WriteFile(file.FullName); Response.End(); } } }
public void StartExport(System.Web.HttpResponse response, bool exportRawValues) { if (response == null) { return; } string fileName = Title + ".csv"; SetupResponse(response, fileName); response.ContentType = "text/plain"; Writer = new StreamWriter(response.OutputStream, System.Text.Encoding.UTF8); // First write out the Column Headers this.WriteColumnHeader(exportRawValues); Writer.WriteLine(); }
/// <summary> /// When possible, writes the file directly to the response. /// </summary> /// <param name="filePath"></param> /// <param name="response"></param> public override void TransmitFile(string filePath, System.Web.HttpResponse response) { Utilities.ValidateParameterNonNull("filePath", filePath); Utilities.ValidateParameterNotEmpty("filePath", filePath); Utilities.ValidateParameterNonNull("response", response); // If the file is the manifest, then copy the streams (ie, do it slowly). if (IsManifest(filePath)) { using (Stream manifestStream = GetFileStream(filePath)) { Utilities.CopyStream(manifestStream, m_impersonationBehavior, response.OutputStream, m_impersonationBehavior); } return; } // The file was not the manifest, so ask the package reader to send it m_fsPackageReader.TransmitFile(filePath, response, true); }
/// <summary> /// 修改一个多键cookie的值. /// </summary> /// <param name="cookieName"></param> /// <param name="key"></param> /// <param name="value"></param> /// <param name="request"></param> /// <param name="response"></param> /// <param name="server"></param> /// <returns></returns> public static bool ChangeKeyValue(string cookieName, string key, string value, System.Web.HttpRequest request, System.Web.HttpResponse response, System.Web.HttpServerUtility server) { if (CheckCookie(cookieName, request) == false) { return(false); } try { System.Web.HttpCookie objCookie = request.Cookies[cookieName]; objCookie.Values[key] = server.UrlEncode(value); response.AppendCookie(objCookie); } catch (Exception ex) { return(false); } return(true); }
public XmlRpcHttpResponse(System.Web.HttpResponse response) { m_resp = response; }
public Export() { appType = "Web"; response = System.Web.HttpContext.Current.Response; }
public Export(string ApplicationType) { appType = ApplicationType; if (appType != "Web" && appType != "Win") throw new Exception("Provide valid application format (Web/Win)"); if (appType == "Web") response = System.Web.HttpContext.Current.Response; }