public override void OnResultExecuting(ResultExecutingContext filterContext) { if (filterContext.Result is INoCompressResult) { return; } System.Web.HttpRequestBase request = filterContext.HttpContext.Request; string acceptEncoding = request.Headers["Accept-Encoding"]; if (string.IsNullOrEmpty(acceptEncoding)) { return; } acceptEncoding = acceptEncoding.ToUpperInvariant(); System.Web.HttpResponseBase response = filterContext.HttpContext.Response; if (acceptEncoding.Contains("GZIP")) { response.AppendHeader("Content-encoding", "gzip"); response.Filter = new GZipStream(response.Filter, CompressionMode.Compress); } else if (acceptEncoding.Contains("DEFLATE")) { response.AppendHeader("Content-encoding", "deflate"); response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress); } }
private void initPdfWriter02(System.Web.HttpResponseBase Response, Stream stream) { if ((int)_pdfRptData.DocumentPreferences.ConformanceLevel > (int)PdfXConformance.PDFX32002) { PdfWriter = PdfAWriter.GetInstance(PdfDoc, stream, PdfConformance.PdfXToPdfA[_pdfRptData.DocumentPreferences.ConformanceLevel]); } else { //PdfWriter = PdfWriter.GetInstance(PdfDoc, stream); PdfWriter = PdfWriter.GetInstance(PdfDoc, Response.OutputStream); } var pageEvents = new PageEvents { PdfRptHeader = _pdfRptData.Header, PageSetup = _pdfRptData.DocumentPreferences, PdfRptFooter = _pdfRptData.Footer, CurrentRowInfoData = LastRenderedRowData, ColumnSummaryCellsData = ColumnSummaryCellsData }; PdfWriter.PageEvent = pageEvents; _pdfConformance = new PdfConformance { PdfWriter = PdfWriter, PageSetup = _pdfRptData.DocumentPreferences }; _pdfConformance.SetConformanceLevel(); }
protected override void WriteFile(System.Web.HttpResponseBase response) { response.ContentType = base.ContentType; Stream outputStrream = response.OutputStream; using (var memStream = new MemoryStream()) { if (string.IsNullOrEmpty(this.Data) == true) { // バイナリファイルの出力 using (BinaryWriter writer = new BinaryWriter(memStream)) { writer.Write(this.ByteData, 0, this.ByteData.Length); writer.Flush(); outputStrream.Write(memStream.GetBuffer(), 0, (int)memStream.Length); } } else { // テキストファイルの出力 using (var writer = new StreamWriter(memStream, this._encode)) { writer.Write(this.Data); writer.Flush(); response.ContentEncoding = this._encode; outputStrream.Write(memStream.GetBuffer(), 0, (int)memStream.Length); } } } }
public override void ExecuteResult(ControllerContext context) { System.Web.HttpResponseBase response = context.HttpContext.Response; response.StatusCode = 304; response.StatusDescription = "Not Modified"; response.SuppressContent = true; }
protected override void WriteFile(System.Web.HttpResponseBase response) { int _bufferSize = (int)Math.Round(1024 * this.rate); byte[] buffer = new byte[_bufferSize]; Stream outputStream = response.OutputStream; using (var stream = File.OpenRead(FileName)) { response.AddHeader("Cache-control", "private"); response.AddHeader("Content-Type", "application/octet-stream"); response.AddHeader("Content-Length", stream.Length.ToString()); response.AddHeader("Content-Disposition", String.Format("filename={0}", new FileInfo(FileName).Name)); response.Flush(); while (true) { if (!response.IsClientConnected) { break; } int bytesRead = stream.Read(buffer, 0, _bufferSize); if (bytesRead == 0) { break; } outputStream.Write(buffer, 0, bytesRead); response.Flush(); Thread.Sleep(1000); } } }
protected override void WriteFile(System.Web.HttpResponseBase response) { var items = new List <SyndicationItem>(); foreach (Dinner d in this.Dinners) { string contentString = String.Format("{0} with {1} on {2:MMM dd, yyyy} at {3}. Where: {4}, {5}", d.Description, d.HostedBy, d.EventDate, d.EventDate.ToShortTimeString(), d.Address, d.Country); var item = new SyndicationItem( title: d.Title, content: contentString, itemAlternateLink: new Uri("http://nrddnr.com/" + d.DinnerId), id: "http://nrddnr.com/" + d.DinnerId, lastUpdatedTime: d.EventDate.ToUniversalTime() ); item.PublishDate = d.EventDate.ToUniversalTime(); item.Summary = new TextSyndicationContent(contentString, TextSyndicationContentKind.Plaintext); items.Add(item); } SyndicationFeed feed = new SyndicationFeed( this.Title, this.Title, /* Using Title also as Description */ currentUrl, items); Rss20FeedFormatter formatter = new Rss20FeedFormatter(feed); using (XmlWriter writer = XmlWriter.Create(response.Output)) { formatter.WriteTo(writer); } }
/// <summary> /// </summary> /// <param name="skey">Secret key.</param> /// <param name="userId">Unique user ID.</param> /// <param name="userName">User name.</param> /// <param name="roomId">Unique room ID.</param> /// <param name="roomName">Room name.</param> /// <param name="expiration">Token expiration time in seconds.</param> /// <param name="userEmail">User email address (visible in tooltip over user name in history, must be unique when used within the scope of a given public key. (optional)</param> /// <param name="welcomeText">Text message to be sent out by welcome robot when room is created. (optional)</param> /// <param name="robotName">Name of welcome robot, if not specified defaults to 'Welcome Robot'. (optional)</param> /// <returns></returns> public static object SetInfo(System.Web.HttpResponseBase Response, string skey, string userId, string userName, string roomId, string roomName, int expiration, string userEmail = "__useremail__", string welcomeText = "__welcometext__", string robotName = "__robotname__") { var payload = new Dictionary <string, object>(); payload.Add("exp", (Math.Round(GetTime() / 1000.00)) + expiration); payload.Add("user_id", userId); payload.Add("user_name", userName); payload.Add("room_id", roomId); payload.Add("room_name", roomName); if (!string.IsNullOrEmpty(userEmail) || userEmail == "__useremail__") { payload.Add("user_email", userEmail); } if (!string.IsNullOrEmpty(welcomeText) || welcomeText == "__welcometext__") { payload.Add("welcome_text", welcomeText); } if (!string.IsNullOrEmpty(robotName) || robotName == "__robotname__") { payload.Add("welcome_robot_name", robotName); } var cookie = new System.Web.HttpCookie("KATO_ADHOC_TOKEN"); cookie.Value = JWT.JsonWebToken.Encode(payload, skey, JWT.JwtHashAlgorithm.HS256); Response.Cookies.Add(cookie); return(Response); }
/// <summary> /// Uses the values in the <see cref="RoutingContext"/> to modify /// the servers response. /// F.x. return an http status code of 404 not found /// or redirect the client to a new URL. /// </summary> /// <param name="context"> /// The routing context returned by React Router. /// It contains new values for the server response. /// </param> /// <param name="Response">The response object to use.</param> public static void ModifyResponse(RoutingContext context, HttpResponse Response) { var statusCode = context.status.Value; // 300-399 if (statusCode >= 300 && statusCode < 400) { if (!string.IsNullOrEmpty(context.url)) { if (statusCode == 301) { #if NET451 Response.RedirectPermanent(context.url); #else Response.Redirect(context.url, true); #endif } else // 302 and all others { Response.Redirect(context.url); } } else { throw new ReactRouterException("Router requested redirect but no url provided."); } } else { Response.StatusCode = statusCode; } }
public static void Generate(System.Web.HttpResponseBase Response, Campaign campaign, CampaignTracking campaignTracking) { var metric = CampaignTrackingMetricVm.FromCampaignTracking(campaign, campaignTracking); var urls = CampaignTrackingMetricDetailVm.FromCampaignTracking(campaign, campaignTracking); ExcelPackage excel = new ExcelPackage(); var workSheet = excel.Workbook.Worksheets.Add("Strat Metrics"); workSheet.Cells[1, 1].LoadFromCollection(metric, true); workSheet.Cells[2, 8].Style.Numberformat.Format = "0.00%"; workSheet.Cells[2, 11].Style.Numberformat.Format = "0.00%"; workSheet.Cells[2, 12].Style.Numberformat.Format = "0.00%"; var workSheet2 = excel.Workbook.Worksheets.Add("Strat URLs"); workSheet2.Cells[1, 1].LoadFromCollection(urls, true); using (var memoryStream = new MemoryStream()) { string orderNumber = campaign.ReBroadcasted ? $"{campaign.ReBroadcastedOrderNumber}" : $"{campaign.OrderNumber}"; string fileName = $"{orderNumber}report.xlsx"; Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader($"content-disposition", $"attachment; filename={fileName}"); excel.SaveAs(memoryStream); memoryStream.WriteTo(Response.OutputStream); Response.Flush(); Response.End(); } }
protected override void WriteFile(System.Web.HttpResponseBase response) { ZipOutputStream outputStream = new ZipOutputStream(response.OutputStream); outputStream.IsStreamOwner = false; byte[] buffer = new byte[4096]; string[] array = this.files; for (int i = 0; i < array.Length; i++) { string file = array[i]; using (System.IO.FileStream stream = new System.IO.FileStream(file, System.IO.FileMode.Open)) { ZipEntry zipEntry = new ZipEntry(System.IO.Path.GetFileName(file)); outputStream.PutNextEntry(zipEntry); while (true) { int count = stream.Read(buffer, 0, 4096); if (count == 0) { break; } outputStream.Write(buffer, 0, count); } outputStream.CloseEntry(); } } outputStream.Close(); }
public override void ExecuteResult(System.Web.Mvc.ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } if (this.JsonRequestBehavior == System.Web.Mvc.JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException("JSON GET is not allowed"); } System.Web.HttpResponseBase response = context.HttpContext.Response; response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType; if (this.ContentEncoding != null) { response.ContentEncoding = this.ContentEncoding; } if (this.Data == null) { return; } var scriptSerializer = Newtonsoft.Json.JsonSerializer.Create(this.Settings); using (var sw = new System.IO.StringWriter()) { scriptSerializer.Serialize(sw, this.Data); response.Write(sw.ToString()); } }
public static RenderMeta SetResponseCode( this RenderMeta renderMeta , System.Web.HttpResponseBase response ) { response.StatusCode = renderMeta.Code; return(renderMeta); }
public override void ExecuteResult(ControllerContext context) { System.Web.HttpResponseBase response = context.HttpContext.Response; response.ContentType = ResultContentType; response.Buffer = false; System.IO.Stream stream = context.HttpContext.Response.OutputStream; _serializer.SerializeAsync(Data, stream).GetAwaiter().GetResult(); response.End(); }
/// <summary> /// Initializes a new instance of the <see cref="HttpResponseFeature"/> class. /// </summary> /// <param name="response">ASP .NET non-core <see cref="System.Web.HttpContext"/> to wrap.</param> public HttpResponseFeature(System.Web.HttpResponseBase response) { this.response = response; this.startingCallbacks = new List <CallbackMethod>(); this.completedCallbacks = new List <CallbackMethod>(); this.headers = new HttpResponseHeaderDictionary(response); }
protected override void WriteFile(System.Web.HttpResponseBase response) { response.Clear(); response.AddHeader("content-disposition", "attachment; filename=" + DownloadedFilename); response.ContentType = this.ContentType; response.WriteFile(Path); response.Flush(); System.IO.File.Delete(Path); response.End(); }
public override bool SendContent(string url, System.Web.HttpResponseBase response) { if (fileList.ContainsKey(url)) { fileList[url] = DateTime.Now; return(base.SendContent(url, response)); } return(false); }
/// <summary> /// /// </summary> /// <param name="response"></param> protected override void WriteFile(System.Web.HttpResponseBase response) { if (this.Stream == null) { this.Stream = new MemoryStream(); } this.Stream.Position = 0; this.Stream.CopyTo(response.OutputStream); }
private void runInReleaseMode02(System.Web.HttpResponseBase Response) { new Document(DocumentSettings.GetPageSizeAndColor(_pdfRptData.DocumentPreferences), _pdfRptData.DocumentPreferences.PagePreferences.Margins.Left, _pdfRptData.DocumentPreferences.PagePreferences.Margins.Right, _pdfRptData.DocumentPreferences.PagePreferences.Margins.Top, _pdfRptData.DocumentPreferences.PagePreferences.Margins.Bottom) .SafeUsingBlock(pdfDisposable => { PdfDoc = pdfDisposable; createPdf02(Response); }); }
/// <summary> /// Start generating the report based on the PdfRptData /// </summary> public void GeneratePdf02(bool debugMode, System.Web.HttpResponseBase Response) { checkNullValues(); if (debugMode) { runInDebugMode(); } else { runInReleaseMode02(Response); } }
public override void ExecuteResult(ControllerContext context) { System.Web.HttpResponseBase response = context.HttpContext.Response; System.Web.HttpRequestBase request = context.HttpContext.Request; string url = request.Url.OriginalString; ViewData["RequestedUrl"] = url; ViewData["ReferrerUrl"] = (request.UrlReferrer != null && request.UrlReferrer.OriginalString != url) ? request.UrlReferrer.OriginalString : null; response.StatusCode = 404; // Prevent IIS7 from overwriting our error page! response.TrySkipIisCustomErrors = true; base.ExecuteResult(context); }
protected override void WriteFile(System.Web.HttpResponseBase response) { SyndicationFeed feed = new SyndicationFeed( this.title, this.description, currentUrl, items); var formatter = new Atom10FeedFormatter(feed); using (XmlWriter writer = XmlWriter.Create(response.Output)) { formatter.WriteTo(writer); } }
public static bool CreateExcelDocument <T>(List <T> list, string filename, System.Web.HttpResponseBase 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> /// Construtor padrão. /// </summary> /// <param name="context"></param> public HttpContext(Microsoft.Owin.IOwinContext context, System.Web.HttpRequestBase request, System.Web.HttpResponseBase response) { _request = request; _response = response; _items = new System.Collections.Hashtable(); _items["owin.Environment"] = context; if (Colosoft.Runtime.PlatformHelper.IsRunningOnMono) { System.Web.WebPages.BrowserHelpers.SetOverriddenBrowser(this, "Mozilla/4.0 (compatible; MSIE 6.1; Windows XP)"); } else { System.Web.WebPages.BrowserHelpers.SetOverriddenBrowser(this, System.Web.WebPages.BrowserOverride.Desktop); } }
public override void OnResultExecuting(ResultExecutingContext filterContext) { filterContext.HttpContext.Response.Buffer = true; System.Web.HttpResponseBase arg_34_0 = filterContext.HttpContext.Response; System.DateTime now = System.DateTime.Now; arg_34_0.ExpiresAbsolute = now.AddSeconds(-1.0); filterContext.HttpContext.Response.Expires = -1; System.Web.HttpCachePolicyBase arg_72_0 = filterContext.HttpContext.Response.Cache; now = System.DateTime.Now; arg_72_0.SetExpires(now.AddSeconds(-1.0)); filterContext.HttpContext.Response.Cache.SetNoServerCaching(); filterContext.HttpContext.Response.Cache.SetNoStore(); filterContext.HttpContext.Response.CacheControl = "no-cache"; filterContext.HttpContext.Response.AddHeader("Pragma", "no-cache"); filterContext.HttpContext.Response.AddHeader("cache-ctrol", "no-cache"); }
public override void ExecuteResult(System.Web.Mvc.ControllerContext context) { if (context == null) { throw (new System.ArgumentNullException("context")); } //if ((JsonRequestBehavior == System.Web.Mvc.JsonRequestBehavior.DenyGet) && // (string.Equals(context.HttpContext.Request.HttpMethod, "GET", System.StringComparison.OrdinalIgnoreCase))) //{ // throw (new System.InvalidOperationException // ("This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.")); //} System.Web.HttpResponseBase response = context.HttpContext.Response; if (string.IsNullOrWhiteSpace(ContentType) == false) { response.ContentType = ContentType; } else { response.ContentType = "application/json"; } if (ContentEncoding != null) { response.ContentEncoding = ContentEncoding; } if (Data != null) { var writer = new Newtonsoft.Json.JsonTextWriter(response.Output) { Formatting = Formatting }; var serializer = Newtonsoft.Json.JsonSerializer.Create(SerializerSettings); serializer.Serialize(writer, Data); writer.Flush(); } }
public static void Generate(System.Web.HttpResponseBase Response, string whiteLabel, List <Campaign> campaigns) { ExcelPackage excel = new ExcelPackage(); var workSheet = excel.Workbook.Worksheets.Add(whiteLabel); List <CustomerOrdersStatusVm> customerOrders = new List <CustomerOrdersStatusVm>(); foreach (var campaign in campaigns) { customerOrders.Add(CustomerOrdersStatusVm.FromCampaign(campaign)); } workSheet.Cells[1, 1].LoadFromCollection(customerOrders, true); var headerRowComplete = workSheet.Row(1); headerRowComplete.Style.Font.Size = 13; headerRowComplete.Style.Font.Bold = true; int Row = 2; foreach (var campaign in campaigns) { var rowComplete = workSheet.Row(Row); rowComplete.Style.Fill.PatternType = ExcelFillStyle.Solid; if (campaign.Status == (int)CampaignStatus.Monitoring) { rowComplete.Style.Fill.BackgroundColor.SetColor(Color.DarkOrange); } else { rowComplete.Style.Fill.BackgroundColor.SetColor(Color.MediumPurple); } Row++; } using (var memoryStream = new MemoryStream()) { Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("content-disposition", "attachment; filename=" + whiteLabel + "OrdersReport.xlsx"); excel.SaveAs(memoryStream); memoryStream.WriteTo(Response.OutputStream); Response.Flush(); Response.End(); } }
/** * */ public void downloadExcel(System.Web.HttpResponseBase OResponse, System.Web.UI.WebControls.GridView OGrid, string nomeDownload) { OResponse.ClearContent(); OResponse.Buffer = true; OResponse.AddHeader("content-disposition", "attachment; filename=" + nomeDownload); OResponse.ContentType = "application/ms-excel"; OResponse.ContentEncoding = Encoding.GetEncoding(28592); OResponse.Charset = ""; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); OGrid.RenderControl(htw); OResponse.Output.Write(sw.ToString()); OResponse.Flush(); OResponse.End(); }
public override bool SendContent(string url, System.Web.HttpResponseBase response) { _cacheLock.EnterWriteLock(); try { if (fileList.ContainsKey(url)) { fileList[url] = DateTime.Now; return(base.SendContent(url, response)); } } finally { _cacheLock.ExitWriteLock(); } return(false); }
private void createPdf02(System.Web.HttpResponseBase Response) { if (FlushInBrowser) { _pdfRptData.PdfStreamOutput = new MemoryStream(); } //var stream = _pdfRptData.PdfStreamOutput; //initPdfWriter02(Response, stream); initPdfWriter02(Response, null); initSettings(); _pdfDocumentSettings.ApplyBeforePdfDocOpenSettings(); _pdfDocumentSettings.SetEncryption(); PdfDoc.Open(); _pdfConformance.SetColorProfile(); if (_pdfRptData.MainTableEvents != null) { _pdfRptData.MainTableEvents.DocumentOpened(new EventsArguments { PdfDoc = PdfDoc, PdfWriter = PdfWriter, ColumnCellsSummaryData = ColumnSummaryCellsData, PageSetup = _pdfRptData.DocumentPreferences, PdfFont = _pdfRptData.PdfFont, PdfColumnsAttributes = _pdfRptData.PdfColumnsAttributes }); } _pdfDocumentSettings.ApplySettings(); _pdfDocumentSettings.AddFileAttachments(); addMainTable(); //_pdfDocumentSettings.ApplySignature(stream); _pdfDocumentSettings.ApplySignature(Response.OutputStream); if (_pdfRptData.MainTableEvents != null) { //_pdfRptData.MainTableEvents.DocumentClosing(new EventsArguments { PdfDoc = PdfDoc, PdfWriter = PdfWriter, PdfStreamOutput = stream, ColumnCellsSummaryData = ColumnSummaryCellsData, PageSetup = _pdfRptData.DocumentPreferences, PdfFont = _pdfRptData.PdfFont, PdfColumnsAttributes = _pdfRptData.PdfColumnsAttributes }); _pdfRptData.MainTableEvents.DocumentClosing(new EventsArguments { PdfDoc = PdfDoc, PdfWriter = PdfWriter, PdfStreamOutput = Response.OutputStream, ColumnCellsSummaryData = ColumnSummaryCellsData, PageSetup = _pdfRptData.DocumentPreferences, PdfFont = _pdfRptData.PdfFont, PdfColumnsAttributes = _pdfRptData.PdfColumnsAttributes }); } flushFileInBrowser02(); }
protected override void WriteFile(System.Web.HttpResponseBase response) { var result = "<?xml version='1.0' encoding='utf-8'?>"; result += "<rss xmlns:a10='http://www.w3.org/2005/Atom' version='2.0'>"; result += "<channel>"; result += "<title>Upcoming Nerd Dinners</title>"; result += "<link>" + currentUrl + "</link>"; result += "<description>Upcoming Nerd Dinners</description>"; foreach (var d in Dinners) { var content = ""; content += d.Description; content += " with "; content += d.HostedBy; content += " on "; content += d.EventDate.ToString("MMM dd, yyyy"); content += " at "; content += d.EventDate.ToShortTimeString(); content += ". Where: "; content += d.Address; content += ", "; content += d.Country; result += "<item>"; result += "<guid isPermaLink='true'>http://nrddnr.com/" + d.DinnerID + "</guid>"; result += "<link>http://nrddnr.com/" + d.DinnerID + "</link>"; result += "<title>" + d.Title + "</title>"; result += "<description>" + content + "</description>"; result += "<pubDate>" + d.EventDate.ToUniversalTime() + "</pubDate>"; result += "<a10:updated>" + d.EventDate.ToUniversalTime() + "</a10:updated>"; result += "<a10:content type='text'>" + content + "</a10:content>"; result += "</item>"; } result += "</channel>"; result += "</rss>"; response.Write(result); }